@omnimedia/omnitool 1.1.0-11 → 1.1.0-12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/s/driver/driver.ts +1 -1
- package/x/demo/demo.bundle.min.js +1 -1
- package/x/demo/demo.bundle.min.js.map +2 -2
- package/x/driver/driver.js +1 -1
- package/x/driver/driver.js.map +1 -1
- package/x/index.html +2 -2
|
@@ -572,7 +572,7 @@ fn mainFragment(
|
|
|
572
572
|
`))},stderr:async i=>{await Deno.stderr.write(new TextEncoder().encode(i+`
|
|
573
573
|
`))}});var Vn=()=>({stdout:async i=>void process.stdout.write(i+`
|
|
574
574
|
`),stderr:async i=>void process.stderr.write(i+`
|
|
575
|
-
`)});var Wn=()=>({stdout:async i=>console.log(i),stderr:async i=>console.error(i)});var Hd=()=>$c()?Ln():qc()?Vn():Wn();var jd=()=>({stdout:async()=>{},stderr:async()=>{}});function $d(){return()=>({stdout:i=>i,stderr:i=>i})}var si=class i{static writers={auto:Hd,void:jd,deno:Ln,node:Vn,console:Wn};static colors={auto:Xc,colorful:()=>hs,colorless:()=>us};static themes={auto:Nd,basic:Un};static shapers={auto:Wd,none:$d,errors:Gn,timestamp:Nn};writer=i.writers.auto();colors=i.colors.auto();theme=i.themes.auto();shaper=i.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=ds(...e),this}};var fs=class extends si{static dummy(){return new this().setWriter(si.writers.void())}rpcRequest=async({request:e,...t})=>{let r=this.colors.none;this.log(...this.#e(t),r(`${e.method}()`))};rpcError=async({request:e,error:t,...r})=>{this.error(...this.#e(r),`${e.method}()`,t)};#e({meta:e,label:t,remote:r}){let s=this.colors.mix(this.colors.blue,this.colors.dim),n=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,t||void 0,r===void 0?void 0:r?s("<-"):n("->")].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 xt=class extends fs{rpcRequest=async()=>{}};var yt=Object.freeze({eq(i,e){if(i.length!==e.length)return!1;for(let t=0;t<=i.length;t++)if(i.at(t)!==e.at(t))return!1;return!0},random(i){return crypto.getRandomValues(new Uint8Array(i))}});var Tr=Object.freeze({fromBytes(i){return[...i].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(i){if(i.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(i.length/2);for(let t=0;t<i.length;t+=2)e[t/2]=parseInt(i.slice(t,t+2),16);return e},random(i=32){return this.fromBytes(yt.random(i))},string(i){return Tr.fromBytes(i)},bytes(i){return Tr.toBytes(i)}});var Yc=58,Hn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Kc=Object.freeze({fromBytes(i){let e=BigInt("0x"+Tr.fromBytes(i)),t="";for(;e>0;){let r=e%BigInt(Yc);e=e/BigInt(Yc),t=Hn[Number(r)]+t}for(let r of i)if(r===0)t=Hn[0]+t;else break;return t},toBytes(i){let e=BigInt(0);for(let o of i){let a=Hn.indexOf(o);if(a===-1)throw new Error(`Invalid character '${o}' in base58 string`);e=e*BigInt(Yc)+BigInt(a)}let t=e.toString(16);t.length%2!==0&&(t="0"+t);let r=Tr.toBytes(t),s=0;for(let o of i)if(o===Hn[0])s++;else break;let n=new Uint8Array(s+r.length);return n.set(r,s),n},random(i=32){return this.fromBytes(yt.random(i))},string(i){return Kc.fromBytes(i)},bytes(i){return Kc.toBytes(i)}});var qd=class{lexicon;static lexicons=Object.freeze({base2:{characters:"01"},hex:{characters:"0123456789abcdef"},base36:{characters:"0123456789abcdefghijklmnopqrstuvwxyz"},base58:{characters:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"},base62:{characters:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},base64url:{negativePrefix:"~",characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"},base64:{characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",padding:{character:"=",size:4}}});lookup;negativePrefix;constructor(e){this.lexicon=e,this.lookup=Object.fromEntries([...e.characters].map((t,r)=>[t,r])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let a=0,c=0,l=[];for(let u of e){if(u===this.lexicon.padding?.character)continue;let h=this.lookup[u];if(h===void 0)throw new Error(`Invalid character: ${u}`);for(a=a<<t|h,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let r=0n,s=BigInt(this.lexicon.characters.length),n=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);r=r*s+BigInt(c)}let o=[];for(;r>0n;)o.unshift(Number(r%256n)),r=r/256n;return new Uint8Array(o)}fromBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let o=0,a=0,c="";for(let l of e)for(o=o<<8|l,a+=8;a>=t;){a-=t;let u=o>>a&(1<<t)-1;c+=this.lexicon.characters[u]}if(a>0){let l=o<<t-a&(1<<t)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let r=0n;for(let o of e)r=(r<<8n)+BigInt(o);if(r===0n)return this.lexicon.characters[0];let s=BigInt(this.lexicon.characters.length),n="";for(;r>0n;)n=this.lexicon.characters[Number(r%s)]+n,r=r/s;return n}toInteger(e){if(!e)return 0;let t=0n,r=!1,s=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),r=!0);for(let n of e){let o=this.lookup[n];if(o===void 0)throw new Error(`Invalid character: ${n}`);t=t*s+BigInt(o)}return Number(r?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,r=BigInt(t?-e:e);if(r===0n)return this.lexicon.characters[0];let s=BigInt(this.lexicon.characters.length),n="";for(;r>0n;)n=this.lexicon.characters[Number(r%s)]+n,r=r/s;return t?`${this.negativePrefix}${n}`:n}random(e=32){return this.fromBytes(yt.random(e))}};var Zc=Object.freeze({fromBytes(i){return typeof btoa=="function"?btoa(String.fromCharCode(...i)):Buffer.from(i).toString("base64")},toBytes(i){return typeof atob=="function"?Uint8Array.from(atob(i),e=>e.charCodeAt(0)):Uint8Array.from(Buffer.from(i,"base64"))},random(i=32){return this.fromBytes(yt.random(i))},string(i){return Zc.fromBytes(i)},bytes(i){return Zc.toBytes(i)}});var Xd=Object.freeze({fromBytes(i){return new TextDecoder().decode(i)},toBytes(i){return new TextEncoder().encode(i)},string(i){return Xd.fromBytes(i)},bytes(i){return Xd.toBytes(i)}});var jn=Object.freeze({set:i=>i!=null,unset:i=>i==null,boolean:i=>typeof i=="boolean",number:i=>typeof i=="number",string:i=>typeof i=="string",bigint:i=>typeof i=="bigint",object:i=>typeof i=="object"&&i!==null,array:i=>Array.isArray(i),fn:i=>typeof i=="function",symbol:i=>typeof i=="symbol"});var ms=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function $n(i,e){return i<=0||i===1/0?e():new Promise((t,r)=>{let s=setTimeout(()=>r(new ms(i)),i);e().then(t).catch(r).finally(()=>clearTimeout(s))})}function kr(){let i,e,t=new Promise((s,n)=>{i=s,e=n});function r(s){return s.then(i).catch(e),t}return{promise:t,resolve:i,reject:e,entangle:r}}function Yd(i,e){let t=i;for(let r of e)if(t=t[r],jn.unset(t))break;return t}function h_(i){return{map:e=>Kd(i,e),filter:e=>Zd(i,e)}}h_.pipe=Object.freeze({map:i=>e=>Kd(e,i),filter:i=>e=>Zd(e,i)});var Kd=(i,e)=>Object.fromEntries(Object.entries(i).map(([t,r])=>[t,e(r,t)])),Zd=(i,e)=>Object.fromEntries(Object.entries(i).filter(([t,r])=>e(r,t)));function d_(){let i=new Set;function e(n){return i.add(n),()=>{i.delete(n)}}async function t(...n){await Promise.all([...i].map(o=>o(...n)))}async function r(){let{promise:n,resolve:o}=kr(),a=e((...c)=>{o(c),a()});return n}function s(){i.clear()}return e.pub=t,e.sub=e,e.on=e,e.next=r,e.clear=s,t.pub=t,t.sub=e,t.on=e,t.next=r,t.clear=s,[t,e]}function qn(i){let e=d_()[0];return i&&e.sub(i),e}var Dt=class{#e=[];add(...e){return this.#e.push(...e),this}disposable(e){return this.bag(e,()=>e.dispose())}bag(e,t){return this.add(()=>t(e)),e}dispose(){for(let e of this.#e.reverse())e();this.#e=[]}};var rr;(function(i){i.version="2.0";function e(t){return"id"in t?t.id:null}i.getId=e,i.errorCodes={serverError:-32e3,unexposedError:-32001}})(rr||(rr={}));var Xn=class extends Error{name=this.constructor.name},vr=class extends Error{name=this.constructor.name};async function Qd({tap:i,request:e,action:t}){let r=rr.getId(e);try{let s=await t();return r===null?null:{id:r,result:s,jsonrpc:rr.version}}catch(s){return i.rpcError({request:e,error:s}),r===null?null:{id:r,jsonrpc:rr.version,error:s instanceof Xn?{code:rr.errorCodes.serverError,message:s.message}:{code:rr.errorCodes.unexposedError,message:"unexposed error"}}}}function Yn(i){let e=i.tap??new xt;return async t=>{let r=t.method.split("."),s=Yd(i.fns,r),n=async()=>await s(...t.params);return e.rpcRequest({request:t}),await Qd({tap:e,request:t,action:n})}}var Pr=Symbol("tune"),f_=Symbol("query"),m_=Symbol("notify"),p_=Symbol("settings");function Jd(i){function e(t){let r={notify:void 0};return new Proxy(()=>{},{apply:(s,n,o)=>i(t,o,r),get:(s,n)=>{if(n!=="then")return n===Pr?o=>(...a)=>i(t,a,{...r,...o}):n===m_?(...o)=>i(t,o,{...r,notify:!0}):n===f_?(...o)=>i(t,o,{...r,notify:!1}):n===p_?r:(s[n]||(s[n]=e([...t,n])),s[n])},set:(s,n,o)=>(s[n]=o,!0)})}return e([])}function Cr(i){let{endpoint:e,tap:t=new xt}=i,r=1;return Jd(async(s,n,o)=>{let a=o.notify??i.notify??!1,c=o.transfer,l={jsonrpc:"2.0",method:s.join("."),params:n},u=a?l:{...l,id:r++};t.rpcRequest({request:u});let h=await e(u,{transfer:c});if(a&&!h)return null;if(!h)throw new vr("response was null, but shouldn't be, because the request was not a notification");if("error"in h)throw new vr(i.label?`${i.label}: ${h.error.message}`:h.error.message);return h.result})}function ps(i){return Cr({endpoint:Yn(i),tap:i.tap})}var Er=class{recv=qn();sendRequest=qn();sendResponse=qn();static makeEntangledPair({origin:e="example.e280.org"}={}){let t=new this,r=new this,s=[t.sendRequest.sub(o=>r.recv(o,{origin:e})),t.sendResponse.sub(o=>r.recv(o,{origin:e})),r.sendRequest.sub(o=>t.recv(o,{origin:e})),r.sendResponse.sub(o=>t.recv(o,{origin:e}))];return[t,r,()=>s.forEach(o=>o())]}};function Kn(i,e){return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}function ef(i,e){return async(t,{transfer:r}={})=>{if("id"in t){let s=kr();return e(t,r,s.promise),i.wait(t.id,t.method).then(n=>(s.resolve(n),n))}else{let s=Promise.resolve(null);return e(t,r,s),s}}}function tf(i){let e=[],t=[];for(let r of Array.isArray(i)?i:[i])"method"in r?e.push(r):t.push(r);return{requests:e,responses:t}}async function rf(i,e){let t=(await Promise.all(e.map(async r=>i(r)))).filter(r=>r!==null);return t.length===0?null:t.length===1?t[0]:t}var ni=class extends Er{#e=new Dt;constructor(e){super(),this.#e.add(this.sendRequest.sub((t,r)=>e.postMessage(t,r)),this.sendResponse.sub((t,r)=>e.postMessage(t,r)),Kn(e,t=>this.recv(t.data,t)))}dispose(){this.#e.dispose()}};var Zn=class{remote;transfer;constructor(e){this.remote=e}};var Qc=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Qn=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,t){let r=kr();return this.pending.set(e,{method:t,deferred:r}),await $n(this.timeout,()=>r.promise).catch(s=>{throw s instanceof ms&&(s.message=`request #${e} ${t}(), ${s.message}`),s})}deliverResponse(e){let t=this.pending.get(e.id);t&&("error"in e?t.deferred.reject(new vr(e.error.message)):t.deferred.resolve(e))}};var Ar=class{options;remote;remoteEndpoint;#e;#t=new Dt;constructor(e){this.options=e;let{conduit:t,tap:r}=e;this.#e=new Qn(e.timeout??Qc.timeout),this.remoteEndpoint=ef(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=Cr({endpoint:this.remoteEndpoint,tap:r&&jc(r,{remote:!0})}),this.#t.add(t.recv.sub(s=>this.recv(s)))}async recv(e){let t=new Zn(this.remote),{conduit:r,rpc:s,tap:n}=this.options,{requests:o,responses:a}=tf(e);for(let h of a)this.#e.deliverResponse(h);if(!s)return;let c=await s(t),l=Yn({fns:c,tap:n&&jc(n,{remote:!1})}),u=await rf(l,o);u&&await r.sendResponse(u,t.transfer)}dispose(){this.#t.dispose()}};var Rt={derive:{host:i=>({host:i.remote.host,get transfer(){return i.transfer},set transfer(e){i.transfer=e}}),work:i=>({work:i.remote,get transfer(){return i.transfer},set transfer(e){i.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var Ot=new xt;async function sf(i,e,t={}){let r=t.tap??Ot,s=new Ar({tap:r,timeout:t.timeout??1/0,conduit:new ni(i.getSelf()),rpc:async n=>e(Rt.derive.host(n))});return await s.remote.infra.ready(),s.remote.host}var st=Object.freeze({eq(i,e){if(i.length!==e.length)return!1;for(let t=0;t<=i.length;t++)if(i.at(t)!==e.at(t))return!1;return!0},random(i){return crypto.getRandomValues(new Uint8Array(i))}});var Le=Object.freeze({fromBytes(i){return[...i].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(i){if(i.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(i.length/2);for(let t=0;t<i.length;t+=2)e[t/2]=parseInt(i.slice(t,t+2),16);return e},random(i=32){return this.fromBytes(st.random(i))},string(i){return Le.fromBytes(i)},bytes(i){return Le.toBytes(i)}});var Jc=["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 el=["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 Ut={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(i,e){let t=st.random(i);return this.fromBytes(t,e)},fromBytes(i,e={}){let{groupSize:t=Ut.defaults.groupSize,wordSeparator:r=Ut.defaults.wordSeparator,groupSeparator:s=Ut.defaults.groupSeparator}=e,n=[],o=[];i.forEach((c,l)=>{let u=l%2===0?Jc:el;o.push(u[c]),o.length===2&&(n.push(o.join("")),o=[])}),o.length&&n.push(o.join(""));let a=[];for(let c=0;c<n.length;c+=t)a.push(n.slice(c,c+t).join(r));return a.join(s)},toBytes(i){let e=i.toLowerCase().replace(/[^a-z]/g,"");if(e.length/3%1!==0)throw new Error(`invalid triplet count, ${e.length} does not divide into triplets`);let r=[];for(let s=0;s<e.length;s+=3)r.push(e.slice(s,s+3));return new Uint8Array(r.map((s,n)=>{let a=(n%2===0?Jc:el).findIndex(c=>c===s);if(a===-1)throw new Error(`unknown triplet ${s}`);return a}))},toHex(i){return Le.fromBytes(Ut.toBytes(i))},fromHex(i,e){return Ut.fromBytes(Le.toBytes(i),e)}};var tl=58,Jn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",gs=Object.freeze({fromBytes(i){let e=BigInt("0x"+Le.fromBytes(i)),t="";for(;e>0;){let r=e%BigInt(tl);e=e/BigInt(tl),t=Jn[Number(r)]+t}for(let r of i)if(r===0)t=Jn[0]+t;else break;return t},toBytes(i){let e=BigInt(0);for(let o of i){let a=Jn.indexOf(o);if(a===-1)throw new Error(`Invalid character '${o}' in base58 string`);e=e*BigInt(tl)+BigInt(a)}let t=e.toString(16);t.length%2!==0&&(t="0"+t);let r=Le.toBytes(t),s=0;for(let o of i)if(o===Jn[0])s++;else break;let n=new Uint8Array(s+r.length);return n.set(r,s),n},random(i=32){return this.fromBytes(st.random(i))},string(i){return gs.fromBytes(i)},bytes(i){return gs.toBytes(i)}});var nt={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(i){i=i.trim();let e=i.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(s=>s.trim());if(e.length<2)return Ut.toBytes(e.join(""));let t=e.pop(),r=e.join("");return new Uint8Array([...Ut.toBytes(r),...gs.toBytes(t)])},parse(i,e){let t=nt.toBytes(i);return nt.build.fromBytes(t,e)},build:{fromBytes(i,e={}){let{delimiter:t,previewBytes:r,sigilBytes:s}={...nt.defaults,...e},n=u=>i.length>0?Ut.fromBytes(i.slice(0,u),{wordSeparator:t,groupSeparator:t}):"",o=n(s),a=n(r),c=i.length>r?gs.fromBytes(i.slice(r)):"",l=[a,c].filter(u=>u.length>0).join(t);return{bytes:i,thumbprint:l,preview:a,bulk:c,sigil:o}},fromHex(i,e){let t=Le.toBytes(i);return nt.build.fromBytes(t,e)}},toHex(i){let e=nt.toBytes(i);return Le.fromBytes(e)},fromBytes(i,e){return nt.build.fromBytes(i,e).thumbprint},fromHex(i,e){return nt.fromBytes(Le.toBytes(i),e)},sigil:{fromHex(i,e){return nt.build.fromHex(i,e).sigil},fromBytes(i,e){return nt.build.fromBytes(i,e).sigil}}};var nf=class{lexicon;static lexicons=Object.freeze({base2:{characters:"01"},hex:{characters:"0123456789abcdef"},base36:{characters:"0123456789abcdefghijklmnopqrstuvwxyz"},base58:{characters:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"},base62:{characters:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},base64url:{negativePrefix:"~",characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"},base64:{characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",padding:{character:"=",size:4}}});lookup;negativePrefix;constructor(e){this.lexicon=e,this.lookup=Object.fromEntries([...e.characters].map((t,r)=>[t,r])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let a=0,c=0,l=[];for(let u of e){if(u===this.lexicon.padding?.character)continue;let h=this.lookup[u];if(h===void 0)throw new Error(`Invalid character: ${u}`);for(a=a<<t|h,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let r=0n,s=BigInt(this.lexicon.characters.length),n=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);r=r*s+BigInt(c)}let o=[];for(;r>0n;)o.unshift(Number(r%256n)),r=r/256n;return new Uint8Array(o)}fromBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let o=0,a=0,c="";for(let l of e)for(o=o<<8|l,a+=8;a>=t;){a-=t;let u=o>>a&(1<<t)-1;c+=this.lexicon.characters[u]}if(a>0){let l=o<<t-a&(1<<t)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let r=0n;for(let o of e)r=(r<<8n)+BigInt(o);if(r===0n)return this.lexicon.characters[0];let s=BigInt(this.lexicon.characters.length),n="";for(;r>0n;)n=this.lexicon.characters[Number(r%s)]+n,r=r/s;return n}toInteger(e){if(!e)return 0;let t=0n,r=!1,s=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),r=!0);for(let n of e){let o=this.lookup[n];if(o===void 0)throw new Error(`Invalid character: ${n}`);t=t*s+BigInt(o)}return Number(r?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,r=BigInt(t?-e:e);if(r===0n)return this.lexicon.characters[0];let s=BigInt(this.lexicon.characters.length),n="";for(;r>0n;)n=this.lexicon.characters[Number(r%s)]+n,r=r/s;return t?`${this.negativePrefix}${n}`:n}random(e=32){return this.fromBytes(st.random(e))}};var rl=Object.freeze({fromBytes(i){return typeof btoa=="function"?btoa(String.fromCharCode(...i)):Buffer.from(i).toString("base64")},toBytes(i){return typeof atob=="function"?Uint8Array.from(atob(i),e=>e.charCodeAt(0)):Uint8Array.from(Buffer.from(i,"base64"))},random(i=32){return this.fromBytes(st.random(i))},string(i){return rl.fromBytes(i)},bytes(i){return rl.toBytes(i)}});var of=Object.freeze({fromBytes(i){return new TextDecoder().decode(i)},toBytes(i){return new TextEncoder().encode(i)},string(i){return of.fromBytes(i)},bytes(i){return of.toBytes(i)}});var il=Object.freeze({set:i=>i!=null,unset:i=>i==null,boolean:i=>typeof i=="boolean",number:i=>typeof i=="number",string:i=>typeof i=="string",bigint:i=>typeof i=="bigint",object:i=>typeof i=="object"&&i!==null,array:i=>Array.isArray(i),fn:i=>typeof i=="function",symbol:i=>typeof i=="symbol"});function xs(){let i,e,t=new Promise((s,n)=>{i=s,e=n});function r(s){return s.then(i).catch(e),t}return{promise:t,resolve:i,reject:e,entangle:r}}var eo=class i extends Map{static require(e,t){if(e.has(t))return e.get(t);throw new Error(`required key not found: "${t}"`)}static guarantee(e,t,r){if(e.has(t))return e.get(t);{let s=r();return e.set(t,s),s}}array(){return[...this]}require(e){return i.require(this,e)}guarantee(e,t){return i.guarantee(this,e,t)}};function b_(i){return{map:e=>af(i,e),filter:e=>cf(i,e)}}b_.pipe=Object.freeze({map:i=>e=>af(e,i),filter:i=>e=>cf(e,i)});var af=(i,e)=>Object.fromEntries(Object.entries(i).map(([t,r])=>[t,e(r,t)])),cf=(i,e)=>Object.fromEntries(Object.entries(i).filter(([t,r])=>e(r,t)));var oi=class{worker;messenger;constructor(e,t){this.worker=e,this.messenger=t}static async make(e,t){let r=t.tap??Ot,s=t.label??"comrade",n=e.loadWorker(t.workerUrl,s),o=xs(),a={async ready(){o.resolve()}},c=new Ar({tap:r,timeout:t.timeout??1/0,conduit:new ni(n),rpc:async l=>({infra:a,host:t.setupHost(Rt.derive.work(l))})});return await o.promise,new this(n,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var to=class{threads;static async make(e,t){let r=t.workerCount??e.guessOptimalThreadCount(),s=await Promise.all([...Array(r)].map(async(n,o)=>oi.make(e,{...t,label:t.label??`${t.label??"comrade"}_${o+1}`})));return new this(s,{tap:t.tap})}work;#e=new Set;#t=[];constructor(e,t={}){this.threads=e;let r=t.tap??Ot,s=async(n,o)=>this.#r({request:n,prom:xs(),transfer:o?.transfer});this.work=Cr({tap:r,endpoint:s}),e.forEach(n=>this.#e.add(n))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#r(e){return this.#t.push(e),this.#i(),e.prom.promise}#i(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let t=this.#t.shift();this.#e.delete(e);let r=e.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(r).finally(()=>{this.#e.add(e),this.#i()})}}};var lf=i=>({thread:e=>oi.make(i,e),cluster:e=>to.make(i,e),worker:(e,t={})=>sf(i,e,t),work:e=>e,host:e=>e,mocks(e){let{setupWork:t,setupHost:r,tap:s=Ot}=e,n=Rt.mock.host(),o=Rt.mock.work();return o.work=ps({tap:s,fns:t(n)}),n.host=ps({tap:s,fns:r(o)}),{workShell:o,hostShell:n,work:o.work,host:n.host}},mockWork(e,t=Ot){let r=Rt.mock.host(),s=Rt.mock.work();return s.work=ps({tap:t,fns:e(r)}),{workShell:s,hostShell:r,work:s.work,mockHost:n=>(r.host=ps({tap:t,fns:n(s)}),{workShell:s,hostShell:r,work:s.work,host:r.host})}}});var uf=()=>({getSelf(){return self},guessOptimalThreadCount(){let i=navigator.hardwareConcurrency??1;return Math.max(1,i-1)},loadWorker(i,e){return new window.Worker(i,{name:e,type:"module"})},async loadWasm(i){return WebAssembly.instantiateStreaming(fetch(i))}});var w_=uf(),ro=lf(w_);function k(i){if(!i)throw new Error("Assertion failed.")}var so=i=>{let e=(i%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${i}.`)},ve=i=>i&&i[i.length-1];var fe=class i{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(this.pos&7),s=(t&1<<r)>>r;return this.pos++,s}readBits(e){if(e===1)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let r=this.pos+e;for(let s=this.pos;s<r;s++){let n=Math.floor(s/8),o=this.bytes[n],a=7-(s&7);o&=~(1<<a),o|=(t&1<<r-s-1)>>r-s-1<<a,this.bytes[n]=o}this.pos=r}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new i(this.bytes);return e.pos=this.pos,e}},R=i=>{let e=0;for(;i.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+i.readBits(e)},ai=i=>{let e=R(i);return(e&1)===0?-(e>>1):e+1>>1};var ir=i=>i instanceof Uint8Array?i:i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),oe=i=>i instanceof DataView?i:i instanceof ArrayBuffer?new DataView(i):new DataView(i.buffer,i.byteOffset,i.byteLength),Be=new TextDecoder,__=new TextEncoder;var nl=i=>Object.fromEntries(Object.entries(i).map(([e,t])=>[t,e])),ol={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},no=nl(ol),al={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},oo=nl(al),cl={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ao=nl(cl);var ll=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),Je=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(s=>{e=s}),r=this.currentPromise;return this.currentPromise=t,await r,e}},ul=i=>[...i].map(e=>e.toString(16).padStart(2,"0")).join(""),hl=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),ae=(i,e,t)=>{let r=0,s=i.length-1,n=-1;for(;r<=s;){let o=r+s>>1,a=t(i[o]);a===e?(n=o,s=o-1):a<e?r=o+1:s=o-1}return n},Q=(i,e,t)=>{let r=0,s=i.length-1,n=-1;for(;r<=s;){let o=r+(s-r+1)/2|0;t(i[o])<=e?(n=o,r=o+1):s=o-1}return n},ot=(i,e,t)=>{let r=Q(i,t(e),t);i.splice(r+1,0,e)},Fe=()=>{let i,e;return{promise:new Promise((r,s)=>{i=r,e=s}),resolve:i,reject:e}};var dl=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return i[t]},co=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return t;return-1},hf=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},df=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},ys=i=>{throw new Error(`Unexpected value: ${i}`)};var fl=(i,e)=>({async next(){let t=await i.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return i.return()},throw(t){return i.throw(t)},[Symbol.asyncIterator](){return this}}),lo=(i,e,t)=>Math.max(e,Math.min(t,i)),Pe="und",Ir=(i,e)=>{let t=10**e;return Math.round(i*t)/t},ff=(i,e)=>Math.round(i/e)*e,mf=i=>{let e=0;for(;i;)e++,i>>=1;return e},S_=/^[a-z]{3}$/,uo=i=>S_.test(i),sr=1e6*(1+Number.EPSILON),ho=(i,e)=>{let t={...i};for(let r in e)typeof i[r]=="object"&&i[r]!==null&&typeof e[r]=="object"&&e[r]!==null?t[r]=ho(i[r],e[r]):t[r]=e[r];return t},ml=async(i,e,t)=>{let r=0;for(;;)try{return await fetch(i,e)}catch(s){r++;let n=t(r);if(n===null)throw s;if(console.error("Retrying failed fetch. Error:",s),!Number.isFinite(n)||n<0)throw new TypeError("Retry delay must be a non-negative finite number.");n>0&&await new Promise(o=>setTimeout(o,1e3*n))}};var io=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},sl=null,fo=()=>{if(sl!==null)return sl;let i=!!(typeof navigator<"u"&&navigator.vendor?.match(/apple/i)&&!navigator.userAgent?.match(/crios/i)&&!navigator.userAgent?.match(/fxios/i)&&!navigator.userAgent?.match(/Opera|OPT\//));return sl=i,i},Mr=(i,e)=>i!==-1?i:e,mo=(i,e,t,r)=>i<=r&&t<=e;var pf=i=>{let e=atob(i),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t};var nr=class{constructor(e,t){this.data=e,this.mimeType=t}};var ws=["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"],T_=["aac","opus","mp3","vorbis","flac"],NI=[...T_,...ws];var Br=[{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 gf=".01.01.01.01.00",xf=".0.110.01.01.01.0";var po=i=>{let{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:o,av1CodecInfo:a}=i;if(e==="avc"){if(s){let c=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc1.${ul(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc1.${ul(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,h,d,f;if(n)c=n.generalProfileSpace,l=n.generalProfileIdc,u=hl(n.generalProfileCompatibilityFlags),h=n.generalTierFlag,d=n.generalLevelIdc,f=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let p=oe(t),g=p.getUint8(1);c=g>>6&3,l=g&31,u=hl(p.getUint32(2)),h=g>>5&1,d=p.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(p.getUint8(6+y))}let m="hev1.";for(m+=["","A","B","C"][c]+l,m+=".",m+=u.toString(16).toUpperCase(),m+=".",m+=h===0?"L":"H",m+=d;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(m+=".",m+=f.map(p=>p.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!o){let y=i.width*i.height,x=ve(Br).level;for(let w of Br)if(y<=w.maxPictureSize){x=w.level;break}return`vp09.00.${x.toString().padStart(2,"0")}.08`}let c=o.profile.toString().padStart(2,"0"),l=o.level.toString().padStart(2,"0"),u=o.bitDepth.toString().padStart(2,"0"),h=o.chromaSubsampling.toString().padStart(2,"0"),d=o.colourPrimaries.toString().padStart(2,"0"),f=o.transferCharacteristics.toString().padStart(2,"0"),m=o.matrixCoefficients.toString().padStart(2,"0"),p=o.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${l}.${u}.${h}`;return g+=`.${d}.${f}.${m}.${p}`,g.endsWith(gf)&&(g=g.slice(0,-gf.length)),g}else if(e==="av1"){if(!a){let w=i.width*i.height,_=ve(Br).level;for(let S of Br)if(w<=S.maxPictureSize){_=S.level;break}return`av01.0.${_.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),u=a.tier?"H":"M",h=a.bitDepth.toString().padStart(2,"0"),d=a.monochrome?"1":"0",f=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),m=r?.primaries?ol[r.primaries]:1,p=r?.transfer?al[r.transfer]:1,g=r?.matrix?cl[r.matrix]:1,y=r?.fullRange?1:0,x=`av01.${c}.${l}${u}.${h}`;return x+=`.${d}.${f.toString().padStart(3,"0")}`,x+=`.${m.toString().padStart(2,"0")}`,x+=`.${p.toString().padStart(2,"0")}`,x+=`.${g.toString().padStart(2,"0")}`,x+=`.${y}`,x.endsWith(xf)&&(x=x.slice(0,-xf.length)),x}}throw new TypeError(`Unhandled codec '${e}'.`)};var go=i=>{let{codec:e,codecDescription:t,aacCodecInfo:r}=i;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");return r.isMpeg2?"mp4a.67":`mp4a.40.${gl(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&&ws.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},bs=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],pl=[-1,1,2,3,4,5,6,8],gl=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new fe(i),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let r=e.readBits(4),s=null;r===15?s=e.readBits(24):r<bs.length&&(s=bs[r]);let n=e.readBits(4),o=null;return n>=1&&n<=7&&(o=pl[n]),{objectType:t,frequencyIndex:r,sampleRate:s,channelConfiguration:n,numberOfChannels:o}},yf=48e3,k_=/^pcm-([usf])(\d+)+(be)?$/,bf=i=>{if(k(ws.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=k_.exec(i);k(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let r=Number(e[2])/8,s=e[3]!=="be",n=i==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:s,silentValue:n}};var ci;(function(i){i[i.IDR=5]="IDR",i[i.SPS=7]="SPS",i[i.PPS=8]="PPS",i[i.SPS_EXT=13]="SPS_EXT"})(ci||(ci={}));var De;(function(i){i[i.RASL_N=8]="RASL_N",i[i.RASL_R=9]="RASL_R",i[i.BLA_W_LP=16]="BLA_W_LP",i[i.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",i[i.VPS_NUT=32]="VPS_NUT",i[i.SPS_NUT=33]="SPS_NUT",i[i.PPS_NUT=34]="PPS_NUT",i[i.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",i[i.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(De||(De={}));var yo=i=>{let e=[],t=0;for(;t<i.length;){let r=-1,s=0;for(let n=t;n<i.length-3;n++){if(i[n]===0&&i[n+1]===0&&i[n+2]===1){r=n,s=3;break}if(n<i.length-4&&i[n]===0&&i[n+1]===0&&i[n+2]===0&&i[n+3]===1){r=n,s=4;break}}if(r===-1)break;if(t>0&&r>t){let n=i.subarray(t,r);n.length>0&&e.push(n)}t=r+s}if(t<i.length){let r=i.subarray(t);r.length>0&&e.push(r)}return e},_f=(i,e)=>{let t=[],r=0,s=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;r+e<=i.length;){let n;e===1?n=s.getUint8(r):e===2?n=s.getUint16(r,!1):e===3?n=(s.getUint16(r,!1)<<8)+s.getUint8(r+2):e===4?n=s.getUint32(r,!1):(ys(e),k(!1)),r+=e;let o=i.subarray(r,r+n);t.push(o),r+=n}return t},xl=i=>{let e=[],t=i.length;for(let r=0;r<t;r++)r+2<t&&i[r]===0&&i[r+1]===0&&i[r+2]===3?(e.push(0,0),r+=2):e.push(i[r]);return new Uint8Array(e)};var v_=(i,e)=>{if(e.description){let s=(ir(e.description)[4]&3)+1;return _f(i,s)}else return yo(i)},xo=i=>i[0]&31,Sf=i=>{try{let e=yo(i),t=e.filter(d=>xo(d)===ci.SPS),r=e.filter(d=>xo(d)===ci.PPS),s=e.filter(d=>xo(d)===ci.SPS_EXT);if(t.length===0||r.length===0)return null;let n=t[0],o=new fe(xl(n));if(o.skipBits(1),o.skipBits(2),o.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;let c=o.readAlignedByte(),l=o.readAlignedByte(),u=o.readAlignedByte(),h={configurationVersion:1,avcProfileIndication:c,profileCompatibility:l,avcLevelIndication:u,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(c===100||c===110||c===122||c===144){R(o);let d=R(o);d===3&&o.skipBits(1);let f=R(o),m=R(o);h.chromaFormat=d,h.bitDepthLumaMinus8=f,h.bitDepthChromaMinus8=m,h.sequenceParameterSetExt=s}return h}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}};var yl=(i,e)=>{if(e.description){let s=(ir(e.description)[21]&3)+1;return _f(i,s)}else return yo(i)},zt=i=>i[0]>>1&63,Tf=i=>{try{let e=yo(i),t=e.filter(C=>zt(C)===De.VPS_NUT),r=e.filter(C=>zt(C)===De.SPS_NUT),s=e.filter(C=>zt(C)===De.PPS_NUT),n=e.filter(C=>zt(C)===De.PREFIX_SEI_NUT||zt(C)===De.SUFFIX_SEI_NUT);if(r.length===0||s.length===0)return null;let o=r[0],a=new fe(xl(o));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:u,general_tier_flag:h,general_profile_idc:d,general_profile_compatibility_flags:f,general_constraint_indicator_flags:m,general_level_idc:p}=P_(a,c);R(a);let g=R(a);g===3&&a.skipBits(1),R(a),R(a),a.readBits(1)&&(R(a),R(a),R(a),R(a));let y=R(a),x=R(a);R(a);let _=a.readBits(1)?0:c;for(let C=_;C<=c;C++)R(a),R(a),R(a);R(a),R(a),R(a),R(a),R(a),R(a),a.readBits(1)&&a.readBits(1)&&C_(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),R(a),R(a),a.skipBits(1));let S=R(a);if(E_(a,S),a.readBits(1)){let C=R(a);for(let E=0;E<C;E++)R(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let T=0;a.readBits(1)&&(T=I_(a,c));let v=0;if(s.length>0){let C=s[0],E=new fe(xl(C));E.skipBits(16),R(E),R(E),E.skipBits(1),E.skipBits(1),E.skipBits(3),E.skipBits(1),E.skipBits(1),R(E),R(E),ai(E),E.skipBits(1),E.skipBits(1),E.readBits(1)&&R(E),ai(E),ai(E),E.skipBits(1),E.skipBits(1),E.skipBits(1),E.skipBits(1);let D=E.readBits(1),j=E.readBits(1);!D&&!j?v=0:D&&!j?v=2:!D&&j?v=3:v=0}let M=[...t.length?[{arrayCompleteness:1,nalUnitType:De.VPS_NUT,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:De.SPS_NUT,nalUnits:r}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:De.PPS_NUT,nalUnits:s}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:zt(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:h,generalProfileIdc:d,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:m,generalLevelIdc:p,minSpatialSegmentationIdc:T,parallelismType:v,chromaFormatIdc:g,bitDepthLumaMinus8:y,bitDepthChromaMinus8:x,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:M}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},P_=(i,e)=>{let t=i.readBits(2),r=i.readBits(1),s=i.readBits(5),n=0;for(let u=0;u<32;u++)n=n<<1|i.readBits(1);let o=new Uint8Array(6);for(let u=0;u<6;u++)o[u]=i.readBits(8);let a=i.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(i.readBits(1)),l.push(i.readBits(1));if(e>0)for(let u=e;u<8;u++)i.skipBits(2);for(let u=0;u<e;u++)c[u]&&i.skipBits(88),l[u]&&i.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:s,general_profile_compatibility_flags:n,general_constraint_indicator_flags:o,general_level_idc:a}},C_=i=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!i.readBits(1))R(i);else{let s=Math.min(64,1<<4+(e<<1));e>1&&ai(i);for(let n=0;n<s;n++)ai(i)}},E_=(i,e)=>{let t=[];for(let r=0;r<e;r++)t[r]=A_(i,r,e,t)},A_=(i,e,t,r)=>{let s=0,n=0,o=0;if(e!==0&&(n=i.readBits(1)),n){if(e===t){let c=R(i);o=e-(c+1)}else o=e-1;i.readBits(1),R(i);let a=r[o]??0;for(let c=0;c<=a;c++)i.readBits(1)||i.readBits(1);s=r[o]}else{let a=R(i),c=R(i);for(let l=0;l<a;l++)R(i),i.readBits(1);for(let l=0;l<c;l++)R(i),i.readBits(1);s=a+c}return s},I_=(i,e)=>{if(i.readBits(1)&&i.readBits(8)===255&&(i.readBits(16),i.readBits(16)),i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),i.readBits(1),i.readBits(1)&&(i.readBits(8),i.readBits(8),i.readBits(8))),i.readBits(1)&&(R(i),R(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(R(i),R(i),R(i),R(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&R(i),i.readBits(1)&&M_(i,!0,e)),i.readBits(1)){i.readBits(1),i.readBits(1),i.readBits(1);let t=R(i);return R(i),R(i),R(i),R(i),t}return 0},M_=(i,e,t)=>{let r=!1,s=!1,n=!1;e&&(r=i.readBits(1)===1,s=i.readBits(1)===1,(r||s)&&(n=i.readBits(1)===1,n&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5)));for(let o=0;o<=t;o++){let a=i.readBits(1)===1,c=!0;a||(c=i.readBits(1)===1);let l=!1;c?R(i):l=i.readBits(1)===1;let u=1;l||(u=R(i)+1),r&&wf(i,u,n),s&&wf(i,u,n)}},wf=(i,e,t)=>{for(let r=0;r<e;r++)R(i),R(i),t&&(R(i),R(i)),i.readBits(1)};var bo=i=>{let e=new fe(i);if(e.readBits(2)!==2)return null;let r=e.readBits(1),n=(e.readBits(1)<<1)+r;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;n>=2&&(l=e.readBits(1)?12:10);let u=e.readBits(3),h=0,d=0;if(u!==7)if(d=e.readBits(1),n===1||n===3){let v=e.readBits(1),M=e.readBits(1);h=!v&&!M?3:v&&!M?2:1,e.skipBits(1)}else h=1;else h=3,d=1;let f=e.readBits(16),m=e.readBits(16),p=f+1,g=m+1,y=p*g,x=ve(Br).level;for(let T of Br)if(y<=T.maxPictureSize){x=T.level;break}return{profile:n,level:x,bitDepth:l,chromaSubsampling:h,videoFullRangeFlag:d,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},kf=function*(i){let e=new fe(i),t=()=>{let r=0;for(let s=0;s<8;s++){let n=e.readAlignedByte();if(r|=(n&127)<<s*7,!(n&128))break;if(s===7&&n&128)return null}return r>=2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);let r=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let o;if(n){let a=t();if(a===null)return;o=a}else o=Math.floor(e.getBitsLeft()/8);k(e.pos%8===0),yield{type:r,data:i.subarray(e.pos/8,e.pos/8+o)},e.skipBits(o*8)}},wo=i=>{for(let{type:e,data:t}of kf(i)){if(e!==1)continue;let r=new fe(t),s=r.readBits(3),n=r.readBits(1),o=r.readBits(1),a=0,c=0,l=0;if(o)a=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;let y=r.readBits(1);y&&(l=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));let x=r.readBits(5);for(let w=0;w<=x;w++){r.skipBits(12);let _=r.readBits(5);if(w===0&&(a=_),_>7){let T=r.readBits(1);w===0&&(c=T)}if(y&&r.readBits(1)){let v=l+1;r.skipBits(v),r.skipBits(v),r.skipBits(1)}r.readBits(1)&&r.skipBits(4)}}let u=r.readBits(1),h=8;s===2&&u?h=r.readBits(1)?12:10:s<=2&&(h=u?10:8);let d=0;s!==1&&(d=r.readBits(1));let f=1,m=1,p=0;return d||(s===0?(f=1,m=1):s===1?(f=0,m=0):h===12&&(f=r.readBits(1),f&&(m=r.readBits(1))),f&&m&&(p=r.readBits(2))),{profile:s,level:a,tier:c,bitDepth:h,monochrome:d,chromaSubsamplingX:f,chromaSubsamplingY:m,chromaSamplePosition:p}}return null},vf=i=>{let e=oe(i),t=e.getUint8(9),r=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),o=e.getUint8(18),a=null;return o&&(a=i.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:s,outputGain:n,channelMappingFamily:o,channelMappingTable:a}},B_=[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],Pf=i=>{let e=i[0]>>3;return{durationInSamples:B_[e]}},Cf=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=i.length,r=new Uint8Array(t);for(let h=0;h<t;h++)r[h]=i[t-1-h];let s=new fe(r),n=0;for(;s.getBitsLeft()>97;)if(s.readBits(1)===1){n=s.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let o=0,a=!1,c=0;for(;s.getBitsLeft()>=97;){let h=s.pos,d=s.readBits(8),f=s.readBits(16),m=s.readBits(16);if(d>63||f!==0||m!==0){s.pos=h;break}if(s.skipBits(1),o++,o>64)break;s.clone().readBits(6)+1===o&&(a=!0,c=o)}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;s.pos=0,s.skipBits(n);let u=Array(l).fill(0);for(let h=l-1;h>=0;h--)s.skipBits(40),u[h]=s.readBits(1);return{modeBlockflags:u}},Ef=async(i,e)=>{switch(k(i.codec),i.codec){case"avc":{let t=await i.getDecoderConfig();return k(t),v_(e.data,t).some(n=>xo(n)===ci.IDR)?"key":"delta"}case"hevc":{let t=await i.getDecoderConfig();return k(t),yl(e.data,t).some(n=>{let o=zt(n);return De.BLA_W_LP<=o&&o<=De.RSV_IRAP_VCL23})?"key":"delta"}case"vp8":return(e.data[0]&1)===0?"key":"delta";case"vp9":{let t=new fe(e.data);if(t.readBits(2)!==2)return null;let r=t.readBits(1);return(t.readBits(1)<<1)+r===3&&t.skipBits(1),t.readBits(1)?null:t.readBits(1)===0?"key":"delta"}case"av1":{let t=!1;for(let{type:r,data:s}of kf(e.data))if(r===1){let n=new fe(s);n.skipBits(4),t=!!n.readBits(1)}else if(r===3||r===6||r===7){if(t)return"key";let n=new fe(s);return n.readBits(1)?null:n.readBits(2)===0?"key":"delta"}return null}default:ys(i.codec),k(!1)}};var Af=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};var _o=class{constructor(e){this.source=e}requestSlice(e,t){if(this.fileSize!==null&&e+t>this.fileSize)return null;let r=e+t,s=this.source._read(e,r);return s instanceof Promise?s.then(n=>n?new li(n.bytes,n.view,n.offset,e,r):null):s?new li(s.bytes,s.view,s.offset,e,r):null}requestSliceRange(e,t,r){if(this.fileSize!==null)return this.requestSlice(e,lo(this.fileSize-e,t,r));{let s=this.requestSlice(e,r),n=o=>{if(o)return o;let a=l=>(k(l!==null),this.requestSlice(e,lo(l-e,t,r))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return s instanceof Promise?s.then(n):n(s)}}},li=class i{constructor(e,t,r,s,n){this.bytes=e,this.view=t,this.offset=r,this.start=s,this.end=n,this.bufferPos=s-r}static tempFromBytes(e){return new i(e,oe(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}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 i(this.bytes,this.view,this.offset,e,e+t)}},W=(i,e)=>{let t=i.bytes.subarray(i.bufferPos,i.bufferPos+e);return i.bufferPos+=e,t},z=i=>i.view.getUint8(i.bufferPos++),ui=(i,e)=>{let t=i.view.getUint16(i.bufferPos,e);return i.bufferPos+=2,t},Ce=i=>{let e=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,e},hi=i=>{let e=Ce(i),t=z(i);return e*256+t},_s=i=>{let e=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,e},Gt=(i,e)=>{let t=i.view.getUint32(i.bufferPos,e);return i.bufferPos+=4,t},B=i=>{let e=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,e},Fr=i=>{let e=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,e},Nt=i=>{let e=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,e},F_=i=>{let e=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,e},bl=(i,e)=>{let t,r;return e?(t=Gt(i,!0),r=Gt(i,!0)):(r=Gt(i,!1),t=Gt(i,!1)),r*4294967296+t},Ye=i=>{let e=B(i),t=B(i);return e*4294967296+t},If=i=>{let e=Nt(i),t=B(i);return e*4294967296+t},Mf=i=>{let e=Fr(i);return F_(i)*4294967296+e},Bf=i=>{let e=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,e},So=i=>{let e=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,e},de=(i,e)=>{if(i.bufferPos+e>i.bytes.length)throw new RangeError("Reading past end of slice.");let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(i.bytes[i.bufferPos++]);return t};var Lt=8,Dr=16,bt=i=>{let e=B(i),t=de(i,4),r=8;e===1&&(e=Ye(i),r=16);let n=e-r;return n<0?null:{name:t,totalSize:e,headerSize:r,contentSize:n}},or=i=>Nt(i)/65536,To=i=>Nt(i)/1073741824,ko=i=>{let e=0;for(let t=0;t<4;t++){e<<=7;let r=z(i);if(e|=r&127,(r&128)===0)break}return e},at=i=>{let e=Ce(i);return i.skip(2),Be.decode(W(i,e))},Ff=i=>{let e=bt(i);if(!e||e.name!=="data")return null;let t=B(i);i.skip(4);let r=W(i,e.contentSize-8);switch(t){case 1:return Be.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new nr(r,"image/jpeg");case 14:return new nr(r,"image/png");case 27:return new nr(r,"image/bmp");default:return r}};var I;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Duration=17545]="Duration",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.MuxingApp=19840]="MuxingApp",i[i.WritingApp=22337]="WritingApp",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.TrackNumber=215]="TrackNumber",i[i.TrackUID=29637]="TrackUID",i[i.TrackType=131]="TrackType",i[i.FlagEnabled=185]="FlagEnabled",i[i.FlagDefault=136]="FlagDefault",i[i.FlagForced=21930]="FlagForced",i[i.FlagLacing=156]="FlagLacing",i[i.Name=21358]="Name",i[i.Language=2274716]="Language",i[i.LanguageBCP47=2274717]="LanguageBCP47",i[i.CodecID=134]="CodecID",i[i.CodecPrivate=25506]="CodecPrivate",i[i.CodecDelay=22186]="CodecDelay",i[i.SeekPreRoll=22203]="SeekPreRoll",i[i.DefaultDuration=2352003]="DefaultDuration",i[i.Video=224]="Video",i[i.PixelWidth=176]="PixelWidth",i[i.PixelHeight=186]="PixelHeight",i[i.Audio=225]="Audio",i[i.SamplingFrequency=181]="SamplingFrequency",i[i.Channels=159]="Channels",i[i.BitDepth=25188]="BitDepth",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.Block=161]="Block",i[i.BlockAdditions=30113]="BlockAdditions",i[i.BlockMore=166]="BlockMore",i[i.BlockAdditional=165]="BlockAdditional",i[i.BlockAddID=238]="BlockAddID",i[i.BlockDuration=155]="BlockDuration",i[i.ReferenceBlock=251]="ReferenceBlock",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.Colour=21936]="Colour",i[i.MatrixCoefficients=21937]="MatrixCoefficients",i[i.TransferCharacteristics=21946]="TransferCharacteristics",i[i.Primaries=21947]="Primaries",i[i.Range=21945]="Range",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPoseRoll=30325]="ProjectionPoseRoll",i[i.Attachments=423732329]="Attachments",i[i.AttachedFile=24999]="AttachedFile",i[i.FileDescription=18046]="FileDescription",i[i.FileName=18030]="FileName",i[i.FileMediaType=18016]="FileMediaType",i[i.FileData=18012]="FileData",i[i.FileUID=18094]="FileUID",i[i.Chapters=272869232]="Chapters",i[i.Tags=307544935]="Tags",i[i.Tag=29555]="Tag",i[i.Targets=25536]="Targets",i[i.TargetTypeValue=26826]="TargetTypeValue",i[i.TargetType=25546]="TargetType",i[i.TagTrackUID=25541]="TagTrackUID",i[i.TagEditionUID=25545]="TagEditionUID",i[i.TagChapterUID=25540]="TagChapterUID",i[i.TagAttachmentUID=25542]="TagAttachmentUID",i[i.SimpleTag=26568]="SimpleTag",i[i.TagName=17827]="TagName",i[i.TagLanguage=17530]="TagLanguage",i[i.TagString=17543]="TagString",i[i.TagBinary=17541]="TagBinary"})(I||(I={}));var D_=[I.EBML,I.Segment],di=[I.SeekHead,I.Info,I.Cluster,I.Tracks,I.Cues,I.Attachments,I.Chapters,I.Tags],vo=[...D_,...di];var wl=8,Ve=2,ct=2*wl,_l=i=>{let e=z(i);if(i.skip(-1),e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;return t},fi=i=>{let e=z(i);if(e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;let s=e&r-1;for(let n=1;n<t;n++)s*=256,s+=z(i);return s},J=(i,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let r=0;r<e;r++)t*=256,t+=z(i);return t},Df=(i,e)=>{let t=J(i,e);return t&1<<e*8-1&&(t-=2**(e*8)),t},Po=i=>{let e=_l(i);return e===null?null:J(i,e)},Sl=i=>{let e=z(i);return e===255?e=null:(i.skip(-1),e=fi(i),e===72057594037927940&&(e=null)),e},lt=i=>{let e=Po(i);if(e===null)return null;let t=Sl(i);return{id:e,size:t}},ar=(i,e)=>{let t=W(i,e),r=0;for(;r<e&&t[r]!==0;)r+=1;return String.fromCharCode(...t.subarray(0,r))},mi=(i,e)=>{let t=W(i,e),r=0;for(;r<e&&t[r]!==0;)r+=1;return Be.decode(t.subarray(0,r))},Co=(i,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Bf(i):So(i)},Eo=async(i,e,t,r)=>{let s=new Set(t),n=e;for(;r===null||n<r;){let o=i.requestSliceRange(n,Ve,ct);if(o instanceof Promise&&(o=await o),!o)break;let a=lt(o);if(!a)break;if(s.has(a.id))return{pos:n,found:!0};Vt(a.size),n=o.filePos+a.size}return{pos:r!==null&&r>n?r:n,found:!1}},Tl=async(i,e,t,r)=>{let n=new Set(t),o=e;for(;o<r;){let a=i.requestSliceRange(o,0,Math.min(65536,r-o));if(a instanceof Promise&&(a=await a),!a||a.length<wl)break;for(let c=0;c<a.length-wl;c++){a.filePos=o;let l=Po(a);if(l!==null&&n.has(l))return o;o++}}return null},ut={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 Vt(i){if(i===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Rf=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};var R_={1:[-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],2:[-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],3:[-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1]},O_={1:[-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],2:[-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1],3:[-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1]},U_={0:[11025,12e3,8e3,-1],2:[22050,24e3,16e3,-1],3:[44100,48e3,32e3,-1]},Of=1483304551,Uf=1231971951,z_=(i,e,t,r)=>Math.floor(i===3?(12*e/t+r)*4:144*e/t+r),zf=(i,e)=>i===3?e===3?21:36:e===3?13:21,Gf=(i,e)=>{let t=i>>>24,r=i>>>16&255,s=i>>>8&255,n=i&255;if(t!==255&&r!==255&&s!==255&&n!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let o=r>>3&3,a=r>>1&3,c=s>>4&15,l=s>>2&3,u=s>>1&1,h=n>>6&3,d=n>>4&3,f=n>>3&1,m=n>>2&1,p=n&3,g=o===3?R_[a]?.[c]:O_[a]?.[c];if(!g||g===-1)return{header:null,bytesAdvanced:1};let y=g*1e3,x=U_[o]?.[l];if(!x||x===-1)return{header:null,bytesAdvanced:1};let w=z_(a,y,x,u);if(e!==null&&e<w)return{header:null,bytesAdvanced:1};let _;return o===3?_=a===3?384:1152:a===3?_=384:a===2?_=1152:_=576,{header:{totalSize:w,mpegVersionId:o,layer:a,bitrate:y,frequencyIndex:l,sampleRate:x,channel:h,modeExtension:d,copyright:f,original:m,emphasis:p,audioSamplesInFrame:_},bytesAdvanced:1}};var Ao=i=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=i&e,e>>=8;return t};var gi;(function(i){i[i.Unsynchronisation=128]="Unsynchronisation",i[i.ExtendedHeader=64]="ExtendedHeader",i[i.ExperimentalIndicator=32]="ExperimentalIndicator",i[i.Footer=16]="Footer"})(gi||(gi={}));var xi;(function(i){i[i.ISO_8859_1=0]="ISO_8859_1",i[i.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",i[i.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",i[i.UTF_8=3]="UTF_8"})(xi||(xi={}));var Ss=128,bi=10,yi=["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"],Ts=async(i,e,t)=>{let r=e;for(;t===null||r<t;){let s=i.requestSlice(r,4);if(s instanceof Promise&&(s=await s),!s)break;let n=B(s),o=Gf(n,i.fileSize!==null?i.fileSize-r:null);if(o.header)return{header:o.header,startPos:r};r+=o.bytesAdvanced}return null},Lf=(i,e)=>{let t=i.filePos;e.raw??={},e.raw.TAG??=W(i,Ss-3),i.filePos=t;let r=pi(i,30);r&&(e.title??=r);let s=pi(i,30);s&&(e.artist??=s);let n=pi(i,30);n&&(e.album??=n);let o=pi(i,4),a=Number.parseInt(o,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=W(i,30),l;if(c[28]===0&&c[29]!==0){let h=c[29];h>0&&(e.trackNumber??=h),i.skip(-30),l=pi(i,28),i.skip(2)}else i.skip(-30),l=pi(i,30);l&&(e.comment??=l);let u=z(i);u<yi.length&&(e.genre??=yi[u])},pi=(i,e)=>{let t=W(i,e),r=Mr(t.indexOf(0),t.length),s=t.subarray(0,r),n="";for(let o=0;o<s.length;o++)n+=String.fromCharCode(s[o]);return n.trimEnd()},ks=i=>{let e=i.filePos,t=de(i,3),r=z(i),s=z(i),n=z(i),o=B(i);if(t!=="ID3"||r===255||s===255||(o&2155905152)!==0)return i.filePos=e,null;let a=Ao(o);return{majorVersion:r,revision:s,flags:n,size:a}},Vf=(i,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let r=W(i,e.size),s=new kl(e,r);if(e.flags&gi.Footer&&s.removeFooter(),e.flags&gi.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&gi.ExtendedHeader){let n=s.readU32();e.majorVersion===3?s.pos+=n:s.pos+=n-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){let n=s.readId3V2Frame();if(!n)break;let o=s.pos,a=s.pos+n.size,c=!1,l=!1,u=!1;if(e.majorVersion===3?(c=!!(n.flags&64),l=!!(n.flags&128)):e.majorVersion===4&&(c=!!(n.flags&4),l=!!(n.flags&8),u=!!(n.flags&2)||!!(e.flags&gi.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${n.id}`),s.pos=a;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${n.id}`),s.pos=a;continue}switch(u&&s.ununsynchronizeRegion(s.pos,a),t.raw??={},n.id[0]==="T"?t.raw[n.id]??=s.readId3V2EncodingAndText(a):t.raw[n.id]??=s.readBytes(n.size),s.pos=o,n.id){case"TIT2":case"TT2":t.title??=s.readId3V2EncodingAndText(a);break;case"TIT3":case"TT3":t.description??=s.readId3V2EncodingAndText(a);break;case"TPE1":case"TP1":t.artist??=s.readId3V2EncodingAndText(a);break;case"TALB":case"TAL":t.album??=s.readId3V2EncodingAndText(a);break;case"TPE2":case"TP2":t.albumArtist??=s.readId3V2EncodingAndText(a);break;case"TRCK":case"TRK":{let d=s.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(d[0],10),m=d[1]&&Number.parseInt(d[1],10);Number.isInteger(f)&&f>0&&(t.trackNumber??=f),m&&Number.isInteger(m)&&m>0&&(t.tracksTotal??=m)}break;case"TPOS":case"TPA":{let d=s.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(d[0],10),m=d[1]&&Number.parseInt(d[1],10);Number.isInteger(f)&&f>0&&(t.discNumber??=f),m&&Number.isInteger(m)&&m>0&&(t.discsTotal??=m)}break;case"TCON":case"TCO":{let h=s.readId3V2EncodingAndText(a),d=/^\((\d+)\)/.exec(h);if(d){let f=Number.parseInt(d[1]);if(yi[f]!==void 0){t.genre??=yi[f];break}}if(d=/^\d+$/.exec(h),d){let f=Number.parseInt(d[0]);if(yi[f]!==void 0){t.genre??=yi[f];break}}t.genre??=h}break;case"TDRC":case"TDAT":{let h=s.readId3V2EncodingAndText(a),d=new Date(h);Number.isNaN(d.getTime())||(t.date??=d)}break;case"TYER":case"TYE":{let h=s.readId3V2EncodingAndText(a),d=Number.parseInt(h,10);Number.isInteger(d)&&(t.date??=new Date(d,0,1))}break;case"USLT":case"ULT":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,a),t.lyrics??=s.readId3V2Text(h,a)}break;case"COMM":case"COM":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,a),t.comment??=s.readId3V2Text(h,a)}break;case"APIC":case"PIC":{let h=s.readId3V2TextEncoding(),d;if(e.majorVersion===2){let g=s.readAscii(3);d=g==="PNG"?"image/png":g==="JPG"?"image/jpeg":"image/*"}else d=s.readId3V2Text(h,a);let f=s.readU8(),m=s.readId3V2Text(h,a).trimEnd(),p=a-s.pos;if(p>=0){let g=s.readBytes(p);t.images||(t.images=[]),t.images.push({data:g,mimeType:d,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=n.size;break}s.pos=a}},kl=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let r=this.bytes[t];e.push(r),r===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let r=[];for(let o=e;o<t;o++){let a=this.bytes[o];r.push(a),a===255&&o!==t-1&&this.bytes[o+1]===0&&o++}let s=this.bytes.subarray(0,e),n=this.bytes.subarray(t);this.bytes=new Uint8Array(s.length+r.length+n.length),this.bytes.set(s,0),this.bytes.set(r,s.length),this.bytes.set(n,s.length+r.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-bi),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),r=this.header.majorVersion===4?Ao(t):t,s=this.readU16(),n=this.pos,o=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(!o(r)){let a=this.header.majorVersion===4?t:Ao(t);o(a)&&(r=a)}return this.pos=n,{id:e,size:r,flags:s}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let r=this.pos,s=this.readBytes(t);switch(e){case xi.ISO_8859_1:{let n="";for(let o=0;o<s.length;o++){let a=s[o];if(a===0){this.pos=r+o+1;break}n+=String.fromCharCode(a)}return n}case xi.UTF_16_WITH_BOM:if(s[0]===255&&s[1]===254){let n=new TextDecoder("utf-16le"),o=Mr(s.findIndex((a,c)=>a===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(o+2,s.length),n.decode(s.subarray(2,o))}else if(s[0]===254&&s[1]===255){let n=new TextDecoder("utf-16be"),o=Mr(s.findIndex((a,c)=>a===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(o+2,s.length),n.decode(s.subarray(2,o))}else{let n=Mr(s.findIndex(o=>o===0),s.length);return this.pos=r+Math.min(n+1,s.length),Be.decode(s.subarray(0,n))}case xi.UTF_16_BE_NO_BOM:{let n=new TextDecoder("utf-16be"),o=Mr(s.findIndex((a,c)=>a===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(o+2,s.length),n.decode(s.subarray(0,o))}case xi.UTF_8:{let n=Mr(s.findIndex(o=>o===0),s.length);return this.pos=r+Math.min(n+1,s.length),Be.decode(s.subarray(0,n))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var vl=1399285583,G_=79764919,Wf=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^G_:e<<1;Wf[i]=e>>>0&4294967295}var Hf=i=>{let e=oe(i),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let s=0;s<i.length;s++){let n=i[s];r=(r<<8^Wf[r>>>24^n])>>>0}return e.setUint32(22,t,!0),r},jf=(i,e,t)=>{let r=0,s=null;if(i.length>0)if(e.codec==="vorbis"){k(e.vorbisInfo);let n=e.vorbisInfo.modeBlockflags.length,a=(1<<mf(n-1))-1<<1,c=(i[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,u=e.vorbisInfo.modeBlockflags[c];if(s=e.vorbisInfo.blocksizes[u],u===1){let h=(a|1)+1,d=i[0]&h?1:0;l=e.vorbisInfo.blocksizes[d]}r=l!==null?l+s>>2:0}else e.codec==="opus"&&(r=Pf(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:s}},$f=i=>{let e="audio/ogg";if(i.codecStrings){let t=[...new Set(i.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var cr=27,Rr=282,qf=Rr+65025,wi=i=>{let e=i.filePos;if(Fr(i)!==vl)return null;i.skip(1);let r=z(i),s=Mf(i),n=Fr(i),o=Fr(i),a=Fr(i),c=z(i),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=z(i);let u=27+c,h=l.reduce((f,m)=>f+m,0),d=u+h;return{headerStartPos:e,totalSize:d,dataStartPos:e+u,dataSize:h,headerType:r,granulePosition:s,serialNumber:n,sequenceNumber:o,checksum:a,lacingValues:l}},Xf=(i,e)=>{for(;i.filePos<e-3;){let t=Fr(i),r=t&255,s=t>>>8&255,n=t>>>16&255,o=t>>>24&255,a=79;if(!(r!==a&&s!==a&&n!==a&&o!==a)){if(i.skip(-4),t===vl)return!0;i.skip(1)}}return!1};var We=class{constructor(e){this.input=e}};var Io=[],Pl=[];var Ee=new Uint8Array(0),ce=class i{constructor(e,t,r,s,n=-1,o){if(this.data=e,this.type=t,this.timestamp=r,this.duration=s,this.sequenceNumber=n,e===Ee&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(s)||s<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");this.byteLength=o}get isMetadataOnly(){return this.data===Ee}get microsecondTimestamp(){return Math.trunc(sr*this.timestamp)}get microsecondDuration(){return Math.trunc(sr*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})}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){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let t=new Uint8Array(e.byteLength);return e.copyTo(t),new i(t,e.type,e.timestamp/1e6,(e.duration??0)/1e6)}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 i(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Ps=class i{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(sr*this.timestamp)}get microsecondDuration(){return Math.trunc(sr*this.duration)}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(!("format"in t)||typeof t.format!="string")throw new TypeError("init.format must be a string.");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=ir(e).slice(),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 VideoColorSpace(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.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=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 i(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*sr),duration:Math.trunc((t.duration??0)*sr)}),t);let r=0,s=0;if("naturalWidth"in e?(r=e.naturalWidth,s=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,s=e.videoHeight):"width"in e&&(r=Number(e.width),s=Number(e.height)),!r||!s)throw new TypeError("Could not determine dimensions.");let n=new OffscreenCanvas(r,s),o=n.getContext("2d",{alpha:!1,willReadFrequently:!0});k(o),o.drawImage(e,0,0),this._data=n,this.format="RGBX",this.codedWidth=r,this.codedHeight=s,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.")}clone(){if(this._closed)throw new Error("VideoSample is closed.");return k(this._data!==null),vs(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new i(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new i(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||(vs(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return k(this._data!==null),vs(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!ll(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if(k(this._data!==null),vs(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)ir(e).set(this._data);else{let r=this._data.getContext("2d",{alpha:!1});k(r);let s=r.getImageData(0,0,this.codedWidth,this.codedHeight);ir(e).set(s.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return k(this._data!==null),vs(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,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}draw(e,t,r,s,n,o,a,c,l){let u=0,h=0,d=this.displayWidth,f=this.displayHeight,m=0,p=0,g=this.displayWidth,y=this.displayHeight;if(o!==void 0?(u=t,h=r,d=s,f=n,m=o,p=a,c!==void 0?(g=c,y=l):(g=d,y=f)):(m=t,p=r,s!==void 0&&(g=s,y=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(h))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");this.rotation===90?[u,h,d,f]=[h,this.codedHeight-u-d,f,d]:this.rotation===180?[u,h]=[this.codedWidth-u-d,this.codedHeight-h-f]:this.rotation===270&&([u,h,d,f]=[this.codedWidth-h-f,u,f,d]);let x=this.toCanvasImageSource();e.save();let w=m+g/2,_=p+y/2;e.translate(w,_),e.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:g/y;e.scale(1/S,S),e.drawImage(x,u,h,d,f,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,t){let r=e.canvas.width,s=e.canvas.height,n=t.rotation??this.rotation,o,a,c,l;if(t.fit==="fill")o=0,a=0,c=r,l=s;else{let[h,d]=n%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth],f=t.fit==="contain"?Math.min(r/h,s/d):Math.max(r/h,s/d);c=h*f,l=d*f,o=(r-c)/2,a=(s-l)/2}let u=n%180===0?1:c/l;e.translate(r/2,s/2),e.rotate(n*Math.PI/180),e.scale(1/u,u),e.translate(-r/2,-s/2),e.drawImage(this.toCanvasImageSource(),o,a,c,l)}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(k(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}},vs=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame;var _i=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Or=i=>{if(typeof i!="number"||Number.isNaN(i))throw new TypeError("timestamp must be a number.")},Cl=(i,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;let s=await i.determinePacketType(r);return s&&(r.type=s),r}):e,Si=class{constructor(e){if(!(e instanceof Ti))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){return _i(e),Cl(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){return Or(e),_i(t),Cl(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");return _i(t),Cl(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Or(e),_i(t),!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return!r||r.type==="delta"?r:await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(_i(t),!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return!r||r.type==="delta"?r:await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(e!==void 0&&!(e instanceof ce))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof ce))throw new TypeError("endPacket must be an EncodedPacket.");_i(r);let s=[],{promise:n,resolve:o}=Fe(),{promise:a,resolve:c}=Fe(),l=!1,u=!1,h=null,d=[],f=()=>Math.max(2,d.length);return(async()=>{let m=e??await this.getFirstPacket(r);for(;m&&!u&&!(t&&m.sequenceNumber>=t?.sequenceNumber);){if(s.length>f()){({promise:a,resolve:c}=Fe()),await a;continue}s.push(m),o(),{promise:n,resolve:o}=Fe(),m=await this.getNextPacket(m,r)}l=!0,o()})().catch(m=>{h||(h=m,o())}),{async next(){for(;;){if(u)return{value:void 0,done:!0};if(h)throw h;if(s.length>0){let m=s.shift(),p=performance.now();for(d.push(p);d.length>0&&p-d[0]>=1e3;)d.shift();return c(),{value:m,done:!1}}else{if(l)return{value:void 0,done:!0};await n}}},async return(){return u=!0,c(),o(),{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}},El=class{constructor(e,t){this.onSample=e,this.onError=t}},Mo=class{mediaSamplesInRange(e=0,t=1/0){Or(e),Or(t);let r=[],s=!1,n=null,{promise:o,resolve:a}=Fe(),{promise:c,resolve:l}=Fe(),u=!1,h=!1,d=!1,f=null;return(async()=>{let m=new Error,p=await this._createDecoder(S=>{if(l(),S.timestamp>=t&&(h=!0),h){S.close();return}n&&(S.timestamp>e?(r.push(n),s=!0):n.close()),S.timestamp>=e&&(r.push(S),s=!0),n=s?null:S,r.length>0&&(a(),{promise:o,resolve:a}=Fe())},S=>{f||(S.stack=m.stack,f=S,a())}),g=this._createPacketSink(),y=await g.getKeyPacket(e,{verifyKeyPackets:!0})??await g.getFirstPacket();if(!y)return;let x=y,w;if(t<1/0){let S=await g.getPacket(t),T=S?S.type==="key"&&S.timestamp===t?S:await g.getNextKeyPacket(S,{verifyKeyPackets:!0}):null;T&&(w=T)}let _=g.packets(y,w);for(await _.next();x&&!h;){let S=Yf(r.length);if(r.length+p.getDecodeQueueSize()>S){({promise:c,resolve:l}=Fe()),await c;continue}p.decode(x);let T=await _.next();if(T.done)break;x=T.value}await _.return(),d||await p.flush(),p.close(),!s&&n&&r.push(n),u=!0,a()})().catch(m=>{f||(f=m,a())}),{async next(){for(;;){if(d)return{value:void 0,done:!0};if(f)throw f;if(r.length>0){let m=r.shift();return l(),{value:m,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}}},async return(){d=!0,h=!0,l(),a(),n?.close();for(let m of r)m.close();return{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){df(e);let t=hf(e),r=[],s=[],{promise:n,resolve:o}=Fe(),{promise:a,resolve:c}=Fe(),l=!1,u=!1,h=null,d=f=>{s.push(f),o(),{promise:n,resolve:o}=Fe()};return(async()=>{let f=new Error,m=await this._createDecoder(S=>{if(c(),u){S.close();return}let T=0;for(;r.length>0&&S.timestamp-r[0]>-1e-10;)T++,r.shift();if(T>0)for(let v=0;v<T;v++)d(v<T-1?S.clone():S);else S.close()},S=>{h||(S.stack=f.stack,h=S,o())}),p=this._createPacketSink(),g=null,y=null,x=-1,w=async()=>{k(y);let S=y;for(m.decode(S);S.sequenceNumber<x;){let T=Yf(s.length);for(;s.length+m.getDecodeQueueSize()>T&&!u;)({promise:a,resolve:c}=Fe()),await a;if(u)break;let v=await p.getNextPacket(S);k(v),m.decode(v),S=v}x=-1},_=async()=>{await m.flush();for(let S=0;S<r.length;S++)d(null);r.length=0};for await(let S of t){if(Or(S),u)break;let T=await p.getPacket(S),v=T&&await p.getKeyPacket(S,{verifyKeyPackets:!0});if(!v){x!==-1&&(await w(),await _()),d(null),g=null;continue}g&&(v.sequenceNumber!==y.sequenceNumber||T.timestamp<g.timestamp)&&(await w(),await _()),r.push(T.timestamp),x=Math.max(T.sequenceNumber,x),g=T,y=v}u||(x!==-1&&await w(),await _()),m.close(),l=!0,o()})().catch(f=>{h||(h=f,o())}),{async next(){for(;;){if(u)return{value:void 0,done:!0};if(h)throw h;if(s.length>0){let f=s.shift();return k(f!==void 0),c(),{value:f,done:!1}}else if(!l)await n;else return{value:void 0,done:!0}}},async return(){u=!0,c(),o();for(let f of s)f?.close();return{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}},Yf=i=>i===0?40:8,Al=class extends El{constructor(e,t,r,s,n,o){super(e,t),this.codec=r,this.decoderConfig=s,this.rotation=n,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new io,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1;let a=Io.find(c=>c.supports(r,s));if(a)this.customDecoder=new a,this.customDecoder.codec=r,this.customDecoder.config=s,this.customDecoder.onSample=c=>{if(!(c instanceof Ps))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=l=>{if(fo()){if(this.sampleQueue.length>0&&l.timestamp>=ve(this.sampleQueue).timestamp){for(let u of this.sampleQueue)this.finalizeAndEmitSample(u);this.sampleQueue.length=0}ot(this.sampleQueue,l,u=>u.timestamp)}else{let u=this.inputTimestamps.shift();k(u!==void 0),l.setTimestamp(u),this.finalizeAndEmitSample(l)}};this.decoder=new VideoDecoder({output:l=>c(new Ps(l)),error:t}),this.decoder.configure(s)}}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)}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(k(this.decoder),this.decoder.decodeQueueSize)}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(yl(e.data,this.decoderConfig).some(s=>{let n=zt(s);return n===De.RASL_N||n===De.RASL_R}))return;this.raslSkipped=!0}this.currentPacketIndex++,this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(k(this.decoder),fo()||ot(this.inputTimestamps,e.timestamp,t=>t),this.decoder.decode(e.toEncodedVideoChunk()))}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(k(this.decoder),await this.decoder.flush()),fo()){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()):(k(this.decoder),this.decoder.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Bo=class extends Mo{constructor(e){if(!(e instanceof wt))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._videoTrack=e}async _createDecoder(e,t){if(!await this._videoTrack.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._videoTrack.codec,s=this._videoTrack.rotation,n=await this._videoTrack.getDecoderConfig(),o=this._videoTrack.timeResolution;return k(r&&n),new Al(e,t,r,n,s,o)}_createPacketSink(){return new Si(this._videoTrack)}async getSample(e){Or(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)}},Cs=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof wt))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");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.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let r=t.rotation??e.rotation,[s,n]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],o=s/n;t.width!==void 0&&t.height===void 0?(s=t.width,n=Math.round(s/o)):t.width===void 0&&t.height!==void 0?(n=t.height,s=Math.round(n*o)):t.width!==void 0&&t.height!==void 0&&(s=t.width,n=t.height),this._videoTrack=e,this._width=s,this._height=n,this._rotation=r,this._fit=t.fit??"fill",this._videoSampleSink=new Bo(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],r=!1;t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),r=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let s=t.getContext("2d",{alpha:!1});k(s),s.resetTransform(),r||s.clearRect(0,0,this._width,this._height),e.drawWithFit(s,{fit:this._fit,rotation:this._rotation});let n={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e){Or(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return fl(this._videoSampleSink.samples(e,t),r=>this._videoSampleToWrappedCanvas(r))}canvasesAtTimestamps(e){return fl(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}};var Ti=class{constructor(e){this._backing=e}isVideoTrack(){return this instanceof wt}isAudioTrack(){return this instanceof Ae}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()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new Si(this),r=1/0,s=-1/0,n=0,o=0;for await(let a of t.packets(void 0,void 0,{metadataOnly:!0})){if(n>=e&&a.timestamp>=s)break;r=Math.min(r,a.timestamp),s=Math.max(s,a.timestamp+a.duration),n++,o+=a.byteLength}return{packetCount:n,averagePacketRate:n?Number((n/(s-r)).toPrecision(16)):0,averageBitrate:n?Number((8*o/(s-r)).toPrecision(16)):0}}},wt=class extends Ti{constructor(e){super(e),this._backing=e}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"}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 k(t!==null),Io.some(s=>s.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 ce))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");return this.codec===null?null:Ef(this,e)}},Ae=class extends Ti{constructor(e){super(e),this._backing=e}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 k(t!==null),Pl.some(r=>r.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Wt;(function(i){i[i.PCM=1]="PCM",i[i.IEEE_FLOAT=3]="IEEE_FLOAT",i[i.ALAW=6]="ALAW",i[i.MULAW=7]="MULAW",i[i.EXTENSIBLE=65534]="EXTENSIBLE"})(Wt||(Wt={}));var Fo=class extends We{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),k(e);let t=de(e,4),r=t!=="RIFX",s=t==="RF64",n=Gt(e,r),o=s?this.reader.fileSize:Math.min(n+8,this.reader.fileSize??1/0);if(de(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;o===null||u<o;){let d=this.reader.requestSlice(u,8);if(d instanceof Promise&&(d=await d),!d)break;let f=de(d,4),m=Gt(d,r),p=d.filePos;if(s&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(p,m,r);else if(f==="data"){if(l??=m,this.dataStart=d.filePos,this.dataSize=Math.min(l,(o??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let g=bl(d,r);l=bl(d,r),o=Math.min(g+8,this.reader.fileSize??1/0)}else f==="LIST"&&await this.parseListChunk(p,m,r);u=p+m+(m&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 h=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/h)*h,this.tracks.push(new Ae(new Il(this)))})()}async parseFmtChunk(e,t,r){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;let n=ui(s,r),o=ui(s,r),a=Gt(s,r);s.skip(4);let c=ui(s,r),l;if(t===14?l=8:l=ui(s,r),t>=18&&n!==357){let u=ui(s,r),h=t-18;if(Math.min(h,u)>=22&&n===Wt.EXTENSIBLE){s.skip(6);let f=W(s,16);n=f[0]|f[1]<<8}}(n===Wt.MULAW||n===Wt.ALAW)&&(l=8),this.audioInfo={format:n,numberOfChannels:o,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,r){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;let n=de(s,4);if(n!=="INFO"&&n!=="INF0")return;let o=s.filePos;for(;o<=e+t-8;){s.filePos=o;let a=de(s,4),c=Gt(s,r),l=W(s,c),u=0;for(let d=0;d<l.length&&l[d]!==0;d++)u++;let h=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=h,a){case"INAM":case"TITL":this.metadataTags.title??=h;break;case"TIT3":this.metadataTags.description??=h;break;case"IART":this.metadataTags.artist??=h;break;case"IPRD":this.metadataTags.album??=h;break;case"IPRT":case"ITRK":case"TRCK":{let d=h.split("/"),f=Number.parseInt(d[0],10),m=d[1]&&Number.parseInt(d[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),m&&Number.isInteger(m)&&m>0&&(this.metadataTags.tracksTotal??=m)}break;case"ICRD":case"IDIT":{let d=new Date(h);Number.isNaN(d.getTime())||(this.metadataTags.date??=d)}break;case"YEAR":{let d=Number.parseInt(h,10);Number.isInteger(d)&&d>0&&(this.metadataTags.date??=new Date(d,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=h;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=h;break}o+=8+c+(c&1)}}getCodec(){if(k(this.audioInfo),this.audioInfo.format===Wt.MULAW)return"ulaw";if(this.audioInfo.format===Wt.ALAW)return"alaw";if(this.audioInfo.format===Wt.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===Wt.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 k(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},ki=2048,Il=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return k(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(k(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 k(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return k(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return k(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Pe}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){k(this.demuxer.audioInfo);let r=e*ki*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let s=Math.min(ki*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,s);if(c instanceof Promise&&(c=await c),!c)return null}let n;if(t.metadataOnly)n=Ee;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,s);c instanceof Promise&&(c=await c),k(c),n=W(c,s)}let o=e*ki/this.demuxer.audioInfo.sampleRate,a=s/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,o),new ce(n,"key",o,a,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){k(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/ki,(this.demuxer.dataSize-1)/(ki*this.demuxer.audioInfo.blockSizeInBytes))),s=await this.getPacketAtIndex(r,t);if(s)return s;if(r===0)return null;k(this.demuxer.reader.fileSize===null);let n=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){let o=await this.getNextPacket(n,t);if(!o)break;n=o}return n}getNextPacket(e,t){k(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ki);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Ur=class{constructor(){this._sizePromise=null,this.onread=null}async getSizeOrNull(){return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var Es=class extends Ur{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&&(!Number.isInteger(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative integer.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Do({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Zf.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||(t=this._blob.slice(e.currentPos).stream().getReader(),this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;){let{done:r,value:s}=await t.read();if(r){if(this._orchestrator.forgetWorker(e),e.currentPos<e.targetPos)throw new Error("Blob reader stopped unexpectedly before all requested data was read.");break}this.onread?.(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}e.running=!1}get _supportsRandomAccess(){return!0}},Kf=.5*2**20,As=class extends Ur{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL))throw new TypeError("url must be a string or URL.");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&&(!Number.isInteger(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative integer.");super(),this._existingResponses=new WeakMap,this._url=e instanceof URL?e:new URL(e,typeof location<"u"?location.href:void 0),this._options=t,this._getRetryDelay=t.getRetryDelay??(r=>Math.min(2**(r-2),8)),this._orchestrator=new Do({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Zf.network})}async _retrieveSize(){let e=new AbortController,t=await ml(this._url,ho(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay);if(!t.ok)throw new Error(`Error fetching ${this._url}: ${t.status} ${t.statusText}`);let r,s;if(t.status===206)s=this._getPartialLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(s,Kf));else{let n=t.headers.get("Content-Length");if(n)s=Number(n),r=this._orchestrator.createWorker(0,s),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=s,this._existingResponses.set(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),s}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;!e.aborted;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let r=t?.abortController,s=t?.response;if(r||(r=new AbortController,s=await ml(this._url,ho(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay)),k(s),!s.ok)throw new Error(`Error fetching ${this._url}: ${s.status} ${s.statusText}`);if(e.currentPos>0&&s.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.");let n=this._getPartialLengthFromRangeResponse(s),o=e.targetPos-e.currentPos;if(n<o)throw new Error(`HTTP response unexpectedly too short: Needed at least ${o} bytes, got only ${n}.`);if(!s.body)throw new Error("Missing HTTP response body.");let a=s.body.getReader();for(;;){let c;try{c=await a.read()}catch(h){let d=this._getRetryDelay(1);if(d!==null){console.error("Error while reading response stream. Attempting to resume.",h),await new Promise(f=>setTimeout(f,1e3*d));break}else throw h}let{done:l,value:u}=c;if(l){if(this._orchestrator.forgetWorker(e),e.currentPos<e.targetPos)throw new Error("Response stream reader stopped unexpectedly before all requested data was read.");e.running=!1;return}if(this.onread?.(e.currentPos,e.currentPos+u.length),this._orchestrator.supplyWorkerData(e,u),e.currentPos>=e.targetPos||e.aborted){r.abort(),e.running=!1;return}}}e.running=!1}_getPartialLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let r=/\/(\d+)/.exec(t);if(r)return Number(r[1]);throw new Error(`Invalid Content-Range header: ${t}`)}else{let r=e.headers.get("Content-Length");if(r)return Number(r);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}}get _supportsRandomAccess(){return!0}};var Zf={none:(i,e)=>({start:i,end:e}),fileSystem:(i,e)=>(i=Math.floor((i-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:i,end:e}),network:(i,e,t)=>{i=Math.max(0,Math.floor((i-65536)/65536)*65536);for(let s of t){let o=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(mo(i,e,o,s.targetPos)){let a=s.targetPos-s.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),u=Math.min(l,c);e=Math.max(e,s.startPos+u)}}return e=Math.max(e,i+Kf),{start:i,end:e}}},Do=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0}read(e,t){k(this.fileSize!==null);let r=this.options.prefetchProfile(e,t,this.workers),s=Math.max(r.start,0),n=Math.min(r.end,this.fileSize);k(s<=e&&t<=n);let o=null,a=Q(this.cache,e,x=>x.start),c=a!==-1?this.cache[a]:null;c&&c.start<=e&&t<=c.end&&(c.age=this.nextAge++,o={bytes:c.bytes,view:c.view,offset:c.start});let l=Q(this.cache,s,x=>x.start),u=o?null:new Uint8Array(t-e),h=0,d=s,f=[];if(l!==-1){for(let x=l;x<this.cache.length;x++){let w=this.cache[x];if(w.start>=n)break;if(w.end<=s)continue;let _=Math.max(s,w.start),S=Math.min(n,w.end);if(k(_<=S),d<_&&f.push({start:d,end:_}),d=S,u){let T=Math.max(e,w.start),v=Math.min(t,w.end);if(T<v){let M=T-e;u.set(w.bytes.subarray(T-w.start,v-w.start),M),M===h&&(h=v-e)}}w.age=this.nextAge++}d<n&&f.push({start:d,end:n})}else f.push({start:s,end:n});if(u&&h>=u.length&&(o={bytes:u,view:oe(u),offset:e}),f.length===0)return k(o),o;let{promise:m,resolve:p,reject:g}=Fe(),y=[];for(let x of f){let w=Math.max(e,x.start),_=Math.min(t,x.end);w===x.start&&_===x.end?y.push(x):w<_&&y.push({start:w,end:_})}for(let x of f){let w=u&&{start:e,bytes:u,holes:y,resolve:p,reject:g},_=!1;for(let S of this.workers)if(mo(x.start-131072,x.start,S.currentPos,S.targetPos)){S.targetPos=Math.max(S.targetPos,x.end),_=!0,w&&!S.pendingSlices.includes(w)&&S.pendingSlices.push(w),S.running||this.runWorker(S);break}if(!_){let S=this.createWorker(x.start,x.end);w&&(S.pendingSlices=[w]),this.runWorker(S)}}return o||(k(u),o=m.then(x=>({bytes:x,view:oe(x),offset:e}))),o}createWorker(e,t){let r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:!1,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let s=0,n=this.workers[0];for(let o=1;o<this.workers.length;o++){let a=this.workers[o];a.age<n.age&&(s=o,n=a)}if(n.running&&n.pendingSlices.length>0)break;n.aborted=!0,this.workers.splice(s,1)}return r}runWorker(e){k(!e.running),k(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(r=>r.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){let r=e.currentPos,s=r+t.length;this.insertIntoCache({start:r,end:s,bytes:t,view:oe(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let n=0;n<e.pendingSlices.length;n++){let o=e.pendingSlices[n],a=Math.max(r,o.start),c=Math.min(s,o.start+o.bytes.length);a<c&&o.bytes.set(t.subarray(a-r,c-r),a-o.start);for(let l=0;l<o.holes.length;l++){let u=o.holes[l];r<=u.start&&s>u.start&&(u.start=s),u.end<=u.start&&(o.holes.splice(l,1),l--)}o.holes.length===0&&(o.resolve(o.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;n<this.workers.length;n++){let o=this.workers[n];e===o||o.running||mo(r,s,o.currentPos,o.targetPos)&&(this.workers.splice(n,1),n--)}}forgetWorker(e){let t=this.workers.indexOf(e);k(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=Q(this.cache,e.start,r=>r.start)+1;if(t>0){let r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){let s=new Uint8Array(e.end-r.start);s.set(r.bytes,0),s.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=s,r.view=oe(s),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){let s=this.cache[r];if(e.end<=s.start)break;if(e.end>=s.end){this.cache.splice(r,1),this.currentCacheSize-=s.bytes.length,r--;continue}let n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=oe(n),e.end=s.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,s=this.cache[0];for(let n=1;n<this.cache.length;n++){let o=this.cache[n];o.age<s.age&&(r=n,s=o)}if(this.currentCacheSize-s.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,1),this.currentCacheSize-=s.bytes.length}}};var N_=new Set(["@day","@mak","@mod","@swr","@xyz","CAME","CNCV","CNFV","CNMN","FIRM","FOV\0","GoPr","LENS","PXMN","SIGM","SNum","TAGS","albm","albr","angl","auth","ccid","cdis","clfn","clid","clsf","cmid","cmnm","coll","cprt","cver","cvru","date","dscp","fsid","gnre","hinv","icnu","info","infu","kgtt","loci","lrcu","mcvr","name","perf","pmcc","reel","rtng","scen","shot","slno","thmb","titl","tnam","urat","uuid","vndr","yrrc","\xA9ART","\xA9TIM","\xA9TSC","\xA9TSZ","\xA9alb","\xA9arg","\xA9ark","\xA9cmt","\xA9cok","\xA9com","\xA9cpy","\xA9day","\xA9dir","\xA9ed1","\xA9ed2","\xA9ed3","\xA9ed4","\xA9ed5","\xA9ed6","\xA9ed7","\xA9ed8","\xA9ed9","\xA9enc","\xA9fmt","\xA9fpt","\xA9frl","\xA9fyw","\xA9gen","\xA9gpt","\xA9grl","\xA9grp","\xA9gyw","\xA9inf","\xA9isr","\xA9lab","\xA9lal","\xA9lyr","\xA9mak","\xA9mal","\xA9mdl","\xA9mod","\xA9nam","\xA9pdk","\xA9phg","\xA9prd","\xA9prf","\xA9prk","\xA9prl","\xA9req","\xA9snk","\xA9snm","\xA9src","\xA9swf","\xA9swk","\xA9swr","\xA9too","\xA9trk","\xA9wrt","\xA9xsp","\xA9xyz","\xA9ysp","\xA9zsp"]),Ro=class extends We{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.fragments=[],this.currentFragment=null,this.fragmentLookupMutex=new Je,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(r=>r.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.inputTrack.getCodecParameterString()));return Af({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,Lt,Dr);if(t instanceof Promise&&(t=await t),!t)break;let r=e,s=bt(t);if(!s)break;if(s.name==="ftyp"){let n=de(t,4);this.isQuickTime=n==="qt "}else if(s.name==="moov"){let n=this.reader.requestSlice(t.filePos,s.contentSize);if(n instanceof Promise&&(n=await n),!n)break;this.moovSlice=n,this.readContiguousBoxes(this.moovSlice);for(let o of this.tracks){let a=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(a*o.timescale)}break}e=r+s.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let t=this.reader.requestSlice(this.reader.fileSize-4,4);t instanceof Promise&&(t=await t),k(t);let r=B(t),s=this.reader.fileSize-r;if(s>=0&&s<=this.reader.fileSize-Dr){let n=this.reader.requestSliceRange(s,Lt,Dr);if(n instanceof Promise&&(n=await n),n){let o=bt(n);if(o&&o.name==="mfra"){let a=this.reader.requestSlice(n.filePos,o.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,k(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ws.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){k(e.info?.type==="audio");let n=bf(e.info.codec),o=[],a=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],h=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let d=0;d<h;d++){let f=l.startSampleIndex+d*l.samplesPerChunk,m=f+l.samplesPerChunk,p=Q(t.sampleTimingEntries,f,M=>M.startIndex),g=t.sampleTimingEntries[p],y=Q(t.sampleTimingEntries,m,M=>M.startIndex),x=t.sampleTimingEntries[y],w=g.startDecodeTimestamp+(f-g.startIndex)*g.delta,S=x.startDecodeTimestamp+(m-x.startIndex)*x.delta-w,T=ve(o);T&&T.delta===S?T.count++:o.push({startIndex:l.startChunkIndex+d,startDecodeTimestamp:w,count:1,delta:S});let v=l.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;a.push(v)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=o,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let n of t.sampleTimingEntries)for(let o=0;o<n.count;o++)t.presentationTimestamps.push({presentationTimestamp:n.startDecodeTimestamp+o*n.delta,sampleIndex:n.startIndex+o});for(let n of t.sampleCompositionTimeOffsets)for(let o=0;o<n.count;o++){let a=n.startIndex+o,c=t.presentationTimestamps[a];c&&(c.presentationTimestamp+=n.offset)}t.presentationTimestamps.sort((n,o)=>n.presentationTimestamp-o.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let n=0;n<t.presentationTimestamps.length;n++)t.presentationTimestampIndexMap[t.presentationTimestamps[n].sampleIndex]=n}return t}async readFragment(e){let t=this.reader.requestSliceRange(e,Lt,Dr);t instanceof Promise&&(t=await t),k(t);let r=bt(t);k(r?.name==="moof");let s=this.reader.requestSlice(e,r.totalSize);s instanceof Promise&&(s=await s),k(s),this.traverseBox(s);let n=ae(this.fragments,e,a=>a.moofOffset);k(n!==-1);let o=this.fragments[n];k(o.moofOffset===e);for(let[a,c]of o.trackData){if(c.startTimestampIsFinal)continue;let l=this.tracks.find(p=>p.id===a),u=0,h=null,d=null,f=Q(l.fragments,e-1,p=>p.moofOffset);f!==-1&&(h=l.fragments[f],d=h,u=h.moofOffset+h.moofSize);let m=u===0;for(;u<=e-Lt;){if(h?.nextFragment)h=h.nextFragment,u=h.moofOffset+h.moofSize;else{let p=this.reader.requestSliceRange(u,Lt,Dr);if(p instanceof Promise&&(p=await p),!p)break;let g=u,y=bt(p);if(!y)break;if(y.name==="moof"){let x=ae(this.fragments,g,_=>_.moofOffset),w;x===-1?w=await this.readFragment(g):w=this.fragments[x],h&&(h.nextFragment=w),h=w,m&&(w.isKnownToBeFirstFragment=!0,m=!1)}u=g+y.totalSize}h&&h.trackData.has(a)&&(d=h)}if(d){let p=d.trackData.get(a);k(p.startTimestampIsFinal),Jf(c,p.endTimestamp)}c.startTimestampIsFinal=!0}return o}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Lt&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Lt;){let r=e.filePos,s=bt(e);if(!s)break;yield{boxInfo:s,slice:e},e.filePos=r+s.totalSize}}traverseBox(e){let t=e.filePos,r=bt(e);if(!r)return!1;let s=e.filePos,n=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"mvhd":{let o=z(e);e.skip(3),o===1?(e.skip(16),this.movieTimescale=B(e),this.movieDurationInTimescale=Ye(e)):(e.skip(8),this.movieTimescale=B(e),this.movieDurationInTimescale=B(e))}break;case"trak":{let o={id:-1,demuxer:this,inputTrack:null,info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Pe,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:null,currentFragmentState:null,fragments:[],fragmentsWithKeyFrame:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=o,this.readContiguousBoxes(e.slice(s,r.contentSize)),o.id!==-1&&o.timescale!==-1&&o.info!==null){if(o.info.type==="video"&&o.info.width!==-1){let a=o;o.inputTrack=new wt(new Ml(a)),this.tracks.push(o)}else if(o.info.type==="audio"&&o.info.numberOfChannels!==-1){let a=o;o.inputTrack=new Ae(new Bl(a)),this.tracks.push(o)}}this.currentTrack=null}break;case"tkhd":{let o=this.currentTrack;if(!o)break;let a=z(e);if(!((hi(e)&1)!==0))break;if(a===0)e.skip(8),o.id=B(e),e.skip(4),o.durationInMovieTimescale=B(e);else if(a===1)e.skip(16),o.id=B(e),e.skip(4),o.durationInMovieTimescale=Ye(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let u=[or(e),or(e),To(e),or(e),or(e),To(e),or(e),or(e),To(e)],h=so(ff(H_(u),90));k(h===0||h===90||h===180||h===270),o.rotation=h}break;case"elst":{let o=this.currentTrack;if(!o)break;let a=z(e);e.skip(3);let c=!1,l=0,u=B(e);for(let h=0;h<u;h++){let d=a===1?Ye(e):B(e),f=a===1?If(e):Nt(e),m=or(e);if(d!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=d;continue}if(m!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}o.editListPreviousSegmentDurations=l,o.editListOffset=f,c=!0}}}break;case"mdhd":{let o=this.currentTrack;if(!o)break;let a=z(e);e.skip(3),a===0?(e.skip(8),o.timescale=B(e),o.durationInMediaTimescale=B(e)):a===1&&(e.skip(16),o.timescale=B(e),o.durationInMediaTimescale=Ye(e));let c=Ce(e);if(c>0){o.languageCode="";for(let l=0;l<3;l++)o.languageCode=String.fromCharCode(96+(c&31))+o.languageCode,c>>=5;uo(o.languageCode)||(o.languageCode=Pe)}}break;case"hdlr":{let o=this.currentTrack;if(!o)break;e.skip(8);let a=de(e,4);a==="vide"?o.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(o.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let o=this.currentTrack;if(!o)break;o.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(s,r.contentSize))}break;case"stsd":{let o=this.currentTrack;if(!o||o.info===null||o.sampleTable)break;let a=z(e);e.skip(3);let c=B(e);for(let l=0;l<c;l++){let u=e.filePos,h=bt(e);if(!h)break;o.internalCodecId=h.name;let d=h.name.toLowerCase();if(o.info.type==="video")d==="avc1"?o.info.codec="avc":d==="hvc1"||d==="hev1"?o.info.codec="hevc":d==="vp08"?o.info.codec="vp8":d==="vp09"?o.info.codec="vp9":d==="av01"?o.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${h.name}').`),e.skip(24),o.info.width=Ce(e),o.info.height=Ce(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,u+h.totalSize-e.filePos));else{d==="mp4a"||(d==="opus"?o.info.codec="opus":d==="flac"?o.info.codec="flac":d==="twos"||d==="sowt"||d==="raw "||d==="in24"||d==="in32"||d==="fl32"||d==="fl64"||d==="lpcm"||d==="ipcm"||d==="fpcm"||(d==="ulaw"?o.info.codec="ulaw":d==="alaw"?o.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${h.name}').`))),e.skip(8);let f=Ce(e);e.skip(6);let m=Ce(e),p=Ce(e);e.skip(4);let g=B(e)/65536;if(a===0&&f>0){if(f===1)e.skip(4),p=8*B(e),e.skip(8);else if(f===2){e.skip(4),g=So(e),m=B(e),e.skip(4),p=B(e);let y=B(e);if(e.skip(8),d==="lpcm"){let x=p+7>>3,w=!!(y&1),_=!!(y&2),S=y&4?-1:0;p>0&&p<=64&&(w?p===32&&(o.info.codec=_?"pcm-f32be":"pcm-f32"):S&1<<x-1?x===1?o.info.codec="pcm-s8":x===2?o.info.codec=_?"pcm-s16be":"pcm-s16":x===3?o.info.codec=_?"pcm-s24be":"pcm-s24":x===4&&(o.info.codec=_?"pcm-s32be":"pcm-s32"):x===1&&(o.info.codec="pcm-u8")),o.info.codec===null&&console.warn("Unsupported PCM format.")}}}o.info.numberOfChannels=m,o.info.sampleRate=g,d==="twos"?p===8?o.info.codec="pcm-s8":p===16?o.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${p} for codec 'twos'.`),o.info.codec=null):d==="sowt"?p===8?o.info.codec="pcm-s8":p===16?o.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${p} for codec 'sowt'.`),o.info.codec=null):d==="raw "?o.info.codec="pcm-u8":d==="in24"?o.info.codec="pcm-s24be":d==="in32"?o.info.codec="pcm-s32be":d==="fl32"?o.info.codec="pcm-f32be":d==="fl64"?o.info.codec="pcm-f64be":d==="ipcm"?o.info.codec="pcm-s16be":d==="fpcm"&&(o.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,u+h.totalSize-e.filePos))}}}break;case"avcC":{let o=this.currentTrack;if(!o)break;k(o.info),o.info.codecDescription=W(e,r.contentSize)}break;case"hvcC":{let o=this.currentTrack;if(!o)break;k(o.info),o.info.codecDescription=W(e,r.contentSize)}break;case"vpcC":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="video"),e.skip(4);let a=z(e),c=z(e),l=z(e),u=l>>4,h=l>>1&7,d=l&1,f=z(e),m=z(e),p=z(e);o.info.vp9CodecInfo={profile:a,level:c,bitDepth:u,chromaSubsampling:h,videoFullRangeFlag:d,colourPrimaries:f,transferCharacteristics:m,matrixCoefficients:p}}break;case"av1C":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="video"),e.skip(1);let a=z(e),c=a>>5,l=a&31,u=z(e),h=u>>7,d=u>>6&1,f=u>>5&1,m=u>>4&1,p=u>>3&1,g=u>>2&1,y=u&3,x=c===2&&d?f?12:10:d?10:8;o.info.av1CodecInfo={profile:c,level:l,tier:h,bitDepth:x,monochrome:m,chromaSubsamplingX:p,chromaSubsamplingY:g,chromaSamplePosition:y}}break;case"colr":{let o=this.currentTrack;if(!o||(k(o.info?.type==="video"),de(e,4)!=="nclx"))break;let c=Ce(e),l=Ce(e),u=Ce(e),h=!!(z(e)&128);o.info.colorSpace={primaries:no[c],transfer:oo[l],matrix:ao[u],fullRange:h}}break;case"wave":this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"esds":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),e.skip(4);let a=z(e);k(a===3),ko(e),e.skip(2);let c=z(e),l=(c&128)!==0,u=(c&64)!==0,h=(c&32)!==0;if(l&&e.skip(2),u){let g=z(e);e.skip(g)}h&&e.skip(2);let d=z(e);k(d===4);let f=ko(e),m=e.filePos,p=z(e);if(p===64||p===103?(o.info.codec="aac",o.info.aacCodecInfo={isMpeg2:p===103}):p===105||p===107?o.info.codec="mp3":p===221?o.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${p}) - discarding track.`),e.skip(12),f>e.filePos-m){let g=z(e);k(g===5);let y=ko(e);if(o.info.codecDescription=W(e,y),o.info.codec==="aac"){let x=gl(o.info.codecDescription);x.numberOfChannels!==null&&(o.info.numberOfChannels=x.numberOfChannels),x.sampleRate!==null&&(o.info.sampleRate=x.sampleRate)}}}break;case"enda":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),Ce(e)&255&&(o.info.codec==="pcm-s16be"?o.info.codec="pcm-s16":o.info.codec==="pcm-s24be"?o.info.codec="pcm-s24":o.info.codec==="pcm-s32be"?o.info.codec="pcm-s32":o.info.codec==="pcm-f32be"?o.info.codec="pcm-f32":o.info.codec==="pcm-f64be"&&(o.info.codec="pcm-f64"))}break;case"pcmC":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),e.skip(4);let c=!!(z(e)&1),l=z(e);o.info.codec==="pcm-s16be"?c?l===16?o.info.codec="pcm-s16":l===24?o.info.codec="pcm-s24":l===32?o.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),o.info.codec=null):l===16?o.info.codec="pcm-s16be":l===24?o.info.codec="pcm-s24be":l===32?o.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),o.info.codec=null):o.info.codec==="pcm-f32be"&&(c?l===32?o.info.codec="pcm-f32":l===64?o.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),o.info.codec=null):l===32?o.info.codec="pcm-f32be":l===64?o.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),o.info.codec=null));break}case"dOps":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),e.skip(1);let a=z(e),c=Ce(e),l=B(e),u=_s(e),h=z(e),d;h!==0?d=W(e,2+a):d=new Uint8Array(0);let f=new Uint8Array(19+d.byteLength),m=new DataView(f.buffer);m.setUint32(0,1332770163,!1),m.setUint32(4,1214603620,!1),m.setUint8(8,1),m.setUint8(9,a),m.setUint16(10,c,!0),m.setUint32(12,l,!0),m.setInt16(16,u,!0),m.setUint8(18,h),f.set(d,19),o.info.codecDescription=f,o.info.numberOfChannels=a,o.info.sampleRate=l}break;case"dfLa":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<n;){let m=z(e),p=hi(e);if((m&a)===0){e.skip(10);let y=B(e),x=y>>>12,w=(y>>9&7)+1;o.info.sampleRate=x,o.info.numberOfChannels=w,e.skip(20)}else e.skip(p);if(m&c)break}let u=e.filePos;e.filePos=l;let h=W(e,u-l),d=new Uint8Array(4+h.byteLength);new DataView(d.buffer).setUint32(0,1716281667,!1),d.set(h,4),o.info.codecDescription=d}break;case"stts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e),c=0,l=0;for(let u=0;u<a;u++){let h=B(e),d=B(e);o.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:h,delta:d}),c+=h,l+=h*d}}break;case"ctts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e),c=0;for(let l=0;l<a;l++){let u=B(e),h=Nt(e);o.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:h}),c+=u}}break;case"stsz":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e),c=B(e);if(a===0)for(let l=0;l<c;l++){let u=B(e);o.sampleTable.sampleSizes.push(u)}else o.sampleTable.sampleSizes.push(a)}break;case"stz2":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),e.skip(3);let a=z(e),c=B(e),l=W(e,Math.ceil(c*a/8)),u=new fe(l);for(let h=0;h<c;h++){let d=u.readBits(a);o.sampleTable.sampleSizes.push(d)}}break;case"stss":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),o.sampleTable.keySampleIndices=[];let a=B(e);for(let c=0;c<a;c++){let l=B(e)-1;o.sampleTable.keySampleIndices.push(l)}o.sampleTable.keySampleIndices[0]!==0&&o.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e);for(let l=0;l<a;l++){let u=B(e)-1,h=B(e),d=B(e);o.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:h,sampleDescriptionIndex:d})}let c=0;for(let l=0;l<o.sampleTable.sampleToChunk.length;l++)if(o.sampleTable.sampleToChunk[l].startSampleIndex=c,l<o.sampleTable.sampleToChunk.length-1){let h=o.sampleTable.sampleToChunk[l+1].startChunkIndex-o.sampleTable.sampleToChunk[l].startChunkIndex;c+=h*o.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e);for(let c=0;c<a;c++){let l=B(e);o.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e);for(let c=0;c<a;c++){let l=Ye(e);o.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"mehd":{let o=z(e);e.skip(3);let a=o===1?Ye(e):B(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let o=B(e),a=B(e),c=B(e),l=B(e),u=B(e);this.fragmentTrackDefaults.push({trackId:o,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{let o=z(e);e.skip(3);let a=B(e),c=this.tracks.find(x=>x.id===a);if(!c)break;c.fragmentLookupTable=[];let l=B(e),u=(l&48)>>4,h=(l&12)>>2,d=l&3,f=[z,Ce,hi,B],m=f[u],p=f[h],g=f[d],y=B(e);for(let x=0;x<y;x++){let w=o===1?Ye(e):B(e),_=o===1?Ye(e):B(e);m(e),p(e),g(e),c.fragmentLookupTable.push({timestamp:w,moofOffset:_})}}break;case"moof":{this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map,dataStart:1/0,dataEnd:0,nextFragment:null,isKnownToBeFirstFragment:!1},this.readContiguousBoxes(e.slice(s,r.contentSize)),ot(this.fragments,this.currentFragment,o=>o.moofOffset);for(let[,o]of this.currentFragment.trackData){let a=o.samples[0],c=ve(o.samples);this.currentFragment.dataStart=Math.min(this.currentFragment.dataStart,a.byteOffset),this.currentFragment.dataEnd=Math.max(this.currentFragment.dataEnd,c.byteOffset+c.byteSize)}this.currentFragment=null}break;case"traf":if(k(this.currentFragment),this.readContiguousBoxes(e.slice(s,r.contentSize)),this.currentTrack){let o=this.currentFragment.trackData.get(this.currentTrack.id);if(o){ot(this.currentTrack.fragments,this.currentFragment,l=>l.moofOffset),o.firstKeyFrameTimestamp!==null&&ot(this.currentTrack.fragmentsWithKeyFrame,this.currentFragment,l=>l.moofOffset);let{currentFragmentState:c}=this.currentTrack;k(c),c.startTimestamp!==null&&(Jf(o,c.startTimestamp),o.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{k(this.currentFragment),e.skip(1);let o=hi(e),a=!!(o&1),c=!!(o&2),l=!!(o&8),u=!!(o&16),h=!!(o&32),d=!!(o&65536),f=!!(o&131072),m=B(e),p=this.tracks.find(y=>y.id===m);if(!p)break;let g=this.fragmentTrackDefaults.find(y=>y.trackId===m);this.currentTrack=p,p.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:g?.defaultSampleDescriptionIndex??null,defaultSampleDuration:g?.defaultSampleDuration??null,defaultSampleSize:g?.defaultSampleSize??null,defaultSampleFlags:g?.defaultSampleFlags??null,startTimestamp:null},a?p.currentFragmentState.baseDataOffset=Ye(e):f&&(p.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(p.currentFragmentState.sampleDescriptionIndex=B(e)),l&&(p.currentFragmentState.defaultSampleDuration=B(e)),u&&(p.currentFragmentState.defaultSampleSize=B(e)),h&&(p.currentFragmentState.defaultSampleFlags=B(e)),d&&(p.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let o=this.currentTrack;if(!o)break;k(o.currentFragmentState);let a=z(e);e.skip(3);let c=a===0?B(e):Ye(e);o.currentFragmentState.startTimestamp=c}break;case"trun":{let o=this.currentTrack;if(!o)break;if(k(this.currentFragment),k(o.currentFragmentState),this.currentFragment.trackData.has(o.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let a=z(e),c=hi(e),l=!!(c&1),u=!!(c&4),h=!!(c&256),d=!!(c&512),f=!!(c&1024),m=!!(c&2048),p=B(e),g=o.currentFragmentState.baseDataOffset;l&&(g+=Nt(e));let y=null;u&&(y=B(e));let x=g;if(p===0){this.currentFragment.implicitBaseDataOffset=x;break}let w=0,_={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(o.id,_);for(let v=0;v<p;v++){let M;h?M=B(e):(k(o.currentFragmentState.defaultSampleDuration!==null),M=o.currentFragmentState.defaultSampleDuration);let P;d?P=B(e):(k(o.currentFragmentState.defaultSampleSize!==null),P=o.currentFragmentState.defaultSampleSize);let C;f?C=B(e):(k(o.currentFragmentState.defaultSampleFlags!==null),C=o.currentFragmentState.defaultSampleFlags),v===0&&y!==null&&(C=y);let E=0;m&&(a===0?E=B(e):E=Nt(e));let D=!(C&65536);_.samples.push({presentationTimestamp:w+E,duration:M,byteOffset:x,byteSize:P,isKeyFrame:D}),x+=P,w+=M}_.presentationTimestamps=_.samples.map((v,M)=>({presentationTimestamp:v.presentationTimestamp,sampleIndex:M})).sort((v,M)=>v.presentationTimestamp-M.presentationTimestamp);for(let v=0;v<_.presentationTimestamps.length;v++){let M=_.presentationTimestamps[v],P=_.samples[M.sampleIndex];if(_.firstKeyFrameTimestamp===null&&P.isKeyFrame&&(_.firstKeyFrameTimestamp=P.presentationTimestamp),v<_.presentationTimestamps.length-1){let C=_.presentationTimestamps[v+1];P.duration=C.presentationTimestamp-M.presentationTimestamp}}let S=_.samples[_.presentationTimestamps[0].sampleIndex],T=_.samples[ve(_.presentationTimestamps).sampleIndex];_.startTimestamp=S.presentationTimestamp,_.endTimestamp=T.presentationTimestamp+T.duration,this.currentFragment.implicitBaseDataOffset=x}break;case"udta":{let o=this.iterateContiguousBoxes(e.slice(s,r.contentSize));for(let{boxInfo:a,slice:c}of o){if(a.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},N_.has(a.name)?this.metadataTags.raw[a.name]??=at(c):this.metadataTags.raw[a.name]??=W(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=Be.decode(W(c,a.contentSize)):this.metadataTags.title??=at(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=at(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=at(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=at(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=at(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=at(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(at(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=at(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=at(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=B(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(s,r.contentSize)):this.readContiguousBoxes(e.slice(s+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let o=B(e);for(let a=0;a<o;a++){let c=B(e);e.skip(4);let l=Be.decode(W(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let o=this.iterateContiguousBoxes(e.slice(s,r.contentSize));for(let{boxInfo:a,slice:c}of o){let l=a.name,u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));let h=Ff(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=h,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof h=="string"&&(this.metadataTags.title??=h);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof h=="string"&&(this.metadataTags.description??=h);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof h=="string"&&(this.metadataTags.artist??=h);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof h=="string"&&(this.metadataTags.album??=h);break;case"aART":case"album_artist":typeof h=="string"&&(this.metadataTags.albumArtist??=h);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof h=="string"&&(this.metadataTags.comment??=h);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof h=="string"&&(this.metadataTags.genre??=h);break;case"\xA9lyr":case"lyrics":typeof h=="string"&&(this.metadataTags.lyrics??=h);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof h=="string"){let d=new Date(h);Number.isNaN(d.getTime())||(this.metadataTags.date??=d)}break;case"covr":case"com.apple.quicktime.artwork":h instanceof nr?(this.metadataTags.images??=[],this.metadataTags.images.push({data:h.data,kind:"coverFront",mimeType:h.mimeType})):h instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:h,kind:"coverFront",mimeType:"image/*"}));break;case"trkn":if(h instanceof Uint8Array){let d=oe(h),f=d.getUint16(2,!1),m=d.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),m>0&&(this.metadataTags.tracksTotal??=m)}break;case"disc":case"disk":if(h instanceof Uint8Array){let d=oe(h),f=d.getUint16(2,!1),m=d.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),m>0&&(this.metadataTags.discsTotal??=m)}break}}}break}return e.filePos=n,!0}},Oo=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}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(()=>{let r=this.internalTrack.demuxer.fragments[0]??null;if(r?.isKnownToBeFirstFragment){let s=r;for(;s;){if(s.trackData.get(this.internalTrack.id))return{fragmentIndex:ae(this.internalTrack.fragments,s.moofOffset,o=>o.moofOffset),sampleIndex:0,correctSampleFound:!0};s=s.nextFragment}}return{fragmentIndex:-1,sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ir(e*this.internalTrack.timescale,14)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Qf(s,r),o=await this.fetchPacketForSampleIndex(n,t);return!em(s)||!this.internalTrack.demuxer.isFragmented?o:this.performFragmentedLookup(()=>this.findSampleInFragmentsForTimestamp(r),r,r,t)}async getNextPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,t);let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");let n=s.fragment.trackData.get(this.internalTrack.id),o=ae(this.internalTrack.fragments,s.fragment.moofOffset,a=>a.moofOffset);return k(o!==-1),this.performFragmentedLookup(()=>{if(s.sampleIndex+1<n.samples.length)return{fragmentIndex:o,sampleIndex:s.sampleIndex+1,correctSampleFound:!0};{let a=s.fragment;for(;a.nextFragment;)if(a=a.nextFragment,a.trackData.get(this.internalTrack.id)){let l=ae(this.internalTrack.fragments,a.moofOffset,u=>u.moofOffset);return k(l!==-1),{fragmentIndex:l,sampleIndex:0,correctSampleFound:!0}}return{fragmentIndex:o,sampleIndex:-1,correctSampleFound:!1}}},-1/0,1/0,t)}async getKeyPacket(e,t){let r=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Qf(s,r),o=n===-1?-1:V_(s,n),a=await this.fetchPacketForSampleIndex(o,t);return!em(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(()=>this.findKeySampleInFragmentsForTimestamp(r),r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),c=W_(a,r);return this.fetchPacketForSampleIndex(c,t)}let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");let n=s.fragment.trackData.get(this.internalTrack.id),o=ae(this.internalTrack.fragments,s.fragment.moofOffset,a=>a.moofOffset);return k(o!==-1),this.performFragmentedLookup(()=>{let a=n.samples.findIndex((c,l)=>c.isKeyFrame&&l>s.sampleIndex);if(a!==-1)return{fragmentIndex:o,sampleIndex:a,correctSampleFound:!0};{let c=s.fragment;for(;c.nextFragment;){c=c.nextFragment;let l=c.trackData.get(this.internalTrack.id);if(l&&l.firstKeyFrameTimestamp!==null){let u=ae(this.internalTrack.fragments,c.moofOffset,d=>d.moofOffset);k(u!==-1);let h=l.samples.findIndex(d=>d.isKeyFrame);return k(h!==-1),{fragmentIndex:u,sampleIndex:h,correctSampleFound:!0}}}return{fragmentIndex:o,sampleIndex:-1,correctSampleFound:!1}}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=L_(r,e);if(!s)return null;let n;if(t.metadataOnly)n=Ee;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.sampleOffset,s.sampleSize);l instanceof Promise&&(l=await l),k(l),n=W(l,s.sampleSize)}let o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=s.duration/this.internalTrack.timescale,c=new ce(n,s.isKeyFrame?"key":"delta",o,a,e,s.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).samples[t];k(n);let o;if(r.metadataOnly)o=Ee;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);u instanceof Promise&&(u=await u),k(u),o=W(u,n.byteSize)}let a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,l=new ce(o,n.isKeyFrame?"key":"delta",a,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}findSampleInFragmentsForTimestamp(e){let t=Q(this.internalTrack.fragments,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,s=!1;if(t!==-1){let o=this.internalTrack.fragments[t].trackData.get(this.internalTrack.id),a=Q(o.presentationTimestamps,e,c=>c.presentationTimestamp);k(a!==-1),r=o.presentationTimestamps[a].sampleIndex,s=e<o.endTimestamp}return{fragmentIndex:t,sampleIndex:r,correctSampleFound:s}}findKeySampleInFragmentsForTimestamp(e){let t=Q(this.internalTrack.fragmentsWithKeyFrame,e,o=>o.trackData.get(this.internalTrack.id).startTimestamp),r=-1,s=-1,n=!1;if(t!==-1){let o=this.internalTrack.fragmentsWithKeyFrame[t];r=ae(this.internalTrack.fragments,o.moofOffset,u=>u.moofOffset),k(r!==-1);let a=o.trackData.get(this.internalTrack.id),c=co(a.presentationTimestamps,u=>a.samples[u.sampleIndex].isKeyFrame&&u.presentationTimestamp<=e);k(c!==-1),s=a.presentationTimestamps[c].sampleIndex,n=e<a.endTimestamp}return{fragmentIndex:r,sampleIndex:s,correctSampleFound:n}}async performFragmentedLookup(e,t,r,s){let n=this.internalTrack.demuxer,o=await n.fragmentLookupMutex.acquire();try{let{fragmentIndex:a,sampleIndex:c,correctSampleFound:l}=e();if(l){let x=this.internalTrack.fragments[a];return this.fetchPacketInFragment(x,c,s)}let u=null,h=a,d=c,f=this.internalTrack.fragmentLookupTable?Q(this.internalTrack.fragmentLookupTable,t,x=>x.timestamp):-1,m=f!==-1?this.internalTrack.fragmentLookupTable[f]:null,p,g=!1;if(a===-1)p=m?.moofOffset??0,g=p===0;else{let x=this.internalTrack.fragments[a];!m||x.moofOffset>=m.moofOffset?(p=x.moofOffset+x.moofSize,u=x):p=m.moofOffset}for(;;){if(u){let S=u.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>r)break;if(u.nextFragment){p=u.nextFragment.moofOffset+u.nextFragment.moofSize,u=u.nextFragment;continue}}let x=n.reader.requestSliceRange(p,Lt,Dr);if(x instanceof Promise&&(x=await x),!x)break;let w=p,_=bt(x);if(!_)break;if(_.name==="moof"){let S=ae(n.fragments,w,C=>C.moofOffset),T;S===-1?T=await n.readFragment(w):T=n.fragments[S],u&&(u.nextFragment=T),u=T,g&&(T.isKnownToBeFirstFragment=!0,g=!1);let{fragmentIndex:v,sampleIndex:M,correctSampleFound:P}=e();if(P){let C=this.internalTrack.fragments[v];return this.fetchPacketInFragment(C,M,s)}v!==-1&&(h=v,d=M)}p=w+_.totalSize}let y=h!==-1?this.internalTrack.fragments[h]:null;if(m&&(!y||y.moofOffset<m.moofOffset)){let w=this.internalTrack.fragmentLookupTable[f-1]?.timestamp??-1/0;return this.performFragmentedLookup(e,w,r,s)}return y?this.fetchPacketInFragment(y,d,s):null}finally{o()}}},Ml=class extends Oo{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 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&&bo(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&wo(e.data)}return{codec:po(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}},Bl=class extends Oo{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:go(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Qf=(i,e)=>{if(i.presentationTimestamps){let t=Q(i.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:i.presentationTimestamps[t].sampleIndex}else{let t=Q(i.sampleTimingEntries,e,s=>s.startDecodeTimestamp);if(t===-1)return-1;let r=i.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},L_=(i,e)=>{let t=Q(i.sampleTimingEntries,e,y=>y.startIndex),r=i.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let n=r.startDecodeTimestamp+(e-r.startIndex)*r.delta,o=Q(i.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=i.sampleCompositionTimeOffsets[o];a&&e-a.startIndex<a.count&&(n+=a.offset);let c=i.sampleSizes[Math.min(e,i.sampleSizes.length-1)],l=Q(i.sampleToChunk,e,y=>y.startSampleIndex),u=i.sampleToChunk[l];k(u);let h=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),d=i.chunkOffsets[h],f=u.startSampleIndex+(h-u.startChunkIndex)*u.samplesPerChunk,m=0,p=d;if(i.sampleSizes.length===1)p+=c*(e-f),m+=c*u.samplesPerChunk;else for(let y=f;y<f+u.samplesPerChunk;y++){let x=i.sampleSizes[y];y<e&&(p+=x),m+=x}let g=r.delta;if(i.presentationTimestamps){let y=i.presentationTimestampIndexMap[e];k(y!==void 0),y<i.presentationTimestamps.length-1&&(g=i.presentationTimestamps[y+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:g,sampleOffset:p,sampleSize:c,chunkOffset:d,chunkSize:m,isKeyFrame:i.keySampleIndices?ae(i.keySampleIndices,e,y=>y)!==-1:!0}},V_=(i,e)=>{if(!i.keySampleIndices)return e;let t=Q(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t]??-1},W_=(i,e)=>{if(!i.keySampleIndices)return e+1;let t=Q(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t+1]??-1},Jf=(i,e)=>{i.startTimestamp+=e,i.endTimestamp+=e;for(let t of i.samples)t.presentationTimestamp+=e;for(let t of i.presentationTimestamps)t.presentationTimestamp+=e},H_=i=>{let[e,,,t]=i,r=Math.hypot(e,t),s=e/r,n=t/r,o=-Math.atan2(n,s)*(180/Math.PI);return Number.isFinite(o)?o:0},em=i=>i.sampleSizes.length===0;var Ht;(function(i){i[i.None=0]="None",i[i.Xiph=1]="Xiph",i[i.FixedSize=2]="FixedSize",i[i.Ebml=3]="Ebml"})(Ht||(Ht={}));var Fl=[{id:I.SeekHead,flag:"seekHeadSeen"},{id:I.Info,flag:"infoSeen"},{id:I.Tracks,flag:"tracksSeen"},{id:I.Cues,flag:"cuesSeen"}],tm=10*2**20,Uo=class extends We{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentCueTime=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(r=>r.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(r=>r.getCodecParameterString()));return Rf({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(s=>s.info?.type==="video")),hasAudio:this.segments.some(r=>r.tracks.some(s=>s.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,Ve,ct);if(t instanceof Promise&&(t=await t),!t)break;let r=lt(t);if(!r)break;let s=r.id,n=r.size,o=t.filePos;if(s===I.EBML){Vt(n);let a=this.reader.requestSlice(o,n);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(s===I.Segment){if(await this.readSegment(o,n),n===null||this.reader.fileSize===null)break}else if(s===I.Cluster){if(this.reader.fileSize===null)break;n===null&&(n=(await Eo(this.reader,o,vo,this.reader.fileSize)).pos-o);let a=ve(this.segments);a&&(a.elementEndPos=o+n)}Vt(n),e=o+n}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===null?null:e+t,clusterSeekStartPos:e,clusters:[],clusterLookupMutex:new Je,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;this.currentSegment.elementEndPos===null||r<this.currentSegment.elementEndPos;){let c=this.reader.requestSliceRange(r,Ve,ct);if(c instanceof Promise&&(c=await c),!c)break;let l=r,u=lt(c);if(!u||!di.includes(u.id)&&u.id!==I.Void){let p=await Tl(this.reader,l,di,Math.min(this.currentSegment.elementEndPos??1/0,l+tm));if(p){r=p;continue}else break}let{id:h,size:d}=u,f=c.filePos,m=Fl.findIndex(p=>p.id===h);if(m!==-1){let p=Fl[m].flag;this.currentSegment[p]=!0,Vt(d);let g=this.reader.requestSlice(f,d);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(h===I.Tags||h===I.Attachments){h===I.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Vt(d);let p=this.reader.requestSlice(f,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(h===I.Cluster){this.currentSegment.clusterSeekStartPos=l;break}if(d===null)break;r=f+d}if(this.currentSegment.seekEntries.sort((c,l)=>c.segmentPosition-l.segmentPosition),this.reader.fileSize!==null)for(let c of this.currentSegment.seekEntries){let l=Fl.find(p=>p.id===c.id);if(!l||this.currentSegment[l.flag])continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,Ve,ct);if(u instanceof Promise&&(u=await u),!u)continue;let h=lt(u);if(!h)continue;let{id:d,size:f}=h;if(d!==l.id)continue;Vt(f),this.currentSegment[l.flag]=!0;let m=this.reader.requestSlice(u.filePos,f);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((c,l)=>Number(l.isDefault)-Number(c.isDefault)),this.currentSegment.cuePoints.sort((c,l)=>c.clusterPosition-l.clusterPosition);let s=this.currentSegment.tracks.map(c=>c.id),n=new Set,o=null,a=null;for(let c of this.currentSegment.cuePoints){if(c.clusterPosition!==o){for(let u of n)k(a),this.currentSegment.tracks.find(d=>d.id===u).cuePoints.push(a);for(let u of s)n.add(u)}if(a=c,!n.has(c.trackId))continue;this.currentSegment.tracks.find(u=>u.id===c.trackId).cuePoints.push(c),n.delete(c.trackId),o=c.clusterPosition}for(let c of n)k(a),this.currentSegment.tracks.find(u=>u.id===c).cuePoints.push(a);for(let c of this.currentSegment.tracks)c.cuePoints.sort((l,u)=>l.time-u.time);this.currentSegment=null}async readCluster(e,t){let r=this.reader.requestSliceRange(e,Ve,ct);r instanceof Promise&&(r=await r),k(r);let s=e,n=lt(r);k(n);let o=n.id,a=n.size,c=r.filePos;a===null&&(a=(await Eo(this.reader,c,vo,t.elementEndPos)).pos-c),k(o===I.Cluster);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let u={elementStartPos:s,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map,nextCluster:null,isKnownToBeFirstCluster:!1};this.currentCluster=u,l&&this.readContiguousElements(l);for(let[h,d]of u.trackData){let f=t.tracks.find(x=>x.id===h)??null;k(d.blocks.length>0);let m=!1,p=!1;for(let x=0;x<d.blocks.length;x++){let w=d.blocks[x];w.timestamp+=u.timestamp,m||=w.referencedTimestamps.length>0,p||=w.lacing!==Ht.None}m&&(d.blocks=j_(d.blocks)),d.presentationTimestamps=d.blocks.map((x,w)=>({timestamp:x.timestamp,blockIndex:w})).sort((x,w)=>x.timestamp-w.timestamp);for(let x=0;x<d.presentationTimestamps.length;x++){let w=d.presentationTimestamps[x],_=d.blocks[w.blockIndex];if(d.firstKeyFrameTimestamp===null&&_.isKeyFrame&&(d.firstKeyFrameTimestamp=_.timestamp),x<d.presentationTimestamps.length-1){let S=d.presentationTimestamps[x+1];_.duration=S.timestamp-_.timestamp}else _.duration===0&&f?.defaultDuration!=null&&_.lacing===Ht.None&&(_.duration=f.defaultDuration)}p&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((x,w)=>({timestamp:x.timestamp,blockIndex:w})).sort((x,w)=>x.timestamp-w.timestamp));let g=d.blocks[d.presentationTimestamps[0].blockIndex],y=d.blocks[ve(d.presentationTimestamps).blockIndex];d.startTimestamp=g.timestamp,d.endTimestamp=y.timestamp+y.duration,f&&(ot(f.clusters,u,w=>w.elementStartPos),d.firstKeyFrameTimestamp!==null&&ot(f.clustersWithKeyFrame,u,w=>w.elementStartPos))}return ot(t.clusters,u,h=>h.elementStartPos),this.currentCluster=null,u}getTrackDataInCluster(e,t){let r=e.trackData.get(t);return r||(r={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)),r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){let s=e[r];if(s.lacing===Ht.None)continue;let n=li.tempFromBytes(s.data),o=[],a=z(n)+1;switch(s.lacing){case Ht.Xiph:{let c=0;for(let l=0;l<a-1;l++){let u=0;for(;n.bufferPos<n.length;){let h=z(n);if(u+=h,h<255){o.push(u),c+=u;break}}}o.push(n.length-(n.bufferPos+c))}break;case Ht.FixedSize:{let c=n.length-1,l=Math.floor(c/a);for(let u=0;u<a;u++)o.push(l)}break;case Ht.Ebml:{let c=fi(n);k(c!==null);let l=c;o.push(l);let u=l;for(let h=1;h<a-1;h++){let d=n.bufferPos,f=fi(n);k(f!==null);let m=f,g=(1<<(n.bufferPos-d)*7-1)-1,y=m-g;l+=y,o.push(l),u+=l}o.push(n.length-(n.bufferPos+u))}break;default:k(!1)}k(o.length===a),e.splice(r,1);for(let c=0;c<a;c++){let l=o[c],u=W(n,l),h=s.duration||a*(t?.defaultDuration??0),d=s.timestamp+h*c/a,f=h/a;e.splice(r+c,0,{timestamp:d,duration:f,isKeyFrame:s.isKeyFrame,referencedTimestamps:s.referencedTimestamps,data:u,lacing:Ht.None})}r+=a,r--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===I.Tags&&!e.tagsSeen)){if(!(t.id===I.Attachments&&!e.attachmentsSeen))continue}let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Ve,ct);if(r instanceof Promise&&(r=await r),!r)continue;let s=lt(r);if(!s||s.id!==t.id)continue;let{size:n}=s;Vt(n),k(!this.currentSegment),this.currentSegment=e;let o=this.reader.requestSlice(r.filePos,n);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o),this.currentSegment=null,t.id===I.Tags?e.tagsSeen=!0:t.id===I.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e){let t=e.filePos;for(;e.filePos-t<=e.length-Ve&&this.traverseElement(e););}traverseElement(e){let t=lt(e);if(!t)return!1;let{id:r,size:s}=t,n=e.filePos;switch(Vt(s),r){case I.DocType:this.isWebM=ar(e,s)==="webm";break;case I.Seek:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(n,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case I.SeekID:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=J(e,s)}break;case I.SeekPosition:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=J(e,s)}break;case I.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=J(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case I.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Co(e,s)}break;case I.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusters:[],clustersWithKeyFrame:[],cuePoints:[],isDefault:!1,inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Pe,info:null},this.readContiguousElements(e.slice(n,s)),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let o=this.currentTrack.codecId.indexOf("/"),a=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===ut.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ut.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):a===ut.vp8?this.currentTrack.info.codec="vp8":a===ut.vp9?this.currentTrack.info.codec="vp9":a===ut.av1&&(this.currentTrack.info.codec="av1");let c=this.currentTrack,l=new wt(new Dl(c));this.currentTrack.inputTrack=l,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){a===ut.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===ut.mp3?this.currentTrack.info.codec="mp3":a===ut.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):a===ut.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):a===ut.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 c=this.currentTrack,l=new Ae(new Rl(c));this.currentTrack.inputTrack=l,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case I.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=J(e,s)}break;case I.TrackType:{if(!this.currentTrack)break;let o=J(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case I.FlagEnabled:{if(!this.currentTrack)break;J(e,s)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case I.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.isDefault=!!J(e,s)}break;case I.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=ar(e,s)}break;case I.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=W(e,s)}break;case I.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*J(e,s)/1e9}break;case I.Name:{if(!this.currentTrack)break;this.currentTrack.name=mi(e,s)}break;case I.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==Pe)break;this.currentTrack.languageCode=ar(e,s),uo(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Pe)}break;case I.LanguageBCP47:{if(!this.currentTrack)break;let a=ar(e,s).split("-")[0];a?this.currentTrack.languageCode=a:this.currentTrack.languageCode=Pe}break;case I.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(n,s))}break;case I.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=J(e,s)}break;case I.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=J(e,s)}break;case I.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(n,s))}break;case I.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=J(e,s),a=ao[o]??null;this.currentTrack.info.colorSpace.matrix=a}break;case I.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=J(e,s)===2}break;case I.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=J(e,s),a=oo[o]??null;this.currentTrack.info.colorSpace.transfer=a}break;case I.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=J(e,s),a=no[o]??null;this.currentTrack.info.colorSpace.primaries=a}break;case I.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(n,s))}break;case I.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let a=-Co(e,s);try{this.currentTrack.info.rotation=so(a)}catch{}}break;case I.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(n,s))}break;case I.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Co(e,s)}break;case I.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=J(e,s)}break;case I.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=J(e,s)}break;case I.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(n,s)),this.currentCueTime=null}break;case I.CueTime:this.currentCueTime=J(e,s);break;case I.CueTrackPositions:{if(this.currentCueTime===null)break;k(this.currentSegment);let o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(n,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case I.CueTrack:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=J(e,s)}break;case I.CueClusterPosition:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;k(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+J(e,s)}break;case I.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=J(e,s)}break;case I.SimpleBlock:{if(!this.currentCluster)break;let o=fi(e);if(o===null)break;let a=_s(e),c=z(e),l=!!(c&128),u=c>>1&3;this.getTrackDataInCluster(this.currentCluster,o).blocks.push({timestamp:a,duration:0,isKeyFrame:l,referencedTimestamps:[],data:W(e,s-(e.filePos-n)),lacing:u})}break;case I.BlockGroup:{if(!this.currentCluster)break;if(this.readContiguousElements(e.slice(n,s)),this.currentBlock){for(let o=0;o<this.currentBlock.referencedTimestamps.length;o++)this.currentBlock.referencedTimestamps[o]+=this.currentBlock.timestamp;this.currentBlock=null}}break;case I.Block:{if(!this.currentCluster)break;let o=fi(e);if(o===null)break;let a=_s(e),l=z(e)>>1&3,u=this.getTrackDataInCluster(this.currentCluster,o);this.currentBlock={timestamp:a,duration:0,isKeyFrame:!0,referencedTimestamps:[],data:W(e,s-(e.filePos-n)),lacing:l},u.blocks.push(this.currentBlock)}break;case I.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=J(e,s)}break;case I.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;let o=Df(e,s);this.currentBlock.referencedTimestamps.push(o)}break;case I.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(n,s));break;case I.Targets:this.readContiguousElements(e.slice(n,s));break;case I.TargetTypeValue:J(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case I.TagTrackUID:case I.TagEditionUID:case I.TagChapterUID:case I.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case I.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(n,s))}break;case I.TagName:this.currentSimpleTagName=mi(e,s);break;case I.TagString:{if(!this.currentSimpleTagName)break;let o=mi(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case I.TagBinary:{if(!this.currentSimpleTagName)break;let o=W(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case I.AttachedFile:{if(!this.currentSegment)break;if(this.currentAttachedFile={fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(n,s)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let o=this.currentAttachedFile.fileName,a="unknown";if(o){let c=o.toLowerCase();c.startsWith("cover.")?a="coverFront":c.startsWith("back.")&&(a="coverBack")}this.currentSegment.metadataTags.images??=[],this.currentSegment.metadataTags.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:a,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case I.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=mi(e,s)}break;case I.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ar(e,s)}break;case I.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=W(e,s)}break;case I.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=mi(e,s)}break}return e.filePos=n+s,!0}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{let s=new Date(t);Number.isNaN(s.getTime())||(r.date??=s)}break;case"track_number":case"part_number":{let s=t.split("/"),n=Number.parseInt(s[0],10),o=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(r.trackNumber??=n),o&&Number.isInteger(o)&&o>0&&(r.tracksTotal??=o)}break;case"disc_number":case"disc":{let s=t.split("/"),n=Number.parseInt(s[0],10),o=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(r.discNumber??=n),o&&Number.isInteger(o)&&o>0&&(r.discsTotal??=o)}break}}},zo=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}async getFirstPacket(e){return this.performClusterLookup(()=>{let t=this.internalTrack.segment.clusters[0]??null;if(t?.isKnownToBeFirstCluster){let r=t;for(;r;){if(r.trackData.get(this.internalTrack.id))return{clusterIndex:ae(this.internalTrack.clusters,r.elementStartPos,n=>n.elementStartPos),blockIndex:0,correctBlockFound:!0};r=r.nextCluster}}return{clusterIndex:-1,blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}intoTimescale(e){return Ir(e*this.internalTrack.segment.timestampFactor,14)}async getPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findBlockInClustersForTimestamp(r),r,r,t)}async getNextPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let s=r.cluster.trackData.get(this.internalTrack.id),n=ae(this.internalTrack.clusters,r.cluster.elementStartPos,o=>o.elementStartPos);return k(n!==-1),this.performClusterLookup(()=>{if(r.blockIndex+1<s.blocks.length)return{clusterIndex:n,blockIndex:r.blockIndex+1,correctBlockFound:!0};{let o=r.cluster;for(;o.nextCluster;)if(o=o.nextCluster,o.trackData.get(this.internalTrack.id)){let c=ae(this.internalTrack.clusters,o.elementStartPos,l=>l.elementStartPos);return k(c!==-1),{clusterIndex:c,blockIndex:0,correctBlockFound:!0}}return{clusterIndex:n,blockIndex:-1,correctBlockFound:!1}}},-1/0,1/0,t)}async getKeyPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findKeyBlockInClustersForTimestamp(r),r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let s=r.cluster.trackData.get(this.internalTrack.id),n=ae(this.internalTrack.clusters,r.cluster.elementStartPos,o=>o.elementStartPos);return k(n!==-1),this.performClusterLookup(()=>{let o=s.blocks.findIndex((a,c)=>a.isKeyFrame&&c>r.blockIndex);if(o!==-1)return{clusterIndex:n,blockIndex:o,correctBlockFound:!0};{let a=r.cluster;for(;a.nextCluster;){a=a.nextCluster;let c=a.trackData.get(this.internalTrack.id);if(c&&c.firstKeyFrameTimestamp!==null){let l=ae(this.internalTrack.clusters,a.elementStartPos,h=>h.elementStartPos);k(l!==-1);let u=c.blocks.findIndex(h=>h.isKeyFrame);return k(u!==-1),{clusterIndex:l,blockIndex:u,correctBlockFound:!0}}}return{clusterIndex:n,blockIndex:-1,correctBlockFound:!1}}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).blocks[t];k(n);let o=r.metadataOnly?Ee:n.data,a=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,l=new ce(o,n.isKeyFrame?"key":"delta",a,c,e.dataStartPos+t,n.data.byteLength);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}findBlockInClustersForTimestamp(e){let t=Q(this.internalTrack.clusters,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,s=!1;if(t!==-1){let o=this.internalTrack.clusters[t].trackData.get(this.internalTrack.id),a=Q(o.presentationTimestamps,e,c=>c.timestamp);k(a!==-1),r=o.presentationTimestamps[a].blockIndex,s=e<o.endTimestamp}return{clusterIndex:t,blockIndex:r,correctBlockFound:s}}findKeyBlockInClustersForTimestamp(e){let t=Q(this.internalTrack.clustersWithKeyFrame,e,o=>o.trackData.get(this.internalTrack.id).firstKeyFrameTimestamp),r=-1,s=-1,n=!1;if(t!==-1){let o=this.internalTrack.clustersWithKeyFrame[t];r=ae(this.internalTrack.clusters,o.elementStartPos,u=>u.elementStartPos),k(r!==-1);let a=o.trackData.get(this.internalTrack.id),c=co(a.presentationTimestamps,u=>a.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=e);k(c!==-1),s=a.presentationTimestamps[c].blockIndex,n=e<a.endTimestamp}return{clusterIndex:r,blockIndex:s,correctBlockFound:n}}async performClusterLookup(e,t,r,s){let{demuxer:n,segment:o}=this.internalTrack,a=await o.clusterLookupMutex.acquire();try{let{clusterIndex:c,blockIndex:l,correctBlockFound:u}=e();if(u){let w=this.internalTrack.clusters[c];return this.fetchPacketInCluster(w,l,s)}let h=null,d=c,f=l,m=Q(this.internalTrack.cuePoints,t,w=>w.time),p=m!==-1?this.internalTrack.cuePoints[m]:null,g,y=!1;if(c===-1)g=p?.clusterPosition??o.clusterSeekStartPos,y=g===o.clusterSeekStartPos;else{let w=this.internalTrack.clusters[c];!p||w.elementStartPos>=p.clusterPosition?(g=w.elementEndPos,h=w):g=p.clusterPosition}for(;o.elementEndPos===null||g<=o.elementEndPos-Ve;){if(h){let P=h.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>r)break;if(h.nextCluster){g=h.nextCluster.elementEndPos,h=h.nextCluster;continue}}let w=n.reader.requestSliceRange(g,Ve,ct);if(w instanceof Promise&&(w=await w),!w)break;let _=g,S=lt(w);if(!S||!di.includes(S.id)&&S.id!==I.Void){let P=await Tl(n.reader,_,di,Math.min(o.elementEndPos??1/0,_+tm));if(P){g=P;continue}else break}let T=S.id,v=S.size,M=w.filePos;if(T===I.Cluster){let P=ae(o.clusters,_,he=>he.elementStartPos),C;P===-1?C=await n.readCluster(_,o):C=o.clusters[P],h&&(h.nextCluster=C),h=C,y&&(C.isKnownToBeFirstCluster=!0,y=!1);let{clusterIndex:E,blockIndex:D,correctBlockFound:j}=e();if(j){let he=this.internalTrack.clusters[E];return this.fetchPacketInCluster(he,D,s)}E!==-1&&(d=E,f=D)}if(v===null){T===I.Cluster?(k(h),v=h.elementEndPos-M):v=(await Eo(n.reader,M,vo,o.elementEndPos)).pos-M;let P=M+v;if(o.elementEndPos!==null&&P>o.elementEndPos-Ve)break;{let C=n.reader.requestSliceRange(P,Ve,ct);if(C instanceof Promise&&(C=await C),!C)break;if(Po(C)===I.Segment){o.elementEndPos=P;break}}}g=M+v}let x=d!==-1?this.internalTrack.clusters[d]:null;if(p&&(!x||x.elementStartPos<p.clusterPosition)){let _=this.internalTrack.cuePoints[m-1]?.time??-1/0;return this.performClusterLookup(e,_,r,s)}return x?this.fetchPacketInCluster(x,f,s):null}finally{a()}}},Dl=class extends zo{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 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:po({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,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Sf(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Tf(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?bo(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?wo(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}},Rl=class extends zo{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:go({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}},j_=i=>{let e=new Map;for(let n=0;n<i.length;n++){let o=i[n];e.set(o.timestamp,o)}let t=new Set,r=[],s=n=>{if(!t.has(n)){t.add(n);for(let o=0;o<n.referencedTimestamps.length;o++){let a=n.referencedTimestamps[o],c=e.get(a);c&&s(c)}r.push(n)}};for(let n=0;n<i.length;n++)s(i[n]);return r};var Go=class extends We{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Je,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 Ae(new Ol(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,bi);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=ks(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await Ts(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let r=zf(t.mpegVersionId,t.channel),s=this.reader.requestSlice(e.startPos+r,4);if(s instanceof Promise&&(s=await s),s){let a=B(s);if(a===Of||a===Uf)return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=t.audioSamplesInFrame/t.sampleRate,o={timestamp:this.nextTimestampInSamples/t.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(o),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 k(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,r=!1;for(;;){let s=this.reader.requestSlice(t,bi);if(s instanceof Promise&&(s=await s),!s)break;let n=ks(s);if(!n)break;r=!0;let o=this.reader.requestSlice(s.filePos,n.size);if(o instanceof Promise&&(o=await o),!o)break;Vf(o,n,this.metadataTags),t=s.filePos+n.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=Ss){let s=this.reader.requestSlice(this.reader.fileSize-Ss,Ss);s instanceof Promise&&(s=await s),k(s),de(s,3)==="TAG"&&Lf(s,this.metadataTags)}return this.metadataTags}finally{e()}}},Ol=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return k(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 Pe}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return k(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return k(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}async getDecoderConfig(){return k(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=Ee;else{let n=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=W(n,r.dataSize)}return new ce(s,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let s=ae(this.demuxer.loadedSamples,e.timestamp,o=>o.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");let n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let s=Q(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var No=class extends We{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,cr,Rr);if(t instanceof Promise&&(t=await t),!t)break;let r=wi(t);if(!r||!!!(r.headerType&2))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(let t of this.bitstreams){let r=await this.readPacket(t.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,t):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,t),t.codecInfo.codec!==null&&this.tracks.push(new Ae(new Ul(t,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s||(r=await this.findNextPacketStart(s),!r))return;let n=await this.readPacket(r.startPage,r.startSegmentIndex);if(!n||s.data[0]!==3||n.data[0]!==5)return;let o=[],a=h=>{for(;o.push(Math.min(255,h)),!(h<255);)h-=255};a(e.data.length),a(s.data.length);let c=new Uint8Array(1+o.length+e.data.length+s.data.length+n.data.length);c[0]=o.length,c.set(o,1),c.set(e.data,1+o.length),c.set(s.data,1+o.length+e.data.length),c.set(n.data,1+o.length+e.data.length+s.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=n;let l=oe(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Cf(n.data).modeBlockflags},this.readVorbisComments(s.data.subarray(7))}async readOpusMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=s;let n=vf(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=n.inputSampleRate,t.codecInfo.opusInfo={preSkip:n.preSkip},this.readVorbisComments(s.data.subarray(8))}readVorbisComments(e){let t=oe(e),r=0,s=t.getUint32(r,!0);r+=4;let n=Be.decode(e.subarray(r,r+s));r+=s,s>0&&(this.metadataTags.raw??={},this.metadataTags.raw.vendor??=n);let o=t.getUint32(r,!0);r+=4;for(let a=0;a<o;a++){let c=t.getUint32(r,!0);r+=4;let l=Be.decode(e.subarray(r,r+c));r+=c;let u=l.indexOf("=");if(u===-1)continue;let h=l.slice(0,u).toUpperCase(),d=l.slice(u+1);switch(this.metadataTags.raw??={},this.metadataTags.raw[h]??=d,h){case"TITLE":this.metadataTags.title??=d;break;case"DESCRIPTION":this.metadataTags.description??=d;break;case"ARTIST":this.metadataTags.artist??=d;break;case"ALBUM":this.metadataTags.album??=d;break;case"ALBUMARTIST":this.metadataTags.albumArtist??=d;break;case"COMMENT":this.metadataTags.comment??=d;break;case"LYRICS":this.metadataTags.lyrics??=d;break;case"TRACKNUMBER":{let f=d.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"TRACKTOTAL":{let f=Number.parseInt(d,10);Number.isInteger(f)&&f>0&&(this.metadataTags.tracksTotal??=f)}break;case"DISCNUMBER":{let f=d.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.discNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.discsTotal??=p)}break;case"DISCTOTAL":{let f=Number.parseInt(d,10);Number.isInteger(f)&&f>0&&(this.metadataTags.discsTotal??=f)}break;case"DATE":{let f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"GENRE":this.metadataTags.genre??=d;break;case"METADATA_BLOCK_PICTURE":{let f=pf(d),m=oe(f),p=m.getUint32(0,!1),g=m.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+g)),x=m.getUint32(8+g,!1),w=Be.decode(f.subarray(12+g,12+g+x)),_=m.getUint32(g+x+28),S=f.subarray(g+x+32,g+x+32+_);this.metadataTags.images??=[],this.metadataTags.images.push({data:S,mimeType:y,kind:p===3?"coverFront":p===4?"coverBack":"unknown",name:void 0,description:w||void 0})}break}}}async readPacket(e,t){k(t<e.lacingValues.length);let r=0;for(let h=0;h<t;h++)r+=e.lacingValues[h];let s=e,n=r,o=t,a=[];e:for(;;){let h=this.reader.requestSlice(s.dataStartPos,s.dataSize);h instanceof Promise&&(h=await h),k(h);let d=W(h,s.dataSize);for(;;){if(o===s.lacingValues.length){a.push(d.subarray(r,n));break}let m=s.lacingValues[o];if(n+=m,m<255){a.push(d.subarray(r,n));break e}o++}let f=s.headerStartPos+s.totalSize;for(;;){let m=this.reader.requestSliceRange(f,cr,Rr);if(m instanceof Promise&&(m=await m),!m)return null;let p=wi(m);if(!p)return null;if(s=p,s.serialNumber===e.serialNumber)break;f=s.headerStartPos+s.totalSize}r=0,n=0,o=0}let c=a.reduce((h,d)=>h+d.length,0),l=new Uint8Array(c),u=0;for(let h=0;h<a.length;h++){let d=a[h];l.set(d,u),u+=d.length}return{data:l,endPage:s,endSegmentIndex:o}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let r=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let s=this.reader.requestSliceRange(r,cr,Rr);if(s instanceof Promise&&(s=await s),!s)return null;let n=wi(s);if(!n)return null;if(n.serialNumber===e.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};r=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.getCodecParameterString()));return $f({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(r=>r.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Ul=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Je,this.internalSampleRate=e.codecInfo.codec==="opus"?yf: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 k(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 Pe}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"?(k(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;let{durationInSamples:s,vorbisBlockSize:n}=jf(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),o=new ce(r.metadataOnly?Ee:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,s/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(o,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),o}async getFirstPacket(e){k(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(k(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);let s=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");let s=await this.demuxer.findNextPacketStart(r.packet);if(!s)return null;let n=r.timestampInSamples+r.durationInSamples,o=await this.demuxer.readPacket(s.startPage,s.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:n,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let r=Ir(e*this.internalSampleRate,14);if(r===0)return this.getFirstPacket(t);if(r<0)return null;k(this.bitstream.lastMetadataPacket);let s=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let n=s.startPage,o=this.demuxer.reader.fileSize,a=[n];e:for(;n.headerStartPos+n.totalSize<o;){let x=n.headerStartPos,w=Math.floor((x+o)/2),_=w;for(;;){let S=Math.min(_+qf,o-cr),T=this.demuxer.reader.requestSlice(_,S-_);if(T instanceof Promise&&(T=await T),k(T),!Xf(T,S)){o=w+cr;continue e}let M=this.demuxer.reader.requestSliceRange(T.filePos,cr,Rr);M instanceof Promise&&(M=await M),k(M);let P=wi(M);k(P);let C=!1;if(P.serialNumber===this.bitstream.serialNumber)C=!0;else{let D=this.demuxer.reader.requestSlice(P.headerStartPos,P.totalSize);D instanceof Promise&&(D=await D),k(D);let j=W(D,P.totalSize);C=Hf(j)===P.checksum}if(!C){_=P.headerStartPos+4;continue}if(C&&P.serialNumber!==this.bitstream.serialNumber){_=P.headerStartPos+P.totalSize;continue}if(P.granulePosition===-1){_=P.headerStartPos+P.totalSize;continue}this.granulePositionToTimestampInSamples(P.granulePosition)>r?o=P.headerStartPos:(n=P,a.push(P));continue e}}let c=s.startPage;for(let x of a){if(x.granulePosition===n.granulePosition)break;(!c||x.headerStartPos>c.headerStartPos)&&(c=x)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===n.granulePosition);){let x=l.headerStartPos+l.totalSize,w=this.demuxer.reader.requestSliceRange(x,cr,Rr);w instanceof Promise&&(w=await w),k(w);let _=wi(w);k(_),l=_,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}k(l.granulePosition!==-1);let h=null,d,f,m=l,p=0;if(l.headerStartPos===s.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),f=!0,h=0;else{d=0,f=!1;for(let _=l.lacingValues.length-1;_>=0;_--)if(l.lacingValues[_]<255){h=_+1;break}if(h===null)throw new Error("Invalid page with granule position: no packets end on this page.");p=h-1;let x={data:Ee,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(x)){let _=im(u,l,h);k(_);let S=rm(u,_.page,_.segmentIndex);S&&(l=S.page,h=S.segmentIndex)}else for(;;){let _=im(u,l,h);if(!_)break;let S=rm(u,_.page,_.segmentIndex);if(!S)break;if(l=S.page,h=S.segmentIndex,_.page.headerStartPos!==m.headerStartPos){m=_.page,p=_.segmentIndex;break}}}let g=null,y=null;for(;l!==null;){k(h!==null);let x=await this.demuxer.readPacket(l,h);if(!x)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&h<s.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:d,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);k(S);let T=this.encodedPacketToMetadata.get(S);if(k(T),!f&&x.endPage.headerStartPos===m.headerStartPos&&x.endSegmentIndex===p?(d=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:d-T.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),k(S),T=this.encodedPacketToMetadata.get(S),k(T)):d+=T.durationInSamples,g=S,y=T,f&&(Math.max(d,0)>r||Math.max(T.timestampInSamples,0)===r))break}let _=await this.demuxer.findNextPacketStart(x);if(!_)break;l=_.startPage,h=_.startSegmentIndex}return g}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let s=Ir(e*this.internalSampleRate,14);e=s/this.internalSampleRate;let n=Q(this.sequentialScanCache,s,c=>c.timestampInSamples),o;if(n!==-1){let c=this.sequentialScanCache[n];o=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else o=await this.getFirstPacket(t);let a=0;for(;o&&o.timestamp<e;){let c=await this.getNextPacket(o,t);if(!c||c.timestamp>e)break;if(o=c,a++,a===100){a=0;let l=this.encodedPacketToMetadata.get(o);k(l),this.sequentialScanCache.length>0&&k(ve(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return o}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},rm=(i,e,t)=>{let r=e,s=t;e:for(;;){for(s--,s;s>=0;s--)if(r.lacingValues[s]<255){s++;break e}if(k(s===-1),!(r.headerType&1)){s=0;break}let o=dl(i,a=>a.headerStartPos<r.headerStartPos);if(!o)return null;r=o,s=r.lacingValues.length}if(k(s!==-1),s===r.lacingValues.length){let n=i[i.indexOf(r)+1];k(n),r=n,s=0}return{page:r,segmentIndex:s}},im=(i,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let r=dl(i,s=>s.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var vi=7,Pi=9,Is=i=>{let e=i.filePos,t=W(i,9),r=new fe(t);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;let o=r.readBits(1),a=r.readBits(2)+1,c=r.readBits(4);if(c===15)return null;r.skipBits(1);let l=r.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let u=r.readBits(13);r.skipBits(11);let h=r.readBits(2)+1;if(h!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let d=null;return o===1?i.filePos-=2:d=r.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:h,crcCheck:d,startPos:e}};var zl=1024,Lo=class extends We{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new Je,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();k(this.firstFrameHeader),this.tracks=[new Ae(new Gl(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,vi,Pi);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Is(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let r=bs[t.samplingFrequencyIndex];k(r!==void 0);let s=zl/r,n=t.crcCheck?Pi:vi,o={timestamp:this.nextTimestampInSamples/r,duration:s,dataStart:t.startPos+n,dataSize:t.frameLength-n};this.loadedSamples.push(o),this.nextTimestampInSamples+=zl,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 k(e),e.computeDuration()}async getMetadataTags(){return{}}},Gl=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/zl}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Pe}getCodec(){return"aac"}getInternalCodecId(){return k(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){k(this.demuxer.firstFrameHeader);let e=pl[this.demuxer.firstFrameHeader.channelConfiguration];return k(e!==void 0),e}getSampleRate(){k(this.demuxer.firstFrameHeader);let e=bs[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return k(e!==void 0),e}async getDecoderConfig(){k(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new fe(e),{objectType:r,samplingFrequencyIndex:s,channelConfiguration:n}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),t.writeBits(4,s),t.writeBits(4,n),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(e===-1)return null;let r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=Ee;else{let n=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=W(n,r.dataSize)}return new ce(s,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let s=ae(this.demuxer.loadedSamples,e.timestamp,o=>o.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");let n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let s=Q(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ht=class{},Ms=class extends ht{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),de(t,4)!=="ftyp")?null:de(t,4)}_createDemuxer(e){return new Ro(e)}},Vo=class extends Ms{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Wo=class extends Ms{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Bs=class extends ht{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,ct);if(r instanceof Promise&&(r=await r),!r)return!1;let s=_l(r);if(s===null||s<1||s>8||J(r,s)!==I.EBML)return!1;let o=Sl(r);if(o===null)return!1;let a=e._reader.requestSlice(r.filePos,o);if(a instanceof Promise&&(a=await a),!a)return!1;let c=r.filePos;for(;a.filePos<=c+o-Ve;){let l=lt(a);if(!l)break;let{id:u,size:h}=l,d=a.filePos;if(h===null)return!1;switch(u){case I.EBMLVersion:if(J(a,h)!==1)return!1;break;case I.EBMLReadVersion:if(J(a,h)!==1)return!1;break;case I.DocType:if(ar(a,h)!==t)return!1;break;case I.DocTypeVersion:if(J(a,h)>4)return!1;break}a.filePos=d+h}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Uo(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Ho=class extends Bs{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},jo=class extends ht{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,s=!1;for(;;){let l=e._reader.requestSlice(r,bi);if(l instanceof Promise&&(l=await l),!l)break;let u=ks(l);if(!u)break;s=!0,r=l.filePos+u.size}let n=await Ts(e._reader,r,r+4096);if(!n)return!1;if(s)return!0;r=n.startPos+=n.header.totalSize;let o=await Ts(e._reader,r,r+4);if(!o)return!1;let a=n.header,c=o.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new Go(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},$o=class extends ht{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let r=de(t,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(t.skip(4),de(t,4)==="WAVE")}_createDemuxer(e){return new Fo(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},qo=class extends ht{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?de(t,4)==="OggS":!1}_createDemuxer(e){return new No(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Xo=class extends ht{async _canReadInput(e){let t=e._reader.requestSliceRange(0,vi,Pi);if(t instanceof Promise&&(t=await t),!t)return!1;let r=Is(t);if(!r||(t=e._reader.requestSliceRange(r.frameLength,vi,Pi),t instanceof Promise&&(t=await t),!t))return!1;let s=Is(t);return s?r.objectType===s.objectType&&r.samplingFrequencyIndex===s.samplingFrequencyIndex&&r.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new Lo(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},sm=new Vo,nm=new Wo,om=new Bs,am=new Ho,cm=new jo,lm=new $o,um=new qo,hm=new Xo,lr=[sm,nm,om,am,lm,um,cm,hm];var _t=class{constructor(e){if(this._demuxerPromise=null,this._format=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof ht)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ur))throw new TypeError("options.source must be a Source.");this._formats=e.formats,this._source=e.source,this._reader=new _o(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(),k(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()}};var Yo=class{count=0;#e=new Map;register(e,t){this.#e.set(e,t)}unregister(e){this.#e.delete(e)}dispatch(e,t){this.#e.get(e)?.(t)}};var dm=i=>ro.host(e=>({async world(){i.count++}}));async function zr(i){return i instanceof Blob?new Es(i):new As(i)}var Ko=class{machina;thread;static async setup(e){let t=new Yo,r=await ro.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.bundle.min.js",setupHost:dm(t)});return new this(t,r)}constructor(e,t){this.machina=e,this.thread=t}async hello(){return this.thread.work.hello()}async getAudioDuration(e){return await(await new _t({source:await zr(e),formats:lr}).getPrimaryAudioTrack())?.computeDuration()}async getVideoDuration(e){return await(await new _t({source:await zr(e),formats:lr}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,r=new TransformStream({async transform(s,n){let o=await e.onFrame?.(s)??s;t?.close(),n.enqueue(o),t=o}});return this.thread.work.decodeVideo[Pr]({transfer:[r.writable]})({source:e.source,video:r.writable,start:e.start,end:e.end}),r.readable}decodeAudio(e){let t=new TransformStream;return this.thread.work.decodeAudio[Pr]({transfer:[t.writable]})({source:e.source,audio:t.writable,start:e.start,end:e.end}),t.readable}async encode({video:e,audio:t,config:r}){let n=await(await window.showSaveFilePicker()).createWritable(),o=new WritableStream({async write(a){await n.write(a)},async close(){await n.close()}});return await this.thread.work.encode[Pr]({transfer:[t??[],e??[],o]})({video:e,audio:t,config:r,bridge:o})}async composite(e){let t=this.#e(e);return await this.thread.work.composite[Pr]({transfer:t})(e)}#e(e){let t=[],r=s=>{if(Array.isArray(s))for(let n of s)r(n);else s&&typeof s=="object"&&"kind"in s&&s.kind==="image"&&s.frame instanceof VideoFrame&&t.push(s.frame)};return r(e),t}};function Se(i,e,t,r){return new(t||(t=Promise))(function(s,n){function o(l){try{c(r.next(l))}catch(u){n(u)}}function a(l){try{c(r.throw(l))}catch(u){n(u)}}function c(l){var u;l.done?s(l.value):(u=l.value,u instanceof t?u:new t(function(h){h(u)})).then(o,a)}c((r=r.apply(i,e||[])).next())})}var Gr=class{constructor(){this.listeners={}}on(e,t,r){if(this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),r?.once){let s=()=>{this.un(e,s),this.un(e,t)};return this.on(e,s),s}return()=>this.un(e,t)}un(e,t){var r;(r=this.listeners[e])===null||r===void 0||r.delete(t)}once(e,t){return this.on(e,t,{once:!0})}unAll(){this.listeners={}}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(r=>r(...t))}},Zo={decode:function(i,e){return Se(this,void 0,void 0,function*(){let t=new AudioContext({sampleRate:e});return t.decodeAudioData(i).finally(()=>t.close())})},createBuffer:function(i,e){return typeof i[0]=="number"&&(i=[i]),function(t){let r=t[0];if(r.some(s=>s>1||s<-1)){let s=r.length,n=0;for(let o=0;o<s;o++){let a=Math.abs(r[o]);a>n&&(n=a)}for(let o of t)for(let a=0;a<s;a++)o[a]/=n}}(i),{duration:e,length:i[0].length,sampleRate:i[0].length/e,numberOfChannels:i.length,getChannelData:t=>i?.[t],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};function mm(i,e){let t=e.xmlns?document.createElementNS(e.xmlns,i):document.createElement(i);for(let[r,s]of Object.entries(e))if(r==="children"&&s)for(let[n,o]of Object.entries(s))o instanceof Node?t.appendChild(o):typeof o=="string"?t.appendChild(document.createTextNode(o)):t.appendChild(mm(n,o));else r==="style"?Object.assign(t.style,s):r==="textContent"?t.textContent=s:t.setAttribute(r,s.toString());return t}function fm(i,e,t){let r=mm(i,e||{});return t?.appendChild(r),r}var $_=Object.freeze({__proto__:null,createElement:fm,default:fm}),q_={fetchBlob:function(i,e,t){return Se(this,void 0,void 0,function*(){let r=yield fetch(i,t);if(r.status>=400)throw new Error(`Failed to fetch ${i}: ${r.status} (${r.statusText})`);return function(s,n){Se(this,void 0,void 0,function*(){if(!s.body||!s.headers)return;let o=s.body.getReader(),a=Number(s.headers.get("Content-Length"))||0,c=0,l=h=>Se(this,void 0,void 0,function*(){c+=h?.length||0;let d=Math.round(c/a*100);n(d)}),u=()=>Se(this,void 0,void 0,function*(){let h;try{h=yield o.read()}catch{return}h.done||(l(h.value),yield u())});u()})}(r.clone(),e),r.blob()})}},Nl=class extends Gr{constructor(e){super(),this.isExternalMedia=!1,e.media?(this.media=e.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),e.mediaControls&&(this.media.controls=!0),e.autoplay&&(this.media.autoplay=!0),e.playbackRate!=null&&this.onMediaEvent("canplay",()=>{e.playbackRate!=null&&(this.media.playbackRate=e.playbackRate)},{once:!0})}onMediaEvent(e,t,r){return this.media.addEventListener(e,t,r),()=>this.media.removeEventListener(e,t,r)}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){let e=this.getSrc();e.startsWith("blob:")&&URL.revokeObjectURL(e)}canPlayType(e){return this.media.canPlayType(e)!==""}setSrc(e,t){let r=this.getSrc();if(e&&r===e)return;this.revokeSrc();let s=t instanceof Blob&&(this.canPlayType(t.type)||!e)?URL.createObjectURL(t):e;if(r&&this.media.removeAttribute("src"),s||e)try{this.media.src=s}catch{this.media.src=e}}destroy(){this.isExternalMedia||(this.media.pause(),this.media.remove(),this.revokeSrc(),this.media.removeAttribute("src"),this.media.load())}setMediaElement(e){this.media=e}play(){return Se(this,void 0,void 0,function*(){return this.media.play()})}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(e){this.media.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(e){this.media.volume=e}getMuted(){return this.media.muted}setMuted(e){this.media.muted=e}getPlaybackRate(){return this.media.playbackRate}isSeeking(){return this.media.seeking}setPlaybackRate(e,t){t!=null&&(this.media.preservesPitch=t),this.media.playbackRate=e}getMediaElement(){return this.media}setSinkId(e){return this.media.setSinkId(e)}},Ds=class i extends Gr{constructor(e,t){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.subscriptions=[],this.unsubscribeOnScroll=[],this.subscriptions=[],this.options=e;let r=this.parentFromOptionsContainer(e.container);this.parent=r;let[s,n]=this.initHtml();r.appendChild(s),this.container=s,this.scrollContainer=n.querySelector(".scroll"),this.wrapper=n.querySelector(".wrapper"),this.canvasWrapper=n.querySelector(".canvases"),this.progressWrapper=n.querySelector(".progress"),this.cursor=n.querySelector(".cursor"),t&&n.appendChild(t),this.initEvents()}parentFromOptionsContainer(e){let t;if(typeof e=="string"?t=document.querySelector(e):e instanceof HTMLElement&&(t=e),!t)throw new Error("Container not found");return t}initEvents(){let e=t=>{let r=this.wrapper.getBoundingClientRect(),s=t.clientX-r.left,n=t.clientY-r.top;return[s/r.width,n/r.height]};if(this.wrapper.addEventListener("click",t=>{let[r,s]=e(t);this.emit("click",r,s)}),this.wrapper.addEventListener("dblclick",t=>{let[r,s]=e(t);this.emit("dblclick",r,s)}),this.options.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.scrollContainer.addEventListener("scroll",()=>{let{scrollLeft:t,scrollWidth:r,clientWidth:s}=this.scrollContainer,n=t/r,o=(t+s)/r;this.emit("scroll",n,o,t,t+s)}),typeof ResizeObserver=="function"){let t=this.createDelay(100);this.resizeObserver=new ResizeObserver(()=>{t().then(()=>this.onContainerResize()).catch(()=>{})}),this.resizeObserver.observe(this.scrollContainer)}}onContainerResize(){let e=this.parent.clientWidth;e===this.lastContainerWidth&&this.options.height!=="auto"||(this.lastContainerWidth=e,this.reRender())}initDrag(){this.subscriptions.push(function(e,t,r,s,n=3,o=0,a=100){if(!e)return()=>{};let c=matchMedia("(pointer: coarse)").matches,l=()=>{},u=h=>{if(h.button!==o)return;h.preventDefault(),h.stopPropagation();let d=h.clientX,f=h.clientY,m=!1,p=Date.now(),g=S=>{if(S.preventDefault(),S.stopPropagation(),c&&Date.now()-p<a)return;let T=S.clientX,v=S.clientY,M=T-d,P=v-f;if(m||Math.abs(M)>n||Math.abs(P)>n){let C=e.getBoundingClientRect(),{left:E,top:D}=C;m||(r?.(d-E,f-D),m=!0),t(M,P,T-E,v-D),d=T,f=v}},y=S=>{if(m){let T=S.clientX,v=S.clientY,M=e.getBoundingClientRect(),{left:P,top:C}=M;s?.(T-P,v-C)}l()},x=S=>{S.relatedTarget&&S.relatedTarget!==document.documentElement||y(S)},w=S=>{m&&(S.stopPropagation(),S.preventDefault())},_=S=>{m&&S.preventDefault()};document.addEventListener("pointermove",g),document.addEventListener("pointerup",y),document.addEventListener("pointerout",x),document.addEventListener("pointercancel",x),document.addEventListener("touchmove",_,{passive:!1}),document.addEventListener("click",w,{capture:!0}),l=()=>{document.removeEventListener("pointermove",g),document.removeEventListener("pointerup",y),document.removeEventListener("pointerout",x),document.removeEventListener("pointercancel",x),document.removeEventListener("touchmove",_),setTimeout(()=>{document.removeEventListener("click",w,{capture:!0})},10)}};return e.addEventListener("pointerdown",u),()=>{l(),e.removeEventListener("pointerdown",u)}}(this.wrapper,(e,t,r)=>{this.emit("drag",Math.max(0,Math.min(1,r/this.wrapper.getBoundingClientRect().width)))},e=>{this.isDragging=!0,this.emit("dragstart",Math.max(0,Math.min(1,e/this.wrapper.getBoundingClientRect().width)))},e=>{this.isDragging=!1,this.emit("dragend",Math.max(0,Math.min(1,e/this.wrapper.getBoundingClientRect().width)))}))}getHeight(e,t){var r;let s=((r=this.audioData)===null||r===void 0?void 0:r.numberOfChannels)||1;if(e==null)return 128;if(!isNaN(Number(e)))return Number(e);if(e==="auto"){let n=this.parent.clientHeight||128;return t?.every(o=>!o.overlay)?n/s:n}return 128}initHtml(){let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=this.options.cspNonce&&typeof this.options.cspNonce=="string"?this.options.cspNonce.replace(/"/g,""):"";return t.innerHTML=`
|
|
575
|
+
`)});var Wn=()=>({stdout:async i=>console.log(i),stderr:async i=>console.error(i)});var Hd=()=>$c()?Ln():qc()?Vn():Wn();var jd=()=>({stdout:async()=>{},stderr:async()=>{}});function $d(){return()=>({stdout:i=>i,stderr:i=>i})}var si=class i{static writers={auto:Hd,void:jd,deno:Ln,node:Vn,console:Wn};static colors={auto:Xc,colorful:()=>hs,colorless:()=>us};static themes={auto:Nd,basic:Un};static shapers={auto:Wd,none:$d,errors:Gn,timestamp:Nn};writer=i.writers.auto();colors=i.colors.auto();theme=i.themes.auto();shaper=i.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=ds(...e),this}};var fs=class extends si{static dummy(){return new this().setWriter(si.writers.void())}rpcRequest=async({request:e,...t})=>{let r=this.colors.none;this.log(...this.#e(t),r(`${e.method}()`))};rpcError=async({request:e,error:t,...r})=>{this.error(...this.#e(r),`${e.method}()`,t)};#e({meta:e,label:t,remote:r}){let s=this.colors.mix(this.colors.blue,this.colors.dim),n=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,t||void 0,r===void 0?void 0:r?s("<-"):n("->")].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 xt=class extends fs{rpcRequest=async()=>{}};var yt=Object.freeze({eq(i,e){if(i.length!==e.length)return!1;for(let t=0;t<=i.length;t++)if(i.at(t)!==e.at(t))return!1;return!0},random(i){return crypto.getRandomValues(new Uint8Array(i))}});var Tr=Object.freeze({fromBytes(i){return[...i].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(i){if(i.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(i.length/2);for(let t=0;t<i.length;t+=2)e[t/2]=parseInt(i.slice(t,t+2),16);return e},random(i=32){return this.fromBytes(yt.random(i))},string(i){return Tr.fromBytes(i)},bytes(i){return Tr.toBytes(i)}});var Yc=58,Hn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Kc=Object.freeze({fromBytes(i){let e=BigInt("0x"+Tr.fromBytes(i)),t="";for(;e>0;){let r=e%BigInt(Yc);e=e/BigInt(Yc),t=Hn[Number(r)]+t}for(let r of i)if(r===0)t=Hn[0]+t;else break;return t},toBytes(i){let e=BigInt(0);for(let o of i){let a=Hn.indexOf(o);if(a===-1)throw new Error(`Invalid character '${o}' in base58 string`);e=e*BigInt(Yc)+BigInt(a)}let t=e.toString(16);t.length%2!==0&&(t="0"+t);let r=Tr.toBytes(t),s=0;for(let o of i)if(o===Hn[0])s++;else break;let n=new Uint8Array(s+r.length);return n.set(r,s),n},random(i=32){return this.fromBytes(yt.random(i))},string(i){return Kc.fromBytes(i)},bytes(i){return Kc.toBytes(i)}});var qd=class{lexicon;static lexicons=Object.freeze({base2:{characters:"01"},hex:{characters:"0123456789abcdef"},base36:{characters:"0123456789abcdefghijklmnopqrstuvwxyz"},base58:{characters:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"},base62:{characters:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},base64url:{negativePrefix:"~",characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"},base64:{characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",padding:{character:"=",size:4}}});lookup;negativePrefix;constructor(e){this.lexicon=e,this.lookup=Object.fromEntries([...e.characters].map((t,r)=>[t,r])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let a=0,c=0,l=[];for(let u of e){if(u===this.lexicon.padding?.character)continue;let h=this.lookup[u];if(h===void 0)throw new Error(`Invalid character: ${u}`);for(a=a<<t|h,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let r=0n,s=BigInt(this.lexicon.characters.length),n=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);r=r*s+BigInt(c)}let o=[];for(;r>0n;)o.unshift(Number(r%256n)),r=r/256n;return new Uint8Array(o)}fromBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let o=0,a=0,c="";for(let l of e)for(o=o<<8|l,a+=8;a>=t;){a-=t;let u=o>>a&(1<<t)-1;c+=this.lexicon.characters[u]}if(a>0){let l=o<<t-a&(1<<t)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let r=0n;for(let o of e)r=(r<<8n)+BigInt(o);if(r===0n)return this.lexicon.characters[0];let s=BigInt(this.lexicon.characters.length),n="";for(;r>0n;)n=this.lexicon.characters[Number(r%s)]+n,r=r/s;return n}toInteger(e){if(!e)return 0;let t=0n,r=!1,s=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),r=!0);for(let n of e){let o=this.lookup[n];if(o===void 0)throw new Error(`Invalid character: ${n}`);t=t*s+BigInt(o)}return Number(r?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,r=BigInt(t?-e:e);if(r===0n)return this.lexicon.characters[0];let s=BigInt(this.lexicon.characters.length),n="";for(;r>0n;)n=this.lexicon.characters[Number(r%s)]+n,r=r/s;return t?`${this.negativePrefix}${n}`:n}random(e=32){return this.fromBytes(yt.random(e))}};var Zc=Object.freeze({fromBytes(i){return typeof btoa=="function"?btoa(String.fromCharCode(...i)):Buffer.from(i).toString("base64")},toBytes(i){return typeof atob=="function"?Uint8Array.from(atob(i),e=>e.charCodeAt(0)):Uint8Array.from(Buffer.from(i,"base64"))},random(i=32){return this.fromBytes(yt.random(i))},string(i){return Zc.fromBytes(i)},bytes(i){return Zc.toBytes(i)}});var Xd=Object.freeze({fromBytes(i){return new TextDecoder().decode(i)},toBytes(i){return new TextEncoder().encode(i)},string(i){return Xd.fromBytes(i)},bytes(i){return Xd.toBytes(i)}});var jn=Object.freeze({set:i=>i!=null,unset:i=>i==null,boolean:i=>typeof i=="boolean",number:i=>typeof i=="number",string:i=>typeof i=="string",bigint:i=>typeof i=="bigint",object:i=>typeof i=="object"&&i!==null,array:i=>Array.isArray(i),fn:i=>typeof i=="function",symbol:i=>typeof i=="symbol"});var ms=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function $n(i,e){return i<=0||i===1/0?e():new Promise((t,r)=>{let s=setTimeout(()=>r(new ms(i)),i);e().then(t).catch(r).finally(()=>clearTimeout(s))})}function kr(){let i,e,t=new Promise((s,n)=>{i=s,e=n});function r(s){return s.then(i).catch(e),t}return{promise:t,resolve:i,reject:e,entangle:r}}function Yd(i,e){let t=i;for(let r of e)if(t=t[r],jn.unset(t))break;return t}function h_(i){return{map:e=>Kd(i,e),filter:e=>Zd(i,e)}}h_.pipe=Object.freeze({map:i=>e=>Kd(e,i),filter:i=>e=>Zd(e,i)});var Kd=(i,e)=>Object.fromEntries(Object.entries(i).map(([t,r])=>[t,e(r,t)])),Zd=(i,e)=>Object.fromEntries(Object.entries(i).filter(([t,r])=>e(r,t)));function d_(){let i=new Set;function e(n){return i.add(n),()=>{i.delete(n)}}async function t(...n){await Promise.all([...i].map(o=>o(...n)))}async function r(){let{promise:n,resolve:o}=kr(),a=e((...c)=>{o(c),a()});return n}function s(){i.clear()}return e.pub=t,e.sub=e,e.on=e,e.next=r,e.clear=s,t.pub=t,t.sub=e,t.on=e,t.next=r,t.clear=s,[t,e]}function qn(i){let e=d_()[0];return i&&e.sub(i),e}var Dt=class{#e=[];add(...e){return this.#e.push(...e),this}disposable(e){return this.bag(e,()=>e.dispose())}bag(e,t){return this.add(()=>t(e)),e}dispose(){for(let e of this.#e.reverse())e();this.#e=[]}};var rr;(function(i){i.version="2.0";function e(t){return"id"in t?t.id:null}i.getId=e,i.errorCodes={serverError:-32e3,unexposedError:-32001}})(rr||(rr={}));var Xn=class extends Error{name=this.constructor.name},vr=class extends Error{name=this.constructor.name};async function Qd({tap:i,request:e,action:t}){let r=rr.getId(e);try{let s=await t();return r===null?null:{id:r,result:s,jsonrpc:rr.version}}catch(s){return i.rpcError({request:e,error:s}),r===null?null:{id:r,jsonrpc:rr.version,error:s instanceof Xn?{code:rr.errorCodes.serverError,message:s.message}:{code:rr.errorCodes.unexposedError,message:"unexposed error"}}}}function Yn(i){let e=i.tap??new xt;return async t=>{let r=t.method.split("."),s=Yd(i.fns,r),n=async()=>await s(...t.params);return e.rpcRequest({request:t}),await Qd({tap:e,request:t,action:n})}}var Pr=Symbol("tune"),f_=Symbol("query"),m_=Symbol("notify"),p_=Symbol("settings");function Jd(i){function e(t){let r={notify:void 0};return new Proxy(()=>{},{apply:(s,n,o)=>i(t,o,r),get:(s,n)=>{if(n!=="then")return n===Pr?o=>(...a)=>i(t,a,{...r,...o}):n===m_?(...o)=>i(t,o,{...r,notify:!0}):n===f_?(...o)=>i(t,o,{...r,notify:!1}):n===p_?r:(s[n]||(s[n]=e([...t,n])),s[n])},set:(s,n,o)=>(s[n]=o,!0)})}return e([])}function Cr(i){let{endpoint:e,tap:t=new xt}=i,r=1;return Jd(async(s,n,o)=>{let a=o.notify??i.notify??!1,c=o.transfer,l={jsonrpc:"2.0",method:s.join("."),params:n},u=a?l:{...l,id:r++};t.rpcRequest({request:u});let h=await e(u,{transfer:c});if(a&&!h)return null;if(!h)throw new vr("response was null, but shouldn't be, because the request was not a notification");if("error"in h)throw new vr(i.label?`${i.label}: ${h.error.message}`:h.error.message);return h.result})}function ps(i){return Cr({endpoint:Yn(i),tap:i.tap})}var Er=class{recv=qn();sendRequest=qn();sendResponse=qn();static makeEntangledPair({origin:e="example.e280.org"}={}){let t=new this,r=new this,s=[t.sendRequest.sub(o=>r.recv(o,{origin:e})),t.sendResponse.sub(o=>r.recv(o,{origin:e})),r.sendRequest.sub(o=>t.recv(o,{origin:e})),r.sendResponse.sub(o=>t.recv(o,{origin:e}))];return[t,r,()=>s.forEach(o=>o())]}};function Kn(i,e){return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}function ef(i,e){return async(t,{transfer:r}={})=>{if("id"in t){let s=kr();return e(t,r,s.promise),i.wait(t.id,t.method).then(n=>(s.resolve(n),n))}else{let s=Promise.resolve(null);return e(t,r,s),s}}}function tf(i){let e=[],t=[];for(let r of Array.isArray(i)?i:[i])"method"in r?e.push(r):t.push(r);return{requests:e,responses:t}}async function rf(i,e){let t=(await Promise.all(e.map(async r=>i(r)))).filter(r=>r!==null);return t.length===0?null:t.length===1?t[0]:t}var ni=class extends Er{#e=new Dt;constructor(e){super(),this.#e.add(this.sendRequest.sub((t,r)=>e.postMessage(t,r)),this.sendResponse.sub((t,r)=>e.postMessage(t,r)),Kn(e,t=>this.recv(t.data,t)))}dispose(){this.#e.dispose()}};var Zn=class{remote;transfer;constructor(e){this.remote=e}};var Qc=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Qn=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,t){let r=kr();return this.pending.set(e,{method:t,deferred:r}),await $n(this.timeout,()=>r.promise).catch(s=>{throw s instanceof ms&&(s.message=`request #${e} ${t}(), ${s.message}`),s})}deliverResponse(e){let t=this.pending.get(e.id);t&&("error"in e?t.deferred.reject(new vr(e.error.message)):t.deferred.resolve(e))}};var Ar=class{options;remote;remoteEndpoint;#e;#t=new Dt;constructor(e){this.options=e;let{conduit:t,tap:r}=e;this.#e=new Qn(e.timeout??Qc.timeout),this.remoteEndpoint=ef(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=Cr({endpoint:this.remoteEndpoint,tap:r&&jc(r,{remote:!0})}),this.#t.add(t.recv.sub(s=>this.recv(s)))}async recv(e){let t=new Zn(this.remote),{conduit:r,rpc:s,tap:n}=this.options,{requests:o,responses:a}=tf(e);for(let h of a)this.#e.deliverResponse(h);if(!s)return;let c=await s(t),l=Yn({fns:c,tap:n&&jc(n,{remote:!1})}),u=await rf(l,o);u&&await r.sendResponse(u,t.transfer)}dispose(){this.#t.dispose()}};var Rt={derive:{host:i=>({host:i.remote.host,get transfer(){return i.transfer},set transfer(e){i.transfer=e}}),work:i=>({work:i.remote,get transfer(){return i.transfer},set transfer(e){i.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var Ot=new xt;async function sf(i,e,t={}){let r=t.tap??Ot,s=new Ar({tap:r,timeout:t.timeout??1/0,conduit:new ni(i.getSelf()),rpc:async n=>e(Rt.derive.host(n))});return await s.remote.infra.ready(),s.remote.host}var st=Object.freeze({eq(i,e){if(i.length!==e.length)return!1;for(let t=0;t<=i.length;t++)if(i.at(t)!==e.at(t))return!1;return!0},random(i){return crypto.getRandomValues(new Uint8Array(i))}});var Le=Object.freeze({fromBytes(i){return[...i].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(i){if(i.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(i.length/2);for(let t=0;t<i.length;t+=2)e[t/2]=parseInt(i.slice(t,t+2),16);return e},random(i=32){return this.fromBytes(st.random(i))},string(i){return Le.fromBytes(i)},bytes(i){return Le.toBytes(i)}});var Jc=["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 el=["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 Ut={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(i,e){let t=st.random(i);return this.fromBytes(t,e)},fromBytes(i,e={}){let{groupSize:t=Ut.defaults.groupSize,wordSeparator:r=Ut.defaults.wordSeparator,groupSeparator:s=Ut.defaults.groupSeparator}=e,n=[],o=[];i.forEach((c,l)=>{let u=l%2===0?Jc:el;o.push(u[c]),o.length===2&&(n.push(o.join("")),o=[])}),o.length&&n.push(o.join(""));let a=[];for(let c=0;c<n.length;c+=t)a.push(n.slice(c,c+t).join(r));return a.join(s)},toBytes(i){let e=i.toLowerCase().replace(/[^a-z]/g,"");if(e.length/3%1!==0)throw new Error(`invalid triplet count, ${e.length} does not divide into triplets`);let r=[];for(let s=0;s<e.length;s+=3)r.push(e.slice(s,s+3));return new Uint8Array(r.map((s,n)=>{let a=(n%2===0?Jc:el).findIndex(c=>c===s);if(a===-1)throw new Error(`unknown triplet ${s}`);return a}))},toHex(i){return Le.fromBytes(Ut.toBytes(i))},fromHex(i,e){return Ut.fromBytes(Le.toBytes(i),e)}};var tl=58,Jn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",gs=Object.freeze({fromBytes(i){let e=BigInt("0x"+Le.fromBytes(i)),t="";for(;e>0;){let r=e%BigInt(tl);e=e/BigInt(tl),t=Jn[Number(r)]+t}for(let r of i)if(r===0)t=Jn[0]+t;else break;return t},toBytes(i){let e=BigInt(0);for(let o of i){let a=Jn.indexOf(o);if(a===-1)throw new Error(`Invalid character '${o}' in base58 string`);e=e*BigInt(tl)+BigInt(a)}let t=e.toString(16);t.length%2!==0&&(t="0"+t);let r=Le.toBytes(t),s=0;for(let o of i)if(o===Jn[0])s++;else break;let n=new Uint8Array(s+r.length);return n.set(r,s),n},random(i=32){return this.fromBytes(st.random(i))},string(i){return gs.fromBytes(i)},bytes(i){return gs.toBytes(i)}});var nt={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(i){i=i.trim();let e=i.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(s=>s.trim());if(e.length<2)return Ut.toBytes(e.join(""));let t=e.pop(),r=e.join("");return new Uint8Array([...Ut.toBytes(r),...gs.toBytes(t)])},parse(i,e){let t=nt.toBytes(i);return nt.build.fromBytes(t,e)},build:{fromBytes(i,e={}){let{delimiter:t,previewBytes:r,sigilBytes:s}={...nt.defaults,...e},n=u=>i.length>0?Ut.fromBytes(i.slice(0,u),{wordSeparator:t,groupSeparator:t}):"",o=n(s),a=n(r),c=i.length>r?gs.fromBytes(i.slice(r)):"",l=[a,c].filter(u=>u.length>0).join(t);return{bytes:i,thumbprint:l,preview:a,bulk:c,sigil:o}},fromHex(i,e){let t=Le.toBytes(i);return nt.build.fromBytes(t,e)}},toHex(i){let e=nt.toBytes(i);return Le.fromBytes(e)},fromBytes(i,e){return nt.build.fromBytes(i,e).thumbprint},fromHex(i,e){return nt.fromBytes(Le.toBytes(i),e)},sigil:{fromHex(i,e){return nt.build.fromHex(i,e).sigil},fromBytes(i,e){return nt.build.fromBytes(i,e).sigil}}};var nf=class{lexicon;static lexicons=Object.freeze({base2:{characters:"01"},hex:{characters:"0123456789abcdef"},base36:{characters:"0123456789abcdefghijklmnopqrstuvwxyz"},base58:{characters:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"},base62:{characters:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},base64url:{negativePrefix:"~",characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"},base64:{characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",padding:{character:"=",size:4}}});lookup;negativePrefix;constructor(e){this.lexicon=e,this.lookup=Object.fromEntries([...e.characters].map((t,r)=>[t,r])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let a=0,c=0,l=[];for(let u of e){if(u===this.lexicon.padding?.character)continue;let h=this.lookup[u];if(h===void 0)throw new Error(`Invalid character: ${u}`);for(a=a<<t|h,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let r=0n,s=BigInt(this.lexicon.characters.length),n=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);r=r*s+BigInt(c)}let o=[];for(;r>0n;)o.unshift(Number(r%256n)),r=r/256n;return new Uint8Array(o)}fromBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let o=0,a=0,c="";for(let l of e)for(o=o<<8|l,a+=8;a>=t;){a-=t;let u=o>>a&(1<<t)-1;c+=this.lexicon.characters[u]}if(a>0){let l=o<<t-a&(1<<t)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let r=0n;for(let o of e)r=(r<<8n)+BigInt(o);if(r===0n)return this.lexicon.characters[0];let s=BigInt(this.lexicon.characters.length),n="";for(;r>0n;)n=this.lexicon.characters[Number(r%s)]+n,r=r/s;return n}toInteger(e){if(!e)return 0;let t=0n,r=!1,s=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),r=!0);for(let n of e){let o=this.lookup[n];if(o===void 0)throw new Error(`Invalid character: ${n}`);t=t*s+BigInt(o)}return Number(r?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,r=BigInt(t?-e:e);if(r===0n)return this.lexicon.characters[0];let s=BigInt(this.lexicon.characters.length),n="";for(;r>0n;)n=this.lexicon.characters[Number(r%s)]+n,r=r/s;return t?`${this.negativePrefix}${n}`:n}random(e=32){return this.fromBytes(st.random(e))}};var rl=Object.freeze({fromBytes(i){return typeof btoa=="function"?btoa(String.fromCharCode(...i)):Buffer.from(i).toString("base64")},toBytes(i){return typeof atob=="function"?Uint8Array.from(atob(i),e=>e.charCodeAt(0)):Uint8Array.from(Buffer.from(i,"base64"))},random(i=32){return this.fromBytes(st.random(i))},string(i){return rl.fromBytes(i)},bytes(i){return rl.toBytes(i)}});var of=Object.freeze({fromBytes(i){return new TextDecoder().decode(i)},toBytes(i){return new TextEncoder().encode(i)},string(i){return of.fromBytes(i)},bytes(i){return of.toBytes(i)}});var il=Object.freeze({set:i=>i!=null,unset:i=>i==null,boolean:i=>typeof i=="boolean",number:i=>typeof i=="number",string:i=>typeof i=="string",bigint:i=>typeof i=="bigint",object:i=>typeof i=="object"&&i!==null,array:i=>Array.isArray(i),fn:i=>typeof i=="function",symbol:i=>typeof i=="symbol"});function xs(){let i,e,t=new Promise((s,n)=>{i=s,e=n});function r(s){return s.then(i).catch(e),t}return{promise:t,resolve:i,reject:e,entangle:r}}var eo=class i extends Map{static require(e,t){if(e.has(t))return e.get(t);throw new Error(`required key not found: "${t}"`)}static guarantee(e,t,r){if(e.has(t))return e.get(t);{let s=r();return e.set(t,s),s}}array(){return[...this]}require(e){return i.require(this,e)}guarantee(e,t){return i.guarantee(this,e,t)}};function b_(i){return{map:e=>af(i,e),filter:e=>cf(i,e)}}b_.pipe=Object.freeze({map:i=>e=>af(e,i),filter:i=>e=>cf(e,i)});var af=(i,e)=>Object.fromEntries(Object.entries(i).map(([t,r])=>[t,e(r,t)])),cf=(i,e)=>Object.fromEntries(Object.entries(i).filter(([t,r])=>e(r,t)));var oi=class{worker;messenger;constructor(e,t){this.worker=e,this.messenger=t}static async make(e,t){let r=t.tap??Ot,s=t.label??"comrade",n=e.loadWorker(t.workerUrl,s),o=xs(),a={async ready(){o.resolve()}},c=new Ar({tap:r,timeout:t.timeout??1/0,conduit:new ni(n),rpc:async l=>({infra:a,host:t.setupHost(Rt.derive.work(l))})});return await o.promise,new this(n,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var to=class{threads;static async make(e,t){let r=t.workerCount??e.guessOptimalThreadCount(),s=await Promise.all([...Array(r)].map(async(n,o)=>oi.make(e,{...t,label:t.label??`${t.label??"comrade"}_${o+1}`})));return new this(s,{tap:t.tap})}work;#e=new Set;#t=[];constructor(e,t={}){this.threads=e;let r=t.tap??Ot,s=async(n,o)=>this.#r({request:n,prom:xs(),transfer:o?.transfer});this.work=Cr({tap:r,endpoint:s}),e.forEach(n=>this.#e.add(n))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#r(e){return this.#t.push(e),this.#i(),e.prom.promise}#i(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let t=this.#t.shift();this.#e.delete(e);let r=e.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(r).finally(()=>{this.#e.add(e),this.#i()})}}};var lf=i=>({thread:e=>oi.make(i,e),cluster:e=>to.make(i,e),worker:(e,t={})=>sf(i,e,t),work:e=>e,host:e=>e,mocks(e){let{setupWork:t,setupHost:r,tap:s=Ot}=e,n=Rt.mock.host(),o=Rt.mock.work();return o.work=ps({tap:s,fns:t(n)}),n.host=ps({tap:s,fns:r(o)}),{workShell:o,hostShell:n,work:o.work,host:n.host}},mockWork(e,t=Ot){let r=Rt.mock.host(),s=Rt.mock.work();return s.work=ps({tap:t,fns:e(r)}),{workShell:s,hostShell:r,work:s.work,mockHost:n=>(r.host=ps({tap:t,fns:n(s)}),{workShell:s,hostShell:r,work:s.work,host:r.host})}}});var uf=()=>({getSelf(){return self},guessOptimalThreadCount(){let i=navigator.hardwareConcurrency??1;return Math.max(1,i-1)},loadWorker(i,e){return new window.Worker(i,{name:e,type:"module"})},async loadWasm(i){return WebAssembly.instantiateStreaming(fetch(i))}});var w_=uf(),ro=lf(w_);function k(i){if(!i)throw new Error("Assertion failed.")}var so=i=>{let e=(i%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${i}.`)},ve=i=>i&&i[i.length-1];var fe=class i{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(this.pos&7),s=(t&1<<r)>>r;return this.pos++,s}readBits(e){if(e===1)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let r=this.pos+e;for(let s=this.pos;s<r;s++){let n=Math.floor(s/8),o=this.bytes[n],a=7-(s&7);o&=~(1<<a),o|=(t&1<<r-s-1)>>r-s-1<<a,this.bytes[n]=o}this.pos=r}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new i(this.bytes);return e.pos=this.pos,e}},R=i=>{let e=0;for(;i.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+i.readBits(e)},ai=i=>{let e=R(i);return(e&1)===0?-(e>>1):e+1>>1};var ir=i=>i instanceof Uint8Array?i:i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),oe=i=>i instanceof DataView?i:i instanceof ArrayBuffer?new DataView(i):new DataView(i.buffer,i.byteOffset,i.byteLength),Be=new TextDecoder,__=new TextEncoder;var nl=i=>Object.fromEntries(Object.entries(i).map(([e,t])=>[t,e])),ol={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},no=nl(ol),al={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},oo=nl(al),cl={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ao=nl(cl);var ll=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),Je=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(s=>{e=s}),r=this.currentPromise;return this.currentPromise=t,await r,e}},ul=i=>[...i].map(e=>e.toString(16).padStart(2,"0")).join(""),hl=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),ae=(i,e,t)=>{let r=0,s=i.length-1,n=-1;for(;r<=s;){let o=r+s>>1,a=t(i[o]);a===e?(n=o,s=o-1):a<e?r=o+1:s=o-1}return n},Q=(i,e,t)=>{let r=0,s=i.length-1,n=-1;for(;r<=s;){let o=r+(s-r+1)/2|0;t(i[o])<=e?(n=o,r=o+1):s=o-1}return n},ot=(i,e,t)=>{let r=Q(i,t(e),t);i.splice(r+1,0,e)},Fe=()=>{let i,e;return{promise:new Promise((r,s)=>{i=r,e=s}),resolve:i,reject:e}};var dl=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return i[t]},co=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return t;return-1},hf=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},df=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},ys=i=>{throw new Error(`Unexpected value: ${i}`)};var fl=(i,e)=>({async next(){let t=await i.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return i.return()},throw(t){return i.throw(t)},[Symbol.asyncIterator](){return this}}),lo=(i,e,t)=>Math.max(e,Math.min(t,i)),Pe="und",Ir=(i,e)=>{let t=10**e;return Math.round(i*t)/t},ff=(i,e)=>Math.round(i/e)*e,mf=i=>{let e=0;for(;i;)e++,i>>=1;return e},S_=/^[a-z]{3}$/,uo=i=>S_.test(i),sr=1e6*(1+Number.EPSILON),ho=(i,e)=>{let t={...i};for(let r in e)typeof i[r]=="object"&&i[r]!==null&&typeof e[r]=="object"&&e[r]!==null?t[r]=ho(i[r],e[r]):t[r]=e[r];return t},ml=async(i,e,t)=>{let r=0;for(;;)try{return await fetch(i,e)}catch(s){r++;let n=t(r);if(n===null)throw s;if(console.error("Retrying failed fetch. Error:",s),!Number.isFinite(n)||n<0)throw new TypeError("Retry delay must be a non-negative finite number.");n>0&&await new Promise(o=>setTimeout(o,1e3*n))}};var io=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},sl=null,fo=()=>{if(sl!==null)return sl;let i=!!(typeof navigator<"u"&&navigator.vendor?.match(/apple/i)&&!navigator.userAgent?.match(/crios/i)&&!navigator.userAgent?.match(/fxios/i)&&!navigator.userAgent?.match(/Opera|OPT\//));return sl=i,i},Mr=(i,e)=>i!==-1?i:e,mo=(i,e,t,r)=>i<=r&&t<=e;var pf=i=>{let e=atob(i),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t};var nr=class{constructor(e,t){this.data=e,this.mimeType=t}};var ws=["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"],T_=["aac","opus","mp3","vorbis","flac"],NI=[...T_,...ws];var Br=[{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 gf=".01.01.01.01.00",xf=".0.110.01.01.01.0";var po=i=>{let{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:o,av1CodecInfo:a}=i;if(e==="avc"){if(s){let c=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc1.${ul(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc1.${ul(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,h,d,f;if(n)c=n.generalProfileSpace,l=n.generalProfileIdc,u=hl(n.generalProfileCompatibilityFlags),h=n.generalTierFlag,d=n.generalLevelIdc,f=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let p=oe(t),g=p.getUint8(1);c=g>>6&3,l=g&31,u=hl(p.getUint32(2)),h=g>>5&1,d=p.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(p.getUint8(6+y))}let m="hev1.";for(m+=["","A","B","C"][c]+l,m+=".",m+=u.toString(16).toUpperCase(),m+=".",m+=h===0?"L":"H",m+=d;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(m+=".",m+=f.map(p=>p.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!o){let y=i.width*i.height,x=ve(Br).level;for(let w of Br)if(y<=w.maxPictureSize){x=w.level;break}return`vp09.00.${x.toString().padStart(2,"0")}.08`}let c=o.profile.toString().padStart(2,"0"),l=o.level.toString().padStart(2,"0"),u=o.bitDepth.toString().padStart(2,"0"),h=o.chromaSubsampling.toString().padStart(2,"0"),d=o.colourPrimaries.toString().padStart(2,"0"),f=o.transferCharacteristics.toString().padStart(2,"0"),m=o.matrixCoefficients.toString().padStart(2,"0"),p=o.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${l}.${u}.${h}`;return g+=`.${d}.${f}.${m}.${p}`,g.endsWith(gf)&&(g=g.slice(0,-gf.length)),g}else if(e==="av1"){if(!a){let w=i.width*i.height,_=ve(Br).level;for(let S of Br)if(w<=S.maxPictureSize){_=S.level;break}return`av01.0.${_.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),u=a.tier?"H":"M",h=a.bitDepth.toString().padStart(2,"0"),d=a.monochrome?"1":"0",f=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),m=r?.primaries?ol[r.primaries]:1,p=r?.transfer?al[r.transfer]:1,g=r?.matrix?cl[r.matrix]:1,y=r?.fullRange?1:0,x=`av01.${c}.${l}${u}.${h}`;return x+=`.${d}.${f.toString().padStart(3,"0")}`,x+=`.${m.toString().padStart(2,"0")}`,x+=`.${p.toString().padStart(2,"0")}`,x+=`.${g.toString().padStart(2,"0")}`,x+=`.${y}`,x.endsWith(xf)&&(x=x.slice(0,-xf.length)),x}}throw new TypeError(`Unhandled codec '${e}'.`)};var go=i=>{let{codec:e,codecDescription:t,aacCodecInfo:r}=i;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");return r.isMpeg2?"mp4a.67":`mp4a.40.${gl(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&&ws.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},bs=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],pl=[-1,1,2,3,4,5,6,8],gl=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new fe(i),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let r=e.readBits(4),s=null;r===15?s=e.readBits(24):r<bs.length&&(s=bs[r]);let n=e.readBits(4),o=null;return n>=1&&n<=7&&(o=pl[n]),{objectType:t,frequencyIndex:r,sampleRate:s,channelConfiguration:n,numberOfChannels:o}},yf=48e3,k_=/^pcm-([usf])(\d+)+(be)?$/,bf=i=>{if(k(ws.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=k_.exec(i);k(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let r=Number(e[2])/8,s=e[3]!=="be",n=i==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:s,silentValue:n}};var ci;(function(i){i[i.IDR=5]="IDR",i[i.SPS=7]="SPS",i[i.PPS=8]="PPS",i[i.SPS_EXT=13]="SPS_EXT"})(ci||(ci={}));var De;(function(i){i[i.RASL_N=8]="RASL_N",i[i.RASL_R=9]="RASL_R",i[i.BLA_W_LP=16]="BLA_W_LP",i[i.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",i[i.VPS_NUT=32]="VPS_NUT",i[i.SPS_NUT=33]="SPS_NUT",i[i.PPS_NUT=34]="PPS_NUT",i[i.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",i[i.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(De||(De={}));var yo=i=>{let e=[],t=0;for(;t<i.length;){let r=-1,s=0;for(let n=t;n<i.length-3;n++){if(i[n]===0&&i[n+1]===0&&i[n+2]===1){r=n,s=3;break}if(n<i.length-4&&i[n]===0&&i[n+1]===0&&i[n+2]===0&&i[n+3]===1){r=n,s=4;break}}if(r===-1)break;if(t>0&&r>t){let n=i.subarray(t,r);n.length>0&&e.push(n)}t=r+s}if(t<i.length){let r=i.subarray(t);r.length>0&&e.push(r)}return e},_f=(i,e)=>{let t=[],r=0,s=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;r+e<=i.length;){let n;e===1?n=s.getUint8(r):e===2?n=s.getUint16(r,!1):e===3?n=(s.getUint16(r,!1)<<8)+s.getUint8(r+2):e===4?n=s.getUint32(r,!1):(ys(e),k(!1)),r+=e;let o=i.subarray(r,r+n);t.push(o),r+=n}return t},xl=i=>{let e=[],t=i.length;for(let r=0;r<t;r++)r+2<t&&i[r]===0&&i[r+1]===0&&i[r+2]===3?(e.push(0,0),r+=2):e.push(i[r]);return new Uint8Array(e)};var v_=(i,e)=>{if(e.description){let s=(ir(e.description)[4]&3)+1;return _f(i,s)}else return yo(i)},xo=i=>i[0]&31,Sf=i=>{try{let e=yo(i),t=e.filter(d=>xo(d)===ci.SPS),r=e.filter(d=>xo(d)===ci.PPS),s=e.filter(d=>xo(d)===ci.SPS_EXT);if(t.length===0||r.length===0)return null;let n=t[0],o=new fe(xl(n));if(o.skipBits(1),o.skipBits(2),o.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;let c=o.readAlignedByte(),l=o.readAlignedByte(),u=o.readAlignedByte(),h={configurationVersion:1,avcProfileIndication:c,profileCompatibility:l,avcLevelIndication:u,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(c===100||c===110||c===122||c===144){R(o);let d=R(o);d===3&&o.skipBits(1);let f=R(o),m=R(o);h.chromaFormat=d,h.bitDepthLumaMinus8=f,h.bitDepthChromaMinus8=m,h.sequenceParameterSetExt=s}return h}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}};var yl=(i,e)=>{if(e.description){let s=(ir(e.description)[21]&3)+1;return _f(i,s)}else return yo(i)},zt=i=>i[0]>>1&63,Tf=i=>{try{let e=yo(i),t=e.filter(C=>zt(C)===De.VPS_NUT),r=e.filter(C=>zt(C)===De.SPS_NUT),s=e.filter(C=>zt(C)===De.PPS_NUT),n=e.filter(C=>zt(C)===De.PREFIX_SEI_NUT||zt(C)===De.SUFFIX_SEI_NUT);if(r.length===0||s.length===0)return null;let o=r[0],a=new fe(xl(o));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:u,general_tier_flag:h,general_profile_idc:d,general_profile_compatibility_flags:f,general_constraint_indicator_flags:m,general_level_idc:p}=P_(a,c);R(a);let g=R(a);g===3&&a.skipBits(1),R(a),R(a),a.readBits(1)&&(R(a),R(a),R(a),R(a));let y=R(a),x=R(a);R(a);let _=a.readBits(1)?0:c;for(let C=_;C<=c;C++)R(a),R(a),R(a);R(a),R(a),R(a),R(a),R(a),R(a),a.readBits(1)&&a.readBits(1)&&C_(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),R(a),R(a),a.skipBits(1));let S=R(a);if(E_(a,S),a.readBits(1)){let C=R(a);for(let E=0;E<C;E++)R(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let T=0;a.readBits(1)&&(T=I_(a,c));let v=0;if(s.length>0){let C=s[0],E=new fe(xl(C));E.skipBits(16),R(E),R(E),E.skipBits(1),E.skipBits(1),E.skipBits(3),E.skipBits(1),E.skipBits(1),R(E),R(E),ai(E),E.skipBits(1),E.skipBits(1),E.readBits(1)&&R(E),ai(E),ai(E),E.skipBits(1),E.skipBits(1),E.skipBits(1),E.skipBits(1);let D=E.readBits(1),j=E.readBits(1);!D&&!j?v=0:D&&!j?v=2:!D&&j?v=3:v=0}let M=[...t.length?[{arrayCompleteness:1,nalUnitType:De.VPS_NUT,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:De.SPS_NUT,nalUnits:r}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:De.PPS_NUT,nalUnits:s}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:zt(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:h,generalProfileIdc:d,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:m,generalLevelIdc:p,minSpatialSegmentationIdc:T,parallelismType:v,chromaFormatIdc:g,bitDepthLumaMinus8:y,bitDepthChromaMinus8:x,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:M}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},P_=(i,e)=>{let t=i.readBits(2),r=i.readBits(1),s=i.readBits(5),n=0;for(let u=0;u<32;u++)n=n<<1|i.readBits(1);let o=new Uint8Array(6);for(let u=0;u<6;u++)o[u]=i.readBits(8);let a=i.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(i.readBits(1)),l.push(i.readBits(1));if(e>0)for(let u=e;u<8;u++)i.skipBits(2);for(let u=0;u<e;u++)c[u]&&i.skipBits(88),l[u]&&i.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:s,general_profile_compatibility_flags:n,general_constraint_indicator_flags:o,general_level_idc:a}},C_=i=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!i.readBits(1))R(i);else{let s=Math.min(64,1<<4+(e<<1));e>1&&ai(i);for(let n=0;n<s;n++)ai(i)}},E_=(i,e)=>{let t=[];for(let r=0;r<e;r++)t[r]=A_(i,r,e,t)},A_=(i,e,t,r)=>{let s=0,n=0,o=0;if(e!==0&&(n=i.readBits(1)),n){if(e===t){let c=R(i);o=e-(c+1)}else o=e-1;i.readBits(1),R(i);let a=r[o]??0;for(let c=0;c<=a;c++)i.readBits(1)||i.readBits(1);s=r[o]}else{let a=R(i),c=R(i);for(let l=0;l<a;l++)R(i),i.readBits(1);for(let l=0;l<c;l++)R(i),i.readBits(1);s=a+c}return s},I_=(i,e)=>{if(i.readBits(1)&&i.readBits(8)===255&&(i.readBits(16),i.readBits(16)),i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),i.readBits(1),i.readBits(1)&&(i.readBits(8),i.readBits(8),i.readBits(8))),i.readBits(1)&&(R(i),R(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(R(i),R(i),R(i),R(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&R(i),i.readBits(1)&&M_(i,!0,e)),i.readBits(1)){i.readBits(1),i.readBits(1),i.readBits(1);let t=R(i);return R(i),R(i),R(i),R(i),t}return 0},M_=(i,e,t)=>{let r=!1,s=!1,n=!1;e&&(r=i.readBits(1)===1,s=i.readBits(1)===1,(r||s)&&(n=i.readBits(1)===1,n&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5)));for(let o=0;o<=t;o++){let a=i.readBits(1)===1,c=!0;a||(c=i.readBits(1)===1);let l=!1;c?R(i):l=i.readBits(1)===1;let u=1;l||(u=R(i)+1),r&&wf(i,u,n),s&&wf(i,u,n)}},wf=(i,e,t)=>{for(let r=0;r<e;r++)R(i),R(i),t&&(R(i),R(i)),i.readBits(1)};var bo=i=>{let e=new fe(i);if(e.readBits(2)!==2)return null;let r=e.readBits(1),n=(e.readBits(1)<<1)+r;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;n>=2&&(l=e.readBits(1)?12:10);let u=e.readBits(3),h=0,d=0;if(u!==7)if(d=e.readBits(1),n===1||n===3){let v=e.readBits(1),M=e.readBits(1);h=!v&&!M?3:v&&!M?2:1,e.skipBits(1)}else h=1;else h=3,d=1;let f=e.readBits(16),m=e.readBits(16),p=f+1,g=m+1,y=p*g,x=ve(Br).level;for(let T of Br)if(y<=T.maxPictureSize){x=T.level;break}return{profile:n,level:x,bitDepth:l,chromaSubsampling:h,videoFullRangeFlag:d,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},kf=function*(i){let e=new fe(i),t=()=>{let r=0;for(let s=0;s<8;s++){let n=e.readAlignedByte();if(r|=(n&127)<<s*7,!(n&128))break;if(s===7&&n&128)return null}return r>=2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);let r=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let o;if(n){let a=t();if(a===null)return;o=a}else o=Math.floor(e.getBitsLeft()/8);k(e.pos%8===0),yield{type:r,data:i.subarray(e.pos/8,e.pos/8+o)},e.skipBits(o*8)}},wo=i=>{for(let{type:e,data:t}of kf(i)){if(e!==1)continue;let r=new fe(t),s=r.readBits(3),n=r.readBits(1),o=r.readBits(1),a=0,c=0,l=0;if(o)a=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;let y=r.readBits(1);y&&(l=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));let x=r.readBits(5);for(let w=0;w<=x;w++){r.skipBits(12);let _=r.readBits(5);if(w===0&&(a=_),_>7){let T=r.readBits(1);w===0&&(c=T)}if(y&&r.readBits(1)){let v=l+1;r.skipBits(v),r.skipBits(v),r.skipBits(1)}r.readBits(1)&&r.skipBits(4)}}let u=r.readBits(1),h=8;s===2&&u?h=r.readBits(1)?12:10:s<=2&&(h=u?10:8);let d=0;s!==1&&(d=r.readBits(1));let f=1,m=1,p=0;return d||(s===0?(f=1,m=1):s===1?(f=0,m=0):h===12&&(f=r.readBits(1),f&&(m=r.readBits(1))),f&&m&&(p=r.readBits(2))),{profile:s,level:a,tier:c,bitDepth:h,monochrome:d,chromaSubsamplingX:f,chromaSubsamplingY:m,chromaSamplePosition:p}}return null},vf=i=>{let e=oe(i),t=e.getUint8(9),r=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),o=e.getUint8(18),a=null;return o&&(a=i.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:s,outputGain:n,channelMappingFamily:o,channelMappingTable:a}},B_=[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],Pf=i=>{let e=i[0]>>3;return{durationInSamples:B_[e]}},Cf=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=i.length,r=new Uint8Array(t);for(let h=0;h<t;h++)r[h]=i[t-1-h];let s=new fe(r),n=0;for(;s.getBitsLeft()>97;)if(s.readBits(1)===1){n=s.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let o=0,a=!1,c=0;for(;s.getBitsLeft()>=97;){let h=s.pos,d=s.readBits(8),f=s.readBits(16),m=s.readBits(16);if(d>63||f!==0||m!==0){s.pos=h;break}if(s.skipBits(1),o++,o>64)break;s.clone().readBits(6)+1===o&&(a=!0,c=o)}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;s.pos=0,s.skipBits(n);let u=Array(l).fill(0);for(let h=l-1;h>=0;h--)s.skipBits(40),u[h]=s.readBits(1);return{modeBlockflags:u}},Ef=async(i,e)=>{switch(k(i.codec),i.codec){case"avc":{let t=await i.getDecoderConfig();return k(t),v_(e.data,t).some(n=>xo(n)===ci.IDR)?"key":"delta"}case"hevc":{let t=await i.getDecoderConfig();return k(t),yl(e.data,t).some(n=>{let o=zt(n);return De.BLA_W_LP<=o&&o<=De.RSV_IRAP_VCL23})?"key":"delta"}case"vp8":return(e.data[0]&1)===0?"key":"delta";case"vp9":{let t=new fe(e.data);if(t.readBits(2)!==2)return null;let r=t.readBits(1);return(t.readBits(1)<<1)+r===3&&t.skipBits(1),t.readBits(1)?null:t.readBits(1)===0?"key":"delta"}case"av1":{let t=!1;for(let{type:r,data:s}of kf(e.data))if(r===1){let n=new fe(s);n.skipBits(4),t=!!n.readBits(1)}else if(r===3||r===6||r===7){if(t)return"key";let n=new fe(s);return n.readBits(1)?null:n.readBits(2)===0?"key":"delta"}return null}default:ys(i.codec),k(!1)}};var Af=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};var _o=class{constructor(e){this.source=e}requestSlice(e,t){if(this.fileSize!==null&&e+t>this.fileSize)return null;let r=e+t,s=this.source._read(e,r);return s instanceof Promise?s.then(n=>n?new li(n.bytes,n.view,n.offset,e,r):null):s?new li(s.bytes,s.view,s.offset,e,r):null}requestSliceRange(e,t,r){if(this.fileSize!==null)return this.requestSlice(e,lo(this.fileSize-e,t,r));{let s=this.requestSlice(e,r),n=o=>{if(o)return o;let a=l=>(k(l!==null),this.requestSlice(e,lo(l-e,t,r))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return s instanceof Promise?s.then(n):n(s)}}},li=class i{constructor(e,t,r,s,n){this.bytes=e,this.view=t,this.offset=r,this.start=s,this.end=n,this.bufferPos=s-r}static tempFromBytes(e){return new i(e,oe(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}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 i(this.bytes,this.view,this.offset,e,e+t)}},W=(i,e)=>{let t=i.bytes.subarray(i.bufferPos,i.bufferPos+e);return i.bufferPos+=e,t},z=i=>i.view.getUint8(i.bufferPos++),ui=(i,e)=>{let t=i.view.getUint16(i.bufferPos,e);return i.bufferPos+=2,t},Ce=i=>{let e=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,e},hi=i=>{let e=Ce(i),t=z(i);return e*256+t},_s=i=>{let e=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,e},Gt=(i,e)=>{let t=i.view.getUint32(i.bufferPos,e);return i.bufferPos+=4,t},B=i=>{let e=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,e},Fr=i=>{let e=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,e},Nt=i=>{let e=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,e},F_=i=>{let e=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,e},bl=(i,e)=>{let t,r;return e?(t=Gt(i,!0),r=Gt(i,!0)):(r=Gt(i,!1),t=Gt(i,!1)),r*4294967296+t},Ye=i=>{let e=B(i),t=B(i);return e*4294967296+t},If=i=>{let e=Nt(i),t=B(i);return e*4294967296+t},Mf=i=>{let e=Fr(i);return F_(i)*4294967296+e},Bf=i=>{let e=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,e},So=i=>{let e=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,e},de=(i,e)=>{if(i.bufferPos+e>i.bytes.length)throw new RangeError("Reading past end of slice.");let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(i.bytes[i.bufferPos++]);return t};var Lt=8,Dr=16,bt=i=>{let e=B(i),t=de(i,4),r=8;e===1&&(e=Ye(i),r=16);let n=e-r;return n<0?null:{name:t,totalSize:e,headerSize:r,contentSize:n}},or=i=>Nt(i)/65536,To=i=>Nt(i)/1073741824,ko=i=>{let e=0;for(let t=0;t<4;t++){e<<=7;let r=z(i);if(e|=r&127,(r&128)===0)break}return e},at=i=>{let e=Ce(i);return i.skip(2),Be.decode(W(i,e))},Ff=i=>{let e=bt(i);if(!e||e.name!=="data")return null;let t=B(i);i.skip(4);let r=W(i,e.contentSize-8);switch(t){case 1:return Be.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new nr(r,"image/jpeg");case 14:return new nr(r,"image/png");case 27:return new nr(r,"image/bmp");default:return r}};var I;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Duration=17545]="Duration",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.MuxingApp=19840]="MuxingApp",i[i.WritingApp=22337]="WritingApp",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.TrackNumber=215]="TrackNumber",i[i.TrackUID=29637]="TrackUID",i[i.TrackType=131]="TrackType",i[i.FlagEnabled=185]="FlagEnabled",i[i.FlagDefault=136]="FlagDefault",i[i.FlagForced=21930]="FlagForced",i[i.FlagLacing=156]="FlagLacing",i[i.Name=21358]="Name",i[i.Language=2274716]="Language",i[i.LanguageBCP47=2274717]="LanguageBCP47",i[i.CodecID=134]="CodecID",i[i.CodecPrivate=25506]="CodecPrivate",i[i.CodecDelay=22186]="CodecDelay",i[i.SeekPreRoll=22203]="SeekPreRoll",i[i.DefaultDuration=2352003]="DefaultDuration",i[i.Video=224]="Video",i[i.PixelWidth=176]="PixelWidth",i[i.PixelHeight=186]="PixelHeight",i[i.Audio=225]="Audio",i[i.SamplingFrequency=181]="SamplingFrequency",i[i.Channels=159]="Channels",i[i.BitDepth=25188]="BitDepth",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.Block=161]="Block",i[i.BlockAdditions=30113]="BlockAdditions",i[i.BlockMore=166]="BlockMore",i[i.BlockAdditional=165]="BlockAdditional",i[i.BlockAddID=238]="BlockAddID",i[i.BlockDuration=155]="BlockDuration",i[i.ReferenceBlock=251]="ReferenceBlock",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.Colour=21936]="Colour",i[i.MatrixCoefficients=21937]="MatrixCoefficients",i[i.TransferCharacteristics=21946]="TransferCharacteristics",i[i.Primaries=21947]="Primaries",i[i.Range=21945]="Range",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPoseRoll=30325]="ProjectionPoseRoll",i[i.Attachments=423732329]="Attachments",i[i.AttachedFile=24999]="AttachedFile",i[i.FileDescription=18046]="FileDescription",i[i.FileName=18030]="FileName",i[i.FileMediaType=18016]="FileMediaType",i[i.FileData=18012]="FileData",i[i.FileUID=18094]="FileUID",i[i.Chapters=272869232]="Chapters",i[i.Tags=307544935]="Tags",i[i.Tag=29555]="Tag",i[i.Targets=25536]="Targets",i[i.TargetTypeValue=26826]="TargetTypeValue",i[i.TargetType=25546]="TargetType",i[i.TagTrackUID=25541]="TagTrackUID",i[i.TagEditionUID=25545]="TagEditionUID",i[i.TagChapterUID=25540]="TagChapterUID",i[i.TagAttachmentUID=25542]="TagAttachmentUID",i[i.SimpleTag=26568]="SimpleTag",i[i.TagName=17827]="TagName",i[i.TagLanguage=17530]="TagLanguage",i[i.TagString=17543]="TagString",i[i.TagBinary=17541]="TagBinary"})(I||(I={}));var D_=[I.EBML,I.Segment],di=[I.SeekHead,I.Info,I.Cluster,I.Tracks,I.Cues,I.Attachments,I.Chapters,I.Tags],vo=[...D_,...di];var wl=8,Ve=2,ct=2*wl,_l=i=>{let e=z(i);if(i.skip(-1),e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;return t},fi=i=>{let e=z(i);if(e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;let s=e&r-1;for(let n=1;n<t;n++)s*=256,s+=z(i);return s},J=(i,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let r=0;r<e;r++)t*=256,t+=z(i);return t},Df=(i,e)=>{let t=J(i,e);return t&1<<e*8-1&&(t-=2**(e*8)),t},Po=i=>{let e=_l(i);return e===null?null:J(i,e)},Sl=i=>{let e=z(i);return e===255?e=null:(i.skip(-1),e=fi(i),e===72057594037927940&&(e=null)),e},lt=i=>{let e=Po(i);if(e===null)return null;let t=Sl(i);return{id:e,size:t}},ar=(i,e)=>{let t=W(i,e),r=0;for(;r<e&&t[r]!==0;)r+=1;return String.fromCharCode(...t.subarray(0,r))},mi=(i,e)=>{let t=W(i,e),r=0;for(;r<e&&t[r]!==0;)r+=1;return Be.decode(t.subarray(0,r))},Co=(i,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Bf(i):So(i)},Eo=async(i,e,t,r)=>{let s=new Set(t),n=e;for(;r===null||n<r;){let o=i.requestSliceRange(n,Ve,ct);if(o instanceof Promise&&(o=await o),!o)break;let a=lt(o);if(!a)break;if(s.has(a.id))return{pos:n,found:!0};Vt(a.size),n=o.filePos+a.size}return{pos:r!==null&&r>n?r:n,found:!1}},Tl=async(i,e,t,r)=>{let n=new Set(t),o=e;for(;o<r;){let a=i.requestSliceRange(o,0,Math.min(65536,r-o));if(a instanceof Promise&&(a=await a),!a||a.length<wl)break;for(let c=0;c<a.length-wl;c++){a.filePos=o;let l=Po(a);if(l!==null&&n.has(l))return o;o++}}return null},ut={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 Vt(i){if(i===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Rf=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};var R_={1:[-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],2:[-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],3:[-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1]},O_={1:[-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],2:[-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1],3:[-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1]},U_={0:[11025,12e3,8e3,-1],2:[22050,24e3,16e3,-1],3:[44100,48e3,32e3,-1]},Of=1483304551,Uf=1231971951,z_=(i,e,t,r)=>Math.floor(i===3?(12*e/t+r)*4:144*e/t+r),zf=(i,e)=>i===3?e===3?21:36:e===3?13:21,Gf=(i,e)=>{let t=i>>>24,r=i>>>16&255,s=i>>>8&255,n=i&255;if(t!==255&&r!==255&&s!==255&&n!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let o=r>>3&3,a=r>>1&3,c=s>>4&15,l=s>>2&3,u=s>>1&1,h=n>>6&3,d=n>>4&3,f=n>>3&1,m=n>>2&1,p=n&3,g=o===3?R_[a]?.[c]:O_[a]?.[c];if(!g||g===-1)return{header:null,bytesAdvanced:1};let y=g*1e3,x=U_[o]?.[l];if(!x||x===-1)return{header:null,bytesAdvanced:1};let w=z_(a,y,x,u);if(e!==null&&e<w)return{header:null,bytesAdvanced:1};let _;return o===3?_=a===3?384:1152:a===3?_=384:a===2?_=1152:_=576,{header:{totalSize:w,mpegVersionId:o,layer:a,bitrate:y,frequencyIndex:l,sampleRate:x,channel:h,modeExtension:d,copyright:f,original:m,emphasis:p,audioSamplesInFrame:_},bytesAdvanced:1}};var Ao=i=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=i&e,e>>=8;return t};var gi;(function(i){i[i.Unsynchronisation=128]="Unsynchronisation",i[i.ExtendedHeader=64]="ExtendedHeader",i[i.ExperimentalIndicator=32]="ExperimentalIndicator",i[i.Footer=16]="Footer"})(gi||(gi={}));var xi;(function(i){i[i.ISO_8859_1=0]="ISO_8859_1",i[i.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",i[i.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",i[i.UTF_8=3]="UTF_8"})(xi||(xi={}));var Ss=128,bi=10,yi=["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"],Ts=async(i,e,t)=>{let r=e;for(;t===null||r<t;){let s=i.requestSlice(r,4);if(s instanceof Promise&&(s=await s),!s)break;let n=B(s),o=Gf(n,i.fileSize!==null?i.fileSize-r:null);if(o.header)return{header:o.header,startPos:r};r+=o.bytesAdvanced}return null},Lf=(i,e)=>{let t=i.filePos;e.raw??={},e.raw.TAG??=W(i,Ss-3),i.filePos=t;let r=pi(i,30);r&&(e.title??=r);let s=pi(i,30);s&&(e.artist??=s);let n=pi(i,30);n&&(e.album??=n);let o=pi(i,4),a=Number.parseInt(o,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=W(i,30),l;if(c[28]===0&&c[29]!==0){let h=c[29];h>0&&(e.trackNumber??=h),i.skip(-30),l=pi(i,28),i.skip(2)}else i.skip(-30),l=pi(i,30);l&&(e.comment??=l);let u=z(i);u<yi.length&&(e.genre??=yi[u])},pi=(i,e)=>{let t=W(i,e),r=Mr(t.indexOf(0),t.length),s=t.subarray(0,r),n="";for(let o=0;o<s.length;o++)n+=String.fromCharCode(s[o]);return n.trimEnd()},ks=i=>{let e=i.filePos,t=de(i,3),r=z(i),s=z(i),n=z(i),o=B(i);if(t!=="ID3"||r===255||s===255||(o&2155905152)!==0)return i.filePos=e,null;let a=Ao(o);return{majorVersion:r,revision:s,flags:n,size:a}},Vf=(i,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let r=W(i,e.size),s=new kl(e,r);if(e.flags&gi.Footer&&s.removeFooter(),e.flags&gi.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&gi.ExtendedHeader){let n=s.readU32();e.majorVersion===3?s.pos+=n:s.pos+=n-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){let n=s.readId3V2Frame();if(!n)break;let o=s.pos,a=s.pos+n.size,c=!1,l=!1,u=!1;if(e.majorVersion===3?(c=!!(n.flags&64),l=!!(n.flags&128)):e.majorVersion===4&&(c=!!(n.flags&4),l=!!(n.flags&8),u=!!(n.flags&2)||!!(e.flags&gi.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${n.id}`),s.pos=a;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${n.id}`),s.pos=a;continue}switch(u&&s.ununsynchronizeRegion(s.pos,a),t.raw??={},n.id[0]==="T"?t.raw[n.id]??=s.readId3V2EncodingAndText(a):t.raw[n.id]??=s.readBytes(n.size),s.pos=o,n.id){case"TIT2":case"TT2":t.title??=s.readId3V2EncodingAndText(a);break;case"TIT3":case"TT3":t.description??=s.readId3V2EncodingAndText(a);break;case"TPE1":case"TP1":t.artist??=s.readId3V2EncodingAndText(a);break;case"TALB":case"TAL":t.album??=s.readId3V2EncodingAndText(a);break;case"TPE2":case"TP2":t.albumArtist??=s.readId3V2EncodingAndText(a);break;case"TRCK":case"TRK":{let d=s.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(d[0],10),m=d[1]&&Number.parseInt(d[1],10);Number.isInteger(f)&&f>0&&(t.trackNumber??=f),m&&Number.isInteger(m)&&m>0&&(t.tracksTotal??=m)}break;case"TPOS":case"TPA":{let d=s.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(d[0],10),m=d[1]&&Number.parseInt(d[1],10);Number.isInteger(f)&&f>0&&(t.discNumber??=f),m&&Number.isInteger(m)&&m>0&&(t.discsTotal??=m)}break;case"TCON":case"TCO":{let h=s.readId3V2EncodingAndText(a),d=/^\((\d+)\)/.exec(h);if(d){let f=Number.parseInt(d[1]);if(yi[f]!==void 0){t.genre??=yi[f];break}}if(d=/^\d+$/.exec(h),d){let f=Number.parseInt(d[0]);if(yi[f]!==void 0){t.genre??=yi[f];break}}t.genre??=h}break;case"TDRC":case"TDAT":{let h=s.readId3V2EncodingAndText(a),d=new Date(h);Number.isNaN(d.getTime())||(t.date??=d)}break;case"TYER":case"TYE":{let h=s.readId3V2EncodingAndText(a),d=Number.parseInt(h,10);Number.isInteger(d)&&(t.date??=new Date(d,0,1))}break;case"USLT":case"ULT":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,a),t.lyrics??=s.readId3V2Text(h,a)}break;case"COMM":case"COM":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,a),t.comment??=s.readId3V2Text(h,a)}break;case"APIC":case"PIC":{let h=s.readId3V2TextEncoding(),d;if(e.majorVersion===2){let g=s.readAscii(3);d=g==="PNG"?"image/png":g==="JPG"?"image/jpeg":"image/*"}else d=s.readId3V2Text(h,a);let f=s.readU8(),m=s.readId3V2Text(h,a).trimEnd(),p=a-s.pos;if(p>=0){let g=s.readBytes(p);t.images||(t.images=[]),t.images.push({data:g,mimeType:d,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=n.size;break}s.pos=a}},kl=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let r=this.bytes[t];e.push(r),r===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let r=[];for(let o=e;o<t;o++){let a=this.bytes[o];r.push(a),a===255&&o!==t-1&&this.bytes[o+1]===0&&o++}let s=this.bytes.subarray(0,e),n=this.bytes.subarray(t);this.bytes=new Uint8Array(s.length+r.length+n.length),this.bytes.set(s,0),this.bytes.set(r,s.length),this.bytes.set(n,s.length+r.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-bi),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),r=this.header.majorVersion===4?Ao(t):t,s=this.readU16(),n=this.pos,o=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(!o(r)){let a=this.header.majorVersion===4?t:Ao(t);o(a)&&(r=a)}return this.pos=n,{id:e,size:r,flags:s}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let r=this.pos,s=this.readBytes(t);switch(e){case xi.ISO_8859_1:{let n="";for(let o=0;o<s.length;o++){let a=s[o];if(a===0){this.pos=r+o+1;break}n+=String.fromCharCode(a)}return n}case xi.UTF_16_WITH_BOM:if(s[0]===255&&s[1]===254){let n=new TextDecoder("utf-16le"),o=Mr(s.findIndex((a,c)=>a===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(o+2,s.length),n.decode(s.subarray(2,o))}else if(s[0]===254&&s[1]===255){let n=new TextDecoder("utf-16be"),o=Mr(s.findIndex((a,c)=>a===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(o+2,s.length),n.decode(s.subarray(2,o))}else{let n=Mr(s.findIndex(o=>o===0),s.length);return this.pos=r+Math.min(n+1,s.length),Be.decode(s.subarray(0,n))}case xi.UTF_16_BE_NO_BOM:{let n=new TextDecoder("utf-16be"),o=Mr(s.findIndex((a,c)=>a===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(o+2,s.length),n.decode(s.subarray(0,o))}case xi.UTF_8:{let n=Mr(s.findIndex(o=>o===0),s.length);return this.pos=r+Math.min(n+1,s.length),Be.decode(s.subarray(0,n))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var vl=1399285583,G_=79764919,Wf=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^G_:e<<1;Wf[i]=e>>>0&4294967295}var Hf=i=>{let e=oe(i),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let s=0;s<i.length;s++){let n=i[s];r=(r<<8^Wf[r>>>24^n])>>>0}return e.setUint32(22,t,!0),r},jf=(i,e,t)=>{let r=0,s=null;if(i.length>0)if(e.codec==="vorbis"){k(e.vorbisInfo);let n=e.vorbisInfo.modeBlockflags.length,a=(1<<mf(n-1))-1<<1,c=(i[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,u=e.vorbisInfo.modeBlockflags[c];if(s=e.vorbisInfo.blocksizes[u],u===1){let h=(a|1)+1,d=i[0]&h?1:0;l=e.vorbisInfo.blocksizes[d]}r=l!==null?l+s>>2:0}else e.codec==="opus"&&(r=Pf(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:s}},$f=i=>{let e="audio/ogg";if(i.codecStrings){let t=[...new Set(i.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var cr=27,Rr=282,qf=Rr+65025,wi=i=>{let e=i.filePos;if(Fr(i)!==vl)return null;i.skip(1);let r=z(i),s=Mf(i),n=Fr(i),o=Fr(i),a=Fr(i),c=z(i),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=z(i);let u=27+c,h=l.reduce((f,m)=>f+m,0),d=u+h;return{headerStartPos:e,totalSize:d,dataStartPos:e+u,dataSize:h,headerType:r,granulePosition:s,serialNumber:n,sequenceNumber:o,checksum:a,lacingValues:l}},Xf=(i,e)=>{for(;i.filePos<e-3;){let t=Fr(i),r=t&255,s=t>>>8&255,n=t>>>16&255,o=t>>>24&255,a=79;if(!(r!==a&&s!==a&&n!==a&&o!==a)){if(i.skip(-4),t===vl)return!0;i.skip(1)}}return!1};var We=class{constructor(e){this.input=e}};var Io=[],Pl=[];var Ee=new Uint8Array(0),ce=class i{constructor(e,t,r,s,n=-1,o){if(this.data=e,this.type=t,this.timestamp=r,this.duration=s,this.sequenceNumber=n,e===Ee&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(s)||s<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");this.byteLength=o}get isMetadataOnly(){return this.data===Ee}get microsecondTimestamp(){return Math.trunc(sr*this.timestamp)}get microsecondDuration(){return Math.trunc(sr*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})}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){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let t=new Uint8Array(e.byteLength);return e.copyTo(t),new i(t,e.type,e.timestamp/1e6,(e.duration??0)/1e6)}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 i(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Ps=class i{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(sr*this.timestamp)}get microsecondDuration(){return Math.trunc(sr*this.duration)}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(!("format"in t)||typeof t.format!="string")throw new TypeError("init.format must be a string.");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=ir(e).slice(),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 VideoColorSpace(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.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=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 i(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*sr),duration:Math.trunc((t.duration??0)*sr)}),t);let r=0,s=0;if("naturalWidth"in e?(r=e.naturalWidth,s=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,s=e.videoHeight):"width"in e&&(r=Number(e.width),s=Number(e.height)),!r||!s)throw new TypeError("Could not determine dimensions.");let n=new OffscreenCanvas(r,s),o=n.getContext("2d",{alpha:!1,willReadFrequently:!0});k(o),o.drawImage(e,0,0),this._data=n,this.format="RGBX",this.codedWidth=r,this.codedHeight=s,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.")}clone(){if(this._closed)throw new Error("VideoSample is closed.");return k(this._data!==null),vs(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new i(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new i(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||(vs(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return k(this._data!==null),vs(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!ll(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if(k(this._data!==null),vs(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)ir(e).set(this._data);else{let r=this._data.getContext("2d",{alpha:!1});k(r);let s=r.getImageData(0,0,this.codedWidth,this.codedHeight);ir(e).set(s.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return k(this._data!==null),vs(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,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}draw(e,t,r,s,n,o,a,c,l){let u=0,h=0,d=this.displayWidth,f=this.displayHeight,m=0,p=0,g=this.displayWidth,y=this.displayHeight;if(o!==void 0?(u=t,h=r,d=s,f=n,m=o,p=a,c!==void 0?(g=c,y=l):(g=d,y=f)):(m=t,p=r,s!==void 0&&(g=s,y=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(h))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");this.rotation===90?[u,h,d,f]=[h,this.codedHeight-u-d,f,d]:this.rotation===180?[u,h]=[this.codedWidth-u-d,this.codedHeight-h-f]:this.rotation===270&&([u,h,d,f]=[this.codedWidth-h-f,u,f,d]);let x=this.toCanvasImageSource();e.save();let w=m+g/2,_=p+y/2;e.translate(w,_),e.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:g/y;e.scale(1/S,S),e.drawImage(x,u,h,d,f,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,t){let r=e.canvas.width,s=e.canvas.height,n=t.rotation??this.rotation,o,a,c,l;if(t.fit==="fill")o=0,a=0,c=r,l=s;else{let[h,d]=n%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth],f=t.fit==="contain"?Math.min(r/h,s/d):Math.max(r/h,s/d);c=h*f,l=d*f,o=(r-c)/2,a=(s-l)/2}let u=n%180===0?1:c/l;e.translate(r/2,s/2),e.rotate(n*Math.PI/180),e.scale(1/u,u),e.translate(-r/2,-s/2),e.drawImage(this.toCanvasImageSource(),o,a,c,l)}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(k(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}},vs=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame;var _i=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Or=i=>{if(typeof i!="number"||Number.isNaN(i))throw new TypeError("timestamp must be a number.")},Cl=(i,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;let s=await i.determinePacketType(r);return s&&(r.type=s),r}):e,Si=class{constructor(e){if(!(e instanceof Ti))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){return _i(e),Cl(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){return Or(e),_i(t),Cl(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");return _i(t),Cl(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Or(e),_i(t),!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return!r||r.type==="delta"?r:await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(_i(t),!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return!r||r.type==="delta"?r:await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(e!==void 0&&!(e instanceof ce))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof ce))throw new TypeError("endPacket must be an EncodedPacket.");_i(r);let s=[],{promise:n,resolve:o}=Fe(),{promise:a,resolve:c}=Fe(),l=!1,u=!1,h=null,d=[],f=()=>Math.max(2,d.length);return(async()=>{let m=e??await this.getFirstPacket(r);for(;m&&!u&&!(t&&m.sequenceNumber>=t?.sequenceNumber);){if(s.length>f()){({promise:a,resolve:c}=Fe()),await a;continue}s.push(m),o(),{promise:n,resolve:o}=Fe(),m=await this.getNextPacket(m,r)}l=!0,o()})().catch(m=>{h||(h=m,o())}),{async next(){for(;;){if(u)return{value:void 0,done:!0};if(h)throw h;if(s.length>0){let m=s.shift(),p=performance.now();for(d.push(p);d.length>0&&p-d[0]>=1e3;)d.shift();return c(),{value:m,done:!1}}else{if(l)return{value:void 0,done:!0};await n}}},async return(){return u=!0,c(),o(),{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}},El=class{constructor(e,t){this.onSample=e,this.onError=t}},Mo=class{mediaSamplesInRange(e=0,t=1/0){Or(e),Or(t);let r=[],s=!1,n=null,{promise:o,resolve:a}=Fe(),{promise:c,resolve:l}=Fe(),u=!1,h=!1,d=!1,f=null;return(async()=>{let m=new Error,p=await this._createDecoder(S=>{if(l(),S.timestamp>=t&&(h=!0),h){S.close();return}n&&(S.timestamp>e?(r.push(n),s=!0):n.close()),S.timestamp>=e&&(r.push(S),s=!0),n=s?null:S,r.length>0&&(a(),{promise:o,resolve:a}=Fe())},S=>{f||(S.stack=m.stack,f=S,a())}),g=this._createPacketSink(),y=await g.getKeyPacket(e,{verifyKeyPackets:!0})??await g.getFirstPacket();if(!y)return;let x=y,w;if(t<1/0){let S=await g.getPacket(t),T=S?S.type==="key"&&S.timestamp===t?S:await g.getNextKeyPacket(S,{verifyKeyPackets:!0}):null;T&&(w=T)}let _=g.packets(y,w);for(await _.next();x&&!h;){let S=Yf(r.length);if(r.length+p.getDecodeQueueSize()>S){({promise:c,resolve:l}=Fe()),await c;continue}p.decode(x);let T=await _.next();if(T.done)break;x=T.value}await _.return(),d||await p.flush(),p.close(),!s&&n&&r.push(n),u=!0,a()})().catch(m=>{f||(f=m,a())}),{async next(){for(;;){if(d)return{value:void 0,done:!0};if(f)throw f;if(r.length>0){let m=r.shift();return l(),{value:m,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}}},async return(){d=!0,h=!0,l(),a(),n?.close();for(let m of r)m.close();return{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){df(e);let t=hf(e),r=[],s=[],{promise:n,resolve:o}=Fe(),{promise:a,resolve:c}=Fe(),l=!1,u=!1,h=null,d=f=>{s.push(f),o(),{promise:n,resolve:o}=Fe()};return(async()=>{let f=new Error,m=await this._createDecoder(S=>{if(c(),u){S.close();return}let T=0;for(;r.length>0&&S.timestamp-r[0]>-1e-10;)T++,r.shift();if(T>0)for(let v=0;v<T;v++)d(v<T-1?S.clone():S);else S.close()},S=>{h||(S.stack=f.stack,h=S,o())}),p=this._createPacketSink(),g=null,y=null,x=-1,w=async()=>{k(y);let S=y;for(m.decode(S);S.sequenceNumber<x;){let T=Yf(s.length);for(;s.length+m.getDecodeQueueSize()>T&&!u;)({promise:a,resolve:c}=Fe()),await a;if(u)break;let v=await p.getNextPacket(S);k(v),m.decode(v),S=v}x=-1},_=async()=>{await m.flush();for(let S=0;S<r.length;S++)d(null);r.length=0};for await(let S of t){if(Or(S),u)break;let T=await p.getPacket(S),v=T&&await p.getKeyPacket(S,{verifyKeyPackets:!0});if(!v){x!==-1&&(await w(),await _()),d(null),g=null;continue}g&&(v.sequenceNumber!==y.sequenceNumber||T.timestamp<g.timestamp)&&(await w(),await _()),r.push(T.timestamp),x=Math.max(T.sequenceNumber,x),g=T,y=v}u||(x!==-1&&await w(),await _()),m.close(),l=!0,o()})().catch(f=>{h||(h=f,o())}),{async next(){for(;;){if(u)return{value:void 0,done:!0};if(h)throw h;if(s.length>0){let f=s.shift();return k(f!==void 0),c(),{value:f,done:!1}}else if(!l)await n;else return{value:void 0,done:!0}}},async return(){u=!0,c(),o();for(let f of s)f?.close();return{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}},Yf=i=>i===0?40:8,Al=class extends El{constructor(e,t,r,s,n,o){super(e,t),this.codec=r,this.decoderConfig=s,this.rotation=n,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new io,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1;let a=Io.find(c=>c.supports(r,s));if(a)this.customDecoder=new a,this.customDecoder.codec=r,this.customDecoder.config=s,this.customDecoder.onSample=c=>{if(!(c instanceof Ps))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=l=>{if(fo()){if(this.sampleQueue.length>0&&l.timestamp>=ve(this.sampleQueue).timestamp){for(let u of this.sampleQueue)this.finalizeAndEmitSample(u);this.sampleQueue.length=0}ot(this.sampleQueue,l,u=>u.timestamp)}else{let u=this.inputTimestamps.shift();k(u!==void 0),l.setTimestamp(u),this.finalizeAndEmitSample(l)}};this.decoder=new VideoDecoder({output:l=>c(new Ps(l)),error:t}),this.decoder.configure(s)}}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)}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(k(this.decoder),this.decoder.decodeQueueSize)}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(yl(e.data,this.decoderConfig).some(s=>{let n=zt(s);return n===De.RASL_N||n===De.RASL_R}))return;this.raslSkipped=!0}this.currentPacketIndex++,this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(k(this.decoder),fo()||ot(this.inputTimestamps,e.timestamp,t=>t),this.decoder.decode(e.toEncodedVideoChunk()))}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(k(this.decoder),await this.decoder.flush()),fo()){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()):(k(this.decoder),this.decoder.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Bo=class extends Mo{constructor(e){if(!(e instanceof wt))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._videoTrack=e}async _createDecoder(e,t){if(!await this._videoTrack.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._videoTrack.codec,s=this._videoTrack.rotation,n=await this._videoTrack.getDecoderConfig(),o=this._videoTrack.timeResolution;return k(r&&n),new Al(e,t,r,n,s,o)}_createPacketSink(){return new Si(this._videoTrack)}async getSample(e){Or(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)}},Cs=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof wt))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");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.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let r=t.rotation??e.rotation,[s,n]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],o=s/n;t.width!==void 0&&t.height===void 0?(s=t.width,n=Math.round(s/o)):t.width===void 0&&t.height!==void 0?(n=t.height,s=Math.round(n*o)):t.width!==void 0&&t.height!==void 0&&(s=t.width,n=t.height),this._videoTrack=e,this._width=s,this._height=n,this._rotation=r,this._fit=t.fit??"fill",this._videoSampleSink=new Bo(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],r=!1;t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),r=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let s=t.getContext("2d",{alpha:!1});k(s),s.resetTransform(),r||s.clearRect(0,0,this._width,this._height),e.drawWithFit(s,{fit:this._fit,rotation:this._rotation});let n={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e){Or(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return fl(this._videoSampleSink.samples(e,t),r=>this._videoSampleToWrappedCanvas(r))}canvasesAtTimestamps(e){return fl(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}};var Ti=class{constructor(e){this._backing=e}isVideoTrack(){return this instanceof wt}isAudioTrack(){return this instanceof Ae}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()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new Si(this),r=1/0,s=-1/0,n=0,o=0;for await(let a of t.packets(void 0,void 0,{metadataOnly:!0})){if(n>=e&&a.timestamp>=s)break;r=Math.min(r,a.timestamp),s=Math.max(s,a.timestamp+a.duration),n++,o+=a.byteLength}return{packetCount:n,averagePacketRate:n?Number((n/(s-r)).toPrecision(16)):0,averageBitrate:n?Number((8*o/(s-r)).toPrecision(16)):0}}},wt=class extends Ti{constructor(e){super(e),this._backing=e}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"}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 k(t!==null),Io.some(s=>s.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 ce))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");return this.codec===null?null:Ef(this,e)}},Ae=class extends Ti{constructor(e){super(e),this._backing=e}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 k(t!==null),Pl.some(r=>r.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Wt;(function(i){i[i.PCM=1]="PCM",i[i.IEEE_FLOAT=3]="IEEE_FLOAT",i[i.ALAW=6]="ALAW",i[i.MULAW=7]="MULAW",i[i.EXTENSIBLE=65534]="EXTENSIBLE"})(Wt||(Wt={}));var Fo=class extends We{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),k(e);let t=de(e,4),r=t!=="RIFX",s=t==="RF64",n=Gt(e,r),o=s?this.reader.fileSize:Math.min(n+8,this.reader.fileSize??1/0);if(de(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;o===null||u<o;){let d=this.reader.requestSlice(u,8);if(d instanceof Promise&&(d=await d),!d)break;let f=de(d,4),m=Gt(d,r),p=d.filePos;if(s&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(p,m,r);else if(f==="data"){if(l??=m,this.dataStart=d.filePos,this.dataSize=Math.min(l,(o??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let g=bl(d,r);l=bl(d,r),o=Math.min(g+8,this.reader.fileSize??1/0)}else f==="LIST"&&await this.parseListChunk(p,m,r);u=p+m+(m&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 h=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/h)*h,this.tracks.push(new Ae(new Il(this)))})()}async parseFmtChunk(e,t,r){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;let n=ui(s,r),o=ui(s,r),a=Gt(s,r);s.skip(4);let c=ui(s,r),l;if(t===14?l=8:l=ui(s,r),t>=18&&n!==357){let u=ui(s,r),h=t-18;if(Math.min(h,u)>=22&&n===Wt.EXTENSIBLE){s.skip(6);let f=W(s,16);n=f[0]|f[1]<<8}}(n===Wt.MULAW||n===Wt.ALAW)&&(l=8),this.audioInfo={format:n,numberOfChannels:o,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,r){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;let n=de(s,4);if(n!=="INFO"&&n!=="INF0")return;let o=s.filePos;for(;o<=e+t-8;){s.filePos=o;let a=de(s,4),c=Gt(s,r),l=W(s,c),u=0;for(let d=0;d<l.length&&l[d]!==0;d++)u++;let h=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=h,a){case"INAM":case"TITL":this.metadataTags.title??=h;break;case"TIT3":this.metadataTags.description??=h;break;case"IART":this.metadataTags.artist??=h;break;case"IPRD":this.metadataTags.album??=h;break;case"IPRT":case"ITRK":case"TRCK":{let d=h.split("/"),f=Number.parseInt(d[0],10),m=d[1]&&Number.parseInt(d[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),m&&Number.isInteger(m)&&m>0&&(this.metadataTags.tracksTotal??=m)}break;case"ICRD":case"IDIT":{let d=new Date(h);Number.isNaN(d.getTime())||(this.metadataTags.date??=d)}break;case"YEAR":{let d=Number.parseInt(h,10);Number.isInteger(d)&&d>0&&(this.metadataTags.date??=new Date(d,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=h;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=h;break}o+=8+c+(c&1)}}getCodec(){if(k(this.audioInfo),this.audioInfo.format===Wt.MULAW)return"ulaw";if(this.audioInfo.format===Wt.ALAW)return"alaw";if(this.audioInfo.format===Wt.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===Wt.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 k(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},ki=2048,Il=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return k(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(k(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 k(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return k(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return k(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Pe}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){k(this.demuxer.audioInfo);let r=e*ki*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let s=Math.min(ki*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,s);if(c instanceof Promise&&(c=await c),!c)return null}let n;if(t.metadataOnly)n=Ee;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,s);c instanceof Promise&&(c=await c),k(c),n=W(c,s)}let o=e*ki/this.demuxer.audioInfo.sampleRate,a=s/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,o),new ce(n,"key",o,a,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){k(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/ki,(this.demuxer.dataSize-1)/(ki*this.demuxer.audioInfo.blockSizeInBytes))),s=await this.getPacketAtIndex(r,t);if(s)return s;if(r===0)return null;k(this.demuxer.reader.fileSize===null);let n=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){let o=await this.getNextPacket(n,t);if(!o)break;n=o}return n}getNextPacket(e,t){k(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ki);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Ur=class{constructor(){this._sizePromise=null,this.onread=null}async getSizeOrNull(){return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var Es=class extends Ur{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&&(!Number.isInteger(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative integer.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Do({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Zf.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||(t=this._blob.slice(e.currentPos).stream().getReader(),this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;){let{done:r,value:s}=await t.read();if(r){if(this._orchestrator.forgetWorker(e),e.currentPos<e.targetPos)throw new Error("Blob reader stopped unexpectedly before all requested data was read.");break}this.onread?.(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}e.running=!1}get _supportsRandomAccess(){return!0}},Kf=.5*2**20,As=class extends Ur{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL))throw new TypeError("url must be a string or URL.");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&&(!Number.isInteger(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative integer.");super(),this._existingResponses=new WeakMap,this._url=e instanceof URL?e:new URL(e,typeof location<"u"?location.href:void 0),this._options=t,this._getRetryDelay=t.getRetryDelay??(r=>Math.min(2**(r-2),8)),this._orchestrator=new Do({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Zf.network})}async _retrieveSize(){let e=new AbortController,t=await ml(this._url,ho(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay);if(!t.ok)throw new Error(`Error fetching ${this._url}: ${t.status} ${t.statusText}`);let r,s;if(t.status===206)s=this._getPartialLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(s,Kf));else{let n=t.headers.get("Content-Length");if(n)s=Number(n),r=this._orchestrator.createWorker(0,s),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=s,this._existingResponses.set(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),s}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;!e.aborted;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let r=t?.abortController,s=t?.response;if(r||(r=new AbortController,s=await ml(this._url,ho(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay)),k(s),!s.ok)throw new Error(`Error fetching ${this._url}: ${s.status} ${s.statusText}`);if(e.currentPos>0&&s.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.");let n=this._getPartialLengthFromRangeResponse(s),o=e.targetPos-e.currentPos;if(n<o)throw new Error(`HTTP response unexpectedly too short: Needed at least ${o} bytes, got only ${n}.`);if(!s.body)throw new Error("Missing HTTP response body.");let a=s.body.getReader();for(;;){let c;try{c=await a.read()}catch(h){let d=this._getRetryDelay(1);if(d!==null){console.error("Error while reading response stream. Attempting to resume.",h),await new Promise(f=>setTimeout(f,1e3*d));break}else throw h}let{done:l,value:u}=c;if(l){if(this._orchestrator.forgetWorker(e),e.currentPos<e.targetPos)throw new Error("Response stream reader stopped unexpectedly before all requested data was read.");e.running=!1;return}if(this.onread?.(e.currentPos,e.currentPos+u.length),this._orchestrator.supplyWorkerData(e,u),e.currentPos>=e.targetPos||e.aborted){r.abort(),e.running=!1;return}}}e.running=!1}_getPartialLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let r=/\/(\d+)/.exec(t);if(r)return Number(r[1]);throw new Error(`Invalid Content-Range header: ${t}`)}else{let r=e.headers.get("Content-Length");if(r)return Number(r);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}}get _supportsRandomAccess(){return!0}};var Zf={none:(i,e)=>({start:i,end:e}),fileSystem:(i,e)=>(i=Math.floor((i-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:i,end:e}),network:(i,e,t)=>{i=Math.max(0,Math.floor((i-65536)/65536)*65536);for(let s of t){let o=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(mo(i,e,o,s.targetPos)){let a=s.targetPos-s.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),u=Math.min(l,c);e=Math.max(e,s.startPos+u)}}return e=Math.max(e,i+Kf),{start:i,end:e}}},Do=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0}read(e,t){k(this.fileSize!==null);let r=this.options.prefetchProfile(e,t,this.workers),s=Math.max(r.start,0),n=Math.min(r.end,this.fileSize);k(s<=e&&t<=n);let o=null,a=Q(this.cache,e,x=>x.start),c=a!==-1?this.cache[a]:null;c&&c.start<=e&&t<=c.end&&(c.age=this.nextAge++,o={bytes:c.bytes,view:c.view,offset:c.start});let l=Q(this.cache,s,x=>x.start),u=o?null:new Uint8Array(t-e),h=0,d=s,f=[];if(l!==-1){for(let x=l;x<this.cache.length;x++){let w=this.cache[x];if(w.start>=n)break;if(w.end<=s)continue;let _=Math.max(s,w.start),S=Math.min(n,w.end);if(k(_<=S),d<_&&f.push({start:d,end:_}),d=S,u){let T=Math.max(e,w.start),v=Math.min(t,w.end);if(T<v){let M=T-e;u.set(w.bytes.subarray(T-w.start,v-w.start),M),M===h&&(h=v-e)}}w.age=this.nextAge++}d<n&&f.push({start:d,end:n})}else f.push({start:s,end:n});if(u&&h>=u.length&&(o={bytes:u,view:oe(u),offset:e}),f.length===0)return k(o),o;let{promise:m,resolve:p,reject:g}=Fe(),y=[];for(let x of f){let w=Math.max(e,x.start),_=Math.min(t,x.end);w===x.start&&_===x.end?y.push(x):w<_&&y.push({start:w,end:_})}for(let x of f){let w=u&&{start:e,bytes:u,holes:y,resolve:p,reject:g},_=!1;for(let S of this.workers)if(mo(x.start-131072,x.start,S.currentPos,S.targetPos)){S.targetPos=Math.max(S.targetPos,x.end),_=!0,w&&!S.pendingSlices.includes(w)&&S.pendingSlices.push(w),S.running||this.runWorker(S);break}if(!_){let S=this.createWorker(x.start,x.end);w&&(S.pendingSlices=[w]),this.runWorker(S)}}return o||(k(u),o=m.then(x=>({bytes:x,view:oe(x),offset:e}))),o}createWorker(e,t){let r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:!1,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let s=0,n=this.workers[0];for(let o=1;o<this.workers.length;o++){let a=this.workers[o];a.age<n.age&&(s=o,n=a)}if(n.running&&n.pendingSlices.length>0)break;n.aborted=!0,this.workers.splice(s,1)}return r}runWorker(e){k(!e.running),k(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(r=>r.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){let r=e.currentPos,s=r+t.length;this.insertIntoCache({start:r,end:s,bytes:t,view:oe(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let n=0;n<e.pendingSlices.length;n++){let o=e.pendingSlices[n],a=Math.max(r,o.start),c=Math.min(s,o.start+o.bytes.length);a<c&&o.bytes.set(t.subarray(a-r,c-r),a-o.start);for(let l=0;l<o.holes.length;l++){let u=o.holes[l];r<=u.start&&s>u.start&&(u.start=s),u.end<=u.start&&(o.holes.splice(l,1),l--)}o.holes.length===0&&(o.resolve(o.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;n<this.workers.length;n++){let o=this.workers[n];e===o||o.running||mo(r,s,o.currentPos,o.targetPos)&&(this.workers.splice(n,1),n--)}}forgetWorker(e){let t=this.workers.indexOf(e);k(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=Q(this.cache,e.start,r=>r.start)+1;if(t>0){let r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){let s=new Uint8Array(e.end-r.start);s.set(r.bytes,0),s.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=s,r.view=oe(s),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){let s=this.cache[r];if(e.end<=s.start)break;if(e.end>=s.end){this.cache.splice(r,1),this.currentCacheSize-=s.bytes.length,r--;continue}let n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=oe(n),e.end=s.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,s=this.cache[0];for(let n=1;n<this.cache.length;n++){let o=this.cache[n];o.age<s.age&&(r=n,s=o)}if(this.currentCacheSize-s.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,1),this.currentCacheSize-=s.bytes.length}}};var N_=new Set(["@day","@mak","@mod","@swr","@xyz","CAME","CNCV","CNFV","CNMN","FIRM","FOV\0","GoPr","LENS","PXMN","SIGM","SNum","TAGS","albm","albr","angl","auth","ccid","cdis","clfn","clid","clsf","cmid","cmnm","coll","cprt","cver","cvru","date","dscp","fsid","gnre","hinv","icnu","info","infu","kgtt","loci","lrcu","mcvr","name","perf","pmcc","reel","rtng","scen","shot","slno","thmb","titl","tnam","urat","uuid","vndr","yrrc","\xA9ART","\xA9TIM","\xA9TSC","\xA9TSZ","\xA9alb","\xA9arg","\xA9ark","\xA9cmt","\xA9cok","\xA9com","\xA9cpy","\xA9day","\xA9dir","\xA9ed1","\xA9ed2","\xA9ed3","\xA9ed4","\xA9ed5","\xA9ed6","\xA9ed7","\xA9ed8","\xA9ed9","\xA9enc","\xA9fmt","\xA9fpt","\xA9frl","\xA9fyw","\xA9gen","\xA9gpt","\xA9grl","\xA9grp","\xA9gyw","\xA9inf","\xA9isr","\xA9lab","\xA9lal","\xA9lyr","\xA9mak","\xA9mal","\xA9mdl","\xA9mod","\xA9nam","\xA9pdk","\xA9phg","\xA9prd","\xA9prf","\xA9prk","\xA9prl","\xA9req","\xA9snk","\xA9snm","\xA9src","\xA9swf","\xA9swk","\xA9swr","\xA9too","\xA9trk","\xA9wrt","\xA9xsp","\xA9xyz","\xA9ysp","\xA9zsp"]),Ro=class extends We{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.fragments=[],this.currentFragment=null,this.fragmentLookupMutex=new Je,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(r=>r.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.inputTrack.getCodecParameterString()));return Af({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,Lt,Dr);if(t instanceof Promise&&(t=await t),!t)break;let r=e,s=bt(t);if(!s)break;if(s.name==="ftyp"){let n=de(t,4);this.isQuickTime=n==="qt "}else if(s.name==="moov"){let n=this.reader.requestSlice(t.filePos,s.contentSize);if(n instanceof Promise&&(n=await n),!n)break;this.moovSlice=n,this.readContiguousBoxes(this.moovSlice);for(let o of this.tracks){let a=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(a*o.timescale)}break}e=r+s.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let t=this.reader.requestSlice(this.reader.fileSize-4,4);t instanceof Promise&&(t=await t),k(t);let r=B(t),s=this.reader.fileSize-r;if(s>=0&&s<=this.reader.fileSize-Dr){let n=this.reader.requestSliceRange(s,Lt,Dr);if(n instanceof Promise&&(n=await n),n){let o=bt(n);if(o&&o.name==="mfra"){let a=this.reader.requestSlice(n.filePos,o.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,k(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ws.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){k(e.info?.type==="audio");let n=bf(e.info.codec),o=[],a=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],h=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let d=0;d<h;d++){let f=l.startSampleIndex+d*l.samplesPerChunk,m=f+l.samplesPerChunk,p=Q(t.sampleTimingEntries,f,M=>M.startIndex),g=t.sampleTimingEntries[p],y=Q(t.sampleTimingEntries,m,M=>M.startIndex),x=t.sampleTimingEntries[y],w=g.startDecodeTimestamp+(f-g.startIndex)*g.delta,S=x.startDecodeTimestamp+(m-x.startIndex)*x.delta-w,T=ve(o);T&&T.delta===S?T.count++:o.push({startIndex:l.startChunkIndex+d,startDecodeTimestamp:w,count:1,delta:S});let v=l.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;a.push(v)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=o,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let n of t.sampleTimingEntries)for(let o=0;o<n.count;o++)t.presentationTimestamps.push({presentationTimestamp:n.startDecodeTimestamp+o*n.delta,sampleIndex:n.startIndex+o});for(let n of t.sampleCompositionTimeOffsets)for(let o=0;o<n.count;o++){let a=n.startIndex+o,c=t.presentationTimestamps[a];c&&(c.presentationTimestamp+=n.offset)}t.presentationTimestamps.sort((n,o)=>n.presentationTimestamp-o.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let n=0;n<t.presentationTimestamps.length;n++)t.presentationTimestampIndexMap[t.presentationTimestamps[n].sampleIndex]=n}return t}async readFragment(e){let t=this.reader.requestSliceRange(e,Lt,Dr);t instanceof Promise&&(t=await t),k(t);let r=bt(t);k(r?.name==="moof");let s=this.reader.requestSlice(e,r.totalSize);s instanceof Promise&&(s=await s),k(s),this.traverseBox(s);let n=ae(this.fragments,e,a=>a.moofOffset);k(n!==-1);let o=this.fragments[n];k(o.moofOffset===e);for(let[a,c]of o.trackData){if(c.startTimestampIsFinal)continue;let l=this.tracks.find(p=>p.id===a),u=0,h=null,d=null,f=Q(l.fragments,e-1,p=>p.moofOffset);f!==-1&&(h=l.fragments[f],d=h,u=h.moofOffset+h.moofSize);let m=u===0;for(;u<=e-Lt;){if(h?.nextFragment)h=h.nextFragment,u=h.moofOffset+h.moofSize;else{let p=this.reader.requestSliceRange(u,Lt,Dr);if(p instanceof Promise&&(p=await p),!p)break;let g=u,y=bt(p);if(!y)break;if(y.name==="moof"){let x=ae(this.fragments,g,_=>_.moofOffset),w;x===-1?w=await this.readFragment(g):w=this.fragments[x],h&&(h.nextFragment=w),h=w,m&&(w.isKnownToBeFirstFragment=!0,m=!1)}u=g+y.totalSize}h&&h.trackData.has(a)&&(d=h)}if(d){let p=d.trackData.get(a);k(p.startTimestampIsFinal),Jf(c,p.endTimestamp)}c.startTimestampIsFinal=!0}return o}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Lt&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Lt;){let r=e.filePos,s=bt(e);if(!s)break;yield{boxInfo:s,slice:e},e.filePos=r+s.totalSize}}traverseBox(e){let t=e.filePos,r=bt(e);if(!r)return!1;let s=e.filePos,n=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"mvhd":{let o=z(e);e.skip(3),o===1?(e.skip(16),this.movieTimescale=B(e),this.movieDurationInTimescale=Ye(e)):(e.skip(8),this.movieTimescale=B(e),this.movieDurationInTimescale=B(e))}break;case"trak":{let o={id:-1,demuxer:this,inputTrack:null,info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Pe,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:null,currentFragmentState:null,fragments:[],fragmentsWithKeyFrame:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=o,this.readContiguousBoxes(e.slice(s,r.contentSize)),o.id!==-1&&o.timescale!==-1&&o.info!==null){if(o.info.type==="video"&&o.info.width!==-1){let a=o;o.inputTrack=new wt(new Ml(a)),this.tracks.push(o)}else if(o.info.type==="audio"&&o.info.numberOfChannels!==-1){let a=o;o.inputTrack=new Ae(new Bl(a)),this.tracks.push(o)}}this.currentTrack=null}break;case"tkhd":{let o=this.currentTrack;if(!o)break;let a=z(e);if(!((hi(e)&1)!==0))break;if(a===0)e.skip(8),o.id=B(e),e.skip(4),o.durationInMovieTimescale=B(e);else if(a===1)e.skip(16),o.id=B(e),e.skip(4),o.durationInMovieTimescale=Ye(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let u=[or(e),or(e),To(e),or(e),or(e),To(e),or(e),or(e),To(e)],h=so(ff(H_(u),90));k(h===0||h===90||h===180||h===270),o.rotation=h}break;case"elst":{let o=this.currentTrack;if(!o)break;let a=z(e);e.skip(3);let c=!1,l=0,u=B(e);for(let h=0;h<u;h++){let d=a===1?Ye(e):B(e),f=a===1?If(e):Nt(e),m=or(e);if(d!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=d;continue}if(m!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}o.editListPreviousSegmentDurations=l,o.editListOffset=f,c=!0}}}break;case"mdhd":{let o=this.currentTrack;if(!o)break;let a=z(e);e.skip(3),a===0?(e.skip(8),o.timescale=B(e),o.durationInMediaTimescale=B(e)):a===1&&(e.skip(16),o.timescale=B(e),o.durationInMediaTimescale=Ye(e));let c=Ce(e);if(c>0){o.languageCode="";for(let l=0;l<3;l++)o.languageCode=String.fromCharCode(96+(c&31))+o.languageCode,c>>=5;uo(o.languageCode)||(o.languageCode=Pe)}}break;case"hdlr":{let o=this.currentTrack;if(!o)break;e.skip(8);let a=de(e,4);a==="vide"?o.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(o.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let o=this.currentTrack;if(!o)break;o.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(s,r.contentSize))}break;case"stsd":{let o=this.currentTrack;if(!o||o.info===null||o.sampleTable)break;let a=z(e);e.skip(3);let c=B(e);for(let l=0;l<c;l++){let u=e.filePos,h=bt(e);if(!h)break;o.internalCodecId=h.name;let d=h.name.toLowerCase();if(o.info.type==="video")d==="avc1"?o.info.codec="avc":d==="hvc1"||d==="hev1"?o.info.codec="hevc":d==="vp08"?o.info.codec="vp8":d==="vp09"?o.info.codec="vp9":d==="av01"?o.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${h.name}').`),e.skip(24),o.info.width=Ce(e),o.info.height=Ce(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,u+h.totalSize-e.filePos));else{d==="mp4a"||(d==="opus"?o.info.codec="opus":d==="flac"?o.info.codec="flac":d==="twos"||d==="sowt"||d==="raw "||d==="in24"||d==="in32"||d==="fl32"||d==="fl64"||d==="lpcm"||d==="ipcm"||d==="fpcm"||(d==="ulaw"?o.info.codec="ulaw":d==="alaw"?o.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${h.name}').`))),e.skip(8);let f=Ce(e);e.skip(6);let m=Ce(e),p=Ce(e);e.skip(4);let g=B(e)/65536;if(a===0&&f>0){if(f===1)e.skip(4),p=8*B(e),e.skip(8);else if(f===2){e.skip(4),g=So(e),m=B(e),e.skip(4),p=B(e);let y=B(e);if(e.skip(8),d==="lpcm"){let x=p+7>>3,w=!!(y&1),_=!!(y&2),S=y&4?-1:0;p>0&&p<=64&&(w?p===32&&(o.info.codec=_?"pcm-f32be":"pcm-f32"):S&1<<x-1?x===1?o.info.codec="pcm-s8":x===2?o.info.codec=_?"pcm-s16be":"pcm-s16":x===3?o.info.codec=_?"pcm-s24be":"pcm-s24":x===4&&(o.info.codec=_?"pcm-s32be":"pcm-s32"):x===1&&(o.info.codec="pcm-u8")),o.info.codec===null&&console.warn("Unsupported PCM format.")}}}o.info.numberOfChannels=m,o.info.sampleRate=g,d==="twos"?p===8?o.info.codec="pcm-s8":p===16?o.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${p} for codec 'twos'.`),o.info.codec=null):d==="sowt"?p===8?o.info.codec="pcm-s8":p===16?o.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${p} for codec 'sowt'.`),o.info.codec=null):d==="raw "?o.info.codec="pcm-u8":d==="in24"?o.info.codec="pcm-s24be":d==="in32"?o.info.codec="pcm-s32be":d==="fl32"?o.info.codec="pcm-f32be":d==="fl64"?o.info.codec="pcm-f64be":d==="ipcm"?o.info.codec="pcm-s16be":d==="fpcm"&&(o.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,u+h.totalSize-e.filePos))}}}break;case"avcC":{let o=this.currentTrack;if(!o)break;k(o.info),o.info.codecDescription=W(e,r.contentSize)}break;case"hvcC":{let o=this.currentTrack;if(!o)break;k(o.info),o.info.codecDescription=W(e,r.contentSize)}break;case"vpcC":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="video"),e.skip(4);let a=z(e),c=z(e),l=z(e),u=l>>4,h=l>>1&7,d=l&1,f=z(e),m=z(e),p=z(e);o.info.vp9CodecInfo={profile:a,level:c,bitDepth:u,chromaSubsampling:h,videoFullRangeFlag:d,colourPrimaries:f,transferCharacteristics:m,matrixCoefficients:p}}break;case"av1C":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="video"),e.skip(1);let a=z(e),c=a>>5,l=a&31,u=z(e),h=u>>7,d=u>>6&1,f=u>>5&1,m=u>>4&1,p=u>>3&1,g=u>>2&1,y=u&3,x=c===2&&d?f?12:10:d?10:8;o.info.av1CodecInfo={profile:c,level:l,tier:h,bitDepth:x,monochrome:m,chromaSubsamplingX:p,chromaSubsamplingY:g,chromaSamplePosition:y}}break;case"colr":{let o=this.currentTrack;if(!o||(k(o.info?.type==="video"),de(e,4)!=="nclx"))break;let c=Ce(e),l=Ce(e),u=Ce(e),h=!!(z(e)&128);o.info.colorSpace={primaries:no[c],transfer:oo[l],matrix:ao[u],fullRange:h}}break;case"wave":this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"esds":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),e.skip(4);let a=z(e);k(a===3),ko(e),e.skip(2);let c=z(e),l=(c&128)!==0,u=(c&64)!==0,h=(c&32)!==0;if(l&&e.skip(2),u){let g=z(e);e.skip(g)}h&&e.skip(2);let d=z(e);k(d===4);let f=ko(e),m=e.filePos,p=z(e);if(p===64||p===103?(o.info.codec="aac",o.info.aacCodecInfo={isMpeg2:p===103}):p===105||p===107?o.info.codec="mp3":p===221?o.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${p}) - discarding track.`),e.skip(12),f>e.filePos-m){let g=z(e);k(g===5);let y=ko(e);if(o.info.codecDescription=W(e,y),o.info.codec==="aac"){let x=gl(o.info.codecDescription);x.numberOfChannels!==null&&(o.info.numberOfChannels=x.numberOfChannels),x.sampleRate!==null&&(o.info.sampleRate=x.sampleRate)}}}break;case"enda":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),Ce(e)&255&&(o.info.codec==="pcm-s16be"?o.info.codec="pcm-s16":o.info.codec==="pcm-s24be"?o.info.codec="pcm-s24":o.info.codec==="pcm-s32be"?o.info.codec="pcm-s32":o.info.codec==="pcm-f32be"?o.info.codec="pcm-f32":o.info.codec==="pcm-f64be"&&(o.info.codec="pcm-f64"))}break;case"pcmC":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),e.skip(4);let c=!!(z(e)&1),l=z(e);o.info.codec==="pcm-s16be"?c?l===16?o.info.codec="pcm-s16":l===24?o.info.codec="pcm-s24":l===32?o.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),o.info.codec=null):l===16?o.info.codec="pcm-s16be":l===24?o.info.codec="pcm-s24be":l===32?o.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),o.info.codec=null):o.info.codec==="pcm-f32be"&&(c?l===32?o.info.codec="pcm-f32":l===64?o.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),o.info.codec=null):l===32?o.info.codec="pcm-f32be":l===64?o.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),o.info.codec=null));break}case"dOps":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),e.skip(1);let a=z(e),c=Ce(e),l=B(e),u=_s(e),h=z(e),d;h!==0?d=W(e,2+a):d=new Uint8Array(0);let f=new Uint8Array(19+d.byteLength),m=new DataView(f.buffer);m.setUint32(0,1332770163,!1),m.setUint32(4,1214603620,!1),m.setUint8(8,1),m.setUint8(9,a),m.setUint16(10,c,!0),m.setUint32(12,l,!0),m.setInt16(16,u,!0),m.setUint8(18,h),f.set(d,19),o.info.codecDescription=f,o.info.numberOfChannels=a,o.info.sampleRate=l}break;case"dfLa":{let o=this.currentTrack;if(!o)break;k(o.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<n;){let m=z(e),p=hi(e);if((m&a)===0){e.skip(10);let y=B(e),x=y>>>12,w=(y>>9&7)+1;o.info.sampleRate=x,o.info.numberOfChannels=w,e.skip(20)}else e.skip(p);if(m&c)break}let u=e.filePos;e.filePos=l;let h=W(e,u-l),d=new Uint8Array(4+h.byteLength);new DataView(d.buffer).setUint32(0,1716281667,!1),d.set(h,4),o.info.codecDescription=d}break;case"stts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e),c=0,l=0;for(let u=0;u<a;u++){let h=B(e),d=B(e);o.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:h,delta:d}),c+=h,l+=h*d}}break;case"ctts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e),c=0;for(let l=0;l<a;l++){let u=B(e),h=Nt(e);o.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:h}),c+=u}}break;case"stsz":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e),c=B(e);if(a===0)for(let l=0;l<c;l++){let u=B(e);o.sampleTable.sampleSizes.push(u)}else o.sampleTable.sampleSizes.push(a)}break;case"stz2":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),e.skip(3);let a=z(e),c=B(e),l=W(e,Math.ceil(c*a/8)),u=new fe(l);for(let h=0;h<c;h++){let d=u.readBits(a);o.sampleTable.sampleSizes.push(d)}}break;case"stss":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),o.sampleTable.keySampleIndices=[];let a=B(e);for(let c=0;c<a;c++){let l=B(e)-1;o.sampleTable.keySampleIndices.push(l)}o.sampleTable.keySampleIndices[0]!==0&&o.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e);for(let l=0;l<a;l++){let u=B(e)-1,h=B(e),d=B(e);o.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:h,sampleDescriptionIndex:d})}let c=0;for(let l=0;l<o.sampleTable.sampleToChunk.length;l++)if(o.sampleTable.sampleToChunk[l].startSampleIndex=c,l<o.sampleTable.sampleToChunk.length-1){let h=o.sampleTable.sampleToChunk[l+1].startChunkIndex-o.sampleTable.sampleToChunk[l].startChunkIndex;c+=h*o.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e);for(let c=0;c<a;c++){let l=B(e);o.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=B(e);for(let c=0;c<a;c++){let l=Ye(e);o.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"mehd":{let o=z(e);e.skip(3);let a=o===1?Ye(e):B(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let o=B(e),a=B(e),c=B(e),l=B(e),u=B(e);this.fragmentTrackDefaults.push({trackId:o,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{let o=z(e);e.skip(3);let a=B(e),c=this.tracks.find(x=>x.id===a);if(!c)break;c.fragmentLookupTable=[];let l=B(e),u=(l&48)>>4,h=(l&12)>>2,d=l&3,f=[z,Ce,hi,B],m=f[u],p=f[h],g=f[d],y=B(e);for(let x=0;x<y;x++){let w=o===1?Ye(e):B(e),_=o===1?Ye(e):B(e);m(e),p(e),g(e),c.fragmentLookupTable.push({timestamp:w,moofOffset:_})}}break;case"moof":{this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map,dataStart:1/0,dataEnd:0,nextFragment:null,isKnownToBeFirstFragment:!1},this.readContiguousBoxes(e.slice(s,r.contentSize)),ot(this.fragments,this.currentFragment,o=>o.moofOffset);for(let[,o]of this.currentFragment.trackData){let a=o.samples[0],c=ve(o.samples);this.currentFragment.dataStart=Math.min(this.currentFragment.dataStart,a.byteOffset),this.currentFragment.dataEnd=Math.max(this.currentFragment.dataEnd,c.byteOffset+c.byteSize)}this.currentFragment=null}break;case"traf":if(k(this.currentFragment),this.readContiguousBoxes(e.slice(s,r.contentSize)),this.currentTrack){let o=this.currentFragment.trackData.get(this.currentTrack.id);if(o){ot(this.currentTrack.fragments,this.currentFragment,l=>l.moofOffset),o.firstKeyFrameTimestamp!==null&&ot(this.currentTrack.fragmentsWithKeyFrame,this.currentFragment,l=>l.moofOffset);let{currentFragmentState:c}=this.currentTrack;k(c),c.startTimestamp!==null&&(Jf(o,c.startTimestamp),o.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{k(this.currentFragment),e.skip(1);let o=hi(e),a=!!(o&1),c=!!(o&2),l=!!(o&8),u=!!(o&16),h=!!(o&32),d=!!(o&65536),f=!!(o&131072),m=B(e),p=this.tracks.find(y=>y.id===m);if(!p)break;let g=this.fragmentTrackDefaults.find(y=>y.trackId===m);this.currentTrack=p,p.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:g?.defaultSampleDescriptionIndex??null,defaultSampleDuration:g?.defaultSampleDuration??null,defaultSampleSize:g?.defaultSampleSize??null,defaultSampleFlags:g?.defaultSampleFlags??null,startTimestamp:null},a?p.currentFragmentState.baseDataOffset=Ye(e):f&&(p.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(p.currentFragmentState.sampleDescriptionIndex=B(e)),l&&(p.currentFragmentState.defaultSampleDuration=B(e)),u&&(p.currentFragmentState.defaultSampleSize=B(e)),h&&(p.currentFragmentState.defaultSampleFlags=B(e)),d&&(p.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let o=this.currentTrack;if(!o)break;k(o.currentFragmentState);let a=z(e);e.skip(3);let c=a===0?B(e):Ye(e);o.currentFragmentState.startTimestamp=c}break;case"trun":{let o=this.currentTrack;if(!o)break;if(k(this.currentFragment),k(o.currentFragmentState),this.currentFragment.trackData.has(o.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let a=z(e),c=hi(e),l=!!(c&1),u=!!(c&4),h=!!(c&256),d=!!(c&512),f=!!(c&1024),m=!!(c&2048),p=B(e),g=o.currentFragmentState.baseDataOffset;l&&(g+=Nt(e));let y=null;u&&(y=B(e));let x=g;if(p===0){this.currentFragment.implicitBaseDataOffset=x;break}let w=0,_={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(o.id,_);for(let v=0;v<p;v++){let M;h?M=B(e):(k(o.currentFragmentState.defaultSampleDuration!==null),M=o.currentFragmentState.defaultSampleDuration);let P;d?P=B(e):(k(o.currentFragmentState.defaultSampleSize!==null),P=o.currentFragmentState.defaultSampleSize);let C;f?C=B(e):(k(o.currentFragmentState.defaultSampleFlags!==null),C=o.currentFragmentState.defaultSampleFlags),v===0&&y!==null&&(C=y);let E=0;m&&(a===0?E=B(e):E=Nt(e));let D=!(C&65536);_.samples.push({presentationTimestamp:w+E,duration:M,byteOffset:x,byteSize:P,isKeyFrame:D}),x+=P,w+=M}_.presentationTimestamps=_.samples.map((v,M)=>({presentationTimestamp:v.presentationTimestamp,sampleIndex:M})).sort((v,M)=>v.presentationTimestamp-M.presentationTimestamp);for(let v=0;v<_.presentationTimestamps.length;v++){let M=_.presentationTimestamps[v],P=_.samples[M.sampleIndex];if(_.firstKeyFrameTimestamp===null&&P.isKeyFrame&&(_.firstKeyFrameTimestamp=P.presentationTimestamp),v<_.presentationTimestamps.length-1){let C=_.presentationTimestamps[v+1];P.duration=C.presentationTimestamp-M.presentationTimestamp}}let S=_.samples[_.presentationTimestamps[0].sampleIndex],T=_.samples[ve(_.presentationTimestamps).sampleIndex];_.startTimestamp=S.presentationTimestamp,_.endTimestamp=T.presentationTimestamp+T.duration,this.currentFragment.implicitBaseDataOffset=x}break;case"udta":{let o=this.iterateContiguousBoxes(e.slice(s,r.contentSize));for(let{boxInfo:a,slice:c}of o){if(a.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},N_.has(a.name)?this.metadataTags.raw[a.name]??=at(c):this.metadataTags.raw[a.name]??=W(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=Be.decode(W(c,a.contentSize)):this.metadataTags.title??=at(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=at(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=at(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=at(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=at(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=at(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(at(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=at(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=at(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=B(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(s,r.contentSize)):this.readContiguousBoxes(e.slice(s+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let o=B(e);for(let a=0;a<o;a++){let c=B(e);e.skip(4);let l=Be.decode(W(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let o=this.iterateContiguousBoxes(e.slice(s,r.contentSize));for(let{boxInfo:a,slice:c}of o){let l=a.name,u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));let h=Ff(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=h,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof h=="string"&&(this.metadataTags.title??=h);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof h=="string"&&(this.metadataTags.description??=h);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof h=="string"&&(this.metadataTags.artist??=h);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof h=="string"&&(this.metadataTags.album??=h);break;case"aART":case"album_artist":typeof h=="string"&&(this.metadataTags.albumArtist??=h);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof h=="string"&&(this.metadataTags.comment??=h);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof h=="string"&&(this.metadataTags.genre??=h);break;case"\xA9lyr":case"lyrics":typeof h=="string"&&(this.metadataTags.lyrics??=h);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof h=="string"){let d=new Date(h);Number.isNaN(d.getTime())||(this.metadataTags.date??=d)}break;case"covr":case"com.apple.quicktime.artwork":h instanceof nr?(this.metadataTags.images??=[],this.metadataTags.images.push({data:h.data,kind:"coverFront",mimeType:h.mimeType})):h instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:h,kind:"coverFront",mimeType:"image/*"}));break;case"trkn":if(h instanceof Uint8Array){let d=oe(h),f=d.getUint16(2,!1),m=d.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),m>0&&(this.metadataTags.tracksTotal??=m)}break;case"disc":case"disk":if(h instanceof Uint8Array){let d=oe(h),f=d.getUint16(2,!1),m=d.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),m>0&&(this.metadataTags.discsTotal??=m)}break}}}break}return e.filePos=n,!0}},Oo=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}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(()=>{let r=this.internalTrack.demuxer.fragments[0]??null;if(r?.isKnownToBeFirstFragment){let s=r;for(;s;){if(s.trackData.get(this.internalTrack.id))return{fragmentIndex:ae(this.internalTrack.fragments,s.moofOffset,o=>o.moofOffset),sampleIndex:0,correctSampleFound:!0};s=s.nextFragment}}return{fragmentIndex:-1,sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ir(e*this.internalTrack.timescale,14)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Qf(s,r),o=await this.fetchPacketForSampleIndex(n,t);return!em(s)||!this.internalTrack.demuxer.isFragmented?o:this.performFragmentedLookup(()=>this.findSampleInFragmentsForTimestamp(r),r,r,t)}async getNextPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,t);let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");let n=s.fragment.trackData.get(this.internalTrack.id),o=ae(this.internalTrack.fragments,s.fragment.moofOffset,a=>a.moofOffset);return k(o!==-1),this.performFragmentedLookup(()=>{if(s.sampleIndex+1<n.samples.length)return{fragmentIndex:o,sampleIndex:s.sampleIndex+1,correctSampleFound:!0};{let a=s.fragment;for(;a.nextFragment;)if(a=a.nextFragment,a.trackData.get(this.internalTrack.id)){let l=ae(this.internalTrack.fragments,a.moofOffset,u=>u.moofOffset);return k(l!==-1),{fragmentIndex:l,sampleIndex:0,correctSampleFound:!0}}return{fragmentIndex:o,sampleIndex:-1,correctSampleFound:!1}}},-1/0,1/0,t)}async getKeyPacket(e,t){let r=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Qf(s,r),o=n===-1?-1:V_(s,n),a=await this.fetchPacketForSampleIndex(o,t);return!em(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(()=>this.findKeySampleInFragmentsForTimestamp(r),r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),c=W_(a,r);return this.fetchPacketForSampleIndex(c,t)}let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");let n=s.fragment.trackData.get(this.internalTrack.id),o=ae(this.internalTrack.fragments,s.fragment.moofOffset,a=>a.moofOffset);return k(o!==-1),this.performFragmentedLookup(()=>{let a=n.samples.findIndex((c,l)=>c.isKeyFrame&&l>s.sampleIndex);if(a!==-1)return{fragmentIndex:o,sampleIndex:a,correctSampleFound:!0};{let c=s.fragment;for(;c.nextFragment;){c=c.nextFragment;let l=c.trackData.get(this.internalTrack.id);if(l&&l.firstKeyFrameTimestamp!==null){let u=ae(this.internalTrack.fragments,c.moofOffset,d=>d.moofOffset);k(u!==-1);let h=l.samples.findIndex(d=>d.isKeyFrame);return k(h!==-1),{fragmentIndex:u,sampleIndex:h,correctSampleFound:!0}}}return{fragmentIndex:o,sampleIndex:-1,correctSampleFound:!1}}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=L_(r,e);if(!s)return null;let n;if(t.metadataOnly)n=Ee;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.sampleOffset,s.sampleSize);l instanceof Promise&&(l=await l),k(l),n=W(l,s.sampleSize)}let o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=s.duration/this.internalTrack.timescale,c=new ce(n,s.isKeyFrame?"key":"delta",o,a,e,s.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).samples[t];k(n);let o;if(r.metadataOnly)o=Ee;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);u instanceof Promise&&(u=await u),k(u),o=W(u,n.byteSize)}let a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,l=new ce(o,n.isKeyFrame?"key":"delta",a,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}findSampleInFragmentsForTimestamp(e){let t=Q(this.internalTrack.fragments,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,s=!1;if(t!==-1){let o=this.internalTrack.fragments[t].trackData.get(this.internalTrack.id),a=Q(o.presentationTimestamps,e,c=>c.presentationTimestamp);k(a!==-1),r=o.presentationTimestamps[a].sampleIndex,s=e<o.endTimestamp}return{fragmentIndex:t,sampleIndex:r,correctSampleFound:s}}findKeySampleInFragmentsForTimestamp(e){let t=Q(this.internalTrack.fragmentsWithKeyFrame,e,o=>o.trackData.get(this.internalTrack.id).startTimestamp),r=-1,s=-1,n=!1;if(t!==-1){let o=this.internalTrack.fragmentsWithKeyFrame[t];r=ae(this.internalTrack.fragments,o.moofOffset,u=>u.moofOffset),k(r!==-1);let a=o.trackData.get(this.internalTrack.id),c=co(a.presentationTimestamps,u=>a.samples[u.sampleIndex].isKeyFrame&&u.presentationTimestamp<=e);k(c!==-1),s=a.presentationTimestamps[c].sampleIndex,n=e<a.endTimestamp}return{fragmentIndex:r,sampleIndex:s,correctSampleFound:n}}async performFragmentedLookup(e,t,r,s){let n=this.internalTrack.demuxer,o=await n.fragmentLookupMutex.acquire();try{let{fragmentIndex:a,sampleIndex:c,correctSampleFound:l}=e();if(l){let x=this.internalTrack.fragments[a];return this.fetchPacketInFragment(x,c,s)}let u=null,h=a,d=c,f=this.internalTrack.fragmentLookupTable?Q(this.internalTrack.fragmentLookupTable,t,x=>x.timestamp):-1,m=f!==-1?this.internalTrack.fragmentLookupTable[f]:null,p,g=!1;if(a===-1)p=m?.moofOffset??0,g=p===0;else{let x=this.internalTrack.fragments[a];!m||x.moofOffset>=m.moofOffset?(p=x.moofOffset+x.moofSize,u=x):p=m.moofOffset}for(;;){if(u){let S=u.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>r)break;if(u.nextFragment){p=u.nextFragment.moofOffset+u.nextFragment.moofSize,u=u.nextFragment;continue}}let x=n.reader.requestSliceRange(p,Lt,Dr);if(x instanceof Promise&&(x=await x),!x)break;let w=p,_=bt(x);if(!_)break;if(_.name==="moof"){let S=ae(n.fragments,w,C=>C.moofOffset),T;S===-1?T=await n.readFragment(w):T=n.fragments[S],u&&(u.nextFragment=T),u=T,g&&(T.isKnownToBeFirstFragment=!0,g=!1);let{fragmentIndex:v,sampleIndex:M,correctSampleFound:P}=e();if(P){let C=this.internalTrack.fragments[v];return this.fetchPacketInFragment(C,M,s)}v!==-1&&(h=v,d=M)}p=w+_.totalSize}let y=h!==-1?this.internalTrack.fragments[h]:null;if(m&&(!y||y.moofOffset<m.moofOffset)){let w=this.internalTrack.fragmentLookupTable[f-1]?.timestamp??-1/0;return this.performFragmentedLookup(e,w,r,s)}return y?this.fetchPacketInFragment(y,d,s):null}finally{o()}}},Ml=class extends Oo{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 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&&bo(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&wo(e.data)}return{codec:po(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}},Bl=class extends Oo{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:go(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Qf=(i,e)=>{if(i.presentationTimestamps){let t=Q(i.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:i.presentationTimestamps[t].sampleIndex}else{let t=Q(i.sampleTimingEntries,e,s=>s.startDecodeTimestamp);if(t===-1)return-1;let r=i.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},L_=(i,e)=>{let t=Q(i.sampleTimingEntries,e,y=>y.startIndex),r=i.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let n=r.startDecodeTimestamp+(e-r.startIndex)*r.delta,o=Q(i.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=i.sampleCompositionTimeOffsets[o];a&&e-a.startIndex<a.count&&(n+=a.offset);let c=i.sampleSizes[Math.min(e,i.sampleSizes.length-1)],l=Q(i.sampleToChunk,e,y=>y.startSampleIndex),u=i.sampleToChunk[l];k(u);let h=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),d=i.chunkOffsets[h],f=u.startSampleIndex+(h-u.startChunkIndex)*u.samplesPerChunk,m=0,p=d;if(i.sampleSizes.length===1)p+=c*(e-f),m+=c*u.samplesPerChunk;else for(let y=f;y<f+u.samplesPerChunk;y++){let x=i.sampleSizes[y];y<e&&(p+=x),m+=x}let g=r.delta;if(i.presentationTimestamps){let y=i.presentationTimestampIndexMap[e];k(y!==void 0),y<i.presentationTimestamps.length-1&&(g=i.presentationTimestamps[y+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:g,sampleOffset:p,sampleSize:c,chunkOffset:d,chunkSize:m,isKeyFrame:i.keySampleIndices?ae(i.keySampleIndices,e,y=>y)!==-1:!0}},V_=(i,e)=>{if(!i.keySampleIndices)return e;let t=Q(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t]??-1},W_=(i,e)=>{if(!i.keySampleIndices)return e+1;let t=Q(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t+1]??-1},Jf=(i,e)=>{i.startTimestamp+=e,i.endTimestamp+=e;for(let t of i.samples)t.presentationTimestamp+=e;for(let t of i.presentationTimestamps)t.presentationTimestamp+=e},H_=i=>{let[e,,,t]=i,r=Math.hypot(e,t),s=e/r,n=t/r,o=-Math.atan2(n,s)*(180/Math.PI);return Number.isFinite(o)?o:0},em=i=>i.sampleSizes.length===0;var Ht;(function(i){i[i.None=0]="None",i[i.Xiph=1]="Xiph",i[i.FixedSize=2]="FixedSize",i[i.Ebml=3]="Ebml"})(Ht||(Ht={}));var Fl=[{id:I.SeekHead,flag:"seekHeadSeen"},{id:I.Info,flag:"infoSeen"},{id:I.Tracks,flag:"tracksSeen"},{id:I.Cues,flag:"cuesSeen"}],tm=10*2**20,Uo=class extends We{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentCueTime=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(r=>r.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(r=>r.getCodecParameterString()));return Rf({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(s=>s.info?.type==="video")),hasAudio:this.segments.some(r=>r.tracks.some(s=>s.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,Ve,ct);if(t instanceof Promise&&(t=await t),!t)break;let r=lt(t);if(!r)break;let s=r.id,n=r.size,o=t.filePos;if(s===I.EBML){Vt(n);let a=this.reader.requestSlice(o,n);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(s===I.Segment){if(await this.readSegment(o,n),n===null||this.reader.fileSize===null)break}else if(s===I.Cluster){if(this.reader.fileSize===null)break;n===null&&(n=(await Eo(this.reader,o,vo,this.reader.fileSize)).pos-o);let a=ve(this.segments);a&&(a.elementEndPos=o+n)}Vt(n),e=o+n}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===null?null:e+t,clusterSeekStartPos:e,clusters:[],clusterLookupMutex:new Je,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;this.currentSegment.elementEndPos===null||r<this.currentSegment.elementEndPos;){let c=this.reader.requestSliceRange(r,Ve,ct);if(c instanceof Promise&&(c=await c),!c)break;let l=r,u=lt(c);if(!u||!di.includes(u.id)&&u.id!==I.Void){let p=await Tl(this.reader,l,di,Math.min(this.currentSegment.elementEndPos??1/0,l+tm));if(p){r=p;continue}else break}let{id:h,size:d}=u,f=c.filePos,m=Fl.findIndex(p=>p.id===h);if(m!==-1){let p=Fl[m].flag;this.currentSegment[p]=!0,Vt(d);let g=this.reader.requestSlice(f,d);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(h===I.Tags||h===I.Attachments){h===I.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Vt(d);let p=this.reader.requestSlice(f,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(h===I.Cluster){this.currentSegment.clusterSeekStartPos=l;break}if(d===null)break;r=f+d}if(this.currentSegment.seekEntries.sort((c,l)=>c.segmentPosition-l.segmentPosition),this.reader.fileSize!==null)for(let c of this.currentSegment.seekEntries){let l=Fl.find(p=>p.id===c.id);if(!l||this.currentSegment[l.flag])continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,Ve,ct);if(u instanceof Promise&&(u=await u),!u)continue;let h=lt(u);if(!h)continue;let{id:d,size:f}=h;if(d!==l.id)continue;Vt(f),this.currentSegment[l.flag]=!0;let m=this.reader.requestSlice(u.filePos,f);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((c,l)=>Number(l.isDefault)-Number(c.isDefault)),this.currentSegment.cuePoints.sort((c,l)=>c.clusterPosition-l.clusterPosition);let s=this.currentSegment.tracks.map(c=>c.id),n=new Set,o=null,a=null;for(let c of this.currentSegment.cuePoints){if(c.clusterPosition!==o){for(let u of n)k(a),this.currentSegment.tracks.find(d=>d.id===u).cuePoints.push(a);for(let u of s)n.add(u)}if(a=c,!n.has(c.trackId))continue;this.currentSegment.tracks.find(u=>u.id===c.trackId).cuePoints.push(c),n.delete(c.trackId),o=c.clusterPosition}for(let c of n)k(a),this.currentSegment.tracks.find(u=>u.id===c).cuePoints.push(a);for(let c of this.currentSegment.tracks)c.cuePoints.sort((l,u)=>l.time-u.time);this.currentSegment=null}async readCluster(e,t){let r=this.reader.requestSliceRange(e,Ve,ct);r instanceof Promise&&(r=await r),k(r);let s=e,n=lt(r);k(n);let o=n.id,a=n.size,c=r.filePos;a===null&&(a=(await Eo(this.reader,c,vo,t.elementEndPos)).pos-c),k(o===I.Cluster);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let u={elementStartPos:s,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map,nextCluster:null,isKnownToBeFirstCluster:!1};this.currentCluster=u,l&&this.readContiguousElements(l);for(let[h,d]of u.trackData){let f=t.tracks.find(x=>x.id===h)??null;k(d.blocks.length>0);let m=!1,p=!1;for(let x=0;x<d.blocks.length;x++){let w=d.blocks[x];w.timestamp+=u.timestamp,m||=w.referencedTimestamps.length>0,p||=w.lacing!==Ht.None}m&&(d.blocks=j_(d.blocks)),d.presentationTimestamps=d.blocks.map((x,w)=>({timestamp:x.timestamp,blockIndex:w})).sort((x,w)=>x.timestamp-w.timestamp);for(let x=0;x<d.presentationTimestamps.length;x++){let w=d.presentationTimestamps[x],_=d.blocks[w.blockIndex];if(d.firstKeyFrameTimestamp===null&&_.isKeyFrame&&(d.firstKeyFrameTimestamp=_.timestamp),x<d.presentationTimestamps.length-1){let S=d.presentationTimestamps[x+1];_.duration=S.timestamp-_.timestamp}else _.duration===0&&f?.defaultDuration!=null&&_.lacing===Ht.None&&(_.duration=f.defaultDuration)}p&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((x,w)=>({timestamp:x.timestamp,blockIndex:w})).sort((x,w)=>x.timestamp-w.timestamp));let g=d.blocks[d.presentationTimestamps[0].blockIndex],y=d.blocks[ve(d.presentationTimestamps).blockIndex];d.startTimestamp=g.timestamp,d.endTimestamp=y.timestamp+y.duration,f&&(ot(f.clusters,u,w=>w.elementStartPos),d.firstKeyFrameTimestamp!==null&&ot(f.clustersWithKeyFrame,u,w=>w.elementStartPos))}return ot(t.clusters,u,h=>h.elementStartPos),this.currentCluster=null,u}getTrackDataInCluster(e,t){let r=e.trackData.get(t);return r||(r={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)),r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){let s=e[r];if(s.lacing===Ht.None)continue;let n=li.tempFromBytes(s.data),o=[],a=z(n)+1;switch(s.lacing){case Ht.Xiph:{let c=0;for(let l=0;l<a-1;l++){let u=0;for(;n.bufferPos<n.length;){let h=z(n);if(u+=h,h<255){o.push(u),c+=u;break}}}o.push(n.length-(n.bufferPos+c))}break;case Ht.FixedSize:{let c=n.length-1,l=Math.floor(c/a);for(let u=0;u<a;u++)o.push(l)}break;case Ht.Ebml:{let c=fi(n);k(c!==null);let l=c;o.push(l);let u=l;for(let h=1;h<a-1;h++){let d=n.bufferPos,f=fi(n);k(f!==null);let m=f,g=(1<<(n.bufferPos-d)*7-1)-1,y=m-g;l+=y,o.push(l),u+=l}o.push(n.length-(n.bufferPos+u))}break;default:k(!1)}k(o.length===a),e.splice(r,1);for(let c=0;c<a;c++){let l=o[c],u=W(n,l),h=s.duration||a*(t?.defaultDuration??0),d=s.timestamp+h*c/a,f=h/a;e.splice(r+c,0,{timestamp:d,duration:f,isKeyFrame:s.isKeyFrame,referencedTimestamps:s.referencedTimestamps,data:u,lacing:Ht.None})}r+=a,r--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===I.Tags&&!e.tagsSeen)){if(!(t.id===I.Attachments&&!e.attachmentsSeen))continue}let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Ve,ct);if(r instanceof Promise&&(r=await r),!r)continue;let s=lt(r);if(!s||s.id!==t.id)continue;let{size:n}=s;Vt(n),k(!this.currentSegment),this.currentSegment=e;let o=this.reader.requestSlice(r.filePos,n);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o),this.currentSegment=null,t.id===I.Tags?e.tagsSeen=!0:t.id===I.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e){let t=e.filePos;for(;e.filePos-t<=e.length-Ve&&this.traverseElement(e););}traverseElement(e){let t=lt(e);if(!t)return!1;let{id:r,size:s}=t,n=e.filePos;switch(Vt(s),r){case I.DocType:this.isWebM=ar(e,s)==="webm";break;case I.Seek:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(n,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case I.SeekID:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=J(e,s)}break;case I.SeekPosition:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=J(e,s)}break;case I.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=J(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case I.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Co(e,s)}break;case I.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusters:[],clustersWithKeyFrame:[],cuePoints:[],isDefault:!1,inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Pe,info:null},this.readContiguousElements(e.slice(n,s)),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let o=this.currentTrack.codecId.indexOf("/"),a=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===ut.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ut.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):a===ut.vp8?this.currentTrack.info.codec="vp8":a===ut.vp9?this.currentTrack.info.codec="vp9":a===ut.av1&&(this.currentTrack.info.codec="av1");let c=this.currentTrack,l=new wt(new Dl(c));this.currentTrack.inputTrack=l,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){a===ut.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===ut.mp3?this.currentTrack.info.codec="mp3":a===ut.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):a===ut.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):a===ut.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 c=this.currentTrack,l=new Ae(new Rl(c));this.currentTrack.inputTrack=l,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case I.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=J(e,s)}break;case I.TrackType:{if(!this.currentTrack)break;let o=J(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case I.FlagEnabled:{if(!this.currentTrack)break;J(e,s)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case I.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.isDefault=!!J(e,s)}break;case I.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=ar(e,s)}break;case I.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=W(e,s)}break;case I.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*J(e,s)/1e9}break;case I.Name:{if(!this.currentTrack)break;this.currentTrack.name=mi(e,s)}break;case I.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==Pe)break;this.currentTrack.languageCode=ar(e,s),uo(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Pe)}break;case I.LanguageBCP47:{if(!this.currentTrack)break;let a=ar(e,s).split("-")[0];a?this.currentTrack.languageCode=a:this.currentTrack.languageCode=Pe}break;case I.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(n,s))}break;case I.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=J(e,s)}break;case I.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=J(e,s)}break;case I.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(n,s))}break;case I.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=J(e,s),a=ao[o]??null;this.currentTrack.info.colorSpace.matrix=a}break;case I.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=J(e,s)===2}break;case I.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=J(e,s),a=oo[o]??null;this.currentTrack.info.colorSpace.transfer=a}break;case I.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=J(e,s),a=no[o]??null;this.currentTrack.info.colorSpace.primaries=a}break;case I.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(n,s))}break;case I.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let a=-Co(e,s);try{this.currentTrack.info.rotation=so(a)}catch{}}break;case I.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(n,s))}break;case I.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Co(e,s)}break;case I.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=J(e,s)}break;case I.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=J(e,s)}break;case I.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(n,s)),this.currentCueTime=null}break;case I.CueTime:this.currentCueTime=J(e,s);break;case I.CueTrackPositions:{if(this.currentCueTime===null)break;k(this.currentSegment);let o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(n,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case I.CueTrack:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=J(e,s)}break;case I.CueClusterPosition:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;k(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+J(e,s)}break;case I.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=J(e,s)}break;case I.SimpleBlock:{if(!this.currentCluster)break;let o=fi(e);if(o===null)break;let a=_s(e),c=z(e),l=!!(c&128),u=c>>1&3;this.getTrackDataInCluster(this.currentCluster,o).blocks.push({timestamp:a,duration:0,isKeyFrame:l,referencedTimestamps:[],data:W(e,s-(e.filePos-n)),lacing:u})}break;case I.BlockGroup:{if(!this.currentCluster)break;if(this.readContiguousElements(e.slice(n,s)),this.currentBlock){for(let o=0;o<this.currentBlock.referencedTimestamps.length;o++)this.currentBlock.referencedTimestamps[o]+=this.currentBlock.timestamp;this.currentBlock=null}}break;case I.Block:{if(!this.currentCluster)break;let o=fi(e);if(o===null)break;let a=_s(e),l=z(e)>>1&3,u=this.getTrackDataInCluster(this.currentCluster,o);this.currentBlock={timestamp:a,duration:0,isKeyFrame:!0,referencedTimestamps:[],data:W(e,s-(e.filePos-n)),lacing:l},u.blocks.push(this.currentBlock)}break;case I.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=J(e,s)}break;case I.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;let o=Df(e,s);this.currentBlock.referencedTimestamps.push(o)}break;case I.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(n,s));break;case I.Targets:this.readContiguousElements(e.slice(n,s));break;case I.TargetTypeValue:J(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case I.TagTrackUID:case I.TagEditionUID:case I.TagChapterUID:case I.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case I.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(n,s))}break;case I.TagName:this.currentSimpleTagName=mi(e,s);break;case I.TagString:{if(!this.currentSimpleTagName)break;let o=mi(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case I.TagBinary:{if(!this.currentSimpleTagName)break;let o=W(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case I.AttachedFile:{if(!this.currentSegment)break;if(this.currentAttachedFile={fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(n,s)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let o=this.currentAttachedFile.fileName,a="unknown";if(o){let c=o.toLowerCase();c.startsWith("cover.")?a="coverFront":c.startsWith("back.")&&(a="coverBack")}this.currentSegment.metadataTags.images??=[],this.currentSegment.metadataTags.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:a,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case I.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=mi(e,s)}break;case I.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ar(e,s)}break;case I.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=W(e,s)}break;case I.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=mi(e,s)}break}return e.filePos=n+s,!0}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{let s=new Date(t);Number.isNaN(s.getTime())||(r.date??=s)}break;case"track_number":case"part_number":{let s=t.split("/"),n=Number.parseInt(s[0],10),o=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(r.trackNumber??=n),o&&Number.isInteger(o)&&o>0&&(r.tracksTotal??=o)}break;case"disc_number":case"disc":{let s=t.split("/"),n=Number.parseInt(s[0],10),o=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(r.discNumber??=n),o&&Number.isInteger(o)&&o>0&&(r.discsTotal??=o)}break}}},zo=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}async getFirstPacket(e){return this.performClusterLookup(()=>{let t=this.internalTrack.segment.clusters[0]??null;if(t?.isKnownToBeFirstCluster){let r=t;for(;r;){if(r.trackData.get(this.internalTrack.id))return{clusterIndex:ae(this.internalTrack.clusters,r.elementStartPos,n=>n.elementStartPos),blockIndex:0,correctBlockFound:!0};r=r.nextCluster}}return{clusterIndex:-1,blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}intoTimescale(e){return Ir(e*this.internalTrack.segment.timestampFactor,14)}async getPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findBlockInClustersForTimestamp(r),r,r,t)}async getNextPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let s=r.cluster.trackData.get(this.internalTrack.id),n=ae(this.internalTrack.clusters,r.cluster.elementStartPos,o=>o.elementStartPos);return k(n!==-1),this.performClusterLookup(()=>{if(r.blockIndex+1<s.blocks.length)return{clusterIndex:n,blockIndex:r.blockIndex+1,correctBlockFound:!0};{let o=r.cluster;for(;o.nextCluster;)if(o=o.nextCluster,o.trackData.get(this.internalTrack.id)){let c=ae(this.internalTrack.clusters,o.elementStartPos,l=>l.elementStartPos);return k(c!==-1),{clusterIndex:c,blockIndex:0,correctBlockFound:!0}}return{clusterIndex:n,blockIndex:-1,correctBlockFound:!1}}},-1/0,1/0,t)}async getKeyPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findKeyBlockInClustersForTimestamp(r),r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let s=r.cluster.trackData.get(this.internalTrack.id),n=ae(this.internalTrack.clusters,r.cluster.elementStartPos,o=>o.elementStartPos);return k(n!==-1),this.performClusterLookup(()=>{let o=s.blocks.findIndex((a,c)=>a.isKeyFrame&&c>r.blockIndex);if(o!==-1)return{clusterIndex:n,blockIndex:o,correctBlockFound:!0};{let a=r.cluster;for(;a.nextCluster;){a=a.nextCluster;let c=a.trackData.get(this.internalTrack.id);if(c&&c.firstKeyFrameTimestamp!==null){let l=ae(this.internalTrack.clusters,a.elementStartPos,h=>h.elementStartPos);k(l!==-1);let u=c.blocks.findIndex(h=>h.isKeyFrame);return k(u!==-1),{clusterIndex:l,blockIndex:u,correctBlockFound:!0}}}return{clusterIndex:n,blockIndex:-1,correctBlockFound:!1}}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).blocks[t];k(n);let o=r.metadataOnly?Ee:n.data,a=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,l=new ce(o,n.isKeyFrame?"key":"delta",a,c,e.dataStartPos+t,n.data.byteLength);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}findBlockInClustersForTimestamp(e){let t=Q(this.internalTrack.clusters,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,s=!1;if(t!==-1){let o=this.internalTrack.clusters[t].trackData.get(this.internalTrack.id),a=Q(o.presentationTimestamps,e,c=>c.timestamp);k(a!==-1),r=o.presentationTimestamps[a].blockIndex,s=e<o.endTimestamp}return{clusterIndex:t,blockIndex:r,correctBlockFound:s}}findKeyBlockInClustersForTimestamp(e){let t=Q(this.internalTrack.clustersWithKeyFrame,e,o=>o.trackData.get(this.internalTrack.id).firstKeyFrameTimestamp),r=-1,s=-1,n=!1;if(t!==-1){let o=this.internalTrack.clustersWithKeyFrame[t];r=ae(this.internalTrack.clusters,o.elementStartPos,u=>u.elementStartPos),k(r!==-1);let a=o.trackData.get(this.internalTrack.id),c=co(a.presentationTimestamps,u=>a.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=e);k(c!==-1),s=a.presentationTimestamps[c].blockIndex,n=e<a.endTimestamp}return{clusterIndex:r,blockIndex:s,correctBlockFound:n}}async performClusterLookup(e,t,r,s){let{demuxer:n,segment:o}=this.internalTrack,a=await o.clusterLookupMutex.acquire();try{let{clusterIndex:c,blockIndex:l,correctBlockFound:u}=e();if(u){let w=this.internalTrack.clusters[c];return this.fetchPacketInCluster(w,l,s)}let h=null,d=c,f=l,m=Q(this.internalTrack.cuePoints,t,w=>w.time),p=m!==-1?this.internalTrack.cuePoints[m]:null,g,y=!1;if(c===-1)g=p?.clusterPosition??o.clusterSeekStartPos,y=g===o.clusterSeekStartPos;else{let w=this.internalTrack.clusters[c];!p||w.elementStartPos>=p.clusterPosition?(g=w.elementEndPos,h=w):g=p.clusterPosition}for(;o.elementEndPos===null||g<=o.elementEndPos-Ve;){if(h){let P=h.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>r)break;if(h.nextCluster){g=h.nextCluster.elementEndPos,h=h.nextCluster;continue}}let w=n.reader.requestSliceRange(g,Ve,ct);if(w instanceof Promise&&(w=await w),!w)break;let _=g,S=lt(w);if(!S||!di.includes(S.id)&&S.id!==I.Void){let P=await Tl(n.reader,_,di,Math.min(o.elementEndPos??1/0,_+tm));if(P){g=P;continue}else break}let T=S.id,v=S.size,M=w.filePos;if(T===I.Cluster){let P=ae(o.clusters,_,he=>he.elementStartPos),C;P===-1?C=await n.readCluster(_,o):C=o.clusters[P],h&&(h.nextCluster=C),h=C,y&&(C.isKnownToBeFirstCluster=!0,y=!1);let{clusterIndex:E,blockIndex:D,correctBlockFound:j}=e();if(j){let he=this.internalTrack.clusters[E];return this.fetchPacketInCluster(he,D,s)}E!==-1&&(d=E,f=D)}if(v===null){T===I.Cluster?(k(h),v=h.elementEndPos-M):v=(await Eo(n.reader,M,vo,o.elementEndPos)).pos-M;let P=M+v;if(o.elementEndPos!==null&&P>o.elementEndPos-Ve)break;{let C=n.reader.requestSliceRange(P,Ve,ct);if(C instanceof Promise&&(C=await C),!C)break;if(Po(C)===I.Segment){o.elementEndPos=P;break}}}g=M+v}let x=d!==-1?this.internalTrack.clusters[d]:null;if(p&&(!x||x.elementStartPos<p.clusterPosition)){let _=this.internalTrack.cuePoints[m-1]?.time??-1/0;return this.performClusterLookup(e,_,r,s)}return x?this.fetchPacketInCluster(x,f,s):null}finally{a()}}},Dl=class extends zo{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 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:po({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,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Sf(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Tf(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?bo(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?wo(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}},Rl=class extends zo{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:go({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}},j_=i=>{let e=new Map;for(let n=0;n<i.length;n++){let o=i[n];e.set(o.timestamp,o)}let t=new Set,r=[],s=n=>{if(!t.has(n)){t.add(n);for(let o=0;o<n.referencedTimestamps.length;o++){let a=n.referencedTimestamps[o],c=e.get(a);c&&s(c)}r.push(n)}};for(let n=0;n<i.length;n++)s(i[n]);return r};var Go=class extends We{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Je,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 Ae(new Ol(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,bi);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=ks(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await Ts(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let r=zf(t.mpegVersionId,t.channel),s=this.reader.requestSlice(e.startPos+r,4);if(s instanceof Promise&&(s=await s),s){let a=B(s);if(a===Of||a===Uf)return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=t.audioSamplesInFrame/t.sampleRate,o={timestamp:this.nextTimestampInSamples/t.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(o),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 k(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,r=!1;for(;;){let s=this.reader.requestSlice(t,bi);if(s instanceof Promise&&(s=await s),!s)break;let n=ks(s);if(!n)break;r=!0;let o=this.reader.requestSlice(s.filePos,n.size);if(o instanceof Promise&&(o=await o),!o)break;Vf(o,n,this.metadataTags),t=s.filePos+n.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=Ss){let s=this.reader.requestSlice(this.reader.fileSize-Ss,Ss);s instanceof Promise&&(s=await s),k(s),de(s,3)==="TAG"&&Lf(s,this.metadataTags)}return this.metadataTags}finally{e()}}},Ol=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return k(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 Pe}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return k(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return k(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}async getDecoderConfig(){return k(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=Ee;else{let n=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=W(n,r.dataSize)}return new ce(s,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let s=ae(this.demuxer.loadedSamples,e.timestamp,o=>o.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");let n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let s=Q(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var No=class extends We{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,cr,Rr);if(t instanceof Promise&&(t=await t),!t)break;let r=wi(t);if(!r||!!!(r.headerType&2))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(let t of this.bitstreams){let r=await this.readPacket(t.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,t):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,t),t.codecInfo.codec!==null&&this.tracks.push(new Ae(new Ul(t,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s||(r=await this.findNextPacketStart(s),!r))return;let n=await this.readPacket(r.startPage,r.startSegmentIndex);if(!n||s.data[0]!==3||n.data[0]!==5)return;let o=[],a=h=>{for(;o.push(Math.min(255,h)),!(h<255);)h-=255};a(e.data.length),a(s.data.length);let c=new Uint8Array(1+o.length+e.data.length+s.data.length+n.data.length);c[0]=o.length,c.set(o,1),c.set(e.data,1+o.length),c.set(s.data,1+o.length+e.data.length),c.set(n.data,1+o.length+e.data.length+s.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=n;let l=oe(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Cf(n.data).modeBlockflags},this.readVorbisComments(s.data.subarray(7))}async readOpusMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=s;let n=vf(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=n.inputSampleRate,t.codecInfo.opusInfo={preSkip:n.preSkip},this.readVorbisComments(s.data.subarray(8))}readVorbisComments(e){let t=oe(e),r=0,s=t.getUint32(r,!0);r+=4;let n=Be.decode(e.subarray(r,r+s));r+=s,s>0&&(this.metadataTags.raw??={},this.metadataTags.raw.vendor??=n);let o=t.getUint32(r,!0);r+=4;for(let a=0;a<o;a++){let c=t.getUint32(r,!0);r+=4;let l=Be.decode(e.subarray(r,r+c));r+=c;let u=l.indexOf("=");if(u===-1)continue;let h=l.slice(0,u).toUpperCase(),d=l.slice(u+1);switch(this.metadataTags.raw??={},this.metadataTags.raw[h]??=d,h){case"TITLE":this.metadataTags.title??=d;break;case"DESCRIPTION":this.metadataTags.description??=d;break;case"ARTIST":this.metadataTags.artist??=d;break;case"ALBUM":this.metadataTags.album??=d;break;case"ALBUMARTIST":this.metadataTags.albumArtist??=d;break;case"COMMENT":this.metadataTags.comment??=d;break;case"LYRICS":this.metadataTags.lyrics??=d;break;case"TRACKNUMBER":{let f=d.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"TRACKTOTAL":{let f=Number.parseInt(d,10);Number.isInteger(f)&&f>0&&(this.metadataTags.tracksTotal??=f)}break;case"DISCNUMBER":{let f=d.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.discNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.discsTotal??=p)}break;case"DISCTOTAL":{let f=Number.parseInt(d,10);Number.isInteger(f)&&f>0&&(this.metadataTags.discsTotal??=f)}break;case"DATE":{let f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"GENRE":this.metadataTags.genre??=d;break;case"METADATA_BLOCK_PICTURE":{let f=pf(d),m=oe(f),p=m.getUint32(0,!1),g=m.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+g)),x=m.getUint32(8+g,!1),w=Be.decode(f.subarray(12+g,12+g+x)),_=m.getUint32(g+x+28),S=f.subarray(g+x+32,g+x+32+_);this.metadataTags.images??=[],this.metadataTags.images.push({data:S,mimeType:y,kind:p===3?"coverFront":p===4?"coverBack":"unknown",name:void 0,description:w||void 0})}break}}}async readPacket(e,t){k(t<e.lacingValues.length);let r=0;for(let h=0;h<t;h++)r+=e.lacingValues[h];let s=e,n=r,o=t,a=[];e:for(;;){let h=this.reader.requestSlice(s.dataStartPos,s.dataSize);h instanceof Promise&&(h=await h),k(h);let d=W(h,s.dataSize);for(;;){if(o===s.lacingValues.length){a.push(d.subarray(r,n));break}let m=s.lacingValues[o];if(n+=m,m<255){a.push(d.subarray(r,n));break e}o++}let f=s.headerStartPos+s.totalSize;for(;;){let m=this.reader.requestSliceRange(f,cr,Rr);if(m instanceof Promise&&(m=await m),!m)return null;let p=wi(m);if(!p)return null;if(s=p,s.serialNumber===e.serialNumber)break;f=s.headerStartPos+s.totalSize}r=0,n=0,o=0}let c=a.reduce((h,d)=>h+d.length,0),l=new Uint8Array(c),u=0;for(let h=0;h<a.length;h++){let d=a[h];l.set(d,u),u+=d.length}return{data:l,endPage:s,endSegmentIndex:o}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let r=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let s=this.reader.requestSliceRange(r,cr,Rr);if(s instanceof Promise&&(s=await s),!s)return null;let n=wi(s);if(!n)return null;if(n.serialNumber===e.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};r=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.getCodecParameterString()));return $f({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(r=>r.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Ul=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Je,this.internalSampleRate=e.codecInfo.codec==="opus"?yf: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 k(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 Pe}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"?(k(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;let{durationInSamples:s,vorbisBlockSize:n}=jf(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),o=new ce(r.metadataOnly?Ee:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,s/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(o,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),o}async getFirstPacket(e){k(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(k(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);let s=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");let s=await this.demuxer.findNextPacketStart(r.packet);if(!s)return null;let n=r.timestampInSamples+r.durationInSamples,o=await this.demuxer.readPacket(s.startPage,s.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:n,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let r=Ir(e*this.internalSampleRate,14);if(r===0)return this.getFirstPacket(t);if(r<0)return null;k(this.bitstream.lastMetadataPacket);let s=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let n=s.startPage,o=this.demuxer.reader.fileSize,a=[n];e:for(;n.headerStartPos+n.totalSize<o;){let x=n.headerStartPos,w=Math.floor((x+o)/2),_=w;for(;;){let S=Math.min(_+qf,o-cr),T=this.demuxer.reader.requestSlice(_,S-_);if(T instanceof Promise&&(T=await T),k(T),!Xf(T,S)){o=w+cr;continue e}let M=this.demuxer.reader.requestSliceRange(T.filePos,cr,Rr);M instanceof Promise&&(M=await M),k(M);let P=wi(M);k(P);let C=!1;if(P.serialNumber===this.bitstream.serialNumber)C=!0;else{let D=this.demuxer.reader.requestSlice(P.headerStartPos,P.totalSize);D instanceof Promise&&(D=await D),k(D);let j=W(D,P.totalSize);C=Hf(j)===P.checksum}if(!C){_=P.headerStartPos+4;continue}if(C&&P.serialNumber!==this.bitstream.serialNumber){_=P.headerStartPos+P.totalSize;continue}if(P.granulePosition===-1){_=P.headerStartPos+P.totalSize;continue}this.granulePositionToTimestampInSamples(P.granulePosition)>r?o=P.headerStartPos:(n=P,a.push(P));continue e}}let c=s.startPage;for(let x of a){if(x.granulePosition===n.granulePosition)break;(!c||x.headerStartPos>c.headerStartPos)&&(c=x)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===n.granulePosition);){let x=l.headerStartPos+l.totalSize,w=this.demuxer.reader.requestSliceRange(x,cr,Rr);w instanceof Promise&&(w=await w),k(w);let _=wi(w);k(_),l=_,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}k(l.granulePosition!==-1);let h=null,d,f,m=l,p=0;if(l.headerStartPos===s.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),f=!0,h=0;else{d=0,f=!1;for(let _=l.lacingValues.length-1;_>=0;_--)if(l.lacingValues[_]<255){h=_+1;break}if(h===null)throw new Error("Invalid page with granule position: no packets end on this page.");p=h-1;let x={data:Ee,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(x)){let _=im(u,l,h);k(_);let S=rm(u,_.page,_.segmentIndex);S&&(l=S.page,h=S.segmentIndex)}else for(;;){let _=im(u,l,h);if(!_)break;let S=rm(u,_.page,_.segmentIndex);if(!S)break;if(l=S.page,h=S.segmentIndex,_.page.headerStartPos!==m.headerStartPos){m=_.page,p=_.segmentIndex;break}}}let g=null,y=null;for(;l!==null;){k(h!==null);let x=await this.demuxer.readPacket(l,h);if(!x)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&h<s.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:d,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);k(S);let T=this.encodedPacketToMetadata.get(S);if(k(T),!f&&x.endPage.headerStartPos===m.headerStartPos&&x.endSegmentIndex===p?(d=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:d-T.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),k(S),T=this.encodedPacketToMetadata.get(S),k(T)):d+=T.durationInSamples,g=S,y=T,f&&(Math.max(d,0)>r||Math.max(T.timestampInSamples,0)===r))break}let _=await this.demuxer.findNextPacketStart(x);if(!_)break;l=_.startPage,h=_.startSegmentIndex}return g}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let s=Ir(e*this.internalSampleRate,14);e=s/this.internalSampleRate;let n=Q(this.sequentialScanCache,s,c=>c.timestampInSamples),o;if(n!==-1){let c=this.sequentialScanCache[n];o=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else o=await this.getFirstPacket(t);let a=0;for(;o&&o.timestamp<e;){let c=await this.getNextPacket(o,t);if(!c||c.timestamp>e)break;if(o=c,a++,a===100){a=0;let l=this.encodedPacketToMetadata.get(o);k(l),this.sequentialScanCache.length>0&&k(ve(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return o}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},rm=(i,e,t)=>{let r=e,s=t;e:for(;;){for(s--,s;s>=0;s--)if(r.lacingValues[s]<255){s++;break e}if(k(s===-1),!(r.headerType&1)){s=0;break}let o=dl(i,a=>a.headerStartPos<r.headerStartPos);if(!o)return null;r=o,s=r.lacingValues.length}if(k(s!==-1),s===r.lacingValues.length){let n=i[i.indexOf(r)+1];k(n),r=n,s=0}return{page:r,segmentIndex:s}},im=(i,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let r=dl(i,s=>s.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var vi=7,Pi=9,Is=i=>{let e=i.filePos,t=W(i,9),r=new fe(t);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;let o=r.readBits(1),a=r.readBits(2)+1,c=r.readBits(4);if(c===15)return null;r.skipBits(1);let l=r.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let u=r.readBits(13);r.skipBits(11);let h=r.readBits(2)+1;if(h!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let d=null;return o===1?i.filePos-=2:d=r.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:h,crcCheck:d,startPos:e}};var zl=1024,Lo=class extends We{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new Je,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();k(this.firstFrameHeader),this.tracks=[new Ae(new Gl(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,vi,Pi);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Is(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let r=bs[t.samplingFrequencyIndex];k(r!==void 0);let s=zl/r,n=t.crcCheck?Pi:vi,o={timestamp:this.nextTimestampInSamples/r,duration:s,dataStart:t.startPos+n,dataSize:t.frameLength-n};this.loadedSamples.push(o),this.nextTimestampInSamples+=zl,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 k(e),e.computeDuration()}async getMetadataTags(){return{}}},Gl=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/zl}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Pe}getCodec(){return"aac"}getInternalCodecId(){return k(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){k(this.demuxer.firstFrameHeader);let e=pl[this.demuxer.firstFrameHeader.channelConfiguration];return k(e!==void 0),e}getSampleRate(){k(this.demuxer.firstFrameHeader);let e=bs[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return k(e!==void 0),e}async getDecoderConfig(){k(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new fe(e),{objectType:r,samplingFrequencyIndex:s,channelConfiguration:n}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),t.writeBits(4,s),t.writeBits(4,n),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(e===-1)return null;let r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=Ee;else{let n=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=W(n,r.dataSize)}return new ce(s,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let s=ae(this.demuxer.loadedSamples,e.timestamp,o=>o.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");let n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let s=Q(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ht=class{},Ms=class extends ht{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),de(t,4)!=="ftyp")?null:de(t,4)}_createDemuxer(e){return new Ro(e)}},Vo=class extends Ms{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Wo=class extends Ms{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Bs=class extends ht{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,ct);if(r instanceof Promise&&(r=await r),!r)return!1;let s=_l(r);if(s===null||s<1||s>8||J(r,s)!==I.EBML)return!1;let o=Sl(r);if(o===null)return!1;let a=e._reader.requestSlice(r.filePos,o);if(a instanceof Promise&&(a=await a),!a)return!1;let c=r.filePos;for(;a.filePos<=c+o-Ve;){let l=lt(a);if(!l)break;let{id:u,size:h}=l,d=a.filePos;if(h===null)return!1;switch(u){case I.EBMLVersion:if(J(a,h)!==1)return!1;break;case I.EBMLReadVersion:if(J(a,h)!==1)return!1;break;case I.DocType:if(ar(a,h)!==t)return!1;break;case I.DocTypeVersion:if(J(a,h)>4)return!1;break}a.filePos=d+h}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Uo(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Ho=class extends Bs{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},jo=class extends ht{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,s=!1;for(;;){let l=e._reader.requestSlice(r,bi);if(l instanceof Promise&&(l=await l),!l)break;let u=ks(l);if(!u)break;s=!0,r=l.filePos+u.size}let n=await Ts(e._reader,r,r+4096);if(!n)return!1;if(s)return!0;r=n.startPos+=n.header.totalSize;let o=await Ts(e._reader,r,r+4);if(!o)return!1;let a=n.header,c=o.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new Go(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},$o=class extends ht{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let r=de(t,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(t.skip(4),de(t,4)==="WAVE")}_createDemuxer(e){return new Fo(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},qo=class extends ht{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?de(t,4)==="OggS":!1}_createDemuxer(e){return new No(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Xo=class extends ht{async _canReadInput(e){let t=e._reader.requestSliceRange(0,vi,Pi);if(t instanceof Promise&&(t=await t),!t)return!1;let r=Is(t);if(!r||(t=e._reader.requestSliceRange(r.frameLength,vi,Pi),t instanceof Promise&&(t=await t),!t))return!1;let s=Is(t);return s?r.objectType===s.objectType&&r.samplingFrequencyIndex===s.samplingFrequencyIndex&&r.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new Lo(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},sm=new Vo,nm=new Wo,om=new Bs,am=new Ho,cm=new jo,lm=new $o,um=new qo,hm=new Xo,lr=[sm,nm,om,am,lm,um,cm,hm];var _t=class{constructor(e){if(this._demuxerPromise=null,this._format=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof ht)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ur))throw new TypeError("options.source must be a Source.");this._formats=e.formats,this._source=e.source,this._reader=new _o(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(),k(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()}};var Yo=class{count=0;#e=new Map;register(e,t){this.#e.set(e,t)}unregister(e){this.#e.delete(e)}dispatch(e,t){this.#e.get(e)?.(t)}};var dm=i=>ro.host(e=>({async world(){i.count++}}));async function zr(i){return i instanceof Blob?new Es(i):new As(i)}var Ko=class{machina;thread;static async setup(e){let t=new Yo,r=await ro.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:dm(t)});return new this(t,r)}constructor(e,t){this.machina=e,this.thread=t}async hello(){return this.thread.work.hello()}async getAudioDuration(e){return await(await new _t({source:await zr(e),formats:lr}).getPrimaryAudioTrack())?.computeDuration()}async getVideoDuration(e){return await(await new _t({source:await zr(e),formats:lr}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,r=new TransformStream({async transform(s,n){let o=await e.onFrame?.(s)??s;t?.close(),n.enqueue(o),t=o}});return this.thread.work.decodeVideo[Pr]({transfer:[r.writable]})({source:e.source,video:r.writable,start:e.start,end:e.end}),r.readable}decodeAudio(e){let t=new TransformStream;return this.thread.work.decodeAudio[Pr]({transfer:[t.writable]})({source:e.source,audio:t.writable,start:e.start,end:e.end}),t.readable}async encode({video:e,audio:t,config:r}){let n=await(await window.showSaveFilePicker()).createWritable(),o=new WritableStream({async write(a){await n.write(a)},async close(){await n.close()}});return await this.thread.work.encode[Pr]({transfer:[t??[],e??[],o]})({video:e,audio:t,config:r,bridge:o})}async composite(e){let t=this.#e(e);return await this.thread.work.composite[Pr]({transfer:t})(e)}#e(e){let t=[],r=s=>{if(Array.isArray(s))for(let n of s)r(n);else s&&typeof s=="object"&&"kind"in s&&s.kind==="image"&&s.frame instanceof VideoFrame&&t.push(s.frame)};return r(e),t}};function Se(i,e,t,r){return new(t||(t=Promise))(function(s,n){function o(l){try{c(r.next(l))}catch(u){n(u)}}function a(l){try{c(r.throw(l))}catch(u){n(u)}}function c(l){var u;l.done?s(l.value):(u=l.value,u instanceof t?u:new t(function(h){h(u)})).then(o,a)}c((r=r.apply(i,e||[])).next())})}var Gr=class{constructor(){this.listeners={}}on(e,t,r){if(this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),r?.once){let s=()=>{this.un(e,s),this.un(e,t)};return this.on(e,s),s}return()=>this.un(e,t)}un(e,t){var r;(r=this.listeners[e])===null||r===void 0||r.delete(t)}once(e,t){return this.on(e,t,{once:!0})}unAll(){this.listeners={}}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(r=>r(...t))}},Zo={decode:function(i,e){return Se(this,void 0,void 0,function*(){let t=new AudioContext({sampleRate:e});return t.decodeAudioData(i).finally(()=>t.close())})},createBuffer:function(i,e){return typeof i[0]=="number"&&(i=[i]),function(t){let r=t[0];if(r.some(s=>s>1||s<-1)){let s=r.length,n=0;for(let o=0;o<s;o++){let a=Math.abs(r[o]);a>n&&(n=a)}for(let o of t)for(let a=0;a<s;a++)o[a]/=n}}(i),{duration:e,length:i[0].length,sampleRate:i[0].length/e,numberOfChannels:i.length,getChannelData:t=>i?.[t],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};function mm(i,e){let t=e.xmlns?document.createElementNS(e.xmlns,i):document.createElement(i);for(let[r,s]of Object.entries(e))if(r==="children"&&s)for(let[n,o]of Object.entries(s))o instanceof Node?t.appendChild(o):typeof o=="string"?t.appendChild(document.createTextNode(o)):t.appendChild(mm(n,o));else r==="style"?Object.assign(t.style,s):r==="textContent"?t.textContent=s:t.setAttribute(r,s.toString());return t}function fm(i,e,t){let r=mm(i,e||{});return t?.appendChild(r),r}var $_=Object.freeze({__proto__:null,createElement:fm,default:fm}),q_={fetchBlob:function(i,e,t){return Se(this,void 0,void 0,function*(){let r=yield fetch(i,t);if(r.status>=400)throw new Error(`Failed to fetch ${i}: ${r.status} (${r.statusText})`);return function(s,n){Se(this,void 0,void 0,function*(){if(!s.body||!s.headers)return;let o=s.body.getReader(),a=Number(s.headers.get("Content-Length"))||0,c=0,l=h=>Se(this,void 0,void 0,function*(){c+=h?.length||0;let d=Math.round(c/a*100);n(d)}),u=()=>Se(this,void 0,void 0,function*(){let h;try{h=yield o.read()}catch{return}h.done||(l(h.value),yield u())});u()})}(r.clone(),e),r.blob()})}},Nl=class extends Gr{constructor(e){super(),this.isExternalMedia=!1,e.media?(this.media=e.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),e.mediaControls&&(this.media.controls=!0),e.autoplay&&(this.media.autoplay=!0),e.playbackRate!=null&&this.onMediaEvent("canplay",()=>{e.playbackRate!=null&&(this.media.playbackRate=e.playbackRate)},{once:!0})}onMediaEvent(e,t,r){return this.media.addEventListener(e,t,r),()=>this.media.removeEventListener(e,t,r)}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){let e=this.getSrc();e.startsWith("blob:")&&URL.revokeObjectURL(e)}canPlayType(e){return this.media.canPlayType(e)!==""}setSrc(e,t){let r=this.getSrc();if(e&&r===e)return;this.revokeSrc();let s=t instanceof Blob&&(this.canPlayType(t.type)||!e)?URL.createObjectURL(t):e;if(r&&this.media.removeAttribute("src"),s||e)try{this.media.src=s}catch{this.media.src=e}}destroy(){this.isExternalMedia||(this.media.pause(),this.media.remove(),this.revokeSrc(),this.media.removeAttribute("src"),this.media.load())}setMediaElement(e){this.media=e}play(){return Se(this,void 0,void 0,function*(){return this.media.play()})}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(e){this.media.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(e){this.media.volume=e}getMuted(){return this.media.muted}setMuted(e){this.media.muted=e}getPlaybackRate(){return this.media.playbackRate}isSeeking(){return this.media.seeking}setPlaybackRate(e,t){t!=null&&(this.media.preservesPitch=t),this.media.playbackRate=e}getMediaElement(){return this.media}setSinkId(e){return this.media.setSinkId(e)}},Ds=class i extends Gr{constructor(e,t){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.subscriptions=[],this.unsubscribeOnScroll=[],this.subscriptions=[],this.options=e;let r=this.parentFromOptionsContainer(e.container);this.parent=r;let[s,n]=this.initHtml();r.appendChild(s),this.container=s,this.scrollContainer=n.querySelector(".scroll"),this.wrapper=n.querySelector(".wrapper"),this.canvasWrapper=n.querySelector(".canvases"),this.progressWrapper=n.querySelector(".progress"),this.cursor=n.querySelector(".cursor"),t&&n.appendChild(t),this.initEvents()}parentFromOptionsContainer(e){let t;if(typeof e=="string"?t=document.querySelector(e):e instanceof HTMLElement&&(t=e),!t)throw new Error("Container not found");return t}initEvents(){let e=t=>{let r=this.wrapper.getBoundingClientRect(),s=t.clientX-r.left,n=t.clientY-r.top;return[s/r.width,n/r.height]};if(this.wrapper.addEventListener("click",t=>{let[r,s]=e(t);this.emit("click",r,s)}),this.wrapper.addEventListener("dblclick",t=>{let[r,s]=e(t);this.emit("dblclick",r,s)}),this.options.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.scrollContainer.addEventListener("scroll",()=>{let{scrollLeft:t,scrollWidth:r,clientWidth:s}=this.scrollContainer,n=t/r,o=(t+s)/r;this.emit("scroll",n,o,t,t+s)}),typeof ResizeObserver=="function"){let t=this.createDelay(100);this.resizeObserver=new ResizeObserver(()=>{t().then(()=>this.onContainerResize()).catch(()=>{})}),this.resizeObserver.observe(this.scrollContainer)}}onContainerResize(){let e=this.parent.clientWidth;e===this.lastContainerWidth&&this.options.height!=="auto"||(this.lastContainerWidth=e,this.reRender())}initDrag(){this.subscriptions.push(function(e,t,r,s,n=3,o=0,a=100){if(!e)return()=>{};let c=matchMedia("(pointer: coarse)").matches,l=()=>{},u=h=>{if(h.button!==o)return;h.preventDefault(),h.stopPropagation();let d=h.clientX,f=h.clientY,m=!1,p=Date.now(),g=S=>{if(S.preventDefault(),S.stopPropagation(),c&&Date.now()-p<a)return;let T=S.clientX,v=S.clientY,M=T-d,P=v-f;if(m||Math.abs(M)>n||Math.abs(P)>n){let C=e.getBoundingClientRect(),{left:E,top:D}=C;m||(r?.(d-E,f-D),m=!0),t(M,P,T-E,v-D),d=T,f=v}},y=S=>{if(m){let T=S.clientX,v=S.clientY,M=e.getBoundingClientRect(),{left:P,top:C}=M;s?.(T-P,v-C)}l()},x=S=>{S.relatedTarget&&S.relatedTarget!==document.documentElement||y(S)},w=S=>{m&&(S.stopPropagation(),S.preventDefault())},_=S=>{m&&S.preventDefault()};document.addEventListener("pointermove",g),document.addEventListener("pointerup",y),document.addEventListener("pointerout",x),document.addEventListener("pointercancel",x),document.addEventListener("touchmove",_,{passive:!1}),document.addEventListener("click",w,{capture:!0}),l=()=>{document.removeEventListener("pointermove",g),document.removeEventListener("pointerup",y),document.removeEventListener("pointerout",x),document.removeEventListener("pointercancel",x),document.removeEventListener("touchmove",_),setTimeout(()=>{document.removeEventListener("click",w,{capture:!0})},10)}};return e.addEventListener("pointerdown",u),()=>{l(),e.removeEventListener("pointerdown",u)}}(this.wrapper,(e,t,r)=>{this.emit("drag",Math.max(0,Math.min(1,r/this.wrapper.getBoundingClientRect().width)))},e=>{this.isDragging=!0,this.emit("dragstart",Math.max(0,Math.min(1,e/this.wrapper.getBoundingClientRect().width)))},e=>{this.isDragging=!1,this.emit("dragend",Math.max(0,Math.min(1,e/this.wrapper.getBoundingClientRect().width)))}))}getHeight(e,t){var r;let s=((r=this.audioData)===null||r===void 0?void 0:r.numberOfChannels)||1;if(e==null)return 128;if(!isNaN(Number(e)))return Number(e);if(e==="auto"){let n=this.parent.clientHeight||128;return t?.every(o=>!o.overlay)?n/s:n}return 128}initHtml(){let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=this.options.cspNonce&&typeof this.options.cspNonce=="string"?this.options.cspNonce.replace(/"/g,""):"";return t.innerHTML=`
|
|
576
576
|
<style${r?` nonce="${r}"`:""}>
|
|
577
577
|
:host {
|
|
578
578
|
user-select: none;
|