@omnimedia/omnitool 1.1.0-60 → 1.1.0-62
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/demo/routines/playback-test.ts +2 -17
- package/s/driver/fns/work.ts +3 -4
- package/s/timeline/renderers/player/parts/playback.ts +5 -2
- package/s/timeline/renderers/player/player.ts +19 -9
- package/x/demo/demo.bundle.min.js +4 -4
- package/x/demo/demo.bundle.min.js.map +3 -3
- package/x/demo/routines/playback-test.js +2 -16
- package/x/demo/routines/playback-test.js.map +1 -1
- package/x/driver/driver.worker.bundle.min.js +7 -11
- package/x/driver/driver.worker.bundle.min.js.map +4 -4
- package/x/driver/fns/work.js +0 -2
- package/x/driver/fns/work.js.map +1 -1
- package/x/index.html +2 -2
- package/x/tests.bundle.min.js +5 -5
- package/x/tests.bundle.min.js.map +3 -3
- package/x/tests.html +1 -1
- package/x/timeline/renderers/player/parts/playback.d.ts +2 -1
- package/x/timeline/renderers/player/parts/playback.js +4 -2
- package/x/timeline/renderers/player/parts/playback.js.map +1 -1
- package/x/timeline/renderers/player/player.d.ts +2 -2
- package/x/timeline/renderers/player/player.js +17 -10
- package/x/timeline/renderers/player/player.js.map +1 -1
- package/x/driver/WebGLRenderer-OMRWYQIV.js +0 -2
- package/x/driver/WebGLRenderer-OMRWYQIV.js.map +0 -7
- package/x/driver/WebGPURenderer-KQJB2OJJ.js +0 -2
- package/x/driver/WebGPURenderer-KQJB2OJJ.js.map +0 -7
- package/x/driver/browserAll-YBZEJCN3.js +0 -2
- package/x/driver/browserAll-YBZEJCN3.js.map +0 -7
- package/x/driver/chunk-3L3MB5NY.js +0 -393
- package/x/driver/chunk-3L3MB5NY.js.map +0 -7
- package/x/driver/chunk-42BQ4XKE.js +0 -269
- package/x/driver/chunk-42BQ4XKE.js.map +0 -7
- package/x/driver/chunk-4HAYG3N5.js +0 -327
- package/x/driver/chunk-4HAYG3N5.js.map +0 -7
- package/x/driver/chunk-BFBY7VYB.js +0 -42
- package/x/driver/chunk-BFBY7VYB.js.map +0 -7
- package/x/driver/chunk-KM6O72WE.js +0 -157
- package/x/driver/chunk-KM6O72WE.js.map +0 -7
- package/x/driver/chunk-N6HD4WYJ.js +0 -2
- package/x/driver/chunk-N6HD4WYJ.js.map +0 -7
- package/x/driver/chunk-WCZ2O3UN.js +0 -15
- package/x/driver/chunk-WCZ2O3UN.js.map +0 -7
- package/x/driver/chunk-XWNSF3WJ.js +0 -2
- package/x/driver/chunk-XWNSF3WJ.js.map +0 -7
- package/x/driver/webworkerAll-BKJQW6P7.js +0 -2
- package/x/driver/webworkerAll-BKJQW6P7.js.map +0 -7
package/x/tests.bundle.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-OTQK6FAJ.js";import{c as Xr,j as is,k as ss,l as
|
|
1
|
+
import"./chunk-OTQK6FAJ.js";import{c as Xr,j as is,k as ss,l as No}from"./chunk-W33LM336.js";import"./chunk-Q7JBQNE4.js";import"./chunk-A45M2HJC.js";import"./chunk-4ONWQOPX.js";import{b as Qr}from"./chunk-W5CN46AR.js";import{Ba as Uo,E as Mo,I as cr,O as Oo,R as os,S as lr,U as Ft,a as Fc,b as Dc,c as Rc,d as Kr,e as es,ea as zo,i as Bo,j as ts,l as rs,n as ns}from"./chunk-WFT3KTZG.js";var kc=Fc((b1,wc)=>{wc.exports=[{name:"Bounce",paramsTypes:{shadow_colour:"vec4",shadow_height:"float",bounces:"float"},defaultParams:{shadow_colour:[0,0,0,.6],shadow_height:.075,bounces:3},glsl:`// Author: Adrian Purser
|
|
2
2
|
// License: MIT
|
|
3
3
|
|
|
4
4
|
uniform vec4 shadow_colour; // = vec4(0.,0.,0.,.6)
|
|
@@ -2331,11 +2331,11 @@ vec4 transition(vec2 uv) {
|
|
|
2331
2331
|
vec4 b=getToColor(p);
|
|
2332
2332
|
return mix(a, b, step(0.0+p.y,progress));
|
|
2333
2333
|
}
|
|
2334
|
-
`,author:"Jake Nelson",license:"MIT",createdAt:"Wed, 1 Nov 2017 15:24:36 -0500",updatedAt:"Thu, 2 Nov 2017 18:37:42 -0500"}]});var We={};Dc(We,{Experiment:()=>Lo,Fail:()=>me,Stderr:()=>at,Stdout:()=>hr,Tube:()=>pr,asTheme:()=>Lc,color:()=>E,colorBgRgb:()=>zc,colorHex:()=>Oc,colorRgb:()=>ds,deliver:()=>$o,execute:()=>Ho,exit:()=>
|
|
2334
|
+
`,author:"Jake Nelson",license:"MIT",createdAt:"Wed, 1 Nov 2017 15:24:36 -0500",updatedAt:"Thu, 2 Nov 2017 18:37:42 -0500"}]});var We={};Dc(We,{Experiment:()=>Lo,Fail:()=>me,Stderr:()=>at,Stdout:()=>hr,Tube:()=>pr,asTheme:()=>Lc,color:()=>E,colorBgRgb:()=>zc,colorHex:()=>Oc,colorRgb:()=>ds,deliver:()=>$o,execute:()=>Ho,exit:()=>Uc,expect:()=>P,getArg:()=>tn,getEnv:()=>rn,hasArg:()=>en,hasEnv:()=>Vc,isColorSupported:()=>Go,isDeno:()=>we,isNode:()=>ke,meta:()=>ie,options:()=>Bc,run:()=>Gc,setExitCode:()=>qo,spy:()=>Hc,suite:()=>Xo,summarize:()=>Ko,test:()=>gr,themes:()=>Dt,uncolor:()=>Nc,writeStderr:()=>jo,writeStdout:()=>Wo});function Yr(t,e="",r="s"){return t===1?e:r}function ur(t){return`${t.toFixed(0)} ms`}function as(t,e){let r=[],n=[];function o(){n.length>0&&(r.push(n),n=[])}for(let s of t)n.push(s),n.length>=e&&o();return o(),r}var me=class extends Error{name=this.constructor.name};var dr=t=>({ok:()=>!!t,available:()=>t!=null,nullish:()=>t==null,happy:()=>t!=null,sad:()=>t==null,is:e=>t===e,isnt:e=>t!==e,gt:e=>t>e,gte:e=>t>=e,lt:e=>t<e,lte:e=>t<=e,throws:e=>{try{if(typeof t!="function")throw new me(".throws() requires a function");return t(),!1}catch(r){return!(e&&!(r instanceof e))}},throwsAsync:async e=>{try{if(typeof t!="function")throw new me(".throwsAsync() requires an async function");let r=t();if(!(r instanceof Promise))throw new me(".throwsAsync() requires an *async* function");return await r,!1}catch(r){return!(e&&!(r instanceof e))}}});function fr(t,e,r,n){return Object.fromEntries(Object.entries(r).map(([o,s])=>{let i=s;return[o,(...c)=>{let l=i(...c);if(l instanceof Promise)return l.then(d=>{if(!d)throw new me(n??ls(t,o,e,c));return d});if(!l)throw new me(n??ls(t,o,e,c));return l}]}))}var Vo=t=>{let e=dr(t);return Object.fromEntries(Object.entries(e).map(([r,n])=>{let o=n;return[r,(...i)=>{let a=o(...i);return a instanceof Promise?a.then(c=>!c):!a}]}))};function Zr(t,e=16){return t.length>e?`${t.slice(0,e)}..`:t}function mr(t){return typeof t>"u"?"undefined":t===null?"null":typeof t=="string"?`"${Zr(t)}"`:typeof t=="number"?Zr(t.toString()):typeof t=="boolean"?t?"true":"false":typeof t=="bigint"||typeof t=="symbol"?Zr(t.toString()):typeof t=="object"?"obj":typeof t=="function"?"fn":"unknown"}function cs(t){return t.map(mr).join(", ")}function ls(t,e,r,n){return t?`expect(${mr(r)}).not.${e}(${cs(n)})`:`expect(${mr(r)}).${e}(${cs(n)})`}var ie=Symbol("meta");function Bc(t){return t}var Lo=class{time;fail;constructor(e,r){this.time=e,this.fail=r}},pr=class{label;fn;path;constructor(e,r,n){this.label=e,this.fn=r,this.path=n}get skip(){return this.fn[ie]?.kind==="skip"}get only(){return this.fn[ie]?.kind==="only"}};function us(t){let e=[];function r(n,o){for(let[s,i]of Object.entries(n))if(typeof i=="function"){let a=i;a[ie]??=n[ie],e.push(new pr(s,a,o))}else{let a=i;a[ie]??=n[ie],r(i,[...o,s])}}return r(t,[]),e}async function Ho(t){let e=us(t),r=e.filter(l=>!l.skip),n=r.filter(l=>l.only),o=n.length>0?n:r;async function s(l){let d=performance.now();return l.fn().then(u=>{let m=performance.now()-d;return{tube:l,experiment:{time:m,fail:u===void 0||u===!0?void 0:u===!1?"test returned false":typeof u=="string"?u:"test returned unknown type"}}}).catch(u=>{let m=performance.now()-d;return{tube:l,experiment:{time:m,fail:typeof u=="string"?u:u instanceof me?u.message:u instanceof Error?`${u.name}: ${u.message}`:mr(u)}}})}let i=performance.now(),a=new Map;for(let l of as([...o],64)){let d=await Promise.all(l.map(s));for(let{tube:u,experiment:m}of d)a.set(u,m)}let c=performance.now()-i;return{tubes:e,selectedTubes:o,experiments:a,time:c}}var P=(t,e)=>({...fr(!1,t,dr(t),e),not:fr(!0,t,Vo(t),e),note:r=>({...fr(!1,t,dr(t),r),not:fr(!0,t,Vo(t),r)})});var Jr=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});function Oc(t){t=t.replace(/^#/,"");let e,r,n,o;if(t.length===3)e=parseInt(t.split("").map(s=>s+s).join(""),16);else if(t.length===6)e=parseInt(t,16);else throw new Error("Invalid hex color");return r=e>>16&255,n=e>>8&255,o=e&255,ds(r,n,o)}function ds(t,e,r){let n=`\x1B[38;2;${t};${e};${r}m`;return o=>`${n}${o}${Jr.reset}`}function zc(t,e,r){let n=`\x1B[48;2;${t};${e};${r}m`;return o=>`${n}${o}${Jr.reset}`}var E={none:t=>t,...Object.fromEntries(Object.entries(Jr).map(([t,e])=>[t,r=>`${e}${r}${Jr.reset}`]))};function Nc(t){return t.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}var hr=class{line;constructor(e){this.line=e}},at=class{line;constructor(e){this.line=e}};function we(){return typeof Deno<"u"&&typeof Deno.version<"u"}function ke(){return typeof process<"u"&&process.versions&&process.versions.node}function Go(){return ke()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":we()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}function Uc(t){ke()?process.exit(t):we()&&Deno.exit(t)}function qo(t){ke()?process.exitCode=t:we()&&(Deno.exitCode=t)}function Vc(t){return ke()?t in process.env:we()?Deno.env.get(t)!==void 0:!1}function en(t){return ke()?process.argv.slice(1).includes(t):we()?Deno.args.includes(t):!1}function ms(t,e){for(let r of e)if(r.includes("=")){let[n,...o]=r.split("=");if(n===t)return o.join("=")}}function tn(t){if(ke())return ms(t,process.argv.slice(1));if(we())return ms(t,Deno.args)}function rn(t){if(ke())return process.env[t];if(we())return Deno.env.get(t)}async function Wo(t){ke()?process.stdout.write(t+`
|
|
2335
2335
|
`):we()?await Deno.stdout.write(new TextEncoder().encode(t+`
|
|
2336
2336
|
`)):console.log(t)}async function jo(t){ke()?process.stderr.write(t+`
|
|
2337
2337
|
`):we()?await Deno.stderr.write(new TextEncoder().encode(t+`
|
|
2338
|
-
`)):console.error(t)}async function $o(t){for(let e of t.outputs)e instanceof at?await jo(e.line):await Wo(e.line);qo(t.code)}function Ko(t,e){let{verbose:r,theme:{icons:n,colors:o}}=e,s=[...t.experiments.values()].filter(T=>T.fail),i=[...t.experiments.values()].filter(T=>!T.fail),a=t.tubes.length,c=i.length,l=s.length,d=t.tubes.filter(T=>T.skip).length,u=t.tubes.filter(T=>T.only).length,m=[],f=T=>m.push(new hr(T)),p=T=>m.push(new at(T)),g=0;function x(T,S){let v=T.only?o.only(` ${n.only} [ONLY]`):T.skip?o.skip(` ${n.skip} [SKIP]`):"";return S&&S.fail?o.errorLabel(n.testFail)+v:S?o.successLabel(n.testSuccess)+v:o.neutral(n.testNeutral)+v}function y(T,S){g+=1;let v=T.path,A=o.errorLabel(T.label),C=[...v.map(o.errorPath),A].join(o.errorGrammar(n.pathSeparator)),R=o.errorMessage(S.fail??"unknown fail"),z=o.errorTime(`${n.timeSeparator}${ur(S.time)}`),B=x(T,S);p(`${B} ${C}${o.errorGrammar(n.messageSeparator)}${R}${z}`)}function b(T,S){g+=1;let v=T.path,A=o.successLabel(T.label),C=[...v.map(o.successPath),A].join(o.successGrammar(n.pathSeparator)),R=o.successTime(`${n.timeSeparator}${ur(S.time)}`),z=x(T,S);f(`${z} ${C}${R}`)}function w(T){g+=1;let S=T.path,v=o.neutralLabel(T.label),A=[...S.map(o.neutral),v].join(o.neutral(n.pathSeparator)),C=x(T,void 0);f(`${C} ${A}`)}for(let T of t.tubes){let S=t.experiments.get(T);S?S.fail?y(T,S):r&&b(T,S):r&&w(T)}if(g>0&&f(""),u){let T=a-u;f(o.only(`${n.only} only ran ${u} test${Yr(u)} (${T} ignored)`))}else d&&f(o.skip(`${n.skip} skipped ${d} test${Yr(d)}`));if(l===0){let T=o.successSuite(n.suiteSuccess),S=o.successLabel(`${c} happy tests`),v=o.successTime(`- ${ur(t.time)}`);f(`${T} ${S} ${v}`)}else{let T=o.errorSuite(n.suiteFail),S=o.errorSuite(`${l} failure${Yr(l)}`),v=o.errorDidnt(`(${c} succeeded)`),A=o.errorTime(`- ${ur(t.time)}`);p(`${T} ${S} ${v} ${A}`)}return{execution:t,outputs:m,code:l>0?1:0}}function Lc(t){return t}var Dt={plain:{colors:{skip:E.none,only:E.none,neutral:E.none,neutralLabel:E.none,successSuite:E.none,successPath:E.none,successGrammar:E.none,successLabel:E.none,successTime:E.none,errorSuite:E.none,errorDidnt:E.none,errorPath:E.none,errorLabel:E.none,errorGrammar:E.none,errorMessage:E.none,errorTime:E.none},icons:{skip:"\u23ED",only:"*",testFail:"\u2718 ",testSuccess:" \u2022",testNeutral:" \u2022",suiteFail:"FAIL!!",suiteSuccess:"good:",timeSeparator:" - ",pathSeparator:" > ",messageSeparator:" :: "}},redgreen:{colors:{skip:E.yellow,only:E.yellow,neutral:t=>E.dim(E.white(t)),neutralLabel:E.white,successSuite:E.brightGreen,successPath:E.green,successGrammar:t=>E.dim(E.green(t)),successLabel:t=>E.bold(E.brightGreen(t)),successTime:t=>E.dim(E.green(t)),errorSuite:E.brightRed,errorDidnt:E.red,errorPath:E.red,errorLabel:t=>E.bold(E.brightRed(t)),errorGrammar:t=>E.dim(E.red(t)),errorMessage:E.red,errorTime:t=>E.dim(E.red(t))},icons:{skip:"\u{1F47B}",only:"\u{1F6A7}",testFail:"\u274C",testSuccess:" \u2022",testNeutral:" \u2022",suiteFail:"\u{1F525}",suiteSuccess:"\u2705",timeSeparator:" - ",pathSeparator:" > ",messageSeparator:" :: "}},seaside:{colors:{skip:E.yellow,only:E.yellow,neutral:t=>E.dim(E.white(t)),neutralLabel:E.white,successSuite:E.brightBlue,successPath:E.blue,successGrammar:t=>E.dim(E.blue(t)),successLabel:t=>E.bold(E.brightBlue(t)),successTime:t=>E.dim(E.blue(t)),errorSuite:E.brightRed,errorDidnt:E.red,errorPath:E.red,errorLabel:t=>E.bold(E.brightRed(t)),errorGrammar:t=>E.dim(E.red(t)),errorMessage:E.red,errorTime:t=>E.dim(E.red(t))},icons:{skip:"\u{1F47B}",only:"\u{1F6A7}",testFail:"\u274C",testSuccess:" \u2022",testNeutral:" \u2022",suiteFail:"\u{1F525}",suiteSuccess:"\u2705",timeSeparator:" - ",pathSeparator:" > ",messageSeparator:" :: "}}};function Hc(t){let e=[];function r(...n){let o=t(...n);return o!=null&&typeof o.then=="function"?o.then(s=>(e.push({args:n,ret:s}),s)):(e.push({args:n,ret:o}),o)}return r.spy={calls:e,get args(){return e.map(n=>n.args)},get rets(){return e.map(n=>n.ret)}},r}var fs=t=>({verbose:t.verbose??(en("--verbose")||tn("--verbose")==="1"||en("-v")||rn("SCIENCE_VERBOSE")==="1"),theme:t.theme??(()=>{let e=tn("--theme")||rn("SCIENCE_THEME");if(e){let r=Dt[e];if(!r)throw new Error(`theme not found "${e}"`);return r}return Dt.redgreen})()});var ps=t=>({...t,colors:Go()?t.colors:Dt.plain.colors});async function Gc(t,e={}){let{verbose:r,theme:n}=fs(e),o=ps(n),s=await Ho(t),i=Ko(s,{verbose:r,theme:o});await $o(i)}function gr(t){return t}gr.only=t=>(t[ie]={kind:"only"},t);gr.skip=t=>(t[ie]={kind:"skip"},t);function Xo(t){return t}Xo.only=t=>(t[ie]={kind:"only"},t);Xo.skip=t=>(t[ie]={kind:"skip"},t);var Rt=Object.freeze({eq(t,e){if(t.length!==e.length)return!1;for(let r=0;r<=t.length;r++)if(t.at(r)!==e.at(r))return!1;return!0},random(t){return crypto.getRandomValues(new Uint8Array(t))}});var ee=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((r,n)=>[r,n])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let r=Math.log2(this.lexicon.characters.length);if(Number.isInteger(r)){let a=0,c=0,l=[];for(let d of e){if(d===this.lexicon.padding?.character)continue;let u=this.lookup[d];if(u===void 0)throw new Error(`Invalid character: ${d}`);for(a=a<<r|u,c+=r;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let n=0n,o=BigInt(this.lexicon.characters.length),s=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),s=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);n=n*o+BigInt(c)}let i=[];for(;n>0n;)i.unshift(Number(n%256n)),n=n/256n;return new Uint8Array(i)}fromBytes(e){let r=Math.log2(this.lexicon.characters.length);if(Number.isInteger(r)){let i=0,a=0,c="";for(let l of e)for(i=i<<8|l,a+=8;a>=r;){a-=r;let d=i>>a&(1<<r)-1;c+=this.lexicon.characters[d]}if(a>0){let l=i<<r-a&(1<<r)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let n=0n;for(let i of e)n=(n<<8n)+BigInt(i);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),s="";for(;n>0n;)s=this.lexicon.characters[Number(n%o)]+s,n=n/o;return s}toInteger(e){if(!e)return 0;let r=0n,n=!1,o=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let s of e){let i=this.lookup[s];if(i===void 0)throw new Error(`Invalid character: ${s}`);r=r*o+BigInt(i)}return Number(n?-r:r)}fromInteger(e){e=Math.floor(e);let r=e<0,n=BigInt(r?-e:e);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),s="";for(;n>0n;)s=this.lexicon.characters[Number(n%o)]+s,n=n/o;return r?`${this.negativePrefix}${s}`:s}random(e=32){return this.fromBytes(Rt.random(e))}};var ve=new ee(ee.lexicons.hex),Yu=new ee(ee.lexicons.base2),Zu=new ee(ee.lexicons.base36),Qo=new ee(ee.lexicons.base58),Ju=new ee(ee.lexicons.base62),ed=new ee(ee.lexicons.base64),td=new ee(ee.lexicons.base64url);var Yo=["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 Zo=["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 Re={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(t,e){let r=Rt.random(t);return this.fromBytes(r,e)},fromBytes(t,e={}){let{groupSize:r=Re.defaults.groupSize,wordSeparator:n=Re.defaults.wordSeparator,groupSeparator:o=Re.defaults.groupSeparator}=e,s=[],i=[];t.forEach((c,l)=>{let d=l%2===0?Yo:Zo;i.push(d[c]),i.length===2&&(s.push(i.join("")),i=[])}),i.length&&s.push(i.join(""));let a=[];for(let c=0;c<s.length;c+=r)a.push(s.slice(c,c+r).join(n));return a.join(o)},toBytes(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");if(e.length/3%1!==0)throw new Error(`invalid triplet count, ${e.length} does not divide into triplets`);let n=[];for(let o=0;o<e.length;o+=3)n.push(e.slice(o,o+3));return new Uint8Array(n.map((o,s)=>{let a=(s%2===0?Yo:Zo).findIndex(c=>c===o);if(a===-1)throw new Error(`unknown triplet ${o}`);return a}))},toHex(t){return ve.fromBytes(Re.toBytes(t))},fromHex(t,e){return Re.fromBytes(ve.toBytes(t),e)}};var Se={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(t){t=t.trim();let e=t.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(o=>o.trim());if(e.length<2)return Re.toBytes(e.join(""));let r=e.pop(),n=e.join("");return new Uint8Array([...Re.toBytes(n),...Qo.toBytes(r)])},parse(t,e){let r=Se.toBytes(t);return Se.build.fromBytes(r,e)},build:{fromBytes(t,e={}){let{delimiter:r,previewBytes:n,sigilBytes:o}={...Se.defaults,...e},s=d=>t.length>0?Re.fromBytes(t.slice(0,d),{wordSeparator:r,groupSeparator:r}):"",i=s(o),a=s(n),c=t.length>n?Qo.fromBytes(t.slice(n)):"",l=[a,c].filter(d=>d.length>0).join(r);return{raw:t,full:l,preview:a,bulk:c,sigil:i,bytes:t,thumbprint:l}},fromHex(t,e){let r=ve.toBytes(t);return Se.build.fromBytes(r,e)}},toHex(t){let e=Se.toBytes(t);return ve.fromBytes(e)},fromBytes(t,e){return Se.build.fromBytes(t,e).full},fromHex(t,e){return Se.fromBytes(ve.toBytes(t),e)},sigil:{fromHex(t,e){return Se.build.fromHex(t,e).sigil},fromBytes(t,e){return Se.build.fromBytes(t,e).sigil}}},hs=Se;var nn=Object.freeze({fromBytes(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(t){if(t.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.slice(r,r+2),16);return e},random(t=32){return this.fromBytes(Rt.random(t))},string(t){return nn.fromBytes(t)},bytes(t){return nn.toBytes(t)}});function Pe(){let t,e,r=new Promise((o,s)=>{t=o,e=s});function n(o){return o.then(t).catch(e),r}return{promise:r,resolve:t,reject:e,entangle:n}}var on=Object.freeze({happy:t=>t!=null,sad:t=>t==null,boolean:t=>typeof t=="boolean",number:t=>typeof t=="number",string:t=>typeof t=="string",bigint:t=>typeof t=="bigint",object:t=>typeof t=="object"&&t!==null,array:t=>Array.isArray(t),fn:t=>typeof t=="function",symbol:t=>typeof t=="symbol"});var sn=class t extends Map{static require(e,r){if(e.has(r))return e.get(r);throw new Error(`required key not found: "${r}"`)}static guarantee(e,r,n){if(e.has(r))return e.get(r);{let o=n();return e.set(r,o),o}}array(){return[...this]}require(e){return t.require(this,e)}guarantee(e,r){return t.guarantee(this,e,r)}};var xr=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function gs(t,e){return t<=0||t===1/0?e():new Promise((r,n)=>{let o=setTimeout(()=>n(new xr(t)),t);e().then(r).catch(n).finally(()=>clearTimeout(o))})}function an(){let t=[];function e(){for(let r of t)r();t=[]}return e.schedule=(...r)=>(t.push(...r),e),e}function xs(t,e){let r=t;for(let n of e)if(r=r[n],on.sad(r))break;return r}function qc(){let t=new Set;async function e(...c){await Promise.all([...t].map(l=>l(...c)))}function r(c){return t.add(c),()=>{t.delete(c)}}async function n(...c){return e(...c)}function o(c){return r(c)}async function s(c){let{promise:l,resolve:d}=Pe(),u=o(async(...m)=>{c&&await c(...m),d(m),u()});return l}function i(){t.clear()}let a={pub:n,sub:o,publish:e,subscribe:r,on:r,next:s,clear:i};return Object.assign(o,a),Object.assign(n,a),a}function Bt(t){let e=qc();return t&&e.sub(t),e.pub}var U;(function(t){t[t.Sequence=0]="Sequence",t[t.Stack=1]="Stack",t[t.Video=2]="Video",t[t.Audio=3]="Audio",t[t.Text=4]="Text",t[t.Gap=5]="Gap",t[t.Spatial=6]="Spatial",t[t.Transition=7]="Transition",t[t.TextStyle=8]="TextStyle"})(U||(U={}));var cn;(function(t){t[t.Crossfade=0]="Crossfade"})(cn||(cn={}));var q=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.timeline.items.find(n=>n.id===e)}get timeline(){return this.state.timeline}getId(){return ve.toInteger(ve.random())}#e(e){this.state.timeline=e(this.state.timeline)}register(e){this.#e(r=>({...r,items:[...r.items,e]}))}textStyle=e=>{let r={id:this.getId(),kind:U.TextStyle,style:e};return this.register(r),r};spatial=e=>{let r={id:this.getId(),kind:U.Spatial,transform:e,enabled:!0};return this.register(r),r};sequence=(...e)=>{let r={id:this.getId(),kind:U.Sequence,childrenIds:e.map(n=>n.id)};return this.register(r),r};stack=(...e)=>{let r={kind:U.Stack,id:this.getId(),childrenIds:e.map(n=>n.id)};return this.register(r),r};video=(e,r)=>{if(!e.hasVideo)throw new Error(`Video clip error: media "${e.datafile.filename}" has no video track.`);let n={kind:U.Video,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:r?.start??0,duration:r?.duration??e.duration};return this.register(n),n};audio=(e,r)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let n={kind:U.Audio,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:r?.start??0,duration:r?.duration??e.duration,gain:r?.gain??1};return this.register(n),n};text=(e,r)=>{let n={id:this.getId(),content:e,kind:U.Text,duration:r?.duration??2e3};return r?.styles&&(n.styleId=this.textStyle(r.styles).id),this.register(n),n};gap=e=>{let r={id:this.getId(),kind:U.Gap,duration:e};return this.register(r),r};transition={crossfade:e=>{let r={id:this.getId(),kind:U.Transition,effect:cn.Crossfade,duration:e};return this.register(r),r}};transform=e=>{let r=[e?.position?.[0]??0,e?.position?.[1]??0],n=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[r,n,o]};addChildren(e,...r){this.#e(n=>(n.items.find(({id:s})=>s===e.id).childrenIds.push(...r.map(s=>s.id)),n))}set=(e,r)=>{this.#e(n=>({...n,items:n.items.map(o=>o.id===e?{...o,...r}:o)}))}};var je=t=>t;function h(t){if(!t)throw new Error("Assertion failed.")}var ln=t=>{let e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},re=t=>t&&t[t.length-1];var L=class t{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,n=7-(this.pos&7),o=(r&1<<n)>>n;return this.pos++,o}readBits(e){if(e===1)return this.readBit();let r=0;for(let n=0;n<e;n++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let n=this.pos+e;for(let o=this.pos;o<n;o++){let s=Math.floor(o/8),i=this.bytes[s],a=7-(o&7);i&=~(1<<a),i|=(r&1<<n-o-1)>>n-o-1<<a,this.bytes[s]=i}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}},_=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},Ce=t=>{let e=_(t);return(e&1)===0?-(e>>1):e+1>>1};var he=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),V=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Y=new TextDecoder;var ni=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),oi={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},un=ni(oi),ii={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},dn=ni(ii),si={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},mn=ni(si);var fn=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),Ie=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,r=new Promise(o=>{e=o}),n=this.currentPromise;return this.currentPromise=r,await n,e}},ai=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),ci=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),ct=(t,e,r)=>{let n=0,o=t.length-1,s=-1;for(;n<=o;){let i=n+o>>1,a=r(t[i]);a===e?(s=i,o=i-1):a<e?n=i+1:o=i-1}return s},N=(t,e,r)=>{let n=0,o=t.length-1,s=-1;for(;n<=o;){let i=n+(o-n+1)/2|0;r(t[i])<=e?(s=i,n=i+1):o=i-1}return s},li=(t,e,r)=>{let n=N(t,r(e),r);t.splice(n+1,0,e)},ne=()=>{let t,e;return{promise:new Promise((n,o)=>{t=n,e=o}),resolve:t,reject:e}};var ui=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return t[r]},pn=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},ys=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},Ts=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},fe=t=>{throw new Error(`Unexpected value: ${t}`)},lt=(t,e,r)=>{let n=t.getUint8(e),o=t.getUint8(e+1),s=t.getUint8(e+2);return r?n|o<<8|s<<16:n<<16|o<<8|s},ws=(t,e,r)=>lt(t,e,r)<<8>>8,ks=(t,e,r,n)=>{r=r>>>0,r=r&16777215,n?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))};var ut=(t,e,r)=>Math.max(e,Math.min(r,t)),Z="und",dt=t=>{let e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},vs=(t,e)=>Math.round(t/e)*e,Ss=t=>{let e=0;for(;t;)e++,t>>=1;return e},Wc=/^[a-z]{3}$/,hn=t=>Wc.test(t),Ae=1e6*(1+Number.EPSILON),di=(t,e)=>{let r={...t,...e};if(t.headers||e.headers){let n=t.headers?bs(t.headers):{},o=e.headers?bs(e.headers):{},s={...n};Object.entries(o).forEach(([i,a])=>{let c=Object.keys(s).find(l=>l.toLowerCase()===i.toLowerCase());c&&delete s[c],s[i]=a}),r.headers=s}return r},bs=t=>{if(t instanceof Headers){let e={};return t.forEach((r,n)=>{e[n]=r}),e}if(Array.isArray(t)){let e={};return t.forEach(([r,n])=>{e[r]=n}),e}return t},mi=async(t,e,r,n,o)=>{let s=0;for(;;)try{return await t(e,r)}catch(i){if(o())throw i;s++;let a=n(s,i,e);if(a===null)throw i;if(console.error("Retrying failed fetch. Error:",i),!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(a>0&&await new Promise(c=>setTimeout(c,1e3*a)),o())throw i}};var br=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Jo=null,$e=()=>Jo!==null?Jo:Jo=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),ei=null,fi=()=>ei!==null?ei:ei=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),ti=null,yr=()=>ti!==null?ti:ti=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),ri=null,Ps=()=>{if(ri!==null)return ri;if(typeof navigator>"u")return null;let t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?ri=Number(t[1]):null},mt=(t,e)=>t!==-1?t:e,gn=(t,e,r,n)=>t<=n&&r<=e;var Is=t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r};var xn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Tr=t=>typeof t=="number"&&!Number.isNaN(t);var Ke=class{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}},bn=class{constructor(e,r,n,o){if(this.data=e,this.mimeType=r,this.name=n,this.description=o,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(o!==void 0&&typeof o!="string")throw new TypeError("description, when provided, must be a string.")}};var se={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};var Xe=["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"],jc=["aac","opus","mp3","vorbis","flac"],Dd=[...jc,...Xe];var ft=[{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 Cs=".01.01.01.01.00",As=".0.110.01.01.01.0";var yn=t=>{let{codec:e,codecDescription:r,colorSpace:n,avcCodecInfo:o,hevcCodecInfo:s,vp9CodecInfo:i,av1CodecInfo:a}=t;if(e==="avc"){if(h(t.avcType!==null),o){let c=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${t.avcType}.${ai(c)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${ai(r.subarray(1,4))}`}else if(e==="hevc"){let c,l,d,u,m,f;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,d=ci(s.generalProfileCompatibilityFlags),u=s.generalTierFlag,m=s.generalLevelIdc,f=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=V(r),x=g.getUint8(1);c=x>>6&3,l=x&31,d=ci(g.getUint32(2)),u=x>>5&1,m=g.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(g.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=d.toString(16).toUpperCase(),p+=".",p+=u===0?"L":"H",p+=m;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!i){let y=t.width*t.height,b=re(ft).level;for(let w of ft)if(y<=w.maxPictureSize){b=w.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}let c=i.profile.toString().padStart(2,"0"),l=i.level.toString().padStart(2,"0"),d=i.bitDepth.toString().padStart(2,"0"),u=i.chromaSubsampling.toString().padStart(2,"0"),m=i.colourPrimaries.toString().padStart(2,"0"),f=i.transferCharacteristics.toString().padStart(2,"0"),p=i.matrixCoefficients.toString().padStart(2,"0"),g=i.videoFullRangeFlag.toString().padStart(2,"0"),x=`vp09.${c}.${l}.${d}.${u}`;return x+=`.${m}.${f}.${p}.${g}`,x.endsWith(Cs)&&(x=x.slice(0,-Cs.length)),x}else if(e==="av1"){if(!a){let w=t.width*t.height,T=re(ft).level;for(let S of ft)if(w<=S.maxPictureSize){T=S.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),d=a.tier?"H":"M",u=a.bitDepth.toString().padStart(2,"0"),m=a.monochrome?"1":"0",f=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=n?.primaries?oi[n.primaries]:1,g=n?.transfer?ii[n.transfer]:1,x=n?.matrix?si[n.matrix]:1,y=n?.fullRange?1:0,b=`av01.${c}.${l}${d}.${u}`;return b+=`.${m}.${f.toString().padStart(3,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${x.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(As)&&(b=b.slice(0,-As.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)};var Tn=t=>{let{codec:e,codecDescription:r,aacCodecInfo:n}=t;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");return n.isMpeg2?"mp4a.67":`mp4a.40.${hi(r).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&Xe.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},wr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],pi=[-1,1,2,3,4,5,6,8],hi=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new L(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let n=e.readBits(4),o=null;n===15?o=e.readBits(24):n<wr.length&&(o=wr[n]);let s=e.readBits(4),i=null;return s>=1&&s<=7&&(i=pi[s]),{objectType:r,frequencyIndex:n,sampleRate:o,channelConfiguration:s,numberOfChannels:i}};var pt=48e3,$c=/^pcm-([usf])(\d+)+(be)?$/,wn=t=>{if(h(Xe.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=$c.exec(t);h(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";let n=Number(e[2])/8,o=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:n,littleEndian:o,silentValue:s}};var ht;(function(t){t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.SPS_EXT=13]="SPS_EXT"})(ht||(ht={}));var oe;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(oe||(oe={}));var vn=t=>{let e=[],r=0;for(;r<t.length;){let n=-1,o=0;for(let s=r;s<t.length-3;s++){if(t[s]===0&&t[s+1]===0&&t[s+2]===1){n=s,o=3;break}if(s<t.length-4&&t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1){n=s,o=4;break}}if(n===-1)break;if(r>0&&n>r){let s=t.subarray(r,n);s.length>0&&e.push(s)}r=n+o}if(r<t.length){let n=t.subarray(r);n.length>0&&e.push(n)}return e},Fs=(t,e)=>{let r=[],n=0,o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;n+e<=t.length;){let s;e===1?s=o.getUint8(n):e===2?s=o.getUint16(n,!1):e===3?s=lt(o,n,!1):e===4?s=o.getUint32(n,!1):(fe(e),h(!1)),n+=e;let i=t.subarray(n,n+s);r.push(i),n+=s}return r},kn=t=>{let e=[],r=t.length;for(let n=0;n<r;n++)n+2<r&&t[n]===0&&t[n+1]===0&&t[n+2]===3?(e.push(0,0),n+=2):e.push(t[n]);return new Uint8Array(e)},gi=new Uint8Array([0,0,0,1]),Xc=t=>{let e=t.reduce((o,s)=>o+gi.byteLength+s.byteLength,0),r=new Uint8Array(e),n=0;for(let o of t)r.set(gi,n),n+=gi.byteLength,r.set(o,n),n+=o.byteLength;return r},Qc=(t,e)=>{let r=t.reduce((s,i)=>s+e+i.byteLength,0),n=new Uint8Array(r),o=0;for(let s of t){let i=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:i.setUint8(o,s.byteLength);break;case 2:i.setUint16(o,s.byteLength,!1);break;case 3:ks(i,o,s.byteLength,!1);break;case 4:i.setUint32(o,s.byteLength,!1);break}o+=e,n.set(s,o),o+=s.byteLength}return n},xi=(t,e)=>{if(e.description){let o=(he(e.description)[4]&3)+1;return Fs(t,o)}else return vn(t)},Ds=(t,e)=>{if(e.description){let o=(he(e.description)[4]&3)+1;return Qc(t,o)}else return Xc(t)},gt=t=>t[0]&31,Rs=t=>{try{let e=vn(t),r=e.filter(c=>gt(c)===ht.SPS),n=e.filter(c=>gt(c)===ht.PPS),o=e.filter(c=>gt(c)===ht.SPS_EXT);if(r.length===0||n.length===0)return null;let s=r[0],i=bi(s);h(i!==null);let a=i.profileIdc===100||i.profileIdc===110||i.profileIdc===122||i.profileIdc===144;return{configurationVersion:1,avcProfileIndication:i.profileIdc,profileCompatibility:i.constraintFlags,avcLevelIndication:i.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:n,chromaFormat:a?i.chromaFormatIdc:null,bitDepthLumaMinus8:a?i.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?i.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?o:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}};var Bs=t=>{try{let e=V(t),r=0,n=e.getUint8(r++),o=e.getUint8(r++),s=e.getUint8(r++),i=e.getUint8(r++),a=e.getUint8(r++)&3,c=e.getUint8(r++)&31,l=[];for(let f=0;f<c;f++){let p=e.getUint16(r,!1);r+=2,l.push(t.subarray(r,r+p)),r+=p}let d=e.getUint8(r++),u=[];for(let f=0;f<d;f++){let p=e.getUint16(r,!1);r+=2,u.push(t.subarray(r,r+p)),r+=p}let m={configurationVersion:n,avcProfileIndication:o,profileCompatibility:s,avcLevelIndication:i,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((o===100||o===110||o===122||o===144)&&r+4<=t.length){let f=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,x=e.getUint8(r++);m.chromaFormat=f,m.bitDepthLumaMinus8=p,m.bitDepthChromaMinus8=g;let y=[];for(let b=0;b<x;b++){let w=e.getUint16(r,!1);r+=2,y.push(t.subarray(r,r+w)),r+=w}m.sequenceParameterSetExt=y}return m}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},bi=t=>{try{let e=new L(kn(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),o=e.readAlignedByte(),s=e.readAlignedByte();_(e);let i=null,a=null,c=null;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(i=_(e),i===3&&e.skipBits(1),a=_(e),c=_(e),e.skipBits(1),e.readBits(1))){for(let m=0;m<(i!==3?8:12);m++)if(e.readBits(1)){let p=m<6?16:64,g=8,x=8;for(let y=0;y<p;y++){if(x!==0){let b=Ce(e);x=(g+b+256)%256}g=x===0?g:x}}}_(e);let l=_(e);if(l===0)_(e);else if(l===1){e.skipBits(1),Ce(e),Ce(e);let u=_(e);for(let m=0;m<u;m++)Ce(e)}_(e),e.skipBits(1),_(e),_(e);let d=e.readBits(1);return{profileIdc:n,constraintFlags:o,levelIdc:s,frameMbsOnlyFlag:d,chromaFormatIdc:i,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},yi=(t,e)=>{if(e.description){let o=(he(e.description)[21]&3)+1;return Fs(t,o)}else return vn(t)},Be=t=>t[0]>>1&63,Ms=t=>{try{let e=vn(t),r=e.filter(z=>Be(z)===oe.VPS_NUT),n=e.filter(z=>Be(z)===oe.SPS_NUT),o=e.filter(z=>Be(z)===oe.PPS_NUT),s=e.filter(z=>Be(z)===oe.PREFIX_SEI_NUT||Be(z)===oe.SUFFIX_SEI_NUT);if(n.length===0||o.length===0)return null;let i=n[0],a=new L(kn(i));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:d,general_tier_flag:u,general_profile_idc:m,general_profile_compatibility_flags:f,general_constraint_indicator_flags:p,general_level_idc:g}=Yc(a,c);_(a);let x=_(a);x===3&&a.skipBits(1),_(a),_(a),a.readBits(1)&&(_(a),_(a),_(a),_(a));let y=_(a),b=_(a);_(a);let T=a.readBits(1)?0:c;for(let z=T;z<=c;z++)_(a),_(a),_(a);_(a),_(a),_(a),_(a),_(a),_(a),a.readBits(1)&&a.readBits(1)&&Zc(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),_(a),_(a),a.skipBits(1));let S=_(a);if(Jc(a,S),a.readBits(1)){let z=_(a);for(let B=0;B<z;B++)_(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let v=0;a.readBits(1)&&(v=tl(a,c));let A=0;if(o.length>0){let z=o[0],B=new L(kn(z));B.skipBits(16),_(B),_(B),B.skipBits(1),B.skipBits(1),B.skipBits(3),B.skipBits(1),B.skipBits(1),_(B),_(B),Ce(B),B.skipBits(1),B.skipBits(1),B.readBits(1)&&_(B),Ce(B),Ce(B),B.skipBits(1),B.skipBits(1),B.skipBits(1),B.skipBits(1);let Q=B.readBits(1),st=B.readBits(1);!Q&&!st?A=0:Q&&!st?A=2:!Q&&st?A=3:A=0}let C=[...r.length?[{arrayCompleteness:1,nalUnitType:oe.VPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:oe.SPS_NUT,nalUnits:n}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:oe.PPS_NUT,nalUnits:o}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:Be(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:u,generalProfileIdc:m,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:p,generalLevelIdc:g,minSpatialSegmentationIdc:v,parallelismType:A,chromaFormatIdc:x,bitDepthLumaMinus8:y,bitDepthChromaMinus8:b,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:C}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Yc=(t,e)=>{let r=t.readBits(2),n=t.readBits(1),o=t.readBits(5),s=0;for(let d=0;d<32;d++)s=s<<1|t.readBits(1);let i=new Uint8Array(6);for(let d=0;d<6;d++)i[d]=t.readBits(8);let a=t.readBits(8),c=[],l=[];for(let d=0;d<e;d++)c.push(t.readBits(1)),l.push(t.readBits(1));if(e>0)for(let d=e;d<8;d++)t.skipBits(2);for(let d=0;d<e;d++)c[d]&&t.skipBits(88),l[d]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:i,general_level_idc:a}},Zc=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))_(t);else{let o=Math.min(64,1<<4+(e<<1));e>1&&Ce(t);for(let s=0;s<o;s++)Ce(t)}},Jc=(t,e)=>{let r=[];for(let n=0;n<e;n++)r[n]=el(t,n,e,r)},el=(t,e,r,n)=>{let o=0,s=0,i=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let c=_(t);i=e-(c+1)}else i=e-1;t.readBits(1),_(t);let a=n[i]??0;for(let c=0;c<=a;c++)t.readBits(1)||t.readBits(1);o=n[i]}else{let a=_(t),c=_(t);for(let l=0;l<a;l++)_(t),t.readBits(1);for(let l=0;l<c;l++)_(t),t.readBits(1);o=a+c}return o},tl=(t,e)=>{if(t.readBits(1)&&t.readBits(8)===255&&(t.readBits(16),t.readBits(16)),t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),t.readBits(1),t.readBits(1)&&(t.readBits(8),t.readBits(8),t.readBits(8))),t.readBits(1)&&(_(t),_(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(_(t),_(t),_(t),_(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&_(t),t.readBits(1)&&rl(t,!0,e)),t.readBits(1)){t.readBits(1),t.readBits(1),t.readBits(1);let r=_(t);return _(t),_(t),_(t),_(t),r}return 0},rl=(t,e,r)=>{let n=!1,o=!1,s=!1;e&&(n=t.readBits(1)===1,o=t.readBits(1)===1,(n||o)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let i=0;i<=r;i++){let a=t.readBits(1)===1,c=!0;a||(c=t.readBits(1)===1);let l=!1;c?_(t):l=t.readBits(1)===1;let d=1;l||(d=_(t)+1),n&&_s(t,d,s),o&&_s(t,d,s)}},_s=(t,e,r)=>{for(let n=0;n<e;n++)_(t),_(t),r&&(_(t),_(t)),t.readBits(1)};var Sn=t=>{let e=new L(t);if(e.readBits(2)!==2)return null;let n=e.readBits(1),s=(e.readBits(1)<<1)+n;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=e.readBits(1)?12:10);let d=e.readBits(3),u=0,m=0;if(d!==7)if(m=e.readBits(1),s===1||s===3){let A=e.readBits(1),C=e.readBits(1);u=!A&&!C?3:A&&!C?2:1,e.skipBits(1)}else u=1;else u=3,m=1;let f=e.readBits(16),p=e.readBits(16),g=f+1,x=p+1,y=g*x,b=re(ft).level;for(let v of ft)if(y<=v.maxPictureSize){b=v.level;break}return{profile:s,level:b,bitDepth:l,chromaSubsampling:u,videoFullRangeFlag:m,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}},Os=function*(t){let e=new L(t),r=()=>{let n=0;for(let o=0;o<8;o++){let s=e.readAlignedByte();if(n|=(s&127)<<o*7,!(s&128))break;if(o===7&&s&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),o=e.readBits(1),s=e.readBits(1);e.skipBits(1),o&&e.skipBits(8);let i;if(s){let a=r();if(a===null)return;i=a}else i=Math.floor(e.getBitsLeft()/8);h(e.pos%8===0),yield{type:n,data:t.subarray(e.pos/8,e.pos/8+i)},e.skipBits(i*8)}},Pn=t=>{for(let{type:e,data:r}of Os(t)){if(e!==1)continue;let n=new L(r),o=n.readBits(3),s=n.readBits(1),i=n.readBits(1),a=0,c=0,l=0;if(i)a=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let v=n.readBits(1);v&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let A=n.readBits(5);for(let C=0;C<=A;C++){n.skipBits(12);let R=n.readBits(5);if(C===0&&(a=R),R>7){let B=n.readBits(1);C===0&&(c=B)}if(v&&n.readBits(1)){let Q=l+1;n.skipBits(Q),n.skipBits(Q),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let d=n.readBits(4),u=n.readBits(4),m=d+1;n.skipBits(m);let f=u+1;n.skipBits(f);let p=0;if(i?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!i){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let S=n.readBits(1);S&&(n.skipBits(1),n.skipBits(1));let v=n.readBits(1),A=0;v?A=2:A=n.readBits(1),A>0&&(n.readBits(1)||n.skipBits(1)),S&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let g=n.readBits(1),x=8;o===2&&g?x=n.readBits(1)?12:10:o<=2&&(x=g?10:8);let y=0;o!==1&&(y=n.readBits(1));let b=1,w=1,T=0;return y||(o===0?(b=1,w=1):o===1?(b=0,w=0):x===12&&(b=n.readBits(1),b&&(w=n.readBits(1))),b&&w&&(T=n.readBits(2))),{profile:o,level:a,tier:c,bitDepth:x,monochrome:y,chromaSubsamplingX:b,chromaSubsamplingY:w,chromaSamplePosition:T}}return null},zs=t=>{let e=V(t),r=e.getUint8(9),n=e.getUint16(10,!0),o=e.getUint32(12,!0),s=e.getInt16(16,!0),i=e.getUint8(18),a=null;return i&&(a=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:n,inputSampleRate:o,outputGain:s,channelMappingFamily:i,channelMappingTable:a}},nl=[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],Us=t=>{let e=t[0]>>3;return{durationInSamples:nl[e]}},Ns=t=>{if(t.length<7)throw new Error("Setup header is too short.");if(t[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...t.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let r=t.length,n=new Uint8Array(r);for(let u=0;u<r;u++)n[u]=t[r-1-u];let o=new L(n),s=0;for(;o.getBitsLeft()>97;)if(o.readBits(1)===1){s=o.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let i=0,a=!1,c=0;for(;o.getBitsLeft()>=97;){let u=o.pos,m=o.readBits(8),f=o.readBits(16),p=o.readBits(16);if(m>63||f!==0||p!==0){o.pos=u;break}if(o.skipBits(1),i++,i>64)break;o.clone().readBits(6)+1===i&&(a=!0,c=i)}if(!a)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;o.pos=0,o.skipBits(s);let d=Array(l).fill(0);for(let u=l-1;u>=0;u--)o.skipBits(40),d[u]=o.readBits(1);return{modeBlockflags:d}},In=(t,e,r)=>{switch(t){case"avc":{let n=xi(r,e),o=n.some(s=>gt(s)===ht.IDR);if(!o&&(!yr()||Ps()>=144))for(let s of n){if(gt(s)!==ht.SEI)continue;let a=kn(s),c=1;do{let l=0;for(;;){let m=a[c++];if(m===void 0||(l+=m,m<255))break}let d=0;for(;;){let m=a[c++];if(m===void 0||(d+=m,m<255))break}if(l===6){let m=new L(a);m.pos=8*c;let f=_(m),p=m.readBits(1);if(f===0&&p===1){o=!0;break}}c+=d}while(c<a.length-1)}return o?"key":"delta"}case"hevc":return yi(r,e).some(s=>{let i=Be(s);return oe.BLA_W_LP<=i&&i<=oe.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{let n=new L(r);if(n.readBits(2)!==2)return null;let o=n.readBits(1);return(n.readBits(1)<<1)+o===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:o,data:s}of Os(r))if(o===1){let i=new L(s);i.skipBits(4),n=!!i.readBits(1)}else if(o===3||o===6||o===7){if(n)return"key";let i=new L(s);return i.readBits(1)?null:i.readBits(2)===0?"key":"delta"}return null}default:fe(t),h(!1)}},Qe;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Qe||(Qe={}));var kr=(t,e)=>{let r=V(t),n=0,o=r.getUint32(n,!0);n+=4;let s=Y.decode(t.subarray(n,n+o));n+=o,o>0&&(e.raw??={},e.raw.vendor??=s);let i=r.getUint32(n,!0);n+=4;for(let a=0;a<i;a++){let c=r.getUint32(n,!0);n+=4;let l=Y.decode(t.subarray(n,n+c));n+=c;let d=l.indexOf("=");if(d===-1)continue;let u=l.slice(0,d).toUpperCase(),m=l.slice(d+1);switch(e.raw??={},e.raw[u]??=m,u){case"TITLE":e.title??=m;break;case"DESCRIPTION":e.description??=m;break;case"ARTIST":e.artist??=m;break;case"ALBUM":e.album??=m;break;case"ALBUMARTIST":e.albumArtist??=m;break;case"COMMENT":e.comment??=m;break;case"LYRICS":e.lyrics??=m;break;case"TRACKNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{let f=new Date(m);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=m;break;case"METADATA_BLOCK_PICTURE":{let f=Is(m),p=V(f),g=p.getUint32(0,!1),x=p.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+x)),b=p.getUint32(8+x,!1),w=Y.decode(f.subarray(12+x,12+x+b)),T=p.getUint32(x+b+28),S=f.subarray(x+b+32,x+b+32+T);e.images??=[],e.images.push({data:S,mimeType:y,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:w||void 0})}break}}};var te=class{constructor(e){this.input=e}};var Cn=[],An=[];var j=new Uint8Array(0),G=class t{constructor(e,r,n,o,s=-1,i,a){if(this.data=e,this.type=r,this.timestamp=n,this.duration=o,this.sequenceNumber=s,e===j&&i===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(i===void 0&&(i=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(o)||o<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(i)||i<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=i,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===j}get microsecondTimestamp(){return Math.trunc(Ae*this.timestamp)}get microsecondDuration(){return Math.trunc(Ae*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new t(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}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 t(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Vs=t=>{let r=0,n=0,o=~t;o&128&&(o&=-129,r=-1),n=((o&240)>>4)+5;let s=(1<<n|(o&15)<<n-4|1<<n-5)-33;return r===0?s:-s};var Ls=t=>{let e=0,r=0,n=t^85;n&128&&(n&=-129,e=-1),r=((n&240)>>4)+4;let o=0;return r!==4?o=1<<r|(n&15)<<r-4|1<<r-5:o=n<<1|1,e===0?o:-o};xn();var Hs=-1/0,Gs=-1/0,Pr=null;typeof FinalizationRegistry<"u"&&(Pr=new FinalizationRegistry(t=>{let e=Date.now();t.type==="video"?(e-Hs>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Hs=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-Gs>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Gs=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));var Ws=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ol=new Set(Ws),Ot=class t{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(Ae*this.timestamp)}get microsecondDuration(){return Math.trunc(Ae*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!ol.has(r.format))throw new TypeError("init.format must be one of: "+Ws.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=he(e).slice(),this._layout=r.layout??il(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Sr(r.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new Sr(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(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new t(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Ae),duration:Math.trunc((r.duration??0)*Ae)||void 0}),r);let n=0,o=0;if("naturalWidth"in e?(n=e.naturalWidth,o=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,o=e.videoHeight):"width"in e&&(n=Number(e.width),o=Number(e.height)),!n||!o)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(n,o),i=s.getContext("2d",{alpha:fi(),willReadFrequently:!0});h(i),i.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.codedWidth=n,this.codedHeight=o,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Sr({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");Pr?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),xt(this._data)?new t(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(h(this._layout),new t(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new t(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||(Pr?.unregister(this),xt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(qs(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)===null)throw new Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!xt(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let r=this.toVideoFrame(),n=r.allocationSize(e);return r.close(),n}return xt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!fn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(qs(r),this._closed)throw new Error("VideoSample is closed.");if((r.format??this.format)===null)throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!xt(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){let n=this.toVideoFrame(),o=await n.copyTo(e,r);return n.close(),o}if(xt(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return h(this._layout),he(e).set(this._data),this._layout;{let o=this._data.getContext("2d");h(o);let s=o.getImageData(0,0,this.codedWidth,this.codedHeight);return he(e).set(s.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),xt(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,r,n,o,s,i,a,c,l){let d=0,u=0,m=this.displayWidth,f=this.displayHeight,p=0,g=0,x=this.displayWidth,y=this.displayHeight;if(i!==void 0?(d=r,u=n,m=o,f=s,p=i,g=a,c!==void 0?(x=c,y=l):(x=m,y=f)):(p=r,g=n,o!==void 0&&(x=o,y=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(x)||x<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:u,sWidth:m,sHeight:f}=this._rotateSourceRegion(d,u,m,f,this.rotation));let b=this.toCanvasImageSource();e.save();let w=p+x/2,T=g+y/2;e.translate(w,T),e.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:x/y;e.scale(1/S,S),e.drawImage(b,d,u,m,f,-x/2,-y/2,x,y),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&$s(r.crop,"options.");let n=e.canvas.width,o=e.canvas.height,s=r.rotation??this.rotation,[i,a]=s%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];r.crop&&js(r.crop,i,a);let c,l,d,u,{sx:m,sy:f,sWidth:p,sHeight:g}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??i,r.crop?.height??a,s);if(r.fit==="fill")c=0,l=0,d=n,u=o;else{let[y,b]=r.crop?[r.crop.width,r.crop.height]:[i,a],w=r.fit==="contain"?Math.min(n/y,o/b):Math.max(n/y,o/b);d=y*w,u=b*w,c=(n-d)/2,l=(o-u)/2}e.save();let x=s%180===0?1:d/u;e.translate(n/2,o/2),e.rotate(s*Math.PI/180),e.scale(1/x,x),e.translate(-n/2,-o/2),e.drawImage(this.toCanvasImageSource(),m,f,p,g,c,l,d,u),e.restore()}_rotateSourceRegion(e,r,n,o,s){return s===90?[e,r,n,o]=[r,this.codedHeight-e-n,o,n]:s===180?[e,r]=[this.codedWidth-e-n,this.codedHeight-r-o]:s===270&&([e,r,n,o]=[this.codedWidth-r-o,e,o,n]),{sx:e,sy:r,sWidth:n,sHeight:o}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(h(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},Sr=class{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},xt=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,js=(t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),h(t.width>=0),h(t.height>=0)},$s=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},qs=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},il=(t,e,r)=>{let n=sl(t),o=[],s=0;for(let i of n){let a=Math.ceil(e/i.widthDivisor),c=Math.ceil(r/i.heightDivisor),l=a*i.sampleBytes,d=l*c;o.push({offset:s,stride:l}),s+=d}return o},sl=t=>{let e=(r,n,o,s,i)=>{let a=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:o,heightDivisor:s},{sampleBytes:n,widthDivisor:o,heightDivisor:s}];return i&&a.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),a};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:fe(t),h(!1)}},Ti=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),zt=class t{get microsecondTimestamp(){return Math.trunc(Ae*this.timestamp)}get microsecondDuration(){return Math.trunc(Ae*this.duration)}constructor(e){if(this._closed=!1,vr(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ti.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(bt(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let o=this.numberOfFrames*this.numberOfChannels*bt(this.format);if(n.byteLength<o)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}Pr?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Ti.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let r=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let o=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(o>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let s=bt(r),i=Mt(r);if(i&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!i&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(i?o:o*this.numberOfChannels)*s}copyTo(e,r){if(!fn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!Ti.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:n,format:o,frameCount:s,frameOffset:i}=r,a=this.format,c=o??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,d=this.numberOfChannels,u=i??0;if(u>=l)throw new RangeError("frameOffset out of range");let m=s!==void 0?s:l-u;if(m>l-u)throw new RangeError("frameCount out of range");let f=bt(c),p=Mt(c);if(p&&n>=d)throw new RangeError("planeIndex out of range");if(!p&&n!==0)throw new RangeError("planeIndex out of range");let x=(p?m:m*d)*f;if(e.byteLength<x)throw new RangeError("Destination buffer is too small");let y=V(e),b=Xs(c);if(vr(this._data))$e()&&d>2&&c!==a?al(this._data,y,a,c,d,n,u,m):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:m,format:c});else{let w=this._data,T=V(w),S=Ks(a),v=bt(a),A=Mt(a);for(let C=0;C<m;C++)if(p){let R=C*f,z;A?z=(n*l+(C+u))*v:z=((C+u)*d+n)*v;let B=S(T,z);b(y,R,B)}else for(let R=0;R<d;R++){let B=(C*d+R)*f,Q;A?Q=(R*l+(C+u))*v:Q=((C+u)*d+R)*v;let st=S(T,Q);b(y,B,st)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(vr(this._data)){let e=new t(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new t({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Pr?.unregister(this),vr(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(vr(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(Mt(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(r,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(r,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(r,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,s=e.sampleRate,i=e.length,a=Math.floor(n/o),c=0,l=i;for(;l>0;){let d=Math.min(a,l),u=new Float32Array(o*d);for(let m=0;m<o;m++)e.copyFromChannel(u.subarray(m*d,(m+1)*d),m,c);yield new t({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:o,timestamp:r+c/s,data:u}),c+=d,l-=d}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,s=e.sampleRate,i=e.length,a=Math.floor(n/o),c=0,l=i,d=[];for(;l>0;){let u=Math.min(a,l),m=new Float32Array(o*u);for(let p=0;p<o;p++)e.copyFromChannel(m.subarray(p*u,(p+1)*u),p,c);let f=new t({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:o,timestamp:r+c/s,data:m});d.push(f),c+=u,l-=u}return d}},bt=t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Mt=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ks=t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},Xs=t=>{switch(t){case"u8":case"u8-planar":return(e,r,n)=>e.setUint8(r,ut((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,n)=>e.setInt16(r,ut(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,n)=>e.setInt32(r,ut(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,n)=>e.setFloat32(r,n,!0)}},vr=t=>typeof AudioData<"u"&&t instanceof AudioData,al=(t,e,r,n,o,s,i,a)=>{let c=Ks(r),l=Xs(n),d=bt(r),u=bt(n),m=Mt(r);if(Mt(n))if(m){let p=new ArrayBuffer(a*d),g=V(p);t.copyTo(p,{planeIndex:s,frameOffset:i,frameCount:a,format:r});for(let x=0;x<a;x++){let y=x*d,b=x*u,w=c(g,y);l(e,b,w)}}else{let p=new ArrayBuffer(a*o*d),g=V(p);t.copyTo(p,{planeIndex:0,frameOffset:i,frameCount:a,format:r});for(let x=0;x<a;x++){let y=(x*o+s)*d,b=x*u,w=c(g,y);l(e,b,w)}}else if(m){let p=a*d,g=new ArrayBuffer(p),x=V(g);for(let y=0;y<o;y++){t.copyTo(g,{planeIndex:y,frameOffset:i,frameCount:a,format:r});for(let b=0;b<a;b++){let w=b*d,T=(b*o+y)*u,S=c(x,w);l(e,T,S)}}}else{let p=new ArrayBuffer(a*o*d),g=V(p);t.copyTo(p,{planeIndex:0,frameOffset:i,frameCount:a,format:r});for(let x=0;x<a;x++)for(let y=0;y<o;y++){let b=x*o+y,w=b*d,T=b*u,S=c(g,w);l(e,T,S)}}};var Ut=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},yt=t=>{if(!Tr(t))throw new TypeError("timestamp must be a number.")},wi=(t,e,r)=>r.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let o=await t.determinePacketType(n);return o&&(n.type=o),n}):e,Tt=class{constructor(e){if(!(e instanceof Nt))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Ut(e),this._track.input._disposed)throw new $;return wi(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,r={}){if(yt(e),Ut(r),this._track.input._disposed)throw new $;return wi(this._track,this._track._backing.getPacket(e,r),r)}getNextPacket(e,r={}){if(!(e instanceof G))throw new TypeError("packet must be an EncodedPacket.");if(Ut(r),this._track.input._disposed)throw new $;return wi(this._track,this._track._backing.getNextPacket(e,r),r)}async getKeyPacket(e,r={}){if(yt(e),Ut(r),this._track.input._disposed)throw new $;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);let n=await this._track._backing.getKeyPacket(e,r);return n&&(h(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,r):n)}async getNextKeyPacket(e,r={}){if(!(e instanceof G))throw new TypeError("packet must be an EncodedPacket.");if(Ut(r),this._track.input._disposed)throw new $;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);let n=await this._track._backing.getNextKeyPacket(e,r);return n&&(h(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,r):n)}packets(e,r,n={}){if(e!==void 0&&!(e instanceof G))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(r!==void 0&&!(r instanceof G))throw new TypeError("endPacket must be an EncodedPacket.");if(Ut(n),this._track.input._disposed)throw new $;let o=[],{promise:s,resolve:i}=ne(),{promise:a,resolve:c}=ne(),l=!1,d=!1,u=null,m=[],f=()=>Math.max(2,m.length);(async()=>{let g=e??await this.getFirstPacket(n);for(;g&&!d&&!this._track.input._disposed&&!(r&&g.sequenceNumber>=r?.sequenceNumber);){if(o.length>f()){({promise:a,resolve:c}=ne()),await a;continue}o.push(g),i(),{promise:s,resolve:i}=ne(),g=await this.getNextPacket(g,n)}l=!0,i()})().catch(g=>{u||(u=g,i())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new $;if(d)return{value:void 0,done:!0};if(u)throw u;if(o.length>0){let g=o.shift(),x=performance.now();for(m.push(x);m.length>0&&x-m[0]>=1e3;)m.shift();return c(),{value:g,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return d=!0,c(),i(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},Ir=class{constructor(e,r){this.onSample=e,this.onError=r}},Cr=class{mediaSamplesInRange(e=0,r=1/0){yt(e),yt(r);let n=[],o=!1,s=null,{promise:i,resolve:a}=ne(),{promise:c,resolve:l}=ne(),d=!1,u=!1,m=!1,f=null;(async()=>{let x=await this._createDecoder(v=>{if(l(),v.timestamp>=r&&(u=!0),u){v.close();return}s&&(v.timestamp>e?(n.push(s),o=!0):s.close()),v.timestamp>=e&&(n.push(v),o=!0),s=o?null:v,n.length>0&&(a(),{promise:i,resolve:a}=ne())},v=>{f||(f=v,a())}),y=this._createPacketSink(),b=await y.getKeyPacket(e,{verifyKeyPackets:!0})??await y.getFirstPacket(),w=b,T;if(r<1/0){let v=await y.getPacket(r),A=v?v.type==="key"&&v.timestamp===r?v:await y.getNextKeyPacket(v,{verifyKeyPackets:!0}):null;A&&(T=A)}let S=y.packets(b??void 0,T);for(await S.next();w&&!u&&!this._track.input._disposed;){let v=Qs(n.length);if(n.length+x.getDecodeQueueSize()>v){({promise:c,resolve:l}=ne()),await c;continue}x.decode(w);let A=await S.next();if(A.done)break;w=A.value}await S.return(),!m&&!this._track.input._disposed&&await x.flush(),x.close(),!o&&s&&n.push(s),d=!0,a()})().catch(x=>{f||(f=x,a())});let p=this._track,g=()=>{s?.close();for(let x of n)x.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new $;if(m)return{value:void 0,done:!0};if(f)throw g(),f;if(n.length>0){let x=n.shift();return l(),{value:x,done:!1}}else if(!d)await i;else return{value:void 0,done:!0}}},async return(){return m=!0,u=!0,l(),a(),g(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Ts(e);let r=ys(e),n=[],o=[],{promise:s,resolve:i}=ne(),{promise:a,resolve:c}=ne(),l=!1,d=!1,u=null,m=g=>{o.push(g),i(),{promise:s,resolve:i}=ne()};(async()=>{let g=await this._createDecoder(v=>{if(c(),d){v.close();return}let A=0;for(;n.length>0&&v.timestamp-n[0]>-1e-10;)A++,n.shift();if(A>0)for(let C=0;C<A;C++)m(C<A-1?v.clone():v);else v.close()},v=>{u||(u=v,i())}),x=this._createPacketSink(),y=null,b=null,w=-1,T=async()=>{h(b);let v=b;for(g.decode(v);v.sequenceNumber<w;){let A=Qs(o.length);for(;o.length+g.getDecodeQueueSize()>A&&!d;)({promise:a,resolve:c}=ne()),await a;if(d)break;let C=await x.getNextPacket(v);h(C),g.decode(C),v=C}w=-1},S=async()=>{await g.flush();for(let v=0;v<n.length;v++)m(null);n.length=0};for await(let v of r){if(yt(v),d||this._track.input._disposed)break;let A=await x.getPacket(v),C=A&&await x.getKeyPacket(v,{verifyKeyPackets:!0});if(!C){w!==-1&&(await T(),await S()),m(null),y=null;continue}y&&(C.sequenceNumber!==b.sequenceNumber||A.timestamp<y.timestamp)&&(await T(),await S()),n.push(A.timestamp),w=Math.max(A.sequenceNumber,w),y=A,b=C}!d&&!this._track.input._disposed&&(w!==-1&&await T(),await S()),g.close(),l=!0,i()})().catch(g=>{u||(u=g,i())});let f=this._track,p=()=>{for(let g of o)g?.close()};return{async next(){for(;;){if(f.input._disposed)throw p(),new $;if(d)return{value:void 0,done:!0};if(u)throw p(),u;if(o.length>0){let g=o.shift();return h(g!==void 0),c(),{value:g,done:!1}}else if(!l)await s;else return{value:void 0,done:!0}}},async return(){return d=!0,c(),i(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},Qs=t=>t===0?40:8,ki=class extends Ir{constructor(e,r,n,o,s,i){super(e,r),this.codec=n,this.decoderConfig=o,this.rotation=s,this.timeResolution=i,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new br,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let a=Cn.find(c=>c.supports(n,o));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=c=>{if(!(c instanceof Ot))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=d=>{if(this.alphaQueue.length>0){let u=this.alphaQueue.shift();h(u!==void 0),this.mergeAlpha(d,u)}else this.colorQueue.push(d)};if(n==="avc"&&this.decoderConfig.description&&yr()){let d=Bs(he(this.decoderConfig.description));if(d&&d.sequenceParameterSets.length>0){let u=bi(d.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:d=>{try{c(d)}catch(u){this.onError(u)}},error:d=>{d.stack=l,this.onError(d)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(h(this.decoder),$e()||li(this.inputTimestamps,e.timestamp,r=>r),yr()&&this.currentPacketIndex===0&&this.codec==="avc"){let n=xi(e.data,this.decoderConfig).filter(s=>{let i=gt(s);return!(i>=20&&i<=31)}),o=Ds(n,this.decoderConfig);e=new G(o,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new vi}catch(n){console.error("Due to an error, only color data will be decoded.",n),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let n=s=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let i=this.colorQueue.shift();h(i!==void 0),this.mergeAlpha(i,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let i=this.colorQueue.shift();h(i!==void 0),this.mergeAlpha(i,null)}else this.alphaQueue.push(null)},o=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(s)}catch(i){this.onError(i)}},error:s=>{s.stack=o,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}let r=In(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return yi(e,this.decoderConfig).some(n=>{let o=Be(n);return o===oe.RASL_N||o===oe.RASL_R})}sampleHandler(e){if($e()){if(this.sampleQueue.length>0&&e.timestamp>=re(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}li(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();h(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,r){if(!r){let s=new Ot(e);this.sampleHandler(s);return}h(this.merger),this.merger.update(e,r),e.close(),r.close();let n=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),o=new Ot(n);this.sampleHandler(o)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),$e()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},vi=class{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2338
|
+
`)):console.error(t)}async function $o(t){for(let e of t.outputs)e instanceof at?await jo(e.line):await Wo(e.line);qo(t.code)}function Ko(t,e){let{verbose:r,theme:{icons:n,colors:o}}=e,s=[...t.experiments.values()].filter(T=>T.fail),i=[...t.experiments.values()].filter(T=>!T.fail),a=t.tubes.length,c=i.length,l=s.length,d=t.tubes.filter(T=>T.skip).length,u=t.tubes.filter(T=>T.only).length,m=[],f=T=>m.push(new hr(T)),p=T=>m.push(new at(T)),g=0;function x(T,S){let v=T.only?o.only(` ${n.only} [ONLY]`):T.skip?o.skip(` ${n.skip} [SKIP]`):"";return S&&S.fail?o.errorLabel(n.testFail)+v:S?o.successLabel(n.testSuccess)+v:o.neutral(n.testNeutral)+v}function y(T,S){g+=1;let v=T.path,A=o.errorLabel(T.label),C=[...v.map(o.errorPath),A].join(o.errorGrammar(n.pathSeparator)),R=o.errorMessage(S.fail??"unknown fail"),z=o.errorTime(`${n.timeSeparator}${ur(S.time)}`),B=x(T,S);p(`${B} ${C}${o.errorGrammar(n.messageSeparator)}${R}${z}`)}function b(T,S){g+=1;let v=T.path,A=o.successLabel(T.label),C=[...v.map(o.successPath),A].join(o.successGrammar(n.pathSeparator)),R=o.successTime(`${n.timeSeparator}${ur(S.time)}`),z=x(T,S);f(`${z} ${C}${R}`)}function w(T){g+=1;let S=T.path,v=o.neutralLabel(T.label),A=[...S.map(o.neutral),v].join(o.neutral(n.pathSeparator)),C=x(T,void 0);f(`${C} ${A}`)}for(let T of t.tubes){let S=t.experiments.get(T);S?S.fail?y(T,S):r&&b(T,S):r&&w(T)}if(g>0&&f(""),u){let T=a-u;f(o.only(`${n.only} only ran ${u} test${Yr(u)} (${T} ignored)`))}else d&&f(o.skip(`${n.skip} skipped ${d} test${Yr(d)}`));if(l===0){let T=o.successSuite(n.suiteSuccess),S=o.successLabel(`${c} happy tests`),v=o.successTime(`- ${ur(t.time)}`);f(`${T} ${S} ${v}`)}else{let T=o.errorSuite(n.suiteFail),S=o.errorSuite(`${l} failure${Yr(l)}`),v=o.errorDidnt(`(${c} succeeded)`),A=o.errorTime(`- ${ur(t.time)}`);p(`${T} ${S} ${v} ${A}`)}return{execution:t,outputs:m,code:l>0?1:0}}function Lc(t){return t}var Dt={plain:{colors:{skip:E.none,only:E.none,neutral:E.none,neutralLabel:E.none,successSuite:E.none,successPath:E.none,successGrammar:E.none,successLabel:E.none,successTime:E.none,errorSuite:E.none,errorDidnt:E.none,errorPath:E.none,errorLabel:E.none,errorGrammar:E.none,errorMessage:E.none,errorTime:E.none},icons:{skip:"\u23ED",only:"*",testFail:"\u2718 ",testSuccess:" \u2022",testNeutral:" \u2022",suiteFail:"FAIL!!",suiteSuccess:"good:",timeSeparator:" - ",pathSeparator:" > ",messageSeparator:" :: "}},redgreen:{colors:{skip:E.yellow,only:E.yellow,neutral:t=>E.dim(E.white(t)),neutralLabel:E.white,successSuite:E.brightGreen,successPath:E.green,successGrammar:t=>E.dim(E.green(t)),successLabel:t=>E.bold(E.brightGreen(t)),successTime:t=>E.dim(E.green(t)),errorSuite:E.brightRed,errorDidnt:E.red,errorPath:E.red,errorLabel:t=>E.bold(E.brightRed(t)),errorGrammar:t=>E.dim(E.red(t)),errorMessage:E.red,errorTime:t=>E.dim(E.red(t))},icons:{skip:"\u{1F47B}",only:"\u{1F6A7}",testFail:"\u274C",testSuccess:" \u2022",testNeutral:" \u2022",suiteFail:"\u{1F525}",suiteSuccess:"\u2705",timeSeparator:" - ",pathSeparator:" > ",messageSeparator:" :: "}},seaside:{colors:{skip:E.yellow,only:E.yellow,neutral:t=>E.dim(E.white(t)),neutralLabel:E.white,successSuite:E.brightBlue,successPath:E.blue,successGrammar:t=>E.dim(E.blue(t)),successLabel:t=>E.bold(E.brightBlue(t)),successTime:t=>E.dim(E.blue(t)),errorSuite:E.brightRed,errorDidnt:E.red,errorPath:E.red,errorLabel:t=>E.bold(E.brightRed(t)),errorGrammar:t=>E.dim(E.red(t)),errorMessage:E.red,errorTime:t=>E.dim(E.red(t))},icons:{skip:"\u{1F47B}",only:"\u{1F6A7}",testFail:"\u274C",testSuccess:" \u2022",testNeutral:" \u2022",suiteFail:"\u{1F525}",suiteSuccess:"\u2705",timeSeparator:" - ",pathSeparator:" > ",messageSeparator:" :: "}}};function Hc(t){let e=[];function r(...n){let o=t(...n);return o!=null&&typeof o.then=="function"?o.then(s=>(e.push({args:n,ret:s}),s)):(e.push({args:n,ret:o}),o)}return r.spy={calls:e,get args(){return e.map(n=>n.args)},get rets(){return e.map(n=>n.ret)}},r}var fs=t=>({verbose:t.verbose??(en("--verbose")||tn("--verbose")==="1"||en("-v")||rn("SCIENCE_VERBOSE")==="1"),theme:t.theme??(()=>{let e=tn("--theme")||rn("SCIENCE_THEME");if(e){let r=Dt[e];if(!r)throw new Error(`theme not found "${e}"`);return r}return Dt.redgreen})()});var ps=t=>({...t,colors:Go()?t.colors:Dt.plain.colors});async function Gc(t,e={}){let{verbose:r,theme:n}=fs(e),o=ps(n),s=await Ho(t),i=Ko(s,{verbose:r,theme:o});await $o(i)}function gr(t){return t}gr.only=t=>(t[ie]={kind:"only"},t);gr.skip=t=>(t[ie]={kind:"skip"},t);function Xo(t){return t}Xo.only=t=>(t[ie]={kind:"only"},t);Xo.skip=t=>(t[ie]={kind:"skip"},t);var Rt=Object.freeze({eq(t,e){if(t.length!==e.length)return!1;for(let r=0;r<=t.length;r++)if(t.at(r)!==e.at(r))return!1;return!0},random(t){return crypto.getRandomValues(new Uint8Array(t))}});var ee=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((r,n)=>[r,n])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let r=Math.log2(this.lexicon.characters.length);if(Number.isInteger(r)){let a=0,c=0,l=[];for(let d of e){if(d===this.lexicon.padding?.character)continue;let u=this.lookup[d];if(u===void 0)throw new Error(`Invalid character: ${d}`);for(a=a<<r|u,c+=r;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let n=0n,o=BigInt(this.lexicon.characters.length),s=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),s=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);n=n*o+BigInt(c)}let i=[];for(;n>0n;)i.unshift(Number(n%256n)),n=n/256n;return new Uint8Array(i)}fromBytes(e){let r=Math.log2(this.lexicon.characters.length);if(Number.isInteger(r)){let i=0,a=0,c="";for(let l of e)for(i=i<<8|l,a+=8;a>=r;){a-=r;let d=i>>a&(1<<r)-1;c+=this.lexicon.characters[d]}if(a>0){let l=i<<r-a&(1<<r)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let n=0n;for(let i of e)n=(n<<8n)+BigInt(i);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),s="";for(;n>0n;)s=this.lexicon.characters[Number(n%o)]+s,n=n/o;return s}toInteger(e){if(!e)return 0;let r=0n,n=!1,o=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let s of e){let i=this.lookup[s];if(i===void 0)throw new Error(`Invalid character: ${s}`);r=r*o+BigInt(i)}return Number(n?-r:r)}fromInteger(e){e=Math.floor(e);let r=e<0,n=BigInt(r?-e:e);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),s="";for(;n>0n;)s=this.lexicon.characters[Number(n%o)]+s,n=n/o;return r?`${this.negativePrefix}${s}`:s}random(e=32){return this.fromBytes(Rt.random(e))}};var ve=new ee(ee.lexicons.hex),Yu=new ee(ee.lexicons.base2),Zu=new ee(ee.lexicons.base36),Qo=new ee(ee.lexicons.base58),Ju=new ee(ee.lexicons.base62),ed=new ee(ee.lexicons.base64),td=new ee(ee.lexicons.base64url);var Yo=["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 Zo=["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 Re={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(t,e){let r=Rt.random(t);return this.fromBytes(r,e)},fromBytes(t,e={}){let{groupSize:r=Re.defaults.groupSize,wordSeparator:n=Re.defaults.wordSeparator,groupSeparator:o=Re.defaults.groupSeparator}=e,s=[],i=[];t.forEach((c,l)=>{let d=l%2===0?Yo:Zo;i.push(d[c]),i.length===2&&(s.push(i.join("")),i=[])}),i.length&&s.push(i.join(""));let a=[];for(let c=0;c<s.length;c+=r)a.push(s.slice(c,c+r).join(n));return a.join(o)},toBytes(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");if(e.length/3%1!==0)throw new Error(`invalid triplet count, ${e.length} does not divide into triplets`);let n=[];for(let o=0;o<e.length;o+=3)n.push(e.slice(o,o+3));return new Uint8Array(n.map((o,s)=>{let a=(s%2===0?Yo:Zo).findIndex(c=>c===o);if(a===-1)throw new Error(`unknown triplet ${o}`);return a}))},toHex(t){return ve.fromBytes(Re.toBytes(t))},fromHex(t,e){return Re.fromBytes(ve.toBytes(t),e)}};var Se={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(t){t=t.trim();let e=t.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(o=>o.trim());if(e.length<2)return Re.toBytes(e.join(""));let r=e.pop(),n=e.join("");return new Uint8Array([...Re.toBytes(n),...Qo.toBytes(r)])},parse(t,e){let r=Se.toBytes(t);return Se.build.fromBytes(r,e)},build:{fromBytes(t,e={}){let{delimiter:r,previewBytes:n,sigilBytes:o}={...Se.defaults,...e},s=d=>t.length>0?Re.fromBytes(t.slice(0,d),{wordSeparator:r,groupSeparator:r}):"",i=s(o),a=s(n),c=t.length>n?Qo.fromBytes(t.slice(n)):"",l=[a,c].filter(d=>d.length>0).join(r);return{raw:t,full:l,preview:a,bulk:c,sigil:i,bytes:t,thumbprint:l}},fromHex(t,e){let r=ve.toBytes(t);return Se.build.fromBytes(r,e)}},toHex(t){let e=Se.toBytes(t);return ve.fromBytes(e)},fromBytes(t,e){return Se.build.fromBytes(t,e).full},fromHex(t,e){return Se.fromBytes(ve.toBytes(t),e)},sigil:{fromHex(t,e){return Se.build.fromHex(t,e).sigil},fromBytes(t,e){return Se.build.fromBytes(t,e).sigil}}},hs=Se;var nn=Object.freeze({fromBytes(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(t){if(t.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.slice(r,r+2),16);return e},random(t=32){return this.fromBytes(Rt.random(t))},string(t){return nn.fromBytes(t)},bytes(t){return nn.toBytes(t)}});function Pe(){let t,e,r=new Promise((o,s)=>{t=o,e=s});function n(o){return o.then(t).catch(e),r}return{promise:r,resolve:t,reject:e,entangle:n}}var on=Object.freeze({happy:t=>t!=null,sad:t=>t==null,boolean:t=>typeof t=="boolean",number:t=>typeof t=="number",string:t=>typeof t=="string",bigint:t=>typeof t=="bigint",object:t=>typeof t=="object"&&t!==null,array:t=>Array.isArray(t),fn:t=>typeof t=="function",symbol:t=>typeof t=="symbol"});var sn=class t extends Map{static require(e,r){if(e.has(r))return e.get(r);throw new Error(`required key not found: "${r}"`)}static guarantee(e,r,n){if(e.has(r))return e.get(r);{let o=n();return e.set(r,o),o}}array(){return[...this]}require(e){return t.require(this,e)}guarantee(e,r){return t.guarantee(this,e,r)}};var xr=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function gs(t,e){return t<=0||t===1/0?e():new Promise((r,n)=>{let o=setTimeout(()=>n(new xr(t)),t);e().then(r).catch(n).finally(()=>clearTimeout(o))})}function an(){let t=[];function e(){for(let r of t)r();t=[]}return e.schedule=(...r)=>(t.push(...r),e),e}function xs(t,e){let r=t;for(let n of e)if(r=r[n],on.sad(r))break;return r}function qc(){let t=new Set;async function e(...c){await Promise.all([...t].map(l=>l(...c)))}function r(c){return t.add(c),()=>{t.delete(c)}}async function n(...c){return e(...c)}function o(c){return r(c)}async function s(c){let{promise:l,resolve:d}=Pe(),u=o(async(...m)=>{c&&await c(...m),d(m),u()});return l}function i(){t.clear()}let a={pub:n,sub:o,publish:e,subscribe:r,on:r,next:s,clear:i};return Object.assign(o,a),Object.assign(n,a),a}function Bt(t){let e=qc();return t&&e.sub(t),e.pub}var N;(function(t){t[t.Sequence=0]="Sequence",t[t.Stack=1]="Stack",t[t.Video=2]="Video",t[t.Audio=3]="Audio",t[t.Text=4]="Text",t[t.Gap=5]="Gap",t[t.Spatial=6]="Spatial",t[t.Transition=7]="Transition",t[t.TextStyle=8]="TextStyle"})(N||(N={}));var cn;(function(t){t[t.Crossfade=0]="Crossfade"})(cn||(cn={}));var q=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.timeline.items.find(n=>n.id===e)}get timeline(){return this.state.timeline}getId(){return ve.toInteger(ve.random())}#e(e){this.state.timeline=e(this.state.timeline)}register(e){this.#e(r=>({...r,items:[...r.items,e]}))}textStyle=e=>{let r={id:this.getId(),kind:N.TextStyle,style:e};return this.register(r),r};spatial=e=>{let r={id:this.getId(),kind:N.Spatial,transform:e,enabled:!0};return this.register(r),r};sequence=(...e)=>{let r={id:this.getId(),kind:N.Sequence,childrenIds:e.map(n=>n.id)};return this.register(r),r};stack=(...e)=>{let r={kind:N.Stack,id:this.getId(),childrenIds:e.map(n=>n.id)};return this.register(r),r};video=(e,r)=>{if(!e.hasVideo)throw new Error(`Video clip error: media "${e.datafile.filename}" has no video track.`);let n={kind:N.Video,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:r?.start??0,duration:r?.duration??e.duration};return this.register(n),n};audio=(e,r)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let n={kind:N.Audio,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:r?.start??0,duration:r?.duration??e.duration,gain:r?.gain??1};return this.register(n),n};text=(e,r)=>{let n={id:this.getId(),content:e,kind:N.Text,duration:r?.duration??2e3};return r?.styles&&(n.styleId=this.textStyle(r.styles).id),this.register(n),n};gap=e=>{let r={id:this.getId(),kind:N.Gap,duration:e};return this.register(r),r};transition={crossfade:e=>{let r={id:this.getId(),kind:N.Transition,effect:cn.Crossfade,duration:e};return this.register(r),r}};transform=e=>{let r=[e?.position?.[0]??0,e?.position?.[1]??0],n=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[r,n,o]};addChildren(e,...r){this.#e(n=>(n.items.find(({id:s})=>s===e.id).childrenIds.push(...r.map(s=>s.id)),n))}set=(e,r)=>{this.#e(n=>({...n,items:n.items.map(o=>o.id===e?{...o,...r}:o)}))}};var je=t=>t;function h(t){if(!t)throw new Error("Assertion failed.")}var ln=t=>{let e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},re=t=>t&&t[t.length-1];var L=class t{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,n=7-(this.pos&7),o=(r&1<<n)>>n;return this.pos++,o}readBits(e){if(e===1)return this.readBit();let r=0;for(let n=0;n<e;n++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let n=this.pos+e;for(let o=this.pos;o<n;o++){let s=Math.floor(o/8),i=this.bytes[s],a=7-(o&7);i&=~(1<<a),i|=(r&1<<n-o-1)>>n-o-1<<a,this.bytes[s]=i}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}},_=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},Ce=t=>{let e=_(t);return(e&1)===0?-(e>>1):e+1>>1};var he=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),V=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Y=new TextDecoder;var ni=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),oi={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},un=ni(oi),ii={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},dn=ni(ii),si={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},mn=ni(si);var fn=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),Ie=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,r=new Promise(o=>{e=o}),n=this.currentPromise;return this.currentPromise=r,await n,e}},ai=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),ci=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),ct=(t,e,r)=>{let n=0,o=t.length-1,s=-1;for(;n<=o;){let i=n+o>>1,a=r(t[i]);a===e?(s=i,o=i-1):a<e?n=i+1:o=i-1}return s},U=(t,e,r)=>{let n=0,o=t.length-1,s=-1;for(;n<=o;){let i=n+(o-n+1)/2|0;r(t[i])<=e?(s=i,n=i+1):o=i-1}return s},li=(t,e,r)=>{let n=U(t,r(e),r);t.splice(n+1,0,e)},ne=()=>{let t,e;return{promise:new Promise((n,o)=>{t=n,e=o}),resolve:t,reject:e}};var ui=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return t[r]},pn=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},ys=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},Ts=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},fe=t=>{throw new Error(`Unexpected value: ${t}`)},lt=(t,e,r)=>{let n=t.getUint8(e),o=t.getUint8(e+1),s=t.getUint8(e+2);return r?n|o<<8|s<<16:n<<16|o<<8|s},ws=(t,e,r)=>lt(t,e,r)<<8>>8,ks=(t,e,r,n)=>{r=r>>>0,r=r&16777215,n?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))};var ut=(t,e,r)=>Math.max(e,Math.min(r,t)),Z="und",dt=t=>{let e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},vs=(t,e)=>Math.round(t/e)*e,Ss=t=>{let e=0;for(;t;)e++,t>>=1;return e},Wc=/^[a-z]{3}$/,hn=t=>Wc.test(t),Ae=1e6*(1+Number.EPSILON),di=(t,e)=>{let r={...t,...e};if(t.headers||e.headers){let n=t.headers?bs(t.headers):{},o=e.headers?bs(e.headers):{},s={...n};Object.entries(o).forEach(([i,a])=>{let c=Object.keys(s).find(l=>l.toLowerCase()===i.toLowerCase());c&&delete s[c],s[i]=a}),r.headers=s}return r},bs=t=>{if(t instanceof Headers){let e={};return t.forEach((r,n)=>{e[n]=r}),e}if(Array.isArray(t)){let e={};return t.forEach(([r,n])=>{e[r]=n}),e}return t},mi=async(t,e,r,n,o)=>{let s=0;for(;;)try{return await t(e,r)}catch(i){if(o())throw i;s++;let a=n(s,i,e);if(a===null)throw i;if(console.error("Retrying failed fetch. Error:",i),!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(a>0&&await new Promise(c=>setTimeout(c,1e3*a)),o())throw i}};var br=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Jo=null,$e=()=>Jo!==null?Jo:Jo=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),ei=null,fi=()=>ei!==null?ei:ei=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),ti=null,yr=()=>ti!==null?ti:ti=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),ri=null,Ps=()=>{if(ri!==null)return ri;if(typeof navigator>"u")return null;let t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?ri=Number(t[1]):null},mt=(t,e)=>t!==-1?t:e,gn=(t,e,r,n)=>t<=n&&r<=e;var Is=t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r};var xn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Tr=t=>typeof t=="number"&&!Number.isNaN(t);var Ke=class{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}},bn=class{constructor(e,r,n,o){if(this.data=e,this.mimeType=r,this.name=n,this.description=o,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(o!==void 0&&typeof o!="string")throw new TypeError("description, when provided, must be a string.")}};var se={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};var Xe=["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"],jc=["aac","opus","mp3","vorbis","flac"],Dd=[...jc,...Xe];var ft=[{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 Cs=".01.01.01.01.00",As=".0.110.01.01.01.0";var yn=t=>{let{codec:e,codecDescription:r,colorSpace:n,avcCodecInfo:o,hevcCodecInfo:s,vp9CodecInfo:i,av1CodecInfo:a}=t;if(e==="avc"){if(h(t.avcType!==null),o){let c=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${t.avcType}.${ai(c)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${ai(r.subarray(1,4))}`}else if(e==="hevc"){let c,l,d,u,m,f;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,d=ci(s.generalProfileCompatibilityFlags),u=s.generalTierFlag,m=s.generalLevelIdc,f=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=V(r),x=g.getUint8(1);c=x>>6&3,l=x&31,d=ci(g.getUint32(2)),u=x>>5&1,m=g.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(g.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=d.toString(16).toUpperCase(),p+=".",p+=u===0?"L":"H",p+=m;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!i){let y=t.width*t.height,b=re(ft).level;for(let w of ft)if(y<=w.maxPictureSize){b=w.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}let c=i.profile.toString().padStart(2,"0"),l=i.level.toString().padStart(2,"0"),d=i.bitDepth.toString().padStart(2,"0"),u=i.chromaSubsampling.toString().padStart(2,"0"),m=i.colourPrimaries.toString().padStart(2,"0"),f=i.transferCharacteristics.toString().padStart(2,"0"),p=i.matrixCoefficients.toString().padStart(2,"0"),g=i.videoFullRangeFlag.toString().padStart(2,"0"),x=`vp09.${c}.${l}.${d}.${u}`;return x+=`.${m}.${f}.${p}.${g}`,x.endsWith(Cs)&&(x=x.slice(0,-Cs.length)),x}else if(e==="av1"){if(!a){let w=t.width*t.height,T=re(ft).level;for(let S of ft)if(w<=S.maxPictureSize){T=S.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),d=a.tier?"H":"M",u=a.bitDepth.toString().padStart(2,"0"),m=a.monochrome?"1":"0",f=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=n?.primaries?oi[n.primaries]:1,g=n?.transfer?ii[n.transfer]:1,x=n?.matrix?si[n.matrix]:1,y=n?.fullRange?1:0,b=`av01.${c}.${l}${d}.${u}`;return b+=`.${m}.${f.toString().padStart(3,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${x.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(As)&&(b=b.slice(0,-As.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)};var Tn=t=>{let{codec:e,codecDescription:r,aacCodecInfo:n}=t;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");return n.isMpeg2?"mp4a.67":`mp4a.40.${hi(r).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&Xe.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},wr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],pi=[-1,1,2,3,4,5,6,8],hi=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new L(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let n=e.readBits(4),o=null;n===15?o=e.readBits(24):n<wr.length&&(o=wr[n]);let s=e.readBits(4),i=null;return s>=1&&s<=7&&(i=pi[s]),{objectType:r,frequencyIndex:n,sampleRate:o,channelConfiguration:s,numberOfChannels:i}};var pt=48e3,$c=/^pcm-([usf])(\d+)+(be)?$/,wn=t=>{if(h(Xe.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=$c.exec(t);h(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";let n=Number(e[2])/8,o=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:n,littleEndian:o,silentValue:s}};var ht;(function(t){t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.SPS_EXT=13]="SPS_EXT"})(ht||(ht={}));var oe;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(oe||(oe={}));var vn=t=>{let e=[],r=0;for(;r<t.length;){let n=-1,o=0;for(let s=r;s<t.length-3;s++){if(t[s]===0&&t[s+1]===0&&t[s+2]===1){n=s,o=3;break}if(s<t.length-4&&t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1){n=s,o=4;break}}if(n===-1)break;if(r>0&&n>r){let s=t.subarray(r,n);s.length>0&&e.push(s)}r=n+o}if(r<t.length){let n=t.subarray(r);n.length>0&&e.push(n)}return e},Fs=(t,e)=>{let r=[],n=0,o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;n+e<=t.length;){let s;e===1?s=o.getUint8(n):e===2?s=o.getUint16(n,!1):e===3?s=lt(o,n,!1):e===4?s=o.getUint32(n,!1):(fe(e),h(!1)),n+=e;let i=t.subarray(n,n+s);r.push(i),n+=s}return r},kn=t=>{let e=[],r=t.length;for(let n=0;n<r;n++)n+2<r&&t[n]===0&&t[n+1]===0&&t[n+2]===3?(e.push(0,0),n+=2):e.push(t[n]);return new Uint8Array(e)},gi=new Uint8Array([0,0,0,1]),Xc=t=>{let e=t.reduce((o,s)=>o+gi.byteLength+s.byteLength,0),r=new Uint8Array(e),n=0;for(let o of t)r.set(gi,n),n+=gi.byteLength,r.set(o,n),n+=o.byteLength;return r},Qc=(t,e)=>{let r=t.reduce((s,i)=>s+e+i.byteLength,0),n=new Uint8Array(r),o=0;for(let s of t){let i=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:i.setUint8(o,s.byteLength);break;case 2:i.setUint16(o,s.byteLength,!1);break;case 3:ks(i,o,s.byteLength,!1);break;case 4:i.setUint32(o,s.byteLength,!1);break}o+=e,n.set(s,o),o+=s.byteLength}return n},xi=(t,e)=>{if(e.description){let o=(he(e.description)[4]&3)+1;return Fs(t,o)}else return vn(t)},Ds=(t,e)=>{if(e.description){let o=(he(e.description)[4]&3)+1;return Qc(t,o)}else return Xc(t)},gt=t=>t[0]&31,Rs=t=>{try{let e=vn(t),r=e.filter(c=>gt(c)===ht.SPS),n=e.filter(c=>gt(c)===ht.PPS),o=e.filter(c=>gt(c)===ht.SPS_EXT);if(r.length===0||n.length===0)return null;let s=r[0],i=bi(s);h(i!==null);let a=i.profileIdc===100||i.profileIdc===110||i.profileIdc===122||i.profileIdc===144;return{configurationVersion:1,avcProfileIndication:i.profileIdc,profileCompatibility:i.constraintFlags,avcLevelIndication:i.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:n,chromaFormat:a?i.chromaFormatIdc:null,bitDepthLumaMinus8:a?i.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?i.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?o:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}};var Bs=t=>{try{let e=V(t),r=0,n=e.getUint8(r++),o=e.getUint8(r++),s=e.getUint8(r++),i=e.getUint8(r++),a=e.getUint8(r++)&3,c=e.getUint8(r++)&31,l=[];for(let f=0;f<c;f++){let p=e.getUint16(r,!1);r+=2,l.push(t.subarray(r,r+p)),r+=p}let d=e.getUint8(r++),u=[];for(let f=0;f<d;f++){let p=e.getUint16(r,!1);r+=2,u.push(t.subarray(r,r+p)),r+=p}let m={configurationVersion:n,avcProfileIndication:o,profileCompatibility:s,avcLevelIndication:i,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((o===100||o===110||o===122||o===144)&&r+4<=t.length){let f=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,x=e.getUint8(r++);m.chromaFormat=f,m.bitDepthLumaMinus8=p,m.bitDepthChromaMinus8=g;let y=[];for(let b=0;b<x;b++){let w=e.getUint16(r,!1);r+=2,y.push(t.subarray(r,r+w)),r+=w}m.sequenceParameterSetExt=y}return m}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},bi=t=>{try{let e=new L(kn(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),o=e.readAlignedByte(),s=e.readAlignedByte();_(e);let i=null,a=null,c=null;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(i=_(e),i===3&&e.skipBits(1),a=_(e),c=_(e),e.skipBits(1),e.readBits(1))){for(let m=0;m<(i!==3?8:12);m++)if(e.readBits(1)){let p=m<6?16:64,g=8,x=8;for(let y=0;y<p;y++){if(x!==0){let b=Ce(e);x=(g+b+256)%256}g=x===0?g:x}}}_(e);let l=_(e);if(l===0)_(e);else if(l===1){e.skipBits(1),Ce(e),Ce(e);let u=_(e);for(let m=0;m<u;m++)Ce(e)}_(e),e.skipBits(1),_(e),_(e);let d=e.readBits(1);return{profileIdc:n,constraintFlags:o,levelIdc:s,frameMbsOnlyFlag:d,chromaFormatIdc:i,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},yi=(t,e)=>{if(e.description){let o=(he(e.description)[21]&3)+1;return Fs(t,o)}else return vn(t)},Be=t=>t[0]>>1&63,Ms=t=>{try{let e=vn(t),r=e.filter(z=>Be(z)===oe.VPS_NUT),n=e.filter(z=>Be(z)===oe.SPS_NUT),o=e.filter(z=>Be(z)===oe.PPS_NUT),s=e.filter(z=>Be(z)===oe.PREFIX_SEI_NUT||Be(z)===oe.SUFFIX_SEI_NUT);if(n.length===0||o.length===0)return null;let i=n[0],a=new L(kn(i));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:d,general_tier_flag:u,general_profile_idc:m,general_profile_compatibility_flags:f,general_constraint_indicator_flags:p,general_level_idc:g}=Yc(a,c);_(a);let x=_(a);x===3&&a.skipBits(1),_(a),_(a),a.readBits(1)&&(_(a),_(a),_(a),_(a));let y=_(a),b=_(a);_(a);let T=a.readBits(1)?0:c;for(let z=T;z<=c;z++)_(a),_(a),_(a);_(a),_(a),_(a),_(a),_(a),_(a),a.readBits(1)&&a.readBits(1)&&Zc(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),_(a),_(a),a.skipBits(1));let S=_(a);if(Jc(a,S),a.readBits(1)){let z=_(a);for(let B=0;B<z;B++)_(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let v=0;a.readBits(1)&&(v=tl(a,c));let A=0;if(o.length>0){let z=o[0],B=new L(kn(z));B.skipBits(16),_(B),_(B),B.skipBits(1),B.skipBits(1),B.skipBits(3),B.skipBits(1),B.skipBits(1),_(B),_(B),Ce(B),B.skipBits(1),B.skipBits(1),B.readBits(1)&&_(B),Ce(B),Ce(B),B.skipBits(1),B.skipBits(1),B.skipBits(1),B.skipBits(1);let Q=B.readBits(1),st=B.readBits(1);!Q&&!st?A=0:Q&&!st?A=2:!Q&&st?A=3:A=0}let C=[...r.length?[{arrayCompleteness:1,nalUnitType:oe.VPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:oe.SPS_NUT,nalUnits:n}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:oe.PPS_NUT,nalUnits:o}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:Be(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:u,generalProfileIdc:m,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:p,generalLevelIdc:g,minSpatialSegmentationIdc:v,parallelismType:A,chromaFormatIdc:x,bitDepthLumaMinus8:y,bitDepthChromaMinus8:b,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:C}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Yc=(t,e)=>{let r=t.readBits(2),n=t.readBits(1),o=t.readBits(5),s=0;for(let d=0;d<32;d++)s=s<<1|t.readBits(1);let i=new Uint8Array(6);for(let d=0;d<6;d++)i[d]=t.readBits(8);let a=t.readBits(8),c=[],l=[];for(let d=0;d<e;d++)c.push(t.readBits(1)),l.push(t.readBits(1));if(e>0)for(let d=e;d<8;d++)t.skipBits(2);for(let d=0;d<e;d++)c[d]&&t.skipBits(88),l[d]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:i,general_level_idc:a}},Zc=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))_(t);else{let o=Math.min(64,1<<4+(e<<1));e>1&&Ce(t);for(let s=0;s<o;s++)Ce(t)}},Jc=(t,e)=>{let r=[];for(let n=0;n<e;n++)r[n]=el(t,n,e,r)},el=(t,e,r,n)=>{let o=0,s=0,i=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let c=_(t);i=e-(c+1)}else i=e-1;t.readBits(1),_(t);let a=n[i]??0;for(let c=0;c<=a;c++)t.readBits(1)||t.readBits(1);o=n[i]}else{let a=_(t),c=_(t);for(let l=0;l<a;l++)_(t),t.readBits(1);for(let l=0;l<c;l++)_(t),t.readBits(1);o=a+c}return o},tl=(t,e)=>{if(t.readBits(1)&&t.readBits(8)===255&&(t.readBits(16),t.readBits(16)),t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),t.readBits(1),t.readBits(1)&&(t.readBits(8),t.readBits(8),t.readBits(8))),t.readBits(1)&&(_(t),_(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(_(t),_(t),_(t),_(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&_(t),t.readBits(1)&&rl(t,!0,e)),t.readBits(1)){t.readBits(1),t.readBits(1),t.readBits(1);let r=_(t);return _(t),_(t),_(t),_(t),r}return 0},rl=(t,e,r)=>{let n=!1,o=!1,s=!1;e&&(n=t.readBits(1)===1,o=t.readBits(1)===1,(n||o)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let i=0;i<=r;i++){let a=t.readBits(1)===1,c=!0;a||(c=t.readBits(1)===1);let l=!1;c?_(t):l=t.readBits(1)===1;let d=1;l||(d=_(t)+1),n&&_s(t,d,s),o&&_s(t,d,s)}},_s=(t,e,r)=>{for(let n=0;n<e;n++)_(t),_(t),r&&(_(t),_(t)),t.readBits(1)};var Sn=t=>{let e=new L(t);if(e.readBits(2)!==2)return null;let n=e.readBits(1),s=(e.readBits(1)<<1)+n;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=e.readBits(1)?12:10);let d=e.readBits(3),u=0,m=0;if(d!==7)if(m=e.readBits(1),s===1||s===3){let A=e.readBits(1),C=e.readBits(1);u=!A&&!C?3:A&&!C?2:1,e.skipBits(1)}else u=1;else u=3,m=1;let f=e.readBits(16),p=e.readBits(16),g=f+1,x=p+1,y=g*x,b=re(ft).level;for(let v of ft)if(y<=v.maxPictureSize){b=v.level;break}return{profile:s,level:b,bitDepth:l,chromaSubsampling:u,videoFullRangeFlag:m,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}},Os=function*(t){let e=new L(t),r=()=>{let n=0;for(let o=0;o<8;o++){let s=e.readAlignedByte();if(n|=(s&127)<<o*7,!(s&128))break;if(o===7&&s&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),o=e.readBits(1),s=e.readBits(1);e.skipBits(1),o&&e.skipBits(8);let i;if(s){let a=r();if(a===null)return;i=a}else i=Math.floor(e.getBitsLeft()/8);h(e.pos%8===0),yield{type:n,data:t.subarray(e.pos/8,e.pos/8+i)},e.skipBits(i*8)}},Pn=t=>{for(let{type:e,data:r}of Os(t)){if(e!==1)continue;let n=new L(r),o=n.readBits(3),s=n.readBits(1),i=n.readBits(1),a=0,c=0,l=0;if(i)a=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let v=n.readBits(1);v&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let A=n.readBits(5);for(let C=0;C<=A;C++){n.skipBits(12);let R=n.readBits(5);if(C===0&&(a=R),R>7){let B=n.readBits(1);C===0&&(c=B)}if(v&&n.readBits(1)){let Q=l+1;n.skipBits(Q),n.skipBits(Q),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let d=n.readBits(4),u=n.readBits(4),m=d+1;n.skipBits(m);let f=u+1;n.skipBits(f);let p=0;if(i?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!i){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let S=n.readBits(1);S&&(n.skipBits(1),n.skipBits(1));let v=n.readBits(1),A=0;v?A=2:A=n.readBits(1),A>0&&(n.readBits(1)||n.skipBits(1)),S&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let g=n.readBits(1),x=8;o===2&&g?x=n.readBits(1)?12:10:o<=2&&(x=g?10:8);let y=0;o!==1&&(y=n.readBits(1));let b=1,w=1,T=0;return y||(o===0?(b=1,w=1):o===1?(b=0,w=0):x===12&&(b=n.readBits(1),b&&(w=n.readBits(1))),b&&w&&(T=n.readBits(2))),{profile:o,level:a,tier:c,bitDepth:x,monochrome:y,chromaSubsamplingX:b,chromaSubsamplingY:w,chromaSamplePosition:T}}return null},zs=t=>{let e=V(t),r=e.getUint8(9),n=e.getUint16(10,!0),o=e.getUint32(12,!0),s=e.getInt16(16,!0),i=e.getUint8(18),a=null;return i&&(a=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:n,inputSampleRate:o,outputGain:s,channelMappingFamily:i,channelMappingTable:a}},nl=[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],Ns=t=>{let e=t[0]>>3;return{durationInSamples:nl[e]}},Us=t=>{if(t.length<7)throw new Error("Setup header is too short.");if(t[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...t.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let r=t.length,n=new Uint8Array(r);for(let u=0;u<r;u++)n[u]=t[r-1-u];let o=new L(n),s=0;for(;o.getBitsLeft()>97;)if(o.readBits(1)===1){s=o.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let i=0,a=!1,c=0;for(;o.getBitsLeft()>=97;){let u=o.pos,m=o.readBits(8),f=o.readBits(16),p=o.readBits(16);if(m>63||f!==0||p!==0){o.pos=u;break}if(o.skipBits(1),i++,i>64)break;o.clone().readBits(6)+1===i&&(a=!0,c=i)}if(!a)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;o.pos=0,o.skipBits(s);let d=Array(l).fill(0);for(let u=l-1;u>=0;u--)o.skipBits(40),d[u]=o.readBits(1);return{modeBlockflags:d}},In=(t,e,r)=>{switch(t){case"avc":{let n=xi(r,e),o=n.some(s=>gt(s)===ht.IDR);if(!o&&(!yr()||Ps()>=144))for(let s of n){if(gt(s)!==ht.SEI)continue;let a=kn(s),c=1;do{let l=0;for(;;){let m=a[c++];if(m===void 0||(l+=m,m<255))break}let d=0;for(;;){let m=a[c++];if(m===void 0||(d+=m,m<255))break}if(l===6){let m=new L(a);m.pos=8*c;let f=_(m),p=m.readBits(1);if(f===0&&p===1){o=!0;break}}c+=d}while(c<a.length-1)}return o?"key":"delta"}case"hevc":return yi(r,e).some(s=>{let i=Be(s);return oe.BLA_W_LP<=i&&i<=oe.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{let n=new L(r);if(n.readBits(2)!==2)return null;let o=n.readBits(1);return(n.readBits(1)<<1)+o===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:o,data:s}of Os(r))if(o===1){let i=new L(s);i.skipBits(4),n=!!i.readBits(1)}else if(o===3||o===6||o===7){if(n)return"key";let i=new L(s);return i.readBits(1)?null:i.readBits(2)===0?"key":"delta"}return null}default:fe(t),h(!1)}},Qe;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Qe||(Qe={}));var kr=(t,e)=>{let r=V(t),n=0,o=r.getUint32(n,!0);n+=4;let s=Y.decode(t.subarray(n,n+o));n+=o,o>0&&(e.raw??={},e.raw.vendor??=s);let i=r.getUint32(n,!0);n+=4;for(let a=0;a<i;a++){let c=r.getUint32(n,!0);n+=4;let l=Y.decode(t.subarray(n,n+c));n+=c;let d=l.indexOf("=");if(d===-1)continue;let u=l.slice(0,d).toUpperCase(),m=l.slice(d+1);switch(e.raw??={},e.raw[u]??=m,u){case"TITLE":e.title??=m;break;case"DESCRIPTION":e.description??=m;break;case"ARTIST":e.artist??=m;break;case"ALBUM":e.album??=m;break;case"ALBUMARTIST":e.albumArtist??=m;break;case"COMMENT":e.comment??=m;break;case"LYRICS":e.lyrics??=m;break;case"TRACKNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{let f=new Date(m);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=m;break;case"METADATA_BLOCK_PICTURE":{let f=Is(m),p=V(f),g=p.getUint32(0,!1),x=p.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+x)),b=p.getUint32(8+x,!1),w=Y.decode(f.subarray(12+x,12+x+b)),T=p.getUint32(x+b+28),S=f.subarray(x+b+32,x+b+32+T);e.images??=[],e.images.push({data:S,mimeType:y,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:w||void 0})}break}}};var te=class{constructor(e){this.input=e}};var Cn=[],An=[];var j=new Uint8Array(0),G=class t{constructor(e,r,n,o,s=-1,i,a){if(this.data=e,this.type=r,this.timestamp=n,this.duration=o,this.sequenceNumber=s,e===j&&i===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(i===void 0&&(i=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(o)||o<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(i)||i<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=i,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===j}get microsecondTimestamp(){return Math.trunc(Ae*this.timestamp)}get microsecondDuration(){return Math.trunc(Ae*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new t(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}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 t(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Vs=t=>{let r=0,n=0,o=~t;o&128&&(o&=-129,r=-1),n=((o&240)>>4)+5;let s=(1<<n|(o&15)<<n-4|1<<n-5)-33;return r===0?s:-s};var Ls=t=>{let e=0,r=0,n=t^85;n&128&&(n&=-129,e=-1),r=((n&240)>>4)+4;let o=0;return r!==4?o=1<<r|(n&15)<<r-4|1<<r-5:o=n<<1|1,e===0?o:-o};xn();var Hs=-1/0,Gs=-1/0,Pr=null;typeof FinalizationRegistry<"u"&&(Pr=new FinalizationRegistry(t=>{let e=Date.now();t.type==="video"?(e-Hs>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Hs=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-Gs>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Gs=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));var Ws=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ol=new Set(Ws),Ot=class t{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(Ae*this.timestamp)}get microsecondDuration(){return Math.trunc(Ae*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!ol.has(r.format))throw new TypeError("init.format must be one of: "+Ws.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=he(e).slice(),this._layout=r.layout??il(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Sr(r.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new Sr(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(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new t(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Ae),duration:Math.trunc((r.duration??0)*Ae)||void 0}),r);let n=0,o=0;if("naturalWidth"in e?(n=e.naturalWidth,o=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,o=e.videoHeight):"width"in e&&(n=Number(e.width),o=Number(e.height)),!n||!o)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(n,o),i=s.getContext("2d",{alpha:fi(),willReadFrequently:!0});h(i),i.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.codedWidth=n,this.codedHeight=o,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Sr({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");Pr?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),xt(this._data)?new t(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(h(this._layout),new t(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new t(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||(Pr?.unregister(this),xt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(qs(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)===null)throw new Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!xt(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let r=this.toVideoFrame(),n=r.allocationSize(e);return r.close(),n}return xt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!fn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(qs(r),this._closed)throw new Error("VideoSample is closed.");if((r.format??this.format)===null)throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!xt(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){let n=this.toVideoFrame(),o=await n.copyTo(e,r);return n.close(),o}if(xt(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return h(this._layout),he(e).set(this._data),this._layout;{let o=this._data.getContext("2d");h(o);let s=o.getImageData(0,0,this.codedWidth,this.codedHeight);return he(e).set(s.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),xt(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,r,n,o,s,i,a,c,l){let d=0,u=0,m=this.displayWidth,f=this.displayHeight,p=0,g=0,x=this.displayWidth,y=this.displayHeight;if(i!==void 0?(d=r,u=n,m=o,f=s,p=i,g=a,c!==void 0?(x=c,y=l):(x=m,y=f)):(p=r,g=n,o!==void 0&&(x=o,y=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(x)||x<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:u,sWidth:m,sHeight:f}=this._rotateSourceRegion(d,u,m,f,this.rotation));let b=this.toCanvasImageSource();e.save();let w=p+x/2,T=g+y/2;e.translate(w,T),e.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:x/y;e.scale(1/S,S),e.drawImage(b,d,u,m,f,-x/2,-y/2,x,y),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&$s(r.crop,"options.");let n=e.canvas.width,o=e.canvas.height,s=r.rotation??this.rotation,[i,a]=s%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];r.crop&&js(r.crop,i,a);let c,l,d,u,{sx:m,sy:f,sWidth:p,sHeight:g}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??i,r.crop?.height??a,s);if(r.fit==="fill")c=0,l=0,d=n,u=o;else{let[y,b]=r.crop?[r.crop.width,r.crop.height]:[i,a],w=r.fit==="contain"?Math.min(n/y,o/b):Math.max(n/y,o/b);d=y*w,u=b*w,c=(n-d)/2,l=(o-u)/2}e.save();let x=s%180===0?1:d/u;e.translate(n/2,o/2),e.rotate(s*Math.PI/180),e.scale(1/x,x),e.translate(-n/2,-o/2),e.drawImage(this.toCanvasImageSource(),m,f,p,g,c,l,d,u),e.restore()}_rotateSourceRegion(e,r,n,o,s){return s===90?[e,r,n,o]=[r,this.codedHeight-e-n,o,n]:s===180?[e,r]=[this.codedWidth-e-n,this.codedHeight-r-o]:s===270&&([e,r,n,o]=[this.codedWidth-r-o,e,o,n]),{sx:e,sy:r,sWidth:n,sHeight:o}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(h(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},Sr=class{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},xt=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,js=(t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),h(t.width>=0),h(t.height>=0)},$s=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},qs=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},il=(t,e,r)=>{let n=sl(t),o=[],s=0;for(let i of n){let a=Math.ceil(e/i.widthDivisor),c=Math.ceil(r/i.heightDivisor),l=a*i.sampleBytes,d=l*c;o.push({offset:s,stride:l}),s+=d}return o},sl=t=>{let e=(r,n,o,s,i)=>{let a=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:o,heightDivisor:s},{sampleBytes:n,widthDivisor:o,heightDivisor:s}];return i&&a.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),a};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:fe(t),h(!1)}},Ti=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),zt=class t{get microsecondTimestamp(){return Math.trunc(Ae*this.timestamp)}get microsecondDuration(){return Math.trunc(Ae*this.duration)}constructor(e){if(this._closed=!1,vr(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ti.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(bt(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let o=this.numberOfFrames*this.numberOfChannels*bt(this.format);if(n.byteLength<o)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}Pr?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Ti.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let r=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let o=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(o>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let s=bt(r),i=Mt(r);if(i&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!i&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(i?o:o*this.numberOfChannels)*s}copyTo(e,r){if(!fn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!Ti.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:n,format:o,frameCount:s,frameOffset:i}=r,a=this.format,c=o??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,d=this.numberOfChannels,u=i??0;if(u>=l)throw new RangeError("frameOffset out of range");let m=s!==void 0?s:l-u;if(m>l-u)throw new RangeError("frameCount out of range");let f=bt(c),p=Mt(c);if(p&&n>=d)throw new RangeError("planeIndex out of range");if(!p&&n!==0)throw new RangeError("planeIndex out of range");let x=(p?m:m*d)*f;if(e.byteLength<x)throw new RangeError("Destination buffer is too small");let y=V(e),b=Xs(c);if(vr(this._data))$e()&&d>2&&c!==a?al(this._data,y,a,c,d,n,u,m):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:m,format:c});else{let w=this._data,T=V(w),S=Ks(a),v=bt(a),A=Mt(a);for(let C=0;C<m;C++)if(p){let R=C*f,z;A?z=(n*l+(C+u))*v:z=((C+u)*d+n)*v;let B=S(T,z);b(y,R,B)}else for(let R=0;R<d;R++){let B=(C*d+R)*f,Q;A?Q=(R*l+(C+u))*v:Q=((C+u)*d+R)*v;let st=S(T,Q);b(y,B,st)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(vr(this._data)){let e=new t(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new t({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Pr?.unregister(this),vr(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(vr(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(Mt(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(r,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(r,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(r,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,s=e.sampleRate,i=e.length,a=Math.floor(n/o),c=0,l=i;for(;l>0;){let d=Math.min(a,l),u=new Float32Array(o*d);for(let m=0;m<o;m++)e.copyFromChannel(u.subarray(m*d,(m+1)*d),m,c);yield new t({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:o,timestamp:r+c/s,data:u}),c+=d,l-=d}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,s=e.sampleRate,i=e.length,a=Math.floor(n/o),c=0,l=i,d=[];for(;l>0;){let u=Math.min(a,l),m=new Float32Array(o*u);for(let p=0;p<o;p++)e.copyFromChannel(m.subarray(p*u,(p+1)*u),p,c);let f=new t({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:o,timestamp:r+c/s,data:m});d.push(f),c+=u,l-=u}return d}},bt=t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Mt=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ks=t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},Xs=t=>{switch(t){case"u8":case"u8-planar":return(e,r,n)=>e.setUint8(r,ut((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,n)=>e.setInt16(r,ut(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,n)=>e.setInt32(r,ut(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,n)=>e.setFloat32(r,n,!0)}},vr=t=>typeof AudioData<"u"&&t instanceof AudioData,al=(t,e,r,n,o,s,i,a)=>{let c=Ks(r),l=Xs(n),d=bt(r),u=bt(n),m=Mt(r);if(Mt(n))if(m){let p=new ArrayBuffer(a*d),g=V(p);t.copyTo(p,{planeIndex:s,frameOffset:i,frameCount:a,format:r});for(let x=0;x<a;x++){let y=x*d,b=x*u,w=c(g,y);l(e,b,w)}}else{let p=new ArrayBuffer(a*o*d),g=V(p);t.copyTo(p,{planeIndex:0,frameOffset:i,frameCount:a,format:r});for(let x=0;x<a;x++){let y=(x*o+s)*d,b=x*u,w=c(g,y);l(e,b,w)}}else if(m){let p=a*d,g=new ArrayBuffer(p),x=V(g);for(let y=0;y<o;y++){t.copyTo(g,{planeIndex:y,frameOffset:i,frameCount:a,format:r});for(let b=0;b<a;b++){let w=b*d,T=(b*o+y)*u,S=c(x,w);l(e,T,S)}}}else{let p=new ArrayBuffer(a*o*d),g=V(p);t.copyTo(p,{planeIndex:0,frameOffset:i,frameCount:a,format:r});for(let x=0;x<a;x++)for(let y=0;y<o;y++){let b=x*o+y,w=b*d,T=b*u,S=c(g,w);l(e,T,S)}}};var Nt=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},yt=t=>{if(!Tr(t))throw new TypeError("timestamp must be a number.")},wi=(t,e,r)=>r.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let o=await t.determinePacketType(n);return o&&(n.type=o),n}):e,Tt=class{constructor(e){if(!(e instanceof Ut))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Nt(e),this._track.input._disposed)throw new $;return wi(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,r={}){if(yt(e),Nt(r),this._track.input._disposed)throw new $;return wi(this._track,this._track._backing.getPacket(e,r),r)}getNextPacket(e,r={}){if(!(e instanceof G))throw new TypeError("packet must be an EncodedPacket.");if(Nt(r),this._track.input._disposed)throw new $;return wi(this._track,this._track._backing.getNextPacket(e,r),r)}async getKeyPacket(e,r={}){if(yt(e),Nt(r),this._track.input._disposed)throw new $;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);let n=await this._track._backing.getKeyPacket(e,r);return n&&(h(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,r):n)}async getNextKeyPacket(e,r={}){if(!(e instanceof G))throw new TypeError("packet must be an EncodedPacket.");if(Nt(r),this._track.input._disposed)throw new $;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);let n=await this._track._backing.getNextKeyPacket(e,r);return n&&(h(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,r):n)}packets(e,r,n={}){if(e!==void 0&&!(e instanceof G))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(r!==void 0&&!(r instanceof G))throw new TypeError("endPacket must be an EncodedPacket.");if(Nt(n),this._track.input._disposed)throw new $;let o=[],{promise:s,resolve:i}=ne(),{promise:a,resolve:c}=ne(),l=!1,d=!1,u=null,m=[],f=()=>Math.max(2,m.length);(async()=>{let g=e??await this.getFirstPacket(n);for(;g&&!d&&!this._track.input._disposed&&!(r&&g.sequenceNumber>=r?.sequenceNumber);){if(o.length>f()){({promise:a,resolve:c}=ne()),await a;continue}o.push(g),i(),{promise:s,resolve:i}=ne(),g=await this.getNextPacket(g,n)}l=!0,i()})().catch(g=>{u||(u=g,i())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new $;if(d)return{value:void 0,done:!0};if(u)throw u;if(o.length>0){let g=o.shift(),x=performance.now();for(m.push(x);m.length>0&&x-m[0]>=1e3;)m.shift();return c(),{value:g,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return d=!0,c(),i(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},Ir=class{constructor(e,r){this.onSample=e,this.onError=r}},Cr=class{mediaSamplesInRange(e=0,r=1/0){yt(e),yt(r);let n=[],o=!1,s=null,{promise:i,resolve:a}=ne(),{promise:c,resolve:l}=ne(),d=!1,u=!1,m=!1,f=null;(async()=>{let x=await this._createDecoder(v=>{if(l(),v.timestamp>=r&&(u=!0),u){v.close();return}s&&(v.timestamp>e?(n.push(s),o=!0):s.close()),v.timestamp>=e&&(n.push(v),o=!0),s=o?null:v,n.length>0&&(a(),{promise:i,resolve:a}=ne())},v=>{f||(f=v,a())}),y=this._createPacketSink(),b=await y.getKeyPacket(e,{verifyKeyPackets:!0})??await y.getFirstPacket(),w=b,T;if(r<1/0){let v=await y.getPacket(r),A=v?v.type==="key"&&v.timestamp===r?v:await y.getNextKeyPacket(v,{verifyKeyPackets:!0}):null;A&&(T=A)}let S=y.packets(b??void 0,T);for(await S.next();w&&!u&&!this._track.input._disposed;){let v=Qs(n.length);if(n.length+x.getDecodeQueueSize()>v){({promise:c,resolve:l}=ne()),await c;continue}x.decode(w);let A=await S.next();if(A.done)break;w=A.value}await S.return(),!m&&!this._track.input._disposed&&await x.flush(),x.close(),!o&&s&&n.push(s),d=!0,a()})().catch(x=>{f||(f=x,a())});let p=this._track,g=()=>{s?.close();for(let x of n)x.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new $;if(m)return{value:void 0,done:!0};if(f)throw g(),f;if(n.length>0){let x=n.shift();return l(),{value:x,done:!1}}else if(!d)await i;else return{value:void 0,done:!0}}},async return(){return m=!0,u=!0,l(),a(),g(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Ts(e);let r=ys(e),n=[],o=[],{promise:s,resolve:i}=ne(),{promise:a,resolve:c}=ne(),l=!1,d=!1,u=null,m=g=>{o.push(g),i(),{promise:s,resolve:i}=ne()};(async()=>{let g=await this._createDecoder(v=>{if(c(),d){v.close();return}let A=0;for(;n.length>0&&v.timestamp-n[0]>-1e-10;)A++,n.shift();if(A>0)for(let C=0;C<A;C++)m(C<A-1?v.clone():v);else v.close()},v=>{u||(u=v,i())}),x=this._createPacketSink(),y=null,b=null,w=-1,T=async()=>{h(b);let v=b;for(g.decode(v);v.sequenceNumber<w;){let A=Qs(o.length);for(;o.length+g.getDecodeQueueSize()>A&&!d;)({promise:a,resolve:c}=ne()),await a;if(d)break;let C=await x.getNextPacket(v);h(C),g.decode(C),v=C}w=-1},S=async()=>{await g.flush();for(let v=0;v<n.length;v++)m(null);n.length=0};for await(let v of r){if(yt(v),d||this._track.input._disposed)break;let A=await x.getPacket(v),C=A&&await x.getKeyPacket(v,{verifyKeyPackets:!0});if(!C){w!==-1&&(await T(),await S()),m(null),y=null;continue}y&&(C.sequenceNumber!==b.sequenceNumber||A.timestamp<y.timestamp)&&(await T(),await S()),n.push(A.timestamp),w=Math.max(A.sequenceNumber,w),y=A,b=C}!d&&!this._track.input._disposed&&(w!==-1&&await T(),await S()),g.close(),l=!0,i()})().catch(g=>{u||(u=g,i())});let f=this._track,p=()=>{for(let g of o)g?.close()};return{async next(){for(;;){if(f.input._disposed)throw p(),new $;if(d)return{value:void 0,done:!0};if(u)throw p(),u;if(o.length>0){let g=o.shift();return h(g!==void 0),c(),{value:g,done:!1}}else if(!l)await s;else return{value:void 0,done:!0}}},async return(){return d=!0,c(),i(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},Qs=t=>t===0?40:8,ki=class extends Ir{constructor(e,r,n,o,s,i){super(e,r),this.codec=n,this.decoderConfig=o,this.rotation=s,this.timeResolution=i,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new br,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let a=Cn.find(c=>c.supports(n,o));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=c=>{if(!(c instanceof Ot))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=d=>{if(this.alphaQueue.length>0){let u=this.alphaQueue.shift();h(u!==void 0),this.mergeAlpha(d,u)}else this.colorQueue.push(d)};if(n==="avc"&&this.decoderConfig.description&&yr()){let d=Bs(he(this.decoderConfig.description));if(d&&d.sequenceParameterSets.length>0){let u=bi(d.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:d=>{try{c(d)}catch(u){this.onError(u)}},error:d=>{d.stack=l,this.onError(d)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(h(this.decoder),$e()||li(this.inputTimestamps,e.timestamp,r=>r),yr()&&this.currentPacketIndex===0&&this.codec==="avc"){let n=xi(e.data,this.decoderConfig).filter(s=>{let i=gt(s);return!(i>=20&&i<=31)}),o=Ds(n,this.decoderConfig);e=new G(o,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new vi}catch(n){console.error("Due to an error, only color data will be decoded.",n),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let n=s=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let i=this.colorQueue.shift();h(i!==void 0),this.mergeAlpha(i,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let i=this.colorQueue.shift();h(i!==void 0),this.mergeAlpha(i,null)}else this.alphaQueue.push(null)},o=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(s)}catch(i){this.onError(i)}},error:s=>{s.stack=o,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}let r=In(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return yi(e,this.decoderConfig).some(n=>{let o=Be(n);return o===oe.RASL_N||o===oe.RASL_R})}sampleHandler(e){if($e()){if(this.sampleQueue.length>0&&e.timestamp>=re(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}li(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();h(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,r){if(!r){let s=new Ot(e);this.sampleHandler(s);return}h(this.merger),this.merger.update(e,r),e.close(),r.close();let n=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),o=new Ot(n);this.sampleHandler(o)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),$e()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},vi=class{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2339
2339
|
in vec2 a_position;
|
|
2340
2340
|
in vec2 a_texCoord;
|
|
2341
2341
|
out vec2 v_texCoord;
|
|
@@ -2357,7 +2357,7 @@ vec4 transition(vec2 uv) {
|
|
|
2357
2357
|
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
2358
2358
|
fragColor = vec4(color, alpha);
|
|
2359
2359
|
}
|
|
2360
|
-
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),n}createShader(e,r){let n=this.gl.createShader(e);return this.gl.shaderSource(n,r),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let o=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,r){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Ar=class extends Cr{constructor(e){if(!(e instanceof Me))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=this._track.rotation,s=await this._track.getDecoderConfig(),i=this._track.timeResolution;return h(n&&s),new ki(e,r,n,s,o,i)}_createPacketSink(){return new Tt(this._track)}async getSample(e){yt(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var Si=class extends Ir{constructor(e,r,n,o){super(e,r),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new br,this.customDecoderQueueSize=0,this.currentTimestamp=null;let s=a=>{(this.currentTimestamp===null||Math.abs(a.timestamp-this.currentTimestamp)>=a.duration)&&(this.currentTimestamp=a.timestamp);let c=this.currentTimestamp;if(this.currentTimestamp+=a.duration,a.numberOfFrames===0){a.close();return}let l=o.sampleRate;a.setTimestamp(Math.round(c*l)/l),e(a)},i=An.find(a=>a.supports(n,o));if(i)this.customDecoder=new i,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=a=>{if(!(a instanceof zt))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(a)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let a=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{s(new zt(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(h(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close())}},Pi=class extends Ir{constructor(e,r,n){super(e,r),this.decoderConfig=n,this.currentTimestamp=null,h(Xe.includes(n.codec)),this.codec=n.codec;let{dataType:o,sampleSize:s,littleEndian:i}=wn(this.codec);switch(this.inputSampleSize=s,s){case 1:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint8(c)-2**7:o==="signed"?this.readInputValue=(a,c)=>a.getInt8(c):o==="ulaw"?this.readInputValue=(a,c)=>Vs(a.getUint8(c)):o==="alaw"?this.readInputValue=(a,c)=>Ls(a.getUint8(c)):h(!1);break;case 2:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint16(c,i)-2**15:o==="signed"?this.readInputValue=(a,c)=>a.getInt16(c,i):h(!1);break;case 3:o==="unsigned"?this.readInputValue=(a,c)=>lt(a,c,i)-2**23:o==="signed"?this.readInputValue=(a,c)=>ws(a,c,i):h(!1);break;case 4:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint32(c,i)-2**31:o==="signed"?this.readInputValue=(a,c)=>a.getInt32(c,i):o==="float"?this.readInputValue=(a,c)=>a.getFloat32(c,i):h(!1);break;case 8:o==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,i):h(!1);break;default:fe(s),h(!1)}switch(s){case 1:o==="ulaw"||o==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(a,c,l)=>a.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,o==="float"?(this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0);break;default:fe(s),h(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=V(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(o),i=new DataView(s);for(let d=0;d<n*this.decoderConfig.numberOfChannels;d++){let u=d*this.inputSampleSize,m=d*this.outputSampleSize,f=this.readInputValue(r,u);this.writeOutputValue(i,m,f)}let a=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=a;let l=new zt({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:c});this.onSample(l)}async flush(){}close(){}},_r=class extends Cr{constructor(e){if(!(e instanceof K))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=await this._track.getDecoderConfig();return h(n&&o),Xe.includes(o.codec)?new Pi(e,r,o):new Si(e,r,n,o)}_createPacketSink(){return new Tt(this._track)}async getSample(e){yt(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var Nt=class{constructor(e,r){this.input=e,this._backing=r}isVideoTrack(){return this instanceof Me}isAudioTrack(){return this instanceof K}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let r=new Tt(this),n=1/0,o=-1/0,s=0,i=0;for await(let a of r.packets(void 0,void 0,{metadataOnly:!0})){if(s>=e&&a.timestamp>=o)break;n=Math.min(n,a.timestamp),o=Math.max(o,a.timestamp+a.duration),s++,i+=a.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(o-n)).toPrecision(16)):0,averageBitrate:s?Number((8*i/(o-n)).toPrecision(16)):0}}},Me=class extends Nt{constructor(e,r){super(e,r),this._backing=r}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return h(r!==null),Cn.some(o=>o.supports(r,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 G))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let r=await this.getDecoderConfig();return h(r),In(this.codec,r,e.data)}},K=class extends Nt{constructor(e,r){super(e,r),this._backing=r}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 r=this._backing.getCodec();return h(r!==null),An.some(n=>n.supports(r,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 G))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Ys=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){let n=[...new Set(t.codecStrings)];r+=`; codecs="${n.join(", ")}"`}return r};var wt=8,Vt=16,Oe=t=>{let e=I(t),r=W(t,4),n=8;e===1&&(e=ce(t),n=16);let s=e-n;return s<0?null:{name:r,totalSize:e,headerSize:n,contentSize:s}},Ye=t=>ze(t)/65536,_n=t=>ze(t)/1073741824,En=t=>{let e=0;for(let r=0;r<4;r++){e<<=7;let n=F(t);if(e|=n&127,(n&128)===0)break}return e},ge=t=>{let e=X(t);return t.skip(2),e=Math.min(e,t.remainingLength),Y.decode(D(t,e))},Zs=t=>{let e=Oe(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;let r=I(t);t.skip(4);let n=D(t,e.contentSize-8);switch(r){case 1:return Y.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new Ke(n,"image/jpeg");case 14:return new Ke(n,"image/png");case 27:return new Ke(n,"image/bmp");default:return n}};var Fn=class extends te{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}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(r=>r.inputTrack.getCodecParameterString()));return Ys({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.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 r=this.reader.requestSliceRange(e,wt,Vt);if(r instanceof Promise&&(r=await r),!r)break;let n=e,o=Oe(r);if(!o)break;if(o.name==="ftyp"){let s=W(r,4);this.isQuickTime=s==="qt "}else if(o.name==="moov"){let s=this.reader.requestSlice(r.filePos,o.contentSize);if(s instanceof Promise&&(s=await s),!s)break;this.moovSlice=s,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((i,a)=>Number(a.disposition.default)-Number(i.disposition.default));for(let i of this.tracks){let a=i.editListPreviousSegmentDurations/this.movieTimescale;i.editListOffset-=Math.round(a*i.timescale)}break}e=n+o.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),h(r);let n=I(r),o=this.reader.fileSize-n;if(o>=0&&o<=this.reader.fileSize-Vt){let s=this.reader.requestSliceRange(o,wt,Vt);if(s instanceof Promise&&(s=await s),s){let i=Oe(s);if(i&&i.name==="mfra"){let a=this.reader.requestSlice(s.filePos,i.contentSize);a instanceof Promise&&(a=await a),a&&this.readContiguousBoxes(a)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,h(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&Xe.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){h(e.info?.type==="audio");let s=wn(e.info.codec),i=[],a=[];for(let c=0;c<r.sampleToChunk.length;c++){let l=r.sampleToChunk[c],d=r.sampleToChunk[c+1],u=(d?d.startChunkIndex:r.chunkOffsets.length)-l.startChunkIndex;for(let m=0;m<u;m++){let f=l.startSampleIndex+m*l.samplesPerChunk,p=f+l.samplesPerChunk,g=N(r.sampleTimingEntries,f,C=>C.startIndex),x=r.sampleTimingEntries[g],y=N(r.sampleTimingEntries,p,C=>C.startIndex),b=r.sampleTimingEntries[y],w=x.startDecodeTimestamp+(f-x.startIndex)*x.delta,S=b.startDecodeTimestamp+(p-b.startIndex)*b.delta-w,v=re(i);v&&v.delta===S?v.count++:i.push({startIndex:l.startChunkIndex+m,startDecodeTimestamp:w,count:1,delta:S});let A=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;a.push(A)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}r.sampleTimingEntries=i,r.sampleSizes=a}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let s of r.sampleTimingEntries)for(let i=0;i<s.count;i++)r.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+i*s.delta,sampleIndex:s.startIndex+i});for(let s of r.sampleCompositionTimeOffsets)for(let i=0;i<s.count;i++){let a=s.startIndex+i,c=r.presentationTimestamps[a];c&&(c.presentationTimestamp+=s.offset)}r.presentationTimestamps.sort((s,i)=>s.presentationTimestamp-i.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let s=0;s<r.presentationTimestamps.length;s++)r.presentationTimestampIndexMap[r.presentationTimestamps[s].sampleIndex]=s}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,wt,Vt);r instanceof Promise&&(r=await r),h(r);let n=Oe(r);h(n?.name==="moof");let o=this.reader.requestSlice(e,n.totalSize);o instanceof Promise&&(o=await o),h(o),this.traverseBox(o);let s=this.lastReadFragment;h(s&&s.moofOffset===e);for(let[,i]of s.trackData){let a=i.track,{fragmentPositionCache:c}=a;if(!i.startTimestampIsFinal){let d=a.fragmentLookupTable.find(u=>u.moofOffset===s.moofOffset);if(d)Ii(i,d.timestamp);else{let u=N(c,s.moofOffset-1,m=>m.moofOffset);if(u!==-1){let m=c[u];Ii(i,m.endTimestamp)}}i.startTimestampIsFinal=!0}let l=N(c,i.startTimestamp,d=>d.startTimestamp);(l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:i.startTimestamp,endTimestamp:i.endTimestamp})}return s}readContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-wt&&this.traverseBox(e););}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-wt;){let n=e.filePos,o=Oe(e);if(!o)break;yield{boxInfo:o,slice:e},e.filePos=n+o.totalSize}}traverseBox(e){let r=e.filePos,n=Oe(e);if(!n)return!1;let o=e.filePos,s=r+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mvhd":{let i=F(e);e.skip(3),i===1?(e.skip(16),this.movieTimescale=I(e),this.movieDurationInTimescale=ce(e)):(e.skip(8),this.movieTimescale=I(e),this.movieDurationInTimescale=I(e))}break;case"trak":{let i={id:-1,demuxer:this,inputTrack:null,disposition:{...se},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Z,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=i,this.readContiguousBoxes(e.slice(o,n.contentSize)),i.id!==-1&&i.timescale!==-1&&i.info!==null){if(i.info.type==="video"&&i.info.width!==-1){let a=i;i.inputTrack=new Me(this.input,new Ci(a)),this.tracks.push(i)}else if(i.info.type==="audio"&&i.info.numberOfChannels!==-1){let a=i;i.inputTrack=new K(this.input,new Ai(a)),this.tracks.push(i)}}this.currentTrack=null}break;case"tkhd":{let i=this.currentTrack;if(!i)break;let a=F(e),l=!!(Ze(e)&1);if(i.disposition.default=l,a===0)e.skip(8),i.id=I(e),e.skip(4),i.durationInMovieTimescale=I(e);else if(a===1)e.skip(16),i.id=I(e),e.skip(4),i.durationInMovieTimescale=ce(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let d=[Ye(e),Ye(e),_n(e),Ye(e),Ye(e),_n(e),Ye(e),Ye(e),_n(e)],u=ln(vs(dl(d),90));h(u===0||u===90||u===180||u===270),i.rotation=u}break;case"elst":{let i=this.currentTrack;if(!i)break;let a=F(e);e.skip(3);let c=!1,l=0,d=I(e);for(let u=0;u<d;u++){let m=a===1?ce(e):I(e),f=a===1?ea(e):ze(e),p=Ye(e);if(m!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=m;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}i.editListPreviousSegmentDurations=l,i.editListOffset=f,c=!0}}}break;case"mdhd":{let i=this.currentTrack;if(!i)break;let a=F(e);e.skip(3),a===0?(e.skip(8),i.timescale=I(e),i.durationInMediaTimescale=I(e)):a===1&&(e.skip(16),i.timescale=I(e),i.durationInMediaTimescale=ce(e));let c=X(e);if(c>0){i.languageCode="";for(let l=0;l<3;l++)i.languageCode=String.fromCharCode(96+(c&31))+i.languageCode,c>>=5;hn(i.languageCode)||(i.languageCode=Z)}}break;case"hdlr":{let i=this.currentTrack;if(!i)break;e.skip(8);let a=W(e,4);a==="vide"?i.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(i.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(o,n.contentSize))}break;case"stsd":{let i=this.currentTrack;if(!i||i.info===null||i.sampleTable)break;let a=F(e);e.skip(3);let c=I(e);for(let l=0;l<c;l++){let d=e.filePos,u=Oe(e);if(!u)break;i.internalCodecId=u.name;let m=u.name.toLowerCase();if(i.info.type==="video")m==="avc1"||m==="avc3"?(i.info.codec="avc",i.info.avcType=m==="avc1"?1:3):m==="hvc1"||m==="hev1"?i.info.codec="hevc":m==="vp08"?i.info.codec="vp8":m==="vp09"?i.info.codec="vp9":m==="av01"?i.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${u.name}').`),e.skip(24),i.info.width=X(e),i.info.height=X(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos));else{m==="mp4a"||(m==="opus"?i.info.codec="opus":m==="flac"?i.info.codec="flac":m==="twos"||m==="sowt"||m==="raw "||m==="in24"||m==="in32"||m==="fl32"||m==="fl64"||m==="lpcm"||m==="ipcm"||m==="fpcm"||(m==="ulaw"?i.info.codec="ulaw":m==="alaw"?i.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${u.name}').`))),e.skip(8);let f=X(e);e.skip(6);let p=X(e),g=X(e);e.skip(4);let x=I(e)/65536;if(a===0&&f>0){if(f===1)e.skip(4),g=8*I(e),e.skip(8);else if(f===2){e.skip(4),x=Rn(e),p=I(e),e.skip(4),g=I(e);let y=I(e);if(e.skip(8),m==="lpcm"){let b=g+7>>3,w=!!(y&1),T=!!(y&2),S=y&4?-1:0;g>0&&g<=64&&(w?g===32&&(i.info.codec=T?"pcm-f32be":"pcm-f32"):S&1<<b-1?b===1?i.info.codec="pcm-s8":b===2?i.info.codec=T?"pcm-s16be":"pcm-s16":b===3?i.info.codec=T?"pcm-s24be":"pcm-s24":b===4&&(i.info.codec=T?"pcm-s32be":"pcm-s32"):b===1&&(i.info.codec="pcm-u8")),i.info.codec===null&&console.warn("Unsupported PCM format.")}}}i.info.codec==="opus"&&(x=pt),i.info.numberOfChannels=p,i.info.sampleRate=x,m==="twos"?g===8?i.info.codec="pcm-s8":g===16?i.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${g} for codec 'twos'.`),i.info.codec=null):m==="sowt"?g===8?i.info.codec="pcm-s8":g===16?i.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${g} for codec 'sowt'.`),i.info.codec=null):m==="raw "?i.info.codec="pcm-u8":m==="in24"?i.info.codec="pcm-s24be":m==="in32"?i.info.codec="pcm-s32be":m==="fl32"?i.info.codec="pcm-f32be":m==="fl64"?i.info.codec="pcm-f64be":m==="ipcm"?i.info.codec="pcm-s16be":m==="fpcm"&&(i.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos))}}}break;case"avcC":{let i=this.currentTrack;if(!i)break;h(i.info),i.info.codecDescription=D(e,n.contentSize)}break;case"hvcC":{let i=this.currentTrack;if(!i)break;h(i.info),i.info.codecDescription=D(e,n.contentSize)}break;case"vpcC":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="video"),e.skip(4);let a=F(e),c=F(e),l=F(e),d=l>>4,u=l>>1&7,m=l&1,f=F(e),p=F(e),g=F(e);i.info.vp9CodecInfo={profile:a,level:c,bitDepth:d,chromaSubsampling:u,videoFullRangeFlag:m,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="video"),e.skip(1);let a=F(e),c=a>>5,l=a&31,d=F(e),u=d>>7,m=d>>6&1,f=d>>5&1,p=d>>4&1,g=d>>3&1,x=d>>2&1,y=d&3,b=c===2&&m?f?12:10:m?10:8;i.info.av1CodecInfo={profile:c,level:l,tier:u,bitDepth:b,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:x,chromaSamplePosition:y}}break;case"colr":{let i=this.currentTrack;if(!i||(h(i.info?.type==="video"),W(e,4)!=="nclx"))break;let c=X(e),l=X(e),d=X(e),u=!!(F(e)&128);i.info.colorSpace={primaries:un[c],transfer:dn[l],matrix:mn[d],fullRange:u}}break;case"wave":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"esds":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),e.skip(4);let a=F(e);h(a===3),En(e),e.skip(2);let c=F(e),l=(c&128)!==0,d=(c&64)!==0,u=(c&32)!==0;if(l&&e.skip(2),d){let x=F(e);e.skip(x)}u&&e.skip(2);let m=F(e);h(m===4);let f=En(e),p=e.filePos,g=F(e);if(g===64||g===103?(i.info.codec="aac",i.info.aacCodecInfo={isMpeg2:g===103}):g===105||g===107?i.info.codec="mp3":g===221?i.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),f>e.filePos-p){let x=F(e);h(x===5);let y=En(e);if(i.info.codecDescription=D(e,y),i.info.codec==="aac"){let b=hi(i.info.codecDescription);b.numberOfChannels!==null&&(i.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(i.info.sampleRate=b.sampleRate)}}}break;case"enda":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),X(e)&255&&(i.info.codec==="pcm-s16be"?i.info.codec="pcm-s16":i.info.codec==="pcm-s24be"?i.info.codec="pcm-s24":i.info.codec==="pcm-s32be"?i.info.codec="pcm-s32":i.info.codec==="pcm-f32be"?i.info.codec="pcm-f32":i.info.codec==="pcm-f64be"&&(i.info.codec="pcm-f64"))}break;case"pcmC":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),e.skip(4);let c=!!(F(e)&1),l=F(e);i.info.codec==="pcm-s16be"?c?l===16?i.info.codec="pcm-s16":l===24?i.info.codec="pcm-s24":l===32?i.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),i.info.codec=null):l===16?i.info.codec="pcm-s16be":l===24?i.info.codec="pcm-s24be":l===32?i.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),i.info.codec=null):i.info.codec==="pcm-f32be"&&(c?l===32?i.info.codec="pcm-f32":l===64?i.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),i.info.codec=null):l===32?i.info.codec="pcm-f32be":l===64?i.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),i.info.codec=null));break}case"dOps":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),e.skip(1);let a=F(e),c=X(e),l=I(e),d=Er(e),u=F(e),m;u!==0?m=D(e,2+a):m=new Uint8Array(0);let f=new Uint8Array(19+m.byteLength),p=new DataView(f.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,a),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,d,!0),p.setUint8(18,u),f.set(m,19),i.info.codecDescription=f,i.info.numberOfChannels=a}break;case"dfLa":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<s;){let p=F(e),g=Ze(e);if((p&a)===Qe.STREAMINFO){e.skip(10);let y=I(e),b=y>>>12,w=(y>>9&7)+1;i.info.sampleRate=b,i.info.numberOfChannels=w,e.skip(20)}else e.skip(g);if(p&c)break}let d=e.filePos;e.filePos=l;let u=D(e,d-l),m=new Uint8Array(4+u.byteLength);new DataView(m.buffer).setUint32(0,1716281667,!1),m.set(u,4),i.info.codecDescription=m}break;case"stts":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e),c=0,l=0;for(let d=0;d<a;d++){let u=I(e),m=I(e);i.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:u,delta:m}),c+=u,l+=u*m}}break;case"ctts":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e),c=0;for(let l=0;l<a;l++){let d=I(e),u=ze(e);i.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:d,offset:u}),c+=d}}break;case"stsz":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e),c=I(e);if(a===0)for(let l=0;l<c;l++){let d=I(e);i.sampleTable.sampleSizes.push(d)}else i.sampleTable.sampleSizes.push(a)}break;case"stz2":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4),e.skip(3);let a=F(e),c=I(e),l=D(e,Math.ceil(c*a/8)),d=new L(l);for(let u=0;u<c;u++){let m=d.readBits(a);i.sampleTable.sampleSizes.push(m)}}break;case"stss":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4),i.sampleTable.keySampleIndices=[];let a=I(e);for(let c=0;c<a;c++){let l=I(e)-1;i.sampleTable.keySampleIndices.push(l)}i.sampleTable.keySampleIndices[0]!==0&&i.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e);for(let l=0;l<a;l++){let d=I(e)-1,u=I(e),m=I(e);i.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:d,samplesPerChunk:u,sampleDescriptionIndex:m})}let c=0;for(let l=0;l<i.sampleTable.sampleToChunk.length;l++)if(i.sampleTable.sampleToChunk[l].startSampleIndex=c,l<i.sampleTable.sampleToChunk.length-1){let u=i.sampleTable.sampleToChunk[l+1].startChunkIndex-i.sampleTable.sampleToChunk[l].startChunkIndex;c+=u*i.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e);for(let c=0;c<a;c++){let l=I(e);i.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e);for(let c=0;c<a;c++){let l=ce(e);i.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mehd":{let i=F(e);e.skip(3);let a=i===1?ce(e):I(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let i=I(e),a=I(e),c=I(e),l=I(e),d=I(e);this.fragmentTrackDefaults.push({trackId:i,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:d})}break;case"tfra":{let i=F(e);e.skip(3);let a=I(e),c=this.tracks.find(b=>b.id===a);if(!c)break;let l=I(e),d=(l&48)>>4,u=(l&12)>>2,m=l&3,f=[F,X,Ze,I],p=f[d],g=f[u],x=f[m],y=I(e);for(let b=0;b<y;b++){let w=i===1?ce(e):I(e),T=i===1?ce(e):I(e);p(e),g(e),x(e),c.fragmentLookupTable.push({timestamp:w,moofOffset:T})}c.fragmentLookupTable.sort((b,w)=>b.timestamp-w.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){let w=c.fragmentLookupTable[b],T=c.fragmentLookupTable[b+1];w.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:r,moofSize:n.totalSize,implicitBaseDataOffset:r,trackData:new Map},this.readContiguousBoxes(e.slice(o,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(h(this.currentFragment),this.readContiguousBoxes(e.slice(o,n.contentSize)),this.currentTrack){let i=this.currentFragment.trackData.get(this.currentTrack.id);if(i){let{currentFragmentState:a}=this.currentTrack;h(a),a.startTimestamp!==null&&(Ii(i,a.startTimestamp),i.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{h(this.currentFragment),e.skip(1);let i=Ze(e),a=!!(i&1),c=!!(i&2),l=!!(i&8),d=!!(i&16),u=!!(i&32),m=!!(i&65536),f=!!(i&131072),p=I(e),g=this.tracks.find(y=>y.id===p);if(!g)break;let x=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:x?.defaultSampleDescriptionIndex??null,defaultSampleDuration:x?.defaultSampleDuration??null,defaultSampleSize:x?.defaultSampleSize??null,defaultSampleFlags:x?.defaultSampleFlags??null,startTimestamp:null},a?g.currentFragmentState.baseDataOffset=ce(e):f&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(g.currentFragmentState.sampleDescriptionIndex=I(e)),l&&(g.currentFragmentState.defaultSampleDuration=I(e)),d&&(g.currentFragmentState.defaultSampleSize=I(e)),u&&(g.currentFragmentState.defaultSampleFlags=I(e)),m&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let i=this.currentTrack;if(!i)break;h(i.currentFragmentState);let a=F(e);e.skip(3);let c=a===0?I(e):ce(e);i.currentFragmentState.startTimestamp=c}break;case"trun":{let i=this.currentTrack;if(!i)break;if(h(this.currentFragment),h(i.currentFragmentState),this.currentFragment.trackData.has(i.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let a=F(e),c=Ze(e),l=!!(c&1),d=!!(c&4),u=!!(c&256),m=!!(c&512),f=!!(c&1024),p=!!(c&2048),g=I(e),x=i.currentFragmentState.baseDataOffset;l&&(x+=ze(e));let y=null;d&&(y=I(e));let b=x;if(g===0){this.currentFragment.implicitBaseDataOffset=b;break}let w=0,T={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(i.id,T);for(let A=0;A<g;A++){let C;u?C=I(e):(h(i.currentFragmentState.defaultSampleDuration!==null),C=i.currentFragmentState.defaultSampleDuration);let R;m?R=I(e):(h(i.currentFragmentState.defaultSampleSize!==null),R=i.currentFragmentState.defaultSampleSize);let z;f?z=I(e):(h(i.currentFragmentState.defaultSampleFlags!==null),z=i.currentFragmentState.defaultSampleFlags),A===0&&y!==null&&(z=y);let B=0;p&&(a===0?B=I(e):B=ze(e));let Q=!(z&65536);T.samples.push({presentationTimestamp:w+B,duration:C,byteOffset:b,byteSize:R,isKeyFrame:Q}),b+=R,w+=C}T.presentationTimestamps=T.samples.map((A,C)=>({presentationTimestamp:A.presentationTimestamp,sampleIndex:C})).sort((A,C)=>A.presentationTimestamp-C.presentationTimestamp);for(let A=0;A<T.presentationTimestamps.length;A++){let C=T.presentationTimestamps[A],R=T.samples[C.sampleIndex];if(T.firstKeyFrameTimestamp===null&&R.isKeyFrame&&(T.firstKeyFrameTimestamp=R.presentationTimestamp),A<T.presentationTimestamps.length-1){let z=T.presentationTimestamps[A+1];R.duration=z.presentationTimestamp-C.presentationTimestamp}}let S=T.samples[T.presentationTimestamps[0].sampleIndex],v=T.samples[re(T.presentationTimestamps).sampleIndex];T.startTimestamp=S.presentationTimestamp,T.endTimestamp=v.presentationTimestamp+v.duration,this.currentFragment.implicitBaseDataOffset=b}break;case"udta":{let i=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of i){if(a.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},a.name[0]==="\xA9"?this.metadataTags.raw[a.name]??=ge(c):this.metadataTags.raw[a.name]??=D(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=Y.decode(D(c,a.contentSize)):this.metadataTags.title??=ge(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=ge(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=ge(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=ge(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=ge(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=ge(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(ge(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=ge(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=ge(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=I(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(o,n.contentSize)):this.readContiguousBoxes(e.slice(o+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let i=I(e);for(let a=0;a<i;a++){let c=I(e);e.skip(4);let l=Y.decode(D(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let i=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of i){let l=a.name,d=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(d)&&(l=this.currentMetadataKeys.get(d));let u=Zs(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=u,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof u=="string"&&(this.metadataTags.title??=u);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof u=="string"&&(this.metadataTags.description??=u);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof u=="string"&&(this.metadataTags.artist??=u);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof u=="string"&&(this.metadataTags.album??=u);break;case"aART":case"album_artist":typeof u=="string"&&(this.metadataTags.albumArtist??=u);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof u=="string"&&(this.metadataTags.comment??=u);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof u=="string"&&(this.metadataTags.genre??=u);break;case"\xA9lyr":case"lyrics":typeof u=="string"&&(this.metadataTags.lyrics??=u);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof u=="string"){let m=new Date(u);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"covr":case"com.apple.quicktime.artwork":u instanceof Ke?(this.metadataTags.images??=[],this.metadataTags.images.push({data:u.data,kind:"coverFront",mimeType:u.mimeType})):u instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:u,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof u=="string"){let m=u.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(u instanceof Uint8Array&&u.length>=6){let m=V(u),f=m.getUint16(2,!1),p=m.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(u instanceof Uint8Array&&u.length>=6){let m=V(u),f=m.getUint16(2,!1),p=m.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}},Dn=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let r=await this.fetchPacketForSampleIndex(0,e);return r||!this.internalTrack.demuxer.isFragmented?r:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return dt(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,r){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=_i(o,n),i=await this.fetchPacketForSampleIndex(s,r);return!Js(o)||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=N(c.presentationTimestamps,n,m=>m.presentationTimestamp),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},n,n,r)}async getNextPacket(e,r){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,r);let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,s=>{if(s===o.fragment){let i=s.trackData.get(this.internalTrack.id);if(o.sampleIndex+1<i.samples.length)return{sampleIndex:o.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=cl(o,n),i=await this.fetchPacketForSampleIndex(s,r);return!Js(o)||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=pn(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=n),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},n,n,r)}async getNextKeyPacket(e,r){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ul(s,n);return this.fetchPacketForSampleIndex(i,r)}let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,s=>{if(s===o.fragment){let a=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>o.sampleIndex);if(a!==-1)return{sampleIndex:a,correctSampleFound:!0}}else{let i=s.trackData.get(this.internalTrack.id);if(i&&i.firstKeyFrameTimestamp!==null){let a=i.samples.findIndex(c=>c.isKeyFrame);return h(a!==-1),{sampleIndex:a,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=ll(n,e);if(!o)return null;let s;if(r.metadataOnly)s=j;else{let l=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);l instanceof Promise&&(l=await l),h(l),s=D(l,o.sampleSize)}let i=(o.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=o.duration/this.internalTrack.timescale,c=new G(s,o.isKeyFrame?"key":"delta",i,a,e,o.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,r,n){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[r];h(s);let i;if(n.metadataOnly)i=j;else{let d=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);d instanceof Promise&&(d=await d),h(d),i=D(d,s.byteSize)}let a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new G(i,s.isKeyFrame?"key":"delta",a,c,e.moofOffset+r,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:r}),l}async performFragmentedLookup(e,r,n,o,s){let i=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:x,correctSampleFound:y}=r(e);if(y)return this.fetchPacketInFragment(e,x,s);x!==-1&&(c=e,l=x)}let d=N(this.internalTrack.fragmentLookupTable,n,x=>x.timestamp),u=d!==-1?this.internalTrack.fragmentLookupTable[d]:null,m=N(this.internalTrack.fragmentPositionCache,n,x=>x.startTimestamp),f=m!==-1?this.internalTrack.fragmentPositionCache[m]:null,p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,a=e):g=p:g=p??0;;){if(a){let w=a.trackData.get(this.internalTrack.id);if(w&&w.startTimestamp>o)break}let x=i.reader.requestSliceRange(g,wt,Vt);if(x instanceof Promise&&(x=await x),!x)break;let y=g,b=Oe(x);if(!b)break;if(b.name==="moof"){a=await i.readFragment(y);let{sampleIndex:w,correctSampleFound:T}=r(a);if(T)return this.fetchPacketInFragment(a,w,s);w!==-1&&(c=a,l=w)}g=y+b.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){let x=this.internalTrack.fragmentLookupTable[d-1];h(!x||x.timestamp<u.timestamp);let y=x?.timestamp??-1/0;return this.performFragmentedLookup(null,r,y,o,s)}return c?this.fetchPacketInFragment(c,l,s):null}},Ci=class extends Dn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Sn(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Pn(e.data)}return{codec:yn(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}},Ai=class extends Dn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Tn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},_i=(t,e)=>{if(t.presentationTimestamps){let r=N(t.presentationTimestamps,e,n=>n.presentationTimestamp);return r===-1?-1:t.presentationTimestamps[r].sampleIndex}else{let r=N(t.sampleTimingEntries,e,o=>o.startDecodeTimestamp);if(r===-1)return-1;let n=t.sampleTimingEntries[r];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},cl=(t,e)=>{if(!t.keySampleIndices)return _i(t,e);if(t.presentationTimestamps){let r=N(t.presentationTimestamps,e,n=>n.presentationTimestamp);if(r===-1)return-1;for(let n=r;n>=0;n--){let o=t.presentationTimestamps[n].sampleIndex;if(ct(t.keySampleIndices,o,i=>i)!==-1)return o}return-1}else{let r=_i(t,e),n=N(t.keySampleIndices,r,o=>o);return t.keySampleIndices[n]??-1}},ll=(t,e)=>{let r=N(t.sampleTimingEntries,e,y=>y.startIndex),n=t.sampleTimingEntries[r];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,i=N(t.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=t.sampleCompositionTimeOffsets[i];a&&e-a.startIndex<a.count&&(s+=a.offset);let c=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],l=N(t.sampleToChunk,e,y=>y.startSampleIndex),d=t.sampleToChunk[l];h(d);let u=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),m=t.chunkOffsets[u],f=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk,p=0,g=m;if(t.sampleSizes.length===1)g+=c*(e-f),p+=c*d.samplesPerChunk;else for(let y=f;y<f+d.samplesPerChunk;y++){let b=t.sampleSizes[y];y<e&&(g+=b),p+=b}let x=n.delta;if(t.presentationTimestamps){let y=t.presentationTimestampIndexMap[e];h(y!==void 0),y<t.presentationTimestamps.length-1&&(x=t.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:x,sampleOffset:g,sampleSize:c,chunkOffset:m,chunkSize:p,isKeyFrame:t.keySampleIndices?ct(t.keySampleIndices,e,y=>y)!==-1:!0}},ul=(t,e)=>{if(!t.keySampleIndices)return e+1;let r=N(t.keySampleIndices,e,n=>n);return t.keySampleIndices[r+1]??-1},Ii=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(let r of t.samples)r.presentationTimestamp+=e;for(let r of t.presentationTimestamps)r.presentationTimestamp+=e},dl=t=>{let[e,,,r]=t,n=Math.hypot(e,r),o=e/n,s=r/n,i=-Math.atan2(s,o)*(180/Math.PI);return Number.isFinite(i)?i:0},Js=t=>t.sampleSizes.length===0;var k;(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(k||(k={}));var ml=[k.EBML,k.Segment],Lt=[k.SeekHead,k.Info,k.Cluster,k.Tracks,k.Cues,k.Attachments,k.Chapters,k.Tags],Fr=[...ml,...Lt];var Ei=8,le=2,xe=2*Ei,Fi=t=>{let e=F(t);if(t.skip(-1),e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;return r},Ht=t=>{let e=F(t);if(e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;let o=e&n-1;for(let s=1;s<r;s++)o*=256,o+=F(t);return o},M=(t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let r=0;for(let n=0;n<e;n++)r*=256,r+=F(t);return r},ta=(t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let r=0n;for(let n=0;n<e;n++)r<<=8n,r+=BigInt(F(t));return r};var Bn=t=>{let e=Fi(t);return e===null?null:M(t,e)},Di=t=>{let e=F(t);return e===255?e=null:(t.skip(-1),e=Ht(t),e===72057594037927940&&(e=null)),e},be=t=>{let e=Bn(t);if(e===null)return null;let r=Di(t);return{id:e,size:r}},Je=(t,e)=>{let r=D(t,e),n=0;for(;n<e&&r[n]!==0;)n+=1;return String.fromCharCode(...r.subarray(0,n))},Gt=(t,e)=>{let r=D(t,e),n=0;for(;n<e&&r[n]!==0;)n+=1;return Y.decode(r.subarray(0,n))},Mn=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?ra(t):Rn(t)},On=async(t,e,r,n)=>{let o=new Set(r),s=e;for(;n===null||s<n;){let i=t.requestSliceRange(s,le,xe);if(i instanceof Promise&&(i=await i),!i)break;let a=be(i);if(!a)break;if(o.has(a.id))return{pos:s,found:!0};Ue(a.size),s=i.filePos+a.size}return{pos:n!==null&&n>s?n:s,found:!1}},Ri=async(t,e,r,n)=>{let s=new Set(r),i=e;for(;i<n;){let a=t.requestSliceRange(i,0,Math.min(65536,n-i));if(a instanceof Promise&&(a=await a),!a||a.length<Ei)break;for(let c=0;c<a.length-Ei;c++){a.filePos=i;let l=Bn(a);if(l!==null&&s.has(l))return i;i++}}return null},ye={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 Ue(t){if(t===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var na=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){let n=[...new Set(t.codecStrings.filter(Boolean))];r+=`; codecs="${n.join(", ")}"`}return r};var Ne;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(Ne||(Ne={}));var zn;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(zn||(zn={}));var Dr;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Dr||(Dr={}));var Bi=[{id:k.SeekHead,flag:"seekHeadSeen"},{id:k.Info,flag:"infoSeen"},{id:k.Tracks,flag:"tracksSeen"},{id:k.Cues,flag:"cuesSeen"}],oa=10*2**20,Un=class extends te{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.getCodecParameterString()));return na({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,le,xe);if(r instanceof Promise&&(r=await r),!r)break;let n=be(r);if(!n)break;let o=n.id,s=n.size,i=r.filePos;if(o===k.EBML){Ue(s);let a=this.reader.requestSlice(i,s);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(o===k.Segment){if(await this.readSegment(i,s),s===null||this.reader.fileSize===null)break}else if(o===k.Cluster){if(this.reader.fileSize===null)break;s===null&&(s=(await On(this.reader,i,Fr,this.reader.fileSize)).pos-i);let a=re(this.segments);a&&(a.elementEndPos=i+s)}Ue(s),e=i+s}})()}async readSegment(e,r){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:r===null?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(n,le,xe);if(a instanceof Promise&&(a=await a),!a)break;let c=n,l=be(a);if(!l||!Lt.includes(l.id)&&l.id!==k.Void){let p=await Ri(this.reader,c,Lt,Math.min(this.currentSegment.elementEndPos??1/0,c+oa));if(p){n=p;continue}else break}let{id:d,size:u}=l,m=a.filePos,f=Bi.findIndex(p=>p.id===d);if(f!==-1){let p=Bi[f].flag;this.currentSegment[p]=!0,Ue(u);let g=this.reader.requestSlice(m,u);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(d===k.Tags||d===k.Attachments){d===k.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ue(u);let p=this.reader.requestSlice(m,u);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(d===k.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(u===null)break;n=m+u}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=Bi.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,le,xe);if(l instanceof Promise&&(l=await l),!l)continue;let d=be(l);if(!d)continue;let{id:u,size:m}=d;if(u!==c.id)continue;Ue(m),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,m);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((a,c)=>Number(c.disposition.default)-Number(a.disposition.default));let o=new Map(this.currentSegment.tracks.map(a=>[a.id,a]));for(let a of this.currentSegment.cuePoints){let c=o.get(a.trackId);c&&c.cuePoints.push(a)}for(let a of this.currentSegment.tracks){a.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<a.cuePoints.length-1;c++){let l=a.cuePoints[c],d=a.cuePoints[c+1];l.time===d.time&&(a.cuePoints.splice(c+1,1),c--)}}let s=null,i=-1/0;for(let a of this.currentSegment.tracks)a.cuePoints.length>i&&(i=a.cuePoints.length,s=a);for(let a of this.currentSegment.tracks)a.cuePoints.length===0&&(a.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let n=this.reader.requestSliceRange(e,le,xe);n instanceof Promise&&(n=await n),h(n);let o=e,s=be(n);h(s);let i=s.id;h(i===k.Cluster);let a=s.size,c=n.filePos;a===null&&(a=(await On(this.reader,c,Fr,r.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let d={segment:r,elementStartPos:o,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=d,l){let u=this.readContiguousElements(l,Fr);d.elementEndPos=u}for(let[,u]of d.trackData){let m=u.track;h(u.blocks.length>0);let f=!1;for(let y=0;y<u.blocks.length;y++){let b=u.blocks[y];b.timestamp+=d.timestamp,f||=b.lacing!==Ne.None}u.presentationTimestamps=u.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<u.presentationTimestamps.length;y++){let b=u.presentationTimestamps[y],w=u.blocks[b.blockIndex];if(u.firstKeyFrameTimestamp===null&&w.isKeyFrame&&(u.firstKeyFrameTimestamp=w.timestamp),y<u.presentationTimestamps.length-1){let T=u.presentationTimestamps[y+1];w.duration=T.timestamp-w.timestamp}else w.duration===0&&m.defaultDuration!=null&&w.lacing===Ne.None&&(w.duration=m.defaultDuration)}f&&(this.expandLacedBlocks(u.blocks,m),u.presentationTimestamps=u.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));let p=u.blocks[u.presentationTimestamps[0].blockIndex],g=u.blocks[re(u.presentationTimestamps).blockIndex];u.startTimestamp=p.timestamp,u.endTimestamp=g.timestamp+g.duration;let x=N(m.clusterPositionCache,u.startTimestamp,y=>y.startTimestamp);(x===-1||m.clusterPositionCache[x].elementStartPos!==o)&&m.clusterPositionCache.splice(x+1,0,{elementStartPos:d.elementStartPos,startTimestamp:u.startTimestamp})}return r.lastReadCluster=d,d}getTrackDataInCluster(e,r){let n=e.trackData.get(r);if(!n){let o=e.segment.tracks.find(s=>s.id===r);if(!o)return null;n={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,n)}return n}expandLacedBlocks(e,r){for(let n=0;n<e.length;n++){let o=e[n];if(o.lacing===Ne.None)continue;o.decoded||(o.data=this.decodeBlockData(r,o.data),o.decoded=!0);let s=qt.tempFromBytes(o.data),i=[],a=F(s)+1;switch(o.lacing){case Ne.Xiph:{let l=0;for(let d=0;d<a-1;d++){let u=0;for(;s.bufferPos<s.length;){let m=F(s);if(u+=m,m<255){i.push(u),l+=u;break}}}i.push(s.length-(s.bufferPos+l))}break;case Ne.FixedSize:{let l=s.length-1,d=Math.floor(l/a);for(let u=0;u<a;u++)i.push(d)}break;case Ne.Ebml:{let l=Ht(s);h(l!==null);let d=l;i.push(d);let u=d;for(let m=1;m<a-1;m++){let f=s.bufferPos,p=Ht(s);h(p!==null);let g=p,y=(1<<(s.bufferPos-f)*7-1)-1,b=g-y;d+=b,i.push(d),u+=d}i.push(s.length-(s.bufferPos+u))}break;default:h(!1)}h(i.length===a),e.splice(n,1);let c=o.duration||a*(r.defaultDuration??0);for(let l=0;l<a;l++){let d=i[l],u=D(s,d),m=o.timestamp+c*l/a,f=c/a;e.splice(n+l,0,{timestamp:m,duration:f,isKeyFrame:o.isKeyFrame,data:u,lacing:Ne.None,decoded:!0,mainAdditional:o.mainAdditional})}n+=a,n--}}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===k.Tags&&!e.tagsSeen)){if(!(r.id===k.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,le,xe);if(n instanceof Promise&&(n=await n),!n)continue;let o=be(n);if(!o||o.id!==r.id)continue;let{size:s}=o;Ue(s),h(!this.currentSegment),this.currentSegment=e;let i=this.reader.requestSlice(n.filePos,s);i instanceof Promise&&(i=await i),i&&this.readContiguousElements(i),this.currentSegment=null,r.id===k.Tags?e.tagsSeen=!0:r.id===k.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,r){let n=e.filePos;for(;e.filePos-n<=e.length-le;){let o=e.filePos;if(!this.traverseElement(e,r))return o}return e.filePos}traverseElement(e,r){let n=be(e);if(!n||r&&r.includes(n.id))return!1;let{id:o,size:s}=n,i=e.filePos;switch(Ue(s),o){case k.DocType:this.isWebM=Je(e,s)==="webm";break;case k.Seek:{if(!this.currentSegment)break;let a={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(a),this.readContiguousElements(e.slice(i,s)),(a.id===-1||a.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case k.SeekID:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.id=M(e,s)}break;case k.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=M(e,s)}break;case k.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=M(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case k.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Mn(e,s)}break;case k.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...se},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Z,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(i,s)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==zn.Block||a.data.algorithm!==Dr.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let a=this.currentTrack.codecId.indexOf("/"),c=a===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,a);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===ye.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ye.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.vp8?this.currentTrack.info.codec="vp8":c===ye.vp9?this.currentTrack.info.codec="vp9":c===ye.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,d=new Me(this.input,new Mi(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===ye.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===ye.mp3?this.currentTrack.info.codec="mp3":c===ye.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=pt):c===ye.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack,d=new K(this.input,new Oi(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case k.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=M(e,s)}break;case k.TrackType:{if(!this.currentTrack)break;let a=M(e,s);a===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:a===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case k.FlagEnabled:{if(!this.currentTrack)break;M(e,s)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case k.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!M(e,s)}break;case k.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!M(e,s)}break;case k.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!M(e,s)}break;case k.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!M(e,s)}break;case k.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!M(e,s)}break;case k.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!M(e,s)}break;case k.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Je(e,s)}break;case k.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=D(e,s)}break;case k.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*M(e,s)/1e9}break;case k.Name:{if(!this.currentTrack)break;this.currentTrack.name=Gt(e,s)}break;case k.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==Z)break;this.currentTrack.languageCode=Je(e,s),hn(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Z)}break;case k.LanguageBCP47:{if(!this.currentTrack)break;let c=Je(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Z}break;case k.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(i,s))}break;case k.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=M(e,s)}break;case k.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=M(e,s)}break;case k.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=M(e,s)===1}break;case k.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(i,s))}break;case k.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,s),c=mn[a]??null;this.currentTrack.info.colorSpace.matrix=c}break;case k.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=M(e,s)===2}break;case k.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,s),c=dn[a]??null;this.currentTrack.info.colorSpace.transfer=c}break;case k.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,s),c=un[a]??null;this.currentTrack.info.colorSpace.primaries=c}break;case k.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(i,s))}break;case k.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-Mn(e,s);try{this.currentTrack.info.rotation=ln(c)}catch{}}break;case k.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(i,s))}break;case k.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Mn(e,s)}break;case k.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=M(e,s)}break;case k.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=M(e,s)}break;case k.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(i,s)),this.currentCueTime=null}break;case k.CueTime:this.currentCueTime=M(e,s);break;case k.CueTrackPositions:{if(this.currentCueTime===null)break;h(this.currentSegment);let a={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(a),this.readContiguousElements(e.slice(i,s)),(a.trackId===-1||a.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case k.CueTrack:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;a.trackId=M(e,s)}break;case k.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;h(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+M(e,s)}break;case k.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=M(e,s)}break;case k.SimpleBlock:{if(!this.currentCluster)break;let a=Ht(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Er(e),d=F(e),u=d>>1&3,m=!!(d&128);c.track.info?.type==="audio"&&c.track.info.codec&&(m=!0);let f=D(e,s-(e.filePos-i)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:m,data:f,lacing:u,decoded:!p,mainAdditional:null})}break;case k.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(i,s)),this.currentBlock=null}break;case k.Block:{if(!this.currentCluster)break;let a=Ht(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Er(e),u=F(e)>>1&3,m=D(e,s-(e.filePos-i)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:m,lacing:u,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case k.BlockAdditions:this.readContiguousElements(e.slice(i,s));break;case k.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(i,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case k.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=D(e,s)}break;case k.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=M(e,s)}break;case k.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=M(e,s)}break;case k.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case k.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(i,s));break;case k.Targets:this.readContiguousElements(e.slice(i,s));break;case k.TargetTypeValue:M(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case k.TagTrackUID:case k.TagEditionUID:case k.TagChapterUID:case k.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case k.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(i,s))}break;case k.TagName:this.currentSimpleTagName=Gt(e,s);break;case k.TagString:{if(!this.currentSimpleTagName)break;let a=Gt(e,s);this.processTagValue(this.currentSimpleTagName,a)}break;case k.TagBinary:{if(!this.currentSimpleTagName)break;let a=D(e,s);this.processTagValue(this.currentSimpleTagName,a)}break;case k.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(i,s));let a=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(a.raw??={},a.raw[this.currentAttachedFile.fileUid.toString()]=new bn(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let d=c.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}a.images??=[],a.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case k.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=ta(e,s)}break;case k.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Gt(e,s)}break;case k.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Je(e,s)}break;case k.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=D(e,s)}break;case k.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Gt(e,s)}break;case k.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(i,s)),this.currentTrack.decodingInstructions.sort((a,c)=>c.order-a.order)}break;case k.ContentEncoding:this.currentDecodingInstruction={order:0,scope:zn.Block,data:null},this.readContiguousElements(e.slice(i,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case k.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=M(e,s)}break;case k.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=M(e,s)}break;case k.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Dr.Zlib,settings:null},this.readContiguousElements(e.slice(i,s))}break;case k.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=M(e,s)}break;case k.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=D(e,s)}break;case k.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=i+s,!0}decodeBlockData(e,r){h(e.decodingInstructions.length>0);let n=r;for(let o of e.decodingInstructions)switch(h(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case Dr.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){let s=o.data.settings,i=new Uint8Array(s.length+n.length);i.set(s,0),i.set(n,s.length),n=i}break;default:}break;default:}return n}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":n.title??=r;break;case"description":n.description??=r;break;case"artist":n.artist??=r;break;case"album":n.album??=r;break;case"album_artist":n.albumArtist??=r;break;case"genre":n.genre??=r;break;case"comment":n.comment??=r;break;case"lyrics":n.lyrics??=r;break;case"date":{let o=new Date(r);Number.isNaN(o.getTime())||(n.date??=o)}break;case"track_number":case"part_number":{let o=r.split("/"),s=Number.parseInt(o[0],10),i=o[1]&&Number.parseInt(o[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case"disc_number":case"disc":{let o=r.split("/"),s=Number.parseInt(o[0],10),i=o[1]&&Number.parseInt(o[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break}}},Nn=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,r=>r.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return dt(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,r){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let s=o.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let i=N(s.presentationTimestamps,n,l=>l.timestamp),a=i!==-1?s.presentationTimestamps[i].blockIndex:-1,c=i!==-1&&n<s.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,r)}async getNextPacket(e,r){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let s=o.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(o.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let s=o.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let i=pn(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),a=i!==-1?s.presentationTimestamps[i].blockIndex:-1,c=i!==-1&&n<s.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,r)}async getNextKeyPacket(e,r){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let i=o.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>n.blockIndex);if(i!==-1)return{blockIndex:i,correctBlockFound:!0}}else{let s=o.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let i=s.blocks.findIndex(a=>a.isKeyFrame);return h(i!==-1),{blockIndex:i,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,n){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[r];h(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let i=n.metadataOnly?j:s.data,a=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,l={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?j:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);let d=new G(i,s.isKeyFrame?"key":"delta",a,c,e.dataStartPos+r,s.data.byteLength,l);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:r}),d}async performClusterLookup(e,r,n,o,s){let{demuxer:i,segment:a}=this.internalTrack,c=null,l=null,d=-1;if(e){let{blockIndex:y,correctBlockFound:b}=r(e);if(b)return this.fetchPacketInCluster(e,y,s);y!==-1&&(l=e,d=y)}let u=N(this.internalTrack.cuePoints,n,y=>y.time),m=u!==-1?this.internalTrack.cuePoints[u]:null,f=N(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,g=Math.max(m?.clusterPosition??0,p?.elementStartPos??0)||null,x;for(e?g===null||e.elementStartPos>=g?(x=e.elementEndPos,c=e):x=g:x=g??a.clusterSeekStartPos;a.elementEndPos===null||x<=a.elementEndPos-le;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>o)break}let y=i.reader.requestSliceRange(x,le,xe);if(y instanceof Promise&&(y=await y),!y)break;let b=x,w=be(y);if(!w||!Lt.includes(w.id)&&w.id!==k.Void){let C=await Ri(i.reader,b,Lt,Math.min(a.elementEndPos??1/0,b+oa));if(C){x=C;continue}else break}let T=w.id,S=w.size,v=y.filePos;if(T===k.Cluster){c=await i.readCluster(b,a),S=c.elementEndPos-v;let{blockIndex:C,correctBlockFound:R}=r(c);if(R)return this.fetchPacketInCluster(c,C,s);C!==-1&&(l=c,d=C)}S===null&&(h(T!==k.Cluster),S=(await On(i.reader,v,Fr,a.elementEndPos)).pos-v);let A=v+S;if(a.elementEndPos===null){let C=i.reader.requestSliceRange(A,le,xe);if(C instanceof Promise&&(C=await C),!C)break;if(Bn(C)===k.Segment){a.elementEndPos=A;break}}x=A}if(m&&(!l||l.elementStartPos<m.clusterPosition)){let y=this.internalTrack.cuePoints[u-1];h(!y||y.time<m.time);let b=y?.time??-1/0;return this.performClusterLookup(null,r,b,o,s)}return l?this.fetchPacketInCluster(l,d,s):null}},Mi=class extends Nn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:yn({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Rs(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Ms(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Sn(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Pn(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}},Oi=class extends Nn{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:Tn({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};var fl=[44100,48e3,32e3],pl=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],ia=1483304551,sa=1231971951,hl=(t,e,r,n,o)=>e===0?0:e===1?Math.floor(144*r/(n<<t))+o:e===2?Math.floor(144*r/n)+o:(Math.floor(12*r/n)+o)*4,aa=(t,e)=>t===3?e===3?21:36:e===3?13:21,ca=(t,e)=>{let r=t>>>24,n=t>>>16&255,o=t>>>8&255,s=t&255;if(r!==255&&n!==255&&o!==255&&s!==255)return{header:null,bytesAdvanced:4};if(r!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let i=0,a=0;n&16?i=n&8?0:1:(i=1,a=1);let c=n>>3&3,l=n>>1&3,d=o>>4&15,u=(o>>2&3)%3,m=o>>1&1,f=s>>6&3,p=s>>4&3,g=s>>3&1,x=s>>2&1,y=s&3,b=pl[i*16*4+l*16+d];if(b===-1)return{header:null,bytesAdvanced:1};let w=b*1e3,T=fl[u]>>i+a,S=hl(i,l,w,T,m);if(e!==null&&e<S)return{header:null,bytesAdvanced:1};let v;return c===3?v=l===3?384:1152:l===3?v=384:l===2?v=1152:v=576,{header:{totalSize:S,mpegVersionId:c,layer:l,bitrate:w,frequencyIndex:u,sampleRate:T,channel:f,modeExtension:p,copyright:g,original:x,emphasis:y,audioSamplesInFrame:v},bytesAdvanced:1}};var Vn=t=>{let e=2130706432,r=0;for(;e!==0;)r>>=1,r|=t&e,e>>=8;return r};var jt;(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(jt||(jt={}));var $t;(function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"})($t||($t={}));var Rr=128,Xt=10,Kt=["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"],la=(t,e)=>{let r=t.filePos;e.raw??={},e.raw.TAG??=D(t,Rr-3),t.filePos=r;let n=Wt(t,30);n&&(e.title??=n);let o=Wt(t,30);o&&(e.artist??=o);let s=Wt(t,30);s&&(e.album??=s);let i=Wt(t,4),a=Number.parseInt(i,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=D(t,30),l;if(c[28]===0&&c[29]!==0){let u=c[29];u>0&&(e.trackNumber??=u),t.skip(-30),l=Wt(t,28),t.skip(2)}else t.skip(-30),l=Wt(t,30);l&&(e.comment??=l);let d=F(t);d<Kt.length&&(e.genre??=Kt[d])},Wt=(t,e)=>{let r=D(t,e),n=mt(r.indexOf(0),r.length),o=r.subarray(0,n),s="";for(let i=0;i<o.length;i++)s+=String.fromCharCode(o[i]);return s.trimEnd()},kt=t=>{let e=t.filePos,r=W(t,3),n=F(t),o=F(t),s=F(t),i=I(t);if(r!=="ID3"||n===255||o===255||(i&2155905152)!==0)return t.filePos=e,null;let a=Vn(i);return{majorVersion:n,revision:o,flags:s,size:a}},Ln=(t,e,r)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=D(t,e.size),o=new zi(e,n);if(e.flags&jt.Footer&&o.removeFooter(),e.flags&jt.Unsynchronisation&&e.majorVersion===3&&o.ununsynchronizeAll(),e.flags&jt.ExtendedHeader){let s=o.readU32();e.majorVersion===3?o.pos+=s:o.pos+=s-4}for(;o.pos<=o.bytes.length-o.frameHeaderSize();){let s=o.readId3V2Frame();if(!s)break;let i=o.pos,a=o.pos+s.size,c=!1,l=!1,d=!1;if(e.majorVersion===3?(c=!!(s.flags&64),l=!!(s.flags&128)):e.majorVersion===4&&(c=!!(s.flags&4),l=!!(s.flags&8),d=!!(s.flags&2)||!!(e.flags&jt.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${s.id}`),o.pos=a;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${s.id}`),o.pos=a;continue}switch(d&&o.ununsynchronizeRegion(o.pos,a),r.raw??={},s.id[0]==="T"?r.raw[s.id]??=o.readId3V2EncodingAndText(a):r.raw[s.id]??=o.readBytes(s.size),o.pos=i,s.id){case"TIT2":case"TT2":r.title??=o.readId3V2EncodingAndText(a);break;case"TIT3":case"TT3":r.description??=o.readId3V2EncodingAndText(a);break;case"TPE1":case"TP1":r.artist??=o.readId3V2EncodingAndText(a);break;case"TALB":case"TAL":r.album??=o.readId3V2EncodingAndText(a);break;case"TPE2":case"TP2":r.albumArtist??=o.readId3V2EncodingAndText(a);break;case"TRCK":case"TRK":{let m=o.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(r.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(r.tracksTotal??=p)}break;case"TPOS":case"TPA":{let m=o.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(r.discNumber??=f),p&&Number.isInteger(p)&&p>0&&(r.discsTotal??=p)}break;case"TCON":case"TCO":{let u=o.readId3V2EncodingAndText(a),m=/^\((\d+)\)/.exec(u);if(m){let f=Number.parseInt(m[1]);if(Kt[f]!==void 0){r.genre??=Kt[f];break}}if(m=/^\d+$/.exec(u),m){let f=Number.parseInt(m[0]);if(Kt[f]!==void 0){r.genre??=Kt[f];break}}r.genre??=u}break;case"TDRC":case"TDAT":{let u=o.readId3V2EncodingAndText(a),m=new Date(u);Number.isNaN(m.getTime())||(r.date??=m)}break;case"TYER":case"TYE":{let u=o.readId3V2EncodingAndText(a),m=Number.parseInt(u,10);Number.isInteger(m)&&(r.date??=new Date(m,0,1))}break;case"USLT":case"ULT":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),r.lyrics??=o.readId3V2Text(u,a)}break;case"COMM":case"COM":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),r.comment??=o.readId3V2Text(u,a)}break;case"APIC":case"PIC":{let u=o.readId3V2TextEncoding(),m;if(e.majorVersion===2){let x=o.readAscii(3);m=x==="PNG"?"image/png":x==="JPG"?"image/jpeg":"image/*"}else m=o.readId3V2Text(u,a);let f=o.readU8(),p=o.readId3V2Text(u,a).trimEnd(),g=a-o.pos;if(g>=0){let x=o.readBytes(g);r.images||(r.images=[]),r.images.push({data:x,mimeType:m,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:p})}}break;default:o.pos+=s.size;break}o.pos=a}},zi=class{constructor(e,r){this.header=e,this.bytes=r,this.pos=0,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let r=0;r<this.bytes.length;r++){let n=this.bytes[r];e.push(n),n===255&&r!==this.bytes.length-1&&this.bytes[r]===0&&r++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,r){let n=[];for(let i=e;i<r;i++){let a=this.bytes[i];n.push(a),a===255&&i!==r-1&&this.bytes[i+1]===0&&i++}let o=this.bytes.subarray(0,e),s=this.bytes.subarray(r);this.bytes=new Uint8Array(o.length+n.length+s.length),this.bytes.set(o,0),this.bytes.set(n,o.length),this.bytes.set(s,o.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-Xt),this.view=new DataView(this.bytes.buffer)}readBytes(e){let r=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,r}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),r=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+r}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,r}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let r=this.readU24();return{id:e,size:r,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let r=this.readU32(),n=this.header.majorVersion===4?Vn(r):r,o=this.readU16(),s=this.pos,i=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(!i(n)){let a=this.header.majorVersion===4?r:Vn(r);i(a)&&(n=a)}return this.pos=s,{id:e,size:n,flags:o}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,r){let n=this.pos,o=this.readBytes(r-this.pos);switch(e){case $t.ISO_8859_1:{let s="";for(let i=0;i<o.length;i++){let a=o[i];if(a===0){this.pos=n+i+1;break}s+=String.fromCharCode(a)}return s}case $t.UTF_16_WITH_BOM:if(o[0]===255&&o[1]===254){let s=new TextDecoder("utf-16le"),i=mt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(i+2,o.length),s.decode(o.subarray(2,i))}else if(o[0]===254&&o[1]===255){let s=new TextDecoder("utf-16be"),i=mt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(i+2,o.length),s.decode(o.subarray(2,i))}else{let s=mt(o.findIndex(i=>i===0),o.length);return this.pos=n+Math.min(s+1,o.length),Y.decode(o.subarray(0,s))}case $t.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),i=mt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(i+2,o.length),s.decode(o.subarray(0,i))}case $t.UTF_8:{let s=mt(o.findIndex(i=>i===0),o.length);return this.pos=n+Math.min(s+1,o.length),Y.decode(o.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let r=this.readId3V2TextEncoding();return this.readId3V2Text(r,e)}};var Br=async(t,e,r)=>{let n=e;for(;r===null||n<r;){let o=t.requestSlice(n,4);if(o instanceof Promise&&(o=await o),!o)break;let s=I(o),i=ca(s,t.fileSize!==null?t.fileSize-n:null);if(i.header)return{header:i.header,startPos:n};n+=i.bytesAdvanced}return null};var Hn=class extends te{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Ie,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 K(this.input,new Ui(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Xt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=kt(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await Br(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=aa(r.mpegVersionId,r.channel),o=this.reader.requestSlice(e.startPos+n,4);if(o instanceof Promise&&(o=await o),o){let a=I(o);if(a===ia||a===sa)return}this.firstFrameHeader||(this.firstFrameHeader=r),r.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${r.sampleRate} Hz. Might be a bug, so please report this file.`);let s=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,i={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(i),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,n=!1;for(;;){let o=this.reader.requestSlice(r,Xt);if(o instanceof Promise&&(o=await o),!o)break;let s=kt(o);if(!s)break;n=!0;let i=this.reader.requestSlice(o.filePos,s.size);if(i instanceof Promise&&(i=await i),!i)break;Ln(i,s,this.metadataTags),r=o.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=Rr){let o=this.reader.requestSlice(this.reader.fileSize-Rr,Rr);o instanceof Promise&&(o=await o),h(o),W(o,3)==="TAG"&&la(o,this.metadataTags)}return this.metadataTags}finally{e()}}},Ui=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Z}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...se}}async getDecoderConfig(){return h(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,r){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(r.metadataOnly)o=j;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;o=D(s,n.dataSize)}return new G(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let o=ct(this.demuxer.loadedSamples,e.timestamp,i=>i.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let s=o+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{n()}}async getPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=N(this.demuxer.loadedSamples,e,s=>s.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,r);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,r);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var Ni=1399285583,gl=79764919,da=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let r=0;r<8;r++)e=e&2147483648?e<<1^gl:e<<1;da[t]=e>>>0&4294967295}var ma=t=>{let e=V(t),r=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let o=0;o<t.length;o++){let s=t[o];n=(n<<8^da[n>>>24^s])>>>0}return e.setUint32(22,r,!0),n},fa=(t,e,r)=>{let n=0,o=null;if(t.length>0)if(e.codec==="vorbis"){h(e.vorbisInfo);let s=e.vorbisInfo.modeBlockflags.length,a=(1<<Ss(s-1))-1<<1,c=(t[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=r,d=e.vorbisInfo.modeBlockflags[c];if(o=e.vorbisInfo.blocksizes[d],d===1){let u=(a|1)+1,m=t[0]&u?1:0;l=e.vorbisInfo.blocksizes[m]}n=l!==null?l+o>>2:0}else e.codec==="opus"&&(n=Us(t).durationInSamples);return{durationInSamples:n,vorbisBlockSize:o}},pa=t=>{let e="audio/ogg";if(t.codecStrings){let r=[...new Set(t.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e};var et=27,St=282,ha=St+65025,Qt=t=>{let e=t.filePos;if(vt(t)!==Ni)return null;t.skip(1);let n=F(t),o=xa(t),s=vt(t),i=vt(t),a=vt(t),c=F(t),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=F(t);let d=27+c,u=l.reduce((f,p)=>f+p,0),m=d+u;return{headerStartPos:e,totalSize:m,dataStartPos:e+d,dataSize:u,headerType:n,granulePosition:o,serialNumber:s,sequenceNumber:i,checksum:a,lacingValues:l}},ga=(t,e)=>{for(;t.filePos<e-3;){let r=vt(t),n=r&255,o=r>>>8&255,s=r>>>16&255,i=r>>>24&255,a=79;if(!(n!==a&&o!==a&&s!==a&&i!==a)){if(t.skip(-4),r===Ni)return!0;t.skip(1)}}return!1};var Gn=class extends te{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 r=this.reader.requestSliceRange(e,et,St);if(r instanceof Promise&&(r=await r),!r)break;let n=Qt(r);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let r of this.bitstreams){let n=await this.readPacket(r.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,r):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,r),r.codecInfo.codec!==null&&this.tracks.push(new K(this.input,new Vi(r,this))))}})()}async readVorbisMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o||(n=await this.findNextPacketStart(o),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||o.data[0]!==3||s.data[0]!==5)return;let i=[],a=u=>{for(;i.push(Math.min(255,u)),!(u<255);)u-=255};a(e.data.length),a(o.data.length);let c=new Uint8Array(1+i.length+e.data.length+o.data.length+s.data.length);c[0]=2,c.set(i,1),c.set(e.data,1+i.length),c.set(o.data,1+i.length+e.data.length),c.set(s.data,1+i.length+e.data.length+o.data.length),r.codecInfo.codec="vorbis",r.description=c,r.lastMetadataPacket=s;let l=V(e.data);r.numberOfChannels=l.getUint8(11),r.sampleRate=l.getUint32(12,!0);let d=l.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(d&15),1<<(d>>4)],modeBlockflags:Ns(s.data).modeBlockflags},kr(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=o;let s=zs(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=pt,r.codecInfo.opusInfo={preSkip:s.preSkip},kr(o.data.subarray(8),this.metadataTags)}async readPacket(e,r){h(r<e.lacingValues.length);let n=0;for(let u=0;u<r;u++)n+=e.lacingValues[u];let o=e,s=n,i=r,a=[];e:for(;;){let u=this.reader.requestSlice(o.dataStartPos,o.dataSize);u instanceof Promise&&(u=await u),h(u);let m=D(u,o.dataSize);for(;;){if(i===o.lacingValues.length){a.push(m.subarray(n,s));break}let p=o.lacingValues[i];if(s+=p,p<255){a.push(m.subarray(n,s));break e}i++}let f=o.headerStartPos+o.totalSize;for(;;){let p=this.reader.requestSliceRange(f,et,St);if(p instanceof Promise&&(p=await p),!p)return null;let g=Qt(p);if(!g)return null;if(o=g,o.serialNumber===e.serialNumber)break;f=o.headerStartPos+o.totalSize}n=0,s=0,i=0}let c=a.reduce((u,m)=>u+m.length,0),l=new Uint8Array(c),d=0;for(let u=0;u<a.length;u++){let m=a[u];l.set(m,d),d+=m.length}return{data:l,endPage:o,endSegmentIndex:i}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let o=this.reader.requestSliceRange(n,et,St);if(o instanceof Promise&&(o=await o),!o)return null;let s=Qt(o);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};n=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return pa({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Vi=class{constructor(e,r){this.bitstream=e,this.demuxer=r,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Ie,this.internalSampleRate=e.codecInfo.codec==="opus"?pt:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return h(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Z}getDisposition(){return{...se}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(h(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,r,n){if(!e)return null;let{durationInSamples:o,vorbisBlockSize:s}=fa(e.data,this.bitstream.codecInfo,r.vorbisLastBlocksize),i=new G(n.metadataOnly?j:e.data,"key",Math.max(0,r.timestampInSamples)/this.internalSampleRate,o/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(i,{packet:e,timestampInSamples:r.timestampInSamples,durationInSamples:o,vorbisLastBlockSize:r.vorbisLastBlocksize,vorbisBlockSize:s}),i}async getFirstPacket(e){h(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(h(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let o=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,r){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let o=await this.demuxer.findNextPacketStart(n.packet);if(!o)return null;let s=n.timestampInSamples+n.durationInSamples,i=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:s,vorbisLastBlocksize:n.vorbisBlockSize},r)}async getPacket(e,r){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,r);let n=dt(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(r);if(n<0)return null;h(this.bitstream.lastMetadataPacket);let o=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!o)return null;let s=o.startPage,i=this.demuxer.reader.fileSize,a=[s];e:for(;s.headerStartPos+s.totalSize<i;){let b=s.headerStartPos,w=Math.floor((b+i)/2),T=w;for(;;){let S=Math.min(T+ha,i-et),v=this.demuxer.reader.requestSlice(T,S-T);if(v instanceof Promise&&(v=await v),h(v),!ga(v,S)){i=w+et;continue e}let C=this.demuxer.reader.requestSliceRange(v.filePos,et,St);C instanceof Promise&&(C=await C),h(C);let R=Qt(C);h(R);let z=!1;if(R.serialNumber===this.bitstream.serialNumber)z=!0;else{let Q=this.demuxer.reader.requestSlice(R.headerStartPos,R.totalSize);Q instanceof Promise&&(Q=await Q),h(Q);let st=D(Q,R.totalSize);z=ma(st)===R.checksum}if(!z){T=R.headerStartPos+4;continue}if(z&&R.serialNumber!==this.bitstream.serialNumber){T=R.headerStartPos+R.totalSize;continue}if(R.granulePosition===-1){T=R.headerStartPos+R.totalSize;continue}this.granulePositionToTimestampInSamples(R.granulePosition)>n?i=R.headerStartPos:(s=R,a.push(R));continue e}}let c=o.startPage;for(let b of a){if(b.granulePosition===s.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c,d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){let b=l.headerStartPos+l.totalSize,w=this.demuxer.reader.requestSliceRange(b,et,St);w instanceof Promise&&(w=await w),h(w);let T=Qt(w);h(T),l=T,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}h(l.granulePosition!==-1);let u=null,m,f,p=l,g=0;if(l.headerStartPos===o.startPage.headerStartPos)m=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{m=0,f=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){u=T+1;break}if(u===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=u-1;let b={data:j,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(b)){let T=ya(d,l,u);h(T);let S=ba(d,T.page,T.segmentIndex);S&&(l=S.page,u=S.segmentIndex)}else for(;;){let T=ya(d,l,u);if(!T)break;let S=ba(d,T.page,T.segmentIndex);if(!S)break;if(l=S.page,u=S.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,g=T.segmentIndex;break}}}let x=null,y=null;for(;l!==null;){h(u!==null);let b=await this.demuxer.readPacket(l,u);if(!b)break;if(!(l.headerStartPos===o.startPage.headerStartPos&&u<o.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:m,vorbisLastBlocksize:y?.vorbisBlockSize??null},r);h(S);let v=this.encodedPacketToMetadata.get(S);if(h(v),!f&&b.endPage.headerStartPos===p.headerStartPos&&b.endSegmentIndex===g?(m=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,S=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:m-v.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},r),h(S),v=this.encodedPacketToMetadata.get(S),h(v)):m+=v.durationInSamples,x=S,y=v,f&&(Math.max(m,0)>n||Math.max(v.timestampInSamples,0)===n))break}let T=await this.demuxer.findNextPacketStart(b);if(!T)break;l=T.startPage,u=T.startSegmentIndex}return x}async getPacketSequential(e,r){let n=await this.sequentialScanMutex.acquire();try{let o=dt(e*this.internalSampleRate);e=o/this.internalSampleRate;let s=N(this.sequentialScanCache,o,c=>c.timestampInSamples),i;if(s!==-1){let c=this.sequentialScanCache[s];i=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},r)}else i=await this.getFirstPacket(r);let a=0;for(;i&&i.timestamp<e;){let c=await this.getNextPacket(i,r);if(!c||c.timestamp>e)break;if(i=c,a++,a===100){a=0;let l=this.encodedPacketToMetadata.get(i);h(l),this.sequentialScanCache.length>0&&h(re(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return i}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}},ba=(t,e,r)=>{let n=e,o=r;e:for(;;){for(o--,o;o>=0;o--)if(n.lacingValues[o]<255){o++;break e}if(h(o===-1),!(n.headerType&1)){o=0;break}let i=ui(t,a=>a.headerStartPos<n.headerStartPos);if(!i)return null;n=i,o=n.lacingValues.length}if(h(o!==-1),o===n.lacingValues.length){let s=t[t.indexOf(n)+1];h(s),n=s,o=0}return{page:n,segmentIndex:o}},ya=(t,e,r)=>{if(r>0)return{page:e,segmentIndex:r-1};let n=ui(t,o=>o.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var Ve;(function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"})(Ve||(Ve={}));var qn=class extends te{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),h(e);let r=W(e,4),n=r!=="RIFX",o=r==="RF64",s=Le(e,n),i=o?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(W(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,d=e.filePos;for(;i===null||d<i;){let m=this.reader.requestSlice(d,8);if(m instanceof Promise&&(m=await m),!m)break;let f=W(m,4),p=Le(m,n),g=m.filePos;if(o&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(g,p,n);else if(f==="data"){if(l??=p,this.dataStart=m.filePos,this.dataSize=Math.min(l,(i??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let x=this.reader.requestSlice(g,p);if(x instanceof Promise&&(x=await x),!x)break;let y=Hi(x,n);l=Hi(x,n),i=Math.min(y+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(g,p,n):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(g,p);d=g+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new K(this.input,new Li(this)))})()}async parseFmtChunk(e,r,n){let o=this.reader.requestSlice(e,r);if(o instanceof Promise&&(o=await o),!o)return;let s=Zt(o,n),i=Zt(o,n),a=Le(o,n);o.skip(4);let c=Zt(o,n),l;if(r===14?l=8:l=Zt(o,n),r>=18&&s!==357){let d=Zt(o,n),u=r-18;if(Math.min(u,d)>=22&&s===Ve.EXTENSIBLE){o.skip(6);let f=D(o,16);s=f[0]|f[1]<<8}}(s===Ve.MULAW||s===Ve.ALAW)&&(l=8),this.audioInfo={format:s,numberOfChannels:i,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,r,n){let o=this.reader.requestSlice(e,r);if(o instanceof Promise&&(o=await o),!o)return;let s=W(o,4);if(s!=="INFO"&&s!=="INF0")return;let i=o.filePos;for(;i<=e+r-8;){o.filePos=i;let a=W(o,4),c=Le(o,n),l=D(o,c),d=0;for(let m=0;m<l.length&&l[m]!==0;m++)d++;let u=String.fromCharCode(...l.subarray(0,d));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=u,a){case"INAM":case"TITL":this.metadataTags.title??=u;break;case"TIT3":this.metadataTags.description??=u;break;case"IART":this.metadataTags.artist??=u;break;case"IPRD":this.metadataTags.album??=u;break;case"IPRT":case"ITRK":case"TRCK":{let m=u.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let m=new Date(u);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"YEAR":{let m=Number.parseInt(u,10);Number.isInteger(m)&&m>0&&(this.metadataTags.date??=new Date(m,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=u;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=u;break}i+=8+c+(c&1)}}async parseId3Chunk(e,r){let n=this.reader.requestSlice(e,r);if(n instanceof Promise&&(n=await n),!n)return;let o=kt(n);if(o){let s=n.slice(e+10,o.size);Ln(s,o,this.metadataTags)}}getCodec(){if(h(this.audioInfo),this.audioInfo.format===Ve.MULAW)return"ulaw";if(this.audioInfo.format===Ve.ALAW)return"alaw";if(this.audioInfo.format===Ve.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===Ve.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Yt=2048,Li=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(h(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getDisposition(){return{...se}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,r){h(this.demuxer.audioInfo);let n=e*Yt*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let o=Math.min(Yt*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);if(c instanceof Promise&&(c=await c),!c)return null}let s;if(r.metadataOnly)s=j;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);c instanceof Promise&&(c=await c),h(c),s=D(c,o)}let i=e*Yt/this.demuxer.audioInfo.sampleRate,a=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,i),new G(s,"key",i,a,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,r){h(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Yt,(this.demuxer.dataSize-1)/(Yt*this.demuxer.audioInfo.blockSizeInBytes))),o=await this.getPacketAtIndex(n,r);if(o)return o;if(n===0)return null;h(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,r);for(;s;){let i=await this.getNextPacket(s,r);if(!i)break;s=i}return s}getNextPacket(e,r){h(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Yt);return this.getPacketAtIndex(n+1,r)}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var Jt=7,er=9,Mr=t=>{let e=t.filePos,r=D(t,9),n=new L(r);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let i=n.readBits(1),a=n.readBits(2)+1,c=n.readBits(4);if(c===15)return null;n.skipBits(1);let l=n.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let d=n.readBits(13);n.skipBits(11);let u=n.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;return i===1?t.filePos-=2:m=n.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:d,numberOfAacFrames:u,crcCheck:m,startPos:e}};var Gi=1024,Wn=class extends te{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new Ie,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();h(this.firstFrameHeader),this.tracks=[new K(this.input,new qi(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,Jt,er);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=Mr(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let n=wr[r.samplingFrequencyIndex];h(n!==void 0);let o=Gi/n,s=r.crcCheck?er:Jt,i={timestamp:this.nextTimestampInSamples/n,duration:o,dataStart:r.startPos+s,dataSize:r.frameLength-s};this.loadedSamples.push(i),this.nextTimestampInSamples+=Gi,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){return{}}},qi=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Gi}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Z}getCodec(){return"aac"}getInternalCodecId(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){h(this.demuxer.firstFrameHeader);let e=pi[this.demuxer.firstFrameHeader.channelConfiguration];return h(e!==void 0),e}getSampleRate(){h(this.demuxer.firstFrameHeader);let e=wr[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return h(e!==void 0),e}getDisposition(){return{...se}}async getDecoderConfig(){h(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),r=new L(e),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:s}=this.demuxer.firstFrameHeader;return n>31?(r.writeBits(5,31),r.writeBits(6,n-32)):r.writeBits(5,n),r.writeBits(4,o),r.writeBits(4,s),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((r.pos-1)/8))}}async getPacketAtIndex(e,r){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(r.metadataOnly)o=j;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;o=D(s,n.dataSize)}return new G(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let o=ct(this.demuxer.loadedSamples,e.timestamp,i=>i.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let s=o+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{n()}}async getPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=N(this.demuxer.loadedSamples,e,s=>s.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,r);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,r);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var Ta=t=>t===0?null:t===1?192:t>=2&&t<=5?144*2**t:t===6?"uncommon-u8":t===7?"uncommon-u16":t>=8&&t<=15?2**t:null,wa=(t,e)=>{switch(t){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},ka=t=>{let e=0,r=new L(D(t,1));for(;r.readBits(1)===1;)e++;if(e===0)return r.readBits(7);let n=[],o=e-1,s=new L(D(t,o)),i=8-e-1;for(let c=0;c<i;c++)n.unshift(r.readBits(1));for(let c=0;c<o;c++)for(let l=0;l<8;l++){let d=s.readBits(1);l<2||n.unshift(d)}return n.reduce((c,l,d)=>c|l<<d,0)},va=(t,e)=>{if(e==="uncommon-u16")return X(t)+1;if(e==="uncommon-u8")return F(t)+1;if(typeof e=="number")return e;fe(e),h(!1)},Sa=(t,e)=>e==="uncommon-u16"?X(t):e==="uncommon-u16-10"?X(t)*10:e==="uncommon-u8"?F(t):typeof e=="number"?e:null,Pa=t=>{let r=0;for(let n of t){r^=n;for(let o=0;o<8;o++)(r&128)!==0?r=r<<1^7:r<<=1,r&=255}return r};var jn=class extends te{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Ie,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),h(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),h(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);h(r);let n=F(r),o=Ze(r),s=(n&128)!==0;switch(n&127){case Qe.STREAMINFO:{let a=this.reader.requestSlice(e,o);if(a instanceof Promise&&(a=await a),h(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=D(a,34),l=new L(c),d=l.readBits(16),u=l.readBits(16),m=l.readBits(24),f=l.readBits(24),p=l.readBits(20),g=l.readBits(3)+1;l.readBits(5);let x=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:g,sampleRate:p,totalSamples:x,minimumBlockSize:d,maximumBlockSize:u,minimumFrameSize:m,maximumFrameSize:f,description:y},this.track=new K(this.input,new Wi(this));break}case Qe.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),h(a),kr(D(a,o),this.metadataTags);break}case Qe.PICTURE:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),h(a);let c=I(a),l=I(a),d=Y.decode(D(a,l)),u=I(a),m=Y.decode(D(a,u));a.skip(16);let f=I(a),p=D(a,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:d,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:m});break}default:break}if(e+=o,s){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:r}){h(this.audioInfo);let n=6,s=this.audioInfo.maximumFrameSize+16,i=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,s);if(!i)return null;let a=this.readFlacFrameHeader({slice:i,isFirstPacket:r});if(!a)return null;for(i.filePos=e+this.audioInfo.minimumFrameSize;;){if(i.filePos>i.end-n)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:i.end-e,isLastFrame:!0};if(F(i)===255){let l=i.filePos,d=F(i),u=this.blockingBit===1?249:248;if(d!==u){i.filePos=l;continue}i.skip(-2);let m=i.filePos-e,f=this.readFlacFrameHeader({slice:i,isFirstPacket:!1});if(!f){i.filePos=l;continue}if(this.blockingBit===0){if(f.num-a.num!==1){i.filePos=l;continue}}else if(f.num-a.num!==a.blockSize){i.filePos=l;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:m,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){let n=e.filePos,o=D(e,4),s=new L(o);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){h(r);let x=s.readBits(1);this.blockingBit=x}else if(this.blockingBit===1){if(h(!r),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(h(!r),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=Ta(s.readBits(4));if(!a)return null;h(this.audioInfo);let c=wa(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let d=ka(e),u=va(e,a),m=Sa(e,c);if(m===null||m!==this.audioInfo.sampleRate)return null;let f=e.filePos-n,p=F(e);e.skip(-f),e.skip(-1);let g=Pa(D(e,f));return p!==g?null:{num:d,blockSize:u,sampleRate:m}}async advanceReader(){await this.readMetadata(),h(this.lastLoadedPos!==null),h(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!r){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(s),r.isLastFrame){this.lastSampleLoaded=!0;return}}},Wi=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...se}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return h(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,r){if(h(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=N(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(o===-1){await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[o],i=s.blockOffset/this.demuxer.audioInfo.sampleRate,a=s.blockSize/this.demuxer.audioInfo.sampleRate;if(i+a<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,r);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(o,r)}}finally{n()}}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let o=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&o>=this.demuxer.loadedSamples.length)return null;for(;o>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(o,r)}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}async getPacketAtIndex(e,r){let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(r.metadataOnly)o=j;else{let a=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;o=D(a,n.byteSize)}h(this.demuxer.audioInfo);let s=n.blockOffset/this.demuxer.audioInfo.sampleRate,i=n.blockSize/this.demuxer.audioInfo.sampleRate;return new G(o,"key",s,i,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var pe=class{},Or=class extends pe{async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);return r instanceof Promise&&(r=await r),!r||(r.skip(4),W(r,4)!=="ftyp")?null:W(r,4)}_createDemuxer(e){return new Fn(e)}},$n=class extends Or{async _canReadInput(e){let r=await this._getMajorBrand(e);return!!r&&r!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Kn=class extends Or{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},zr=class extends pe{async isSupportedEBMLOfDocType(e,r){let n=e._reader.requestSlice(0,xe);if(n instanceof Promise&&(n=await n),!n)return!1;let o=Fi(n);if(o===null||o<1||o>8||M(n,o)!==k.EBML)return!1;let i=Di(n);if(i===null)return!1;let a=e._reader.requestSlice(n.filePos,i);if(a instanceof Promise&&(a=await a),!a)return!1;let c=n.filePos;for(;a.filePos<=c+i-le;){let l=be(a);if(!l)break;let{id:d,size:u}=l,m=a.filePos;if(u===null)return!1;switch(d){case k.EBMLVersion:if(M(a,u)!==1)return!1;break;case k.EBMLReadVersion:if(M(a,u)!==1)return!1;break;case k.DocType:if(Je(a,u)!==r)return!1;break;case k.DocTypeVersion:if(M(a,u)>4)return!1;break}a.filePos=m+u}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Un(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Xn=class extends zr{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Qn=class extends pe{async _canReadInput(e){let r=e._reader.requestSlice(0,10);if(r instanceof Promise&&(r=await r),!r)return!1;let n=0,o=!1;for(;;){let l=e._reader.requestSlice(n,Xt);if(l instanceof Promise&&(l=await l),!l)break;let d=kt(l);if(!d)break;o=!0,n=l.filePos+d.size}let s=await Br(e._reader,n,n+4096);if(!s)return!1;if(o)return!0;n=s.startPos+s.header.totalSize;let i=await Br(e._reader,n,n+4);if(!i)return!1;let a=s.header,c=i.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new Hn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Yn=class extends pe{async _canReadInput(e){let r=e._reader.requestSlice(0,12);if(r instanceof Promise&&(r=await r),!r)return!1;let n=W(r,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(r.skip(4),W(r,4)==="WAVE")}_createDemuxer(e){return new qn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Zn=class extends pe{async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?W(r,4)==="OggS":!1}_createDemuxer(e){return new Gn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Jn=class extends pe{async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?W(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new jn(e)}},eo=class extends pe{async _canReadInput(e){let r=e._reader.requestSliceRange(0,Jt,er);if(r instanceof Promise&&(r=await r),!r)return!1;let n=Mr(r);if(!n||(r=e._reader.requestSliceRange(n.frameLength,Jt,er),r instanceof Promise&&(r=await r),!r))return!1;let o=Mr(r);return o?n.objectType===o.objectType&&n.samplingFrequencyIndex===o.samplingFrequencyIndex&&n.channelConfiguration===o.channelConfiguration:!1}_createDemuxer(e){return new Wn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Ia=new $n,Ca=new Kn,Aa=new zr,_a=new Xn,Ea=new Qn,Fa=new Yn,Da=new Zn,Ra=new eo,Ba=new Jn,Te=[Ia,Ca,Aa,_a,Fa,Da,Ba,Ea,Ra];var Pt=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new $;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new $;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var Ur=class extends Pt{constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!Tr(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new to({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Oa.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!$e()?r=this._blob.slice(e.currentPos).stream().getReader():r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){let{done:n,value:o}=await r.read();if(n)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}e.running=!1,e.aborted&&await r?.cancel()}_dispose(){this._orchestrator.dispose()}},Ma=.5*2**20,xl=((t,e,r)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let o=null;try{typeof window<"u"&&typeof window.location<"u"&&(o=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&o!==null&&o!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(t-2),16)}),Nr=class extends Pt{constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!Tr(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??xl,this._orchestrator=new to({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Oa.network})}async _retrieveSize(){let e=new AbortController,r=await mi(this._options.fetchFn??fetch,this._url,di(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);let n,o;if(r.status===206)o=this._getTotalLengthFromRangeResponse(r),n=this._orchestrator.createWorker(0,Math.min(o,Ma));else{let s=r.headers.get("Content-Length");if(s)o=Number(s),n=this._orchestrator.createWorker(0,o),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=o,this._existingResponses.set(n,{response:r,abortController:e}),this._orchestrator.runWorker(n),o}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;;){let r=this._existingResponses.get(e);this._existingResponses.delete(e);let n=r?.abortController,o=r?.response;if(n||(n=new AbortController,o=await mi(this._options.fetchFn??fetch,this._url,di(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),h(o),!o.ok)throw new Error(`Error fetching ${String(this._url)}: ${o.status} ${o.statusText}`);if(e.currentPos>0&&o.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!o.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let s=o.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let i;try{i=await s.read()}catch(l){if(this._disposed)throw l;let d=this._getRetryDelay(1,l,this._url);if(d!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(u=>setTimeout(u,1e3*d));break}else throw l}if(e.aborted)continue;let{done:a,value:c}=i;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let r=e.headers.get("Content-Range");if(r){let o=/\/(\d+)/.exec(r);if(o)return Number(o[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var Oa={none:(t,e)=>({start:t,end:e}),fileSystem:(t,e)=>(t=Math.floor((t-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:t,end:e}),network:(t,e,r)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(let o of r){let i=Math.max((o.startPos+o.targetPos)/2,o.targetPos-8388608);if(gn(t,e,i,o.targetPos)){let a=o.targetPos-o.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),d=Math.min(l,c);e=Math.max(e,o.startPos+d)}}return e=Math.max(e,t+Ma),{start:t,end:e}}},to=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){h(this.fileSize!==null);let n=this.options.prefetchProfile(e,r,this.workers),o=Math.max(n.start,0),s=Math.min(n.end,this.fileSize);h(o<=e&&r<=s);let i=null,a=N(this.cache,e,b=>b.start),c=a!==-1?this.cache[a]:null;c&&c.start<=e&&r<=c.end&&(c.age=this.nextAge++,i={bytes:c.bytes,view:c.view,offset:c.start});let l=N(this.cache,o,b=>b.start),d=i?null:new Uint8Array(r-e),u=0,m=o,f=[];if(l!==-1){for(let b=l;b<this.cache.length;b++){let w=this.cache[b];if(w.start>=s)break;if(w.end<=o)continue;let T=Math.max(o,w.start),S=Math.min(s,w.end);if(h(T<=S),m<T&&f.push({start:m,end:T}),m=S,d){let v=Math.max(e,w.start),A=Math.min(r,w.end);if(v<A){let C=v-e;d.set(w.bytes.subarray(v-w.start,A-w.start),C),C===u&&(u=A-e)}}w.age=this.nextAge++}m<s&&f.push({start:m,end:s})}else f.push({start:o,end:s});if(d&&u>=d.length&&(i={bytes:d,view:V(d),offset:e}),f.length===0)return h(i),i;let{promise:p,resolve:g,reject:x}=ne(),y=[];for(let b of f){let w=Math.max(e,b.start),T=Math.min(r,b.end);w===b.start&&T===b.end?y.push(b):w<T&&y.push({start:w,end:T})}for(let b of f){let w=d&&{start:e,bytes:d,holes:y,resolve:g,reject:x},T=!1;for(let S of this.workers)if(gn(b.start-131072,b.start,S.currentPos,S.targetPos)){S.targetPos=Math.max(S.targetPos,b.end),T=!0,w&&!S.pendingSlices.includes(w)&&S.pendingSlices.push(w),S.running||this.runWorker(S);break}if(!T){let S=this.createWorker(b.start,b.end);w&&(S.pendingSlices=[w]),this.runWorker(S)}}return i||(h(d),i=p.then(b=>({bytes:b,view:V(b),offset:e}))),i}createWorker(e,r){let n={startPos:e,currentPos:e,targetPos:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let o=0,s=this.workers[0];for(let i=1;i<this.workers.length;i++){let a=this.workers[i];a.age<s.age&&(o=i,s=a)}if(s.running&&s.pendingSlices.length>0)break;s.aborted=!0,this.workers.splice(o,1)}return n}runWorker(e){h(!e.running),h(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(r=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(r)),e.pendingSlices.length=0;else throw r})}supplyWorkerData(e,r){h(!e.aborted);let n=e.currentPos,o=n+r.length;this.insertIntoCache({start:n,end:o,bytes:r,view:V(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let s=0;s<e.pendingSlices.length;s++){let i=e.pendingSlices[s],a=Math.max(n,i.start),c=Math.min(o,i.start+i.bytes.length);a<c&&i.bytes.set(r.subarray(a-n,c-n),a-i.start);for(let l=0;l<i.holes.length;l++){let d=i.holes[l];n<=d.start&&o>d.start&&(d.start=o),d.end<=d.start&&(i.holes.splice(l,1),l--)}i.holes.length===0&&(i.resolve(i.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let i=this.workers[s];e===i||i.running||gn(n,o,i.currentPos,i.targetPos)&&(this.workers.splice(s,1),s--)}}forgetWorker(e){let r=this.workers.indexOf(e);h(r!==-1),this.workers.splice(r,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let r=N(this.cache,e.start,n=>n.start)+1;if(r>0){let n=this.cache[r-1];if(n.end>=e.end)return;if(n.end>e.start){let o=new Uint8Array(e.end-n.start);o.set(n.bytes,0),o.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=o,n.view=V(o),n.end=e.end,r--,e=n}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length;for(let n=r+1;n<this.cache.length;n++){let o=this.cache[n];if(e.end<=o.start)break;if(e.end>=o.end){this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length,n--;continue}let s=new Uint8Array(o.end-e.start);s.set(e.bytes,0),s.set(o.bytes,o.start-e.start),this.currentCacheSize-=e.end-o.start,e.bytes=s,e.view=V(s),e.end=o.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,o=this.cache[0];for(let s=1;s<this.cache.length;s++){let i=this.cache[s];i.age<o.age&&(n=s,o=i)}if(this.currentCacheSize-o.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};xn();var ue=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof pe)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Pt))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new ro(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),h(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(r=>r.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(r=>r.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(r=>r.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(r=>r.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},$=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var ro=class{constructor(e){this.source=e}requestSlice(e,r){if(this.source._disposed)throw new $;if(this.fileSize!==null&&e+r>this.fileSize)return null;let n=e+r,o=this.source._read(e,n);return o instanceof Promise?o.then(s=>s?new qt(s.bytes,s.view,s.offset,e,n):null):o?new qt(o.bytes,o.view,o.offset,e,n):null}requestSliceRange(e,r,n){if(this.source._disposed)throw new $;if(this.fileSize!==null)return this.requestSlice(e,ut(this.fileSize-e,r,n));{let o=this.requestSlice(e,n),s=i=>{if(i)return i;let a=l=>(h(l!==null),this.requestSlice(e,ut(l-e,r,n))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return o instanceof Promise?o.then(s):s(o)}}},qt=class t{constructor(e,r,n,o,s){this.bytes=e,this.view=r,this.offset=n,this.start=o,this.end=s,this.bufferPos=o-n}static tempFromBytes(e){return new t(e,V(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,r=this.end-e){if(e<this.start||e+r>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+r)}},ae=(t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},D=(t,e)=>{ae(t,e);let r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},F=t=>(ae(t,1),t.view.getUint8(t.bufferPos++)),Zt=(t,e)=>{ae(t,2);let r=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,r},X=t=>{ae(t,2);let e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},Ze=t=>{ae(t,3);let e=lt(t.view,t.bufferPos,!1);return t.bufferPos+=3,e},Er=t=>{ae(t,2);let e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},Le=(t,e)=>{ae(t,4);let r=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,r},I=t=>{ae(t,4);let e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},vt=t=>{ae(t,4);let e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},ze=t=>{ae(t,4);let e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},bl=t=>{ae(t,4);let e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},Hi=(t,e)=>{let r,n;return e?(r=Le(t,!0),n=Le(t,!0)):(n=Le(t,!1),r=Le(t,!1)),n*4294967296+r},ce=t=>{let e=I(t),r=I(t);return e*4294967296+r},ea=t=>{let e=ze(t),r=I(t);return e*4294967296+r},xa=t=>{let e=vt(t);return bl(t)*4294967296+e},ra=t=>{ae(t,4);let e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},Rn=t=>{ae(t,8);let e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},W=(t,e)=>{ae(t,e);let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(t.bytes[t.bufferPos++]);return r};async function _e(t){return t instanceof Blob?new Ur(t):new Nr(t)}var no=class{datafile;duration=0;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let r=new this(e),n=await this.duration(e.url)*1e3;r.duration=n;let{video:o,audio:s}=await this.#e(e.url);return r.hasAudio=s,r.hasVideo=o,r}static async duration(e){let n=await new ue({formats:Te,source:await _e(e)}).computeDuration();return Number(n.toFixed(5))}static async#e(e){let r=new ue({formats:Te,source:await _e(e)});return{audio:!!await r.getPrimaryAudioTrack(),video:!!await r.getPrimaryVideoTrack()}}};var oo=class{#e=new sn;async store(e){let r=await no.analyze(e),{hash:n}=r.datafile.checksum,{filename:o,bytes:s,url:i,blob:a}=r.datafile;if(this.#e.has(n)){let c=this.#e.require(n);c.filename=o}else this.#e.set(n,{kind:"media",filename:o,bytes:s,url:i,blob:a,duration:r.duration});return r}require(e){return this.#e.require(e)}};var O=t=>t;var za=()=>{let t=!1,e=je(60),r=1e3/e,n=0,o=0,s=Bt(),i=null,a=l=>{if(requestAnimationFrame(a),!!t)for(n=l;l-o>=r;)o+=r,i?.(),i=null,s()};async function*c(){for(n=performance.now(),o=n,requestAnimationFrame(a);;)await new Promise(l=>i=l),yield}return{play(){t||(t=!0,n=performance.now(),o=n)},pause(){t=!1},setFPS(l){e=l,r=1e3/e},isPlaying(){return t},ticks:c,onTick:s}},Ua=async(t,e)=>{let r=O(1e3/t.fps),n=t.duration/1e3,o=Math.ceil(n*t.fps);for(let s=0;s<o;s++){let i=O(s*r);await e(i,s)}};var Na={extension:{type:Kr.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-6TVTCHHE.js")}};var Va={extension:{type:Kr.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-VVIU3M54.js")}};var io;function La(t){return io!==void 0||(io=(()=>{let e={stencil:!0,failIfMajorPerformanceCaveat:t??Qr.defaultOptions.failIfMajorPerformanceCaveat};try{if(!lr.get().getWebGLRenderingContext())return!1;let n=lr.get().createCanvas().getContext("webgl",e),o=!!n?.getContextAttributes()?.stencil;if(n){let s=n.getExtension("WEBGL_lose_context");s&&s.loseContext()}return n=null,o}catch{return!1}})()),io}var so;async function Ha(t={}){return so!==void 0||(so=await(async()=>{let e=lr.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(t)).requestDevice(),!0}catch{return!1}})()),so}var Ga=["webgl","webgpu","canvas"];async function ji(t){let e=[];t.preference?(e.push(t.preference),Ga.forEach(s=>{s!==t.preference&&e.push(s)})):e=Ga.slice();let r,n={};for(let s=0;s<e.length;s++){let i=e[s];if(i==="webgpu"&&await Ha()){let{WebGPURenderer:a}=await import("./WebGPURenderer-XMCMEXAO.js");r=a,n={...t,...t.webgpu};break}else if(i==="webgl"&&La(t.failIfMajorPerformanceCaveat??Qr.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:a}=await import("./WebGLRenderer-7X274AYV.js");r=a,n={...t,...t.webgl};break}else if(i==="canvas")throw n={...t},new Error("CanvasRenderer is not yet implemented")}if(delete n.webgpu,delete n.webgl,!r)throw new Error("No available renderer for the current environment");let o=new r;return await o.init(n),o}var ao=class extends os{constructor(e,r){let{text:n,resolution:o,style:s,anchor:i,width:a,height:c,roundPixels:l,...d}=e;super({...d}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=r,this.text=n??"",this.style=s,this.resolution=o??null,this.allowChildren=!1,this._anchor=new ts({_onUpdate:()=>{this.onViewUpdate()}}),i&&(this.anchor=i),this.roundPixels=l??!1,a!==void 0&&(this.width=a),c!==void 0&&(this.height=c)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||(e={}),this._style?.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,r){typeof e=="object"?(r=e.height??e.width,e=e.width):r??(r=e),e!==void 0&&this._setWidth(e,this.bounds.width),r!==void 0&&this._setHeight(r,this.bounds.height)}containsPoint(e){let r=this.bounds.width,n=this.bounds.height,o=-r*this.anchor.x,s=0;return e.x>=o&&e.x<=o+r&&(s=-n*this.anchor.y,e.y>=s&&e.y<=s+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function qa(t,e){let r=t[0]??{};return(typeof r=="string"||t[1])&&(ns(rs,`use new ${e}({ text: "hi!", style }) instead`),r={text:r,style:t[1]}),r}var Vr=class extends ao{constructor(...e){let r=qa(e,"Text");super(r,is),this.renderPipeId="text",r.textureStyle&&(this.textureStyle=r.textureStyle instanceof Mo?r.textureStyle:new Mo(r.textureStyle))}updateBounds(){let e=this._bounds,r=this._anchor,n=0,o=0;if(this._style.trim){let{frame:s,canvasAndContext:i}=Uo.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Uo.returnCanvasAndContext(i),n=s.width,o=s.height}else{let s=ss.measureText(this._text,this._style);n=s.width,o=s.height}e.minX=-r._x*n,e.maxX=e.minX+n,e.minY=-r._y*o,e.maxY=e.minY+o}};es.add(Na,Va);var Wa=t=>{let[e,r,n]=t,[o,s]=e,[i,a]=r,c=n*Math.PI/180,l=Math.cos(c),d=Math.sin(c);return[l*i,d*i,-d*a,l*a,o,s]},ja=([t,e,r,n,o,s])=>new Bo(t,e,r,n,o,s);var $a=(t,e)=>{let[r,n,o,s,i,a]=t,[c,l,d,u,m,f]=e;return[r*c+o*l,n*c+s*l,r*d+o*u,n*d+s*u,r*m+o*f+i,n*m+s*f+a]},Ka=[1,0,0,1,0,0];function Qa(t){return"duration"in t}function Ya(t){let e=[],r=new Map(t.timeline.items.map(n=>[n.id,n]));return $i(t.timeline.rootId,r,t.from,{sequence:()=>{},stack:()=>{},video:(n,o,s)=>e.push({item:n,localTime:o,ancestors:s}),text:(n,o,s)=>e.push({item:n,localTime:o,ancestors:s}),audio:(n,o,s)=>e.push({item:n,localTime:o,ancestors:s})}),e}function Za(t,e,r){let n=Ka;for(let o of e)n=Xa(t,o,n);return Xa(t,r,n)}function Xa(t,e,r){if("spatialId"in e&&e.spatialId){let n=t.get(e.spatialId);if(n?.enabled){let o=Wa(n.transform);return $a(o,r)}}return r}function $i(t,e,r,n,o=[]){let s=e.get(t);if(s)switch(s.kind){case U.Stack:n.stack(s,r,o);for(let i of s.childrenIds)$i(i,e,r,n,[...o,s]);break;case U.Sequence:{n.sequence(s,r,o);let i=O(0);for(let a of s.childrenIds){let c=e.get(a);if(!c||!Qa(c))continue;let l=O(i+c.duration);if(r>=l){i=l;continue}let d=O(Math.max(0,r-i));$i(a,e,d,n,[...o,s]),i=l}break}case U.Video:n.video(s,r,o);break;case U.Text:n.text(s,r,o);break;case U.Audio:n.audio(s,r,o);break}}function H(t,e){let r=e.items.find(n=>n.id===t);if(!r)return O(0);switch(r.kind){case U.Sequence:{let n=r.childrenIds.map(s=>e.items.find(i=>i.id===s)).filter(Boolean),o=O(0);for(let s=0;s<n.length;s++){let i=n[s];if(i.kind===U.Transition){let a=n[s-1],c=n[s+1];if(a&&c&&a.kind!==U.Transition&&c.kind!==U.Transition){let l=H(a.id,e),d=H(c.id,e),u=Math.max(0,Math.min(i.duration,l,d));o=O(o-u)}continue}o=O(o+H(i.id,e))}return o}case U.Stack:{let n=O(0);for(let o of r.childrenIds){let s=H(o,e);s>n&&(n=s)}return n}default:return Qa(r)?r.duration:O(0)}}var Lr=t=>t;var co=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let r=this.#e.get(e);if(r)return r.sink;let n=new ue({formats:Te,source:await _e(this.resolveMedia(e))}),o=await n.getPrimaryVideoTrack(),i=!!o&&await o.canDecode()&&o?new Ar(o):null;return this.#e.set(e,{input:n,sink:i}),i}};async function Ja(t,e,r,n){let[o,s]=await Promise.all([r,n]),i=o.find(l=>l.kind==="image")?.frame,a=s.find(l=>l.kind==="image")?.frame,c=[...o.filter(l=>l.kind!=="image"),...s.filter(l=>l.kind!=="image")];return i&&a?[{id:t.id,kind:"transition",name:"circle",progress:e,from:i,to:a},...c]:c}async function ec(t,e,r,n){let o=yl(t,e,r);if(!o)return[];let s=[...n,e];return o.isTransitioning?Ja(o.transition,o.progress,It(t,o.outgoing,o.outgoingTime,s),It(t,o.incoming,o.incomingTime,s)):It(t,o.item,o.localTime,s)}function yl(t,e,r){let n=e.childrenIds.map(s=>t.items.get(s)).filter(s=>!!s),o=O(0);for(let s=0;s<n.length;s++){let i=n[s];if(i.kind===U.Transition)continue;let a=o,c=H(i.id,t.timeline),l=O(a+c),d=n[s+1];if(!(d?.kind===U.Transition)){if(r<l)return{isTransitioning:!1,item:i,localTime:O(r-a)};o=l;continue}let m=d,f=n[s+2];if(!f||f.kind===U.Transition){o=l;continue}let p=H(f.id,t.timeline),g=Math.max(0,Math.min(m.duration,c,p)),x=O(l-g);if(r<x)return{isTransitioning:!1,item:i,localTime:O(r-a)};if(r<l){let y=O(r-x),b=O(r-a);return{isTransitioning:!0,incoming:f,outgoing:i,outgoingTime:b,incomingTime:y,progress:g>0?y/g:1,transition:m}}o=x,s++}return null}async function It(t,e,r,n){let o=Za(t.items,n,e);switch(e.kind){case U.Stack:{let s=[...n,e];return(await Promise.all(e.childrenIds.map(a=>t.items.get(a)).filter(a=>!!a).map(a=>It(t,a,r,s)))).flat()}case U.Sequence:return ec(t,e,r,n);case U.Video:{if(r<0||r>=e.duration)return[];let s=await t.videoSampler(e,r);return s?[{kind:"image",frame:s,matrix:o,id:e.id}]:[]}case U.Text:{if(r<0||r>=e.duration)return[];let s=e.styleId?t.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:e.content,style:s,matrix:o}]}case U.Gap:return[{id:e.id,kind:"gap"}];default:return[]}}function tc(t){return async(e,r)=>{let o=await(await t.getSink(e.mediaHash))?.getSample(r/1e3),s=o?.toVideoFrame();return o?.close(),s??void 0}}function tr(t,e){let r=new co(t),n=e??tc(r);return{async sample(o,s){let i=new Map(o.items.map(c=>[c.id,c])),a=i.get(o.rootId);return a?It({videoSampler:n,timeline:o,items:i},a,s,[]):[]}}}var tt=class{driver;resolveMedia;timeline;#e=-1/0;#t=new Map;#r;constructor(e,r,n){this.driver=e,this.resolveMedia=r,this.timeline=n,this.#r=tr(this.resolveMedia,(o,s)=>{let i=rc(s),a=this.#t.get(o.id);if(!a){let c=this.resolveMedia(o.mediaHash),l=rc(O(o.start+o.duration));a=this.#n(c,i,l),this.#t.set(o.id,a)}return a.next(i)})}next(e){if(e<this.#e)throw new Error(`Forward-only cursor regression: ${e}ms < ${this.#e}ms`);return this.#e=e,this.#r.sample(this.timeline,e)}async cancel(){await Promise.all([...this.#t.values()].map(e=>e.cancel())),this.#t.clear()}#n(e,r,n){let o=this.driver.decodeVideo({source:e,start:r/1e6,end:n/1e6}),s=o.readable.getReader(),i=null,a=null,c=!1,l=async()=>{if(c)return null;let{done:d,value:u}=await s.read();if(d)return c=!0,null;let m=new VideoFrame(u);return u.close(),m};return{async next(d){if(i??=await l(),!!i)for(;;){a??=l();let u=await a;if(!u)return new VideoFrame(i);let m=i.timestamp??-1/0,f=u.timestamp??m;if(f<d){i.close(),i=u,a=null;continue}if(Math.abs(f-d)<Math.abs(m-d)){i.close(),i=u,a=null;continue}return new VideoFrame(i)}},async cancel(){let d=a;a=null,i?.close(),i=null,o.cancel(),(await d?.catch(()=>null))?.close()}}}},rc=t=>Math.round(t*1e3);async function nc(t,e,r){return(await Promise.all(e.map(async({item:o,localTime:s})=>{if(o.kind!==U.Audio)return;let i=await t.getSink(o.mediaHash);if(!i)return;let a=o.start+s,c=Lr((r-a)/1e3),l=i.samples(a/1e3),d=await l.next();if(d.done)return;let u=d.value,m=l.next();return{offset:c,gain:o.gain??1,get currentSample(){return u},timelineTime:()=>Lr(c+u.timestamp),output:()=>({sample:u,timestamp:c+u.timestamp,gain:o.gain??1}),advance:async()=>{let f=await m;return f.done?!1:(u=f.value,m=l.next(),!0)}}}))).filter(o=>!!o)}var lo=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let r=this.#e.get(e);if(r)return r.sink;let n=new ue({formats:Te,source:await _e(this.resolveMedia(e))}),o=await n.getPrimaryAudioTrack(),i=!!o&&await o.canDecode()&&o?new _r(o):null;return this.#e.set(e,{input:n,sink:i}),i}};function oc(t){let e={index:0,stream:t[0],time:t[0].timelineTime()};for(let[r,n]of t.entries()){let o=n.timelineTime();o<e.time&&(e={time:o,stream:n,index:r})}return e}function uo(t){let e=new lo(t);return{async*sampleAudio(r,n){let o=Ya({timeline:r,from:n}),s=await nc(e,o,n);for(;s.length>0;){let{stream:i,index:a}=oc(s);yield i.output(),await i.advance()||s.splice(a,1)}}}}var mo=class{driver;timeline;resolveMedia;audioSampler;seekVisualSampler;playVisualSampler=null;#e=O(0);#t=null;#r=za();onTick=this.#r.onTick;audioContext=new AudioContext({sampleRate:48e3});audioGain=this.audioContext.createGain();audioNodes=new Set;#n=null;constructor(e,r,n){this.driver=e,this.timeline=r,this.resolveMedia=n,this.audioGain.connect(this.audioContext.destination),this.audioGain.gain.value=.7**2,this.seekVisualSampler=tr(this.resolveMedia),this.audioSampler=uo(this.resolveMedia),this.#o()}async#o(){for await(let e of this.#r.ticks()){let r=await this.playVisualSampler?.next(this.currentTime)??[];(await this.driver.composite(r)).close(),this.currentTime>=this.duration&&this.pause()}}async seek(e){return this.pause(),this.#e=e,await this.seekVisualSampler.sample(this.timeline,e)}async start(e){if(!this.#r.isPlaying()){this.timeline=e,await this.audioContext.resume(),this.#e=this.currentTime,this.#t=this.audioContext.currentTime,this.#n?.abort(),this.#n=new AbortController;for(let r of this.audioNodes)r.stop();this.audioNodes.clear(),this.playVisualSampler?.cancel(),this.playVisualSampler=new tt(this.driver,this.resolveMedia,this.timeline),this.#r.play(),this.#i(this.#n.signal,Lr(this.#e/1e3))}}pause(){this.#e=this.currentTime,this.#r.pause(),this.#n?.abort();for(let e of this.audioNodes)e.stop();this.audioNodes.clear(),this.playVisualSampler?.cancel(),this.playVisualSampler=null}get duration(){return H(this.timeline.rootId,this.timeline)}get currentTime(){if(!this.#r.isPlaying()||this.#t===null)return this.#e;let e=(this.audioContext.currentTime-this.#t)*1e3;return O(this.#e+e)}setFps(e){this.#r.setFPS(e)}async#i(e,r){let n=this.audioContext;if(this.#t!==null)for await(let{sample:o,timestamp:s}of this.audioSampler.sampleAudio(this.timeline,O(r*1e3))){if(e.aborted||!this.#r.isPlaying())return;for(;s-(n.currentTime-this.#t+r)>.75;)await new Promise(c=>setTimeout(c,25));let i=n.createBufferSource();i.buffer=o.toAudioBuffer(),i.connect(this.audioGain),i.onended=()=>this.audioNodes.delete(i),this.audioNodes.add(i);let a=this.#t+s-r;a>=n.currentTime?i.start(a):i.start(n.currentTime,n.currentTime-a)}}};var fo=class{driver;timeline;canvas;playback;constructor(e,r,n){this.driver=e,this.timeline=n,this.playback=new mo(e,n,r),this.canvas=e.compositor.pixi.renderer.canvas}async play(){await this.playback.start(this.timeline)}pause(){this.playback.pause()}async seek(e){let r=await this.playback.seek(O(e));(await this.driver.composite(r)).close()}setFPS(e){this.playback.setFps(je(e))}get duration(){return this.playback.duration}get currentTime(){return this.playback.currentTime}async update(e){this.timeline=e}};var Ee=class{#e;#t;constructor(e={}){this.#e=e.chunkFrames??1024,this.#t=e.clamp??!0}async*mix(e){let r=this.#e,n=null,o=null,s=[],i=0,a=0;for await(let c of e){if(o===null)o=c.planes.length,n=c.sampleRate;else{if(c.planes.length!==o)throw new Error("Channel count changed");if(c.sampleRate!==n)throw new Error("Sample rate changed")}let l=Math.round(c.timestamp*n),d=c.planes[0]?.length??0;for(;i+r<=l;)yield this.#r(s,i,o,n),i+=r;s.push({startFrame:l,endFrame:l+d,data:c.planes}),a=Math.max(a,l+d)}if(o!==null&&n!==null)for(;i<a;)yield this.#r(s,i,o,n),i+=r}#r(e,r,n,o){let s=this.#e,i=new Float32Array(n*s),a=r+s;for(let c=0;c<n;c++){let l=c*s,d=i.subarray(l,l+s);for(let u of e){let m=u.data[c];if(!m)continue;let f=Math.max(r,u.startFrame),p=Math.min(a,u.endFrame);if(f>=p)continue;let g=f-r,x=f-u.startFrame,y=p-f;for(let b=0;b<y;b++)d[g+b]+=m[x+b]}if(this.#t)for(let u=0;u<s;u++){let m=d[u];d[u]=m<-1?-1:m>1?1:m}}for(let c=e.length-1;c>=0;c--)e[c].endFrame<=a&&e.splice(c,1);return{planar:i,sampleRate:o,channels:n,frames:s,startFrame:r}}};var Tl=(t,e,r)=>{if(e===r)return t;let n=r/e,o=Math.max(1,Math.round(t.length*n)),s=new Float32Array(o);for(let i=0;i<o;i++){let a=i/n,c=Math.floor(a),l=Math.min(c+1,t.length-1),d=a-c;s[i]=t[c]*(1-d)+t[l]*d}return s},Fe=(t,e)=>{let r=t.numberOfChannels,n=new Array(r),o=0;for(let s=0;s<r;s++){let i=new Float32Array(t.numberOfFrames);t.copyTo(i,{planeIndex:s,format:"f32-planar"});let a=Tl(i,t.sampleRate,e);n[s]=a,o=a.length}return{data:n,frames:o}};var rr=(t,e)=>{if(e!==1)for(let r of t)for(let n=0;n<r.length;n++)r[n]*=e};function po({timeline:t,resolveMedia:e}){let r=new Ee,n=wl(t,e),o=new TransformStream,s=o.writable.getWriter();async function i(){for await(let a of r.mix(n)){let c=new AudioData({format:"f32-planar",sampleRate:a.sampleRate,numberOfFrames:a.frames,numberOfChannels:a.channels,timestamp:Math.round(a.startFrame/a.sampleRate*1e6),data:new Float32Array(a.planar)});await s.write(c)}await s.close()}return i(),o.readable}async function*wl(t,e){let r=uo(e);for await(let{sample:n,timestamp:o,gain:s}of r.sampleAudio(t,O(0))){let{data:i}=Fe(n,48e3);rr(i,s),yield{planes:i,sampleRate:48e3,timestamp:o},n.close()}}function ho({timeline:t,fps:e,driver:r,resolveMedia:n}){let o=new TransformStream,s=o.writable.getWriter(),i=new tt(r,n,t),a=1/e,c=H(t.rootId,t);async function l(){await Ua({fps:e,duration:c},async(d,u)=>{let m=await i.next(d),f=await r.composite(m),p=new VideoFrame(f,{timestamp:Math.round(u*a*1e6),duration:Math.round(a*1e6)});await s.write(p),f.close()}),await s.close()}return l(),o.readable}function ic(t){let e=po({...t}),r=ho({...t});return t.driver.encode({video:r,audio:e,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}var rt=class{driver;resources=new oo;constructor(e){this.driver=e}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,n])=>[r,await this.resources.store(await n)])));timeline=e=>{let r=new q({timeline:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),n=e(r);return r.timeline.rootId=n.id,r.timeline};playback=async e=>new fo(this.driver,r=>this.resources.require(r).url,e);render=async(e,r=30)=>ic({timeline:e,fps:je(r),driver:this.driver,resolveMedia:n=>this.resources.require(n).url})};function Ki(t,e){return{error:r=>t.error({...e,...r}),rpcRequest:r=>t.rpcRequest({...e,...r}),rpcError:r=>t.rpcError({...e,...r})}}var go=()=>t=>({plain:t.none,errMessage:t.mix(t.brightRed,t.bold),errName:t.red,errStack:t.mix(t.red,t.dim),timestamp:t.blue,timestampErr:t.red});function sc(){return go()}var nt=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});var xo=()=>({none:t=>t,uncolor:vl,mix:Sl,hex:Pl,rgb:ac,bgRgb:Il});function vl(t){return t.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function Sl(...t){return e=>{for(let r of t)e=r(e);return e}}function Pl(t){t=t.replace(/^#/,"");let e,r,n,o;if(t.length===3)e=parseInt(t.split("").map(s=>s+s).join(""),16);else if(t.length===6)e=parseInt(t,16);else throw new Error("Invalid hex color");return r=e>>16&255,n=e>>8&255,o=e&255,ac(r,n,o)}function ac(t,e,r){let n=`\x1B[38;2;${t};${e};${r}m`;return o=>`${n}${o}${nt.reset}`}function Il(t,e,r){let n=`\x1B[48;2;${t};${e};${r}m`;return o=>`${n}${o}${nt.reset}`}var Hr={...Object.fromEntries(Object.entries(nt).map(([t])=>[t,e=>e])),...xo()};var Gr={...Object.fromEntries(Object.entries(nt).map(([t,e])=>[t,r=>`${e}${r}${nt.reset}`])),...xo()};function Xi(){return typeof Deno<"u"&&typeof Deno.version<"u"}function Qi(){return typeof process<"u"&&process.versions&&process.versions.node}function cc(){return Qi()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":Xi()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var Yi=()=>cc()?Gr:Hr;var bo=()=>({colors:t,theme:e})=>{let r=e(t);function n(i){let a=i.stack?`
|
|
2360
|
+
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),n}createShader(e,r){let n=this.gl.createShader(e);return this.gl.shaderSource(n,r),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let o=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,r){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Ar=class extends Cr{constructor(e){if(!(e instanceof Me))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=this._track.rotation,s=await this._track.getDecoderConfig(),i=this._track.timeResolution;return h(n&&s),new ki(e,r,n,s,o,i)}_createPacketSink(){return new Tt(this._track)}async getSample(e){yt(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var Si=class extends Ir{constructor(e,r,n,o){super(e,r),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new br,this.customDecoderQueueSize=0,this.currentTimestamp=null;let s=a=>{(this.currentTimestamp===null||Math.abs(a.timestamp-this.currentTimestamp)>=a.duration)&&(this.currentTimestamp=a.timestamp);let c=this.currentTimestamp;if(this.currentTimestamp+=a.duration,a.numberOfFrames===0){a.close();return}let l=o.sampleRate;a.setTimestamp(Math.round(c*l)/l),e(a)},i=An.find(a=>a.supports(n,o));if(i)this.customDecoder=new i,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=a=>{if(!(a instanceof zt))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(a)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let a=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{s(new zt(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(h(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close())}},Pi=class extends Ir{constructor(e,r,n){super(e,r),this.decoderConfig=n,this.currentTimestamp=null,h(Xe.includes(n.codec)),this.codec=n.codec;let{dataType:o,sampleSize:s,littleEndian:i}=wn(this.codec);switch(this.inputSampleSize=s,s){case 1:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint8(c)-2**7:o==="signed"?this.readInputValue=(a,c)=>a.getInt8(c):o==="ulaw"?this.readInputValue=(a,c)=>Vs(a.getUint8(c)):o==="alaw"?this.readInputValue=(a,c)=>Ls(a.getUint8(c)):h(!1);break;case 2:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint16(c,i)-2**15:o==="signed"?this.readInputValue=(a,c)=>a.getInt16(c,i):h(!1);break;case 3:o==="unsigned"?this.readInputValue=(a,c)=>lt(a,c,i)-2**23:o==="signed"?this.readInputValue=(a,c)=>ws(a,c,i):h(!1);break;case 4:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint32(c,i)-2**31:o==="signed"?this.readInputValue=(a,c)=>a.getInt32(c,i):o==="float"?this.readInputValue=(a,c)=>a.getFloat32(c,i):h(!1);break;case 8:o==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,i):h(!1);break;default:fe(s),h(!1)}switch(s){case 1:o==="ulaw"||o==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(a,c,l)=>a.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,o==="float"?(this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0);break;default:fe(s),h(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=V(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(o),i=new DataView(s);for(let d=0;d<n*this.decoderConfig.numberOfChannels;d++){let u=d*this.inputSampleSize,m=d*this.outputSampleSize,f=this.readInputValue(r,u);this.writeOutputValue(i,m,f)}let a=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=a;let l=new zt({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:c});this.onSample(l)}async flush(){}close(){}},_r=class extends Cr{constructor(e){if(!(e instanceof K))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=await this._track.getDecoderConfig();return h(n&&o),Xe.includes(o.codec)?new Pi(e,r,o):new Si(e,r,n,o)}_createPacketSink(){return new Tt(this._track)}async getSample(e){yt(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var Ut=class{constructor(e,r){this.input=e,this._backing=r}isVideoTrack(){return this instanceof Me}isAudioTrack(){return this instanceof K}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let r=new Tt(this),n=1/0,o=-1/0,s=0,i=0;for await(let a of r.packets(void 0,void 0,{metadataOnly:!0})){if(s>=e&&a.timestamp>=o)break;n=Math.min(n,a.timestamp),o=Math.max(o,a.timestamp+a.duration),s++,i+=a.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(o-n)).toPrecision(16)):0,averageBitrate:s?Number((8*i/(o-n)).toPrecision(16)):0}}},Me=class extends Ut{constructor(e,r){super(e,r),this._backing=r}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return h(r!==null),Cn.some(o=>o.supports(r,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 G))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let r=await this.getDecoderConfig();return h(r),In(this.codec,r,e.data)}},K=class extends Ut{constructor(e,r){super(e,r),this._backing=r}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 r=this._backing.getCodec();return h(r!==null),An.some(n=>n.supports(r,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 G))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Ys=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){let n=[...new Set(t.codecStrings)];r+=`; codecs="${n.join(", ")}"`}return r};var wt=8,Vt=16,Oe=t=>{let e=I(t),r=W(t,4),n=8;e===1&&(e=ce(t),n=16);let s=e-n;return s<0?null:{name:r,totalSize:e,headerSize:n,contentSize:s}},Ye=t=>ze(t)/65536,_n=t=>ze(t)/1073741824,En=t=>{let e=0;for(let r=0;r<4;r++){e<<=7;let n=F(t);if(e|=n&127,(n&128)===0)break}return e},ge=t=>{let e=X(t);return t.skip(2),e=Math.min(e,t.remainingLength),Y.decode(D(t,e))},Zs=t=>{let e=Oe(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;let r=I(t);t.skip(4);let n=D(t,e.contentSize-8);switch(r){case 1:return Y.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new Ke(n,"image/jpeg");case 14:return new Ke(n,"image/png");case 27:return new Ke(n,"image/bmp");default:return n}};var Fn=class extends te{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}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(r=>r.inputTrack.getCodecParameterString()));return Ys({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.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 r=this.reader.requestSliceRange(e,wt,Vt);if(r instanceof Promise&&(r=await r),!r)break;let n=e,o=Oe(r);if(!o)break;if(o.name==="ftyp"){let s=W(r,4);this.isQuickTime=s==="qt "}else if(o.name==="moov"){let s=this.reader.requestSlice(r.filePos,o.contentSize);if(s instanceof Promise&&(s=await s),!s)break;this.moovSlice=s,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((i,a)=>Number(a.disposition.default)-Number(i.disposition.default));for(let i of this.tracks){let a=i.editListPreviousSegmentDurations/this.movieTimescale;i.editListOffset-=Math.round(a*i.timescale)}break}e=n+o.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),h(r);let n=I(r),o=this.reader.fileSize-n;if(o>=0&&o<=this.reader.fileSize-Vt){let s=this.reader.requestSliceRange(o,wt,Vt);if(s instanceof Promise&&(s=await s),s){let i=Oe(s);if(i&&i.name==="mfra"){let a=this.reader.requestSlice(s.filePos,i.contentSize);a instanceof Promise&&(a=await a),a&&this.readContiguousBoxes(a)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,h(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&Xe.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){h(e.info?.type==="audio");let s=wn(e.info.codec),i=[],a=[];for(let c=0;c<r.sampleToChunk.length;c++){let l=r.sampleToChunk[c],d=r.sampleToChunk[c+1],u=(d?d.startChunkIndex:r.chunkOffsets.length)-l.startChunkIndex;for(let m=0;m<u;m++){let f=l.startSampleIndex+m*l.samplesPerChunk,p=f+l.samplesPerChunk,g=U(r.sampleTimingEntries,f,C=>C.startIndex),x=r.sampleTimingEntries[g],y=U(r.sampleTimingEntries,p,C=>C.startIndex),b=r.sampleTimingEntries[y],w=x.startDecodeTimestamp+(f-x.startIndex)*x.delta,S=b.startDecodeTimestamp+(p-b.startIndex)*b.delta-w,v=re(i);v&&v.delta===S?v.count++:i.push({startIndex:l.startChunkIndex+m,startDecodeTimestamp:w,count:1,delta:S});let A=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;a.push(A)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}r.sampleTimingEntries=i,r.sampleSizes=a}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let s of r.sampleTimingEntries)for(let i=0;i<s.count;i++)r.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+i*s.delta,sampleIndex:s.startIndex+i});for(let s of r.sampleCompositionTimeOffsets)for(let i=0;i<s.count;i++){let a=s.startIndex+i,c=r.presentationTimestamps[a];c&&(c.presentationTimestamp+=s.offset)}r.presentationTimestamps.sort((s,i)=>s.presentationTimestamp-i.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let s=0;s<r.presentationTimestamps.length;s++)r.presentationTimestampIndexMap[r.presentationTimestamps[s].sampleIndex]=s}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,wt,Vt);r instanceof Promise&&(r=await r),h(r);let n=Oe(r);h(n?.name==="moof");let o=this.reader.requestSlice(e,n.totalSize);o instanceof Promise&&(o=await o),h(o),this.traverseBox(o);let s=this.lastReadFragment;h(s&&s.moofOffset===e);for(let[,i]of s.trackData){let a=i.track,{fragmentPositionCache:c}=a;if(!i.startTimestampIsFinal){let d=a.fragmentLookupTable.find(u=>u.moofOffset===s.moofOffset);if(d)Ii(i,d.timestamp);else{let u=U(c,s.moofOffset-1,m=>m.moofOffset);if(u!==-1){let m=c[u];Ii(i,m.endTimestamp)}}i.startTimestampIsFinal=!0}let l=U(c,i.startTimestamp,d=>d.startTimestamp);(l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:i.startTimestamp,endTimestamp:i.endTimestamp})}return s}readContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-wt&&this.traverseBox(e););}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-wt;){let n=e.filePos,o=Oe(e);if(!o)break;yield{boxInfo:o,slice:e},e.filePos=n+o.totalSize}}traverseBox(e){let r=e.filePos,n=Oe(e);if(!n)return!1;let o=e.filePos,s=r+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mvhd":{let i=F(e);e.skip(3),i===1?(e.skip(16),this.movieTimescale=I(e),this.movieDurationInTimescale=ce(e)):(e.skip(8),this.movieTimescale=I(e),this.movieDurationInTimescale=I(e))}break;case"trak":{let i={id:-1,demuxer:this,inputTrack:null,disposition:{...se},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Z,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=i,this.readContiguousBoxes(e.slice(o,n.contentSize)),i.id!==-1&&i.timescale!==-1&&i.info!==null){if(i.info.type==="video"&&i.info.width!==-1){let a=i;i.inputTrack=new Me(this.input,new Ci(a)),this.tracks.push(i)}else if(i.info.type==="audio"&&i.info.numberOfChannels!==-1){let a=i;i.inputTrack=new K(this.input,new Ai(a)),this.tracks.push(i)}}this.currentTrack=null}break;case"tkhd":{let i=this.currentTrack;if(!i)break;let a=F(e),l=!!(Ze(e)&1);if(i.disposition.default=l,a===0)e.skip(8),i.id=I(e),e.skip(4),i.durationInMovieTimescale=I(e);else if(a===1)e.skip(16),i.id=I(e),e.skip(4),i.durationInMovieTimescale=ce(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let d=[Ye(e),Ye(e),_n(e),Ye(e),Ye(e),_n(e),Ye(e),Ye(e),_n(e)],u=ln(vs(dl(d),90));h(u===0||u===90||u===180||u===270),i.rotation=u}break;case"elst":{let i=this.currentTrack;if(!i)break;let a=F(e);e.skip(3);let c=!1,l=0,d=I(e);for(let u=0;u<d;u++){let m=a===1?ce(e):I(e),f=a===1?ea(e):ze(e),p=Ye(e);if(m!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=m;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}i.editListPreviousSegmentDurations=l,i.editListOffset=f,c=!0}}}break;case"mdhd":{let i=this.currentTrack;if(!i)break;let a=F(e);e.skip(3),a===0?(e.skip(8),i.timescale=I(e),i.durationInMediaTimescale=I(e)):a===1&&(e.skip(16),i.timescale=I(e),i.durationInMediaTimescale=ce(e));let c=X(e);if(c>0){i.languageCode="";for(let l=0;l<3;l++)i.languageCode=String.fromCharCode(96+(c&31))+i.languageCode,c>>=5;hn(i.languageCode)||(i.languageCode=Z)}}break;case"hdlr":{let i=this.currentTrack;if(!i)break;e.skip(8);let a=W(e,4);a==="vide"?i.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(i.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(o,n.contentSize))}break;case"stsd":{let i=this.currentTrack;if(!i||i.info===null||i.sampleTable)break;let a=F(e);e.skip(3);let c=I(e);for(let l=0;l<c;l++){let d=e.filePos,u=Oe(e);if(!u)break;i.internalCodecId=u.name;let m=u.name.toLowerCase();if(i.info.type==="video")m==="avc1"||m==="avc3"?(i.info.codec="avc",i.info.avcType=m==="avc1"?1:3):m==="hvc1"||m==="hev1"?i.info.codec="hevc":m==="vp08"?i.info.codec="vp8":m==="vp09"?i.info.codec="vp9":m==="av01"?i.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${u.name}').`),e.skip(24),i.info.width=X(e),i.info.height=X(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos));else{m==="mp4a"||(m==="opus"?i.info.codec="opus":m==="flac"?i.info.codec="flac":m==="twos"||m==="sowt"||m==="raw "||m==="in24"||m==="in32"||m==="fl32"||m==="fl64"||m==="lpcm"||m==="ipcm"||m==="fpcm"||(m==="ulaw"?i.info.codec="ulaw":m==="alaw"?i.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${u.name}').`))),e.skip(8);let f=X(e);e.skip(6);let p=X(e),g=X(e);e.skip(4);let x=I(e)/65536;if(a===0&&f>0){if(f===1)e.skip(4),g=8*I(e),e.skip(8);else if(f===2){e.skip(4),x=Rn(e),p=I(e),e.skip(4),g=I(e);let y=I(e);if(e.skip(8),m==="lpcm"){let b=g+7>>3,w=!!(y&1),T=!!(y&2),S=y&4?-1:0;g>0&&g<=64&&(w?g===32&&(i.info.codec=T?"pcm-f32be":"pcm-f32"):S&1<<b-1?b===1?i.info.codec="pcm-s8":b===2?i.info.codec=T?"pcm-s16be":"pcm-s16":b===3?i.info.codec=T?"pcm-s24be":"pcm-s24":b===4&&(i.info.codec=T?"pcm-s32be":"pcm-s32"):b===1&&(i.info.codec="pcm-u8")),i.info.codec===null&&console.warn("Unsupported PCM format.")}}}i.info.codec==="opus"&&(x=pt),i.info.numberOfChannels=p,i.info.sampleRate=x,m==="twos"?g===8?i.info.codec="pcm-s8":g===16?i.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${g} for codec 'twos'.`),i.info.codec=null):m==="sowt"?g===8?i.info.codec="pcm-s8":g===16?i.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${g} for codec 'sowt'.`),i.info.codec=null):m==="raw "?i.info.codec="pcm-u8":m==="in24"?i.info.codec="pcm-s24be":m==="in32"?i.info.codec="pcm-s32be":m==="fl32"?i.info.codec="pcm-f32be":m==="fl64"?i.info.codec="pcm-f64be":m==="ipcm"?i.info.codec="pcm-s16be":m==="fpcm"&&(i.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos))}}}break;case"avcC":{let i=this.currentTrack;if(!i)break;h(i.info),i.info.codecDescription=D(e,n.contentSize)}break;case"hvcC":{let i=this.currentTrack;if(!i)break;h(i.info),i.info.codecDescription=D(e,n.contentSize)}break;case"vpcC":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="video"),e.skip(4);let a=F(e),c=F(e),l=F(e),d=l>>4,u=l>>1&7,m=l&1,f=F(e),p=F(e),g=F(e);i.info.vp9CodecInfo={profile:a,level:c,bitDepth:d,chromaSubsampling:u,videoFullRangeFlag:m,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="video"),e.skip(1);let a=F(e),c=a>>5,l=a&31,d=F(e),u=d>>7,m=d>>6&1,f=d>>5&1,p=d>>4&1,g=d>>3&1,x=d>>2&1,y=d&3,b=c===2&&m?f?12:10:m?10:8;i.info.av1CodecInfo={profile:c,level:l,tier:u,bitDepth:b,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:x,chromaSamplePosition:y}}break;case"colr":{let i=this.currentTrack;if(!i||(h(i.info?.type==="video"),W(e,4)!=="nclx"))break;let c=X(e),l=X(e),d=X(e),u=!!(F(e)&128);i.info.colorSpace={primaries:un[c],transfer:dn[l],matrix:mn[d],fullRange:u}}break;case"wave":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"esds":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),e.skip(4);let a=F(e);h(a===3),En(e),e.skip(2);let c=F(e),l=(c&128)!==0,d=(c&64)!==0,u=(c&32)!==0;if(l&&e.skip(2),d){let x=F(e);e.skip(x)}u&&e.skip(2);let m=F(e);h(m===4);let f=En(e),p=e.filePos,g=F(e);if(g===64||g===103?(i.info.codec="aac",i.info.aacCodecInfo={isMpeg2:g===103}):g===105||g===107?i.info.codec="mp3":g===221?i.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),f>e.filePos-p){let x=F(e);h(x===5);let y=En(e);if(i.info.codecDescription=D(e,y),i.info.codec==="aac"){let b=hi(i.info.codecDescription);b.numberOfChannels!==null&&(i.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(i.info.sampleRate=b.sampleRate)}}}break;case"enda":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),X(e)&255&&(i.info.codec==="pcm-s16be"?i.info.codec="pcm-s16":i.info.codec==="pcm-s24be"?i.info.codec="pcm-s24":i.info.codec==="pcm-s32be"?i.info.codec="pcm-s32":i.info.codec==="pcm-f32be"?i.info.codec="pcm-f32":i.info.codec==="pcm-f64be"&&(i.info.codec="pcm-f64"))}break;case"pcmC":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),e.skip(4);let c=!!(F(e)&1),l=F(e);i.info.codec==="pcm-s16be"?c?l===16?i.info.codec="pcm-s16":l===24?i.info.codec="pcm-s24":l===32?i.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),i.info.codec=null):l===16?i.info.codec="pcm-s16be":l===24?i.info.codec="pcm-s24be":l===32?i.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),i.info.codec=null):i.info.codec==="pcm-f32be"&&(c?l===32?i.info.codec="pcm-f32":l===64?i.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),i.info.codec=null):l===32?i.info.codec="pcm-f32be":l===64?i.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),i.info.codec=null));break}case"dOps":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),e.skip(1);let a=F(e),c=X(e),l=I(e),d=Er(e),u=F(e),m;u!==0?m=D(e,2+a):m=new Uint8Array(0);let f=new Uint8Array(19+m.byteLength),p=new DataView(f.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,a),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,d,!0),p.setUint8(18,u),f.set(m,19),i.info.codecDescription=f,i.info.numberOfChannels=a}break;case"dfLa":{let i=this.currentTrack;if(!i)break;h(i.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<s;){let p=F(e),g=Ze(e);if((p&a)===Qe.STREAMINFO){e.skip(10);let y=I(e),b=y>>>12,w=(y>>9&7)+1;i.info.sampleRate=b,i.info.numberOfChannels=w,e.skip(20)}else e.skip(g);if(p&c)break}let d=e.filePos;e.filePos=l;let u=D(e,d-l),m=new Uint8Array(4+u.byteLength);new DataView(m.buffer).setUint32(0,1716281667,!1),m.set(u,4),i.info.codecDescription=m}break;case"stts":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e),c=0,l=0;for(let d=0;d<a;d++){let u=I(e),m=I(e);i.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:u,delta:m}),c+=u,l+=u*m}}break;case"ctts":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e),c=0;for(let l=0;l<a;l++){let d=I(e),u=ze(e);i.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:d,offset:u}),c+=d}}break;case"stsz":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e),c=I(e);if(a===0)for(let l=0;l<c;l++){let d=I(e);i.sampleTable.sampleSizes.push(d)}else i.sampleTable.sampleSizes.push(a)}break;case"stz2":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4),e.skip(3);let a=F(e),c=I(e),l=D(e,Math.ceil(c*a/8)),d=new L(l);for(let u=0;u<c;u++){let m=d.readBits(a);i.sampleTable.sampleSizes.push(m)}}break;case"stss":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4),i.sampleTable.keySampleIndices=[];let a=I(e);for(let c=0;c<a;c++){let l=I(e)-1;i.sampleTable.keySampleIndices.push(l)}i.sampleTable.keySampleIndices[0]!==0&&i.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e);for(let l=0;l<a;l++){let d=I(e)-1,u=I(e),m=I(e);i.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:d,samplesPerChunk:u,sampleDescriptionIndex:m})}let c=0;for(let l=0;l<i.sampleTable.sampleToChunk.length;l++)if(i.sampleTable.sampleToChunk[l].startSampleIndex=c,l<i.sampleTable.sampleToChunk.length-1){let u=i.sampleTable.sampleToChunk[l+1].startChunkIndex-i.sampleTable.sampleToChunk[l].startChunkIndex;c+=u*i.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e);for(let c=0;c<a;c++){let l=I(e);i.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let i=this.currentTrack;if(!i||!i.sampleTable)break;e.skip(4);let a=I(e);for(let c=0;c<a;c++){let l=ce(e);i.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mehd":{let i=F(e);e.skip(3);let a=i===1?ce(e):I(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let i=I(e),a=I(e),c=I(e),l=I(e),d=I(e);this.fragmentTrackDefaults.push({trackId:i,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:d})}break;case"tfra":{let i=F(e);e.skip(3);let a=I(e),c=this.tracks.find(b=>b.id===a);if(!c)break;let l=I(e),d=(l&48)>>4,u=(l&12)>>2,m=l&3,f=[F,X,Ze,I],p=f[d],g=f[u],x=f[m],y=I(e);for(let b=0;b<y;b++){let w=i===1?ce(e):I(e),T=i===1?ce(e):I(e);p(e),g(e),x(e),c.fragmentLookupTable.push({timestamp:w,moofOffset:T})}c.fragmentLookupTable.sort((b,w)=>b.timestamp-w.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){let w=c.fragmentLookupTable[b],T=c.fragmentLookupTable[b+1];w.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:r,moofSize:n.totalSize,implicitBaseDataOffset:r,trackData:new Map},this.readContiguousBoxes(e.slice(o,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(h(this.currentFragment),this.readContiguousBoxes(e.slice(o,n.contentSize)),this.currentTrack){let i=this.currentFragment.trackData.get(this.currentTrack.id);if(i){let{currentFragmentState:a}=this.currentTrack;h(a),a.startTimestamp!==null&&(Ii(i,a.startTimestamp),i.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{h(this.currentFragment),e.skip(1);let i=Ze(e),a=!!(i&1),c=!!(i&2),l=!!(i&8),d=!!(i&16),u=!!(i&32),m=!!(i&65536),f=!!(i&131072),p=I(e),g=this.tracks.find(y=>y.id===p);if(!g)break;let x=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:x?.defaultSampleDescriptionIndex??null,defaultSampleDuration:x?.defaultSampleDuration??null,defaultSampleSize:x?.defaultSampleSize??null,defaultSampleFlags:x?.defaultSampleFlags??null,startTimestamp:null},a?g.currentFragmentState.baseDataOffset=ce(e):f&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(g.currentFragmentState.sampleDescriptionIndex=I(e)),l&&(g.currentFragmentState.defaultSampleDuration=I(e)),d&&(g.currentFragmentState.defaultSampleSize=I(e)),u&&(g.currentFragmentState.defaultSampleFlags=I(e)),m&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let i=this.currentTrack;if(!i)break;h(i.currentFragmentState);let a=F(e);e.skip(3);let c=a===0?I(e):ce(e);i.currentFragmentState.startTimestamp=c}break;case"trun":{let i=this.currentTrack;if(!i)break;if(h(this.currentFragment),h(i.currentFragmentState),this.currentFragment.trackData.has(i.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let a=F(e),c=Ze(e),l=!!(c&1),d=!!(c&4),u=!!(c&256),m=!!(c&512),f=!!(c&1024),p=!!(c&2048),g=I(e),x=i.currentFragmentState.baseDataOffset;l&&(x+=ze(e));let y=null;d&&(y=I(e));let b=x;if(g===0){this.currentFragment.implicitBaseDataOffset=b;break}let w=0,T={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(i.id,T);for(let A=0;A<g;A++){let C;u?C=I(e):(h(i.currentFragmentState.defaultSampleDuration!==null),C=i.currentFragmentState.defaultSampleDuration);let R;m?R=I(e):(h(i.currentFragmentState.defaultSampleSize!==null),R=i.currentFragmentState.defaultSampleSize);let z;f?z=I(e):(h(i.currentFragmentState.defaultSampleFlags!==null),z=i.currentFragmentState.defaultSampleFlags),A===0&&y!==null&&(z=y);let B=0;p&&(a===0?B=I(e):B=ze(e));let Q=!(z&65536);T.samples.push({presentationTimestamp:w+B,duration:C,byteOffset:b,byteSize:R,isKeyFrame:Q}),b+=R,w+=C}T.presentationTimestamps=T.samples.map((A,C)=>({presentationTimestamp:A.presentationTimestamp,sampleIndex:C})).sort((A,C)=>A.presentationTimestamp-C.presentationTimestamp);for(let A=0;A<T.presentationTimestamps.length;A++){let C=T.presentationTimestamps[A],R=T.samples[C.sampleIndex];if(T.firstKeyFrameTimestamp===null&&R.isKeyFrame&&(T.firstKeyFrameTimestamp=R.presentationTimestamp),A<T.presentationTimestamps.length-1){let z=T.presentationTimestamps[A+1];R.duration=z.presentationTimestamp-C.presentationTimestamp}}let S=T.samples[T.presentationTimestamps[0].sampleIndex],v=T.samples[re(T.presentationTimestamps).sampleIndex];T.startTimestamp=S.presentationTimestamp,T.endTimestamp=v.presentationTimestamp+v.duration,this.currentFragment.implicitBaseDataOffset=b}break;case"udta":{let i=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of i){if(a.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},a.name[0]==="\xA9"?this.metadataTags.raw[a.name]??=ge(c):this.metadataTags.raw[a.name]??=D(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=Y.decode(D(c,a.contentSize)):this.metadataTags.title??=ge(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=ge(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=ge(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=ge(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=ge(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=ge(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(ge(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=ge(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=ge(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=I(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(o,n.contentSize)):this.readContiguousBoxes(e.slice(o+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let i=I(e);for(let a=0;a<i;a++){let c=I(e);e.skip(4);let l=Y.decode(D(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let i=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of i){let l=a.name,d=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(d)&&(l=this.currentMetadataKeys.get(d));let u=Zs(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=u,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof u=="string"&&(this.metadataTags.title??=u);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof u=="string"&&(this.metadataTags.description??=u);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof u=="string"&&(this.metadataTags.artist??=u);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof u=="string"&&(this.metadataTags.album??=u);break;case"aART":case"album_artist":typeof u=="string"&&(this.metadataTags.albumArtist??=u);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof u=="string"&&(this.metadataTags.comment??=u);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof u=="string"&&(this.metadataTags.genre??=u);break;case"\xA9lyr":case"lyrics":typeof u=="string"&&(this.metadataTags.lyrics??=u);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof u=="string"){let m=new Date(u);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"covr":case"com.apple.quicktime.artwork":u instanceof Ke?(this.metadataTags.images??=[],this.metadataTags.images.push({data:u.data,kind:"coverFront",mimeType:u.mimeType})):u instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:u,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof u=="string"){let m=u.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(u instanceof Uint8Array&&u.length>=6){let m=V(u),f=m.getUint16(2,!1),p=m.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(u instanceof Uint8Array&&u.length>=6){let m=V(u),f=m.getUint16(2,!1),p=m.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}},Dn=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let r=await this.fetchPacketForSampleIndex(0,e);return r||!this.internalTrack.demuxer.isFragmented?r:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return dt(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,r){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=_i(o,n),i=await this.fetchPacketForSampleIndex(s,r);return!Js(o)||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=U(c.presentationTimestamps,n,m=>m.presentationTimestamp),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},n,n,r)}async getNextPacket(e,r){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,r);let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,s=>{if(s===o.fragment){let i=s.trackData.get(this.internalTrack.id);if(o.sampleIndex+1<i.samples.length)return{sampleIndex:o.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=cl(o,n),i=await this.fetchPacketForSampleIndex(s,r);return!Js(o)||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=pn(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=n),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},n,n,r)}async getNextKeyPacket(e,r){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ul(s,n);return this.fetchPacketForSampleIndex(i,r)}let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,s=>{if(s===o.fragment){let a=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>o.sampleIndex);if(a!==-1)return{sampleIndex:a,correctSampleFound:!0}}else{let i=s.trackData.get(this.internalTrack.id);if(i&&i.firstKeyFrameTimestamp!==null){let a=i.samples.findIndex(c=>c.isKeyFrame);return h(a!==-1),{sampleIndex:a,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=ll(n,e);if(!o)return null;let s;if(r.metadataOnly)s=j;else{let l=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);l instanceof Promise&&(l=await l),h(l),s=D(l,o.sampleSize)}let i=(o.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=o.duration/this.internalTrack.timescale,c=new G(s,o.isKeyFrame?"key":"delta",i,a,e,o.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,r,n){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[r];h(s);let i;if(n.metadataOnly)i=j;else{let d=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);d instanceof Promise&&(d=await d),h(d),i=D(d,s.byteSize)}let a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new G(i,s.isKeyFrame?"key":"delta",a,c,e.moofOffset+r,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:r}),l}async performFragmentedLookup(e,r,n,o,s){let i=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:x,correctSampleFound:y}=r(e);if(y)return this.fetchPacketInFragment(e,x,s);x!==-1&&(c=e,l=x)}let d=U(this.internalTrack.fragmentLookupTable,n,x=>x.timestamp),u=d!==-1?this.internalTrack.fragmentLookupTable[d]:null,m=U(this.internalTrack.fragmentPositionCache,n,x=>x.startTimestamp),f=m!==-1?this.internalTrack.fragmentPositionCache[m]:null,p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,a=e):g=p:g=p??0;;){if(a){let w=a.trackData.get(this.internalTrack.id);if(w&&w.startTimestamp>o)break}let x=i.reader.requestSliceRange(g,wt,Vt);if(x instanceof Promise&&(x=await x),!x)break;let y=g,b=Oe(x);if(!b)break;if(b.name==="moof"){a=await i.readFragment(y);let{sampleIndex:w,correctSampleFound:T}=r(a);if(T)return this.fetchPacketInFragment(a,w,s);w!==-1&&(c=a,l=w)}g=y+b.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){let x=this.internalTrack.fragmentLookupTable[d-1];h(!x||x.timestamp<u.timestamp);let y=x?.timestamp??-1/0;return this.performFragmentedLookup(null,r,y,o,s)}return c?this.fetchPacketInFragment(c,l,s):null}},Ci=class extends Dn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Sn(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Pn(e.data)}return{codec:yn(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}},Ai=class extends Dn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Tn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},_i=(t,e)=>{if(t.presentationTimestamps){let r=U(t.presentationTimestamps,e,n=>n.presentationTimestamp);return r===-1?-1:t.presentationTimestamps[r].sampleIndex}else{let r=U(t.sampleTimingEntries,e,o=>o.startDecodeTimestamp);if(r===-1)return-1;let n=t.sampleTimingEntries[r];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},cl=(t,e)=>{if(!t.keySampleIndices)return _i(t,e);if(t.presentationTimestamps){let r=U(t.presentationTimestamps,e,n=>n.presentationTimestamp);if(r===-1)return-1;for(let n=r;n>=0;n--){let o=t.presentationTimestamps[n].sampleIndex;if(ct(t.keySampleIndices,o,i=>i)!==-1)return o}return-1}else{let r=_i(t,e),n=U(t.keySampleIndices,r,o=>o);return t.keySampleIndices[n]??-1}},ll=(t,e)=>{let r=U(t.sampleTimingEntries,e,y=>y.startIndex),n=t.sampleTimingEntries[r];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,i=U(t.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=t.sampleCompositionTimeOffsets[i];a&&e-a.startIndex<a.count&&(s+=a.offset);let c=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],l=U(t.sampleToChunk,e,y=>y.startSampleIndex),d=t.sampleToChunk[l];h(d);let u=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),m=t.chunkOffsets[u],f=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk,p=0,g=m;if(t.sampleSizes.length===1)g+=c*(e-f),p+=c*d.samplesPerChunk;else for(let y=f;y<f+d.samplesPerChunk;y++){let b=t.sampleSizes[y];y<e&&(g+=b),p+=b}let x=n.delta;if(t.presentationTimestamps){let y=t.presentationTimestampIndexMap[e];h(y!==void 0),y<t.presentationTimestamps.length-1&&(x=t.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:x,sampleOffset:g,sampleSize:c,chunkOffset:m,chunkSize:p,isKeyFrame:t.keySampleIndices?ct(t.keySampleIndices,e,y=>y)!==-1:!0}},ul=(t,e)=>{if(!t.keySampleIndices)return e+1;let r=U(t.keySampleIndices,e,n=>n);return t.keySampleIndices[r+1]??-1},Ii=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(let r of t.samples)r.presentationTimestamp+=e;for(let r of t.presentationTimestamps)r.presentationTimestamp+=e},dl=t=>{let[e,,,r]=t,n=Math.hypot(e,r),o=e/n,s=r/n,i=-Math.atan2(s,o)*(180/Math.PI);return Number.isFinite(i)?i:0},Js=t=>t.sampleSizes.length===0;var k;(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(k||(k={}));var ml=[k.EBML,k.Segment],Lt=[k.SeekHead,k.Info,k.Cluster,k.Tracks,k.Cues,k.Attachments,k.Chapters,k.Tags],Fr=[...ml,...Lt];var Ei=8,le=2,xe=2*Ei,Fi=t=>{let e=F(t);if(t.skip(-1),e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;return r},Ht=t=>{let e=F(t);if(e===0)return null;let r=1,n=128;for(;(e&n)===0;)r++,n>>=1;let o=e&n-1;for(let s=1;s<r;s++)o*=256,o+=F(t);return o},M=(t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let r=0;for(let n=0;n<e;n++)r*=256,r+=F(t);return r},ta=(t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let r=0n;for(let n=0;n<e;n++)r<<=8n,r+=BigInt(F(t));return r};var Bn=t=>{let e=Fi(t);return e===null?null:M(t,e)},Di=t=>{let e=F(t);return e===255?e=null:(t.skip(-1),e=Ht(t),e===72057594037927940&&(e=null)),e},be=t=>{let e=Bn(t);if(e===null)return null;let r=Di(t);return{id:e,size:r}},Je=(t,e)=>{let r=D(t,e),n=0;for(;n<e&&r[n]!==0;)n+=1;return String.fromCharCode(...r.subarray(0,n))},Gt=(t,e)=>{let r=D(t,e),n=0;for(;n<e&&r[n]!==0;)n+=1;return Y.decode(r.subarray(0,n))},Mn=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?ra(t):Rn(t)},On=async(t,e,r,n)=>{let o=new Set(r),s=e;for(;n===null||s<n;){let i=t.requestSliceRange(s,le,xe);if(i instanceof Promise&&(i=await i),!i)break;let a=be(i);if(!a)break;if(o.has(a.id))return{pos:s,found:!0};Ne(a.size),s=i.filePos+a.size}return{pos:n!==null&&n>s?n:s,found:!1}},Ri=async(t,e,r,n)=>{let s=new Set(r),i=e;for(;i<n;){let a=t.requestSliceRange(i,0,Math.min(65536,n-i));if(a instanceof Promise&&(a=await a),!a||a.length<Ei)break;for(let c=0;c<a.length-Ei;c++){a.filePos=i;let l=Bn(a);if(l!==null&&s.has(l))return i;i++}}return null},ye={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 Ne(t){if(t===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var na=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){let n=[...new Set(t.codecStrings.filter(Boolean))];r+=`; codecs="${n.join(", ")}"`}return r};var Ue;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(Ue||(Ue={}));var zn;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(zn||(zn={}));var Dr;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Dr||(Dr={}));var Bi=[{id:k.SeekHead,flag:"seekHeadSeen"},{id:k.Info,flag:"infoSeen"},{id:k.Tracks,flag:"tracksSeen"},{id:k.Cues,flag:"cuesSeen"}],oa=10*2**20,Nn=class extends te{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.getCodecParameterString()));return na({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,le,xe);if(r instanceof Promise&&(r=await r),!r)break;let n=be(r);if(!n)break;let o=n.id,s=n.size,i=r.filePos;if(o===k.EBML){Ne(s);let a=this.reader.requestSlice(i,s);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(o===k.Segment){if(await this.readSegment(i,s),s===null||this.reader.fileSize===null)break}else if(o===k.Cluster){if(this.reader.fileSize===null)break;s===null&&(s=(await On(this.reader,i,Fr,this.reader.fileSize)).pos-i);let a=re(this.segments);a&&(a.elementEndPos=i+s)}Ne(s),e=i+s}})()}async readSegment(e,r){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:r===null?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(n,le,xe);if(a instanceof Promise&&(a=await a),!a)break;let c=n,l=be(a);if(!l||!Lt.includes(l.id)&&l.id!==k.Void){let p=await Ri(this.reader,c,Lt,Math.min(this.currentSegment.elementEndPos??1/0,c+oa));if(p){n=p;continue}else break}let{id:d,size:u}=l,m=a.filePos,f=Bi.findIndex(p=>p.id===d);if(f!==-1){let p=Bi[f].flag;this.currentSegment[p]=!0,Ne(u);let g=this.reader.requestSlice(m,u);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(d===k.Tags||d===k.Attachments){d===k.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ne(u);let p=this.reader.requestSlice(m,u);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(d===k.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(u===null)break;n=m+u}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=Bi.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,le,xe);if(l instanceof Promise&&(l=await l),!l)continue;let d=be(l);if(!d)continue;let{id:u,size:m}=d;if(u!==c.id)continue;Ne(m),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,m);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((a,c)=>Number(c.disposition.default)-Number(a.disposition.default));let o=new Map(this.currentSegment.tracks.map(a=>[a.id,a]));for(let a of this.currentSegment.cuePoints){let c=o.get(a.trackId);c&&c.cuePoints.push(a)}for(let a of this.currentSegment.tracks){a.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<a.cuePoints.length-1;c++){let l=a.cuePoints[c],d=a.cuePoints[c+1];l.time===d.time&&(a.cuePoints.splice(c+1,1),c--)}}let s=null,i=-1/0;for(let a of this.currentSegment.tracks)a.cuePoints.length>i&&(i=a.cuePoints.length,s=a);for(let a of this.currentSegment.tracks)a.cuePoints.length===0&&(a.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let n=this.reader.requestSliceRange(e,le,xe);n instanceof Promise&&(n=await n),h(n);let o=e,s=be(n);h(s);let i=s.id;h(i===k.Cluster);let a=s.size,c=n.filePos;a===null&&(a=(await On(this.reader,c,Fr,r.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let d={segment:r,elementStartPos:o,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=d,l){let u=this.readContiguousElements(l,Fr);d.elementEndPos=u}for(let[,u]of d.trackData){let m=u.track;h(u.blocks.length>0);let f=!1;for(let y=0;y<u.blocks.length;y++){let b=u.blocks[y];b.timestamp+=d.timestamp,f||=b.lacing!==Ue.None}u.presentationTimestamps=u.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<u.presentationTimestamps.length;y++){let b=u.presentationTimestamps[y],w=u.blocks[b.blockIndex];if(u.firstKeyFrameTimestamp===null&&w.isKeyFrame&&(u.firstKeyFrameTimestamp=w.timestamp),y<u.presentationTimestamps.length-1){let T=u.presentationTimestamps[y+1];w.duration=T.timestamp-w.timestamp}else w.duration===0&&m.defaultDuration!=null&&w.lacing===Ue.None&&(w.duration=m.defaultDuration)}f&&(this.expandLacedBlocks(u.blocks,m),u.presentationTimestamps=u.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));let p=u.blocks[u.presentationTimestamps[0].blockIndex],g=u.blocks[re(u.presentationTimestamps).blockIndex];u.startTimestamp=p.timestamp,u.endTimestamp=g.timestamp+g.duration;let x=U(m.clusterPositionCache,u.startTimestamp,y=>y.startTimestamp);(x===-1||m.clusterPositionCache[x].elementStartPos!==o)&&m.clusterPositionCache.splice(x+1,0,{elementStartPos:d.elementStartPos,startTimestamp:u.startTimestamp})}return r.lastReadCluster=d,d}getTrackDataInCluster(e,r){let n=e.trackData.get(r);if(!n){let o=e.segment.tracks.find(s=>s.id===r);if(!o)return null;n={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,n)}return n}expandLacedBlocks(e,r){for(let n=0;n<e.length;n++){let o=e[n];if(o.lacing===Ue.None)continue;o.decoded||(o.data=this.decodeBlockData(r,o.data),o.decoded=!0);let s=qt.tempFromBytes(o.data),i=[],a=F(s)+1;switch(o.lacing){case Ue.Xiph:{let l=0;for(let d=0;d<a-1;d++){let u=0;for(;s.bufferPos<s.length;){let m=F(s);if(u+=m,m<255){i.push(u),l+=u;break}}}i.push(s.length-(s.bufferPos+l))}break;case Ue.FixedSize:{let l=s.length-1,d=Math.floor(l/a);for(let u=0;u<a;u++)i.push(d)}break;case Ue.Ebml:{let l=Ht(s);h(l!==null);let d=l;i.push(d);let u=d;for(let m=1;m<a-1;m++){let f=s.bufferPos,p=Ht(s);h(p!==null);let g=p,y=(1<<(s.bufferPos-f)*7-1)-1,b=g-y;d+=b,i.push(d),u+=d}i.push(s.length-(s.bufferPos+u))}break;default:h(!1)}h(i.length===a),e.splice(n,1);let c=o.duration||a*(r.defaultDuration??0);for(let l=0;l<a;l++){let d=i[l],u=D(s,d),m=o.timestamp+c*l/a,f=c/a;e.splice(n+l,0,{timestamp:m,duration:f,isKeyFrame:o.isKeyFrame,data:u,lacing:Ue.None,decoded:!0,mainAdditional:o.mainAdditional})}n+=a,n--}}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===k.Tags&&!e.tagsSeen)){if(!(r.id===k.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,le,xe);if(n instanceof Promise&&(n=await n),!n)continue;let o=be(n);if(!o||o.id!==r.id)continue;let{size:s}=o;Ne(s),h(!this.currentSegment),this.currentSegment=e;let i=this.reader.requestSlice(n.filePos,s);i instanceof Promise&&(i=await i),i&&this.readContiguousElements(i),this.currentSegment=null,r.id===k.Tags?e.tagsSeen=!0:r.id===k.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,r){let n=e.filePos;for(;e.filePos-n<=e.length-le;){let o=e.filePos;if(!this.traverseElement(e,r))return o}return e.filePos}traverseElement(e,r){let n=be(e);if(!n||r&&r.includes(n.id))return!1;let{id:o,size:s}=n,i=e.filePos;switch(Ne(s),o){case k.DocType:this.isWebM=Je(e,s)==="webm";break;case k.Seek:{if(!this.currentSegment)break;let a={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(a),this.readContiguousElements(e.slice(i,s)),(a.id===-1||a.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case k.SeekID:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.id=M(e,s)}break;case k.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=M(e,s)}break;case k.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=M(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case k.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Mn(e,s)}break;case k.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...se},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Z,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(i,s)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==zn.Block||a.data.algorithm!==Dr.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let a=this.currentTrack.codecId.indexOf("/"),c=a===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,a);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===ye.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ye.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.vp8?this.currentTrack.info.codec="vp8":c===ye.vp9?this.currentTrack.info.codec="vp9":c===ye.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,d=new Me(this.input,new Mi(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===ye.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===ye.mp3?this.currentTrack.info.codec="mp3":c===ye.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=pt):c===ye.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack,d=new K(this.input,new Oi(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case k.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=M(e,s)}break;case k.TrackType:{if(!this.currentTrack)break;let a=M(e,s);a===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:a===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case k.FlagEnabled:{if(!this.currentTrack)break;M(e,s)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case k.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!M(e,s)}break;case k.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!M(e,s)}break;case k.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!M(e,s)}break;case k.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!M(e,s)}break;case k.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!M(e,s)}break;case k.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!M(e,s)}break;case k.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Je(e,s)}break;case k.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=D(e,s)}break;case k.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*M(e,s)/1e9}break;case k.Name:{if(!this.currentTrack)break;this.currentTrack.name=Gt(e,s)}break;case k.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==Z)break;this.currentTrack.languageCode=Je(e,s),hn(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Z)}break;case k.LanguageBCP47:{if(!this.currentTrack)break;let c=Je(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Z}break;case k.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(i,s))}break;case k.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=M(e,s)}break;case k.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=M(e,s)}break;case k.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=M(e,s)===1}break;case k.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(i,s))}break;case k.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,s),c=mn[a]??null;this.currentTrack.info.colorSpace.matrix=c}break;case k.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=M(e,s)===2}break;case k.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,s),c=dn[a]??null;this.currentTrack.info.colorSpace.transfer=c}break;case k.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,s),c=un[a]??null;this.currentTrack.info.colorSpace.primaries=c}break;case k.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(i,s))}break;case k.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-Mn(e,s);try{this.currentTrack.info.rotation=ln(c)}catch{}}break;case k.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(i,s))}break;case k.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Mn(e,s)}break;case k.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=M(e,s)}break;case k.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=M(e,s)}break;case k.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(i,s)),this.currentCueTime=null}break;case k.CueTime:this.currentCueTime=M(e,s);break;case k.CueTrackPositions:{if(this.currentCueTime===null)break;h(this.currentSegment);let a={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(a),this.readContiguousElements(e.slice(i,s)),(a.trackId===-1||a.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case k.CueTrack:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;a.trackId=M(e,s)}break;case k.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;h(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+M(e,s)}break;case k.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=M(e,s)}break;case k.SimpleBlock:{if(!this.currentCluster)break;let a=Ht(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Er(e),d=F(e),u=d>>1&3,m=!!(d&128);c.track.info?.type==="audio"&&c.track.info.codec&&(m=!0);let f=D(e,s-(e.filePos-i)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:m,data:f,lacing:u,decoded:!p,mainAdditional:null})}break;case k.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(i,s)),this.currentBlock=null}break;case k.Block:{if(!this.currentCluster)break;let a=Ht(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Er(e),u=F(e)>>1&3,m=D(e,s-(e.filePos-i)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:m,lacing:u,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case k.BlockAdditions:this.readContiguousElements(e.slice(i,s));break;case k.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(i,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case k.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=D(e,s)}break;case k.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=M(e,s)}break;case k.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=M(e,s)}break;case k.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case k.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(i,s));break;case k.Targets:this.readContiguousElements(e.slice(i,s));break;case k.TargetTypeValue:M(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case k.TagTrackUID:case k.TagEditionUID:case k.TagChapterUID:case k.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case k.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(i,s))}break;case k.TagName:this.currentSimpleTagName=Gt(e,s);break;case k.TagString:{if(!this.currentSimpleTagName)break;let a=Gt(e,s);this.processTagValue(this.currentSimpleTagName,a)}break;case k.TagBinary:{if(!this.currentSimpleTagName)break;let a=D(e,s);this.processTagValue(this.currentSimpleTagName,a)}break;case k.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(i,s));let a=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(a.raw??={},a.raw[this.currentAttachedFile.fileUid.toString()]=new bn(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let d=c.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}a.images??=[],a.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case k.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=ta(e,s)}break;case k.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Gt(e,s)}break;case k.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Je(e,s)}break;case k.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=D(e,s)}break;case k.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Gt(e,s)}break;case k.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(i,s)),this.currentTrack.decodingInstructions.sort((a,c)=>c.order-a.order)}break;case k.ContentEncoding:this.currentDecodingInstruction={order:0,scope:zn.Block,data:null},this.readContiguousElements(e.slice(i,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case k.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=M(e,s)}break;case k.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=M(e,s)}break;case k.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Dr.Zlib,settings:null},this.readContiguousElements(e.slice(i,s))}break;case k.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=M(e,s)}break;case k.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=D(e,s)}break;case k.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=i+s,!0}decodeBlockData(e,r){h(e.decodingInstructions.length>0);let n=r;for(let o of e.decodingInstructions)switch(h(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case Dr.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){let s=o.data.settings,i=new Uint8Array(s.length+n.length);i.set(s,0),i.set(n,s.length),n=i}break;default:}break;default:}return n}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":n.title??=r;break;case"description":n.description??=r;break;case"artist":n.artist??=r;break;case"album":n.album??=r;break;case"album_artist":n.albumArtist??=r;break;case"genre":n.genre??=r;break;case"comment":n.comment??=r;break;case"lyrics":n.lyrics??=r;break;case"date":{let o=new Date(r);Number.isNaN(o.getTime())||(n.date??=o)}break;case"track_number":case"part_number":{let o=r.split("/"),s=Number.parseInt(o[0],10),i=o[1]&&Number.parseInt(o[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case"disc_number":case"disc":{let o=r.split("/"),s=Number.parseInt(o[0],10),i=o[1]&&Number.parseInt(o[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break}}},Un=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,r=>r.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return dt(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,r){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let s=o.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let i=U(s.presentationTimestamps,n,l=>l.timestamp),a=i!==-1?s.presentationTimestamps[i].blockIndex:-1,c=i!==-1&&n<s.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,r)}async getNextPacket(e,r){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let s=o.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(o.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let s=o.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let i=pn(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),a=i!==-1?s.presentationTimestamps[i].blockIndex:-1,c=i!==-1&&n<s.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,r)}async getNextKeyPacket(e,r){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let i=o.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>n.blockIndex);if(i!==-1)return{blockIndex:i,correctBlockFound:!0}}else{let s=o.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let i=s.blocks.findIndex(a=>a.isKeyFrame);return h(i!==-1),{blockIndex:i,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,n){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[r];h(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let i=n.metadataOnly?j:s.data,a=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,l={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?j:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);let d=new G(i,s.isKeyFrame?"key":"delta",a,c,e.dataStartPos+r,s.data.byteLength,l);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:r}),d}async performClusterLookup(e,r,n,o,s){let{demuxer:i,segment:a}=this.internalTrack,c=null,l=null,d=-1;if(e){let{blockIndex:y,correctBlockFound:b}=r(e);if(b)return this.fetchPacketInCluster(e,y,s);y!==-1&&(l=e,d=y)}let u=U(this.internalTrack.cuePoints,n,y=>y.time),m=u!==-1?this.internalTrack.cuePoints[u]:null,f=U(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,g=Math.max(m?.clusterPosition??0,p?.elementStartPos??0)||null,x;for(e?g===null||e.elementStartPos>=g?(x=e.elementEndPos,c=e):x=g:x=g??a.clusterSeekStartPos;a.elementEndPos===null||x<=a.elementEndPos-le;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>o)break}let y=i.reader.requestSliceRange(x,le,xe);if(y instanceof Promise&&(y=await y),!y)break;let b=x,w=be(y);if(!w||!Lt.includes(w.id)&&w.id!==k.Void){let C=await Ri(i.reader,b,Lt,Math.min(a.elementEndPos??1/0,b+oa));if(C){x=C;continue}else break}let T=w.id,S=w.size,v=y.filePos;if(T===k.Cluster){c=await i.readCluster(b,a),S=c.elementEndPos-v;let{blockIndex:C,correctBlockFound:R}=r(c);if(R)return this.fetchPacketInCluster(c,C,s);C!==-1&&(l=c,d=C)}S===null&&(h(T!==k.Cluster),S=(await On(i.reader,v,Fr,a.elementEndPos)).pos-v);let A=v+S;if(a.elementEndPos===null){let C=i.reader.requestSliceRange(A,le,xe);if(C instanceof Promise&&(C=await C),!C)break;if(Bn(C)===k.Segment){a.elementEndPos=A;break}}x=A}if(m&&(!l||l.elementStartPos<m.clusterPosition)){let y=this.internalTrack.cuePoints[u-1];h(!y||y.time<m.time);let b=y?.time??-1/0;return this.performClusterLookup(null,r,b,o,s)}return l?this.fetchPacketInCluster(l,d,s):null}},Mi=class extends Un{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:yn({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Rs(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Ms(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Sn(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Pn(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}},Oi=class extends Un{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:Tn({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};var fl=[44100,48e3,32e3],pl=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],ia=1483304551,sa=1231971951,hl=(t,e,r,n,o)=>e===0?0:e===1?Math.floor(144*r/(n<<t))+o:e===2?Math.floor(144*r/n)+o:(Math.floor(12*r/n)+o)*4,aa=(t,e)=>t===3?e===3?21:36:e===3?13:21,ca=(t,e)=>{let r=t>>>24,n=t>>>16&255,o=t>>>8&255,s=t&255;if(r!==255&&n!==255&&o!==255&&s!==255)return{header:null,bytesAdvanced:4};if(r!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let i=0,a=0;n&16?i=n&8?0:1:(i=1,a=1);let c=n>>3&3,l=n>>1&3,d=o>>4&15,u=(o>>2&3)%3,m=o>>1&1,f=s>>6&3,p=s>>4&3,g=s>>3&1,x=s>>2&1,y=s&3,b=pl[i*16*4+l*16+d];if(b===-1)return{header:null,bytesAdvanced:1};let w=b*1e3,T=fl[u]>>i+a,S=hl(i,l,w,T,m);if(e!==null&&e<S)return{header:null,bytesAdvanced:1};let v;return c===3?v=l===3?384:1152:l===3?v=384:l===2?v=1152:v=576,{header:{totalSize:S,mpegVersionId:c,layer:l,bitrate:w,frequencyIndex:u,sampleRate:T,channel:f,modeExtension:p,copyright:g,original:x,emphasis:y,audioSamplesInFrame:v},bytesAdvanced:1}};var Vn=t=>{let e=2130706432,r=0;for(;e!==0;)r>>=1,r|=t&e,e>>=8;return r};var jt;(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(jt||(jt={}));var $t;(function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"})($t||($t={}));var Rr=128,Xt=10,Kt=["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"],la=(t,e)=>{let r=t.filePos;e.raw??={},e.raw.TAG??=D(t,Rr-3),t.filePos=r;let n=Wt(t,30);n&&(e.title??=n);let o=Wt(t,30);o&&(e.artist??=o);let s=Wt(t,30);s&&(e.album??=s);let i=Wt(t,4),a=Number.parseInt(i,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=D(t,30),l;if(c[28]===0&&c[29]!==0){let u=c[29];u>0&&(e.trackNumber??=u),t.skip(-30),l=Wt(t,28),t.skip(2)}else t.skip(-30),l=Wt(t,30);l&&(e.comment??=l);let d=F(t);d<Kt.length&&(e.genre??=Kt[d])},Wt=(t,e)=>{let r=D(t,e),n=mt(r.indexOf(0),r.length),o=r.subarray(0,n),s="";for(let i=0;i<o.length;i++)s+=String.fromCharCode(o[i]);return s.trimEnd()},kt=t=>{let e=t.filePos,r=W(t,3),n=F(t),o=F(t),s=F(t),i=I(t);if(r!=="ID3"||n===255||o===255||(i&2155905152)!==0)return t.filePos=e,null;let a=Vn(i);return{majorVersion:n,revision:o,flags:s,size:a}},Ln=(t,e,r)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=D(t,e.size),o=new zi(e,n);if(e.flags&jt.Footer&&o.removeFooter(),e.flags&jt.Unsynchronisation&&e.majorVersion===3&&o.ununsynchronizeAll(),e.flags&jt.ExtendedHeader){let s=o.readU32();e.majorVersion===3?o.pos+=s:o.pos+=s-4}for(;o.pos<=o.bytes.length-o.frameHeaderSize();){let s=o.readId3V2Frame();if(!s)break;let i=o.pos,a=o.pos+s.size,c=!1,l=!1,d=!1;if(e.majorVersion===3?(c=!!(s.flags&64),l=!!(s.flags&128)):e.majorVersion===4&&(c=!!(s.flags&4),l=!!(s.flags&8),d=!!(s.flags&2)||!!(e.flags&jt.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${s.id}`),o.pos=a;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${s.id}`),o.pos=a;continue}switch(d&&o.ununsynchronizeRegion(o.pos,a),r.raw??={},s.id[0]==="T"?r.raw[s.id]??=o.readId3V2EncodingAndText(a):r.raw[s.id]??=o.readBytes(s.size),o.pos=i,s.id){case"TIT2":case"TT2":r.title??=o.readId3V2EncodingAndText(a);break;case"TIT3":case"TT3":r.description??=o.readId3V2EncodingAndText(a);break;case"TPE1":case"TP1":r.artist??=o.readId3V2EncodingAndText(a);break;case"TALB":case"TAL":r.album??=o.readId3V2EncodingAndText(a);break;case"TPE2":case"TP2":r.albumArtist??=o.readId3V2EncodingAndText(a);break;case"TRCK":case"TRK":{let m=o.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(r.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(r.tracksTotal??=p)}break;case"TPOS":case"TPA":{let m=o.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(r.discNumber??=f),p&&Number.isInteger(p)&&p>0&&(r.discsTotal??=p)}break;case"TCON":case"TCO":{let u=o.readId3V2EncodingAndText(a),m=/^\((\d+)\)/.exec(u);if(m){let f=Number.parseInt(m[1]);if(Kt[f]!==void 0){r.genre??=Kt[f];break}}if(m=/^\d+$/.exec(u),m){let f=Number.parseInt(m[0]);if(Kt[f]!==void 0){r.genre??=Kt[f];break}}r.genre??=u}break;case"TDRC":case"TDAT":{let u=o.readId3V2EncodingAndText(a),m=new Date(u);Number.isNaN(m.getTime())||(r.date??=m)}break;case"TYER":case"TYE":{let u=o.readId3V2EncodingAndText(a),m=Number.parseInt(u,10);Number.isInteger(m)&&(r.date??=new Date(m,0,1))}break;case"USLT":case"ULT":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),r.lyrics??=o.readId3V2Text(u,a)}break;case"COMM":case"COM":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),r.comment??=o.readId3V2Text(u,a)}break;case"APIC":case"PIC":{let u=o.readId3V2TextEncoding(),m;if(e.majorVersion===2){let x=o.readAscii(3);m=x==="PNG"?"image/png":x==="JPG"?"image/jpeg":"image/*"}else m=o.readId3V2Text(u,a);let f=o.readU8(),p=o.readId3V2Text(u,a).trimEnd(),g=a-o.pos;if(g>=0){let x=o.readBytes(g);r.images||(r.images=[]),r.images.push({data:x,mimeType:m,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:p})}}break;default:o.pos+=s.size;break}o.pos=a}},zi=class{constructor(e,r){this.header=e,this.bytes=r,this.pos=0,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let r=0;r<this.bytes.length;r++){let n=this.bytes[r];e.push(n),n===255&&r!==this.bytes.length-1&&this.bytes[r]===0&&r++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,r){let n=[];for(let i=e;i<r;i++){let a=this.bytes[i];n.push(a),a===255&&i!==r-1&&this.bytes[i+1]===0&&i++}let o=this.bytes.subarray(0,e),s=this.bytes.subarray(r);this.bytes=new Uint8Array(o.length+n.length+s.length),this.bytes.set(o,0),this.bytes.set(n,o.length),this.bytes.set(s,o.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-Xt),this.view=new DataView(this.bytes.buffer)}readBytes(e){let r=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,r}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),r=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+r}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,r}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let r=this.readU24();return{id:e,size:r,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let r=this.readU32(),n=this.header.majorVersion===4?Vn(r):r,o=this.readU16(),s=this.pos,i=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(!i(n)){let a=this.header.majorVersion===4?r:Vn(r);i(a)&&(n=a)}return this.pos=s,{id:e,size:n,flags:o}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,r){let n=this.pos,o=this.readBytes(r-this.pos);switch(e){case $t.ISO_8859_1:{let s="";for(let i=0;i<o.length;i++){let a=o[i];if(a===0){this.pos=n+i+1;break}s+=String.fromCharCode(a)}return s}case $t.UTF_16_WITH_BOM:if(o[0]===255&&o[1]===254){let s=new TextDecoder("utf-16le"),i=mt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(i+2,o.length),s.decode(o.subarray(2,i))}else if(o[0]===254&&o[1]===255){let s=new TextDecoder("utf-16be"),i=mt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(i+2,o.length),s.decode(o.subarray(2,i))}else{let s=mt(o.findIndex(i=>i===0),o.length);return this.pos=n+Math.min(s+1,o.length),Y.decode(o.subarray(0,s))}case $t.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),i=mt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(i+2,o.length),s.decode(o.subarray(0,i))}case $t.UTF_8:{let s=mt(o.findIndex(i=>i===0),o.length);return this.pos=n+Math.min(s+1,o.length),Y.decode(o.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let r=this.readId3V2TextEncoding();return this.readId3V2Text(r,e)}};var Br=async(t,e,r)=>{let n=e;for(;r===null||n<r;){let o=t.requestSlice(n,4);if(o instanceof Promise&&(o=await o),!o)break;let s=I(o),i=ca(s,t.fileSize!==null?t.fileSize-n:null);if(i.header)return{header:i.header,startPos:n};n+=i.bytesAdvanced}return null};var Hn=class extends te{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Ie,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 K(this.input,new Ni(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Xt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=kt(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await Br(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=aa(r.mpegVersionId,r.channel),o=this.reader.requestSlice(e.startPos+n,4);if(o instanceof Promise&&(o=await o),o){let a=I(o);if(a===ia||a===sa)return}this.firstFrameHeader||(this.firstFrameHeader=r),r.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${r.sampleRate} Hz. Might be a bug, so please report this file.`);let s=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,i={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(i),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,n=!1;for(;;){let o=this.reader.requestSlice(r,Xt);if(o instanceof Promise&&(o=await o),!o)break;let s=kt(o);if(!s)break;n=!0;let i=this.reader.requestSlice(o.filePos,s.size);if(i instanceof Promise&&(i=await i),!i)break;Ln(i,s,this.metadataTags),r=o.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=Rr){let o=this.reader.requestSlice(this.reader.fileSize-Rr,Rr);o instanceof Promise&&(o=await o),h(o),W(o,3)==="TAG"&&la(o,this.metadataTags)}return this.metadataTags}finally{e()}}},Ni=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Z}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...se}}async getDecoderConfig(){return h(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,r){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(r.metadataOnly)o=j;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;o=D(s,n.dataSize)}return new G(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let o=ct(this.demuxer.loadedSamples,e.timestamp,i=>i.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let s=o+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{n()}}async getPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=U(this.demuxer.loadedSamples,e,s=>s.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,r);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,r);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var Ui=1399285583,gl=79764919,da=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let r=0;r<8;r++)e=e&2147483648?e<<1^gl:e<<1;da[t]=e>>>0&4294967295}var ma=t=>{let e=V(t),r=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let o=0;o<t.length;o++){let s=t[o];n=(n<<8^da[n>>>24^s])>>>0}return e.setUint32(22,r,!0),n},fa=(t,e,r)=>{let n=0,o=null;if(t.length>0)if(e.codec==="vorbis"){h(e.vorbisInfo);let s=e.vorbisInfo.modeBlockflags.length,a=(1<<Ss(s-1))-1<<1,c=(t[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=r,d=e.vorbisInfo.modeBlockflags[c];if(o=e.vorbisInfo.blocksizes[d],d===1){let u=(a|1)+1,m=t[0]&u?1:0;l=e.vorbisInfo.blocksizes[m]}n=l!==null?l+o>>2:0}else e.codec==="opus"&&(n=Ns(t).durationInSamples);return{durationInSamples:n,vorbisBlockSize:o}},pa=t=>{let e="audio/ogg";if(t.codecStrings){let r=[...new Set(t.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e};var et=27,St=282,ha=St+65025,Qt=t=>{let e=t.filePos;if(vt(t)!==Ui)return null;t.skip(1);let n=F(t),o=xa(t),s=vt(t),i=vt(t),a=vt(t),c=F(t),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=F(t);let d=27+c,u=l.reduce((f,p)=>f+p,0),m=d+u;return{headerStartPos:e,totalSize:m,dataStartPos:e+d,dataSize:u,headerType:n,granulePosition:o,serialNumber:s,sequenceNumber:i,checksum:a,lacingValues:l}},ga=(t,e)=>{for(;t.filePos<e-3;){let r=vt(t),n=r&255,o=r>>>8&255,s=r>>>16&255,i=r>>>24&255,a=79;if(!(n!==a&&o!==a&&s!==a&&i!==a)){if(t.skip(-4),r===Ui)return!0;t.skip(1)}}return!1};var Gn=class extends te{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 r=this.reader.requestSliceRange(e,et,St);if(r instanceof Promise&&(r=await r),!r)break;let n=Qt(r);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let r of this.bitstreams){let n=await this.readPacket(r.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,r):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,r),r.codecInfo.codec!==null&&this.tracks.push(new K(this.input,new Vi(r,this))))}})()}async readVorbisMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o||(n=await this.findNextPacketStart(o),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||o.data[0]!==3||s.data[0]!==5)return;let i=[],a=u=>{for(;i.push(Math.min(255,u)),!(u<255);)u-=255};a(e.data.length),a(o.data.length);let c=new Uint8Array(1+i.length+e.data.length+o.data.length+s.data.length);c[0]=2,c.set(i,1),c.set(e.data,1+i.length),c.set(o.data,1+i.length+e.data.length),c.set(s.data,1+i.length+e.data.length+o.data.length),r.codecInfo.codec="vorbis",r.description=c,r.lastMetadataPacket=s;let l=V(e.data);r.numberOfChannels=l.getUint8(11),r.sampleRate=l.getUint32(12,!0);let d=l.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(d&15),1<<(d>>4)],modeBlockflags:Us(s.data).modeBlockflags},kr(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=o;let s=zs(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=pt,r.codecInfo.opusInfo={preSkip:s.preSkip},kr(o.data.subarray(8),this.metadataTags)}async readPacket(e,r){h(r<e.lacingValues.length);let n=0;for(let u=0;u<r;u++)n+=e.lacingValues[u];let o=e,s=n,i=r,a=[];e:for(;;){let u=this.reader.requestSlice(o.dataStartPos,o.dataSize);u instanceof Promise&&(u=await u),h(u);let m=D(u,o.dataSize);for(;;){if(i===o.lacingValues.length){a.push(m.subarray(n,s));break}let p=o.lacingValues[i];if(s+=p,p<255){a.push(m.subarray(n,s));break e}i++}let f=o.headerStartPos+o.totalSize;for(;;){let p=this.reader.requestSliceRange(f,et,St);if(p instanceof Promise&&(p=await p),!p)return null;let g=Qt(p);if(!g)return null;if(o=g,o.serialNumber===e.serialNumber)break;f=o.headerStartPos+o.totalSize}n=0,s=0,i=0}let c=a.reduce((u,m)=>u+m.length,0),l=new Uint8Array(c),d=0;for(let u=0;u<a.length;u++){let m=a[u];l.set(m,d),d+=m.length}return{data:l,endPage:o,endSegmentIndex:i}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let o=this.reader.requestSliceRange(n,et,St);if(o instanceof Promise&&(o=await o),!o)return null;let s=Qt(o);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};n=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return pa({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...r)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Vi=class{constructor(e,r){this.bitstream=e,this.demuxer=r,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Ie,this.internalSampleRate=e.codecInfo.codec==="opus"?pt:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return h(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Z}getDisposition(){return{...se}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(h(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,r,n){if(!e)return null;let{durationInSamples:o,vorbisBlockSize:s}=fa(e.data,this.bitstream.codecInfo,r.vorbisLastBlocksize),i=new G(n.metadataOnly?j:e.data,"key",Math.max(0,r.timestampInSamples)/this.internalSampleRate,o/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(i,{packet:e,timestampInSamples:r.timestampInSamples,durationInSamples:o,vorbisLastBlockSize:r.vorbisLastBlocksize,vorbisBlockSize:s}),i}async getFirstPacket(e){h(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(h(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let o=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,r){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let o=await this.demuxer.findNextPacketStart(n.packet);if(!o)return null;let s=n.timestampInSamples+n.durationInSamples,i=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:s,vorbisLastBlocksize:n.vorbisBlockSize},r)}async getPacket(e,r){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,r);let n=dt(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(r);if(n<0)return null;h(this.bitstream.lastMetadataPacket);let o=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!o)return null;let s=o.startPage,i=this.demuxer.reader.fileSize,a=[s];e:for(;s.headerStartPos+s.totalSize<i;){let b=s.headerStartPos,w=Math.floor((b+i)/2),T=w;for(;;){let S=Math.min(T+ha,i-et),v=this.demuxer.reader.requestSlice(T,S-T);if(v instanceof Promise&&(v=await v),h(v),!ga(v,S)){i=w+et;continue e}let C=this.demuxer.reader.requestSliceRange(v.filePos,et,St);C instanceof Promise&&(C=await C),h(C);let R=Qt(C);h(R);let z=!1;if(R.serialNumber===this.bitstream.serialNumber)z=!0;else{let Q=this.demuxer.reader.requestSlice(R.headerStartPos,R.totalSize);Q instanceof Promise&&(Q=await Q),h(Q);let st=D(Q,R.totalSize);z=ma(st)===R.checksum}if(!z){T=R.headerStartPos+4;continue}if(z&&R.serialNumber!==this.bitstream.serialNumber){T=R.headerStartPos+R.totalSize;continue}if(R.granulePosition===-1){T=R.headerStartPos+R.totalSize;continue}this.granulePositionToTimestampInSamples(R.granulePosition)>n?i=R.headerStartPos:(s=R,a.push(R));continue e}}let c=o.startPage;for(let b of a){if(b.granulePosition===s.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c,d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){let b=l.headerStartPos+l.totalSize,w=this.demuxer.reader.requestSliceRange(b,et,St);w instanceof Promise&&(w=await w),h(w);let T=Qt(w);h(T),l=T,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}h(l.granulePosition!==-1);let u=null,m,f,p=l,g=0;if(l.headerStartPos===o.startPage.headerStartPos)m=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{m=0,f=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){u=T+1;break}if(u===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=u-1;let b={data:j,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(b)){let T=ya(d,l,u);h(T);let S=ba(d,T.page,T.segmentIndex);S&&(l=S.page,u=S.segmentIndex)}else for(;;){let T=ya(d,l,u);if(!T)break;let S=ba(d,T.page,T.segmentIndex);if(!S)break;if(l=S.page,u=S.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,g=T.segmentIndex;break}}}let x=null,y=null;for(;l!==null;){h(u!==null);let b=await this.demuxer.readPacket(l,u);if(!b)break;if(!(l.headerStartPos===o.startPage.headerStartPos&&u<o.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:m,vorbisLastBlocksize:y?.vorbisBlockSize??null},r);h(S);let v=this.encodedPacketToMetadata.get(S);if(h(v),!f&&b.endPage.headerStartPos===p.headerStartPos&&b.endSegmentIndex===g?(m=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,S=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:m-v.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},r),h(S),v=this.encodedPacketToMetadata.get(S),h(v)):m+=v.durationInSamples,x=S,y=v,f&&(Math.max(m,0)>n||Math.max(v.timestampInSamples,0)===n))break}let T=await this.demuxer.findNextPacketStart(b);if(!T)break;l=T.startPage,u=T.startSegmentIndex}return x}async getPacketSequential(e,r){let n=await this.sequentialScanMutex.acquire();try{let o=dt(e*this.internalSampleRate);e=o/this.internalSampleRate;let s=U(this.sequentialScanCache,o,c=>c.timestampInSamples),i;if(s!==-1){let c=this.sequentialScanCache[s];i=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},r)}else i=await this.getFirstPacket(r);let a=0;for(;i&&i.timestamp<e;){let c=await this.getNextPacket(i,r);if(!c||c.timestamp>e)break;if(i=c,a++,a===100){a=0;let l=this.encodedPacketToMetadata.get(i);h(l),this.sequentialScanCache.length>0&&h(re(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return i}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}},ba=(t,e,r)=>{let n=e,o=r;e:for(;;){for(o--,o;o>=0;o--)if(n.lacingValues[o]<255){o++;break e}if(h(o===-1),!(n.headerType&1)){o=0;break}let i=ui(t,a=>a.headerStartPos<n.headerStartPos);if(!i)return null;n=i,o=n.lacingValues.length}if(h(o!==-1),o===n.lacingValues.length){let s=t[t.indexOf(n)+1];h(s),n=s,o=0}return{page:n,segmentIndex:o}},ya=(t,e,r)=>{if(r>0)return{page:e,segmentIndex:r-1};let n=ui(t,o=>o.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var Ve;(function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"})(Ve||(Ve={}));var qn=class extends te{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),h(e);let r=W(e,4),n=r!=="RIFX",o=r==="RF64",s=Le(e,n),i=o?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(W(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,d=e.filePos;for(;i===null||d<i;){let m=this.reader.requestSlice(d,8);if(m instanceof Promise&&(m=await m),!m)break;let f=W(m,4),p=Le(m,n),g=m.filePos;if(o&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(g,p,n);else if(f==="data"){if(l??=p,this.dataStart=m.filePos,this.dataSize=Math.min(l,(i??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let x=this.reader.requestSlice(g,p);if(x instanceof Promise&&(x=await x),!x)break;let y=Hi(x,n);l=Hi(x,n),i=Math.min(y+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(g,p,n):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(g,p);d=g+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new K(this.input,new Li(this)))})()}async parseFmtChunk(e,r,n){let o=this.reader.requestSlice(e,r);if(o instanceof Promise&&(o=await o),!o)return;let s=Zt(o,n),i=Zt(o,n),a=Le(o,n);o.skip(4);let c=Zt(o,n),l;if(r===14?l=8:l=Zt(o,n),r>=18&&s!==357){let d=Zt(o,n),u=r-18;if(Math.min(u,d)>=22&&s===Ve.EXTENSIBLE){o.skip(6);let f=D(o,16);s=f[0]|f[1]<<8}}(s===Ve.MULAW||s===Ve.ALAW)&&(l=8),this.audioInfo={format:s,numberOfChannels:i,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,r,n){let o=this.reader.requestSlice(e,r);if(o instanceof Promise&&(o=await o),!o)return;let s=W(o,4);if(s!=="INFO"&&s!=="INF0")return;let i=o.filePos;for(;i<=e+r-8;){o.filePos=i;let a=W(o,4),c=Le(o,n),l=D(o,c),d=0;for(let m=0;m<l.length&&l[m]!==0;m++)d++;let u=String.fromCharCode(...l.subarray(0,d));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=u,a){case"INAM":case"TITL":this.metadataTags.title??=u;break;case"TIT3":this.metadataTags.description??=u;break;case"IART":this.metadataTags.artist??=u;break;case"IPRD":this.metadataTags.album??=u;break;case"IPRT":case"ITRK":case"TRCK":{let m=u.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let m=new Date(u);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"YEAR":{let m=Number.parseInt(u,10);Number.isInteger(m)&&m>0&&(this.metadataTags.date??=new Date(m,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=u;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=u;break}i+=8+c+(c&1)}}async parseId3Chunk(e,r){let n=this.reader.requestSlice(e,r);if(n instanceof Promise&&(n=await n),!n)return;let o=kt(n);if(o){let s=n.slice(e+10,o.size);Ln(s,o,this.metadataTags)}}getCodec(){if(h(this.audioInfo),this.audioInfo.format===Ve.MULAW)return"ulaw";if(this.audioInfo.format===Ve.ALAW)return"alaw";if(this.audioInfo.format===Ve.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===Ve.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Yt=2048,Li=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(h(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getDisposition(){return{...se}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,r){h(this.demuxer.audioInfo);let n=e*Yt*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let o=Math.min(Yt*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);if(c instanceof Promise&&(c=await c),!c)return null}let s;if(r.metadataOnly)s=j;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);c instanceof Promise&&(c=await c),h(c),s=D(c,o)}let i=e*Yt/this.demuxer.audioInfo.sampleRate,a=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,i),new G(s,"key",i,a,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,r){h(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Yt,(this.demuxer.dataSize-1)/(Yt*this.demuxer.audioInfo.blockSizeInBytes))),o=await this.getPacketAtIndex(n,r);if(o)return o;if(n===0)return null;h(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,r);for(;s;){let i=await this.getNextPacket(s,r);if(!i)break;s=i}return s}getNextPacket(e,r){h(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Yt);return this.getPacketAtIndex(n+1,r)}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var Jt=7,er=9,Mr=t=>{let e=t.filePos,r=D(t,9),n=new L(r);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let i=n.readBits(1),a=n.readBits(2)+1,c=n.readBits(4);if(c===15)return null;n.skipBits(1);let l=n.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let d=n.readBits(13);n.skipBits(11);let u=n.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;return i===1?t.filePos-=2:m=n.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:d,numberOfAacFrames:u,crcCheck:m,startPos:e}};var Gi=1024,Wn=class extends te{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new Ie,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();h(this.firstFrameHeader),this.tracks=[new K(this.input,new qi(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,Jt,er);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=Mr(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let n=wr[r.samplingFrequencyIndex];h(n!==void 0);let o=Gi/n,s=r.crcCheck?er:Jt,i={timestamp:this.nextTimestampInSamples/n,duration:o,dataStart:r.startPos+s,dataSize:r.frameLength-s};this.loadedSamples.push(i),this.nextTimestampInSamples+=Gi,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){return{}}},qi=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Gi}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Z}getCodec(){return"aac"}getInternalCodecId(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){h(this.demuxer.firstFrameHeader);let e=pi[this.demuxer.firstFrameHeader.channelConfiguration];return h(e!==void 0),e}getSampleRate(){h(this.demuxer.firstFrameHeader);let e=wr[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return h(e!==void 0),e}getDisposition(){return{...se}}async getDecoderConfig(){h(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),r=new L(e),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:s}=this.demuxer.firstFrameHeader;return n>31?(r.writeBits(5,31),r.writeBits(6,n-32)):r.writeBits(5,n),r.writeBits(4,o),r.writeBits(4,s),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((r.pos-1)/8))}}async getPacketAtIndex(e,r){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(r.metadataOnly)o=j;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;o=D(s,n.dataSize)}return new G(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let o=ct(this.demuxer.loadedSamples,e.timestamp,i=>i.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let s=o+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{n()}}async getPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=U(this.demuxer.loadedSamples,e,s=>s.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,r);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,r);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var Ta=t=>t===0?null:t===1?192:t>=2&&t<=5?144*2**t:t===6?"uncommon-u8":t===7?"uncommon-u16":t>=8&&t<=15?2**t:null,wa=(t,e)=>{switch(t){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},ka=t=>{let e=0,r=new L(D(t,1));for(;r.readBits(1)===1;)e++;if(e===0)return r.readBits(7);let n=[],o=e-1,s=new L(D(t,o)),i=8-e-1;for(let c=0;c<i;c++)n.unshift(r.readBits(1));for(let c=0;c<o;c++)for(let l=0;l<8;l++){let d=s.readBits(1);l<2||n.unshift(d)}return n.reduce((c,l,d)=>c|l<<d,0)},va=(t,e)=>{if(e==="uncommon-u16")return X(t)+1;if(e==="uncommon-u8")return F(t)+1;if(typeof e=="number")return e;fe(e),h(!1)},Sa=(t,e)=>e==="uncommon-u16"?X(t):e==="uncommon-u16-10"?X(t)*10:e==="uncommon-u8"?F(t):typeof e=="number"?e:null,Pa=t=>{let r=0;for(let n of t){r^=n;for(let o=0;o<8;o++)(r&128)!==0?r=r<<1^7:r<<=1,r&=255}return r};var jn=class extends te{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Ie,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),h(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),h(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);h(r);let n=F(r),o=Ze(r),s=(n&128)!==0;switch(n&127){case Qe.STREAMINFO:{let a=this.reader.requestSlice(e,o);if(a instanceof Promise&&(a=await a),h(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=D(a,34),l=new L(c),d=l.readBits(16),u=l.readBits(16),m=l.readBits(24),f=l.readBits(24),p=l.readBits(20),g=l.readBits(3)+1;l.readBits(5);let x=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:g,sampleRate:p,totalSamples:x,minimumBlockSize:d,maximumBlockSize:u,minimumFrameSize:m,maximumFrameSize:f,description:y},this.track=new K(this.input,new Wi(this));break}case Qe.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),h(a),kr(D(a,o),this.metadataTags);break}case Qe.PICTURE:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),h(a);let c=I(a),l=I(a),d=Y.decode(D(a,l)),u=I(a),m=Y.decode(D(a,u));a.skip(16);let f=I(a),p=D(a,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:d,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:m});break}default:break}if(e+=o,s){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:r}){h(this.audioInfo);let n=6,s=this.audioInfo.maximumFrameSize+16,i=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,s);if(!i)return null;let a=this.readFlacFrameHeader({slice:i,isFirstPacket:r});if(!a)return null;for(i.filePos=e+this.audioInfo.minimumFrameSize;;){if(i.filePos>i.end-n)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:i.end-e,isLastFrame:!0};if(F(i)===255){let l=i.filePos,d=F(i),u=this.blockingBit===1?249:248;if(d!==u){i.filePos=l;continue}i.skip(-2);let m=i.filePos-e,f=this.readFlacFrameHeader({slice:i,isFirstPacket:!1});if(!f){i.filePos=l;continue}if(this.blockingBit===0){if(f.num-a.num!==1){i.filePos=l;continue}}else if(f.num-a.num!==a.blockSize){i.filePos=l;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:m,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){let n=e.filePos,o=D(e,4),s=new L(o);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){h(r);let x=s.readBits(1);this.blockingBit=x}else if(this.blockingBit===1){if(h(!r),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(h(!r),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=Ta(s.readBits(4));if(!a)return null;h(this.audioInfo);let c=wa(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let d=ka(e),u=va(e,a),m=Sa(e,c);if(m===null||m!==this.audioInfo.sampleRate)return null;let f=e.filePos-n,p=F(e);e.skip(-f),e.skip(-1);let g=Pa(D(e,f));return p!==g?null:{num:d,blockSize:u,sampleRate:m}}async advanceReader(){await this.readMetadata(),h(this.lastLoadedPos!==null),h(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!r){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(s),r.isLastFrame){this.lastSampleLoaded=!0;return}}},Wi=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...se}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return h(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,r){if(h(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=U(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(o===-1){await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[o],i=s.blockOffset/this.demuxer.audioInfo.sampleRate,a=s.blockSize/this.demuxer.audioInfo.sampleRate;if(i+a<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,r);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(o,r)}}finally{n()}}async getNextPacket(e,r){let n=await this.demuxer.readingMutex.acquire();try{let o=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&o>=this.demuxer.loadedSamples.length)return null;for(;o>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(o,r)}finally{n()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}async getPacketAtIndex(e,r){let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(r.metadataOnly)o=j;else{let a=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;o=D(a,n.byteSize)}h(this.demuxer.audioInfo);let s=n.blockOffset/this.demuxer.audioInfo.sampleRate,i=n.blockSize/this.demuxer.audioInfo.sampleRate;return new G(o,"key",s,i,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var pe=class{},Or=class extends pe{async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);return r instanceof Promise&&(r=await r),!r||(r.skip(4),W(r,4)!=="ftyp")?null:W(r,4)}_createDemuxer(e){return new Fn(e)}},$n=class extends Or{async _canReadInput(e){let r=await this._getMajorBrand(e);return!!r&&r!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Kn=class extends Or{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},zr=class extends pe{async isSupportedEBMLOfDocType(e,r){let n=e._reader.requestSlice(0,xe);if(n instanceof Promise&&(n=await n),!n)return!1;let o=Fi(n);if(o===null||o<1||o>8||M(n,o)!==k.EBML)return!1;let i=Di(n);if(i===null)return!1;let a=e._reader.requestSlice(n.filePos,i);if(a instanceof Promise&&(a=await a),!a)return!1;let c=n.filePos;for(;a.filePos<=c+i-le;){let l=be(a);if(!l)break;let{id:d,size:u}=l,m=a.filePos;if(u===null)return!1;switch(d){case k.EBMLVersion:if(M(a,u)!==1)return!1;break;case k.EBMLReadVersion:if(M(a,u)!==1)return!1;break;case k.DocType:if(Je(a,u)!==r)return!1;break;case k.DocTypeVersion:if(M(a,u)>4)return!1;break}a.filePos=m+u}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Nn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Xn=class extends zr{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Qn=class extends pe{async _canReadInput(e){let r=e._reader.requestSlice(0,10);if(r instanceof Promise&&(r=await r),!r)return!1;let n=0,o=!1;for(;;){let l=e._reader.requestSlice(n,Xt);if(l instanceof Promise&&(l=await l),!l)break;let d=kt(l);if(!d)break;o=!0,n=l.filePos+d.size}let s=await Br(e._reader,n,n+4096);if(!s)return!1;if(o)return!0;n=s.startPos+s.header.totalSize;let i=await Br(e._reader,n,n+4);if(!i)return!1;let a=s.header,c=i.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new Hn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Yn=class extends pe{async _canReadInput(e){let r=e._reader.requestSlice(0,12);if(r instanceof Promise&&(r=await r),!r)return!1;let n=W(r,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(r.skip(4),W(r,4)==="WAVE")}_createDemuxer(e){return new qn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Zn=class extends pe{async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?W(r,4)==="OggS":!1}_createDemuxer(e){return new Gn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Jn=class extends pe{async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?W(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new jn(e)}},eo=class extends pe{async _canReadInput(e){let r=e._reader.requestSliceRange(0,Jt,er);if(r instanceof Promise&&(r=await r),!r)return!1;let n=Mr(r);if(!n||(r=e._reader.requestSliceRange(n.frameLength,Jt,er),r instanceof Promise&&(r=await r),!r))return!1;let o=Mr(r);return o?n.objectType===o.objectType&&n.samplingFrequencyIndex===o.samplingFrequencyIndex&&n.channelConfiguration===o.channelConfiguration:!1}_createDemuxer(e){return new Wn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Ia=new $n,Ca=new Kn,Aa=new zr,_a=new Xn,Ea=new Qn,Fa=new Yn,Da=new Zn,Ra=new eo,Ba=new Jn,Te=[Ia,Ca,Aa,_a,Fa,Da,Ba,Ea,Ra];var Pt=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new $;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new $;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var Nr=class extends Pt{constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!Tr(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new to({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Oa.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!$e()?r=this._blob.slice(e.currentPos).stream().getReader():r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){let{done:n,value:o}=await r.read();if(n)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}e.running=!1,e.aborted&&await r?.cancel()}_dispose(){this._orchestrator.dispose()}},Ma=.5*2**20,xl=((t,e,r)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let o=null;try{typeof window<"u"&&typeof window.location<"u"&&(o=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&o!==null&&o!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(t-2),16)}),Ur=class extends Pt{constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!Tr(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??xl,this._orchestrator=new to({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Oa.network})}async _retrieveSize(){let e=new AbortController,r=await mi(this._options.fetchFn??fetch,this._url,di(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);let n,o;if(r.status===206)o=this._getTotalLengthFromRangeResponse(r),n=this._orchestrator.createWorker(0,Math.min(o,Ma));else{let s=r.headers.get("Content-Length");if(s)o=Number(s),n=this._orchestrator.createWorker(0,o),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=o,this._existingResponses.set(n,{response:r,abortController:e}),this._orchestrator.runWorker(n),o}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;;){let r=this._existingResponses.get(e);this._existingResponses.delete(e);let n=r?.abortController,o=r?.response;if(n||(n=new AbortController,o=await mi(this._options.fetchFn??fetch,this._url,di(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),h(o),!o.ok)throw new Error(`Error fetching ${String(this._url)}: ${o.status} ${o.statusText}`);if(e.currentPos>0&&o.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!o.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let s=o.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let i;try{i=await s.read()}catch(l){if(this._disposed)throw l;let d=this._getRetryDelay(1,l,this._url);if(d!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(u=>setTimeout(u,1e3*d));break}else throw l}if(e.aborted)continue;let{done:a,value:c}=i;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let r=e.headers.get("Content-Range");if(r){let o=/\/(\d+)/.exec(r);if(o)return Number(o[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var Oa={none:(t,e)=>({start:t,end:e}),fileSystem:(t,e)=>(t=Math.floor((t-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:t,end:e}),network:(t,e,r)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(let o of r){let i=Math.max((o.startPos+o.targetPos)/2,o.targetPos-8388608);if(gn(t,e,i,o.targetPos)){let a=o.targetPos-o.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),d=Math.min(l,c);e=Math.max(e,o.startPos+d)}}return e=Math.max(e,t+Ma),{start:t,end:e}}},to=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){h(this.fileSize!==null);let n=this.options.prefetchProfile(e,r,this.workers),o=Math.max(n.start,0),s=Math.min(n.end,this.fileSize);h(o<=e&&r<=s);let i=null,a=U(this.cache,e,b=>b.start),c=a!==-1?this.cache[a]:null;c&&c.start<=e&&r<=c.end&&(c.age=this.nextAge++,i={bytes:c.bytes,view:c.view,offset:c.start});let l=U(this.cache,o,b=>b.start),d=i?null:new Uint8Array(r-e),u=0,m=o,f=[];if(l!==-1){for(let b=l;b<this.cache.length;b++){let w=this.cache[b];if(w.start>=s)break;if(w.end<=o)continue;let T=Math.max(o,w.start),S=Math.min(s,w.end);if(h(T<=S),m<T&&f.push({start:m,end:T}),m=S,d){let v=Math.max(e,w.start),A=Math.min(r,w.end);if(v<A){let C=v-e;d.set(w.bytes.subarray(v-w.start,A-w.start),C),C===u&&(u=A-e)}}w.age=this.nextAge++}m<s&&f.push({start:m,end:s})}else f.push({start:o,end:s});if(d&&u>=d.length&&(i={bytes:d,view:V(d),offset:e}),f.length===0)return h(i),i;let{promise:p,resolve:g,reject:x}=ne(),y=[];for(let b of f){let w=Math.max(e,b.start),T=Math.min(r,b.end);w===b.start&&T===b.end?y.push(b):w<T&&y.push({start:w,end:T})}for(let b of f){let w=d&&{start:e,bytes:d,holes:y,resolve:g,reject:x},T=!1;for(let S of this.workers)if(gn(b.start-131072,b.start,S.currentPos,S.targetPos)){S.targetPos=Math.max(S.targetPos,b.end),T=!0,w&&!S.pendingSlices.includes(w)&&S.pendingSlices.push(w),S.running||this.runWorker(S);break}if(!T){let S=this.createWorker(b.start,b.end);w&&(S.pendingSlices=[w]),this.runWorker(S)}}return i||(h(d),i=p.then(b=>({bytes:b,view:V(b),offset:e}))),i}createWorker(e,r){let n={startPos:e,currentPos:e,targetPos:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let o=0,s=this.workers[0];for(let i=1;i<this.workers.length;i++){let a=this.workers[i];a.age<s.age&&(o=i,s=a)}if(s.running&&s.pendingSlices.length>0)break;s.aborted=!0,this.workers.splice(o,1)}return n}runWorker(e){h(!e.running),h(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(r=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(r)),e.pendingSlices.length=0;else throw r})}supplyWorkerData(e,r){h(!e.aborted);let n=e.currentPos,o=n+r.length;this.insertIntoCache({start:n,end:o,bytes:r,view:V(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let s=0;s<e.pendingSlices.length;s++){let i=e.pendingSlices[s],a=Math.max(n,i.start),c=Math.min(o,i.start+i.bytes.length);a<c&&i.bytes.set(r.subarray(a-n,c-n),a-i.start);for(let l=0;l<i.holes.length;l++){let d=i.holes[l];n<=d.start&&o>d.start&&(d.start=o),d.end<=d.start&&(i.holes.splice(l,1),l--)}i.holes.length===0&&(i.resolve(i.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let i=this.workers[s];e===i||i.running||gn(n,o,i.currentPos,i.targetPos)&&(this.workers.splice(s,1),s--)}}forgetWorker(e){let r=this.workers.indexOf(e);h(r!==-1),this.workers.splice(r,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let r=U(this.cache,e.start,n=>n.start)+1;if(r>0){let n=this.cache[r-1];if(n.end>=e.end)return;if(n.end>e.start){let o=new Uint8Array(e.end-n.start);o.set(n.bytes,0),o.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=o,n.view=V(o),n.end=e.end,r--,e=n}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length;for(let n=r+1;n<this.cache.length;n++){let o=this.cache[n];if(e.end<=o.start)break;if(e.end>=o.end){this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length,n--;continue}let s=new Uint8Array(o.end-e.start);s.set(e.bytes,0),s.set(o.bytes,o.start-e.start),this.currentCacheSize-=e.end-o.start,e.bytes=s,e.view=V(s),e.end=o.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,o=this.cache[0];for(let s=1;s<this.cache.length;s++){let i=this.cache[s];i.age<o.age&&(n=s,o=i)}if(this.currentCacheSize-o.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};xn();var ue=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof pe)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Pt))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new ro(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),h(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(r=>r.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(r=>r.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(r=>r.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(r=>r.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},$=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var ro=class{constructor(e){this.source=e}requestSlice(e,r){if(this.source._disposed)throw new $;if(this.fileSize!==null&&e+r>this.fileSize)return null;let n=e+r,o=this.source._read(e,n);return o instanceof Promise?o.then(s=>s?new qt(s.bytes,s.view,s.offset,e,n):null):o?new qt(o.bytes,o.view,o.offset,e,n):null}requestSliceRange(e,r,n){if(this.source._disposed)throw new $;if(this.fileSize!==null)return this.requestSlice(e,ut(this.fileSize-e,r,n));{let o=this.requestSlice(e,n),s=i=>{if(i)return i;let a=l=>(h(l!==null),this.requestSlice(e,ut(l-e,r,n))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return o instanceof Promise?o.then(s):s(o)}}},qt=class t{constructor(e,r,n,o,s){this.bytes=e,this.view=r,this.offset=n,this.start=o,this.end=s,this.bufferPos=o-n}static tempFromBytes(e){return new t(e,V(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,r=this.end-e){if(e<this.start||e+r>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+r)}},ae=(t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},D=(t,e)=>{ae(t,e);let r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},F=t=>(ae(t,1),t.view.getUint8(t.bufferPos++)),Zt=(t,e)=>{ae(t,2);let r=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,r},X=t=>{ae(t,2);let e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},Ze=t=>{ae(t,3);let e=lt(t.view,t.bufferPos,!1);return t.bufferPos+=3,e},Er=t=>{ae(t,2);let e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},Le=(t,e)=>{ae(t,4);let r=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,r},I=t=>{ae(t,4);let e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},vt=t=>{ae(t,4);let e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},ze=t=>{ae(t,4);let e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},bl=t=>{ae(t,4);let e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},Hi=(t,e)=>{let r,n;return e?(r=Le(t,!0),n=Le(t,!0)):(n=Le(t,!1),r=Le(t,!1)),n*4294967296+r},ce=t=>{let e=I(t),r=I(t);return e*4294967296+r},ea=t=>{let e=ze(t),r=I(t);return e*4294967296+r},xa=t=>{let e=vt(t);return bl(t)*4294967296+e},ra=t=>{ae(t,4);let e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},Rn=t=>{ae(t,8);let e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},W=(t,e)=>{ae(t,e);let r="";for(let n=0;n<e;n++)r+=String.fromCharCode(t.bytes[t.bufferPos++]);return r};async function _e(t){return t instanceof Blob?new Nr(t):new Ur(t)}var no=class{datafile;duration=0;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let r=new this(e),n=await this.duration(e.url)*1e3;r.duration=n;let{video:o,audio:s}=await this.#e(e.url);return r.hasAudio=s,r.hasVideo=o,r}static async duration(e){let n=await new ue({formats:Te,source:await _e(e)}).computeDuration();return Number(n.toFixed(5))}static async#e(e){let r=new ue({formats:Te,source:await _e(e)});return{audio:!!await r.getPrimaryAudioTrack(),video:!!await r.getPrimaryVideoTrack()}}};var oo=class{#e=new sn;async store(e){let r=await no.analyze(e),{hash:n}=r.datafile.checksum,{filename:o,bytes:s,url:i,blob:a}=r.datafile;if(this.#e.has(n)){let c=this.#e.require(n);c.filename=o}else this.#e.set(n,{kind:"media",filename:o,bytes:s,url:i,blob:a,duration:r.duration});return r}require(e){return this.#e.require(e)}};var O=t=>t;var za=()=>{let t=!1,e=je(60),r=1e3/e,n=0,o=0,s=Bt(),i=null,a=l=>{if(requestAnimationFrame(a),!!t)for(n=l;l-o>=r;)o+=r,i?.(),i=null,s()};async function*c(){for(n=performance.now(),o=n,requestAnimationFrame(a);;)await new Promise(l=>i=l),yield}return{play(){t||(t=!0,n=performance.now(),o=n)},pause(){t=!1},setFPS(l){e=l,r=1e3/e},isPlaying(){return t},ticks:c,onTick:s}},Na=async(t,e)=>{let r=O(1e3/t.fps),n=t.duration/1e3,o=Math.ceil(n*t.fps);for(let s=0;s<o;s++){let i=O(s*r);await e(i,s)}};var Ua={extension:{type:Kr.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-6TVTCHHE.js")}};var Va={extension:{type:Kr.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-VVIU3M54.js")}};var io;function La(t){return io!==void 0||(io=(()=>{let e={stencil:!0,failIfMajorPerformanceCaveat:t??Qr.defaultOptions.failIfMajorPerformanceCaveat};try{if(!lr.get().getWebGLRenderingContext())return!1;let n=lr.get().createCanvas().getContext("webgl",e),o=!!n?.getContextAttributes()?.stencil;if(n){let s=n.getExtension("WEBGL_lose_context");s&&s.loseContext()}return n=null,o}catch{return!1}})()),io}var so;async function Ha(t={}){return so!==void 0||(so=await(async()=>{let e=lr.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(t)).requestDevice(),!0}catch{return!1}})()),so}var Ga=["webgl","webgpu","canvas"];async function ji(t){let e=[];t.preference?(e.push(t.preference),Ga.forEach(s=>{s!==t.preference&&e.push(s)})):e=Ga.slice();let r,n={};for(let s=0;s<e.length;s++){let i=e[s];if(i==="webgpu"&&await Ha()){let{WebGPURenderer:a}=await import("./WebGPURenderer-XMCMEXAO.js");r=a,n={...t,...t.webgpu};break}else if(i==="webgl"&&La(t.failIfMajorPerformanceCaveat??Qr.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:a}=await import("./WebGLRenderer-7X274AYV.js");r=a,n={...t,...t.webgl};break}else if(i==="canvas")throw n={...t},new Error("CanvasRenderer is not yet implemented")}if(delete n.webgpu,delete n.webgl,!r)throw new Error("No available renderer for the current environment");let o=new r;return await o.init(n),o}var ao=class extends os{constructor(e,r){let{text:n,resolution:o,style:s,anchor:i,width:a,height:c,roundPixels:l,...d}=e;super({...d}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=r,this.text=n??"",this.style=s,this.resolution=o??null,this.allowChildren=!1,this._anchor=new ts({_onUpdate:()=>{this.onViewUpdate()}}),i&&(this.anchor=i),this.roundPixels=l??!1,a!==void 0&&(this.width=a),c!==void 0&&(this.height=c)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||(e={}),this._style?.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,r){typeof e=="object"?(r=e.height??e.width,e=e.width):r??(r=e),e!==void 0&&this._setWidth(e,this.bounds.width),r!==void 0&&this._setHeight(r,this.bounds.height)}containsPoint(e){let r=this.bounds.width,n=this.bounds.height,o=-r*this.anchor.x,s=0;return e.x>=o&&e.x<=o+r&&(s=-n*this.anchor.y,e.y>=s&&e.y<=s+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function qa(t,e){let r=t[0]??{};return(typeof r=="string"||t[1])&&(ns(rs,`use new ${e}({ text: "hi!", style }) instead`),r={text:r,style:t[1]}),r}var Vr=class extends ao{constructor(...e){let r=qa(e,"Text");super(r,is),this.renderPipeId="text",r.textureStyle&&(this.textureStyle=r.textureStyle instanceof Mo?r.textureStyle:new Mo(r.textureStyle))}updateBounds(){let e=this._bounds,r=this._anchor,n=0,o=0;if(this._style.trim){let{frame:s,canvasAndContext:i}=No.getCanvasAndContext({text:this.text,style:this._style,resolution:1});No.returnCanvasAndContext(i),n=s.width,o=s.height}else{let s=ss.measureText(this._text,this._style);n=s.width,o=s.height}e.minX=-r._x*n,e.maxX=e.minX+n,e.minY=-r._y*o,e.maxY=e.minY+o}};es.add(Ua,Va);var Wa=t=>{let[e,r,n]=t,[o,s]=e,[i,a]=r,c=n*Math.PI/180,l=Math.cos(c),d=Math.sin(c);return[l*i,d*i,-d*a,l*a,o,s]},ja=([t,e,r,n,o,s])=>new Bo(t,e,r,n,o,s);var $a=(t,e)=>{let[r,n,o,s,i,a]=t,[c,l,d,u,m,f]=e;return[r*c+o*l,n*c+s*l,r*d+o*u,n*d+s*u,r*m+o*f+i,n*m+s*f+a]},Ka=[1,0,0,1,0,0];function Qa(t){return"duration"in t}function Ya(t){let e=[],r=new Map(t.timeline.items.map(n=>[n.id,n]));return $i(t.timeline.rootId,r,t.from,{sequence:()=>{},stack:()=>{},video:(n,o,s)=>e.push({item:n,localTime:o,ancestors:s}),text:(n,o,s)=>e.push({item:n,localTime:o,ancestors:s}),audio:(n,o,s)=>e.push({item:n,localTime:o,ancestors:s})}),e}function Za(t,e,r){let n=Ka;for(let o of e)n=Xa(t,o,n);return Xa(t,r,n)}function Xa(t,e,r){if("spatialId"in e&&e.spatialId){let n=t.get(e.spatialId);if(n?.enabled){let o=Wa(n.transform);return $a(o,r)}}return r}function $i(t,e,r,n,o=[]){let s=e.get(t);if(s)switch(s.kind){case N.Stack:n.stack(s,r,o);for(let i of s.childrenIds)$i(i,e,r,n,[...o,s]);break;case N.Sequence:{n.sequence(s,r,o);let i=O(0);for(let a of s.childrenIds){let c=e.get(a);if(!c||!Qa(c))continue;let l=O(i+c.duration);if(r>=l){i=l;continue}let d=O(Math.max(0,r-i));$i(a,e,d,n,[...o,s]),i=l}break}case N.Video:n.video(s,r,o);break;case N.Text:n.text(s,r,o);break;case N.Audio:n.audio(s,r,o);break}}function H(t,e){let r=e.items.find(n=>n.id===t);if(!r)return O(0);switch(r.kind){case N.Sequence:{let n=r.childrenIds.map(s=>e.items.find(i=>i.id===s)).filter(Boolean),o=O(0);for(let s=0;s<n.length;s++){let i=n[s];if(i.kind===N.Transition){let a=n[s-1],c=n[s+1];if(a&&c&&a.kind!==N.Transition&&c.kind!==N.Transition){let l=H(a.id,e),d=H(c.id,e),u=Math.max(0,Math.min(i.duration,l,d));o=O(o-u)}continue}o=O(o+H(i.id,e))}return o}case N.Stack:{let n=O(0);for(let o of r.childrenIds){let s=H(o,e);s>n&&(n=s)}return n}default:return Qa(r)?r.duration:O(0)}}var Lr=t=>t;var co=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let r=this.#e.get(e);if(r)return r.sink;let n=new ue({formats:Te,source:await _e(this.resolveMedia(e))}),o=await n.getPrimaryVideoTrack(),i=!!o&&await o.canDecode()&&o?new Ar(o):null;return this.#e.set(e,{input:n,sink:i}),i}};async function Ja(t,e,r,n){let[o,s]=await Promise.all([r,n]),i=o.find(l=>l.kind==="image")?.frame,a=s.find(l=>l.kind==="image")?.frame,c=[...o.filter(l=>l.kind!=="image"),...s.filter(l=>l.kind!=="image")];return i&&a?[{id:t.id,kind:"transition",name:"circle",progress:e,from:i,to:a},...c]:c}async function ec(t,e,r,n){let o=yl(t,e,r);if(!o)return[];let s=[...n,e];return o.isTransitioning?Ja(o.transition,o.progress,It(t,o.outgoing,o.outgoingTime,s),It(t,o.incoming,o.incomingTime,s)):It(t,o.item,o.localTime,s)}function yl(t,e,r){let n=e.childrenIds.map(s=>t.items.get(s)).filter(s=>!!s),o=O(0);for(let s=0;s<n.length;s++){let i=n[s];if(i.kind===N.Transition)continue;let a=o,c=H(i.id,t.timeline),l=O(a+c),d=n[s+1];if(!(d?.kind===N.Transition)){if(r<l)return{isTransitioning:!1,item:i,localTime:O(r-a)};o=l;continue}let m=d,f=n[s+2];if(!f||f.kind===N.Transition){o=l;continue}let p=H(f.id,t.timeline),g=Math.max(0,Math.min(m.duration,c,p)),x=O(l-g);if(r<x)return{isTransitioning:!1,item:i,localTime:O(r-a)};if(r<l){let y=O(r-x),b=O(r-a);return{isTransitioning:!0,incoming:f,outgoing:i,outgoingTime:b,incomingTime:y,progress:g>0?y/g:1,transition:m}}o=x,s++}return null}async function It(t,e,r,n){let o=Za(t.items,n,e);switch(e.kind){case N.Stack:{let s=[...n,e];return(await Promise.all(e.childrenIds.map(a=>t.items.get(a)).filter(a=>!!a).map(a=>It(t,a,r,s)))).flat()}case N.Sequence:return ec(t,e,r,n);case N.Video:{if(r<0||r>=e.duration)return[];let s=await t.videoSampler(e,r);return s?[{kind:"image",frame:s,matrix:o,id:e.id}]:[]}case N.Text:{if(r<0||r>=e.duration)return[];let s=e.styleId?t.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:e.content,style:s,matrix:o}]}case N.Gap:return[{id:e.id,kind:"gap"}];default:return[]}}function tc(t){return async(e,r)=>{let o=await(await t.getSink(e.mediaHash))?.getSample(r/1e3),s=o?.toVideoFrame();return o?.close(),s??void 0}}function tr(t,e){let r=new co(t),n=e??tc(r);return{async sample(o,s){let i=new Map(o.items.map(c=>[c.id,c])),a=i.get(o.rootId);return a?It({videoSampler:n,timeline:o,items:i},a,s,[]):[]}}}var tt=class{driver;resolveMedia;timeline;#e=-1/0;#t=new Map;#r;constructor(e,r,n){this.driver=e,this.resolveMedia=r,this.timeline=n,this.#r=tr(this.resolveMedia,(o,s)=>{let i=rc(s),a=this.#t.get(o.id);if(!a){let c=this.resolveMedia(o.mediaHash),l=rc(O(o.start+o.duration));a=this.#n(c,i,l),this.#t.set(o.id,a)}return a.next(i)})}next(e){if(e<this.#e)throw new Error(`Forward-only cursor regression: ${e}ms < ${this.#e}ms`);return this.#e=e,this.#r.sample(this.timeline,e)}async cancel(){await Promise.all([...this.#t.values()].map(e=>e.cancel())),this.#t.clear()}#n(e,r,n){let o=this.driver.decodeVideo({source:e,start:r/1e6,end:n/1e6}),s=o.readable.getReader(),i=null,a=null,c=!1,l=async()=>{if(c)return null;let{done:d,value:u}=await s.read();if(d)return c=!0,null;let m=new VideoFrame(u);return u.close(),m};return{async next(d){if(i??=await l(),!!i)for(;;){a??=l();let u=await a;if(!u)return new VideoFrame(i);let m=i.timestamp??-1/0,f=u.timestamp??m;if(f<d){i.close(),i=u,a=null;continue}if(Math.abs(f-d)<Math.abs(m-d)){i.close(),i=u,a=null;continue}return new VideoFrame(i)}},async cancel(){let d=a;a=null,i?.close(),i=null,o.cancel(),(await d?.catch(()=>null))?.close()}}}},rc=t=>Math.round(t*1e3);async function nc(t,e,r){return(await Promise.all(e.map(async({item:o,localTime:s})=>{if(o.kind!==N.Audio)return;let i=await t.getSink(o.mediaHash);if(!i)return;let a=o.start+s,c=Lr((r-a)/1e3),l=i.samples(a/1e3),d=await l.next();if(d.done)return;let u=d.value,m=l.next();return{offset:c,gain:o.gain??1,get currentSample(){return u},timelineTime:()=>Lr(c+u.timestamp),output:()=>({sample:u,timestamp:c+u.timestamp,gain:o.gain??1}),advance:async()=>{let f=await m;return f.done?!1:(u=f.value,m=l.next(),!0)}}}))).filter(o=>!!o)}var lo=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let r=this.#e.get(e);if(r)return r.sink;let n=new ue({formats:Te,source:await _e(this.resolveMedia(e))}),o=await n.getPrimaryAudioTrack(),i=!!o&&await o.canDecode()&&o?new _r(o):null;return this.#e.set(e,{input:n,sink:i}),i}};function oc(t){let e={index:0,stream:t[0],time:t[0].timelineTime()};for(let[r,n]of t.entries()){let o=n.timelineTime();o<e.time&&(e={time:o,stream:n,index:r})}return e}function uo(t){let e=new lo(t);return{async*sampleAudio(r,n){let o=Ya({timeline:r,from:n}),s=await nc(e,o,n);for(;s.length>0;){let{stream:i,index:a}=oc(s);yield i.output(),await i.advance()||s.splice(a,1)}}}}var mo=class{driver;timeline;resolveMedia;audioSampler;seekVisualSampler;playVisualSampler=null;#e=O(0);#t=null;#r=za();onTick=this.#r.onTick;audioContext=new AudioContext({sampleRate:48e3});audioGain=this.audioContext.createGain();audioNodes=new Set;#n=null;constructor(e,r,n){this.driver=e,this.timeline=r,this.resolveMedia=n,this.audioGain.connect(this.audioContext.destination),this.audioGain.gain.value=.7**2,this.seekVisualSampler=tr(this.resolveMedia),this.audioSampler=uo(this.resolveMedia),this.#o()}update(e){this.timeline=e}async#o(){for await(let e of this.#r.ticks()){let r=await this.playVisualSampler?.next(this.currentTime)??[];(await this.driver.composite(r)).close(),this.currentTime>=this.duration&&this.pause()}}async seek(e){return this.pause(),this.#e=e,await this.seekVisualSampler.sample(this.timeline,e)}async start(){if(!this.#r.isPlaying()){await this.audioContext.resume(),this.#e=this.currentTime,this.#t=this.audioContext.currentTime,this.#n?.abort(),this.#n=new AbortController;for(let e of this.audioNodes)e.stop();this.audioNodes.clear(),this.playVisualSampler?.cancel(),this.playVisualSampler=new tt(this.driver,this.resolveMedia,this.timeline),this.#r.play(),this.#i(this.#n.signal,Lr(this.#e/1e3))}}pause(){this.#e=this.currentTime,this.#r.pause(),this.#n?.abort();for(let e of this.audioNodes)e.stop();this.audioNodes.clear(),this.playVisualSampler?.cancel(),this.playVisualSampler=null}get duration(){return H(this.timeline.rootId,this.timeline)}get currentTime(){if(!this.#r.isPlaying()||this.#t===null)return this.#e;let e=(this.audioContext.currentTime-this.#t)*1e3;return O(this.#e+e)}setFps(e){this.#r.setFPS(e)}async#i(e,r){let n=this.audioContext;if(this.#t!==null)for await(let{sample:o,timestamp:s}of this.audioSampler.sampleAudio(this.timeline,O(r*1e3))){if(e.aborted||!this.#r.isPlaying())return;for(;s-(n.currentTime-this.#t+r)>.75;)await new Promise(c=>setTimeout(c,25));let i=n.createBufferSource();i.buffer=o.toAudioBuffer(),i.connect(this.audioGain),i.onended=()=>this.audioNodes.delete(i),this.audioNodes.add(i);let a=this.#t+s-r;a>=n.currentTime?i.start(a):i.start(n.currentTime,n.currentTime-a)}}};var fo=class{driver;canvas;playback;#e=null;#t=null;constructor(e,r,n){this.driver=e,this.playback=new mo(e,n,r),this.canvas=e.compositor.pixi.renderer.canvas}async play(){await this.playback.start()}pause(){this.playback.pause()}seek(e){return this.#e=e,this.#t??=this.#r().finally(()=>this.#t=null)}setFPS(e){this.playback.setFps(je(e))}get duration(){return this.playback.duration}get currentTime(){return this.playback.currentTime}update(e){this.playback.update(e)}async#r(){for(;this.#e!==null;){let e=this.#e;this.#e=null;let r=await this.playback.seek(O(e));(await this.driver.composite(r)).close()}}};var Ee=class{#e;#t;constructor(e={}){this.#e=e.chunkFrames??1024,this.#t=e.clamp??!0}async*mix(e){let r=this.#e,n=null,o=null,s=[],i=0,a=0;for await(let c of e){if(o===null)o=c.planes.length,n=c.sampleRate;else{if(c.planes.length!==o)throw new Error("Channel count changed");if(c.sampleRate!==n)throw new Error("Sample rate changed")}let l=Math.round(c.timestamp*n),d=c.planes[0]?.length??0;for(;i+r<=l;)yield this.#r(s,i,o,n),i+=r;s.push({startFrame:l,endFrame:l+d,data:c.planes}),a=Math.max(a,l+d)}if(o!==null&&n!==null)for(;i<a;)yield this.#r(s,i,o,n),i+=r}#r(e,r,n,o){let s=this.#e,i=new Float32Array(n*s),a=r+s;for(let c=0;c<n;c++){let l=c*s,d=i.subarray(l,l+s);for(let u of e){let m=u.data[c];if(!m)continue;let f=Math.max(r,u.startFrame),p=Math.min(a,u.endFrame);if(f>=p)continue;let g=f-r,x=f-u.startFrame,y=p-f;for(let b=0;b<y;b++)d[g+b]+=m[x+b]}if(this.#t)for(let u=0;u<s;u++){let m=d[u];d[u]=m<-1?-1:m>1?1:m}}for(let c=e.length-1;c>=0;c--)e[c].endFrame<=a&&e.splice(c,1);return{planar:i,sampleRate:o,channels:n,frames:s,startFrame:r}}};var Tl=(t,e,r)=>{if(e===r)return t;let n=r/e,o=Math.max(1,Math.round(t.length*n)),s=new Float32Array(o);for(let i=0;i<o;i++){let a=i/n,c=Math.floor(a),l=Math.min(c+1,t.length-1),d=a-c;s[i]=t[c]*(1-d)+t[l]*d}return s},Fe=(t,e)=>{let r=t.numberOfChannels,n=new Array(r),o=0;for(let s=0;s<r;s++){let i=new Float32Array(t.numberOfFrames);t.copyTo(i,{planeIndex:s,format:"f32-planar"});let a=Tl(i,t.sampleRate,e);n[s]=a,o=a.length}return{data:n,frames:o}};var rr=(t,e)=>{if(e!==1)for(let r of t)for(let n=0;n<r.length;n++)r[n]*=e};function po({timeline:t,resolveMedia:e}){let r=new Ee,n=wl(t,e),o=new TransformStream,s=o.writable.getWriter();async function i(){for await(let a of r.mix(n)){let c=new AudioData({format:"f32-planar",sampleRate:a.sampleRate,numberOfFrames:a.frames,numberOfChannels:a.channels,timestamp:Math.round(a.startFrame/a.sampleRate*1e6),data:new Float32Array(a.planar)});await s.write(c)}await s.close()}return i(),o.readable}async function*wl(t,e){let r=uo(e);for await(let{sample:n,timestamp:o,gain:s}of r.sampleAudio(t,O(0))){let{data:i}=Fe(n,48e3);rr(i,s),yield{planes:i,sampleRate:48e3,timestamp:o},n.close()}}function ho({timeline:t,fps:e,driver:r,resolveMedia:n}){let o=new TransformStream,s=o.writable.getWriter(),i=new tt(r,n,t),a=1/e,c=H(t.rootId,t);async function l(){await Na({fps:e,duration:c},async(d,u)=>{let m=await i.next(d),f=await r.composite(m),p=new VideoFrame(f,{timestamp:Math.round(u*a*1e6),duration:Math.round(a*1e6)});await s.write(p),f.close()}),await s.close()}return l(),o.readable}function ic(t){let e=po({...t}),r=ho({...t});return t.driver.encode({video:r,audio:e,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}var rt=class{driver;resources=new oo;constructor(e){this.driver=e}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,n])=>[r,await this.resources.store(await n)])));timeline=e=>{let r=new q({timeline:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),n=e(r);return r.timeline.rootId=n.id,r.timeline};playback=async e=>new fo(this.driver,r=>this.resources.require(r).url,e);render=async(e,r=30)=>ic({timeline:e,fps:je(r),driver:this.driver,resolveMedia:n=>this.resources.require(n).url})};function Ki(t,e){return{error:r=>t.error({...e,...r}),rpcRequest:r=>t.rpcRequest({...e,...r}),rpcError:r=>t.rpcError({...e,...r})}}var go=()=>t=>({plain:t.none,errMessage:t.mix(t.brightRed,t.bold),errName:t.red,errStack:t.mix(t.red,t.dim),timestamp:t.blue,timestampErr:t.red});function sc(){return go()}var nt=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});var xo=()=>({none:t=>t,uncolor:vl,mix:Sl,hex:Pl,rgb:ac,bgRgb:Il});function vl(t){return t.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function Sl(...t){return e=>{for(let r of t)e=r(e);return e}}function Pl(t){t=t.replace(/^#/,"");let e,r,n,o;if(t.length===3)e=parseInt(t.split("").map(s=>s+s).join(""),16);else if(t.length===6)e=parseInt(t,16);else throw new Error("Invalid hex color");return r=e>>16&255,n=e>>8&255,o=e&255,ac(r,n,o)}function ac(t,e,r){let n=`\x1B[38;2;${t};${e};${r}m`;return o=>`${n}${o}${nt.reset}`}function Il(t,e,r){let n=`\x1B[48;2;${t};${e};${r}m`;return o=>`${n}${o}${nt.reset}`}var Hr={...Object.fromEntries(Object.entries(nt).map(([t])=>[t,e=>e])),...xo()};var Gr={...Object.fromEntries(Object.entries(nt).map(([t,e])=>[t,r=>`${e}${r}${nt.reset}`])),...xo()};function Xi(){return typeof Deno<"u"&&typeof Deno.version<"u"}function Qi(){return typeof process<"u"&&process.versions&&process.versions.node}function cc(){return Qi()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":Xi()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var Yi=()=>cc()?Gr:Hr;var bo=()=>({colors:t,theme:e})=>{let r=e(t);function n(i){let a=i.stack?`
|
|
2361
2361
|
`+i.stack+`
|
|
2362
2362
|
`:"";return[r.errName(i.name+":"),r.errMessage(i.message)].join(" ")+r.errStack(a)}function o(i){return i&&i instanceof Error?n(i):i}function s(i){return i&&i instanceof Error?n(i):r.errMessage(i)}return{stdout:i=>i.map(o),stderr:i=>i.map(s)}};function qr(...t){return e=>({stdout:r=>{for(let n of t)r=n(e).stdout(r);return r},stderr:r=>{for(let n of t)r=n(e).stderr(r);return r}})}function Cl(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var yo=t=>({colors:e,theme:r})=>{let n={...Cl(),...t},o=r(e),s=new Date(n.now()),i=s.getUTCFullYear().toString().padStart(4,"0"),a=(s.getUTCMonth()+1).toString().padStart(2,"0"),c=s.getUTCDate().toString().padStart(2,"0"),l=`${i}-${a}-${c}`,d=s.getUTCHours().toString().padStart(2,"0"),u=s.getUTCMinutes().toString().padStart(2,"0"),m=s.getUTCSeconds().toString().padStart(2,"0"),f=s.getUTCMilliseconds().toString().padStart(3,"0"),p=`${d}:${u}:${m}.${f}`,g=`${l}::${p}`;return{stdout:x=>[o.timestamp(g),...x],stderr:x=>[o.timestampErr(g),...[n.icon].filter(Boolean),...x]}};function lc(){return qr(bo(),yo())}var To=()=>({stdout:async t=>{await Deno.stdout.write(new TextEncoder().encode(t+`
|
|
2363
2363
|
`))},stderr:async t=>{await Deno.stderr.write(new TextEncoder().encode(t+`
|
|
@@ -2416,7 +2416,7 @@ vec4 transition(vec2 uv) {
|
|
|
2416
2416
|
vec2 uv = vTextureCoord.xy;
|
|
2417
2417
|
gl_FragColor = transition(vTextureCoord);
|
|
2418
2418
|
}
|
|
2419
|
-
`;function Ic({name:t,renderer:e}){let r=Pc.default.find(c=>c.name===t),n=new Ft,o=new cr,s=new Xr({}),i=new Xr({}),a=new No({glProgram:new zo({vertex:vc,fragment:Sc(r.glsl)}),resources:{from:s,to:i,uniforms:{...Ji.basics,...Ji.custom(r)}}});return n.filters=[a],{render({width:c,height:l,from:d,to:u,progress:m}){return(n.width!==c||n.height!==l)&&(n.setSize({width:c,height:l}),o.source.resize(c,l)),s.resource=d,i.resource=u,s.update(),i.update(),a.resources.uniforms.uniforms.progress=m,e.render({container:n,target:o,clear:!1,width:c,height:l}),o}}}var Fo=class{pixi;static async setup(){let e=await ji({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),r=new Oo;return r.interactive=!0,new this({renderer:e,stage:r})}constructor(e){this.pixi=e}#e=new Map;#t=new Map;async composite(e){let{stage:r,renderer:n}=this.pixi;this.#l(this.#c(e));let{dispose:o}=await this.#r(e,r);n.render(r);let s=new VideoFrame(n.canvas,{timestamp:0,duration:0});return o(),s}async#r(e,r){if(Array.isArray(e)){e.reverse();let n=[];for(let o of e){let s=await this.#r(o,r);n.push(s.dispose)}return{dispose:()=>n.forEach(o=>o())}}switch(e.kind){case"text":return this.#n(e,r);case"image":return this.#o(e,r);case"transition":return this.#i(e,r);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#n(e,r){let n=this.#a(e);return this.#s(n,e.matrix),r.addChild(n),{dispose:()=>{}}}#o(e,r){let n=cr.from(e.frame),o=this.#a(e);return o.texture=n,this.#s(o,e.matrix),r.addChild(o),{dispose:()=>{n.destroy(!0),e.frame.close()}}}#i({from:e,to:r,progress:n,name:o},s){let a=(this.#e.get(o)??(this.#e.set(o,Ic({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:r,progress:n,width:e.displayWidth,height:e.displayHeight}),c=new Ft(a);return s.addChild(c),{dispose:()=>c.destroy(!1)}}#s(e,r){if(!r)return;let n=ja(r);e.setFromMatrix(n)}#a(e){let r=this.#t.get(e.id);if(r)return r;switch(e.kind){case"text":{let n=new Vr({text:e.content,style:e.style});return n.onmouseenter=()=>console.log("enter text"),this.#t.set(e.id,n).get(e.id)}case"image":{let n=new Ft;return n.onmouseenter=()=>console.log("enter"),this.#t.set(e.id,n).get(e.id)}}}#c(e){let r=new Set,n=o=>{if(Array.isArray(o))for(let s of o)n(s);else r.add(o.id)};return n(e),r}#l(e){for(let r of this.#t.keys())e.has(r)||(this.#t.get(r).destroy(!0),this.#t.delete(r))}};var Cc=t=>_o.host(e=>({async world(){t.count++}}));var ot=class{machina;thread;compositor;static async setup(e){let r=new Eo,n=await _o.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:Cc(r)}),o=await Fo.setup();return new this(r,n,o)}constructor(e,r,n){this.machina=e,this.thread=r,this.compositor=n}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let n=await new ue({source:await _e(e),formats:Te}).getPrimaryAudioTrack();if(!n)throw new Error("primary audio track not found");return await n.computeDuration()}async getVideoDuration(e){return await(await new ue({source:await _e(e),formats:Te}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let r=null,{port1:n,port2:o}=new MessageChannel,s=new TransformStream({async transform(i,a){let c=await e.onFrame?.(i)??i;r?.close(),a.enqueue(c),r=c}});return this.thread.work.decodeVideo[or]({transfer:[s.writable,o]})({source:e.source,cancel:o,video:s.writable,start:e.start,end:e.end}),{readable:s.readable,cancel(){n.postMessage("close"),n.close()}}}decodeAudio(e){let r=new TransformStream,{port1:n,port2:o}=new MessageChannel;return this.thread.work.decodeAudio[or]({transfer:[r.writable,o]})({source:e.source,cancel:o,audio:r.writable,start:e.start,end:e.end}),{readable:r.readable,cancel(){n.postMessage("close"),n.close()}}}encode({audio:e,video:r,config:n}){let{readable:o,writable:s}=new TransformStream,i=[e,r,s].filter(on.happy),a=this.thread.work.encode[or]({transfer:i})({audio:e,video:r,config:n,writable:s});return{readable:o,done:a}}async composite(e){return await this.compositor.composite(e)}};var Do=class{data;bytes;hash;nickname;constructor(e,r,n,o){this.data=e,this.bytes=r,this.hash=n,this.nickname=o}static async make(e){let r=new Uint8Array(e),n=new Uint8Array(await crypto.subtle.digest("SHA-256",r)),o=nn.fromBytes(n),s=hs.sigil.fromBytes(n);return new this(e,n,o,s)}};var it=class{url;bytes;blob;filename;checksum;constructor(e,r,n,o,s){this.url=e,this.bytes=r,this.blob=n,this.filename=o,this.checksum=s}static async make(e,r){let n=await e.arrayBuffer(),o=new Uint8Array(n),s=await Do.make(o),i=r??s.nickname,a=URL.createObjectURL(e);return new this(a,o,e,i,s)}static async load(e){}};async function ar(t){return fetch(t).then(e=>e.blob())}var Ac=new URL("../driver/driver.worker.bundle.min.js",import.meta.url);async function de(){let t=await ot.setup({workerUrl:Ac}),e=new rt(t),r=await ar("/assets/temp/test.mp4"),{videoA:n}=await e.load({videoA:it.make(r,"test.mp4")});return{driver:t,omni:e,testVideo:r,videoA:n}}var _c=We.suite({"basic demo":async()=>{let t=await ot.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),e=new rt(t),r=await ar("/assets/temp/test.mp4"),{videoA:n}=await e.load({videoA:it.make(r,"test.mp4")}),o=new q({timeline:e.timeline(l=>l.sequence())}),s=o.require(o.timeline.rootId),i=o.video(n);o.addChildren(s,i);let a=H(i.id,o.timeline),c=H(o.timeline.rootId,o.timeline);P(a).is(c)},"sequence duration is 3x":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.sequence(o.video(e),o.video(e),o.video(e)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration*3)},"stack duration is 1x":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.stack(o.video(e),o.video(e),o.video(e)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration)},"nested stack inside sequence":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.sequence(o.video(e),o.stack(o.video(e),o.video(e)),o.video(e)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration*3)},"nested sequence inside stack":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.stack(o.video(e),o.sequence(o.video(e),o.video(e))))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration*2)},"empty timeline duration is 0":async()=>{let{omni:t}=await de(),e=new q({timeline:t.timeline(s=>s.sequence())}),r=new q({timeline:t.timeline(s=>s.stack())}),n=H(e.timeline.rootId,e.timeline),o=H(r.timeline.rootId,r.timeline);P(n).is(0),P(o).is(0)},"transition in a sequence":async()=>{let{omni:t,videoA:e}=await de(),r=1e3,n=new q({timeline:t.timeline(i=>i.sequence(i.video(e),i.transition.crossfade(r),i.video(e)))}),o=H(n.timeline.rootId,n.timeline),s=e.duration*2-r;P(o).is(s)},"transition in a stack":async()=>{let{omni:t,videoA:e}=await de(),r=1e3,n=new q({timeline:t.timeline(s=>s.stack(s.video(e),s.transition.crossfade(r),s.video(e)))}),o=H(n.timeline.rootId,n.timeline);P(o).is(e.duration)},"ignore invalid transition":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.sequence(o.transition.crossfade(1e3),o.video(e),o.video(e),o.transition.crossfade(1e3)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration*2)},"clamp transition duration on overflow":async()=>{let{omni:t,videoA:e}=await de(),r=3e3,n=new q({timeline:t.timeline(s=>s.sequence(s.video(e,{duration:r}),s.transition.crossfade(r*2),s.video(e,{duration:r})))}),o=H(n.timeline.rootId,n.timeline);P(o).is(r)},"multiple transitions":async()=>{let{omni:t,videoA:e}=await de(),r=1e3,n=new q({timeline:t.timeline(i=>i.sequence(i.video(e),i.transition.crossfade(r),i.video(e),i.transition.crossfade(r),i.video(e)))}),o=H(n.timeline.rootId,n.timeline),s=e.duration*3-r*2;P(o).is(s)},"gap item in a sequence":async()=>{let{omni:t,videoA:e}=await de(),r=1e3,n=new q({timeline:t.timeline(i=>i.sequence(i.video(e),i.gap(r),i.video(e)))}),o=H(n.timeline.rootId,n.timeline),s=e.duration*2+r;P(o).is(s)},"gap item in a stack":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.stack(o.video(e),o.gap(1e3),o.video(e)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration)},"load media into Omni":async()=>{let t=await ot.setup({workerUrl:Ac}),e=new rt(t),r=await ar("/assets/temp/test.mp4"),{videoA:n}=await e.load({videoA:it.make(r,"test.mp4")});P(e.resources.require(n.datafile.checksum.hash)).happy()},"playback seeks to correct time":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.sequence(o.video(e,{duration:2e3}),o.gap(500),o.video(e,{duration:2500})))}),n=await t.playback(r.timeline);await n.seek(1e3),P(n.currentTime).is(1e3)}});var Ml=new URL("../driver/driver.worker.bundle.min.js",import.meta.url);async function Ro(){let t=await ot.setup({workerUrl:Ml}),e=new rt(t),r=await ar("/assets/temp/test.mp4"),{videoA:n}=await e.load({videoA:it.make(r,"test.mp4")});return{driver:t,omni:e,testVideo:r,videoA:n,resolveMedia:s=>e.resources.require(s).blob}}async function $r(t){let e=[];for await(let r of t)e.push(r);return e}var J=(t,e,r=1e-6)=>Math.abs(t-e)<r,Ec=We.suite({"cursor visual sampler cannot get previous samples":async()=>{let{omni:t,videoA:e,resolveMedia:r,driver:n}=await Ro(),{timeline:o}=new q({timeline:t.timeline(i=>i.sequence(i.video(e,{duration:2e3}),i.gap(500),i.video(e,{duration:2e3}),i.audio(e,{duration:500})))}),s=new tt(n,r,o);await s.next(O(1e3)),await P(async()=>await s.next(O(100))).throwsAsync()},"visual sampler gives correct layer at x time":async()=>{let{omni:t,videoA:e,resolveMedia:r}=await Ro(),{timeline:n}=new q({timeline:t.timeline(l=>l.sequence(l.video(e,{duration:2e3}),l.gap(500),l.video(e,{duration:2e3}),l.audio(e,{duration:500}),l.text("123",{duration:1e3})))}),o=tr(r),s=await o.sample(n,O(1e3));P(s[0].kind).is("image");let i=await o.sample(n,O(2300));P(i[0].kind).is("gap");let a=await o.sample(n,O(2700));P(a[0].kind).is("image");let c=await o.sample(n,O(5500));P(c[0].kind).is("text")},"audio mix sums overlapping chunks":async()=>{let t=new Ee({chunkFrames:4,clamp:!1});async function*e(){yield{planes:[new Float32Array([.25,.25,.25,.25])],sampleRate:4,timestamp:0},yield{planes:[new Float32Array([.5,.5,.5,.5])],sampleRate:4,timestamp:.5}}let r=await $r(t.mix(e()));P(r.length).is(2),P(r[0].startFrame).is(0),P(r[0].frames).is(4),P(r[0].channels).is(1),P(r[0].planar[0]).is(.25),P(r[0].planar[1]).is(.25),P(r[0].planar[2]).is(.75),P(r[0].planar[3]).is(.75),P(r[1].startFrame).is(4),P(r[1].planar[0]).is(.5),P(r[1].planar[1]).is(.5),P(r[1].planar[2]).is(0),P(r[1].planar[3]).is(0)},"audio mix clamps output to [-1, 1]":async()=>{let t=new Ee({chunkFrames:4,clamp:!0});async function*e(){yield{planes:[new Float32Array([.9,.9,.9,.9])],sampleRate:4,timestamp:0},yield{planes:[new Float32Array([.8,.8,.8,.8])],sampleRate:4,timestamp:0}}let r=await $r(t.mix(e()));P(r.length).is(1),P(r[0].planar[0]).is(1),P(r[0].planar[1]).is(1),P(r[0].planar[2]).is(1),P(r[0].planar[3]).is(1)},"audio mix fills gaps with silence":async()=>{let t=new Ee({chunkFrames:4,clamp:!1});async function*e(){yield{planes:[new Float32Array([1,1,1,1])],sampleRate:4,timestamp:0},yield{planes:[new Float32Array([2,2,2,2])],sampleRate:4,timestamp:2}}let r=await $r(t.mix(e()));P(r.length).is(3),P(r[0].startFrame).is(0),P(r[0].planar[0]).is(1),P(r[1].startFrame).is(4),P(r[1].planar[0]).is(0),P(r[1].planar[3]).is(0),P(r[2].startFrame).is(8),P(r[2].planar[0]).is(2)},"audio mix truncates negative timestamps":async()=>{let t=new Ee({chunkFrames:4,clamp:!1});async function*e(){yield{planes:[new Float32Array([1,2,3,4])],sampleRate:4,timestamp:-.5}}let r=await $r(t.mix(e()));P(r.length).is(1),P(r[0].startFrame).is(0),P(r[0].planar[0]).is(3),P(r[0].planar[1]).is(4),P(r[0].planar[2]).is(0),P(r[0].planar[3]).is(0)},"audio mix handles stereo planar layout":async()=>{let t=new Ee({chunkFrames:4,clamp:!1});async function*e(){yield{planes:[new Float32Array([1,1,1,1]),new Float32Array([2,2,2,2])],sampleRate:4,timestamp:0}}let r=await $r(t.mix(e()));P(r.length).is(1),P(r[0].channels).is(2),P(r[0].planar.length).is(8),P(r[0].planar[0]).is(1),P(r[0].planar[4]).is(2)},"applyGainToPlanar scales values across multiple channels":async()=>{let t=[new Float32Array([.2,-.4]),new Float32Array([.6,-.8])];rr(t,.5),P(J(t[0][0],.1)).ok(),P(J(t[0][1],-.2)).ok(),P(J(t[1][0],.3)).ok(),P(J(t[1][1],-.4)).ok()},"applyGainToPlanar does not mutate when gain is 1":async()=>{let t=[new Float32Array([.5,-.5])];rr(t,1),P(J(t[0][0],.5)).ok(),P(J(t[0][1],-.5)).ok()},"applyGainToPlanar mutes entirely when gain is 0":async()=>{let t=[new Float32Array([.9,-.9])];rr(t,0),P(t[0][0]).is(0),P(t[0][1]).is(0)},"resampleToPlanar returns original data when sample rates match":async()=>{let e=Fe({numberOfFrames:3,numberOfChannels:1,sampleRate:48e3,copyTo:r=>r.set([.1,.2,.3])},48e3);P(e.frames).is(3),P(e.data.length).is(1),P(J(e.data[0][0],.1)).ok(),P(J(e.data[0][1],.2)).ok(),P(J(e.data[0][2],.3)).ok()},"resampleToPlanar upsamples using linear interpolation":async()=>{let e=Fe({numberOfFrames:2,numberOfChannels:1,sampleRate:1,copyTo:r=>r.set([10,20])},2);P(e.frames).is(4),P(J(e.data[0][0],10)).ok(),P(J(e.data[0][1],15)).ok(),P(J(e.data[0][2],20)).ok(),P(J(e.data[0][3],20)).ok()},"resampleToPlanar downsamples correctly":async()=>{let e=Fe({numberOfFrames:4,numberOfChannels:1,sampleRate:4,copyTo:r=>r.set([1,2,3,4])},2);P(e.frames).is(2),P(J(e.data[0][0],1)).ok(),P(J(e.data[0][1],3)).ok()},"resampleToPlanar processes multi-channel planar data":async()=>{let t=[new Float32Array([1,2]),new Float32Array([3,4])],r=Fe({numberOfFrames:2,numberOfChannels:2,sampleRate:1,copyTo:(n,o)=>{n.set(t[o.planeIndex])}},2);P(r.data.length).is(2),P(J(r.data[0][1],1.5)).ok(),P(J(r.data[1][1],3.5)).ok()},"resampleToPlanar handles zero channels gracefully":async()=>{let e=Fe({numberOfFrames:10,numberOfChannels:0,sampleRate:48e3,copyTo:()=>{throw new Error("Should not be called")}},44100);P(e.data.length).is(0),P(e.frames).is(0)},"resampleToPlanar enforces minimum of 1 frame on aggressive downsample":async()=>{let e=Fe({numberOfFrames:1,numberOfChannels:1,sampleRate:48e3,copyTo:r=>r.set([.8])},8e3);P(e.frames).is(1),P(e.data[0].length).is(1),P(J(e.data[0][0],.8)).ok()},"resampleToPlanar calls copyTo with strict contract shape":async()=>{let t=null;Fe({numberOfFrames:2,numberOfChannels:1,sampleRate:48e3,copyTo:(r,n)=>{t=n}},44100),P(t).not.is(null),P(t.planeIndex).is(0),P(t.format).is("f32-planar")},"5s long export at 30fps renders exacly 150 frames":async()=>{let{omni:t,videoA:e,driver:r,resolveMedia:n}=await Ro(),{timeline:o}=new q({timeline:t.timeline(a=>a.sequence(a.video(e,{duration:2e3}),a.gap(500),a.video(e,{duration:2e3}),a.audio(e,{duration:500})))}),s=ho({timeline:o,fps:je(30),driver:r,resolveMedia:n}),i=0;for await(let a of s)a.close(),i++;P(i).is(150)},"5s long audio export at 48000Hz renders exactly 240000 frames":async()=>{let{omni:t,videoA:e,resolveMedia:r}=await Ro(),{timeline:n}=new q({timeline:t.timeline(i=>i.sequence(i.video(e,{duration:2e3}),i.gap(500),i.video(e,{duration:2e3}),i.audio(e,{duration:500})))}),o=po({timeline:n,resolveMedia:r}),s=0;for await(let i of o)s+=i.numberOfFrames,i.close();P(s).is(24e4)}});await We.run({omniTest:_c,renderersTest:Ec});
|
|
2419
|
+
`;function Ic({name:t,renderer:e}){let r=Pc.default.find(c=>c.name===t),n=new Ft,o=new cr,s=new Xr({}),i=new Xr({}),a=new Uo({glProgram:new zo({vertex:vc,fragment:Sc(r.glsl)}),resources:{from:s,to:i,uniforms:{...Ji.basics,...Ji.custom(r)}}});return n.filters=[a],{render({width:c,height:l,from:d,to:u,progress:m}){return(n.width!==c||n.height!==l)&&(n.setSize({width:c,height:l}),o.source.resize(c,l)),s.resource=d,i.resource=u,s.update(),i.update(),a.resources.uniforms.uniforms.progress=m,e.render({container:n,target:o,clear:!1,width:c,height:l}),o}}}var Fo=class{pixi;static async setup(){let e=await ji({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),r=new Oo;return r.interactive=!0,new this({renderer:e,stage:r})}constructor(e){this.pixi=e}#e=new Map;#t=new Map;async composite(e){let{stage:r,renderer:n}=this.pixi;this.#l(this.#c(e));let{dispose:o}=await this.#r(e,r);n.render(r);let s=new VideoFrame(n.canvas,{timestamp:0,duration:0});return o(),s}async#r(e,r){if(Array.isArray(e)){e.reverse();let n=[];for(let o of e){let s=await this.#r(o,r);n.push(s.dispose)}return{dispose:()=>n.forEach(o=>o())}}switch(e.kind){case"text":return this.#n(e,r);case"image":return this.#o(e,r);case"transition":return this.#i(e,r);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#n(e,r){let n=this.#a(e);return this.#s(n,e.matrix),r.addChild(n),{dispose:()=>{}}}#o(e,r){let n=cr.from(e.frame),o=this.#a(e);return o.texture=n,this.#s(o,e.matrix),r.addChild(o),{dispose:()=>{n.destroy(!0),e.frame.close()}}}#i({from:e,to:r,progress:n,name:o},s){let a=(this.#e.get(o)??(this.#e.set(o,Ic({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:r,progress:n,width:e.displayWidth,height:e.displayHeight}),c=new Ft(a);return s.addChild(c),{dispose:()=>c.destroy(!1)}}#s(e,r){if(!r)return;let n=ja(r);e.setFromMatrix(n)}#a(e){let r=this.#t.get(e.id);if(r)return r;switch(e.kind){case"text":{let n=new Vr({text:e.content,style:e.style});return n.onmouseenter=()=>console.log("enter text"),this.#t.set(e.id,n).get(e.id)}case"image":{let n=new Ft;return n.onmouseenter=()=>console.log("enter"),this.#t.set(e.id,n).get(e.id)}}}#c(e){let r=new Set,n=o=>{if(Array.isArray(o))for(let s of o)n(s);else r.add(o.id)};return n(e),r}#l(e){for(let r of this.#t.keys())e.has(r)||(this.#t.get(r).destroy(!0),this.#t.delete(r))}};var Cc=t=>_o.host(e=>({async world(){t.count++}}));var ot=class{machina;thread;compositor;static async setup(e){let r=new Eo,n=await _o.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:Cc(r)}),o=await Fo.setup();return new this(r,n,o)}constructor(e,r,n){this.machina=e,this.thread=r,this.compositor=n}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let n=await new ue({source:await _e(e),formats:Te}).getPrimaryAudioTrack();if(!n)throw new Error("primary audio track not found");return await n.computeDuration()}async getVideoDuration(e){return await(await new ue({source:await _e(e),formats:Te}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let r=null,{port1:n,port2:o}=new MessageChannel,s=new TransformStream({async transform(i,a){let c=await e.onFrame?.(i)??i;r?.close(),a.enqueue(c),r=c}});return this.thread.work.decodeVideo[or]({transfer:[s.writable,o]})({source:e.source,cancel:o,video:s.writable,start:e.start,end:e.end}),{readable:s.readable,cancel(){n.postMessage("close"),n.close()}}}decodeAudio(e){let r=new TransformStream,{port1:n,port2:o}=new MessageChannel;return this.thread.work.decodeAudio[or]({transfer:[r.writable,o]})({source:e.source,cancel:o,audio:r.writable,start:e.start,end:e.end}),{readable:r.readable,cancel(){n.postMessage("close"),n.close()}}}encode({audio:e,video:r,config:n}){let{readable:o,writable:s}=new TransformStream,i=[e,r,s].filter(on.happy),a=this.thread.work.encode[or]({transfer:i})({audio:e,video:r,config:n,writable:s});return{readable:o,done:a}}async composite(e){return await this.compositor.composite(e)}};var Do=class{data;bytes;hash;nickname;constructor(e,r,n,o){this.data=e,this.bytes=r,this.hash=n,this.nickname=o}static async make(e){let r=new Uint8Array(e),n=new Uint8Array(await crypto.subtle.digest("SHA-256",r)),o=nn.fromBytes(n),s=hs.sigil.fromBytes(n);return new this(e,n,o,s)}};var it=class{url;bytes;blob;filename;checksum;constructor(e,r,n,o,s){this.url=e,this.bytes=r,this.blob=n,this.filename=o,this.checksum=s}static async make(e,r){let n=await e.arrayBuffer(),o=new Uint8Array(n),s=await Do.make(o),i=r??s.nickname,a=URL.createObjectURL(e);return new this(a,o,e,i,s)}static async load(e){}};async function ar(t){return fetch(t).then(e=>e.blob())}var Ac=new URL("../driver/driver.worker.bundle.min.js",import.meta.url);async function de(){let t=await ot.setup({workerUrl:Ac}),e=new rt(t),r=await ar("/assets/temp/test.mp4"),{videoA:n}=await e.load({videoA:it.make(r,"test.mp4")});return{driver:t,omni:e,testVideo:r,videoA:n}}var _c=We.suite({"basic demo":async()=>{let t=await ot.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),e=new rt(t),r=await ar("/assets/temp/test.mp4"),{videoA:n}=await e.load({videoA:it.make(r,"test.mp4")}),o=new q({timeline:e.timeline(l=>l.sequence())}),s=o.require(o.timeline.rootId),i=o.video(n);o.addChildren(s,i);let a=H(i.id,o.timeline),c=H(o.timeline.rootId,o.timeline);P(a).is(c)},"sequence duration is 3x":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.sequence(o.video(e),o.video(e),o.video(e)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration*3)},"stack duration is 1x":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.stack(o.video(e),o.video(e),o.video(e)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration)},"nested stack inside sequence":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.sequence(o.video(e),o.stack(o.video(e),o.video(e)),o.video(e)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration*3)},"nested sequence inside stack":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.stack(o.video(e),o.sequence(o.video(e),o.video(e))))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration*2)},"empty timeline duration is 0":async()=>{let{omni:t}=await de(),e=new q({timeline:t.timeline(s=>s.sequence())}),r=new q({timeline:t.timeline(s=>s.stack())}),n=H(e.timeline.rootId,e.timeline),o=H(r.timeline.rootId,r.timeline);P(n).is(0),P(o).is(0)},"transition in a sequence":async()=>{let{omni:t,videoA:e}=await de(),r=1e3,n=new q({timeline:t.timeline(i=>i.sequence(i.video(e),i.transition.crossfade(r),i.video(e)))}),o=H(n.timeline.rootId,n.timeline),s=e.duration*2-r;P(o).is(s)},"transition in a stack":async()=>{let{omni:t,videoA:e}=await de(),r=1e3,n=new q({timeline:t.timeline(s=>s.stack(s.video(e),s.transition.crossfade(r),s.video(e)))}),o=H(n.timeline.rootId,n.timeline);P(o).is(e.duration)},"ignore invalid transition":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.sequence(o.transition.crossfade(1e3),o.video(e),o.video(e),o.transition.crossfade(1e3)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration*2)},"clamp transition duration on overflow":async()=>{let{omni:t,videoA:e}=await de(),r=3e3,n=new q({timeline:t.timeline(s=>s.sequence(s.video(e,{duration:r}),s.transition.crossfade(r*2),s.video(e,{duration:r})))}),o=H(n.timeline.rootId,n.timeline);P(o).is(r)},"multiple transitions":async()=>{let{omni:t,videoA:e}=await de(),r=1e3,n=new q({timeline:t.timeline(i=>i.sequence(i.video(e),i.transition.crossfade(r),i.video(e),i.transition.crossfade(r),i.video(e)))}),o=H(n.timeline.rootId,n.timeline),s=e.duration*3-r*2;P(o).is(s)},"gap item in a sequence":async()=>{let{omni:t,videoA:e}=await de(),r=1e3,n=new q({timeline:t.timeline(i=>i.sequence(i.video(e),i.gap(r),i.video(e)))}),o=H(n.timeline.rootId,n.timeline),s=e.duration*2+r;P(o).is(s)},"gap item in a stack":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.stack(o.video(e),o.gap(1e3),o.video(e)))}),n=H(r.timeline.rootId,r.timeline);P(n).is(e.duration)},"load media into Omni":async()=>{let t=await ot.setup({workerUrl:Ac}),e=new rt(t),r=await ar("/assets/temp/test.mp4"),{videoA:n}=await e.load({videoA:it.make(r,"test.mp4")});P(e.resources.require(n.datafile.checksum.hash)).happy()},"playback seeks to correct time":async()=>{let{omni:t,videoA:e}=await de(),r=new q({timeline:t.timeline(o=>o.sequence(o.video(e,{duration:2e3}),o.gap(500),o.video(e,{duration:2500})))}),n=await t.playback(r.timeline);await n.seek(1e3),P(n.currentTime).is(1e3)}});var Ml=new URL("../driver/driver.worker.bundle.min.js",import.meta.url);async function Ro(){let t=await ot.setup({workerUrl:Ml}),e=new rt(t),r=await ar("/assets/temp/test.mp4"),{videoA:n}=await e.load({videoA:it.make(r,"test.mp4")});return{driver:t,omni:e,testVideo:r,videoA:n,resolveMedia:s=>e.resources.require(s).blob}}async function $r(t){let e=[];for await(let r of t)e.push(r);return e}var J=(t,e,r=1e-6)=>Math.abs(t-e)<r,Ec=We.suite({"cursor visual sampler cannot get previous samples":async()=>{let{omni:t,videoA:e,resolveMedia:r,driver:n}=await Ro(),{timeline:o}=new q({timeline:t.timeline(i=>i.sequence(i.video(e,{duration:2e3}),i.gap(500),i.video(e,{duration:2e3}),i.audio(e,{duration:500})))}),s=new tt(n,r,o);await s.next(O(1e3)),await P(async()=>await s.next(O(100))).throwsAsync()},"visual sampler gives correct layer at x time":async()=>{let{omni:t,videoA:e,resolveMedia:r}=await Ro(),{timeline:n}=new q({timeline:t.timeline(l=>l.sequence(l.video(e,{duration:2e3}),l.gap(500),l.video(e,{duration:2e3}),l.audio(e,{duration:500}),l.text("123",{duration:1e3})))}),o=tr(r),s=await o.sample(n,O(1e3));P(s[0].kind).is("image");let i=await o.sample(n,O(2300));P(i[0].kind).is("gap");let a=await o.sample(n,O(2700));P(a[0].kind).is("image");let c=await o.sample(n,O(5500));P(c[0].kind).is("text")},"audio mix sums overlapping chunks":async()=>{let t=new Ee({chunkFrames:4,clamp:!1});async function*e(){yield{planes:[new Float32Array([.25,.25,.25,.25])],sampleRate:4,timestamp:0},yield{planes:[new Float32Array([.5,.5,.5,.5])],sampleRate:4,timestamp:.5}}let r=await $r(t.mix(e()));P(r.length).is(2),P(r[0].startFrame).is(0),P(r[0].frames).is(4),P(r[0].channels).is(1),P(r[0].planar[0]).is(.25),P(r[0].planar[1]).is(.25),P(r[0].planar[2]).is(.75),P(r[0].planar[3]).is(.75),P(r[1].startFrame).is(4),P(r[1].planar[0]).is(.5),P(r[1].planar[1]).is(.5),P(r[1].planar[2]).is(0),P(r[1].planar[3]).is(0)},"audio mix clamps output to [-1, 1]":async()=>{let t=new Ee({chunkFrames:4,clamp:!0});async function*e(){yield{planes:[new Float32Array([.9,.9,.9,.9])],sampleRate:4,timestamp:0},yield{planes:[new Float32Array([.8,.8,.8,.8])],sampleRate:4,timestamp:0}}let r=await $r(t.mix(e()));P(r.length).is(1),P(r[0].planar[0]).is(1),P(r[0].planar[1]).is(1),P(r[0].planar[2]).is(1),P(r[0].planar[3]).is(1)},"audio mix fills gaps with silence":async()=>{let t=new Ee({chunkFrames:4,clamp:!1});async function*e(){yield{planes:[new Float32Array([1,1,1,1])],sampleRate:4,timestamp:0},yield{planes:[new Float32Array([2,2,2,2])],sampleRate:4,timestamp:2}}let r=await $r(t.mix(e()));P(r.length).is(3),P(r[0].startFrame).is(0),P(r[0].planar[0]).is(1),P(r[1].startFrame).is(4),P(r[1].planar[0]).is(0),P(r[1].planar[3]).is(0),P(r[2].startFrame).is(8),P(r[2].planar[0]).is(2)},"audio mix truncates negative timestamps":async()=>{let t=new Ee({chunkFrames:4,clamp:!1});async function*e(){yield{planes:[new Float32Array([1,2,3,4])],sampleRate:4,timestamp:-.5}}let r=await $r(t.mix(e()));P(r.length).is(1),P(r[0].startFrame).is(0),P(r[0].planar[0]).is(3),P(r[0].planar[1]).is(4),P(r[0].planar[2]).is(0),P(r[0].planar[3]).is(0)},"audio mix handles stereo planar layout":async()=>{let t=new Ee({chunkFrames:4,clamp:!1});async function*e(){yield{planes:[new Float32Array([1,1,1,1]),new Float32Array([2,2,2,2])],sampleRate:4,timestamp:0}}let r=await $r(t.mix(e()));P(r.length).is(1),P(r[0].channels).is(2),P(r[0].planar.length).is(8),P(r[0].planar[0]).is(1),P(r[0].planar[4]).is(2)},"applyGainToPlanar scales values across multiple channels":async()=>{let t=[new Float32Array([.2,-.4]),new Float32Array([.6,-.8])];rr(t,.5),P(J(t[0][0],.1)).ok(),P(J(t[0][1],-.2)).ok(),P(J(t[1][0],.3)).ok(),P(J(t[1][1],-.4)).ok()},"applyGainToPlanar does not mutate when gain is 1":async()=>{let t=[new Float32Array([.5,-.5])];rr(t,1),P(J(t[0][0],.5)).ok(),P(J(t[0][1],-.5)).ok()},"applyGainToPlanar mutes entirely when gain is 0":async()=>{let t=[new Float32Array([.9,-.9])];rr(t,0),P(t[0][0]).is(0),P(t[0][1]).is(0)},"resampleToPlanar returns original data when sample rates match":async()=>{let e=Fe({numberOfFrames:3,numberOfChannels:1,sampleRate:48e3,copyTo:r=>r.set([.1,.2,.3])},48e3);P(e.frames).is(3),P(e.data.length).is(1),P(J(e.data[0][0],.1)).ok(),P(J(e.data[0][1],.2)).ok(),P(J(e.data[0][2],.3)).ok()},"resampleToPlanar upsamples using linear interpolation":async()=>{let e=Fe({numberOfFrames:2,numberOfChannels:1,sampleRate:1,copyTo:r=>r.set([10,20])},2);P(e.frames).is(4),P(J(e.data[0][0],10)).ok(),P(J(e.data[0][1],15)).ok(),P(J(e.data[0][2],20)).ok(),P(J(e.data[0][3],20)).ok()},"resampleToPlanar downsamples correctly":async()=>{let e=Fe({numberOfFrames:4,numberOfChannels:1,sampleRate:4,copyTo:r=>r.set([1,2,3,4])},2);P(e.frames).is(2),P(J(e.data[0][0],1)).ok(),P(J(e.data[0][1],3)).ok()},"resampleToPlanar processes multi-channel planar data":async()=>{let t=[new Float32Array([1,2]),new Float32Array([3,4])],r=Fe({numberOfFrames:2,numberOfChannels:2,sampleRate:1,copyTo:(n,o)=>{n.set(t[o.planeIndex])}},2);P(r.data.length).is(2),P(J(r.data[0][1],1.5)).ok(),P(J(r.data[1][1],3.5)).ok()},"resampleToPlanar handles zero channels gracefully":async()=>{let e=Fe({numberOfFrames:10,numberOfChannels:0,sampleRate:48e3,copyTo:()=>{throw new Error("Should not be called")}},44100);P(e.data.length).is(0),P(e.frames).is(0)},"resampleToPlanar enforces minimum of 1 frame on aggressive downsample":async()=>{let e=Fe({numberOfFrames:1,numberOfChannels:1,sampleRate:48e3,copyTo:r=>r.set([.8])},8e3);P(e.frames).is(1),P(e.data[0].length).is(1),P(J(e.data[0][0],.8)).ok()},"resampleToPlanar calls copyTo with strict contract shape":async()=>{let t=null;Fe({numberOfFrames:2,numberOfChannels:1,sampleRate:48e3,copyTo:(r,n)=>{t=n}},44100),P(t).not.is(null),P(t.planeIndex).is(0),P(t.format).is("f32-planar")},"5s long export at 30fps renders exacly 150 frames":async()=>{let{omni:t,videoA:e,driver:r,resolveMedia:n}=await Ro(),{timeline:o}=new q({timeline:t.timeline(a=>a.sequence(a.video(e,{duration:2e3}),a.gap(500),a.video(e,{duration:2e3}),a.audio(e,{duration:500})))}),s=ho({timeline:o,fps:je(30),driver:r,resolveMedia:n}),i=0;for await(let a of s)a.close(),i++;P(i).is(150)},"5s long audio export at 48000Hz renders exactly 240000 frames":async()=>{let{omni:t,videoA:e,resolveMedia:r}=await Ro(),{timeline:n}=new q({timeline:t.timeline(i=>i.sequence(i.video(e,{duration:2e3}),i.gap(500),i.video(e,{duration:2e3}),i.audio(e,{duration:500})))}),o=po({timeline:n,resolveMedia:r}),s=0;for await(let i of o)s+=i.numberOfFrames,i.close();P(s).is(24e4)}});await We.run({omniTest:_c,renderersTest:Ec});
|
|
2420
2420
|
/*! Bundled license information:
|
|
2421
2421
|
|
|
2422
2422
|
mediabunny/dist/modules/src/misc.js:
|