@motionscript/browser 0.1.0-alpha.3 → 0.1.0-alpha.5
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/CHANGELOG.md +95 -0
- package/LICENSE +201 -201
- package/NOTICE +48 -0
- package/README.md +118 -69
- package/dist/asset-bytes.js.map +1 -1
- package/dist/audio/bus-graph.d.ts +2 -2
- package/dist/audio/bus-graph.d.ts.map +1 -1
- package/dist/audio/bus-graph.js +6 -6
- package/dist/audio/bus-graph.js.map +1 -1
- package/dist/audio/filter-graph.d.ts +5 -5
- package/dist/audio/filter-graph.d.ts.map +1 -1
- package/dist/audio/filter-graph.js +15 -15
- package/dist/audio/filter-graph.js.map +1 -1
- package/dist/audio/index.js.map +1 -1
- package/dist/audio/loop-region.d.ts +31 -0
- package/dist/audio/loop-region.d.ts.map +1 -0
- package/dist/audio/loop-region.js +43 -0
- package/dist/audio/loop-region.js.map +1 -0
- package/dist/audio/mixer.d.ts.map +1 -1
- package/dist/audio/mixer.js +26 -10
- package/dist/audio/mixer.js.map +1 -1
- package/dist/audio/player.d.ts +4 -4
- package/dist/audio/player.d.ts.map +1 -1
- package/dist/audio/player.js +15 -14
- package/dist/audio/player.js.map +1 -1
- package/dist/browser/THIRD_PARTY_LICENSES.txt +432 -0
- package/dist/browser/audio.js +1 -1
- package/dist/browser/chunks/chunk-2MAFJWBZ.js +2 -0
- package/dist/browser/chunks/chunk-2MAFJWBZ.js.map +7 -0
- package/dist/browser/index.js +130 -276
- package/dist/browser/index.js.map +4 -4
- package/dist/browser/manifest.json +19 -2
- package/dist/concat.js.map +1 -1
- package/dist/decode/image-levels.js.map +1 -1
- package/dist/decode/levels.js.map +1 -1
- package/dist/decode/video-levels.js.map +1 -1
- package/dist/dynamic-nodes.js.map +1 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +1 -0
- package/dist/engine.js.map +1 -1
- package/dist/exporter.d.ts +8 -2
- package/dist/exporter.d.ts.map +1 -1
- package/dist/exporter.js +8 -7
- package/dist/exporter.js.map +1 -1
- package/dist/getter.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/measure-context.js.map +1 -1
- package/dist/mix-timeline-audio.d.ts +2 -2
- package/dist/mix-timeline-audio.d.ts.map +1 -1
- package/dist/mix-timeline-audio.js +1 -2
- package/dist/mix-timeline-audio.js.map +1 -1
- package/dist/render-context.js.map +1 -1
- package/dist/screenshot.d.ts +3 -3
- package/dist/screenshot.d.ts.map +1 -1
- package/dist/screenshot.js +1 -2
- package/dist/screenshot.js.map +1 -1
- package/dist/still.d.ts +6 -4
- package/dist/still.d.ts.map +1 -1
- package/dist/still.js +12 -9
- package/dist/still.js.map +1 -1
- package/dist/storage-adapter.d.ts.map +1 -1
- package/dist/storage-adapter.js +5 -4
- package/dist/storage-adapter.js.map +1 -1
- package/dist/three/renderer.js.map +1 -1
- package/dist/ticker.d.ts +22 -4
- package/dist/ticker.d.ts.map +1 -1
- package/dist/ticker.js +65 -28
- package/dist/ticker.js.map +1 -1
- package/package.json +7 -6
- package/dist/browser/chunks/chunk-M7XD73ED.js +0 -2
- package/dist/browser/chunks/chunk-M7XD73ED.js.map +0 -7
- package/dist/output.d.ts +0 -7
- package/dist/output.d.ts.map +0 -1
- package/dist/output.js +0 -6
- package/dist/output.js.map +0 -1
package/dist/browser/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as Cy,b as gl,c as th,f as yl,g as rh,h as Py,i as wl}from"./chunks/chunk-2MAFJWBZ.js";import{a as vy,b as _y}from"./chunks/chunk-FY3BTKY4.js";var Q0=vy((s4,qd)=>{(r=>{"use strict";var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,s=(S,A)=>{for(var I in A)e(S,I,{get:A[I],enumerable:!0})},a=(S,A,I,U)=>{if(A&&typeof A=="object"||typeof A=="function")for(let j of n(A))!i.call(S,j)&&j!==I&&e(S,j,{get:()=>A[j],enumerable:!(U=t(A,j))||U.enumerable});return S},o=S=>a(e({},"__esModule",{value:!0}),S),c=(S,A,I)=>new Promise((U,j)=>{var $=B=>{try{se(I.next(B))}catch(re){j(re)}},H=B=>{try{se(I.throw(B))}catch(re){j(re)}},se=B=>B.done?U(B.value):Promise.resolve(B.value).then($,H);se((I=I.apply(S,A)).next())}),l={};s(l,{analyzeMetafile:()=>my,analyzeMetafileSync:()=>wy,build:()=>uy,buildSync:()=>py,context:()=>dy,default:()=>xy,formatMessages:()=>fy,formatMessagesSync:()=>yy,initialize:()=>ky,stop:()=>by,transform:()=>hy,transformSync:()=>gy,version:()=>ly}),r.exports=o(l);function u(S){let A=U=>{if(U===null)I.write8(0);else if(typeof U=="boolean")I.write8(1),I.write8(+U);else if(typeof U=="number")I.write8(2),I.write32(U|0);else if(typeof U=="string")I.write8(3),I.write(f(U));else if(U instanceof Uint8Array)I.write8(4),I.write(U);else if(U instanceof Array){I.write8(5),I.write32(U.length);for(let j of U)A(j)}else{let j=Object.keys(U);I.write8(6),I.write32(j.length);for(let $ of j)I.write(f($)),A(U[$])}},I=new h;return I.write32(0),I.write32(S.id<<1|+!S.isRequest),A(S.value),y(I.buf,I.len-4,0),I.buf.subarray(0,I.len)}function d(S){let A=()=>{switch(I.read8()){case 0:return null;case 1:return!!I.read8();case 2:return I.read32();case 3:return p(I.read());case 4:return I.read();case 5:{let H=I.read32(),se=[];for(let B=0;B<H;B++)se.push(A());return se}case 6:{let H=I.read32(),se={};for(let B=0;B<H;B++)se[p(I.read())]=A();return se}default:throw new Error("Invalid packet")}},I=new h(S),U=I.read32(),j=(U&1)===0;U>>>=1;let $=A();if(I.ptr!==S.length)throw new Error("Invalid packet");return{id:U,isRequest:j,value:$}}var h=class{constructor(S=new Uint8Array(1024)){this.buf=S,this.len=0,this.ptr=0}_write(S){if(this.len+S>this.buf.length){let A=new Uint8Array((this.len+S)*2);A.set(this.buf),this.buf=A}return this.len+=S,this.len-S}write8(S){let A=this._write(1);this.buf[A]=S}write32(S){let A=this._write(4);y(this.buf,S,A)}write(S){let A=this._write(4+S.length);y(this.buf,S.length,A),this.buf.set(S,A+4)}_read(S){if(this.ptr+S>this.buf.length)throw new Error("Invalid packet");return this.ptr+=S,this.ptr-S}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let S=this.read32(),A=new Uint8Array(S),I=this._read(A.length);return A.set(this.buf.subarray(I,I+S)),A}},f,p,m;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let S=new TextEncoder,A=new TextDecoder;f=I=>S.encode(I),p=I=>A.decode(I),m='new TextEncoder().encode("")'}else if(typeof Buffer<"u")f=S=>Buffer.from(S),p=S=>{let{buffer:A,byteOffset:I,byteLength:U}=S;return Buffer.from(A,I,U).toString()},m='Buffer.from("")';else throw new Error("No UTF-8 codec found");if(!(f("")instanceof Uint8Array))throw new Error(`Invariant violation: "${m} instanceof Uint8Array" is incorrectly false
|
|
2
2
|
|
|
3
3
|
This indicates that your JavaScript environment is broken. You cannot use
|
|
4
4
|
esbuild in this environment because esbuild relies on this invariant. This
|
|
5
5
|
is not a problem with esbuild. You need to fix your environment instead.
|
|
6
|
-
`);function g(
|
|
7
|
-
`;break;case 114:ae+="\r";break;case 116:ae+=" ";break;case 117:{let de=0;for(let Be=0;Be<4;Be++)te=x[B++],de<<=4,te>=48&&te<=57?de|=te-48:te>=97&&te<=102?de|=te+-87:te>=65&&te<=70?de|=te+-55:k(x,--B);ae+=b(de);break}default:k(x,--B);break}else if(te<=127)ae+=b(te);else if((te&224)===192)ae+=b((te&31)<<6|x[B++]&63);else if((te&240)===224)ae+=b((te&15)<<12|(x[B++]&63)<<6|x[B++]&63);else if((te&248)==240){let de=(te&7)<<18|(x[B++]&63)<<12|(x[B++]&63)<<6|x[B++]&63;de>65535&&(de-=65536,ae+=b(de>>10&1023|55296),de=56320|de&1023),ae+=b(de)}ae[0];break}case 91:{ae=[],v.push($),E.push(se),U.push(H),$=null,se=ae,H=1;continue}case 123:{ae={},v.push($),E.push(se),U.push(H),$=null,se=ae,H=2;continue}case 93:{H!==1&&k(x,--B),ae=se,$=v.pop(),se=E.pop(),H=U.pop();break}case 125:{H!==2&&k(x,--B),ae=se,$=v.pop(),se=E.pop(),H=U.pop();break}default:k(x,--B)}for(te=x[B];te<=32;)te=x[++B];switch(H){case 0:{if(B===G)return ae;break}case 1:{if(se.push(ae),te===44){B++;continue}if(te===93)continue;break}case 2:{if($===null){if($=ae,te===58){B++;continue}}else{if(se[$]=ae,$=null,te===44){B++;continue}if(te===125)continue}break}}break}k(x,B)}var S=JSON.stringify,_="warning",M="silent";function P(x,v){let E=[];for(let U of x){if(bt(U,v),U.indexOf(",")>=0)throw new Error(`Invalid ${v}: ${U}`);E.push(U)}return E.join(",")}var A=()=>null,F=x=>typeof x=="boolean"?null:"a boolean",I=x=>typeof x=="string"?null:"a string",O=x=>x instanceof RegExp?null:"a RegExp object",Q=x=>typeof x=="number"&&x===(x|0)?null:"an integer",ge=x=>typeof x=="number"&&x===(x|0)&&x>=0&&x<=65535?null:"a valid port number",be=x=>typeof x=="function"?null:"a function",J=x=>Array.isArray(x)?null:"an array",Ae=x=>Array.isArray(x)&&x.every(v=>typeof v=="string")?null:"an array of strings",Re=x=>typeof x=="object"&&x!==null&&!Array.isArray(x)?null:"an object",et=x=>typeof x=="object"&&x!==null?null:"an array or an object",Ia=x=>x instanceof WebAssembly.Module?null:"a WebAssembly.Module",Wd=x=>typeof x=="object"&&!Array.isArray(x)?null:"an object or null",qd=x=>typeof x=="string"||typeof x=="boolean"?null:"a string or a boolean",B0=x=>typeof x=="string"||typeof x=="object"&&x!==null&&!Array.isArray(x)?null:"a string or an object",jd=x=>typeof x=="string"||Array.isArray(x)&&x.every(v=>typeof v=="string")?null:"a string or an array of strings",Gd=x=>typeof x=="string"||x instanceof Uint8Array?null:"a string or a Uint8Array",D0=x=>typeof x=="string"||x instanceof URL?null:"a string or a URL";function R(x,v,E,U){let G=x[E];if(v[E+""]=!0,G===void 0)return;let $=U(G);if($!==null)throw new Error(`${S(E)} must be ${$}`);return G}function tt(x,v,E){for(let U in x)if(!(U in v))throw new Error(`Invalid option ${E}: ${S(U)}`)}function O0(x){let v=Object.create(null),E=R(x,v,"wasmURL",D0),U=R(x,v,"wasmModule",Ia),G=R(x,v,"worker",F);return tt(x,v,"in initialize() call"),{wasmURL:E,wasmModule:U,worker:G}}function Kd(x){let v;if(x!==void 0){v=Object.create(null);for(let E in x){let U=x[E];if(typeof U=="string"||U===!1)v[E]=U;else throw new Error(`Expected ${S(E)} in mangle cache to map to either a string or false`)}}return v}function Ma(x,v,E,U,G){let $=R(v,E,"color",F),H=R(v,E,"logLevel",I),se=R(v,E,"logLimit",Q),B=R(v,E,"logStyle",I);$!==void 0?x.push(`--color=${$}`):U&&x.push("--color=true"),x.push(`--log-level=${H||G}`),x.push(`--log-limit=${se||0}`),B&&x.push(`--log-style=${B}`)}function bt(x,v,E){if(typeof x!="string")throw new Error(`Expected value for ${v}${E!==void 0?" "+S(E):""} to be a string, got ${typeof x} instead`);return x}function $d(x,v,E){let U=R(v,E,"legalComments",I),G=R(v,E,"sourceRoot",I),$=R(v,E,"sourcesContent",F),H=R(v,E,"target",jd),se=R(v,E,"format",I),B=R(v,E,"globalName",I),te=R(v,E,"mangleProps",O),ae=R(v,E,"reserveProps",O),de=R(v,E,"mangleQuoted",F),Be=R(v,E,"minify",F),Ee=R(v,E,"minifySyntax",F),Le=R(v,E,"minifyWhitespace",F),Ue=R(v,E,"minifyIdentifiers",F),pe=R(v,E,"lineLimit",Q),Qe=R(v,E,"drop",Ae),me=R(v,E,"dropLabels",Ae),fe=R(v,E,"charset",I),Z=R(v,E,"treeShaking",F),q=R(v,E,"ignoreAnnotations",F),D=R(v,E,"jsx",I),V=R(v,E,"jsxFactory",I),W=R(v,E,"jsxFragment",I),ee=R(v,E,"jsxImportSource",I),le=R(v,E,"jsxDev",F),N=R(v,E,"jsxSideEffects",F),X=R(v,E,"define",Re),oe=R(v,E,"logOverride",Re),Te=R(v,E,"supported",Re),C=R(v,E,"pure",Ae),L=R(v,E,"keepNames",F),re=R(v,E,"platform",I),he=R(v,E,"tsconfigRaw",B0),Me=R(v,E,"absPaths",Ae);if(U&&x.push(`--legal-comments=${U}`),G!==void 0&&x.push(`--source-root=${G}`),$!==void 0&&x.push(`--sources-content=${$}`),H&&x.push(`--target=${P(Array.isArray(H)?H:[H],"target")}`),se&&x.push(`--format=${se}`),B&&x.push(`--global-name=${B}`),re&&x.push(`--platform=${re}`),he&&x.push(`--tsconfig-raw=${typeof he=="string"?he:JSON.stringify(he)}`),Be&&x.push("--minify"),Ee&&x.push("--minify-syntax"),Le&&x.push("--minify-whitespace"),Ue&&x.push("--minify-identifiers"),pe&&x.push(`--line-limit=${pe}`),fe&&x.push(`--charset=${fe}`),Z!==void 0&&x.push(`--tree-shaking=${Z}`),q&&x.push("--ignore-annotations"),Qe)for(let ue of Qe)x.push(`--drop:${bt(ue,"drop")}`);if(me&&x.push(`--drop-labels=${P(me,"drop label")}`),Me&&x.push(`--abs-paths=${P(Me,"abs paths")}`),te&&x.push(`--mangle-props=${Ba(te)}`),ae&&x.push(`--reserve-props=${Ba(ae)}`),de!==void 0&&x.push(`--mangle-quoted=${de}`),D&&x.push(`--jsx=${D}`),V&&x.push(`--jsx-factory=${V}`),W&&x.push(`--jsx-fragment=${W}`),ee&&x.push(`--jsx-import-source=${ee}`),le&&x.push("--jsx-dev"),N&&x.push("--jsx-side-effects"),X)for(let ue in X){if(ue.indexOf("=")>=0)throw new Error(`Invalid define: ${ue}`);x.push(`--define:${ue}=${bt(X[ue],"define",ue)}`)}if(oe)for(let ue in oe){if(ue.indexOf("=")>=0)throw new Error(`Invalid log override: ${ue}`);x.push(`--log-override:${ue}=${bt(oe[ue],"log override",ue)}`)}if(Te)for(let ue in Te){if(ue.indexOf("=")>=0)throw new Error(`Invalid supported: ${ue}`);let ze=Te[ue];if(typeof ze!="boolean")throw new Error(`Expected value for supported ${S(ue)} to be a boolean, got ${typeof ze} instead`);x.push(`--supported:${ue}=${ze}`)}if(C)for(let ue of C)x.push(`--pure:${bt(ue,"pure")}`);L&&x.push("--keep-names")}function L0(x,v,E,U,G){var $;let H=[],se=[],B=Object.create(null),te=null,ae=null;Ma(H,v,B,E,U),$d(H,v,B);let de=R(v,B,"sourcemap",qd),Be=R(v,B,"bundle",F),Ee=R(v,B,"splitting",F),Le=R(v,B,"preserveSymlinks",F),Ue=R(v,B,"metafile",F),pe=R(v,B,"outfile",I),Qe=R(v,B,"outdir",I),me=R(v,B,"outbase",I),fe=R(v,B,"tsconfig",I),Z=R(v,B,"resolveExtensions",Ae),q=R(v,B,"nodePaths",Ae),D=R(v,B,"mainFields",Ae),V=R(v,B,"conditions",Ae),W=R(v,B,"external",Ae),ee=R(v,B,"packages",I),le=R(v,B,"alias",Re),N=R(v,B,"loader",Re),X=R(v,B,"outExtension",Re),oe=R(v,B,"publicPath",I),Te=R(v,B,"entryNames",I),C=R(v,B,"chunkNames",I),L=R(v,B,"assetNames",I),re=R(v,B,"inject",Ae),he=R(v,B,"banner",Re),Me=R(v,B,"footer",Re),ue=R(v,B,"entryPoints",et),ze=R(v,B,"absWorkingDir",I),De=R(v,B,"stdin",Re),Fe=($=R(v,B,"write",F))!=null?$:G,kt=R(v,B,"allowOverwrite",F),rt=R(v,B,"mangleCache",Re);if(B.plugins=!0,tt(v,B,`in ${x}() call`),de&&H.push(`--sourcemap${de===!0?"":`=${de}`}`),Be&&H.push("--bundle"),kt&&H.push("--allow-overwrite"),Ee&&H.push("--splitting"),Le&&H.push("--preserve-symlinks"),Ue&&H.push("--metafile"),pe&&H.push(`--outfile=${pe}`),Qe&&H.push(`--outdir=${Qe}`),me&&H.push(`--outbase=${me}`),fe&&H.push(`--tsconfig=${fe}`),ee&&H.push(`--packages=${ee}`),Z&&H.push(`--resolve-extensions=${P(Z,"resolve extension")}`),oe&&H.push(`--public-path=${oe}`),Te&&H.push(`--entry-names=${Te}`),C&&H.push(`--chunk-names=${C}`),L&&H.push(`--asset-names=${L}`),D&&H.push(`--main-fields=${P(D,"main field")}`),V&&H.push(`--conditions=${P(V,"condition")}`),W)for(let xe of W)H.push(`--external:${bt(xe,"external")}`);if(le)for(let xe in le){if(xe.indexOf("=")>=0)throw new Error(`Invalid package name in alias: ${xe}`);H.push(`--alias:${xe}=${bt(le[xe],"alias",xe)}`)}if(he)for(let xe in he){if(xe.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${xe}`);H.push(`--banner:${xe}=${bt(he[xe],"banner",xe)}`)}if(Me)for(let xe in Me){if(xe.indexOf("=")>=0)throw new Error(`Invalid footer file type: ${xe}`);H.push(`--footer:${xe}=${bt(Me[xe],"footer",xe)}`)}if(re)for(let xe of re)H.push(`--inject:${bt(xe,"inject")}`);if(N)for(let xe in N){if(xe.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${xe}`);H.push(`--loader:${xe}=${bt(N[xe],"loader",xe)}`)}if(X)for(let xe in X){if(xe.indexOf("=")>=0)throw new Error(`Invalid out extension: ${xe}`);H.push(`--out-extension:${xe}=${bt(X[xe],"out extension",xe)}`)}if(ue)if(Array.isArray(ue))for(let xe=0,kr=ue.length;xe<kr;xe++){let Ut=ue[xe];if(typeof Ut=="object"&&Ut!==null){let ar=Object.create(null),xr=R(Ut,ar,"in",I),zt=R(Ut,ar,"out",I);if(tt(Ut,ar,"in entry point at index "+xe),xr===void 0)throw new Error('Missing property "in" for entry point at index '+xe);if(zt===void 0)throw new Error('Missing property "out" for entry point at index '+xe);se.push([zt,xr])}else se.push(["",bt(Ut,"entry point at index "+xe)])}else for(let xe in ue)se.push([xe,bt(ue[xe],"entry point",xe)]);if(De){let xe=Object.create(null),kr=R(De,xe,"contents",Gd),Ut=R(De,xe,"resolveDir",I),ar=R(De,xe,"sourcefile",I),xr=R(De,xe,"loader",I);tt(De,xe,'in "stdin" object'),ar&&H.push(`--sourcefile=${ar}`),xr&&H.push(`--loader=${xr}`),Ut&&(ae=Ut),typeof kr=="string"?te=f(kr):kr instanceof Uint8Array&&(te=kr)}let br=[];if(q)for(let xe of q)xe+="",br.push(xe);return{entries:se,flags:H,write:Fe,stdinContents:te,stdinResolveDir:ae,absWorkingDir:ze,nodePaths:br,mangleCache:Kd(rt)}}function U0(x,v,E,U){let G=[],$=Object.create(null);Ma(G,v,$,E,U),$d(G,v,$);let H=R(v,$,"sourcemap",qd),se=R(v,$,"sourcefile",I),B=R(v,$,"loader",I),te=R(v,$,"banner",I),ae=R(v,$,"footer",I),de=R(v,$,"mangleCache",Re);return tt(v,$,`in ${x}() call`),H&&G.push(`--sourcemap=${H===!0?"external":H}`),se&&G.push(`--sourcefile=${se}`),B&&G.push(`--loader=${B}`),te&&G.push(`--banner=${te}`),ae&&G.push(`--footer=${ae}`),{flags:G,mangleCache:Kd(de)}}function z0(x){let v={},E={didClose:!1,reason:""},U={},G=0,$=0,H=new Uint8Array(16*1024),se=0,B=fe=>{let Z=se+fe.length;if(Z>H.length){let D=new Uint8Array(Z*2);D.set(H),H=D}H.set(fe,se),se+=fe.length;let q=0;for(;q+4<=se;){let D=g(H,q);if(q+4+D>se)break;q+=4,Le(H.subarray(q,q+D)),q+=D}q>0&&(H.copyWithin(0,q,se),se-=q)},te=fe=>{E.didClose=!0,fe&&(E.reason=": "+(fe.message||fe));let Z="The service was stopped"+E.reason;for(let q in U)U[q](Z,null);U={}},ae=(fe,Z,q)=>{if(E.didClose)return q("The service is no longer running"+E.reason,null);let D=G++;U[D]=(V,W)=>{try{q(V,W)}finally{fe&&fe.unref()}},fe&&fe.ref(),x.writeToStdin(u({id:D,isRequest:!0,value:Z}))},de=(fe,Z)=>{if(E.didClose)throw new Error("The service is no longer running"+E.reason);x.writeToStdin(u({id:fe,isRequest:!1,value:Z}))},Be=(fe,Z)=>c(null,null,function*(){try{if(Z.command==="ping"){de(fe,{});return}if(typeof Z.key=="number"){let q=v[Z.key];if(!q)return;let D=q[Z.command];if(D){yield D(fe,Z);return}}throw new Error("Invalid command: "+Z.command)}catch(q){let D=[Sn(q,x,null,void 0,"")];try{de(fe,{errors:D})}catch{}}}),Ee=!0,Le=fe=>{if(Ee){Ee=!1;let q=String.fromCharCode(...fe);if(q!=="0.28.2")throw new Error(`Cannot start service: Host version "0.28.2" does not match binary version ${S(q)}`);return}let Z=d(fe);if(Z.isRequest)Be(Z.id,Z.value);else{let q=U[Z.id];delete U[Z.id],Z.value.error?q(Z.value.error,{}):q(null,Z.value)}};return{readFromStdout:B,afterClose:te,service:{buildOrContext:({callName:fe,refs:Z,options:q,isTTY:D,defaultWD:V,callback:W})=>{let ee=0,le=$++,N={},X={ref(){++ee===1&&Z&&Z.ref()},unref(){--ee===0&&(delete v[le],Z&&Z.unref())}};v[le]=N,X.ref(),N0(fe,le,ae,de,X,x,N,q,D,V,(oe,Te)=>{try{W(oe,Te)}finally{X.unref()}})},transform:({callName:fe,refs:Z,input:q,options:D,isTTY:V,fs:W,callback:ee})=>{let le=Xd(),N=X=>{try{if(typeof q!="string"&&!(q instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:oe,mangleCache:Te}=U0(fe,D,V,M),C={command:"transform",flags:oe,inputFS:X!==null,input:X!==null?f(X):typeof q=="string"?f(q):q};Te&&(C.mangleCache=Te),ae(Z,C,(L,re)=>{if(L)return ee(new Error(L),null);let he=ri(re.errors,le),Me=ri(re.warnings,le),ue=1,ze=()=>{if(--ue===0){let De={warnings:Me,code:re.code,map:re.map,mangleCache:void 0,legalComments:void 0};"legalComments"in re&&(De.legalComments=re?.legalComments),re.mangleCache&&(De.mangleCache=re?.mangleCache),ee(null,De)}};if(he.length>0)return ee(bs("Transform failed",he,Me),null);re.codeFS&&(ue++,W.readFile(re.code,(De,Fe)=>{De!==null?ee(De,null):(re.code=Fe,ze())})),re.mapFS&&(ue++,W.readFile(re.map,(De,Fe)=>{De!==null?ee(De,null):(re.map=Fe,ze())})),ze()})}catch(oe){let Te=[];try{Ma(Te,D,{},V,M)}catch{}let C=Sn(oe,x,le,void 0,"");ae(Z,{command:"error",flags:Te,error:C},()=>{C.detail=le.load(C.detail),ee(bs("Transform failed",[C],[]),null)})}};if((typeof q=="string"||q instanceof Uint8Array)&&q.length>1024*1024){let X=N;N=()=>W.writeFile(q,X)}N(null)},formatMessages:({callName:fe,refs:Z,messages:q,options:D,callback:V})=>{if(!D)throw new Error(`Missing second argument in ${fe}() call`);let W={},ee=R(D,W,"kind",I),le=R(D,W,"color",F),N=R(D,W,"terminalWidth",Q),X=R(D,W,"logStyle",I);if(tt(D,W,`in ${fe}() call`),ee===void 0)throw new Error(`Missing "kind" in ${fe}() call`);if(ee!=="error"&&ee!=="warning")throw new Error(`Expected "kind" to be "error" or "warning" in ${fe}() call`);let oe={command:"format-msgs",messages:wr(q,"messages",null,"",N),isWarning:ee==="warning"};le!==void 0&&(oe.color=le),N!==void 0&&(oe.terminalWidth=N),X!==void 0&&(oe.logStyle=X),ae(Z,oe,(Te,C)=>{if(Te)return V(new Error(Te),null);V(null,C.messages)})},analyzeMetafile:({callName:fe,refs:Z,metafile:q,options:D,callback:V})=>{D===void 0&&(D={});let W={},ee=R(D,W,"color",F),le=R(D,W,"verbose",F);tt(D,W,`in ${fe}() call`);let N={command:"analyze-metafile",metafile:q};ee!==void 0&&(N.color=ee),le!==void 0&&(N.verbose=le),ae(Z,N,(X,oe)=>{if(X)return V(new Error(X),null);V(null,oe.result)})}}}}function N0(x,v,E,U,G,$,H,se,B,te,ae){let de=Xd(),Be=x==="context",Ee=(pe,Qe)=>{let me=[];try{Ma(me,se,{},B,_)}catch{}let fe=Sn(pe,$,de,void 0,Qe);E(G,{command:"error",flags:me,error:fe},()=>{fe.detail=de.load(fe.detail),ae(bs(Be?"Context failed":"Build failed",[fe],[]),null)})},Le;if(typeof se=="object"){let pe=se.plugins;if(pe!==void 0){if(!Array.isArray(pe))return Ee(new Error('"plugins" must be an array'),"");Le=pe}}if(Le&&Le.length>0){if($.isSync)return Ee(new Error("Cannot use plugins in synchronous API calls"),"");V0(v,E,U,G,$,H,se,Le,de).then(pe=>{if(!pe.ok)return Ee(pe.error,pe.pluginName);try{Ue(pe.requestPlugins,pe.runOnEndCallbacks,pe.scheduleOnDisposeCallbacks)}catch(Qe){Ee(Qe,"")}},pe=>Ee(pe,""));return}try{Ue(null,(pe,Qe)=>Qe([],[]),()=>{})}catch(pe){Ee(pe,"")}function Ue(pe,Qe,me){let fe=$.hasFS,{entries:Z,flags:q,write:D,stdinContents:V,stdinResolveDir:W,absWorkingDir:ee,nodePaths:le,mangleCache:N}=L0(x,se,B,_,fe);if(D&&!$.hasFS)throw new Error('The "write" option is unavailable in this environment');let X={command:"build",key:v,entries:Z,flags:q,write:D,stdinContents:V,stdinResolveDir:W,absWorkingDir:ee||te,nodePaths:le,context:Be};pe&&(X.plugins=pe),N&&(X.mangleCache=N);let oe=(L,re)=>{let he={errors:ri(L.errors,de),warnings:ri(L.warnings,de),outputFiles:void 0,metafile:void 0,mangleCache:void 0},Me=he.errors.slice(),ue=he.warnings.slice();L.outputFiles&&(he.outputFiles=L.outputFiles.map(W0)),L.metafile&&L.metafile.length&&(he.metafile=q0(L.metafile)),L.mangleCache&&(he.mangleCache=L.mangleCache),L.writeToStdout!==void 0&&console.log(p(L.writeToStdout).replace(/\n$/,"")),Qe(he,(ze,De)=>{if(Me.length>0||ze.length>0){let Fe=bs("Build failed",Me.concat(ze),ue.concat(De));return re(Fe,null,ze,De)}re(null,he,ze,De)})},Te,C;Be&&(H["on-end"]=(L,re)=>new Promise(he=>{oe(re,(Me,ue,ze,De)=>{let Fe={errors:ze,warnings:De};C&&C(Me,ue),Te=void 0,C=void 0,U(L,Fe),he()})})),E(G,X,(L,re)=>{if(L)return ae(new Error(L),null);if(!Be)return oe(re,(ue,ze)=>(me(),ae(ue,ze)));if(re.errors.length>0)return ae(bs("Context failed",re.errors,re.warnings),null);let he=!1,Me={rebuild:()=>(Te||(Te=new Promise((ue,ze)=>{let De;C=(kt,rt)=>{De||(De=()=>kt?ze(kt):ue(rt))};let Fe=()=>{E(G,{command:"rebuild",key:v},(rt,br)=>{rt?ze(new Error(rt)):De?De():Fe()})};Fe()})),Te),watch:(ue={})=>new Promise((ze,De)=>{if(!$.hasFS)throw new Error('Cannot use the "watch" API in this environment');let Fe={},kt=R(ue,Fe,"delay",Q);tt(ue,Fe,"in watch() call");let rt={command:"watch",key:v};kt&&(rt.delay=kt),E(G,rt,br=>{br?De(new Error(br)):ze(void 0)})}),serve:(ue={})=>new Promise((ze,De)=>{if(!$.hasFS)throw new Error('Cannot use the "serve" API in this environment');let Fe={},kt=R(ue,Fe,"port",ge),rt=R(ue,Fe,"host",I),br=R(ue,Fe,"servedir",I),xe=R(ue,Fe,"keyfile",I),kr=R(ue,Fe,"certfile",I),Ut=R(ue,Fe,"fallback",I),ar=R(ue,Fe,"cors",Re),xr=R(ue,Fe,"onRequest",be);tt(ue,Fe,"in serve() call");let zt={command:"serve",key:v,onRequest:!!xr};if(kt!==void 0&&(zt.port=kt),rt!==void 0&&(zt.host=rt),br!==void 0&&(zt.servedir=br),xe!==void 0&&(zt.keyfile=xe),kr!==void 0&&(zt.certfile=kr),Ut!==void 0&&(zt.fallback=Ut),ar){let xs={},ni=R(ar,xs,"origin",jd);tt(ar,xs,'on "cors" object'),Array.isArray(ni)?zt.corsOrigin=ni:ni!==void 0&&(zt.corsOrigin=[ni])}E(G,zt,(xs,ni)=>{if(xs)return De(new Error(xs));xr&&(H["serve-request"]=(sy,ay)=>{xr(ay.args),U(sy,{})}),ze(ni)})}),cancel:()=>new Promise(ue=>{if(he)return ue();E(G,{command:"cancel",key:v},()=>{ue()})}),dispose:()=>new Promise(ue=>{if(he)return ue();he=!0,E(G,{command:"dispose",key:v},()=>{ue(),me(),G.unref()})})};G.ref(),ae(null,Me)})}}var V0=(x,v,E,U,G,$,H,se,B)=>c(null,null,function*(){let te=[],ae=[],de={},Be={},Ee=[],Le=0,Ue=0,pe=[],Qe=!1;se=[...se];for(let Z of se){let q={};if(typeof Z!="object")throw new Error(`Plugin at index ${Ue} must be an object`);let D=R(Z,q,"name",I);if(typeof D!="string"||D==="")throw new Error(`Plugin at index ${Ue} is missing a name`);try{let V=R(Z,q,"setup",be);if(typeof V!="function")throw new Error("Plugin is missing a setup function");tt(Z,q,`on plugin ${S(D)}`);let W={name:D,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};Ue++;let le=V({initialOptions:H,resolve:(N,X={})=>{if(!Qe)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof N!="string")throw new Error("The path to resolve must be a string");let oe=Object.create(null),Te=R(X,oe,"pluginName",I),C=R(X,oe,"importer",I),L=R(X,oe,"namespace",I),re=R(X,oe,"resolveDir",I),he=R(X,oe,"kind",I),Me=R(X,oe,"pluginData",A),ue=R(X,oe,"with",Re);return tt(X,oe,"in resolve() call"),new Promise((ze,De)=>{let Fe={command:"resolve",path:N,key:x,pluginName:D};if(Te!=null&&(Fe.pluginName=Te),C!=null&&(Fe.importer=C),L!=null&&(Fe.namespace=L),re!=null&&(Fe.resolveDir=re),he!=null)Fe.kind=he;else throw new Error('Must specify "kind" when calling "resolve"');Me!=null&&(Fe.pluginData=B.store(Me)),ue!=null&&(Fe.with=H0(ue,"with")),v(U,Fe,(kt,rt)=>{kt!==null?De(new Error(kt)):ze({errors:ri(rt.errors,B),warnings:ri(rt.warnings,B),path:rt.path,external:rt.external,sideEffects:rt.sideEffects,namespace:rt.namespace,suffix:rt.suffix,pluginData:B.load(rt.pluginData)})})})},onStart(N){let X='This error came from the "onStart" callback registered here:',oe=Fa(new Error(X),G,"onStart");te.push({name:D,callback:N,note:oe}),W.onStart=!0},onEnd(N){let X='This error came from the "onEnd" callback registered here:',oe=Fa(new Error(X),G,"onEnd");ae.push({name:D,callback:N,note:oe}),W.onEnd=!0},onResolve(N,X){let oe='This error came from the "onResolve" callback registered here:',Te=Fa(new Error(oe),G,"onResolve"),C={},L=R(N,C,"filter",O),re=R(N,C,"namespace",I);if(tt(N,C,`in onResolve() call for plugin ${S(D)}`),L==null)throw new Error("onResolve() call is missing a filter");let he=Le++;de[he]={name:D,callback:X,note:Te},W.onResolve.push({id:he,filter:Ba(L),namespace:re||""})},onLoad(N,X){let oe='This error came from the "onLoad" callback registered here:',Te=Fa(new Error(oe),G,"onLoad"),C={},L=R(N,C,"filter",O),re=R(N,C,"namespace",I);if(tt(N,C,`in onLoad() call for plugin ${S(D)}`),L==null)throw new Error("onLoad() call is missing a filter");let he=Le++;Be[he]={name:D,callback:X,note:Te},W.onLoad.push({id:he,filter:Ba(L),namespace:re||""})},onDispose(N){Ee.push(N)},esbuild:G.esbuild});le&&(yield le),pe.push(W)}catch(V){return{ok:!1,error:V,pluginName:D}}}$["on-start"]=(Z,q)=>c(null,null,function*(){B.clear();let D={errors:[],warnings:[]};yield Promise.all(te.map(V=>c(null,[V],function*({name:W,callback:ee,note:le}){try{let N=yield ee();if(N!=null){if(typeof N!="object")throw new Error(`Expected onStart() callback in plugin ${S(W)} to return an object`);let X={},oe=R(N,X,"errors",J),Te=R(N,X,"warnings",J);tt(N,X,`from onStart() callback in plugin ${S(W)}`),oe!=null&&D.errors.push(...wr(oe,"errors",B,W,void 0)),Te!=null&&D.warnings.push(...wr(Te,"warnings",B,W,void 0))}}catch(N){D.errors.push(Sn(N,G,B,le&&le(),W))}}))),E(Z,D)}),$["on-resolve"]=(Z,q)=>c(null,null,function*(){let D={},V="",W,ee;for(let le of q.ids)try{({name:V,callback:W,note:ee}=de[le]);let N=yield W({path:q.path,importer:q.importer,namespace:q.namespace,resolveDir:q.resolveDir,kind:q.kind,pluginData:B.load(q.pluginData),with:q.with});if(N!=null){if(typeof N!="object")throw new Error(`Expected onResolve() callback in plugin ${S(V)} to return an object`);let X={},oe=R(N,X,"pluginName",I),Te=R(N,X,"path",I),C=R(N,X,"namespace",I),L=R(N,X,"suffix",I),re=R(N,X,"external",F),he=R(N,X,"sideEffects",F),Me=R(N,X,"pluginData",A),ue=R(N,X,"errors",J),ze=R(N,X,"warnings",J),De=R(N,X,"watchFiles",Ae),Fe=R(N,X,"watchDirs",Ae);tt(N,X,`from onResolve() callback in plugin ${S(V)}`),D.id=le,oe!=null&&(D.pluginName=oe),Te!=null&&(D.path=Te),C!=null&&(D.namespace=C),L!=null&&(D.suffix=L),re!=null&&(D.external=re),he!=null&&(D.sideEffects=he),Me!=null&&(D.pluginData=B.store(Me)),ue!=null&&(D.errors=wr(ue,"errors",B,V,void 0)),ze!=null&&(D.warnings=wr(ze,"warnings",B,V,void 0)),De!=null&&(D.watchFiles=Ra(De,"watchFiles")),Fe!=null&&(D.watchDirs=Ra(Fe,"watchDirs"));break}}catch(N){D={id:le,errors:[Sn(N,G,B,ee&&ee(),V)]};break}E(Z,D)}),$["on-load"]=(Z,q)=>c(null,null,function*(){let D={},V="",W,ee;for(let le of q.ids)try{({name:V,callback:W,note:ee}=Be[le]);let N=yield W({path:q.path,namespace:q.namespace,suffix:q.suffix,pluginData:B.load(q.pluginData),with:q.with});if(N!=null){if(typeof N!="object")throw new Error(`Expected onLoad() callback in plugin ${S(V)} to return an object`);let X={},oe=R(N,X,"pluginName",I),Te=R(N,X,"contents",Gd),C=R(N,X,"resolveDir",I),L=R(N,X,"pluginData",A),re=R(N,X,"loader",I),he=R(N,X,"errors",J),Me=R(N,X,"warnings",J),ue=R(N,X,"watchFiles",Ae),ze=R(N,X,"watchDirs",Ae);tt(N,X,`from onLoad() callback in plugin ${S(V)}`),D.id=le,oe!=null&&(D.pluginName=oe),Te instanceof Uint8Array?D.contents=Te:Te!=null&&(D.contents=f(Te)),C!=null&&(D.resolveDir=C),L!=null&&(D.pluginData=B.store(L)),re!=null&&(D.loader=re),he!=null&&(D.errors=wr(he,"errors",B,V,void 0)),Me!=null&&(D.warnings=wr(Me,"warnings",B,V,void 0)),ue!=null&&(D.watchFiles=Ra(ue,"watchFiles")),ze!=null&&(D.watchDirs=Ra(ze,"watchDirs"));break}}catch(N){D={id:le,errors:[Sn(N,G,B,ee&&ee(),V)]};break}E(Z,D)});let me=(Z,q)=>q([],[]);ae.length>0&&(me=(Z,q)=>{c(null,null,function*(){let D=[],V=[];for(let{name:W,callback:ee,note:le}of ae){let N,X;try{let oe=yield ee(Z);if(oe!=null){if(typeof oe!="object")throw new Error(`Expected onEnd() callback in plugin ${S(W)} to return an object`);let Te={},C=R(oe,Te,"errors",J),L=R(oe,Te,"warnings",J);tt(oe,Te,`from onEnd() callback in plugin ${S(W)}`),C!=null&&(N=wr(C,"errors",B,W,void 0)),L!=null&&(X=wr(L,"warnings",B,W,void 0))}}catch(oe){N=[Sn(oe,G,B,le&&le(),W)]}if(N){D.push(...N);try{Z.errors.push(...N)}catch{}}if(X){V.push(...X);try{Z.warnings.push(...X)}catch{}}}q(D,V)})});let fe=()=>{for(let Z of Ee)setTimeout(()=>Z(),0)};return Qe=!0,{ok:!0,requestPlugins:pe,runOnEndCallbacks:me,scheduleOnDisposeCallbacks:fe}});function Xd(){let x=new Map,v=0;return{clear(){x.clear()},load(E){return x.get(E)},store(E){if(E===void 0)return-1;let U=v++;return x.set(U,E),U}}}function Fa(x,v,E){let U,G=!1;return()=>{if(G)return U;G=!0;try{let $=(x.stack+"").split(`
|
|
8
|
-
`);$.splice(1,1);let H=
|
|
9
|
-
`),"")}catch{}return{id:"",pluginName:
|
|
10
|
-
`+
|
|
11
|
-
`),suggestion:""}}break}}return null}function
|
|
6
|
+
`);function g(S,A){return(S[A++]|S[A++]<<8|S[A++]<<16|S[A++]<<24)>>>0}function y(S,A,I){S[I++]=A,S[I++]=A>>8,S[I++]=A>>16,S[I++]=A>>24}var b=String.fromCharCode;function k(S,A,I){let U=S[A],j=1,$=0;for(let H=0;H<A;H++)S[H]===10?(j++,$=0):$++;throw new SyntaxError(I||(A===S.length?"Unexpected end of input while parsing JSON":U>=32&&U<=126?`Unexpected character ${b(U)} in JSON at position ${A} (line ${j}, column ${$})`:`Unexpected byte 0x${U.toString(16)} in JSON at position ${A} (line ${j}, column ${$})`))}function T(S){if(!(S instanceof Uint8Array))throw new Error("JSON input must be a Uint8Array");let A=[],I=[],U=[],j=S.length,$=null,H=0,se,B=0;for(;B<j;){let re=S[B++];if(re<=32)continue;let ae;switch(H===2&&$===null&&re!==34&&re!==125&&k(S,--B),re){case 116:{(S[B++]!==114||S[B++]!==117||S[B++]!==101)&&k(S,--B),ae=!0;break}case 102:{(S[B++]!==97||S[B++]!==108||S[B++]!==115||S[B++]!==101)&&k(S,--B),ae=!1;break}case 110:{(S[B++]!==117||S[B++]!==108||S[B++]!==108)&&k(S,--B),ae=null;break}case 45:case 46:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:{let he=B;for(ae=b(re),re=S[B];;){switch(re){case 43:case 45:case 46:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 101:case 69:{ae+=b(re),re=S[++B];continue}}break}ae=+ae,isNaN(ae)&&k(S,--he,"Invalid number");break}case 34:{for(ae="";B>=j&&k(S,j),re=S[B++],re!==34;)if(re===92)switch(S[B++]){case 34:ae+='"';break;case 47:ae+="/";break;case 92:ae+="\\";break;case 98:ae+="\b";break;case 102:ae+="\f";break;case 110:ae+=`
|
|
7
|
+
`;break;case 114:ae+="\r";break;case 116:ae+=" ";break;case 117:{let he=0;for(let Be=0;Be<4;Be++)re=S[B++],he<<=4,re>=48&&re<=57?he|=re-48:re>=97&&re<=102?he|=re+-87:re>=65&&re<=70?he|=re+-55:k(S,--B);ae+=b(he);break}default:k(S,--B);break}else if(re<=127)ae+=b(re);else if((re&224)===192)ae+=b((re&31)<<6|S[B++]&63);else if((re&240)===224)ae+=b((re&15)<<12|(S[B++]&63)<<6|S[B++]&63);else if((re&248)==240){let he=(re&7)<<18|(S[B++]&63)<<12|(S[B++]&63)<<6|S[B++]&63;he>65535&&(he-=65536,ae+=b(he>>10&1023|55296),he=56320|he&1023),ae+=b(he)}ae[0];break}case 91:{ae=[],A.push($),I.push(se),U.push(H),$=null,se=ae,H=1;continue}case 123:{ae={},A.push($),I.push(se),U.push(H),$=null,se=ae,H=2;continue}case 93:{H!==1&&k(S,--B),ae=se,$=A.pop(),se=I.pop(),H=U.pop();break}case 125:{H!==2&&k(S,--B),ae=se,$=A.pop(),se=I.pop(),H=U.pop();break}default:k(S,--B)}for(re=S[B];re<=32;)re=S[++B];switch(H){case 0:{if(B===j)return ae;break}case 1:{if(se.push(ae),re===44){B++;continue}if(re===93)continue;break}case 2:{if($===null){if($=ae,re===58){B++;continue}}else{if(se[$]=ae,$=null,re===44){B++;continue}if(re===125)continue}break}}break}k(S,B)}var x=JSON.stringify,v="warning",M="silent";function C(S,A){let I=[];for(let U of S){if(bt(U,A),U.indexOf(",")>=0)throw new Error(`Invalid ${A}: ${U}`);I.push(U)}return I.join(",")}var _=()=>null,F=S=>typeof S=="boolean"?null:"a boolean",E=S=>typeof S=="string"?null:"a string",O=S=>S instanceof RegExp?null:"a RegExp object",Q=S=>typeof S=="number"&&S===(S|0)?null:"an integer",ye=S=>typeof S=="number"&&S===(S|0)&&S>=0&&S<=65535?null:"a valid port number",Z=S=>typeof S=="function"?null:"a function",ee=S=>Array.isArray(S)?null:"an array",ve=S=>Array.isArray(S)&&S.every(A=>typeof A=="string")?null:"an array of strings",Re=S=>typeof S=="object"&&S!==null&&!Array.isArray(S)?null:"an object",et=S=>typeof S=="object"&&S!==null?null:"an array or an object",Ra=S=>S instanceof WebAssembly.Module?null:"a WebAssembly.Module",jd=S=>typeof S=="object"&&!Array.isArray(S)?null:"an object or null",Kd=S=>typeof S=="string"||typeof S=="boolean"?null:"a string or a boolean",Z0=S=>typeof S=="string"||typeof S=="object"&&S!==null&&!Array.isArray(S)?null:"a string or an object",$d=S=>typeof S=="string"||Array.isArray(S)&&S.every(A=>typeof A=="string")?null:"a string or an array of strings",Xd=S=>typeof S=="string"||S instanceof Uint8Array?null:"a string or a Uint8Array",J0=S=>typeof S=="string"||S instanceof URL?null:"a string or a URL";function R(S,A,I,U){let j=S[I];if(A[I+""]=!0,j===void 0)return;let $=U(j);if($!==null)throw new Error(`${x(I)} must be ${$}`);return j}function tt(S,A,I){for(let U in S)if(!(U in A))throw new Error(`Invalid option ${I}: ${x(U)}`)}function ey(S){let A=Object.create(null),I=R(S,A,"wasmURL",J0),U=R(S,A,"wasmModule",Ra),j=R(S,A,"worker",F);return tt(S,A,"in initialize() call"),{wasmURL:I,wasmModule:U,worker:j}}function Qd(S){let A;if(S!==void 0){A=Object.create(null);for(let I in S){let U=S[I];if(typeof U=="string"||U===!1)A[I]=U;else throw new Error(`Expected ${x(I)} in mangle cache to map to either a string or false`)}}return A}function Ba(S,A,I,U,j){let $=R(A,I,"color",F),H=R(A,I,"logLevel",E),se=R(A,I,"logLimit",Q),B=R(A,I,"logStyle",E);$!==void 0?S.push(`--color=${$}`):U&&S.push("--color=true"),S.push(`--log-level=${H||j}`),S.push(`--log-limit=${se||0}`),B&&S.push(`--log-style=${B}`)}function bt(S,A,I){if(typeof S!="string")throw new Error(`Expected value for ${A}${I!==void 0?" "+x(I):""} to be a string, got ${typeof S} instead`);return S}function Yd(S,A,I){let U=R(A,I,"legalComments",E),j=R(A,I,"sourceRoot",E),$=R(A,I,"sourcesContent",F),H=R(A,I,"target",$d),se=R(A,I,"format",E),B=R(A,I,"globalName",E),re=R(A,I,"mangleProps",O),ae=R(A,I,"reserveProps",O),he=R(A,I,"mangleQuoted",F),Be=R(A,I,"minify",F),Ee=R(A,I,"minifySyntax",F),Le=R(A,I,"minifyWhitespace",F),Ue=R(A,I,"minifyIdentifiers",F),ge=R(A,I,"lineLimit",Q),Qe=R(A,I,"drop",ve),pe=R(A,I,"dropLabels",ve),me=R(A,I,"charset",E),J=R(A,I,"treeShaking",F),q=R(A,I,"ignoreAnnotations",F),D=R(A,I,"jsx",E),V=R(A,I,"jsxFactory",E),W=R(A,I,"jsxFragment",E),te=R(A,I,"jsxImportSource",E),le=R(A,I,"jsxDev",F),z=R(A,I,"jsxSideEffects",F),X=R(A,I,"define",Re),oe=R(A,I,"logOverride",Re),Te=R(A,I,"supported",Re),P=R(A,I,"pure",ve),L=R(A,I,"keepNames",F),ne=R(A,I,"platform",E),fe=R(A,I,"tsconfigRaw",Z0),Me=R(A,I,"absPaths",ve);if(U&&S.push(`--legal-comments=${U}`),j!==void 0&&S.push(`--source-root=${j}`),$!==void 0&&S.push(`--sources-content=${$}`),H&&S.push(`--target=${C(Array.isArray(H)?H:[H],"target")}`),se&&S.push(`--format=${se}`),B&&S.push(`--global-name=${B}`),ne&&S.push(`--platform=${ne}`),fe&&S.push(`--tsconfig-raw=${typeof fe=="string"?fe:JSON.stringify(fe)}`),Be&&S.push("--minify"),Ee&&S.push("--minify-syntax"),Le&&S.push("--minify-whitespace"),Ue&&S.push("--minify-identifiers"),ge&&S.push(`--line-limit=${ge}`),me&&S.push(`--charset=${me}`),J!==void 0&&S.push(`--tree-shaking=${J}`),q&&S.push("--ignore-annotations"),Qe)for(let de of Qe)S.push(`--drop:${bt(de,"drop")}`);if(pe&&S.push(`--drop-labels=${C(pe,"drop label")}`),Me&&S.push(`--abs-paths=${C(Me,"abs paths")}`),re&&S.push(`--mangle-props=${La(re)}`),ae&&S.push(`--reserve-props=${La(ae)}`),he!==void 0&&S.push(`--mangle-quoted=${he}`),D&&S.push(`--jsx=${D}`),V&&S.push(`--jsx-factory=${V}`),W&&S.push(`--jsx-fragment=${W}`),te&&S.push(`--jsx-import-source=${te}`),le&&S.push("--jsx-dev"),z&&S.push("--jsx-side-effects"),X)for(let de in X){if(de.indexOf("=")>=0)throw new Error(`Invalid define: ${de}`);S.push(`--define:${de}=${bt(X[de],"define",de)}`)}if(oe)for(let de in oe){if(de.indexOf("=")>=0)throw new Error(`Invalid log override: ${de}`);S.push(`--log-override:${de}=${bt(oe[de],"log override",de)}`)}if(Te)for(let de in Te){if(de.indexOf("=")>=0)throw new Error(`Invalid supported: ${de}`);let Ne=Te[de];if(typeof Ne!="boolean")throw new Error(`Expected value for supported ${x(de)} to be a boolean, got ${typeof Ne} instead`);S.push(`--supported:${de}=${Ne}`)}if(P)for(let de of P)S.push(`--pure:${bt(de,"pure")}`);L&&S.push("--keep-names")}function ty(S,A,I,U,j){var $;let H=[],se=[],B=Object.create(null),re=null,ae=null;Ba(H,A,B,I,U),Yd(H,A,B);let he=R(A,B,"sourcemap",Kd),Be=R(A,B,"bundle",F),Ee=R(A,B,"splitting",F),Le=R(A,B,"preserveSymlinks",F),Ue=R(A,B,"metafile",F),ge=R(A,B,"outfile",E),Qe=R(A,B,"outdir",E),pe=R(A,B,"outbase",E),me=R(A,B,"tsconfig",E),J=R(A,B,"resolveExtensions",ve),q=R(A,B,"nodePaths",ve),D=R(A,B,"mainFields",ve),V=R(A,B,"conditions",ve),W=R(A,B,"external",ve),te=R(A,B,"packages",E),le=R(A,B,"alias",Re),z=R(A,B,"loader",Re),X=R(A,B,"outExtension",Re),oe=R(A,B,"publicPath",E),Te=R(A,B,"entryNames",E),P=R(A,B,"chunkNames",E),L=R(A,B,"assetNames",E),ne=R(A,B,"inject",ve),fe=R(A,B,"banner",Re),Me=R(A,B,"footer",Re),de=R(A,B,"entryPoints",et),Ne=R(A,B,"absWorkingDir",E),De=R(A,B,"stdin",Re),Fe=($=R(A,B,"write",F))!=null?$:j,kt=R(A,B,"allowOverwrite",F),rt=R(A,B,"mangleCache",Re);if(B.plugins=!0,tt(A,B,`in ${S}() call`),he&&H.push(`--sourcemap${he===!0?"":`=${he}`}`),Be&&H.push("--bundle"),kt&&H.push("--allow-overwrite"),Ee&&H.push("--splitting"),Le&&H.push("--preserve-symlinks"),Ue&&H.push("--metafile"),ge&&H.push(`--outfile=${ge}`),Qe&&H.push(`--outdir=${Qe}`),pe&&H.push(`--outbase=${pe}`),me&&H.push(`--tsconfig=${me}`),te&&H.push(`--packages=${te}`),J&&H.push(`--resolve-extensions=${C(J,"resolve extension")}`),oe&&H.push(`--public-path=${oe}`),Te&&H.push(`--entry-names=${Te}`),P&&H.push(`--chunk-names=${P}`),L&&H.push(`--asset-names=${L}`),D&&H.push(`--main-fields=${C(D,"main field")}`),V&&H.push(`--conditions=${C(V,"condition")}`),W)for(let ke of W)H.push(`--external:${bt(ke,"external")}`);if(le)for(let ke in le){if(ke.indexOf("=")>=0)throw new Error(`Invalid package name in alias: ${ke}`);H.push(`--alias:${ke}=${bt(le[ke],"alias",ke)}`)}if(fe)for(let ke in fe){if(ke.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${ke}`);H.push(`--banner:${ke}=${bt(fe[ke],"banner",ke)}`)}if(Me)for(let ke in Me){if(ke.indexOf("=")>=0)throw new Error(`Invalid footer file type: ${ke}`);H.push(`--footer:${ke}=${bt(Me[ke],"footer",ke)}`)}if(ne)for(let ke of ne)H.push(`--inject:${bt(ke,"inject")}`);if(z)for(let ke in z){if(ke.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${ke}`);H.push(`--loader:${ke}=${bt(z[ke],"loader",ke)}`)}if(X)for(let ke in X){if(ke.indexOf("=")>=0)throw new Error(`Invalid out extension: ${ke}`);H.push(`--out-extension:${ke}=${bt(X[ke],"out extension",ke)}`)}if(de)if(Array.isArray(de))for(let ke=0,kr=de.length;ke<kr;ke++){let Ut=de[ke];if(typeof Ut=="object"&&Ut!==null){let or=Object.create(null),Sr=R(Ut,or,"in",E),Nt=R(Ut,or,"out",E);if(tt(Ut,or,"in entry point at index "+ke),Sr===void 0)throw new Error('Missing property "in" for entry point at index '+ke);if(Nt===void 0)throw new Error('Missing property "out" for entry point at index '+ke);se.push([Nt,Sr])}else se.push(["",bt(Ut,"entry point at index "+ke)])}else for(let ke in de)se.push([ke,bt(de[ke],"entry point",ke)]);if(De){let ke=Object.create(null),kr=R(De,ke,"contents",Xd),Ut=R(De,ke,"resolveDir",E),or=R(De,ke,"sourcefile",E),Sr=R(De,ke,"loader",E);tt(De,ke,'in "stdin" object'),or&&H.push(`--sourcefile=${or}`),Sr&&H.push(`--loader=${Sr}`),Ut&&(ae=Ut),typeof kr=="string"?re=f(kr):kr instanceof Uint8Array&&(re=kr)}let br=[];if(q)for(let ke of q)ke+="",br.push(ke);return{entries:se,flags:H,write:Fe,stdinContents:re,stdinResolveDir:ae,absWorkingDir:Ne,nodePaths:br,mangleCache:Qd(rt)}}function ry(S,A,I,U){let j=[],$=Object.create(null);Ba(j,A,$,I,U),Yd(j,A,$);let H=R(A,$,"sourcemap",Kd),se=R(A,$,"sourcefile",E),B=R(A,$,"loader",E),re=R(A,$,"banner",E),ae=R(A,$,"footer",E),he=R(A,$,"mangleCache",Re);return tt(A,$,`in ${S}() call`),H&&j.push(`--sourcemap=${H===!0?"external":H}`),se&&j.push(`--sourcefile=${se}`),B&&j.push(`--loader=${B}`),re&&j.push(`--banner=${re}`),ae&&j.push(`--footer=${ae}`),{flags:j,mangleCache:Qd(he)}}function ny(S){let A={},I={didClose:!1,reason:""},U={},j=0,$=0,H=new Uint8Array(16*1024),se=0,B=me=>{let J=se+me.length;if(J>H.length){let D=new Uint8Array(J*2);D.set(H),H=D}H.set(me,se),se+=me.length;let q=0;for(;q+4<=se;){let D=g(H,q);if(q+4+D>se)break;q+=4,Le(H.subarray(q,q+D)),q+=D}q>0&&(H.copyWithin(0,q,se),se-=q)},re=me=>{I.didClose=!0,me&&(I.reason=": "+(me.message||me));let J="The service was stopped"+I.reason;for(let q in U)U[q](J,null);U={}},ae=(me,J,q)=>{if(I.didClose)return q("The service is no longer running"+I.reason,null);let D=j++;U[D]=(V,W)=>{try{q(V,W)}finally{me&&me.unref()}},me&&me.ref(),S.writeToStdin(u({id:D,isRequest:!0,value:J}))},he=(me,J)=>{if(I.didClose)throw new Error("The service is no longer running"+I.reason);S.writeToStdin(u({id:me,isRequest:!1,value:J}))},Be=(me,J)=>c(null,null,function*(){try{if(J.command==="ping"){he(me,{});return}if(typeof J.key=="number"){let q=A[J.key];if(!q)return;let D=q[J.command];if(D){yield D(me,J);return}}throw new Error("Invalid command: "+J.command)}catch(q){let D=[Tn(q,S,null,void 0,"")];try{he(me,{errors:D})}catch{}}}),Ee=!0,Le=me=>{if(Ee){Ee=!1;let q=String.fromCharCode(...me);if(q!=="0.28.2")throw new Error(`Cannot start service: Host version "0.28.2" does not match binary version ${x(q)}`);return}let J=d(me);if(J.isRequest)Be(J.id,J.value);else{let q=U[J.id];delete U[J.id],J.value.error?q(J.value.error,{}):q(null,J.value)}};return{readFromStdout:B,afterClose:re,service:{buildOrContext:({callName:me,refs:J,options:q,isTTY:D,defaultWD:V,callback:W})=>{let te=0,le=$++,z={},X={ref(){++te===1&&J&&J.ref()},unref(){--te===0&&(delete A[le],J&&J.unref())}};A[le]=z,X.ref(),iy(me,le,ae,he,X,S,z,q,D,V,(oe,Te)=>{try{W(oe,Te)}finally{X.unref()}})},transform:({callName:me,refs:J,input:q,options:D,isTTY:V,fs:W,callback:te})=>{let le=Zd(),z=X=>{try{if(typeof q!="string"&&!(q instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:oe,mangleCache:Te}=ry(me,D,V,M),P={command:"transform",flags:oe,inputFS:X!==null,input:X!==null?f(X):typeof q=="string"?f(q):q};Te&&(P.mangleCache=Te),ae(J,P,(L,ne)=>{if(L)return te(new Error(L),null);let fe=ii(ne.errors,le),Me=ii(ne.warnings,le),de=1,Ne=()=>{if(--de===0){let De={warnings:Me,code:ne.code,map:ne.map,mangleCache:void 0,legalComments:void 0};"legalComments"in ne&&(De.legalComments=ne?.legalComments),ne.mangleCache&&(De.mangleCache=ne?.mangleCache),te(null,De)}};if(fe.length>0)return te(ks("Transform failed",fe,Me),null);ne.codeFS&&(de++,W.readFile(ne.code,(De,Fe)=>{De!==null?te(De,null):(ne.code=Fe,Ne())})),ne.mapFS&&(de++,W.readFile(ne.map,(De,Fe)=>{De!==null?te(De,null):(ne.map=Fe,Ne())})),Ne()})}catch(oe){let Te=[];try{Ba(Te,D,{},V,M)}catch{}let P=Tn(oe,S,le,void 0,"");ae(J,{command:"error",flags:Te,error:P},()=>{P.detail=le.load(P.detail),te(ks("Transform failed",[P],[]),null)})}};if((typeof q=="string"||q instanceof Uint8Array)&&q.length>1024*1024){let X=z;z=()=>W.writeFile(q,X)}z(null)},formatMessages:({callName:me,refs:J,messages:q,options:D,callback:V})=>{if(!D)throw new Error(`Missing second argument in ${me}() call`);let W={},te=R(D,W,"kind",E),le=R(D,W,"color",F),z=R(D,W,"terminalWidth",Q),X=R(D,W,"logStyle",E);if(tt(D,W,`in ${me}() call`),te===void 0)throw new Error(`Missing "kind" in ${me}() call`);if(te!=="error"&&te!=="warning")throw new Error(`Expected "kind" to be "error" or "warning" in ${me}() call`);let oe={command:"format-msgs",messages:wr(q,"messages",null,"",z),isWarning:te==="warning"};le!==void 0&&(oe.color=le),z!==void 0&&(oe.terminalWidth=z),X!==void 0&&(oe.logStyle=X),ae(J,oe,(Te,P)=>{if(Te)return V(new Error(Te),null);V(null,P.messages)})},analyzeMetafile:({callName:me,refs:J,metafile:q,options:D,callback:V})=>{D===void 0&&(D={});let W={},te=R(D,W,"color",F),le=R(D,W,"verbose",F);tt(D,W,`in ${me}() call`);let z={command:"analyze-metafile",metafile:q};te!==void 0&&(z.color=te),le!==void 0&&(z.verbose=le),ae(J,z,(X,oe)=>{if(X)return V(new Error(X),null);V(null,oe.result)})}}}}function iy(S,A,I,U,j,$,H,se,B,re,ae){let he=Zd(),Be=S==="context",Ee=(ge,Qe)=>{let pe=[];try{Ba(pe,se,{},B,v)}catch{}let me=Tn(ge,$,he,void 0,Qe);I(j,{command:"error",flags:pe,error:me},()=>{me.detail=he.load(me.detail),ae(ks(Be?"Context failed":"Build failed",[me],[]),null)})},Le;if(typeof se=="object"){let ge=se.plugins;if(ge!==void 0){if(!Array.isArray(ge))return Ee(new Error('"plugins" must be an array'),"");Le=ge}}if(Le&&Le.length>0){if($.isSync)return Ee(new Error("Cannot use plugins in synchronous API calls"),"");sy(A,I,U,j,$,H,se,Le,he).then(ge=>{if(!ge.ok)return Ee(ge.error,ge.pluginName);try{Ue(ge.requestPlugins,ge.runOnEndCallbacks,ge.scheduleOnDisposeCallbacks)}catch(Qe){Ee(Qe,"")}},ge=>Ee(ge,""));return}try{Ue(null,(ge,Qe)=>Qe([],[]),()=>{})}catch(ge){Ee(ge,"")}function Ue(ge,Qe,pe){let me=$.hasFS,{entries:J,flags:q,write:D,stdinContents:V,stdinResolveDir:W,absWorkingDir:te,nodePaths:le,mangleCache:z}=ty(S,se,B,v,me);if(D&&!$.hasFS)throw new Error('The "write" option is unavailable in this environment');let X={command:"build",key:A,entries:J,flags:q,write:D,stdinContents:V,stdinResolveDir:W,absWorkingDir:te||re,nodePaths:le,context:Be};ge&&(X.plugins=ge),z&&(X.mangleCache=z);let oe=(L,ne)=>{let fe={errors:ii(L.errors,he),warnings:ii(L.warnings,he),outputFiles:void 0,metafile:void 0,mangleCache:void 0},Me=fe.errors.slice(),de=fe.warnings.slice();L.outputFiles&&(fe.outputFiles=L.outputFiles.map(oy)),L.metafile&&L.metafile.length&&(fe.metafile=cy(L.metafile)),L.mangleCache&&(fe.mangleCache=L.mangleCache),L.writeToStdout!==void 0&&console.log(p(L.writeToStdout).replace(/\n$/,"")),Qe(fe,(Ne,De)=>{if(Me.length>0||Ne.length>0){let Fe=ks("Build failed",Me.concat(Ne),de.concat(De));return ne(Fe,null,Ne,De)}ne(null,fe,Ne,De)})},Te,P;Be&&(H["on-end"]=(L,ne)=>new Promise(fe=>{oe(ne,(Me,de,Ne,De)=>{let Fe={errors:Ne,warnings:De};P&&P(Me,de),Te=void 0,P=void 0,U(L,Fe),fe()})})),I(j,X,(L,ne)=>{if(L)return ae(new Error(L),null);if(!Be)return oe(ne,(de,Ne)=>(pe(),ae(de,Ne)));if(ne.errors.length>0)return ae(ks("Context failed",ne.errors,ne.warnings),null);let fe=!1,Me={rebuild:()=>(Te||(Te=new Promise((de,Ne)=>{let De;P=(kt,rt)=>{De||(De=()=>kt?Ne(kt):de(rt))};let Fe=()=>{I(j,{command:"rebuild",key:A},(rt,br)=>{rt?Ne(new Error(rt)):De?De():Fe()})};Fe()})),Te),watch:(de={})=>new Promise((Ne,De)=>{if(!$.hasFS)throw new Error('Cannot use the "watch" API in this environment');let Fe={},kt=R(de,Fe,"delay",Q);tt(de,Fe,"in watch() call");let rt={command:"watch",key:A};kt&&(rt.delay=kt),I(j,rt,br=>{br?De(new Error(br)):Ne(void 0)})}),serve:(de={})=>new Promise((Ne,De)=>{if(!$.hasFS)throw new Error('Cannot use the "serve" API in this environment');let Fe={},kt=R(de,Fe,"port",ye),rt=R(de,Fe,"host",E),br=R(de,Fe,"servedir",E),ke=R(de,Fe,"keyfile",E),kr=R(de,Fe,"certfile",E),Ut=R(de,Fe,"fallback",E),or=R(de,Fe,"cors",Re),Sr=R(de,Fe,"onRequest",Z);tt(de,Fe,"in serve() call");let Nt={command:"serve",key:A,onRequest:!!Sr};if(kt!==void 0&&(Nt.port=kt),rt!==void 0&&(Nt.host=rt),br!==void 0&&(Nt.servedir=br),ke!==void 0&&(Nt.keyfile=ke),kr!==void 0&&(Nt.certfile=kr),Ut!==void 0&&(Nt.fallback=Ut),or){let xs={},si=R(or,xs,"origin",$d);tt(or,xs,'on "cors" object'),Array.isArray(si)?Nt.corsOrigin=si:si!==void 0&&(Nt.corsOrigin=[si])}I(j,Nt,(xs,si)=>{if(xs)return De(new Error(xs));Sr&&(H["serve-request"]=(Ty,Ay)=>{Sr(Ay.args),U(Ty,{})}),Ne(si)})}),cancel:()=>new Promise(de=>{if(fe)return de();I(j,{command:"cancel",key:A},()=>{de()})}),dispose:()=>new Promise(de=>{if(fe)return de();fe=!0,I(j,{command:"dispose",key:A},()=>{de(),pe(),j.unref()})})};j.ref(),ae(null,Me)})}}var sy=(S,A,I,U,j,$,H,se,B)=>c(null,null,function*(){let re=[],ae=[],he={},Be={},Ee=[],Le=0,Ue=0,ge=[],Qe=!1;se=[...se];for(let J of se){let q={};if(typeof J!="object")throw new Error(`Plugin at index ${Ue} must be an object`);let D=R(J,q,"name",E);if(typeof D!="string"||D==="")throw new Error(`Plugin at index ${Ue} is missing a name`);try{let V=R(J,q,"setup",Z);if(typeof V!="function")throw new Error("Plugin is missing a setup function");tt(J,q,`on plugin ${x(D)}`);let W={name:D,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};Ue++;let le=V({initialOptions:H,resolve:(z,X={})=>{if(!Qe)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof z!="string")throw new Error("The path to resolve must be a string");let oe=Object.create(null),Te=R(X,oe,"pluginName",E),P=R(X,oe,"importer",E),L=R(X,oe,"namespace",E),ne=R(X,oe,"resolveDir",E),fe=R(X,oe,"kind",E),Me=R(X,oe,"pluginData",_),de=R(X,oe,"with",Re);return tt(X,oe,"in resolve() call"),new Promise((Ne,De)=>{let Fe={command:"resolve",path:z,key:S,pluginName:D};if(Te!=null&&(Fe.pluginName=Te),P!=null&&(Fe.importer=P),L!=null&&(Fe.namespace=L),ne!=null&&(Fe.resolveDir=ne),fe!=null)Fe.kind=fe;else throw new Error('Must specify "kind" when calling "resolve"');Me!=null&&(Fe.pluginData=B.store(Me)),de!=null&&(Fe.with=ay(de,"with")),A(U,Fe,(kt,rt)=>{kt!==null?De(new Error(kt)):Ne({errors:ii(rt.errors,B),warnings:ii(rt.warnings,B),path:rt.path,external:rt.external,sideEffects:rt.sideEffects,namespace:rt.namespace,suffix:rt.suffix,pluginData:B.load(rt.pluginData)})})})},onStart(z){let X='This error came from the "onStart" callback registered here:',oe=Da(new Error(X),j,"onStart");re.push({name:D,callback:z,note:oe}),W.onStart=!0},onEnd(z){let X='This error came from the "onEnd" callback registered here:',oe=Da(new Error(X),j,"onEnd");ae.push({name:D,callback:z,note:oe}),W.onEnd=!0},onResolve(z,X){let oe='This error came from the "onResolve" callback registered here:',Te=Da(new Error(oe),j,"onResolve"),P={},L=R(z,P,"filter",O),ne=R(z,P,"namespace",E);if(tt(z,P,`in onResolve() call for plugin ${x(D)}`),L==null)throw new Error("onResolve() call is missing a filter");let fe=Le++;he[fe]={name:D,callback:X,note:Te},W.onResolve.push({id:fe,filter:La(L),namespace:ne||""})},onLoad(z,X){let oe='This error came from the "onLoad" callback registered here:',Te=Da(new Error(oe),j,"onLoad"),P={},L=R(z,P,"filter",O),ne=R(z,P,"namespace",E);if(tt(z,P,`in onLoad() call for plugin ${x(D)}`),L==null)throw new Error("onLoad() call is missing a filter");let fe=Le++;Be[fe]={name:D,callback:X,note:Te},W.onLoad.push({id:fe,filter:La(L),namespace:ne||""})},onDispose(z){Ee.push(z)},esbuild:j.esbuild});le&&(yield le),ge.push(W)}catch(V){return{ok:!1,error:V,pluginName:D}}}$["on-start"]=(J,q)=>c(null,null,function*(){B.clear();let D={errors:[],warnings:[]};yield Promise.all(re.map(V=>c(null,[V],function*({name:W,callback:te,note:le}){try{let z=yield te();if(z!=null){if(typeof z!="object")throw new Error(`Expected onStart() callback in plugin ${x(W)} to return an object`);let X={},oe=R(z,X,"errors",ee),Te=R(z,X,"warnings",ee);tt(z,X,`from onStart() callback in plugin ${x(W)}`),oe!=null&&D.errors.push(...wr(oe,"errors",B,W,void 0)),Te!=null&&D.warnings.push(...wr(Te,"warnings",B,W,void 0))}}catch(z){D.errors.push(Tn(z,j,B,le&&le(),W))}}))),I(J,D)}),$["on-resolve"]=(J,q)=>c(null,null,function*(){let D={},V="",W,te;for(let le of q.ids)try{({name:V,callback:W,note:te}=he[le]);let z=yield W({path:q.path,importer:q.importer,namespace:q.namespace,resolveDir:q.resolveDir,kind:q.kind,pluginData:B.load(q.pluginData),with:q.with});if(z!=null){if(typeof z!="object")throw new Error(`Expected onResolve() callback in plugin ${x(V)} to return an object`);let X={},oe=R(z,X,"pluginName",E),Te=R(z,X,"path",E),P=R(z,X,"namespace",E),L=R(z,X,"suffix",E),ne=R(z,X,"external",F),fe=R(z,X,"sideEffects",F),Me=R(z,X,"pluginData",_),de=R(z,X,"errors",ee),Ne=R(z,X,"warnings",ee),De=R(z,X,"watchFiles",ve),Fe=R(z,X,"watchDirs",ve);tt(z,X,`from onResolve() callback in plugin ${x(V)}`),D.id=le,oe!=null&&(D.pluginName=oe),Te!=null&&(D.path=Te),P!=null&&(D.namespace=P),L!=null&&(D.suffix=L),ne!=null&&(D.external=ne),fe!=null&&(D.sideEffects=fe),Me!=null&&(D.pluginData=B.store(Me)),de!=null&&(D.errors=wr(de,"errors",B,V,void 0)),Ne!=null&&(D.warnings=wr(Ne,"warnings",B,V,void 0)),De!=null&&(D.watchFiles=Oa(De,"watchFiles")),Fe!=null&&(D.watchDirs=Oa(Fe,"watchDirs"));break}}catch(z){D={id:le,errors:[Tn(z,j,B,te&&te(),V)]};break}I(J,D)}),$["on-load"]=(J,q)=>c(null,null,function*(){let D={},V="",W,te;for(let le of q.ids)try{({name:V,callback:W,note:te}=Be[le]);let z=yield W({path:q.path,namespace:q.namespace,suffix:q.suffix,pluginData:B.load(q.pluginData),with:q.with});if(z!=null){if(typeof z!="object")throw new Error(`Expected onLoad() callback in plugin ${x(V)} to return an object`);let X={},oe=R(z,X,"pluginName",E),Te=R(z,X,"contents",Xd),P=R(z,X,"resolveDir",E),L=R(z,X,"pluginData",_),ne=R(z,X,"loader",E),fe=R(z,X,"errors",ee),Me=R(z,X,"warnings",ee),de=R(z,X,"watchFiles",ve),Ne=R(z,X,"watchDirs",ve);tt(z,X,`from onLoad() callback in plugin ${x(V)}`),D.id=le,oe!=null&&(D.pluginName=oe),Te instanceof Uint8Array?D.contents=Te:Te!=null&&(D.contents=f(Te)),P!=null&&(D.resolveDir=P),L!=null&&(D.pluginData=B.store(L)),ne!=null&&(D.loader=ne),fe!=null&&(D.errors=wr(fe,"errors",B,V,void 0)),Me!=null&&(D.warnings=wr(Me,"warnings",B,V,void 0)),de!=null&&(D.watchFiles=Oa(de,"watchFiles")),Ne!=null&&(D.watchDirs=Oa(Ne,"watchDirs"));break}}catch(z){D={id:le,errors:[Tn(z,j,B,te&&te(),V)]};break}I(J,D)});let pe=(J,q)=>q([],[]);ae.length>0&&(pe=(J,q)=>{c(null,null,function*(){let D=[],V=[];for(let{name:W,callback:te,note:le}of ae){let z,X;try{let oe=yield te(J);if(oe!=null){if(typeof oe!="object")throw new Error(`Expected onEnd() callback in plugin ${x(W)} to return an object`);let Te={},P=R(oe,Te,"errors",ee),L=R(oe,Te,"warnings",ee);tt(oe,Te,`from onEnd() callback in plugin ${x(W)}`),P!=null&&(z=wr(P,"errors",B,W,void 0)),L!=null&&(X=wr(L,"warnings",B,W,void 0))}}catch(oe){z=[Tn(oe,j,B,le&&le(),W)]}if(z){D.push(...z);try{J.errors.push(...z)}catch{}}if(X){V.push(...X);try{J.warnings.push(...X)}catch{}}}q(D,V)})});let me=()=>{for(let J of Ee)setTimeout(()=>J(),0)};return Qe=!0,{ok:!0,requestPlugins:ge,runOnEndCallbacks:pe,scheduleOnDisposeCallbacks:me}});function Zd(){let S=new Map,A=0;return{clear(){S.clear()},load(I){return S.get(I)},store(I){if(I===void 0)return-1;let U=A++;return S.set(U,I),U}}}function Da(S,A,I){let U,j=!1;return()=>{if(j)return U;j=!0;try{let $=(S.stack+"").split(`
|
|
8
|
+
`);$.splice(1,1);let H=Jd(A,$,I);if(H)return U={text:S.message,location:H},U}catch{}}}function Tn(S,A,I,U,j){let $="Internal error",H=null;try{$=(S&&S.message||S)+""}catch{}try{H=Jd(A,(S.stack+"").split(`
|
|
9
|
+
`),"")}catch{}return{id:"",pluginName:j,text:$,location:H,notes:U?[U]:[],detail:I?I.store(S):-1}}function Jd(S,A,I){let U=" at ";if(S.readFileSync&&!A[0].startsWith(U)&&A[1].startsWith(U))for(let j=1;j<A.length;j++){let $=A[j];if($.startsWith(U))for($=$.slice(U.length);;){let H=/^(?:new |async )?\S+ \((.*)\)$/.exec($);if(H){$=H[1];continue}if(H=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec($),H){$=H[1];continue}if(H=/^(\S+):(\d+):(\d+)$/.exec($),H){let se;try{se=S.readFileSync(H[1],"utf8")}catch{break}let B=se.split(/\r\n|\r|\n|\u2028|\u2029/)[+H[2]-1]||"",re=+H[3]-1,ae=B.slice(re,re+I.length)===I?I.length:0;return{file:H[1],namespace:"file",line:+H[2],column:f(B.slice(0,re)).length,length:f(B.slice(re,re+ae)).length,lineText:B+`
|
|
10
|
+
`+A.slice(1).join(`
|
|
11
|
+
`),suggestion:""}}break}}return null}function ks(S,A,I){let U=5;S+=A.length<1?"":` with ${A.length} error${A.length<2?"":"s"}:`+A.slice(0,U+1).map(($,H)=>{if(H===U)return`
|
|
12
12
|
...`;if(!$.location)return`
|
|
13
|
-
error: ${$.text}`;let{file:se,line:B,column:
|
|
14
|
-
${se}:${B}:${
|
|
13
|
+
error: ${$.text}`;let{file:se,line:B,column:re}=$.location,ae=$.pluginName?`[plugin: ${$.pluginName}] `:"";return`
|
|
14
|
+
${se}:${B}:${re}: ERROR: ${ae}${$.text}`}).join("");let j=new Error(S);for(let[$,H]of[["errors",A],["warnings",I]])Object.defineProperty(j,$,{configurable:!0,enumerable:!0,get:()=>H,set:se=>Object.defineProperty(j,$,{configurable:!0,enumerable:!0,value:se})});return j}function ii(S,A){for(let I of S)I.detail=A.load(I.detail);return S}function eh(S,A,I){if(S==null)return null;let U={},j=R(S,U,"file",E),$=R(S,U,"namespace",E),H=R(S,U,"line",Q),se=R(S,U,"column",Q),B=R(S,U,"length",Q),re=R(S,U,"lineText",E),ae=R(S,U,"suggestion",E);if(tt(S,U,A),re){let he=re.slice(0,(se&&se>0?se:0)+(B&&B>0?B:0)+(I&&I>0?I:80));!/[\x7F-\uFFFF]/.test(he)&&!/\n/.test(re)&&(re=he)}return{file:j||"",namespace:$||"",line:H||0,column:se||0,length:B||0,lineText:re||"",suggestion:ae||""}}function wr(S,A,I,U,j){let $=[],H=0;for(let se of S){let B={},re=R(se,B,"id",E),ae=R(se,B,"pluginName",E),he=R(se,B,"text",E),Be=R(se,B,"location",jd),Ee=R(se,B,"notes",ee),Le=R(se,B,"detail",_),Ue=`in element ${H} of "${A}"`;tt(se,B,Ue);let ge=[];if(Ee)for(let Qe of Ee){let pe={},me=R(Qe,pe,"text",E),J=R(Qe,pe,"location",jd);tt(Qe,pe,Ue),ge.push({text:me||"",location:eh(J,Ue,j)})}$.push({id:re||"",pluginName:ae||U,text:he||"",location:eh(Be,Ue,j),notes:ge,detail:I?I.store(Le):-1}),H++}return $}function Oa(S,A){let I=[];for(let U of S){if(typeof U!="string")throw new Error(`${x(A)} must be an array of strings`);I.push(U)}return I}function ay(S,A){let I=Object.create(null);for(let U in S){let j=S[U];if(typeof j!="string")throw new Error(`key ${x(U)} in object ${x(A)} must be a string`);I[U]=j}return I}function oy({path:S,contents:A,hash:I}){let U=null;return{path:S,contents:A,hash:I,get text(){let j=this.contents;return(U===null||j!==A)&&(A=j,U=p(j)),U}}}function La(S){let A=S.source;return S.flags&&(A=`(?${S.flags})${A}`),A}function cy(S){let A;try{A=p(S)}catch{return T(S)}return JSON.parse(A)}var ly="0.28.2",uy=S=>Ss().build(S),dy=S=>Ss().context(S),hy=(S,A)=>Ss().transform(S,A),fy=(S,A)=>Ss().formatMessages(S,A),my=(S,A)=>Ss().analyzeMetafile(S,A),py=()=>{throw new Error('The "buildSync" API only works in node')},gy=()=>{throw new Error('The "transformSync" API only works in node')},yy=()=>{throw new Error('The "formatMessagesSync" API only works in node')},wy=()=>{throw new Error('The "analyzeMetafileSync" API only works in node')},by=()=>(Ua&&Ua(),Promise.resolve()),An,Ua,Na,Ss=()=>{if(Na)return Na;throw An?new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this'):new Error('You need to call "initialize" before calling this')},ky=S=>{S=ey(S||{});let A=S.wasmURL,I=S.wasmModule,U=S.worker!==!1;if(!A&&!I)throw new Error('Must provide either the "wasmURL" option or the "wasmModule" option');if(An)throw new Error('Cannot call "initialize" more than once');return An=Sy(A||"",I,U),An.catch(()=>{An=void 0}),An},Sy=(S,A,I)=>c(null,null,function*(){let U,j,$=new Promise(he=>j=he);if(I){let he=new Blob([`onmessage=((postMessage) => {
|
|
15
15
|
// Copyright 2018 The Go Authors. All rights reserved.
|
|
16
16
|
// Use of this source code is governed by a BSD-style
|
|
17
17
|
// license that can be found in the LICENSE file.
|
|
@@ -689,10 +689,10 @@ ${se}:${B}:${te}: ERROR: ${ae}${$.text}`}).join("");let G=new Error(x);for(let[$
|
|
|
689
689
|
});
|
|
690
690
|
}
|
|
691
691
|
return (m) => onmessage(m);
|
|
692
|
-
})(postMessage)`],{type:"text/javascript"});U=new Worker(URL.createObjectURL(
|
|
693
|
-
`);return W!=-1&&(console.log(q.substring(0,W)),q=q.substring(W+1)),V.length},write(D,V,W,
|
|
692
|
+
})(postMessage)`],{type:"text/javascript"});U=new Worker(URL.createObjectURL(he))}else{let he=(Ee=>{var Le=(pe,me,J)=>new Promise((q,D)=>{var V=le=>{try{te(J.next(le))}catch(z){D(z)}},W=le=>{try{te(J.throw(le))}catch(z){D(z)}},te=le=>le.done?q(le.value):Promise.resolve(le.value).then(V,W);te((J=J.apply(pe,me)).next())});let Ue,ge={};for(let pe=self;pe;pe=Object.getPrototypeOf(pe))for(let me of Object.getOwnPropertyNames(pe))me in ge||Object.defineProperty(ge,me,{get:()=>self[me]});(()=>{let pe=()=>{let q=new Error("not implemented");return q.code="ENOSYS",q};if(!ge.fs){let q="";ge.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1,O_DIRECTORY:-1},writeSync(D,V){q+=J.decode(V);let W=q.lastIndexOf(`
|
|
693
|
+
`);return W!=-1&&(console.log(q.substring(0,W)),q=q.substring(W+1)),V.length},write(D,V,W,te,le,z){if(W!==0||te!==V.length||le!==null){z(pe());return}let X=this.writeSync(D,V);z(null,X)},chmod(D,V,W){W(pe())},chown(D,V,W,te){te(pe())},close(D,V){V(pe())},fchmod(D,V,W){W(pe())},fchown(D,V,W,te){te(pe())},fstat(D,V){V(pe())},fsync(D,V){V(null)},ftruncate(D,V,W){W(pe())},lchown(D,V,W,te){te(pe())},link(D,V,W){W(pe())},lstat(D,V){V(pe())},mkdir(D,V,W){W(pe())},open(D,V,W,te){te(pe())},read(D,V,W,te,le,z){z(pe())},readdir(D,V){V(pe())},readlink(D,V){V(pe())},rename(D,V,W){W(pe())},rmdir(D,V){V(pe())},stat(D,V){V(pe())},symlink(D,V,W){W(pe())},truncate(D,V,W){W(pe())},unlink(D,V){V(pe())},utimes(D,V,W,te){te(pe())}}}if(ge.process||(ge.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw pe()},pid:-1,ppid:-1,umask(){throw pe()},cwd(){throw pe()},chdir(){throw pe()}}),ge.path||(ge.path={resolve(...q){return q.join("/")}}),!ge.crypto)throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");if(!ge.performance)throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");if(!ge.TextEncoder)throw new Error("globalThis.TextEncoder is not available, polyfill required");if(!ge.TextDecoder)throw new Error("globalThis.TextDecoder is not available, polyfill required");let me=new TextEncoder("utf-8"),J=new TextDecoder("utf-8");ge.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=P=>{P!==0&&console.warn("exit code:",P)},this._exitPromise=new Promise(P=>{this._resolveExitPromise=P}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let q=(P,L)=>{this.mem.setUint32(P+0,L,!0),this.mem.setUint32(P+4,Math.floor(L/4294967296),!0)},D=(P,L)=>{this.mem.setUint32(P+0,L,!0)},V=P=>{let L=this.mem.getUint32(P+0,!0),ne=this.mem.getInt32(P+4,!0);return L+ne*4294967296},W=P=>{let L=this.mem.getFloat64(P,!0);if(L===0)return;if(!isNaN(L))return L;let ne=this.mem.getUint32(P,!0);return this._values[ne]},te=(P,L)=>{if(typeof L=="number"&&L!==0){if(isNaN(L)){this.mem.setUint32(P+4,2146959360,!0),this.mem.setUint32(P,0,!0);return}this.mem.setFloat64(P,L,!0);return}if(L===void 0){this.mem.setFloat64(P,0,!0);return}let fe=this._ids.get(L);fe===void 0&&(fe=this._idPool.pop(),fe===void 0&&(fe=this._values.length),this._values[fe]=L,this._goRefCounts[fe]=0,this._ids.set(L,fe)),this._goRefCounts[fe]++;let Me=0;switch(typeof L){case"object":L!==null&&(Me=1);break;case"string":Me=2;break;case"symbol":Me=3;break;case"function":Me=4;break}this.mem.setUint32(P+4,2146959360|Me,!0),this.mem.setUint32(P,fe,!0)},le=P=>{let L=V(P+0),ne=V(P+8);return new Uint8Array(this._inst.exports.mem.buffer,L,ne)},z=P=>{let L=V(P+0),ne=V(P+8),fe=new Array(ne);for(let Me=0;Me<ne;Me++)fe[Me]=W(L+Me*8);return fe},X=P=>{let L=V(P+0),ne=V(P+8);return J.decode(new DataView(this._inst.exports.mem.buffer,L,ne))},oe=(P,L)=>(this._inst.exports.testExport0(),this._inst.exports.testExport(P,L)),Te=Date.now()-performance.now();this.importObject={_gotest:{add:(P,L)=>P+L,callExport:oe},gojs:{"runtime.wasmExit":P=>{P>>>=0;let L=this.mem.getInt32(P+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(L)},"runtime.wasmWrite":P=>{P>>>=0;let L=V(P+8),ne=V(P+16),fe=this.mem.getInt32(P+24,!0);ge.fs.writeSync(L,new Uint8Array(this._inst.exports.mem.buffer,ne,fe))},"runtime.resetMemoryDataView":P=>{P>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":P=>{P>>>=0,q(P+8,(Te+performance.now())*1e6)},"runtime.walltime":P=>{P>>>=0;let L=new Date().getTime();q(P+8,L/1e3),this.mem.setInt32(P+16,L%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":P=>{P>>>=0;let L=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(L,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(L);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},V(P+8))),this.mem.setInt32(P+16,L,!0)},"runtime.clearTimeoutEvent":P=>{P>>>=0;let L=this.mem.getInt32(P+8,!0);clearTimeout(this._scheduledTimeouts.get(L)),this._scheduledTimeouts.delete(L)},"runtime.getRandomData":P=>{P>>>=0,crypto.getRandomValues(le(P+8))},"syscall/js.finalizeRef":P=>{P>>>=0;let L=this.mem.getUint32(P+8,!0);if(this._goRefCounts[L]--,this._goRefCounts[L]===0){let ne=this._values[L];this._values[L]=null,this._ids.delete(ne),this._idPool.push(L)}},"syscall/js.stringVal":P=>{P>>>=0,te(P+24,X(P+8))},"syscall/js.valueGet":P=>{P>>>=0;let L=Reflect.get(W(P+8),X(P+16));P=this._inst.exports.getsp()>>>0,te(P+32,L)},"syscall/js.valueSet":P=>{P>>>=0,Reflect.set(W(P+8),X(P+16),W(P+32))},"syscall/js.valueDelete":P=>{P>>>=0,Reflect.deleteProperty(W(P+8),X(P+16))},"syscall/js.valueIndex":P=>{P>>>=0,te(P+24,Reflect.get(W(P+8),V(P+16)))},"syscall/js.valueSetIndex":P=>{P>>>=0,Reflect.set(W(P+8),V(P+16),W(P+24))},"syscall/js.valueCall":P=>{P>>>=0;try{let L=W(P+8),ne=Reflect.get(L,X(P+16)),fe=z(P+32),Me=Reflect.apply(ne,L,fe);P=this._inst.exports.getsp()>>>0,te(P+56,Me),this.mem.setUint8(P+64,1)}catch(L){P=this._inst.exports.getsp()>>>0,te(P+56,L),this.mem.setUint8(P+64,0)}},"syscall/js.valueInvoke":P=>{P>>>=0;try{let L=W(P+8),ne=z(P+16),fe=Reflect.apply(L,void 0,ne);P=this._inst.exports.getsp()>>>0,te(P+40,fe),this.mem.setUint8(P+48,1)}catch(L){P=this._inst.exports.getsp()>>>0,te(P+40,L),this.mem.setUint8(P+48,0)}},"syscall/js.valueNew":P=>{P>>>=0;try{let L=W(P+8),ne=z(P+16),fe=Reflect.construct(L,ne);P=this._inst.exports.getsp()>>>0,te(P+40,fe),this.mem.setUint8(P+48,1)}catch(L){P=this._inst.exports.getsp()>>>0,te(P+40,L),this.mem.setUint8(P+48,0)}},"syscall/js.valueLength":P=>{P>>>=0,q(P+16,parseInt(W(P+8).length))},"syscall/js.valuePrepareString":P=>{P>>>=0;let L=me.encode(String(W(P+8)));te(P+16,L),q(P+24,L.length)},"syscall/js.valueLoadString":P=>{P>>>=0;let L=W(P+8);le(P+16).set(L)},"syscall/js.valueInstanceOf":P=>{P>>>=0,this.mem.setUint8(P+24,W(P+8)instanceof W(P+16)?1:0)},"syscall/js.copyBytesToGo":P=>{P>>>=0;let L=le(P+8),ne=W(P+32);if(!(ne instanceof Uint8Array||ne instanceof Uint8ClampedArray)){this.mem.setUint8(P+48,0);return}let fe=ne.subarray(0,L.length);L.set(fe),q(P+40,fe.length),this.mem.setUint8(P+48,1)},"syscall/js.copyBytesToJS":P=>{P>>>=0;let L=W(P+8),ne=le(P+16);if(!(L instanceof Uint8Array||L instanceof Uint8ClampedArray)){this.mem.setUint8(P+48,0);return}let fe=ne.subarray(0,L.length);L.set(fe),q(P+40,fe.length),this.mem.setUint8(P+48,1)},debug:P=>{console.log(P)}}}}run(q){return Le(this,null,function*(){if(!(q instanceof WebAssembly.Instance))throw new Error("Go.run: WebAssembly.Instance expected");this._inst=q,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,ge,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[ge,5],[this,6]]),this._idPool=[],this.exited=!1;let D=4096,V=oe=>{let Te=D,P=me.encode(oe+"\0");return new Uint8Array(this.mem.buffer,D,P.length).set(P),D+=P.length,D%8!==0&&(D+=8-D%8),Te},W=this.argv.length,te=[];this.argv.forEach(oe=>{te.push(V(oe))}),te.push(0),Object.keys(this.env).sort().forEach(oe=>{te.push(V(`${oe}=${this.env[oe]}`))}),te.push(0);let z=D;if(te.forEach(oe=>{this.mem.setUint32(D,oe,!0),this.mem.setUint32(D+4,0,!0),D+=8}),D>=12288)throw new Error("total length of command line and environment variables exceeds limit");this._inst.exports.run(W,z),this.exited&&this._resolveExitPromise(),yield this._exitPromise})}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(q){let D=this;return function(){let V={id:q,this:this,args:arguments};return D._pendingEvent=V,D._resume(),V.result}}}})(),Ue=({data:pe})=>{let me=new TextDecoder,J=ge.fs,q="";J.writeSync=(le,z)=>{if(le===1)Ee(z);else if(le===2){q+=me.decode(z);let X=q.split(`
|
|
694
694
|
`);X.length>1&&console.log(X.slice(0,-1).join(`
|
|
695
|
-
`)),q=X[X.length-1]}else throw new Error("Bad write");return N.length};let D=[],V,W=0;Ue=({data:le})=>(le.length>0&&(D.push(le),V&&V()),ee),Z.read=(le,N,X,oe,Te,C)=>{if(le!==0||X!==0||oe!==N.length||Te!==null)throw new Error("Bad read");if(D.length===0){V=()=>Z.read(le,N,X,oe,Te,C);return}let L=D[0],re=Math.max(0,Math.min(oe,L.length-W));N.set(L.subarray(W,W+re),X),W+=re,W===L.length&&(D.shift(),W=0),C(null,re)};let ee=new pe.Go;return ee.argv=["","--service=0.28.2"],Qe(me,ee).then(le=>{Ee(null),ee.run(le)},le=>{Ee(le)}),ee};function Qe(me,fe){return Le(this,null,function*(){if(me instanceof WebAssembly.Module)return WebAssembly.instantiate(me,fe.importObject);let Z=yield fetch(me);if(!Z.ok)throw new Error(`Failed to download ${JSON.stringify(me)}`);if("instantiateStreaming"in WebAssembly&&/^application\/wasm($|;)/i.test(Z.headers.get("Content-Type")||""))return(yield WebAssembly.instantiateStreaming(Z,fe.importObject)).instance;let q=yield Z.arrayBuffer();return(yield WebAssembly.instantiate(q,fe.importObject)).instance})}return me=>Ue(me)})(Ee=>U.onmessage({data:Ee})),Be;U={onmessage:null,postMessage:Ee=>setTimeout(()=>{try{Be=de({data:Ee})}catch(Le){G(Le)}}),terminate(){if(Be)for(let Ee of Be._scheduledTimeouts.values())clearTimeout(Ee)}}}let H,se,B=new Promise((de,Be)=>{H=de,se=Be});U.onmessage=({data:de})=>{U.onmessage=({data:Be})=>te(Be),de?se(de):H()},U.postMessage(v||new URL(x,location.href).toString());let{readFromStdout:te,service:ae}=z0({writeToStdin(de){U.postMessage(de)},isSync:!1,hasFS:!1,esbuild:l});yield B,Da=()=>{U.terminate(),Tn=void 0,Da=void 0,Oa=void 0},Oa={build:de=>new Promise((Be,Ee)=>{$.then(Ee),ae.buildOrContext({callName:"build",refs:null,options:de,isTTY:!1,defaultWD:"/",callback:(Le,Ue)=>Le?Ee(Le):Be(Ue)})}),context:de=>new Promise((Be,Ee)=>{$.then(Ee),ae.buildOrContext({callName:"context",refs:null,options:de,isTTY:!1,defaultWD:"/",callback:(Le,Ue)=>Le?Ee(Le):Be(Ue)})}),transform:(de,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.transform({callName:"transform",refs:null,input:de,options:Be||{},isTTY:!1,fs:{readFile(Ue,pe){pe(new Error("Internal error"),null)},writeFile(Ue,pe){pe(null)}},callback:(Ue,pe)=>Ue?Le(Ue):Ee(pe)})}),formatMessages:(de,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.formatMessages({callName:"formatMessages",refs:null,messages:de,options:Be,callback:(Ue,pe)=>Ue?Le(Ue):Ee(pe)})}),analyzeMetafile:(de,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof de=="string"?de:JSON.stringify(de),options:Be,callback:(Ue,pe)=>Ue?Le(Ue):Ee(pe)})})}}),iy=l})(typeof Vd=="object"?Vd:{set exports(r){(typeof self<"u"?self:this).esbuild=r}})});import{resolveSurfaceSource as Xx,CanvasRenderContext2D as Qx,withRichTextDescriptor as Yx,fillOps as Zx,strokeOps as Jx,shadowOps as eS,alignmentOps as tS,resolveShapeAlignment as rS,resolvePivotPosition as nS,stripShapeAlignmentKeys as iS}from"@motionscript/core";import{canvas3DResourceKey as th,parseCanvas3DResourceKey as dy,registerCanvas3DResourceLoader as hy,registerCanvas3DWarmup as fy}from"@motionscript/core";var bl=null,eh=null,La=new Set,Ss=new Map;function kl(){return bl}function Ts(){return bl?Promise.resolve():(eh??=import("./chunks/three.module-Z4EOVUWF.js").then(r=>(bl=r,r)),eh.then(()=>{}))}function xl(r){La.add(r)}function Sl(){return La.size>0||Ss.size>0}function rh(r,e){Ss.set(r,e)}async function Tl(){let r=!1;for(let e=0;e<4&&!(La.size===0&&Ss.size===0);e++){La.clear();let t=[...Ss];Ss.clear(),await Ts(),t.length>0&&await Promise.all(t.map(([n])=>nh(n))),r=!0}return r}var Ua=new Map;async function nh(r){let e=dy(r);if(e?.kind!=="gltf")return;let t=await my(e.src);t&&Ua.set(r,t)}function vn(r){return Ua.get(th("gltf",r))??null}async function my(r){try{let[,e,t]=await Promise.all([Ts(),import("./chunks/GLTFLoader-PGXD4V5B.js"),import("./chunks/SkeletonUtils-XYDMTGTM.js")]),n=await new e.GLTFLoader().loadAsync(r);return{scene:n.scene,animations:n.animations,clone:()=>t.clone(n.scene)}}catch{return null}}function py(r){r.scene.traverse(e=>{let t=e;t.geometry?.dispose?.();let n=Array.isArray(t.material)?t.material:[t.material];for(let i of n)if(i){for(let s of Object.values(i)){let a=s;a?.isTexture&&a.dispose()}i.dispose()}})}function vl(){fy(Ts),hy(async(r,e)=>{let t=th(r,e);await nh(t);let n=Ua.get(t);return n?()=>{Ua.delete(t),py(n)}:()=>{}})}import{canvas3DResourceKey as Xy}from"@motionscript/core";import{parseColor as ih}from"@motionscript/core";function He(r){return r*(Math.PI/180)}function sh(r,e){switch(e){case"back":return r.BackSide;case"both":return r.DoubleSide;default:return r.FrontSide}}function ah(r,e){switch(e){case"additive":return r.AdditiveBlending;case"subtractive":return r.SubtractiveBlending;case"multiply":return r.MultiplyBlending;case"none":return r.NoBlending;default:return r.NormalBlending}}function Al(r,e){switch(e){case"repeat":return r.RepeatWrapping;case"mirror":return r.MirroredRepeatWrapping;default:return r.ClampToEdgeWrapping}}function oh(r,e){return e==="nearest"?r.NearestFilter:r.LinearFilter}function ch(r,e){return e==="nearest"?r.NearestFilter:r.LinearMipmapLinearFilter}function lh(r,e){return e==="linear"?r.LinearSRGBColorSpace:r.SRGBColorSpace}function uh(r,e){switch(e){case"low":return{type:r.PCFShadowMap,mapSize:512};case"high":return{type:r.PCFSoftShadowMap,mapSize:4096};default:return{type:r.PCFSoftShadowMap,mapSize:2048}}}function dh(r,e){switch(e){case"none":return r.NoToneMapping;case"linear":return r.LinearToneMapping;case"reinhard":return r.ReinhardToneMapping;case"cineon":return r.CineonToneMapping;case"agx":return r.AgXToneMapping;case"neutral":return r.NeutralToneMapping;default:return r.ACESFilmicToneMapping}}function xt(r,e,t){let[n,i,s,a]=typeof t=="string"?ih(t):t;return e.setRGB(n,i,s,r.SRGBColorSpace),a}function _l(r,e){let t=new r.Color;return xt(r,t,e),t}function Cl(r){let[,,,e]=typeof r=="string"?ih(r):r;return e}import{cylinderRadii as gy,evaluateParametric as hh,evaluateRoundedBox as yy,resolveBevel3D as wy,resolveVector3 as fh,segmentsOf as St,toPathString as by}from"@motionscript/core";function Qr(r,e){switch(e.type){case"box":{let[t,n,i]=St(e.segments,[1,1,1]),s=e.width??1,a=e.height??1,o=e.depth??1;return(e.cornerRadius??0)>0?Pl(r,yy({width:s,height:a,depth:o,radius:e.cornerRadius,segments:[t,n,i]})):new r.BoxGeometry(s,a,o,t,n,i)}case"sphere":{let[t,n]=St(e.segments,[32,16]);return new r.SphereGeometry(e.radius??1,t,n,He(e.startAngle??0),He(e.sweep??360),He(e.startLatitude??0),He(e.latitudeSweep??180))}case"plane":{let[t,n]=St(e.segments,[1,1]);return new r.PlaneGeometry(e.width??1,e.height??1,t,n)}case"cylinder":{let[t,n]=gy(e.radius),[i,s]=St(e.segments,[32,1]);return new r.CylinderGeometry(t,n,e.height??1,i,s,!(e.capped??!0),He(e.startAngle??0),He(e.sweep??360))}case"cone":{let[t,n]=St(e.segments,[32,1]);return new r.ConeGeometry(e.radius??1,e.height??1,t,n,!(e.capped??!0),He(e.startAngle??0),He(e.sweep??360))}case"torus":{let[t,n]=St(e.segments,[16,48]);return new r.TorusGeometry(e.radius??1,e.thickness??.4,t,n,He(e.sweep??360))}case"torusKnot":{let[t,n]=St(e.segments,[64,8]),[i,s]=e.windings??[2,3];return new r.TorusKnotGeometry(e.radius??1,e.thickness??.4,t,n,i,s)}case"circle":{let[t]=St(e.segments,[32]);return new r.CircleGeometry(e.radius??1,t,He(e.startAngle??0),He(e.sweep??360))}case"ring":{let[t,n]=St(e.segments,[32,1]);return new r.RingGeometry(e.innerRadius??.5,e.radius??1,t,n,He(e.startAngle??0),He(e.sweep??360))}case"capsule":{let[t,n]=St(e.segments,[16,8]);return new r.CapsuleGeometry(e.radius??.5,e.height??1,n,t)}case"polyhedron":{let[t]=St(e.segments,[1]);return xy(r,e.shape,e.radius??1,e.segments===void 0?0:t)}case"extrude":return Sy(r,e);case"lathe":{let[t]=St(e.segments,[12]);return new r.LatheGeometry(e.points.map(n=>Cy(r,n)),t,He(e.startAngle??0),He(e.sweep??360))}case"tube":{let[t,n]=St(e.segments,[64,8]);return new r.TubeGeometry(new r.CatmullRomCurve3(e.points.map(i=>_y(r,i)),e.closed??!1),t,e.radius??1,n,e.closed??!1)}case"buffer":return Pl(r,e);case"parametric":return Pl(r,hh(e));case"edges":{let t=Qr(r,e.source),n=new r.EdgesGeometry(t,e.thresholdAngle??1);return t.dispose(),n}case"wireframe":{let t=Qr(r,e.source),n=new r.WireframeGeometry(t);return t.dispose(),n}case"modelGeometry":return ky(vn(e.src)?.scene,e.node)?.geometry.clone()??new r.BufferGeometry;default:return new r.BufferGeometry}}function ky(r,e){if(!r)return null;if(e!==void 0){let n=r.getObjectByName(e);return n?.isMesh?n:null}let t=null;return r.traverse(n=>{let i=n;t===null&&i.isMesh&&(t=i)}),t}function xy(r,e,t,n){switch(e){case"tetrahedron":return new r.TetrahedronGeometry(t,n);case"octahedron":return new r.OctahedronGeometry(t,n);case"dodecahedron":return new r.DodecahedronGeometry(t,n);default:return new r.IcosahedronGeometry(t,n)}}function Sy(r,e){let t=e.path,n=typeof t=="object"&&"toPathState"in t?t.toPathState().data:t,i=Ty(r,by(n));if(i.length===0)return new r.BufferGeometry;let[s]=St(e.segments,[12]),a=wy(e.bevel);return new r.ExtrudeGeometry(i,{depth:e.depth??1,curveSegments:s,bevelEnabled:a!==null,bevelThickness:a?.thickness??.2,bevelSize:a?.size??.1,bevelOffset:a?.offset??0,bevelSegments:a?.segments??3})}function Ty(r,e){let t=[],n=null,i=0,s=0,a=e.match(/[MLCQZmlcqz][^MLCQZmlcqz]*/g)??[];for(let o of a){let c=o[0],l=(o.slice(1).match(/-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]).map(Number);switch(c){case"M":case"m":{n&&t.push(n),n=new r.Shape,i=l[0]??0,s=l[1]??0,n.moveTo(i,s);break}case"L":case"l":{if(!n)break;for(let u=0;u+1<l.length;u+=2)i=l[u],s=l[u+1],n.lineTo(i,s);break}case"C":case"c":{if(!n)break;for(let u=0;u+5<l.length;u+=6)n.bezierCurveTo(l[u],l[u+1],l[u+2],l[u+3],l[u+4],l[u+5]),i=l[u+4],s=l[u+5];break}case"Q":case"q":{if(!n)break;for(let u=0;u+3<l.length;u+=4)n.quadraticCurveTo(l[u],l[u+1],l[u+2],l[u+3]),i=l[u+2],s=l[u+3];break}case"Z":case"z":{n?.closePath();break}}}return n&&t.push(n),t}function Pl(r,e){let t=new r.BufferGeometry;return t.setAttribute("position",new r.BufferAttribute(Na(e.position),3)),e.normal&&t.setAttribute("normal",new r.BufferAttribute(Na(e.normal),3)),e.uv&&t.setAttribute("uv",new r.BufferAttribute(Na(e.uv),2)),e.color&&t.setAttribute("color",new r.BufferAttribute(Na(e.color),3)),e.index&&t.setIndex(new r.BufferAttribute(Ay(e.index),1)),e.computeNormals&&!e.normal&&t.computeVertexNormals(),t}function mh(r,e){if(!za(r,"position",e.position,3)||!za(r,"normal",e.normal,3)||!za(r,"uv",e.uv,2)||!za(r,"color",e.color,3))return!1;if(e.index){let t=r.getIndex();if(!t||t.array.length!==e.index.length)return!1;t.array.set(e.index),t.needsUpdate=!0}return e.computeNormals&&!e.normal&&r.computeVertexNormals(),r.computeBoundingSphere(),!0}function za(r,e,t,n){let i=r.getAttribute(e);return t?!i||i.array.length!==t.length||i.itemSize!==n?!1:(i.array.set(t),i.needsUpdate=!0,!0):i===void 0}function An(r){let e=[r.type];r.type==="modelGeometry"&&e.push(`loaded=${vn(r.src)?"1":"0"}`);let t=r;for(let n of Object.keys(t).sort()){if(n==="type"||n==="revision"||n==="staticData")continue;let i=t[n];if(i!==void 0)if(n==="source")e.push(`source=${An(i)}`);else{if(typeof i=="function")continue;vy(i)?e.push(`${n}#${i.length}`):Array.isArray(i)?e.push(`${n}=${JSON.stringify(i)}`):typeof i=="object"?e.push(`${n}=${JSON.stringify(i)}`):e.push(`${n}=${String(i)}`)}}return e.join("|")}function ph(r){return r.type==="parametric"?!0:r.type!=="buffer"?!1:r.staticData!==!0}function gh(r){return r.type==="parametric"?hh(r):r}function vy(r){return ArrayBuffer.isView(r)?!0:Array.isArray(r)&&r.length>4}function Na(r){return r instanceof Float32Array?r:new Float32Array(Array.from(r))}function Ay(r){return r instanceof Uint32Array?r:new Uint32Array(Array.from(r))}function _y(r,e){let t=fh(e);return new r.Vector3(t.x,t.y,t.z)}function Cy(r,e){let t=fh(e);return new r.Vector2(t.x,t.y)}import{STRUCTURAL_MATERIAL_KEYS as bh}from"@motionscript/core";var Il=["map","alphaMap","aoMap","normalMap","displacementMap","envMap","lightMap","emissionMap","roughnessMap","metalnessMap","specularMap","gradientMap","matcap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap"],El={emission:"emissive",emissionStrength:"emissiveIntensity",emissionMap:"emissiveMap"},Py=new Set(["normalMap","roughnessMap","metalnessMap","aoMap","displacementMap","alphaMap","clearcoatRoughnessMap","clearcoatNormalMap","transmissionMap","thicknessMap"]),yh=["color","emission","specular","sheenColor","specularColor","attenuationColor"];function Ey(r){let e=r;return e.transparent===!0||typeof e.opacity=="number"&&e.opacity<1||e.alphaMap!==void 0||typeof e.transmission=="number"&&e.transmission>0||e.color!==void 0&&Cl(e.color)<1}function Iy(r,e){switch(e.type){case"basic":return new r.MeshBasicMaterial;case"standard":return new r.MeshStandardMaterial;case"physical":return new r.MeshPhysicalMaterial;case"phong":return new r.MeshPhongMaterial;case"lambert":return new r.MeshLambertMaterial;case"toon":return new r.MeshToonMaterial;case"normal":return new r.MeshNormalMaterial;case"depth":return new r.MeshDepthMaterial;case"matcap":return new r.MeshMatcapMaterial;case"points":return new r.PointsMaterial;case"lineBasic":return new r.LineBasicMaterial;case"lineDashed":return new r.LineDashedMaterial;case"sprite":return new r.SpriteMaterial;case"shadow":return new r.ShadowMaterial;case"shader":return My(r,e);default:return new r.MeshStandardMaterial}}function My(r,e){let t=e.raw?r.RawShaderMaterial:r.ShaderMaterial;return new t({vertexShader:e.vertex,fragmentShader:e.fragment,defines:e.defines,uniforms:{}})}function Sr(r,e,t){let n=Iy(r,e);return ii(r,n,e,t,!0),n}function ii(r,e,t,n,i=!1){let s=t,a=e,o;for(let l of yh){let u=s[l];if(u===void 0)continue;let d=El[l]??l,h=a[d];if(h&&typeof h=="object"&&"setRGB"in h?xt(r,h,u):a[d]=_l(r,u),l==="color"){let f=Cl(u);f<1&&(o=f)}}for(let l of Object.keys(s)){if(l==="type"||l==="params"||yh.includes(l)||Il.includes(l)||l==="uniforms"||l==="vertex"||l==="fragment"||l==="defines"||l==="raw"||l==="extends"||!i&&bh.includes(l)||l==="transparent")continue;let u=s[l];if(u!==void 0)switch(l){case"faces":e.side=sh(r,u);break;case"shading":a.flatShading=u==="flat";break;case"blend":e.blending=ah(r,u);break;case"normalScale":Fy(r,a,u);break;case"rotation":a.rotation=He(u);break;case"iridescenceThicknessRange":a.iridescenceThicknessRange=[...u];break;case"width":a.linewidth=u;break;case"anisotropyRotation":a.anisotropyRotation=He(u);break;default:a[El[l]??l]=u;break}}o!==void 0&&s.opacity===void 0&&(e.opacity=o);let c=Ey(t);!e.transparent&&c&&(e.transparent=!0,e.needsUpdate=!0),s.depthWrite===void 0&&(e.depthWrite=!c);for(let l of Il){let u=s[l];u!==void 0&&(a[El[l]??l]=n.resolve(u,Py.has(l)?"linear":"srgb"))}if(t.type==="shader"&&Ry(r,e,t.uniforms,n),t.params)for(let l of Object.keys(t.params))a[l]=t.params[l];i&&(e.needsUpdate=!0)}function Fy(r,e,t){let n=e.normalScale,i=typeof t=="number"?t:t.x,s=typeof t=="number"?t:t.y;n&&"set"in n?n.set(i,s):e.normalScale=new r.Vector2(i,s)}function Ry(r,e,t,n){if(t)for(let i of Object.keys(t)){let s=By(r,t[i],n),a=e.uniforms[i];a?a.value=s:e.uniforms[i]={value:s}}}function By(r,e,t){if(typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return Dy(e)?t.resolve(e,"srgb"):_l(r,e);if(Array.isArray(e)){let n=e;switch(n.length){case 2:return new r.Vector2(n[0],n[1]);case 3:return new r.Vector3(n[0],n[1],n[2]);case 4:return new r.Vector4(n[0],n[1],n[2],n[3]);default:return[...n]}}if(typeof e=="object"&&e!==null){let n=e;if("src"in n||"data"in n)return t.resolve(e,"srgb");if("w"in n)return new r.Vector4(n.x,n.y,n.z,n.w);if("z"in n)return new r.Vector3(n.x,n.y,n.z);if("y"in n)return new r.Vector2(n.x,n.y)}return e}function Dy(r){return r.startsWith("/")||r.startsWith(".")||/\.(png|jpe?g|webp|avif|svg|ktx2?|hdr|exr)$/i.test(r)}function _n(r){let e=r,t=[r.type];for(let n of bh){let i=e[n];i!==void 0&&t.push(`${n}=${JSON.stringify(i)}`)}for(let n of Il)e[n]!==void 0&&t.push(`+${n}`);return r.type==="shader"&&(t.push(`v=${wh(r.vertex)}`,`f=${wh(r.fragment)}`),r.uniforms&&t.push(`u=${Object.keys(r.uniforms).sort().join(",")}`)),r.params&&t.push(`params=${JSON.stringify(r.params)}`),t.join("|")}function wh(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}import{resolveShadowOptions3D as kh,resolveVector3 as Oy}from"@motionscript/core";var Ly=4*Math.PI;function xh(r,e){switch(e.type){case"ambient":return new r.AmbientLight;case"hemisphere":return new r.HemisphereLight;case"directional":return new r.DirectionalLight;case"point":return new r.PointLight;case"spot":return new r.SpotLight;case"area":return new r.RectAreaLight;default:return new r.AmbientLight}}function Sh(r,e,t){let n=t;if(t.type==="hemisphere"){let s=e;t.sky!==void 0&&xt(r,s.color,t.sky),t.ground!==void 0&&xt(r,s.groundColor,t.ground)}else n.color!==void 0&&xt(r,e.color,n.color);if(n.intensity!==void 0){let s=t.type==="point"||t.type==="spot"?Ly:1;e.intensity=n.intensity*s}let i=e;if(n.distance!==void 0&&(i.distance=n.distance),n.decay!==void 0&&(i.decay=n.decay),n.penumbra!==void 0&&(i.penumbra=n.penumbra),n.angle!==void 0&&(i.angle=He(n.angle)),n.width!==void 0&&(i.width=n.width),n.height!==void 0&&(i.height=n.height),"target"in n&&n.target!==void 0&&"target"in e){let s=Oy(n.target),a=e.target;a.position.set(s.x,s.y,s.z),a.parent||e.add(a),a.updateMatrixWorld()}if(t.params)for(let s of Object.keys(t.params))i[s]=t.params[s]}function Th(r,e,t){if(!("shadow"in r)||!r.shadow)return;let n=e.shadow,i=n===void 0?null:kh(n);if(r.castShadow=i!==null,!i)return;let s=r.shadow,a=s.camera;s.radius=1+(i.softness??.5)*8;let o=i.extent??Uy(t),c=!1;e.type==="directional"&&a.left!==-o&&(a.left=-o,a.right=o,a.top=o,a.bottom=-o,c=!0);let l=Math.max(.05,o*.05),u=Math.max(l+1,o*8);a.near!==l&&(a.near=l,c=!0),a.far!==u&&(a.far=u,c=!0),c&&a.updateProjectionMatrix();let d=s.mapSize.x||2048;if(s.bias=-(u-l)/(d*512),s.normalBias=o*.01,i.params){let h=s;for(let f of Object.keys(i.params))h[f]=i.params[f]}}function Uy(r){if(!r)return 10;let e=Math.max(r.max.x-r.min.x,r.max.y-r.min.y,r.max.z-r.min.z);return Math.max(1,e*.75)}function vh(r){let e=r.shadow,t=e!==void 0&&kh(e)!==null,n=[r.type];return t&&n.push("shadow"),r.params&&n.push(`params=${JSON.stringify(r.params)}`),n.join("|")}import{resolveCameraPlacement as Hy}from"@motionscript/core";import{resolveVector3 as Va,shadowCasts as zy,shadowReceives as Ny}from"@motionscript/core";function si(r,e){if(!e){r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),r.visible=!0;return}if(e.position!==void 0){let t=Va(e.position);r.position.set(t.x,t.y,t.z)}else r.position.set(0,0,0);if(e.scale!==void 0){let t=Va(e.scale);r.scale.set(t.x,t.y,t.z)}else r.scale.set(1,1,1);if(e.lookAt!==void 0){let t=Va(e.lookAt);r.lookAt(t.x,t.y,t.z)}else if(e.quaternion!==void 0){let t=e.quaternion;r.quaternion.set(t.x,t.y,t.z,t.w)}else e.rotation!==void 0?Vy(r,e.rotation):r.rotation.set(0,0,0);r.visible=e.visible!==!1,r.castShadow=zy(e.shadow),r.receiveShadow=Ny(e.shadow),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder)}function Vy(r,e){let t=Va(e),n=e?.order;r.rotation.set(He(t.x),He(t.y),He(t.z),n??"XYZ")}function Ah(r,e,t){return t.type==="perspective"?e instanceof r.PerspectiveCamera:e instanceof r.OrthographicCamera}function Ml(r,e){return e?.type==="orthographic"?new r.OrthographicCamera:new r.PerspectiveCamera}function _h(r,e,t,n,i,s){let a=i>0?n/i:1;if(!t){let u=e;u.fov=50,u.near=.1,u.far=1e3,u.aspect!==a&&(u.aspect=a),u.position.set(0,0,5),u.lookAt(0,0,0),u.updateProjectionMatrix();return}let o=Wy(t,s),c=!1;if(t.type==="perspective"){let u=e,d=t.fov??50,h=t.zoom??1;u.fov!==d&&(u.fov=d,c=!0),u.near!==o.near&&(u.near=o.near,c=!0),u.far!==o.far&&(u.far=o.far,c=!0),u.aspect!==a&&(u.aspect=a,c=!0),u.zoom!==h&&(u.zoom=h,c=!0)}else{let u=e,d=t.zoom??1,h=(t.frustumHeight??10)/2,f=-h*a,p=h*a;u.left!==f&&(u.left=f,c=!0),u.right!==p&&(u.right=p,c=!0),u.top!==h&&(u.top=h,c=!0),u.bottom!==-h&&(u.bottom=-h,c=!0),u.near!==o.near&&(u.near=o.near,c=!0),u.far!==o.far&&(u.far=o.far,c=!0),u.zoom!==d&&(u.zoom=d,c=!0)}let l=Hy(t);if(si(e,{...t,position:l.position,lookAt:l.lookAt}),t.params){let u=e;for(let d of Object.keys(t.params))u[d]=t.params[d];c=!0}c&&e.updateProjectionMatrix()}function Wy(r,e){if(r.near!==void 0&&r.far!==void 0)return{near:r.near,far:r.far};let t=e?Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z):10,n=r.distance??Math.max(t,1)*2,i=Math.max(t,n,1);return{near:r.near??Math.max(.01,i/1e3),far:r.far??i*10}}import{resolveVector3 as qy}from"@motionscript/core";function Ch(r,e,t){if(!t){e.fog=null;return}if(t.density!==void 0){let s=t.density;if(e.fog instanceof r.FogExp2){t.color!==void 0&&xt(r,e.fog.color,t.color),e.fog.density=s;return}e.fog=new r.FogExp2(0,s),t.color!==void 0&&xt(r,e.fog.color,t.color);return}let n=t.near??1,i=t.far??1e3;if(e.fog instanceof r.Fog){t.color!==void 0&&xt(r,e.fog.color,t.color),e.fog.near=n,e.fog.far=i;return}e.fog=new r.Fog(0,n,i),t.color!==void 0&&xt(r,e.fog.color,t.color)}function Ph(r,e,t,n){if(!t){Ha(e),e.environment=null,e.background=null;return}let i=jy(r,e,t,n);if(!i){e.background=null;return}if(e.environment=i,e.environmentIntensity=t.intensity??1,t.rotation!==void 0&&"environmentRotation"in e){let{x:s,y:a,z:o}=qy(t.rotation);e.environmentRotation.set(He(s),He(a),He(o))}t.background?(e.background=i,e.backgroundBlurriness=t.blur??0,e.backgroundIntensity=t.intensity??1):e.background=null}function Ha(r){r.userData.__roomEnvironment?.texture.dispose(),r.userData.__roomEnvironment=void 0}function jy(r,e,t,n){if(t.preset===void 0||!n)return null;let i=e.userData.__roomEnvironment;if(i?.renderer===n)return i.texture;Ha(e);let s=new r.PMREMGenerator(n),a=new r.Scene;a.background=new r.Color(12303291);let o=s.fromScene(a,.04);return s.dispose(),e.userData.__roomEnvironment={renderer:n,texture:o.texture},o.texture}function Eh(r){return vn(r)?.clone()??null}function Ih(r){return vn(r)!==null}function Mh(r,e,t,n,i){let s=vn(t)?.animations??[];if(s.length===0)return i;if(!n||n.length===0){if(i)for(let o of i.actions.values())o.enabled=!1;return i}let a=i??{mixer:new r.AnimationMixer(e),actions:new Map};for(let o of a.actions.values())o.enabled=!1;for(let o of n){let c=Ky(s,o.clip);if(!c)continue;let l=a.actions.get(c.name);l||(l=a.mixer.clipAction(c),a.actions.set(c.name,l)),l.enabled=!0,l.setEffectiveWeight(o.weight??1),l.play(),l.paused=!0,l.time=$y(o.time,c.duration)}return a.mixer.update(0),a}function Fh(r,e,t,n){t&&e.traverse(i=>{let s=i;if(!s.isMesh)return;let a=Array.isArray(s.material)?s.material:[s.material],o=a.map(c=>{let l=Gy(t,s.name,c?.name);return l===null?c:Sr(r,t[l],n)});o.some((c,l)=>c!==a[l])&&(s.material=Array.isArray(s.material)?o:o[0])})}function Rh(r){return r?Object.keys(r).sort().map(e=>`${e}=${JSON.stringify(r[e])}`).join("&"):""}function Gy(r,e,t){return r[e]!==void 0?e:t!==void 0&&r[t]!==void 0?t:null}function Ky(r,e){return e===void 0?r[0]:typeof e=="number"?r[e]:r.find(t=>t.name===e)}function $y(r,e){if(!Number.isFinite(r)||e<=0)return 0;let t=r%e;return t<0?t+e:t}var Wa=class{three;scene;camera;cache=new Map;frame=0;constructor(e){this.three=e,this.scene=new e.Scene,this.camera=Ml(e,null)}sync(e,t,n,i,s=null){this.frame++;let a=this.three,o=[-1],c=[this.scene],l=[""],u=new Map,d=[],h=null,f=!1;for(let b of e.ops()){if(b.kind==="pop"){c.length>1&&(c.pop(),o.pop(),l.pop());continue}o[o.length-1]++;let k=l[l.length-1],T=c[c.length-1];if(b.kind==="push"){let M=k?`${k}.${o[o.length-1]}`:String(o[o.length-1]),P=this.resolveGroup(M,b.transform,T);c.push(P),o.push(-1),l.push(b.transform?.key?`@${b.transform.key}`:M);continue}if(b.kind==="camera"){h={descriptor:b.camera,parent:T},f=!0;continue}let S=Yy(b),_=this.resolveDrawable(b,Qy(k,b,S,u),T,i,S);_&&b.kind==="light"&&d.push({light:_.object,descriptor:b.light})}this.sweep();let p=this.sceneBounds();for(let{light:b,descriptor:k}of d)Th(b,k,p);h&&this.resolveCamera(h.descriptor,t,n,h.parent,p),Ch(a,this.scene,e.fogDescriptor()),Ph(a,this.scene,e.environmentDescriptor(),s?.active()??null);let m=e.shadowSettings(),g=e.toneSettings(),y=uh(a,m?.quality);s?.applySettings(a,{shadowsEnabled:m?.enabled===!0,shadowType:y.type,toneMapping:dh(a,g?.mapping),toneMappingExposure:g?.exposure??1});for(let{light:b}of d){let k=b.shadow;k&&k.mapSize.x!==y.mapSize&&(k.mapSize.set(y.mapSize,y.mapSize),k.map?.dispose(),k.map=null)}return f||this.resolveCamera(null,t,n,this.scene,p),{scene:this.scene,camera:this.camera}}sceneBounds(){this.scene.updateMatrixWorld(!0);let e=new this.three.Box3().setFromObject(this.scene);return e.isEmpty()?null:{min:{x:e.min.x,y:e.min.y,z:e.min.z},max:{x:e.max.x,y:e.max.y,z:e.max.z}}}resolveGroup(e,t,n){let i=t?.key?`@${t.key}|push`:`${e}|push`,s=this.cache.get(i);return(!s||s.kind!=="push")&&(this.discard(s),s={object:new this.three.Group,kind:"push",seen:this.frame},this.cache.set(i,s)),s.seen=this.frame,si(s.object,t),s.object.parent!==n&&n.add(s.object),s.object}resolveDrawable(e,t,n,i,s){let a=this.cache.get(t);if(a&&a.kind!==e.kind&&(this.discard(a),a=void 0),a=this.ensure(a,t,e,i,s),!!a)return a.seen=this.frame,this.mutate(a,e,i),a.object.parent!==n&&n.add(a.object),a}ensure(e,t,n,i,s){if(e&&Jy(e,s))return e;this.discard(e);let a=this.build(n,i);if(!a)return;let o={object:a,kind:n.kind,seen:this.frame,...s},c=n.geometry;return c?.type==="parametric"&&(o.parametricRevision=c.revision),this.cache.set(t,o),o}build(e,t){let n=this.three;switch(e.kind){case"mesh":{let i=Qr(n,e.geometry),s=this.buildMaterials(e.material,t);return new n.Mesh(i,s)}case"light":return xh(n,e.light);case"instances":{let i=Qr(n,e.geometry),s=Sr(n,e.material,t),a=new n.InstancedMesh(i,s,Math.max(1,e.instances.length));return a.instanceMatrix.setUsage(n.DynamicDrawUsage),a}case"points":{let i=Qr(n,e.geometry),s=Sr(n,e.material,t);return new n.Points(i,s)}case"line":{let i=Qr(n,e.geometry),s=Sr(n,e.material,t),a=e.mode==="segments"?new n.LineSegments(i,s):e.mode==="loop"?new n.LineLoop(i,s):new n.Line(i,s);return e.material.type==="lineDashed"&&a.computeLineDistances(),a}case"sprite":{let i=Sr(n,e.material,t);return new n.Sprite(i)}case"model":{let i=Eh(e.src);return i||rh(Xy("gltf",e.src),"gltf"),i}default:return null}}buildMaterials(e,t){return Array.isArray(e)?e.map(n=>Sr(this.three,n,t)):Sr(this.three,e,t)}mutate(e,t,n){let i=this.three;switch(si(e.object,t.transform),t.kind){case"mesh":case"points":case"line":{let s=e.object;this.refreshDynamicGeometry(s,t.geometry,e),this.applyMaterials(s.material,(t.kind==="mesh",t.material),n);break}case"instances":{let s=e.object;this.refreshDynamicGeometry(s,t.geometry,e),ii(i,s.material,t.material,n),this.writeInstances(s,t.instances,t.colors);break}case"sprite":ii(i,e.object.material,t.material,n);break;case"light":Sh(i,e.object,t.light);break;case"model":e.modelPlayback=Mh(i,e.object,t.src,t.animation,e.modelPlayback),Fh(i,e.object,t.override,n);break}}applyMaterials(e,t,n){if(Array.isArray(e)&&Array.isArray(t)){let i=Math.min(e.length,t.length);for(let s=0;s<i;s++)ii(this.three,e[s],t[s],n);return}!Array.isArray(e)&&!Array.isArray(t)&&ii(this.three,e,t,n)}refreshDynamicGeometry(e,t,n){if(!ph(t))return;if(t.type==="parametric"&&t.revision!==void 0){if(n.parametricRevision===t.revision)return;n.parametricRevision=t.revision}let i=gh(t);mh(e.geometry,i)||(e.geometry.dispose(),e.geometry=Qr(this.three,i),n.geometrySig=An(t),e.computeLineDistances&&e.isLine&&e.computeLineDistances())}writeInstances(e,t,n){let i=this.three,s=e.userData.__scratch??(e.userData.__scratch=new i.Object3D),a=Math.min(t.length,e.count);for(let o=0;o<a;o++)si(s,t[o]),s.updateMatrix(),e.setMatrixAt(o,s.matrix);if(e.instanceMatrix.needsUpdate=!0,a<e.count){s.position.set(0,0,0),s.rotation.set(0,0,0),s.scale.set(0,0,0),s.updateMatrix();for(let o=a;o<e.count;o++)e.setMatrixAt(o,s.matrix)}if(n){let o=new i.Color;for(let c=0;c<Math.min(n.length,e.count);c++)xt(i,o,n[c]),e.setColorAt(c,o);e.instanceColor&&(e.instanceColor.needsUpdate=!0)}}resolveCamera(e,t,n,i,s){let a=this.three;e&&!Ah(a,this.camera,e)&&(this.camera=Ml(a,e)),_h(a,this.camera,e,t,n,s),i!==this.scene?this.camera.parent!==i&&i.add(this.camera):this.camera.parent&&this.camera.removeFromParent()}sweep(){for(let[e,t]of this.cache)t.seen!==this.frame&&(this.discard(t),this.cache.delete(e))}discard(e){e&&(e.object.removeFromParent(),Bh(e.object))}dispose(){for(let e of this.cache.values())this.discard(e);this.cache.clear(),Ha(this.scene),this.scene.environment=null,this.scene.clear()}};function Qy(r,e,t,n){let i=`${r}|${e.kind}|${t.geometrySig??""}|${t.materialSig??""}|${t.lightSig??""}|${t.count??""}`,s=n.get(i)??0;return n.set(i,s+1),`${i}#${s}`}function Yy(r){switch(r.kind){case"mesh":return{geometrySig:An(r.geometry),materialSig:Zy(r.material)};case"points":return{geometrySig:An(r.geometry),materialSig:_n(r.material)};case"line":return{geometrySig:An(r.geometry),materialSig:`${r.mode}|${_n(r.material)}`};case"instances":return{geometrySig:An(r.geometry),materialSig:_n(r.material),count:r.instances.length};case"sprite":return{materialSig:_n(r.material)};case"light":return{lightSig:vh(r.light)};case"model":return{geometrySig:`${r.src}|${Ih(r.src)?"1":"0"}`,materialSig:Rh(r.override)};default:return{}}}function Zy(r){return Array.isArray(r)?r.map(_n).join("&"):_n(r)}function Jy(r,e){return r.geometrySig===e.geometrySig&&r.materialSig===e.materialSig&&r.lightSig===e.lightSig&&r.count===e.count}function Bh(r){let e=r;e.geometry?.dispose?.();let t=e.material;if(Array.isArray(t))for(let n of t)n.dispose();else t?.dispose?.();for(let n of[...r.children])Bh(n)}var Dh=null;function Fl(r){Dh=r}function vs(){return Dh}import{isDataTexture3D as Uh,isSurfaceTexture3D as zh,resolveTexture3D as ew}from"@motionscript/core";var or=new Map,Dl=new Map,Rl=0,qa=class{three;assets;surfaceOwner="";rasters;constructor(e,t){this.three=e,this.assets=t}beginFrame(){Rl++}setRasters(e,t){this.surfaceOwner=e,this.rasters=t}resolve(e,t){let n=ew(e),i=tw(e,t,this.surfaceOwner);if(zh(n)){let o=this.rasters?.get(n);if(!o)return null;let c=or.get(i);if(c?.resolved)return c.raster!==o&&(this.uploadRaster(c.texture,o),c.raster=o),c.texture;let l=this.createRasterTexture(o);return this.applySampler(l,e,t),or.set(i,{texture:l,resolved:!0,raster:o}),l}if(!Uh(n))return this.resolveImage(n.src,e,t,i);let s=or.get(i);if(s?.resolved)return s.revision!==n.revision&&(this.uploadData(s.texture,n),s.revision=n.revision),s.texture;let a=this.createDataTexture(n);return this.applySampler(a,e,t),or.set(i,{texture:a,revision:n.revision,resolved:!0}),a}resolveImage(e,t,n,i){let s=this.assets.getImagePixels(e);if(!s)return null;let a=`${i}|px=${s.width}x${s.height}`,o=or.get(a);if(o?.resolved){if(o.pixels!==s){let c=o.texture.image;c.data=s.pixels,o.texture.needsUpdate=!0,o.pixels=s}}else{let c=this.createImageTexture(s);this.applySampler(c,t,n),o={texture:c,resolved:!0,pixels:s},or.set(a,o)}return this.touchLevel(i,a),o.texture}touchLevel(e,t){let n=Dl.get(e);n||Dl.set(e,n=new Map),n.set(t,Rl);for(let[i,s]of n)s>=Rl-1||(or.get(i)?.texture.dispose(),or.delete(i),n.delete(i))}createImageTexture(e){let t=new this.three.DataTexture(e.pixels,e.width,e.height,this.three.RGBAFormat,this.three.UnsignedByteType);return t.flipY=!0,t.needsUpdate=!0,t}createRasterTexture(e){let t=new this.three.DataTexture(e.pixels,e.width,e.height,this.three.RGBAFormat,this.three.UnsignedByteType);return t.flipY=!0,t.needsUpdate=!0,t}uploadRaster(e,t){let n=e.image;n.width===t.width&&n.height===t.height?n.data.set(t.pixels):(n.data=t.pixels,n.width=t.width,n.height=t.height),e.needsUpdate=!0}createDataTexture(e){let t=new this.three.DataTexture(Lh(e.data),e.width,e.height,this.three.RGBAFormat,this.three.UnsignedByteType);return t.needsUpdate=!0,t}uploadData(e,t){let n=e.image,i=Lh(t.data);n.data.length===i.length?n.data.set(i):n.data=i,e.needsUpdate=!0}applySampler(e,t,n){let i=this.three,s=typeof t=="string"?{}:t;if(e.wrapS=Al(i,s.wrapS),e.wrapT=Al(i,s.wrapT),e.magFilter=oh(i,s.magFilter),e.minFilter=ch(i,s.minFilter),e.colorSpace=lh(i,s.colorSpace??n),s.repeat){let[a,o]=Bl(s.repeat);e.repeat.set(a,o)}if(s.offset){let[a,o]=Bl(s.offset);e.offset.set(a,o)}if(s.center){let[a,o]=Bl(s.center);e.center.set(a,o)}s.rotation!==void 0&&(e.rotation=He(s.rotation)),s.anisotropy!==void 0&&(e.anisotropy=s.anisotropy),s.flipY!==void 0&&(e.flipY=s.flipY),e.generateMipmaps=e.minFilter!==i.NearestFilter&&e.minFilter!==i.LinearFilter}};function tw(r,e,t){if(typeof r=="string")return`${r}|${e}`;let n=r,i=[];for(let s of Object.keys(n).sort())s==="data"||s==="revision"||s!=="source"&&i.push(`${s}=${JSON.stringify(n[s])}`);return Uh(r)&&i.push(`data=${r.width}x${r.height}`),zh(r)&&i.push(`owner=${t}`,`sfc=${nw(r)}`),i.push(`cs=${e}`),i.join("|")}var Oh=new WeakMap,rw=0;function nw(r){if(r.identity!==void 0)return r.identity;let e=r.source,t=Oh.get(e);return t===void 0&&(t=`s${rw++}`,Oh.set(e,t)),t}function Bl(r){return Array.isArray(r)?[r[0],r[1]]:[r.x,r.y]}function Lh(r){return r instanceof Uint8Array?r:new Uint8Array(Array.from(r))}function Nh(){for(let r of or.values())r.texture.dispose();or.clear(),Dl.clear()}var As=class{three;assets;host;graphs=new Map;textures;frame=0;touched=new Set;constructor(e,t,n){this.three=e,this.assets=t,this.host=n,this.textures=new qa(e,t)}render(e,t,n,i,s={}){let a=this.graphs.get(e);a||(a=new Wa(this.three),this.graphs.set(e,a)),this.touched.add(e),this.textures.setRasters(e,s.rasters),this.host.prepare(this.three,s);let{scene:o,camera:c}=a.sync(t,n,i,this.textures,this.host);return this.host.render(this.three,e,o,c,n,i,s)}beginFrame(){this.frame++,this.touched.clear(),this.textures.beginFrame()}sweep(){for(let[e,t]of this.graphs)this.touched.has(e)||(this.release(e,t),this.graphs.delete(e))}dispose(){for(let[e,t]of this.graphs)this.release(e,t);this.graphs.clear(),this.touched.clear()}release(e,t){t.dispose(),this.host.forgetBuffer(e),this.assets.release3DTexture(e)}get module(){return this.three}},ja=null;function ai(r){let e=kl();if(!e)return null;let t=vs();return t?(ja??=new As(e,r,t),ja):null}function Ga(){ja?.dispose(),ja=null}import{forEachTexture3D as qk,isSurfaceTexture3D as jk}from"@motionscript/core";function Ka(r){return 1/Math.max(r.getDeviceScale(),1e-4)}var qe=class{dispose(){}};import{AssetNotLoadedError as Lk,isPixelFilter as Uk}from"@motionscript/core";var iw=[224,224,224],sw=[200,200,200],_s=null;function aw(r){let t=new Uint8Array(4096);for(let n=0;n<32;n++)for(let i=0;i<32;i++){let s=i<16==n<16,[a,o,c]=s?iw:sw,l=(n*32+i)*4;t[l]=a,t[l+1]=o,t[l+2]=c,t[l+3]=255}return r.MakeImage({width:32,height:32,alphaType:r.AlphaType.Unpremul,colorType:r.ColorType.RGBA_8888,colorSpace:r.ColorSpace.SRGB},t,128)}function $a(r){let e=r.canvasKit;if(_s??=aw(e),!_s)return!1;let t=r.getShapeBounds(),n=t?.left??0,i=t?.top??0;return r.paint.setShader(_s.makeShaderOptions(e.TileMode.Repeat,e.TileMode.Repeat,e.FilterMode.Nearest,e.MipmapMode.None,[1,0,n,0,1,i,0,0,1])),!0}function Vh(){_s?.delete(),_s=null}import{effectSurface as Rk}from"@motionscript/core";var Hh={type:"blur",makeImageFilter(r,e){let t=r.radius/2;return e.ImageFilter.MakeBlur(t,t,e.TileMode.Decal,null)}};var Wh={type:"directionalBlur",makeImageFilter(r,e){if(r.radius<=0)return null;let t=r.radius/2,n=r.angle*Math.PI/180,i=Math.cos(n),s=Math.sin(n),a={filter:e.FilterMode.Linear},o=e.ImageFilter.MakeMatrixTransform([i,s,0,-s,i,0,0,0,1],a,null),c=e.ImageFilter.MakeBlur(t,0,e.TileMode.Decal,o);o.delete();let l=e.ImageFilter.MakeMatrixTransform([i,-s,0,s,i,0,0,0,1],a,c);return c.delete(),l}};var qh={type:"grayscale",makeImageFilter(r,e){let t=Math.max(0,Math.min(1,r.amount)),n=[1-t+t*.2126,t*.7152,t*.0722,0,0,t*.2126,1-t+t*.7152,t*.0722,0,0,t*.2126,t*.7152,1-t+t*.0722,0,0,0,0,0,1,0],i=e.ColorFilter.MakeMatrix(n),s=e.ImageFilter.MakeColorFilter(i,null);return i.delete(),s}};var jh={type:"pixelate",makeImageFilter(r,e,{width:t,height:n}){let i=Math.max(1,Math.min(t,r.blocks.x)),s=Math.max(1,Math.min(n,r.blocks.y)),a=t/i,o=n/s,c={filter:e.FilterMode.Nearest},l=r.sharpColors?{filter:e.FilterMode.Nearest}:{filter:e.FilterMode.Linear},u=-t/2,d=-n/2,h=e.ImageFilter.MakeMatrixTransform([1/a,0,-u/a,0,1/o,-d/o,0,0,1],c,null),f=e.ImageFilter.MakeMatrixTransform([a,0,u,0,o,d,0,0,1],l,h);return h.delete(),f}};var Gh={type:"bloom",makeImageFilter(r,e){if(r.radius<=0||r.intensity<=0)return null;let t=Math.max(0,Math.min(1,r.threshold)),n=r.radius/2,i=t<1?1/(1-t):1,s=-t*i,a=[i,0,0,0,s,0,i,0,0,s,0,0,i,0,s,0,0,0,1,0],o=e.ColorFilter.MakeMatrix(a),c=e.ImageFilter.MakeColorFilter(o,null);o.delete();let l=e.ImageFilter.MakeBlur(n,n,e.TileMode.Decal,c);c.delete();let u=l;if(r.intensity!==1){let h=r.intensity,f=[h,0,0,0,0,0,h,0,0,0,0,0,h,0,0,0,0,0,1,0],p=e.ColorFilter.MakeMatrix(f);u=e.ImageFilter.MakeColorFilter(p,l),p.delete(),l.delete()}let d=e.ImageFilter.MakeBlend(e.BlendMode.Screen,null,u);return u.delete(),d}};var Kh={type:"vintage",makeImageFilter(r,e){if(r.amount<=0&&r.warmth===0)return null;let t=Math.max(0,Math.min(1,r.amount)),n=Math.max(-1,Math.min(1,r.warmth)),i=(m,g)=>m+(g-m)*t,s=[.393,.769,.189],a=[.349,.686,.168],o=[.272,.534,.131],c=n>0?n*.15:0,l=n<0?-n*.15:0,u=n<0?-n*.05:0,d=n>0?n*.05:0,h=[i(1,s[0]),i(0,s[1]),i(0,s[2]),0,c-u,i(0,a[0]),i(1,a[1]),i(0,a[2]),0,0,i(0,o[0]),i(0,o[1]),i(1,o[2]),0,-l+d,0,0,0,1,0],f=e.ColorFilter.MakeMatrix(h),p=e.ImageFilter.MakeColorFilter(f,null);return f.delete(),p}};var $h={type:"chromaticAberration",makeImageFilter(r,e){if(r.amount<=0)return null;let t=r.angle*Math.PI/180,n=Math.cos(t)*r.amount,i=Math.sin(t)*r.amount,s=[1.4,-.2,-.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],a=e.ColorFilter.MakeMatrix(s),o=e.ImageFilter.MakeOffset(n,i,null),c=e.ImageFilter.MakeColorFilter(a,o);a.delete(),o.delete();let l=[0,0,0,0,0,0,0,0,0,0,-.2,-.2,1.4,0,0,0,0,0,1,0],u=e.ColorFilter.MakeMatrix(l),d=e.ImageFilter.MakeOffset(-n,-i,null),h=e.ImageFilter.MakeColorFilter(u,d);u.delete(),d.delete();let f=e.ImageFilter.MakeBlend(e.BlendMode.Screen,null,c);c.delete();let p=e.ImageFilter.MakeBlend(e.BlendMode.Screen,f,h);return f.delete(),h.delete(),p}};var ow=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],oi=.2126,ci=.7152,li=.0722;function cw(r){switch(r){case"red":return[-1,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];case"green":return[1,0,0,0,0,0,-1,0,0,1,0,0,1,0,0,0,0,0,1,0];case"blue":return[1,0,0,0,0,0,1,0,0,0,0,0,-1,0,1,0,0,0,1,0];case"alpha":return[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,-1,1];case"hue":return[2*oi-1,2*ci,2*li,0,0,2*oi,2*ci-1,2*li,0,0,2*oi,2*ci,2*li-1,0,0,0,0,0,1,0];case"luminance":return[1-2*oi,-2*ci,-2*li,0,1,-2*oi,1-2*ci,-2*li,0,1,-2*oi,-2*ci,1-2*li,0,1,0,0,0,1,0];default:return[-1,0,0,0,1,0,-1,0,0,1,0,0,-1,0,1,0,0,0,1,0]}}var Xh={type:"invert",makeImageFilter(r,e){let t=Math.max(0,Math.min(1,r.strength));if(t===0)return null;let n=cw(r.channel),i=ow.map((o,c)=>o+(n[c]-o)*t),s=e.ColorFilter.MakeMatrix(i),a=e.ImageFilter.MakeColorFilter(s,null);return s.delete(),a}};var ui=new Map,lw=64,Ol=!1;function ne(r,e){let t=ui.get(r);if(t)return t;let n=e.RuntimeEffect.Make(r,i=>{console.warn("[SkSL] Compilation error:",i)});return n&&ui.set(r,n),ui.size>lw&&!Ol&&(Ol=!0,console.warn(`[SkSL] ${ui.size} distinct shader sources have been compiled. If a shader's source is built per frame (e.g. a value interpolated into a template literal), keep the source constant and move what changes into a uniform \u2014 uniform values are an in-place write, a new source is a new program.`)),n??null}function Qh(){for(let r of ui.values())r.delete();ui.clear(),Ol=!1}import{resolveEffectAxis as uw}from"@motionscript/core";function di(r,e){return r.mode==="backdrop"?[0,0]:[e.centerX-e.width/2,e.centerY-e.height/2]}var dw=`
|
|
695
|
+
`)),q=X[X.length-1]}else throw new Error("Bad write");return z.length};let D=[],V,W=0;Ue=({data:le})=>(le.length>0&&(D.push(le),V&&V()),te),J.read=(le,z,X,oe,Te,P)=>{if(le!==0||X!==0||oe!==z.length||Te!==null)throw new Error("Bad read");if(D.length===0){V=()=>J.read(le,z,X,oe,Te,P);return}let L=D[0],ne=Math.max(0,Math.min(oe,L.length-W));z.set(L.subarray(W,W+ne),X),W+=ne,W===L.length&&(D.shift(),W=0),P(null,ne)};let te=new ge.Go;return te.argv=["","--service=0.28.2"],Qe(pe,te).then(le=>{Ee(null),te.run(le)},le=>{Ee(le)}),te};function Qe(pe,me){return Le(this,null,function*(){if(pe instanceof WebAssembly.Module)return WebAssembly.instantiate(pe,me.importObject);let J=yield fetch(pe);if(!J.ok)throw new Error(`Failed to download ${JSON.stringify(pe)}`);if("instantiateStreaming"in WebAssembly&&/^application\/wasm($|;)/i.test(J.headers.get("Content-Type")||""))return(yield WebAssembly.instantiateStreaming(J,me.importObject)).instance;let q=yield J.arrayBuffer();return(yield WebAssembly.instantiate(q,me.importObject)).instance})}return pe=>Ue(pe)})(Ee=>U.onmessage({data:Ee})),Be;U={onmessage:null,postMessage:Ee=>setTimeout(()=>{try{Be=he({data:Ee})}catch(Le){j(Le)}}),terminate(){if(Be)for(let Ee of Be._scheduledTimeouts.values())clearTimeout(Ee)}}}let H,se,B=new Promise((he,Be)=>{H=he,se=Be});U.onmessage=({data:he})=>{U.onmessage=({data:Be})=>re(Be),he?se(he):H()},U.postMessage(A||new URL(S,location.href).toString());let{readFromStdout:re,service:ae}=ny({writeToStdin(he){U.postMessage(he)},isSync:!1,hasFS:!1,esbuild:l});yield B,Ua=()=>{U.terminate(),An=void 0,Ua=void 0,Na=void 0},Na={build:he=>new Promise((Be,Ee)=>{$.then(Ee),ae.buildOrContext({callName:"build",refs:null,options:he,isTTY:!1,defaultWD:"/",callback:(Le,Ue)=>Le?Ee(Le):Be(Ue)})}),context:he=>new Promise((Be,Ee)=>{$.then(Ee),ae.buildOrContext({callName:"context",refs:null,options:he,isTTY:!1,defaultWD:"/",callback:(Le,Ue)=>Le?Ee(Le):Be(Ue)})}),transform:(he,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.transform({callName:"transform",refs:null,input:he,options:Be||{},isTTY:!1,fs:{readFile(Ue,ge){ge(new Error("Internal error"),null)},writeFile(Ue,ge){ge(null)}},callback:(Ue,ge)=>Ue?Le(Ue):Ee(ge)})}),formatMessages:(he,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.formatMessages({callName:"formatMessages",refs:null,messages:he,options:Be,callback:(Ue,ge)=>Ue?Le(Ue):Ee(ge)})}),analyzeMetafile:(he,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof he=="string"?he:JSON.stringify(he),options:Be,callback:(Ue,ge)=>Ue?Le(Ue):Ee(ge)})})}}),xy=l})(typeof qd=="object"?qd:{set exports(r){(typeof self<"u"?self:this).esbuild=r}})});import{resolveSurfaceSource as bx,CanvasRenderContext2D as kx,withRichTextDescriptor as Sx,fillOps as xx,strokeOps as Tx,shadowOps as Ax,alignmentOps as vx,resolveShapeAlignment as _x,resolvePivotPosition as Cx,stripShapeAlignmentKeys as Px}from"@motionscript/core";import{canvas3DResourceKey as sh,parseCanvas3DResourceKey as Ey,registerCanvas3DResourceLoader as Iy,registerCanvas3DWarmup as My}from"@motionscript/core";var bl=null,nh=null,za=new Set,Ts=new Map;function kl(){return bl}function As(){return bl?Promise.resolve():(nh??=import("./chunks/three.module-Z4EOVUWF.js").then(r=>(bl=r,r)),nh.then(()=>{}))}function Sl(r){za.add(r)}function xl(){return za.size>0||Ts.size>0}function ah(r,e){Ts.set(r,e)}async function Tl(){let r=!1;for(let e=0;e<4&&!(za.size===0&&Ts.size===0);e++){za.clear();let t=[...Ts];Ts.clear(),await As(),t.length>0&&await Promise.all(t.map(([n])=>oh(n))),r=!0}return r}var Va=new Map;async function oh(r){let e=Ey(r);if(e?.kind!=="gltf")return;let t=await Fy(e.src);t&&Va.set(r,t)}function vn(r){return Va.get(sh("gltf",r))??null}async function Fy(r){try{let[,e,t]=await Promise.all([As(),import("./chunks/GLTFLoader-PGXD4V5B.js"),import("./chunks/SkeletonUtils-XYDMTGTM.js")]),n=await new e.GLTFLoader().loadAsync(r);return{scene:n.scene,animations:n.animations,clone:()=>t.clone(n.scene)}}catch(e){return ih.has(r)||(ih.add(r),console.warn(`[motionscript] Could not load the model "${r}" (only glTF/GLB files load): ${e instanceof Error?e.message:String(e)}`)),null}}var ih=new Set;function Ry(r){r.scene.traverse(e=>{let t=e;t.geometry?.dispose?.();let n=Array.isArray(t.material)?t.material:[t.material];for(let i of n)if(i){for(let s of Object.values(i)){let a=s;a?.isTexture&&a.dispose()}i.dispose()}})}function Al(){My(As),Iy(async(r,e)=>{let t=sh(r,e);await oh(t);let n=Va.get(t);return n?()=>{Va.delete(t),Ry(n)}:()=>{}})}import{canvas3DResourceKey as fw}from"@motionscript/core";import{parseColor as ch}from"@motionscript/core";function He(r){return r*(Math.PI/180)}function lh(r,e){switch(e){case"back":return r.BackSide;case"both":return r.DoubleSide;default:return r.FrontSide}}function uh(r,e){switch(e){case"additive":return r.AdditiveBlending;case"subtractive":return r.SubtractiveBlending;case"multiply":return r.MultiplyBlending;case"none":return r.NoBlending;default:return r.NormalBlending}}function vl(r,e){switch(e){case"repeat":return r.RepeatWrapping;case"mirror":return r.MirroredRepeatWrapping;default:return r.ClampToEdgeWrapping}}function dh(r,e){return e==="nearest"?r.NearestFilter:r.LinearFilter}function hh(r,e){return e==="nearest"?r.NearestFilter:r.LinearMipmapLinearFilter}function fh(r,e){return e==="linear"?r.LinearSRGBColorSpace:r.SRGBColorSpace}function mh(r,e){switch(e){case"low":return{type:r.PCFShadowMap,mapSize:512};case"high":return{type:r.PCFSoftShadowMap,mapSize:4096};default:return{type:r.PCFSoftShadowMap,mapSize:2048}}}function ph(r,e){switch(e){case"none":return r.NoToneMapping;case"linear":return r.LinearToneMapping;case"reinhard":return r.ReinhardToneMapping;case"cineon":return r.CineonToneMapping;case"agx":return r.AgXToneMapping;case"neutral":return r.NeutralToneMapping;default:return r.ACESFilmicToneMapping}}function St(r,e,t){let[n,i,s,a]=typeof t=="string"?ch(t):t;return e.setRGB(n,i,s,r.SRGBColorSpace),a}function _l(r,e){let t=new r.Color;return St(r,t,e),t}function Cl(r){let[,,,e]=typeof r=="string"?ch(r):r;return e}import{cylinderRadii as By,evaluateParametric as gh,evaluateRoundedBox as Dy,resolveBevel3D as Oy,resolveVector3 as yh,segmentsOf as xt,toPathString as Ly}from"@motionscript/core";function Qr(r,e){switch(e.type){case"box":{let[t,n,i]=xt(e.segments,[1,1,1]),s=e.width??1,a=e.height??1,o=e.depth??1;return(e.cornerRadius??0)>0?Pl(r,Dy({width:s,height:a,depth:o,radius:e.cornerRadius,segments:[t,n,i]})):new r.BoxGeometry(s,a,o,t,n,i)}case"sphere":{let[t,n]=xt(e.segments,[32,16]);return new r.SphereGeometry(e.radius??1,t,n,He(e.startAngle??0),He(e.sweep??360),He(e.startLatitude??0),He(e.latitudeSweep??180))}case"plane":{let[t,n]=xt(e.segments,[1,1]);return new r.PlaneGeometry(e.width??1,e.height??1,t,n)}case"cylinder":{let[t,n]=By(e.radius),[i,s]=xt(e.segments,[32,1]);return new r.CylinderGeometry(t,n,e.height??1,i,s,!(e.capped??!0),He(e.startAngle??0),He(e.sweep??360))}case"cone":{let[t,n]=xt(e.segments,[32,1]);return new r.ConeGeometry(e.radius??1,e.height??1,t,n,!(e.capped??!0),He(e.startAngle??0),He(e.sweep??360))}case"torus":{let[t,n]=xt(e.segments,[16,48]),i=new r.TorusGeometry(e.radius??1,e.thickness??.4,t,n,He(e.sweep??360));return e.startAngle&&i.rotateZ(He(e.startAngle)),i}case"torusKnot":{let[t,n]=xt(e.segments,[64,8]),[i,s]=e.windings??[2,3];return new r.TorusKnotGeometry(e.radius??1,e.thickness??.4,t,n,i,s)}case"circle":{let[t]=xt(e.segments,[32]);return new r.CircleGeometry(e.radius??1,t,He(e.startAngle??0),He(e.sweep??360))}case"ring":{let[t,n]=xt(e.segments,[32,1]);return new r.RingGeometry(e.innerRadius??.5,e.radius??1,t,n,He(e.startAngle??0),He(e.sweep??360))}case"capsule":{let[t,n]=xt(e.segments,[16,8]);return new r.CapsuleGeometry(e.radius??.5,e.height??1,n,t)}case"polyhedron":{let[t]=xt(e.segments,[1]);return Ny(r,e.shape,e.radius??1,e.segments===void 0?0:t)}case"extrude":return zy(r,e);case"lathe":{let[t]=xt(e.segments,[12]);return new r.LatheGeometry(e.points.map(n=>Gy(r,n)),t,He(e.startAngle??0),He(e.sweep??360))}case"tube":{let[t,n]=xt(e.segments,[64,8]);return new r.TubeGeometry(new r.CatmullRomCurve3(e.points.map(i=>qy(r,i)),e.closed??!1),t,e.radius??1,n,e.closed??!1)}case"buffer":return Pl(r,e);case"parametric":return Pl(r,gh(e));case"edges":{let t=Qr(r,e.source),n=new r.EdgesGeometry(t,e.thresholdAngle??1);return t.dispose(),n}case"wireframe":{let t=Qr(r,e.source),n=new r.WireframeGeometry(t);return t.dispose(),n}case"modelGeometry":return Uy(vn(e.src)?.scene,e.node)?.geometry.clone()??new r.BufferGeometry;default:return new r.BufferGeometry}}function Uy(r,e){if(!r)return null;if(e!==void 0){let n=r.getObjectByName(e);return n?.isMesh?n:null}let t=null;return r.traverse(n=>{let i=n;t===null&&i.isMesh&&(t=i)}),t}function Ny(r,e,t,n){switch(e){case"tetrahedron":return new r.TetrahedronGeometry(t,n);case"octahedron":return new r.OctahedronGeometry(t,n);case"dodecahedron":return new r.DodecahedronGeometry(t,n);default:return new r.IcosahedronGeometry(t,n)}}function zy(r,e){let t=e.path,n=typeof t=="object"&&"toPathState"in t?t.toPathState().data:t,i=Vy(r,Ly(n));if(i.length===0)return new r.BufferGeometry;let[s]=xt(e.segments,[12]),a=Oy(e.bevel);return new r.ExtrudeGeometry(i,{depth:e.depth??1,curveSegments:s,bevelEnabled:a!==null,bevelThickness:a?.thickness??.2,bevelSize:a?.size??.1,bevelOffset:a?.offset??0,bevelSegments:a?.segments??3})}function Vy(r,e){let t=[],n=null,i=0,s=0,a=e.match(/[MLCQZmlcqz][^MLCQZmlcqz]*/g)??[];for(let o of a){let c=o[0],l=(o.slice(1).match(/-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]).map(Number);switch(c){case"M":case"m":{n&&t.push(n),n=new r.Shape,i=l[0]??0,s=l[1]??0,n.moveTo(i,s);break}case"L":case"l":{if(!n)break;for(let u=0;u+1<l.length;u+=2)i=l[u],s=l[u+1],n.lineTo(i,s);break}case"C":case"c":{if(!n)break;for(let u=0;u+5<l.length;u+=6)n.bezierCurveTo(l[u],l[u+1],l[u+2],l[u+3],l[u+4],l[u+5]),i=l[u+4],s=l[u+5];break}case"Q":case"q":{if(!n)break;for(let u=0;u+3<l.length;u+=4)n.quadraticCurveTo(l[u],l[u+1],l[u+2],l[u+3]),i=l[u+2],s=l[u+3];break}case"Z":case"z":{n?.closePath();break}}}return n&&t.push(n),t}function Pl(r,e){let t=new r.BufferGeometry;return t.setAttribute("position",new r.BufferAttribute(Wa(e.position),3)),e.normal&&t.setAttribute("normal",new r.BufferAttribute(Wa(e.normal),3)),e.uv&&t.setAttribute("uv",new r.BufferAttribute(Wa(e.uv),2)),e.color&&t.setAttribute("color",new r.BufferAttribute(Wa(e.color),3)),e.index&&t.setIndex(new r.BufferAttribute(Wy(e.index),1)),wh(e)&&bh(t),t}var El="derivedNormals";function wh(r){return r.computeNormals===!0&&!r.normal}function bh(r){r.computeVertexNormals(),r.userData[El]=!0}function kh(r,e){if(!Ha(r,"position",e.position,3))return!1;let t=wh(e);if(!(t&&r.userData[El]===!0)&&!Ha(r,"normal",e.normal,3)||!Ha(r,"uv",e.uv,2)||!Ha(r,"color",e.color,3))return!1;if(e.index){let i=r.getIndex();if(!i||i.array.length!==e.index.length)return!1;i.array.set(e.index),i.needsUpdate=!0}return t?bh(r):r.userData[El]=!1,r.computeBoundingSphere(),!0}function Ha(r,e,t,n){let i=r.getAttribute(e);return t?!i||i.array.length!==t.length||i.itemSize!==n?!1:(i.array.set(t),i.needsUpdate=!0,!0):i===void 0}function _n(r){let e=[r.type];r.type==="modelGeometry"&&e.push(`loaded=${vn(r.src)?"1":"0"}`);let t=r;for(let n of Object.keys(t).sort()){if(n==="type"||n==="revision"||n==="staticData")continue;let i=t[n];if(i!==void 0)if(n==="source")e.push(`source=${_n(i)}`);else{if(typeof i=="function")continue;Hy(i)?e.push(`${n}#${i.length}`):Array.isArray(i)?e.push(`${n}=${JSON.stringify(i)}`):typeof i=="object"?e.push(`${n}=${JSON.stringify(i)}`):e.push(`${n}=${String(i)}`)}}return e.join("|")}function Sh(r){return r.type==="parametric"?!0:r.type!=="buffer"?!1:r.staticData!==!0}function xh(r){return r.type==="parametric"?gh(r):r}function Hy(r){return ArrayBuffer.isView(r)?!0:Array.isArray(r)&&r.length>4}function Wa(r){return r instanceof Float32Array?r:new Float32Array(Array.from(r))}function Wy(r){return r instanceof Uint32Array?r:new Uint32Array(Array.from(r))}function qy(r,e){let t=yh(e);return new r.Vector3(t.x,t.y,t.z)}function Gy(r,e){let t=yh(e);return new r.Vector2(t.x,t.y)}import{STRUCTURAL_MATERIAL_KEYS as vh}from"@motionscript/core";var Ml=["map","alphaMap","aoMap","normalMap","displacementMap","envMap","lightMap","emissionMap","roughnessMap","metalnessMap","specularMap","gradientMap","matcap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap"],Il={emission:"emissive",emissionStrength:"emissiveIntensity",emissionMap:"emissiveMap"},jy=new Set(["normalMap","roughnessMap","metalnessMap","aoMap","displacementMap","alphaMap","clearcoatRoughnessMap","clearcoatNormalMap","transmissionMap","thicknessMap"]),Th=["color","emission","specular","sheenColor","specularColor","attenuationColor"];function Ky(r){let e=r;return e.transparent===!0||typeof e.opacity=="number"&&e.opacity<1||e.alphaMap!==void 0||typeof e.transmission=="number"&&e.transmission>0||e.color!==void 0&&Cl(e.color)<1}function $y(r,e){switch(e.type){case"basic":return new r.MeshBasicMaterial;case"standard":return new r.MeshStandardMaterial;case"physical":return new r.MeshPhysicalMaterial;case"phong":return new r.MeshPhongMaterial;case"lambert":return new r.MeshLambertMaterial;case"toon":return new r.MeshToonMaterial;case"normal":return new r.MeshNormalMaterial;case"depth":return new r.MeshDepthMaterial;case"matcap":return new r.MeshMatcapMaterial;case"points":return new r.PointsMaterial;case"lineBasic":return new r.LineBasicMaterial;case"lineDashed":return new r.LineDashedMaterial;case"sprite":return new r.SpriteMaterial;case"shadow":return new r.ShadowMaterial;case"shader":return Xy(r,e);default:return new r.MeshStandardMaterial}}function Xy(r,e){let t=e.raw?r.RawShaderMaterial:r.ShaderMaterial;return new t({vertexShader:e.vertex,fragmentShader:e.fragment,defines:e.defines,uniforms:{}})}function xr(r,e,t){let n=$y(r,e);return Yr(r,n,e,t,!0),n}function Yr(r,e,t,n,i=!1){let s=t,a=e,o;for(let l of Th){let u=s[l];if(u===void 0)continue;let d=Il[l]??l,h=a[d];if(h&&typeof h=="object"&&"setRGB"in h?St(r,h,u):a[d]=_l(r,u),l==="color"){let f=Cl(u);f<1&&(o=f)}}for(let l of Object.keys(s)){if(l==="type"||l==="params"||Th.includes(l)||Ml.includes(l)||l==="uniforms"||l==="vertex"||l==="fragment"||l==="defines"||l==="raw"||l==="extends"||!i&&vh.includes(l)||l==="transparent")continue;let u=s[l];if(u!==void 0)switch(l){case"faces":e.side=lh(r,u);break;case"shading":a.flatShading=u==="flat";break;case"blend":e.blending=uh(r,u);break;case"normalScale":Qy(r,a,u);break;case"rotation":a.rotation=He(u);break;case"iridescenceThicknessRange":a.iridescenceThicknessRange=[...u];break;case"width":a.linewidth=u;break;case"anisotropyRotation":a.anisotropyRotation=He(u);break;default:a[Il[l]??l]=u;break}}o!==void 0&&s.opacity===void 0&&(e.opacity=o);let c=Ky(t);!e.transparent&&c&&(e.transparent=!0,e.needsUpdate=!0),s.depthWrite===void 0&&(e.depthWrite=!c);for(let l of Ml){let u=s[l];u!==void 0&&(a[Il[l]??l]=n.resolve(u,jy.has(l)?"linear":"srgb"))}if(t.type==="shader"&&Yy(r,e,t.uniforms,n),t.params)for(let l of Object.keys(t.params))a[l]=t.params[l];i&&(e.needsUpdate=!0)}function Qy(r,e,t){let n=e.normalScale,i=typeof t=="number"?t:t.x,s=typeof t=="number"?t:t.y;n&&"set"in n?n.set(i,s):e.normalScale=new r.Vector2(i,s)}function Yy(r,e,t,n){if(t)for(let i of Object.keys(t)){let s=Zy(r,t[i],n),a=e.uniforms[i];a?a.value=s:e.uniforms[i]={value:s}}}function Zy(r,e,t){if(typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return Jy(e)?t.resolve(e,"srgb"):_l(r,e);if(Array.isArray(e)){let n=e;switch(n.length){case 2:return new r.Vector2(n[0],n[1]);case 3:return new r.Vector3(n[0],n[1],n[2]);case 4:return new r.Vector4(n[0],n[1],n[2],n[3]);default:return[...n]}}if(typeof e=="object"&&e!==null){let n=e;if("src"in n||"data"in n)return t.resolve(e,"srgb");if("w"in n)return new r.Vector4(n.x,n.y,n.z,n.w);if("z"in n)return new r.Vector3(n.x,n.y,n.z);if("y"in n)return new r.Vector2(n.x,n.y)}return e}function Jy(r){return r.startsWith("/")||r.startsWith(".")||/\.(png|jpe?g|webp|avif|svg|ktx2?|hdr|exr)$/i.test(r)}function Cn(r){let e=r,t=[r.type];for(let n of vh){let i=e[n];i!==void 0&&t.push(`${n}=${JSON.stringify(i)}`)}for(let n of Ml)e[n]!==void 0&&t.push(`+${n}`);return r.type==="shader"&&(t.push(`v=${Ah(r.vertex)}`,`f=${Ah(r.fragment)}`),r.uniforms&&t.push(`u=${Object.keys(r.uniforms).sort().join(",")}`)),r.params&&t.push(`params=${JSON.stringify(r.params)}`),t.join("|")}function Ah(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}import{resolveShadowOptions3D as _h,resolveVector3 as ew}from"@motionscript/core";var tw=4*Math.PI;function Ch(r,e){switch(e.type){case"ambient":return new r.AmbientLight;case"hemisphere":return new r.HemisphereLight;case"directional":return new r.DirectionalLight;case"point":return new r.PointLight;case"spot":return new r.SpotLight;case"area":return new r.RectAreaLight;default:return new r.AmbientLight}}function Ph(r,e,t){let n=t;if(t.type==="hemisphere"){let s=e;t.sky!==void 0&&St(r,s.color,t.sky),t.ground!==void 0&&St(r,s.groundColor,t.ground)}else n.color!==void 0&&St(r,e.color,n.color);if(n.intensity!==void 0){let s=t.type==="point"||t.type==="spot"?tw:1;e.intensity=n.intensity*s}let i=e;if(n.distance!==void 0&&(i.distance=n.distance),n.decay!==void 0&&(i.decay=n.decay),n.penumbra!==void 0&&(i.penumbra=n.penumbra),n.angle!==void 0&&(i.angle=He(n.angle)),n.width!==void 0&&(i.width=n.width),n.height!==void 0&&(i.height=n.height),t.params)for(let s of Object.keys(t.params))i[s]=t.params[s]}function Eh(r,e,t){let n=t;if(!("target"in e))return;let i=e.target;if(n.target===void 0){i.parent===e&&(e.remove(i),i.position.set(0,0,0),i.updateMatrixWorld());return}let s=ew(n.target);i.parent||e.add(i),e.updateWorldMatrix(!0,!1),i.position.copy(e.worldToLocal(new r.Vector3(s.x,s.y,s.z))),i.updateMatrixWorld()}function Ih(r,e,t){if(!("shadow"in r)||!r.shadow)return;let n=e.shadow,i=n===void 0?null:_h(n);if(r.castShadow=i!==null,!i)return;let s=r.shadow,a=s.camera;s.radius=1+(i.softness??.5)*8;let o=i.extent??rw(t),c=!1;e.type==="directional"&&a.left!==-o&&(a.left=-o,a.right=o,a.top=o,a.bottom=-o,c=!0);let l=Math.max(.05,o*.05),u=Math.max(l+1,o*8);a.near!==l&&(a.near=l,c=!0),a.far!==u&&(a.far=u,c=!0),c&&a.updateProjectionMatrix();let d=s.mapSize.x||2048;if(s.bias=-(u-l)/(d*512),s.normalBias=o*.01,i.params){let h=s;for(let f of Object.keys(i.params))h[f]=i.params[f]}}function rw(r){if(!r)return 10;let e=Math.max(r.max.x-r.min.x,r.max.y-r.min.y,r.max.z-r.min.z);return Math.max(1,e*.75)}function Mh(r){let e=r.shadow,t=e!==void 0&&_h(e)!==null,n=[r.type];return t&&n.push("shadow"),r.params&&n.push(`params=${JSON.stringify(r.params)}`),n.join("|")}import{resolveCameraPlacement as aw}from"@motionscript/core";import{resolveVector3 as qa,shadowCasts as nw,shadowReceives as iw}from"@motionscript/core";function ai(r,e){if(!e){r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),r.visible=!0,Fh(r,void 0);return}if(e.position!==void 0){let t=qa(e.position);r.position.set(t.x,t.y,t.z)}else r.position.set(0,0,0);if(e.scale!==void 0){let t=qa(e.scale);r.scale.set(t.x,t.y,t.z)}else r.scale.set(1,1,1);if(e.lookAt!==void 0){let t=qa(e.lookAt);r.lookAt(t.x,t.y,t.z)}else if(e.quaternion!==void 0){let t=e.quaternion;r.quaternion.set(t.x,t.y,t.z,t.w)}else e.rotation!==void 0?sw(r,e.rotation):r.rotation.set(0,0,0);r.visible=e.visible!==!1,Fh(r,e.shadow),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder)}function Fh(r,e){r.isLight||(r.castShadow=nw(e),r.receiveShadow=iw(e))}function sw(r,e){let t=qa(e),n=e?.order;r.rotation.set(He(t.x),He(t.y),He(t.z),n??"XYZ")}function Rh(r,e,t){return t.type==="perspective"?e instanceof r.PerspectiveCamera:e instanceof r.OrthographicCamera}function Fl(r,e){return e?.type==="orthographic"?new r.OrthographicCamera:new r.PerspectiveCamera}function Bh(r,e,t,n,i,s){let a=i>0?n/i:1;if(!t){let u=e;u.fov=50,u.near=.1,u.far=1e3,u.aspect!==a&&(u.aspect=a),u.position.set(0,0,5),u.lookAt(0,0,0),u.updateProjectionMatrix();return}let o=ow(t,s),c=!1;if(t.type==="perspective"){let u=e,d=t.fov??50,h=t.zoom??1;u.fov!==d&&(u.fov=d,c=!0),u.near!==o.near&&(u.near=o.near,c=!0),u.far!==o.far&&(u.far=o.far,c=!0),u.aspect!==a&&(u.aspect=a,c=!0),u.zoom!==h&&(u.zoom=h,c=!0)}else{let u=e,d=t.zoom??1,h=(t.frustumHeight??10)/2,f=-h*a,p=h*a;u.left!==f&&(u.left=f,c=!0),u.right!==p&&(u.right=p,c=!0),u.top!==h&&(u.top=h,c=!0),u.bottom!==-h&&(u.bottom=-h,c=!0),u.near!==o.near&&(u.near=o.near,c=!0),u.far!==o.far&&(u.far=o.far,c=!0),u.zoom!==d&&(u.zoom=d,c=!0)}let l=aw(t);if(ai(e,{...t,position:l.position,lookAt:l.lookAt}),t.params){let u=e;for(let d of Object.keys(t.params))u[d]=t.params[d];c=!0}c&&e.updateProjectionMatrix()}function ow(r,e){if(r.near!==void 0&&r.far!==void 0)return{near:r.near,far:r.far};let t=e?Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z):10,n=r.distance??Math.max(t,1)*2,i=Math.max(t,n,1);return{near:r.near??Math.max(.01,i/1e3),far:r.far??i*10}}import{resolveVector3 as cw}from"@motionscript/core";function Dh(r,e,t){if(!t){e.fog=null;return}if(t.density!==void 0){let s=t.density;if(e.fog instanceof r.FogExp2){t.color!==void 0&&St(r,e.fog.color,t.color),e.fog.density=s;return}e.fog=new r.FogExp2(0,s),t.color!==void 0&&St(r,e.fog.color,t.color);return}let n=t.near??1,i=t.far??1e3;if(e.fog instanceof r.Fog){t.color!==void 0&&St(r,e.fog.color,t.color),e.fog.near=n,e.fog.far=i;return}e.fog=new r.Fog(0,n,i),t.color!==void 0&&St(r,e.fog.color,t.color)}function Oh(r,e,t,n){if(!t){Ga(e),e.environment=null,e.background=null;return}let i=lw(r,e,t,n);if(!i){e.background=null;return}if(e.environment=i,e.environmentIntensity=t.intensity??1,t.rotation!==void 0&&"environmentRotation"in e){let{x:s,y:a,z:o}=cw(t.rotation);e.environmentRotation.set(He(s),He(a),He(o))}t.background?(e.background=i,e.backgroundBlurriness=t.blur??0,e.backgroundIntensity=t.intensity??1):e.background=null}function Ga(r){r.userData.__roomEnvironment?.texture.dispose(),r.userData.__roomEnvironment=void 0}function lw(r,e,t,n){if(t.preset===void 0||!n)return null;let i=e.userData.__roomEnvironment;if(i?.renderer===n)return i.texture;Ga(e);let s=new r.PMREMGenerator(n),a=new r.Scene;a.background=new r.Color(12303291);let o=s.fromScene(a,.04);return s.dispose(),e.userData.__roomEnvironment={renderer:n,texture:o.texture},o.texture}function Uh(r){return vn(r)?.clone()??null}function Nh(r){return vn(r)!==null}function zh(r,e,t,n,i){let s=vn(t)?.animations??[];if(s.length===0)return i;if(!n||n.length===0){if(i)for(let o of i.actions.values())o.enabled=!1;return i}let a=i??{mixer:new r.AnimationMixer(e),actions:new Map};for(let o of a.actions.values())o.enabled=!1;for(let o of n){let c=dw(s,o.clip);if(!c)continue;let l=a.actions.get(c.name);l||(l=a.mixer.clipAction(c),a.actions.set(c.name,l)),l.enabled=!0,l.setEffectiveWeight(o.weight??1),l.play(),l.paused=!0,l.time=hw(o.time,c.duration)}return a.mixer.update(0),a}var Lh=new WeakMap;function Vh(r,e,t,n){t&&e.traverse(i=>{let s=i;if(!s.isMesh)return;let a=Array.isArray(s.material)?s.material:[s.material],o=!1,c=a.map(l=>{let u=l?Lh.get(l):void 0;if(u!==void 0&&t[u]!==void 0)return Yr(r,l,t[u],n),l;let d=uw(t,s.name,l?.name);if(d===null)return l;let h=xr(r,t[d],n);return Lh.set(h,d),o=!0,h});o&&(s.material=Array.isArray(s.material)?c:c[0])})}function Hh(r){return r?Object.keys(r).sort().map(e=>`${e}=${JSON.stringify(r[e])}`).join("&"):""}function uw(r,e,t){return r[e]!==void 0?e:t!==void 0&&r[t]!==void 0?t:null}function dw(r,e){return e===void 0?r[0]:typeof e=="number"?r[e]:r.find(t=>t.name===e)}function hw(r,e){if(!Number.isFinite(r)||e<=0)return 0;let t=r%e;return t<0?t+e:t}var ja=class{three;scene;camera;cache=new Map;frame=0;constructor(e){this.three=e,this.scene=new e.Scene,this.camera=Fl(e,null)}sync(e,t,n,i,s=null){this.frame++;let a=this.three,o=[-1],c=[this.scene],l=[""],u=new Map,d=[],h=null,f=!1;for(let b of e.ops()){if(b.kind==="pop"){c.length>1&&(c.pop(),o.pop(),l.pop());continue}o[o.length-1]++;let k=l[l.length-1],T=c[c.length-1];if(b.kind==="push"){let M=k?`${k}.${o[o.length-1]}`:String(o[o.length-1]),C=this.resolveGroup(M,b.transform,T);c.push(C),o.push(-1),l.push(b.transform?.key?`@${b.transform.key}`:M);continue}if(b.kind==="camera"){h={descriptor:b.camera,parent:T},f=!0;continue}let x=pw(b),v=this.resolveDrawable(b,mw(k,b,x,u),T,i,x);v&&b.kind==="light"&&d.push({light:v.object,descriptor:b.light})}this.sweep();let p=this.sceneBounds();for(let{light:b,descriptor:k}of d)Eh(a,b,k),Ih(b,k,p);h&&this.resolveCamera(h.descriptor,t,n,h.parent,p),Dh(a,this.scene,e.fogDescriptor()),Oh(a,this.scene,e.environmentDescriptor(),s?.active()??null);let m=e.shadowSettings(),g=e.toneSettings(),y=mh(a,m?.quality);s?.applySettings(a,{shadowsEnabled:m?.enabled===!0,shadowType:y.type,toneMapping:ph(a,g?.mapping),toneMappingExposure:g?.exposure??1});for(let{light:b}of d){let k=b.shadow;k&&k.mapSize.x!==y.mapSize&&(k.mapSize.set(y.mapSize,y.mapSize),k.map?.dispose(),k.map=null)}return f||this.resolveCamera(null,t,n,this.scene,p),{scene:this.scene,camera:this.camera}}sceneBounds(){this.scene.updateMatrixWorld(!0);let e=new this.three.Box3().setFromObject(this.scene);return e.isEmpty()?null:{min:{x:e.min.x,y:e.min.y,z:e.min.z},max:{x:e.max.x,y:e.max.y,z:e.max.z}}}resolveGroup(e,t,n){let i=t?.key?`@${t.key}|push`:`${e}|push`,s=this.cache.get(i);return(!s||s.kind!=="push")&&(this.discard(s),s={object:new this.three.Group,kind:"push",seen:this.frame},this.cache.set(i,s)),s.seen=this.frame,ai(s.object,t),s.object.parent!==n&&n.add(s.object),s.object}resolveDrawable(e,t,n,i,s){let a=this.cache.get(t);if(a&&a.kind!==e.kind&&(this.discard(a),a=void 0),a=this.ensure(a,t,e,i,s),!!a)return a.seen=this.frame,this.mutate(a,e,i),a.object.parent!==n&&n.add(a.object),a}ensure(e,t,n,i,s){if(e&&yw(e,s))return e;this.discard(e);let a=this.build(n,i);if(!a)return;let o={object:a,kind:n.kind,seen:this.frame,...s},c=n.geometry;return c?.type==="parametric"&&(o.parametricRevision=c.revision),this.cache.set(t,o),o}build(e,t){let n=this.three;switch(e.kind){case"mesh":{let i=Qr(n,e.geometry),s=this.buildMaterials(e.material,t);return new n.Mesh(i,s)}case"light":return Ch(n,e.light);case"instances":{let i=Qr(n,e.geometry),s=xr(n,e.material,t),a=new n.InstancedMesh(i,s,Math.max(1,e.instances.length));return a.instanceMatrix.setUsage(n.DynamicDrawUsage),a}case"points":{let i=Qr(n,e.geometry),s=xr(n,e.material,t);return new n.Points(i,s)}case"line":{let i=Qr(n,e.geometry),s=xr(n,e.material,t),a=e.mode==="segments"?new n.LineSegments(i,s):e.mode==="loop"?new n.LineLoop(i,s):new n.Line(i,s);return e.material.type==="lineDashed"&&a.computeLineDistances(),a}case"sprite":{let i=xr(n,e.material,t);return new n.Sprite(i)}case"model":{let i=Uh(e.src);return i||ah(fw("gltf",e.src),"gltf"),i}default:return null}}buildMaterials(e,t){return Array.isArray(e)?e.map(n=>xr(this.three,n,t)):xr(this.three,e,t)}mutate(e,t,n){let i=this.three;switch(ai(e.object,t.transform),t.kind){case"mesh":case"points":case"line":{let s=e.object;this.refreshDynamicGeometry(s,t.geometry,e),this.applyMaterials(s.material,(t.kind==="mesh",t.material),n);break}case"instances":{let s=e.object;this.refreshDynamicGeometry(s,t.geometry,e),Yr(i,s.material,t.material,n),this.writeInstances(s,t.instances,t.colors);break}case"sprite":Yr(i,e.object.material,t.material,n);break;case"light":Ph(i,e.object,t.light);break;case"model":e.modelPlayback=zh(i,e.object,t.src,t.animation,e.modelPlayback),Vh(i,e.object,t.override,n);break}}applyMaterials(e,t,n){if(Array.isArray(e)&&Array.isArray(t)){let i=Math.min(e.length,t.length);for(let s=0;s<i;s++)Yr(this.three,e[s],t[s],n);return}!Array.isArray(e)&&!Array.isArray(t)&&Yr(this.three,e,t,n)}refreshDynamicGeometry(e,t,n){if(!Sh(t))return;if(t.type==="parametric"&&t.revision!==void 0){if(n.parametricRevision===t.revision)return;n.parametricRevision=t.revision}let i=xh(t);kh(e.geometry,i)||(e.geometry.dispose(),e.geometry=Qr(this.three,i),n.geometrySig=_n(t),e.computeLineDistances&&e.isLine&&e.computeLineDistances())}writeInstances(e,t,n){let i=this.three,s=e.userData.__scratch??(e.userData.__scratch=new i.Object3D),a=Math.min(t.length,e.count);for(let o=0;o<a;o++)ai(s,t[o]),s.updateMatrix(),e.setMatrixAt(o,s.matrix);if(e.instanceMatrix.needsUpdate=!0,a<e.count){s.position.set(0,0,0),s.rotation.set(0,0,0),s.scale.set(0,0,0),s.updateMatrix();for(let o=a;o<e.count;o++)e.setMatrixAt(o,s.matrix)}if(n){let o=new i.Color;for(let c=0;c<Math.min(n.length,e.count);c++)St(i,o,n[c]),e.setColorAt(c,o);e.instanceColor&&(e.instanceColor.needsUpdate=!0)}}resolveCamera(e,t,n,i,s){let a=this.three;e&&!Rh(a,this.camera,e)&&(this.camera=Fl(a,e)),Bh(a,this.camera,e,t,n,s),i!==this.scene?this.camera.parent!==i&&i.add(this.camera):this.camera.parent&&this.camera.removeFromParent()}sweep(){for(let[e,t]of this.cache)t.seen!==this.frame&&(this.discard(t),this.cache.delete(e))}discard(e){e&&(e.object.removeFromParent(),Wh(e.object))}dispose(){for(let e of this.cache.values())this.discard(e);this.cache.clear(),Ga(this.scene),this.scene.environment=null,this.scene.clear()}};function mw(r,e,t,n){let i=`${r}|${e.kind}|${t.geometrySig??""}|${t.materialSig??""}|${t.lightSig??""}|${t.count??""}`,s=n.get(i)??0;return n.set(i,s+1),`${i}#${s}`}function pw(r){switch(r.kind){case"mesh":return{geometrySig:_n(r.geometry),materialSig:gw(r.material)};case"points":return{geometrySig:_n(r.geometry),materialSig:Cn(r.material)};case"line":return{geometrySig:_n(r.geometry),materialSig:`${r.mode}|${Cn(r.material)}`};case"instances":return{geometrySig:_n(r.geometry),materialSig:Cn(r.material),count:r.instances.length};case"sprite":return{materialSig:Cn(r.material)};case"light":return{lightSig:Mh(r.light)};case"model":return{geometrySig:`${r.src}|${Nh(r.src)?"1":"0"}`,materialSig:Hh(r.override)};default:return{}}}function gw(r){return Array.isArray(r)?r.map(Cn).join("&"):Cn(r)}function yw(r,e){return r.geometrySig===e.geometrySig&&r.materialSig===e.materialSig&&r.lightSig===e.lightSig&&r.count===e.count}function Wh(r){let e=r;e.geometry?.dispose?.();let t=e.material;if(Array.isArray(t))for(let n of t)n.dispose();else t?.dispose?.();for(let n of[...r.children])Wh(n)}var qh=null;function Rl(r){qh=r}function vs(){return qh}import{isDataTexture3D as $h,isSurfaceTexture3D as Xh,resolveTexture3D as ww}from"@motionscript/core";var zt=new Map,Dl=new Map,Pn=0,oi=new Map,Ka=class{three;assets;surfaceOwner="";rasters;constructor(e,t){this.three=e,this.assets=t}beginFrame(){Pn++}setRasters(e,t){this.surfaceOwner=e,this.rasters=t}resolve(e,t){let n=ww(e),i=bw(e,t,this.surfaceOwner);if(Xh(n)){let o=this.rasters?.get(n);if(!o)return null;let c=zt.get(i);if(c?.resolved)return c.raster!==o&&(this.uploadRaster(c.texture,o),c.raster=o),oi.set(i,Pn),c.texture;let l=this.createRasterTexture(o);return this.applySampler(l,e,t),zt.set(i,{texture:l,resolved:!0,raster:o}),this.touchData(i),l}if(!$h(n))return this.resolveImage(n.src,e,t,i);let s=zt.get(i);if(s?.resolved)return s.revision!==n.revision&&(this.uploadData(s.texture,n),s.revision=n.revision),oi.set(i,Pn),s.texture;let a=this.createDataTexture(n);return this.applySampler(a,e,t),zt.set(i,{texture:a,revision:n.revision,resolved:!0}),this.touchData(i),a}touchData(e){oi.set(e,Pn);for(let[t,n]of oi)n>=Pn-1||(zt.get(t)?.texture.dispose(),zt.delete(t),oi.delete(t))}resolveImage(e,t,n,i){let s=this.assets.getImagePixels(e);if(!s)return null;let a=`${i}|px=${s.width}x${s.height}`,o=zt.get(a);if(o?.resolved){if(o.pixels!==s){let c=o.texture.image;c.data=s.pixels,o.texture.needsUpdate=!0,o.pixels=s}}else{let c=this.createImageTexture(s);this.applySampler(c,t,n),o={texture:c,resolved:!0,pixels:s},zt.set(a,o)}return this.touchLevel(i,a),o.texture}touchLevel(e,t){let n=Dl.get(e);n||Dl.set(e,n=new Map),n.set(t,Pn);for(let[i,s]of n)s>=Pn-1||(zt.get(i)?.texture.dispose(),zt.delete(i),n.delete(i))}createImageTexture(e){let t=new this.three.DataTexture(e.pixels,e.width,e.height,this.three.RGBAFormat,this.three.UnsignedByteType);return t.flipY=!0,t.needsUpdate=!0,t}createRasterTexture(e){let t=new this.three.DataTexture(e.pixels,e.width,e.height,this.three.RGBAFormat,this.three.UnsignedByteType);return t.flipY=!0,t.needsUpdate=!0,t}uploadRaster(e,t){let n=e.image;n.width===t.width&&n.height===t.height?n.data.set(t.pixels):(n.data=t.pixels,n.width=t.width,n.height=t.height),e.needsUpdate=!0}createDataTexture(e){let t=new this.three.DataTexture(Kh(e.data),e.width,e.height,this.three.RGBAFormat,this.three.UnsignedByteType);return t.needsUpdate=!0,t}uploadData(e,t){let n=e.image,i=Kh(t.data);n.data.length===i.length?n.data.set(i):n.data=i,e.needsUpdate=!0}applySampler(e,t,n){let i=this.three,s=typeof t=="string"?{}:t;if(e.wrapS=vl(i,s.wrapS),e.wrapT=vl(i,s.wrapT),e.magFilter=dh(i,s.magFilter),e.minFilter=hh(i,s.minFilter),e.colorSpace=fh(i,s.colorSpace??n),s.repeat){let[a,o]=Bl(s.repeat);e.repeat.set(a,o)}if(s.offset){let[a,o]=Bl(s.offset);e.offset.set(a,o)}if(s.center){let[a,o]=Bl(s.center);e.center.set(a,o)}s.rotation!==void 0&&(e.rotation=He(s.rotation)),s.anisotropy!==void 0&&(e.anisotropy=s.anisotropy),s.flipY!==void 0&&(e.flipY=s.flipY),e.generateMipmaps=e.minFilter!==i.NearestFilter&&e.minFilter!==i.LinearFilter}};function bw(r,e,t){if(typeof r=="string")return`${r}|${e}`;let n=r,i=[];for(let s of Object.keys(n).sort())s==="data"||s==="revision"||s!=="source"&&i.push(`${s}=${JSON.stringify(n[s])}`);return $h(r)&&i.push(`data=${r.width}x${r.height}#${xw(r.data)}`),Xh(r)&&i.push(`owner=${t}`,`sfc=${Tw(r)}`),i.push(`cs=${e}`),i.join("|")}var Gh=new WeakMap,kw=0,jh=new WeakMap,Sw=0;function xw(r){let e=jh.get(r);return e===void 0&&(e=`d${Sw++}`,jh.set(r,e)),e}function Tw(r){if(r.identity!==void 0)return r.identity;let e=r.source,t=Gh.get(e);return t===void 0&&(t=`s${kw++}`,Gh.set(e,t)),t}function Bl(r){return Array.isArray(r)?[r[0],r[1]]:[r.x,r.y]}function Kh(r){return r instanceof Uint8Array?r:new Uint8Array(Array.from(r))}function Qh(){for(let r of zt.values())r.texture.dispose();zt.clear(),Dl.clear(),oi.clear()}var _s=class{three;assets;host;graphs=new Map;textures;frame=0;touched=new Set;constructor(e,t,n){this.three=e,this.assets=t,this.host=n,this.textures=new Ka(e,t)}get frameIndex(){return this.frame}render(e,t,n,i,s={}){let a=this.graphs.get(e);a||(a=new ja(this.three),this.graphs.set(e,a)),this.touched.add(e),this.textures.setRasters(e,s.rasters),this.host.prepare(this.three,s);let{scene:o,camera:c}=a.sync(t,n,i,this.textures,this.host);return this.host.render(this.three,e,o,c,n,i,s)}beginFrame(){this.frame++,this.touched.clear(),this.textures.beginFrame()}sweep(){for(let[e,t]of this.graphs)this.touched.has(e)||(this.release(e,t),this.graphs.delete(e))}dispose(){for(let[e,t]of this.graphs)this.release(e,t);this.graphs.clear(),this.touched.clear()}release(e,t){t.dispose(),this.host.forgetBuffer(e),this.assets.release3DTexture(e)}get module(){return this.three}},$a=null;function ci(r){let e=kl();if(!e)return null;let t=vs();return t?($a??=new _s(e,r,t),$a):null}function Xa(){$a?.dispose(),$a=null}import{forEachTexture3D as eS,isSurfaceTexture3D as tS}from"@motionscript/core";function Qa(r){return 1/Math.max(r.getDeviceScale(),1e-4)}function Ya(r,e){return e.opacityRealised?1:r.opacity??1}var qe=class{dispose(){}};import{AssetNotLoadedError as Kk,isPixelFilter as $k}from"@motionscript/core";var Aw=[224,224,224],vw=[200,200,200],Cs=null;function _w(r){let t=new Uint8Array(4096);for(let n=0;n<32;n++)for(let i=0;i<32;i++){let s=i<16==n<16,[a,o,c]=s?Aw:vw,l=(n*32+i)*4;t[l]=a,t[l+1]=o,t[l+2]=c,t[l+3]=255}return r.MakeImage({width:32,height:32,alphaType:r.AlphaType.Unpremul,colorType:r.ColorType.RGBA_8888,colorSpace:r.ColorSpace.SRGB},t,128)}function Za(r){let e=r.canvasKit;if(Cs??=_w(e),!Cs)return!1;let t=r.getShapeBounds(),n=t?.left??0,i=t?.top??0,s=Cs.makeShaderOptions(e.TileMode.Repeat,e.TileMode.Repeat,e.FilterMode.Nearest,e.MipmapMode.None,[1,0,n,0,1,i,0,0,1]);return r.paint.setShader(s),r.transientPaintObjects.push(s),!0}function Yh(){Cs?.delete(),Cs=null}import{effectSurface as Hk}from"@motionscript/core";var Zh={type:"blur",makeImageFilter(r,e){let t=r.radius/2;return e.ImageFilter.MakeBlur(t,t,e.TileMode.Decal,null)}};var Jh={type:"directionalBlur",makeImageFilter(r,e){if(r.radius<=0)return null;let t=r.radius/2,n=r.angle*Math.PI/180,i=Math.cos(n),s=Math.sin(n),a={filter:e.FilterMode.Linear},o=e.ImageFilter.MakeMatrixTransform([i,s,0,-s,i,0,0,0,1],a,null),c=e.ImageFilter.MakeBlur(t,0,e.TileMode.Decal,o);o.delete();let l=e.ImageFilter.MakeMatrixTransform([i,-s,0,s,i,0,0,0,1],a,c);return c.delete(),l}};var ef={type:"grayscale",makeImageFilter(r,e){let t=Math.max(0,Math.min(1,r.amount)),n=[1-t+t*.2126,t*.7152,t*.0722,0,0,t*.2126,1-t+t*.7152,t*.0722,0,0,t*.2126,t*.7152,1-t+t*.0722,0,0,0,0,0,1,0],i=e.ColorFilter.MakeMatrix(n),s=e.ImageFilter.MakeColorFilter(i,null);return i.delete(),s}};var tf={type:"pixelate",makeImageFilter(r,e,{width:t,height:n}){let i=Math.max(1,Math.min(t,r.blocks.x)),s=Math.max(1,Math.min(n,r.blocks.y)),a=t/i,o=n/s,c={filter:e.FilterMode.Nearest},l=r.sharpColors?{filter:e.FilterMode.Nearest}:{filter:e.FilterMode.Linear},u=-t/2,d=-n/2,h=e.ImageFilter.MakeMatrixTransform([1/a,0,-u/a,0,1/o,-d/o,0,0,1],c,null),f=e.ImageFilter.MakeMatrixTransform([a,0,u,0,o,d,0,0,1],l,h);return h.delete(),f}};var rf={type:"bloom",makeImageFilter(r,e){if(r.radius<=0||r.intensity<=0)return null;let t=Math.max(0,Math.min(1,r.threshold)),n=r.radius/2,i=t<1?1/(1-t):1,s=-t*i,a=[i,0,0,0,s,0,i,0,0,s,0,0,i,0,s,0,0,0,1,0],o=e.ColorFilter.MakeMatrix(a),c=e.ImageFilter.MakeColorFilter(o,null);o.delete();let l=e.ImageFilter.MakeBlur(n,n,e.TileMode.Decal,c);c.delete();let u=l;if(r.intensity!==1){let h=r.intensity,f=[h,0,0,0,0,0,h,0,0,0,0,0,h,0,0,0,0,0,1,0],p=e.ColorFilter.MakeMatrix(f);u=e.ImageFilter.MakeColorFilter(p,l),p.delete(),l.delete()}let d=e.ImageFilter.MakeBlend(e.BlendMode.Screen,null,u);return u.delete(),d}};var nf={type:"vintage",makeImageFilter(r,e){if(r.amount<=0&&r.warmth===0)return null;let t=Math.max(0,Math.min(1,r.amount)),n=Math.max(-1,Math.min(1,r.warmth)),i=(m,g)=>m+(g-m)*t,s=[.393,.769,.189],a=[.349,.686,.168],o=[.272,.534,.131],c=n>0?n*.15:0,l=n<0?-n*.15:0,u=n<0?-n*.05:0,d=n>0?n*.05:0,h=[i(1,s[0]),i(0,s[1]),i(0,s[2]),0,c-u,i(0,a[0]),i(1,a[1]),i(0,a[2]),0,0,i(0,o[0]),i(0,o[1]),i(1,o[2]),0,-l+d,0,0,0,1,0],f=e.ColorFilter.MakeMatrix(h),p=e.ImageFilter.MakeColorFilter(f,null);return f.delete(),p}};var sf={type:"chromaticAberration",makeImageFilter(r,e){if(r.amount<=0)return null;let t=r.angle*Math.PI/180,n=Math.cos(t)*r.amount,i=Math.sin(t)*r.amount,s=[1.4,-.2,-.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],a=e.ColorFilter.MakeMatrix(s),o=e.ImageFilter.MakeOffset(n,i,null),c=e.ImageFilter.MakeColorFilter(a,o);a.delete(),o.delete();let l=[0,0,0,0,0,0,0,0,0,0,-.2,-.2,1.4,0,0,0,0,0,1,0],u=e.ColorFilter.MakeMatrix(l),d=e.ImageFilter.MakeOffset(-n,-i,null),h=e.ImageFilter.MakeColorFilter(u,d);u.delete(),d.delete();let f=e.ImageFilter.MakeBlend(e.BlendMode.Screen,null,c);c.delete();let p=e.ImageFilter.MakeBlend(e.BlendMode.Screen,f,h);return f.delete(),h.delete(),p}};var Cw=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],li=.2126,ui=.7152,di=.0722;function Pw(r){switch(r){case"red":return[-1,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];case"green":return[1,0,0,0,0,0,-1,0,0,1,0,0,1,0,0,0,0,0,1,0];case"blue":return[1,0,0,0,0,0,1,0,0,0,0,0,-1,0,1,0,0,0,1,0];case"alpha":return[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,-1,1];case"hue":return[2*li-1,2*ui,2*di,0,0,2*li,2*ui-1,2*di,0,0,2*li,2*ui,2*di-1,0,0,0,0,0,1,0];case"luminance":return[1-2*li,-2*ui,-2*di,0,1,-2*li,1-2*ui,-2*di,0,1,-2*li,-2*ui,1-2*di,0,1,0,0,0,1,0];default:return[-1,0,0,0,1,0,-1,0,0,1,0,0,-1,0,1,0,0,0,1,0]}}var af={type:"invert",makeImageFilter(r,e){let t=Math.max(0,Math.min(1,r.strength));if(t===0)return null;let n=Pw(r.channel),i=Cw.map((o,c)=>o+(n[c]-o)*t),s=e.ColorFilter.MakeMatrix(i),a=e.ImageFilter.MakeColorFilter(s,null);return s.delete(),a}};var hi=new Map,Ew=64,Ol=!1;function ue(r,e){let t=hi.get(r);if(t)return t;let n=e.RuntimeEffect.Make(r,i=>{console.warn("[SkSL] Compilation error:",i)});return n&&hi.set(r,n),hi.size>Ew&&!Ol&&(Ol=!0,console.warn(`[SkSL] ${hi.size} distinct shader sources have been compiled. If a shader's source is built per frame (e.g. a value interpolated into a template literal), keep the source constant and move what changes into a uniform \u2014 uniform values are an in-place write, a new source is a new program.`)),n??null}function of(){for(let r of hi.values())r.delete();hi.clear(),Ol=!1}import{resolveEffectAxis as Iw}from"@motionscript/core";function fi(r,e){return r.mode==="backdrop"?[0,0]:[e.centerX-e.width/2,e.centerY-e.height/2]}var Mw=`
|
|
696
696
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
697
697
|
uniform vec2 u_origin; // node box top-left, device px (0,0 on a backdrop)
|
|
698
698
|
uniform vec2 u_offset; // max displacement per axis, device px
|
|
@@ -709,7 +709,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
709
709
|
vec2 jitter = vec2(hash(cell, 0.0), hash(cell, 37.13)) * 2.0 - 1.0;
|
|
710
710
|
return u_content.eval(fragCoord + jitter * u_offset);
|
|
711
711
|
}
|
|
712
|
-
`;function
|
|
712
|
+
`;function Fw(r,e,t,n,i=[0,0]){if(!(r.strength>0))return null;let s=ue(Mw,e);if(!s)return null;let a=Iw(r.axis),o=r.strength*n;return s.makeShaderWithChildren([i[0],i[1],o*a.x,o*a.y],[t])}var cf={type:"scatter",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Fw(r,e,t,n.scale,fi(r,n))};import{resolveEffectAxis as Rw,resolveMotionBlurAlignment as Bw}from"@motionscript/core";var Dw=32,Ow=64;function lf(r,e,t){if(t<=0||r.strength<=0||r.length<=0)return null;let n=Rw(r.axis),i=r.length/100,s=e.x*t*n.x*i*r.strength,a=e.y*t*n.y*i*r.strength,o=Math.hypot(s,a);return o<.01?null:{type:"motionBlurResolved",angle:Math.atan2(a,s)*180/Math.PI,radius:o,phase:Bw(r.alignment),samples:r.samples}}var uf={type:"motionBlurResolved",makeImageFilter(r,e){if(r.radius<=0)return null;let t=r.angle*Math.PI/180,n=Math.cos(t),i=Math.sin(t),s=r.phase*r.radius/2,a=n*s,o=i*s,c=Math.min(Math.round(r.samples),Ow);return c>Dw?Uw(r,e,n,i,a,o,c):Lw(r,e,n,i,a,o)}};function Lw(r,e,t,n,i,s){let a=r.radius/2,o={filter:e.FilterMode.Linear},c=i!==0||s!==0?e.ImageFilter.MakeOffset(i,s,null):null,l=e.ImageFilter.MakeMatrixTransform([t,n,0,-n,t,0,0,0,1],o,c);c?.delete();let u=e.ImageFilter.MakeBlur(a,0,e.TileMode.Decal,l);l.delete();let d=e.ImageFilter.MakeMatrixTransform([t,-n,0,n,t,0,0,0,1],o,u);return u.delete(),d}function Uw(r,e,t,n,i,s,a){let o=r.radius/2,c=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1/a,0],l=e.ColorFilter.MakeMatrix(c),u=null;for(let d=0;d<a;d++){let h=a===1?0:d/(a-1)*2-1,f=t*o*h+i,p=n*o*h+s,m=e.ImageFilter.MakeOffset(f,p,null),g=e.ImageFilter.MakeColorFilter(l,m);if(m.delete(),u===null)u=g;else{let y=e.ImageFilter.MakeBlend(e.BlendMode.Plus,u,g);u.delete(),g.delete(),u=y}}return l.delete(),u}import{normalizeUniforms as Vw,writeUniforms as Hw}from"@motionscript/core";function Kt(r,e){switch(e){case"multiply":return r.BlendMode.Multiply;case"screen":return r.BlendMode.Screen;case"overlay":return r.BlendMode.Overlay;case"darken":return r.BlendMode.Darken;case"lighten":return r.BlendMode.Lighten;case"color-dodge":return r.BlendMode.ColorDodge;case"color-burn":return r.BlendMode.ColorBurn;case"hard-light":return r.BlendMode.HardLight;case"soft-light":return r.BlendMode.SoftLight;case"difference":return r.BlendMode.Difference;case"exclusion":return r.BlendMode.Exclusion;case"hue":return r.BlendMode.Hue;case"saturation":return r.BlendMode.Saturation;case"color":return r.BlendMode.Color;case"luminosity":return r.BlendMode.Luminosity;default:return r.BlendMode.SrcOver}}import{describeUniforms as Nw,parseShaderChildren as zw}from"@motionscript/core";var df=new WeakMap;function Ps(r,e){let t=df.get(r);if(t)return t;let n={slots:Nw(r),floats:r.getUniformFloatCount(),children:zw(e)};return df.set(r,n),n}var Ja=new Set;function Zr(r){Ja.has(r)||(Ja.size>512&&Ja.clear(),Ja.add(r),console.warn(`[SkSL] ${r}`))}var hf="u_backdrop";function Ww(r){let{width:e,height:t,centerX:n,centerY:i}=r;return{u_size:[e,t],u_resolution:[e,t],u_half:[e/2,t/2],u_center:[n,i],u_origin:[n-e/2,i-t/2],u_aspect:t===0?0:e/t,u_time:r.time,u_scale:r.scale}}var qw={};function ff(r,e,t){return Hw(r.slots,r.floats,Vw(e.uniforms),t,e.source)}function Gw(r,e){let t=[];for(let n of r.children){if(n.name===hf&&n.kind==="shader"){t.push(e);continue}return Zr(`a backdrop shader effect declares "${n.name}", which nothing supplies \u2014 an effect can only sample "${hf}".`),null}return t}var mf={type:"shader",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop"&&r.mode==="backdrop",makeShader(r,e,t,n){let i=ue(r.source,e);if(!i)return null;let s=Ps(i,r.source),a=ff(s,r,Ww(n)),o=Gw(s,t);if(!o)return null;let c=i.makeShaderWithChildren(a,o);return c||(Zr(`a backdrop shader effect's uniform buffer was rejected (${s.floats} floats, ${s.slots.length} uniform(s)).`),null)},makeImageFilter(r,e){if(r.mode==="backdrop")return null;let t=ue(r.source,e);if(!t)return null;let n=Ps(t,r.source);if(n.children.length>0)return Zr(`a foreground shader effect declares "${n.children[0].name}", but only a backdrop shader is given a child to sample \u2014 set mode: 'backdrop'.`),null;let i=t.makeShader(ff(n,r,qw));if(!i)return null;let s=e.ImageFilter.MakeShader(i);i.delete();let a=Kt(e,r.blendMode??"screen"),o=e.ImageFilter.MakeBlend(a,null,s);return s.delete(),o}};var Ul=new WeakMap,Nl=new Set;function jw(r,e){let t=Ul.get(r.table);if(t)return t.shader;let n=r.size;if(!Number.isInteger(n)||n<2)return null;let i=n*n,s=n,a=new Uint8Array(i*s*4);for(let u=0;u<n;u++)for(let d=0;d<n;d++)for(let h=0;h<n;h++){let f=((u*n+d)*n+h)*3;if(f+2>=r.table.length)continue;let p=(d*i+(u*n+h))*4;a[p]=Ll(r.table[f]),a[p+1]=Ll(r.table[f+1]),a[p+2]=Ll(r.table[f+2]),a[p+3]=255}let o=e.MakeImage({width:i,height:s,alphaType:e.AlphaType.Unpremul,colorType:e.ColorType.RGBA_8888,colorSpace:e.ColorSpace.SRGB},a,i*4);if(!o)return null;let c=o.makeShaderOptions(e.TileMode.Clamp,e.TileMode.Clamp,e.FilterMode.Linear,e.MipmapMode.None),l={image:o,shader:c};return Ul.set(r.table,l),Nl.add(l),c}function Ll(r){return Number.isFinite(r)?Math.max(0,Math.min(255,Math.round(r*255))):0}var Kw=`
|
|
713
713
|
uniform shader u_content;
|
|
714
714
|
uniform shader u_lut;
|
|
715
715
|
uniform float u_size;
|
|
@@ -743,7 +743,7 @@ vec4 main(vec2 p) {
|
|
|
743
743
|
vec3 graded = mix(rgb, lookup(rgb), clamp(u_amount, 0.0, 1.0));
|
|
744
744
|
return vec4(graded * src.a, src.a);
|
|
745
745
|
}
|
|
746
|
-
`,
|
|
746
|
+
`,pf={type:"lut",sampling:{tileMode:"clamp",filterMode:"linear"},resources(r,e){let t=jw(r,e);return t?[t]:null},makeShader(r,e,t,n,i){if(r.amount<=0)return null;let s=i?.[0];if(!s)return null;let a=ue(Kw,e);return a?a.makeShaderWithChildren([r.size,r.amount],[t,s]):null},dispose(){for(let{image:r,shader:e}of Nl)e.delete(),r.delete();Nl.clear(),Ul=new WeakMap}};var $w=`
|
|
747
747
|
uniform shader u_content; // snapshot of the source (node content, or backdrop)
|
|
748
748
|
uniform vec2 u_center; // node centre, device px
|
|
749
749
|
uniform vec2 u_half; // node half-extent (halfWidth, halfHeight), device px
|
|
@@ -758,7 +758,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
758
758
|
vec2 samplePos = u_center + distorted * u_half;
|
|
759
759
|
return u_content.eval(samplePos);
|
|
760
760
|
}
|
|
761
|
-
`;function
|
|
761
|
+
`;function Xw(r,e,t,n,i,s,a){let o=r.strength;if(o===0||s<=0||a<=0)return null;let c=s/2,l=a/2,u=ue($w,e);if(!u)return null;let d=n+(r.center.x-.5)*s,h=i+(r.center.y-.5)*a;return u.makeShaderWithChildren([d,h,c,l,o],[t])}var gf={type:"bulge",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Xw(r,e,t,n.centerX,n.centerY,n.width,n.height)};var Qw=`
|
|
762
762
|
uniform shader u_backdrop;
|
|
763
763
|
uniform vec2 u_center; // lens centre, device px
|
|
764
764
|
uniform float u_scale; // magnification factor (1 = none, 2 = 2x)
|
|
@@ -767,7 +767,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
767
767
|
vec2 samplePos = u_center + (fragCoord - u_center) / max(u_scale, 0.001);
|
|
768
768
|
return u_backdrop.eval(samplePos);
|
|
769
769
|
}
|
|
770
|
-
`;function
|
|
770
|
+
`;function Yw(r,e,t,n,i,s,a){let o=r.scale;if(o===1||o<=0||s<=0||a<=0)return null;let c=n+(r.center.x-.5)*s,l=i+(r.center.y-.5)*a,u=ue(Qw,e);return u?u.makeShaderWithChildren([c,l,o],[t]):null}var yf={type:"magnify",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop",makeShader:(r,e,t,n)=>Yw(r,e,t,n.centerX,n.centerY,n.width,n.height)};var Zw=`
|
|
771
771
|
uniform shader u_content; // snapshot of the node's own content (premultiplied)
|
|
772
772
|
uniform float u_level; // number of brightness bands per channel (>= 2)
|
|
773
773
|
|
|
@@ -782,7 +782,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
782
782
|
q = clamp(q, 0.0, 1.0);
|
|
783
783
|
return vec4(q * a, a); // re-premultiply
|
|
784
784
|
}
|
|
785
|
-
`;function
|
|
785
|
+
`;function Jw(r,e,t){if(r.levels<2)return null;let n=ue(Zw,e);return n?n.makeShaderWithChildren([r.levels],[t]):null}var wf={type:"posterize",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>Jw(r,e,t)};import{resolveEffectColor as eb}from"@motionscript/core";var zl=[12,16,24,32,40],tb=3;function rb(r){let e=2*Math.PI*r/tb;return zl.find(t=>t>=e)??zl[zl.length-1]}function nb(r,e){let t=r!=="inside",n=r!=="outside",i=r!=="outside",s=(2*Math.PI/e).toFixed(8);return`
|
|
786
786
|
uniform shader u_content; // snapshot of the node's own content (premultiplied)
|
|
787
787
|
${t?"uniform float u_radiusOut; // dilate distance, device px":""}
|
|
788
788
|
${n?"uniform float u_radiusIn; // erode distance, device px":""}
|
|
@@ -812,7 +812,7 @@ ${n?` eroded = min(eroded, u_content.eval(fragCoord + dir * u_radiusIn).a
|
|
|
812
812
|
vec4 bottom = ${i?"src":"band"};
|
|
813
813
|
return top + bottom * (1.0 - top.a);
|
|
814
814
|
}
|
|
815
|
-
`}function
|
|
815
|
+
`}function ib(r,e){switch(r){case"inside":return{out:0,in:e};case"center":return{out:e/2,in:e/2};default:return{out:e,in:0}}}function sb(r,e,t,n){let i=r.width*n,s=eb(r.color);if(!(i>0)||s[3]<=0)return null;let a=ib(r.position,i),o=nb(r.position,rb(Math.max(a.out,a.in))),c=ue(o,e);if(!c)return null;let l=r.position==="inside"?[a.in]:r.position==="center"?[a.out,a.in]:[a.out];return c.makeShaderWithChildren([...l,...s],[t])}var bf={type:"outline",sampling:{tileMode:"decal",filterMode:"linear"},handles:(r,e)=>e==="foreground",makeShader:(r,e,t,n)=>sb(r,e,t,n.scale)};import{resolveEffectColor as ab}from"@motionscript/core";var Vl=[2,3,4,6],Hl=12,ob=4;function cb(r){let e=r/ob;return Vl.find(t=>t>=e)??Vl[Vl.length-1]}function lb(r,e){let t=(2*Math.PI/Hl).toFixed(8),n=e?`
|
|
816
816
|
float silhouette(vec2 p) {
|
|
817
817
|
float a = u_content.eval(p).a;
|
|
818
818
|
for (int i = 0; i < ${Hl}; i++) {
|
|
@@ -863,7 +863,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
863
863
|
// Source-over of the content on top of its own shadow.
|
|
864
864
|
return src + shadow * (1.0 - src.a);
|
|
865
865
|
}
|
|
866
|
-
`}function
|
|
866
|
+
`}function ub(r,e,t,n){let i=ab(r.color);if(i[3]<=0)return null;let s=r.offsetX*n,a=-r.offsetY*n,o=Math.max(0,r.blur*n)/2,c=Math.max(0,r.spread*n);if(s===0&&a===0&&o===0&&c===0)return null;let l=lb(cb(o),c>0),u=ue(l,e);if(!u)return null;let d=[s,a,o,...i];return c>0&&d.push(c),u.makeShaderWithChildren(d,[t])}var kf={type:"dropShadow",sampling:{tileMode:"decal",filterMode:"linear"},handles:(r,e)=>e==="foreground",makeShader:(r,e,t,n)=>ub(r,e,t,n.scale)};import{resolveEffectColor as db}from"@motionscript/core";var hb=`
|
|
867
867
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
868
868
|
uniform vec2 u_center; // box centre, device px
|
|
869
869
|
uniform vec2 u_half; // box half-extent, device px
|
|
@@ -887,7 +887,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
887
887
|
vec3 tinted = mix(base, u_color.rgb, clamp(falloff, 0.0, 1.0));
|
|
888
888
|
return vec4(tinted * c.a, c.a); // re-premultiply
|
|
889
889
|
}
|
|
890
|
-
`;function
|
|
890
|
+
`;function fb(r,e,t,n){let i=db(r.color);if(r.amount<=0||i[3]<=0||n.width<=0||n.height<=0)return null;let s=ue(hb,e);return s?s.makeShaderWithChildren([n.centerX,n.centerY,n.width/2,n.height/2,i[0],i[1],i[2],i[3],r.amount,r.radius,r.softness],[t]):null}var Sf={type:"vignette",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>fb(r,e,t,n)};var mb=`
|
|
891
891
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
892
892
|
uniform vec2 u_origin; // node box top-left, device px (0,0 on a backdrop)
|
|
893
893
|
uniform float u_amount; // noise amplitude, 0\u20131
|
|
@@ -918,7 +918,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
918
918
|
vec3 grained = clamp(base + noise * u_amount, 0.0, 1.0);
|
|
919
919
|
return vec4(grained * c.a, c.a); // re-premultiply
|
|
920
920
|
}
|
|
921
|
-
`;function
|
|
921
|
+
`;function pb(r,e,t,n,i,s=[0,0]){if(!(r.amount>0))return null;let a=ue(mb,e);if(!a)return null;let o=r.animated?r.seed+Math.floor(i*1e3):r.seed;return a.makeShaderWithChildren([s[0],s[1],r.amount,Math.max(r.size*n,1),o,r.colored?1:0],[t])}var xf={type:"grain",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>pb(r,e,t,n.scale,n.time,fi(r,n))};var gb=`
|
|
922
922
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
923
923
|
uniform float u_amount; // edge-contrast boost
|
|
924
924
|
uniform float u_radius; // tap spacing, device px
|
|
@@ -944,7 +944,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
944
944
|
vec3 sharpened = clamp(base + (base - reference) * u_amount, 0.0, 1.0);
|
|
945
945
|
return vec4(sharpened * c.a, c.a);
|
|
946
946
|
}
|
|
947
|
-
`;function
|
|
947
|
+
`;function yb(r,e,t,n){if(r.amount===0)return null;let i=ue(gb,e);return i?i.makeShaderWithChildren([r.amount,Math.max(r.radius,0)*n],[t]):null}var Tf={type:"sharpen",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>yb(r,e,t,n.scale)};var wb={sobel:0,prewitt:1,laplacian:2},bb=`
|
|
948
948
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
949
949
|
uniform float u_strength; // magnitude multiplier
|
|
950
950
|
uniform float u_kernel; // 0 = sobel, 1 = prewitt, 2 = laplacian
|
|
@@ -980,7 +980,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
980
980
|
float a = max(c11.a, max(edge.r, max(edge.g, edge.b)));
|
|
981
981
|
return vec4(edge * a, a);
|
|
982
982
|
}
|
|
983
|
-
`;function
|
|
983
|
+
`;function kb(r,e,t,n){if(!(r.strength>0))return null;let i=ue(bb,e);return i?i.makeShaderWithChildren([r.strength,wb[r.kernel]??0,r.colored?1:0,n],[t]):null}var Af={type:"edges",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>kb(r,e,t,n.scale)};var Sb=`
|
|
984
984
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
985
985
|
uniform float u_level; // 0\u20131 cut point
|
|
986
986
|
uniform float u_smoothness; // 0\u20131 ramp width
|
|
@@ -1001,7 +1001,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1001
1001
|
|
|
1002
1002
|
return vec4(vec3(v) * c.a, c.a); // re-premultiply
|
|
1003
1003
|
}
|
|
1004
|
-
`;function
|
|
1004
|
+
`;function xb(r,e,t){let n=ue(Sb,e);return n?n.makeShaderWithChildren([r.level,r.smoothness],[t]):null}var vf={type:"threshold",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>xb(r,e,t)};var Tb=2,Ab=32;function vb(r){return`
|
|
1005
1005
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1006
1006
|
uniform vec2 u_center; // blur centre, device px
|
|
1007
1007
|
uniform float u_amount; // smear length, 0\u20131
|
|
@@ -1028,7 +1028,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1028
1028
|
|
|
1029
1029
|
return acc / ${r}.0;
|
|
1030
1030
|
}
|
|
1031
|
-
`}function
|
|
1031
|
+
`}function _b(r,e,t,n){if(!(r.amount>0)||n.width<=0||n.height<=0)return null;let i=Math.round(Math.max(Tb,Math.min(Ab,r.samples))),s=ue(vb(i),e);if(!s)return null;let a=n.centerX+(r.center.x-.5)*n.width,o=n.centerY+(r.center.y-.5)*n.height;return s.makeShaderWithChildren([a,o,r.amount,r.style==="spin"?1:0],[t])}var _f={type:"radialBlur",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>_b(r,e,t,n)};var Cb={dot:0,line:1,cross:2},Pb={mono:0,rgb:1,cmyk:2},Eb=`
|
|
1032
1032
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1033
1033
|
uniform vec2 u_center; // grid anchor, device px
|
|
1034
1034
|
uniform float u_size; // cell pitch, device px
|
|
@@ -1184,7 +1184,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1184
1184
|
|
|
1185
1185
|
return vec4(clamp(screened, 0.0, 1.0) * c.a, c.a); // re-premultiply
|
|
1186
1186
|
}
|
|
1187
|
-
`;function
|
|
1187
|
+
`;function Ib(r,e,t,n){let i=r.size*n.scale;if(!(i>=1))return null;let s=ue(Eb,e);return s?s.makeShaderWithChildren([n.centerX,n.centerY,i,r.angle*Math.PI/180,Cb[r.shape]??0,Pb[r.separation]??0],[t]):null}var Cf={type:"halftone",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Ib(r,e,t,n)};var Mb="e8yOVglJi3jaB+U3jl3KakXertJzm985bcTcngPJTPc8ddJT6mIl7ztdoQdH8wxyKr6F1wCTXqg8aZ50OCCKRakgO9+09jbERrJS0AzsM7J9JxY+6i5arBCOK3w3qXHAXOWPG4DYqhCT3HXpkSay25w//61F4y53670E4MOiZtlQ/51iK5hqGewpmmeAvRmQ516kirgCftDuUbn5YOcTLZ0ORqXDOHhRshw0VcBmglDGCV0he6MZyUyQLFmCDewWwG4DzYQO0qVdhv4gQqRT0gfB/2xP8p8+HWmaC0SRuOCAyP0rWwj4yGrxz6oV+jcc72+Wu9RU74cQ27LyR886kieB5Eu58D962ACryeNs+Dx0Sy8SyiRfvIvmJ8XXax1UOGKvct+YgyhCiQB7RZbVrYtG3jUMaz63cDplGZxxsGDuP6cadVkgvTBNcjgRliaEtZvggJfcdArTS3WrNIP4n9ADjBm5RugUuqBh58tuDl3nJaSB+MifJf+ojcgp+QrUFI/EL96wjPmZ4cCMYNnDC/EfWr40Ra/7MKQQ8VEItSl47lDWNWWn0Vj8Oh6jLbw+ewPATReSWwPUUg/mXYVMnm1T+mWbEEdsDFoe964yVaZHz24F9IkaWH7LXojamGPiP74jmfQFdC2TC8SGUduK9KnQYuZ3N+2+fzZ2rD3cvzC00waFO8nqKdGmekUFf+1rjzHonLZk4JlC6xe6I0PIFo9srVp/weNNfddoru8FZhlSMZcfttdrK5rqvSCVAnbnQ3wovORffbSJOee33Jkhyw6sfBZPKsgAsyyea/57qlb3Cc84Fa8hnfUYSSV4QcaR2XD3QaJTFbBKDF76zVaoG5r1qEwdoQJQ8hVfJ21Psz71Vtw90oZz6GGGTs43AtUtoEnhiP9FbMk5tJjou5v9LbQPhsgHfPvMhNxxRIIv8WEKN2rZj/42w26dzY7EFuVjhyi6ZvumHzy+9RSrjeZph8B2KKNh1I0LXd1wCTNaG35I6idh4pUjYjuiKK8TwI3P4onID1p0qyHgPwf/NXybAceiGJEJwkufDGrdJlW2Qx/yElXDAjGo8CiJTsuE3ahkzZirTbk02qwD9Y7T625MJndEsCvnQNORXLaFU6nZRflxN+x6MV7wgteWQHf2D57eXrGV6XffSnDDrhz4QsEU5zUBbvYSdUmIwk8XXTkForsY8GKfvxiACfYrb+kRZyu0WNhKzJjesSpZHLHKiWTBNIDWLUQetJYPPeRhoCZqk0+1hNg7ksrzGm7lfcWqh/xamdUFek7yY8RMotMjwIPOG44LsGsaRAFuwvlPBTHtF5NIBm31gstf+4GZA3q38Al1+x1YsSVioC+wPZwn30fOMbM+j+Eyl6053g6QPp5N6KV38yaf/X7Okjh6mtmndFLN+6nBmlIVNNIkVMjgTjKlz0HDnOt9C+JZ1Qj0ZRlyDIL3HVa8EdEfiWu7VnbxBGE2wkVivzJYqeAR6idgQOG5JXlcGznjr45xte07II/WXIkrbA9J1L1DkHa+UoW17MNj0HuoaP51VOku+hrXtiiL1RCW3QmM6hdLZ72LshyGDqE96YjVZALxRBOfZK9zDuwYqvKOMmmlJ/EWmCvYPJ0kSQI27CZGk8IBqXuYOGmo/nBP7Xk80G8oxqE9B/zQaOxW0gq8KH6gxVveegn3x0i4ft1QzLD9BoRjzkf9qhRWi67jlcaDDLU01V5Fyw/kQxm5LK0cpE23kPd/3Fd4Rp41iq9smFH/PR6HLr6TVTSfImY7AHUeV5njNa5xAWF9yfNxYBtQ26DlbIoi7LSMVn2Z0FuE2mXzBThdEi/Kqya+BPcgQusUs3DXqu1G1Bziif3Kmr2K5zDWScEg5oy74DIPQKC+dDpdGUv1owhtLdPsATzwDcAjmXjSnuJvkBnogVvXdsVfzTOUVAdlI3KtXXYNUyvzQWC4chSBWqE5Th2Us9so8Aez+Y3IL37fTZ8eumGxdJQ0WN9DuiFJtPBSask9lCykC4XkGfbDm4X6AM8wqNl/FqXODJKs9NIN7sxt+lh7SIrWLnqqDGS3OcL0c0SIJNZL+KyBFGr9hwA6nw2o5RK5+k1qrUd9Mdw8tk2N70G3W+RuJvpRLmpClSqBpjoG0BlqnFYe6kjZjxZdkg3L/aQQwm0Ey+szplzZxIX6Jk9nfzuZ3ie/Y6oMXMsXom0fkwfCSZ14vOEbs3TDVRfWjqzE/j250W+aJv130SmuVzdo5iqQP6BUjb8beSxIb7iQ0eofywKJ8RXnknTyLV/gx3r3MoveAj2CzFn+Aea3aelcgQ7aiAM1xlgJoT3vg+Eam4JXutkicQviTvWx1BXiNwdXrndfQJ9PzSRGp4G4DFE8q2kesFvupBCMNZxIhh1BLLVSJaRg9oKt42i9TQJrv9Q9+RZ68KzRKJppCY5bpHzElzP1vdotbYS14RnUN/6e2BXsxTfTbSlO161wJtyj9pVr7nfkQ7QZRy5/F9qUpyhTCK1jmks2ZoQ/6Kc08iFH/WwYS40OqfQGOmWWVG6MJWKBl1F8Epi/82Uc68ZUdQTIGjeXwRNy35HJ87BgM+564pHNLOgBvv2xD8hQfsxlsxHUouMlfblZksf5EMLsAK/HPgjgqPxHhwa1PYMQtDTZSuCxB0/SM6JiBlAjh8xIFbJpQ4DGX5EYVdtvJLoC3pAvf1rDZ+041CBKc6YoRnjkU/S2LGYgyTZ44pxM9JFgp4hYfPNmjf8dvOhxof4IvFv3Id4OqTHge6EzivqXPnVS6aw8AZZHEnib2jODt9KTNRuLdddMkuerXCXOayvWDP8izj+lKbh4Vz+IMNRAZ55/NoqeT/hxRCLrwkoVYOykDcci+XLepcH9XrME8VoRZtupWxCdwABsGPWMC7ehfENyuwrlGNdGAsfdpg26fRzsxA/Wb70alNa0Zgec17Ah0DeVVobNKVWIMBrib5Q96aAnvv5A4zB/01G8P91XG8foLZltkVp/oPCUJ2brWZfcK1OqQfEuXMUMiFL0ey5yU4T1br4RQrEK6mxAn0zEIbt5SIAYb69e+JoteaZp+TuMXa9MxST7uzNeFn21OxXJRXWSz2UCrX7jPKYnuUDlxQS1SBfcnfBmkdW2gM4N+4hYBvDHltEKjUQRx+gFJoK+CNIY9IKrQwtz58xL+4tw8aUJ+COF6ZdGIPxw2oQaomGT2CqqYTF8wiNNFvMqrmQ13aNoIjdW7ijbpWRLktirUO12njkDZsrdjK8rowXFJFUyv188uhjLZLOPVwDHS/sUOu10kP9RBN86pGKXVHrllhvOQa7jgbVrv30h+7U1bh2UKmHW7ZYuWB1Fbt1anOa2h+Kb23hSMeEL0C/vZ6+JcMtMCbshyY2ub+rJBtg7EcFRg/d2AqE/F1LkOogTWfHPROO8TyJ15qPB8ROHN3lGDWkfTAWx+qCIdEqlkzof2iydsFvZhELoVRKDMriK+KJvK7oTWccq/s+bBKvNc7+bBLJ7EqdCug06Y5XPsfUX06f6fNCQKmAWO/HCEuR2u1TqEHz2M2kXnSu9/ElxImBH0+iVOuCYaU6McPBiQ+EsTYZoMfWLZ/6I1nsCTi5nwJJZL7k77nLK3rdoKIVZ0weXZcVDHZK48HnYYJUY4bDMAIQfZbJ/HNS3EzK9JJYNqPcf38FWz6AXUKsl+KR/4SQ/6wqfXhKmQo8DU63/HadH9jCL4abVSgypPgDMplSRNO+nPvkKTO03efVI24DrVXjRkECYByneM8Bf3D+8Ww6vhG/LiOXEUyN37ZnZcDLBfRa1cQRfK3TIV/aHazjzDna+TnDLmsFipwaTsFwWrMkyZRFcruuDs3jpCXGOFdSX/1DaHUosef+y0S9BFU2O212f0E/9v4btH5kvu+Igg8ZfJI7dGTOHIdhVzCJzkUEA76C7/DVsSA6UQ57JMO9IczQEs2ScuAWVGGOJus2k6gQ87h80nRQ9sWLedxJSrkHaoOkIq1zjbP9BgeY4xv+5bIlLKXvIHtL0ZSP5Ua1qHsyj54s59tVAa+FK9Ah8YSZ4uZBjhNpX5Y8GR6vWj/9rF1E5wX5CsgSduhJpowlYLd8czuMGj6JUMbjXfQ+K37eBYCnGeg9bjMGpKp5V5zis+UwT4sRzqCNq+sgiYTUFmLaF92gq74rQWC6V8ErZeZlHp3RZr0DmdYkDoT7GLFgIQPMWVOCtIu02C3bKHJPXDWfOoUMqAUnTtjiAou19w+QvzQ6U1hNOIuh3wx6GsRTK7wrCM/JoEcRO6Vtw45n8qNWPv5w0a89/U9f7X7dGgMSYJXv2s5TueBOaVAvSQlcdYHZGtFefx22qQNxhMfZlJYFflx6K2CeqNs4hshI5dB9mL3MB/EahEbiUPoct7BhZPOYJVW01ylct88BtJ7KDnfOq4CH8fzXyFIkAodFEkbw41PpDu1F+/mSWgfZPwIfKSO6xWsONKvJkHq4C251x/b2IptjBEYKj24VF3ZD7D9E2AYo8agi2lFm8/E5/Ct+jUxGtdgHPmxSvCkKi2mEF5KER2IIc3XbJSeVzxmhPrA8sYz8dl0r8IGMEqBk4ZE25clS/06TlSiThNmqwKcVvHuqNZealOW7gx+95LxuTtzFYkic/qFUKOaeGMfgbNs1+3bL0eeNnszrOvHLtxqXhIpTuFnkqXsNzzoMb645c9EJ7zDAgWvYaSyRcuMxw8EV++2/I6Wn3vZPcDVubvY3yRJkBVirLCIvoUZYlWXsGhkTXY5xC848arAWdQdMPty6pBbhL25PAd4w/lAHmU6kMxRqxTgaXMHlQJLnrQ3UIYCNs0Ye6Rp8uehf4QtWeL/WtCy7NtgrYRftj51amck3Wkl7+noAIL6za/qZsOyGD2mScNonftR3T72Z+qyXK5KO/6zKlE/ld0appsoITu09oxXb6UoVno3cwix7CLPqDGOdzORXJaulRFH0p1bSb+EEl0/MTXn5IpAQ9zRBXlTJOEnxJ4WaBG+RIAN408m7mEDyRpho47CTLtEzba5IDxkCzIr9U8T6b0GPFS+5bE262jlVyujvK/W3EnOWL/GjUg/i2HJbFO7WRJ8aaTY8mqYXOI1/ZwJdXB/KaDrg+32edWYzZfKkghg2yH4wHgMIz6gOsH+mbCi2NGl4sSh67A6oob9VWBu5xUvx6XdELwlrdSvG0AXNE4oJiNnT3V6ww6g/1MwZnvE73OuKj0UWW1lB8z0SHZN2xU+u3c9yjeT7lX5w16IsppRG5Ohyl5HUyF6B5No38FafDGrDQIoATkM9xRKLK5jDVlXJSaDD5HGcpofsuxhVJetI5hBLFMfSQUMwKrne7QdJi24bvaEGK/LhoDuVQr2ctQN+KSaLpx0wmhbpYjhSAXgOu7hC8d6fkvhRclXCr9iOgAPmVUGMNviCG/kkbXPKCI5gIsCm9A5pHzYW/JNV+ypha7xBkMm22+AvYIf1Ks/LHLA==";var Fb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eo=null;function Pf(){if(eo)return eo;let r=Mb.replace(/[^A-Za-z0-9+/]/g,""),e=new Uint8Array(r.length*3>>2),t=0,n=0,i=0;for(let s=0;s<r.length;s++)t=t<<6|Fb.indexOf(r[s]),n+=6,n>=8&&(n-=8,e[i++]=t>>n&255);return eo=e.subarray(0,i),eo}function Rb(r,e){let t=r==="blue",n=t?`u_noise.eval(mod(cell, ${64}.0) + 0.5).r`:e===2?"bayer2(cell)":e===4?"bayer2(cell * 0.5) * 0.25 + bayer2(cell)":"(bayer2(cell * 0.25) * 0.25 + bayer2(cell * 0.5)) * 0.25 + bayer2(cell)";return`
|
|
1188
1188
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1189
1189
|
${t?`uniform shader u_noise; // 64x64 blue-noise thresholds, tiled
|
|
1190
1190
|
`:""}uniform vec2 u_origin; // node box top-left, device px (0,0 on a backdrop)
|
|
@@ -1214,7 +1214,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1214
1214
|
vec3 dithered = clamp(floor(base * steps + threshold) / steps, 0.0, 1.0);
|
|
1215
1215
|
return vec4(dithered * c.a, c.a); // re-premultiply
|
|
1216
1216
|
}
|
|
1217
|
-
`}var
|
|
1217
|
+
`}var ro=new WeakMap,Wl=new Set;function Bb(r){let e=ro.get(r);if(e!==void 0)return e?.shader??null;let t=Pf(),n=new Uint8Array(t.length*4);for(let o=0;o<t.length;o++){let c=t[o];n[o*4]=c,n[o*4+1]=c,n[o*4+2]=c,n[o*4+3]=255}let i=r.MakeImage({width:64,height:64,alphaType:r.AlphaType.Unpremul,colorType:r.ColorType.RGBA_8888,colorSpace:r.ColorSpace.SRGB},n,256);if(!i)return ro.set(r,null),null;let s=i.makeShaderOptions(r.TileMode.Repeat,r.TileMode.Repeat,r.FilterMode.Nearest,r.MipmapMode.None),a={image:i,shader:s};return ro.set(r,a),Wl.add(a),s}function Db(r,e,t,n,i=[0,0]){if(r.levels>=256)return null;let s=r.noise==="blue"?Bb(e):null,a=r.noise==="blue"&&s?"blue":"bayer",o=ue(Rb(a,r.matrix),e);if(!o)return null;let c=a==="blue"?[t,s]:[t];return o.makeShaderWithChildren([i[0],i[1],r.levels,Math.max(r.scale*n,1),r.monochrome?1:0],c)}var Ef={type:"dither",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>Db(r,e,t,n.scale,fi(r,n)),dispose(){for(let{image:r,shader:e}of Wl)e.delete(),r.delete();Wl.clear(),ro=new WeakMap}};import{resolveEffectColor as If}from"@motionscript/core";var Ob=.2126,Lb=.7152,Ub=.0722;function Nb(r,e,t){let n=Math.max(0,Math.min(1,r)),i=c=>{let l=(t[c]-e[c])*n;return[l*Ob,l*Lb,l*Ub,0,e[c]*n]},[s,a,o]=[i(0),i(1),i(2)];return s[0]+=1-n,a[1]+=1-n,o[2]+=1-n,[...s,...a,...o,0,0,0,1,0]}var Mf={type:"duotone",makeImageFilter(r,e){if(r.amount<=0)return null;let t=Nb(r.amount,If(r.shadows),If(r.highlights)),n=e.ColorFilter.MakeMatrix(t),i=e.ImageFilter.MakeColorFilter(n,null);return n.delete(),i}};var zb=`
|
|
1218
1218
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1219
1219
|
uniform vec2 u_red; // red plane offset, device px
|
|
1220
1220
|
uniform vec2 u_green; // green plane offset, device px
|
|
@@ -1237,7 +1237,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1237
1237
|
vec3 straight = vec3(r.r, g.g, b.b);
|
|
1238
1238
|
return vec4(straight * a, a); // re-premultiply
|
|
1239
1239
|
}
|
|
1240
|
-
`;function
|
|
1240
|
+
`;function Vb(r,e,t,n){let{red:i,green:s,blue:a}=r;if(i.x===0&&i.y===0&&s.x===0&&s.y===0&&a.x===0&&a.y===0)return null;let c=ue(zb,e);return c?c.makeShaderWithChildren([i.x*n,i.y*n,s.x*n,s.y*n,a.x*n,a.y*n],[t]):null}var Ff={type:"rgbShift",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Vb(r,e,t,n.scale)};var Hb=`
|
|
1241
1241
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1242
1242
|
uniform vec2 u_center; // band origin, device px
|
|
1243
1243
|
uniform float u_spacing; // period, device px
|
|
@@ -1267,7 +1267,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1267
1267
|
float lit = 1.0 - band * clamp(u_darkness, 0.0, 1.0);
|
|
1268
1268
|
return vec4(c.rgb * lit, c.a); // premultiplied: scaling rgb dims, keeps alpha
|
|
1269
1269
|
}
|
|
1270
|
-
`;function
|
|
1270
|
+
`;function Wb(r,e,t,n){let i=r.spacing*n.scale;if(!(r.darkness>0)||!(i>=1))return null;let s=ue(Hb,e);if(!s)return null;let a=r.angle*Math.PI/180;return s.makeShaderWithChildren([n.centerX,n.centerY,i,r.thickness,r.darkness,r.offset*n.scale,Math.cos(a),Math.sin(a)],[t])}var Rf={type:"scanlines",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Wb(r,e,t,n)};import{resolveEffectAxis as qb}from"@motionscript/core";var Gb=`
|
|
1271
1271
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1272
1272
|
uniform vec2 u_center; // band origin, device px
|
|
1273
1273
|
uniform float u_amount; // max displacement, device px
|
|
@@ -1292,7 +1292,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1292
1292
|
|
|
1293
1293
|
return u_content.eval(fragCoord - u_axis * shift);
|
|
1294
1294
|
}
|
|
1295
|
-
`;function
|
|
1295
|
+
`;function jb(r,e,t,n){if(!(r.amount>0)||!(r.density>0))return null;let i=ue(Gb,e);if(!i)return null;let s=qb(r.axis);return s.x===0&&s.y===0?null:i.makeShaderWithChildren([n.centerX,n.centerY,r.amount*n.scale,Math.max(r.size*n.scale,1),r.density,r.seed,s.x,s.y],[t])}var Bf={type:"blockDisplace",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>jb(r,e,t,n)};var Df={gameboy:["#0f380f","#306230","#8bac0f","#9bbc0f"],cga:["#000000","#55ffff","#ff55ff","#ffffff"],nes:["#000000","#fcfcfc","#bcbcbc","#7c7c7c","#0000fc","#0078f8","#3cbcfc","#a4e4fc","#b8f818","#00b800","#005800","#f83800","#e40058","#f878f8","#f8b800","#503000"]};function Of(r){let e=parseInt(r.slice(1),16),t=n=>((e>>n&255)/255).toFixed(4);return`vec3(${t(16)}, ${t(8)}, ${t(0)})`}function Kb(r){return`
|
|
1296
1296
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1297
1297
|
uniform float u_bits; // bits per channel (palette 'none' only)
|
|
1298
1298
|
uniform float u_amount; // 0\u20131 blend toward the crushed colour
|
|
@@ -1307,16 +1307,16 @@ ${r==="none"?`
|
|
|
1307
1307
|
float steps = max(exp2(clamp(u_bits, 1.0, 8.0)) - 1.0, 1.0);
|
|
1308
1308
|
vec3 crushed = floor(base * steps + 0.5) / steps;`:`
|
|
1309
1309
|
// Nearest entry of the ${r} palette, by squared distance.
|
|
1310
|
-
vec3 crushed = ${
|
|
1310
|
+
vec3 crushed = ${Of(Df[r][0])};
|
|
1311
1311
|
float bestDist = dot(base - crushed, base - crushed);
|
|
1312
|
-
${
|
|
1312
|
+
${Df[r].slice(1).map(t=>` { vec3 p = ${Of(t)}; float d = dot(base - p, base - p);
|
|
1313
1313
|
if (d < bestDist) { bestDist = d; crushed = p; } }`).join(`
|
|
1314
1314
|
`)}`}
|
|
1315
1315
|
|
|
1316
1316
|
vec3 out_ = mix(base, crushed, clamp(u_amount, 0.0, 1.0));
|
|
1317
1317
|
return vec4(out_ * c.a, c.a); // re-premultiply
|
|
1318
1318
|
}
|
|
1319
|
-
`}function
|
|
1319
|
+
`}function $b(r,e,t){if(!(r.amount>0)||r.palette==="none"&&r.bits>=8)return null;let n=ue(Kb(r.palette),e);return n?n.makeShaderWithChildren([r.bits,r.amount],[t]):null}var Lf={type:"bitCrush",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>$b(r,e,t)};import{resolveAsciiCharset as zf,resolveEffectColor as Vf}from"@motionscript/core";function Xb(r,e,t=!1){return{weight:{value:Math.max(1,Math.min(1e3,Math.round(e)))},slant:t?r.FontSlant.Italic:r.FontSlant.Upright,width:r.FontWidth.Normal}}function ql(r,e,t,n,i=!1){return e.matchFamilyStyle(t,Xb(r,n,i))}function mi(r,e,t){let n=new r.Font(e,t);return n.setSubpixel(!0),n.setHinting(r.FontHinting.None),n.setLinearMetrics(!0),n}var Qb=64,Uf=256,Gl=r=>Math.max(4,Math.min(Qb,Math.round(r))),Nf=r=>Math.min([...r].length,Uf),Yb=(r,e)=>`${e}|${r.cell}|${r.fontFamily}|${r.fontWeight}|${r.charset}`,no=class{entries=new Map;get(e,t,n){let i=Yb(e,n.fontEpoch),s=this.entries.get(i);if(s!==void 0)return s;let a=Jb(e,t,n);return this.entries.set(i,a),a}dispose(){for(let e of this.entries.values())e?.dispose();this.entries.clear()}};function Zb(r,e,t){let n=ql(e,t.fontMgr,r.fontFamily,r.fontWeight);if(n)return n;if(t.fontMgr.countFamilies()>0){let i=t.fontMgr.getFamilyName(0),s=ql(e,t.fontMgr,i,r.fontWeight);if(s)return s}return null}function Jb(r,e,t){let n=[...r.charset].slice(0,Uf);if(n.length===0)return null;let i=Gl(r.cell),s=t.makeSurface(i*n.length,i);if(!s)return null;let a=mi(e,Zb(r,e,t),i*.8),o=s.getCanvas();o.clear(e.BLACK);let c=new e.Paint;c.setColor(e.WHITE),c.setAntiAlias(!0);let l=0;if(n.forEach((h,f)=>{let p=a.getGlyphIDs(h);if(p.length===0||p[0]===0){l++;return}let g=a.getGlyphWidths(p)[0]??i,y=f*i+(i-g)/2,b=i*.78;o.drawGlyphs(p,[y,b],0,0,a,c)}),l>0&&console.warn(`[motionscript] ascii: ${l}/${n.length} glyphs are missing from '${r.fontFamily}'. Register a font covering those characters, or use the 'standard' charset, which is plain ASCII.`),l===n.length)return c.delete(),a.delete(),s.delete(),null;c.delete(),a.delete(),s.flush();let u=s.makeImageSnapshot(),d=u.makeShaderOptions(e.TileMode.Clamp,e.TileMode.Clamp,e.FilterMode.Linear,e.MipmapMode.None);return{shader:d,count:n.length,cell:i,dispose(){d.delete(),u.delete(),s.delete()}}}var ek=2,Hf=r=>Gl(Math.max(8,r*ek)),tk=`
|
|
1320
1320
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1321
1321
|
uniform shader u_atlas; // charset baked darkest-first, one row of cells
|
|
1322
1322
|
uniform vec2 u_center; // cell grid anchor, device px
|
|
@@ -1362,7 +1362,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1362
1362
|
|
|
1363
1363
|
return vec4(straight * alpha, alpha); // re-premultiply
|
|
1364
1364
|
}
|
|
1365
|
-
`,
|
|
1365
|
+
`,qf={type:"ascii",sampling:{tileMode:"decal",filterMode:"nearest"},resources(r,e,t){let n=zf(r.charset);if(n.length===0)return null;let i=Wf.get({charset:n,fontFamily:r.fontFamily,fontWeight:400,cell:Hf(r.size)},e,t);return i?[i.shader]:null},makeShader(r,e,t,n,i){let s=i?.[0];if(!s)return null;let a=r.size*n.scale;if(!(a>=2))return null;let o=ue(tk,e);if(!o)return null;let c=Vf(r.ink),l=Vf(r.background);return o.makeShaderWithChildren([n.centerX,n.centerY,a,Nf(zf(r.charset)),Hf(r.size),...c,...l,r.colored?1:0],[t,s])},dispose(){Wf.dispose()}},Wf=new no;var Gf={type:"streak",makeImageFilter(r,e){if(r.intensity<=0||r.length<=0)return null;let t=Math.max(0,Math.min(1,r.threshold)),n=t<1?1/(1-t):1,i=-t*n,s=[n,0,0,0,i,0,n,0,0,i,0,0,n,0,i,0,0,0,1,0],a=e.ColorFilter.MakeMatrix(s),o=e.ImageFilter.MakeColorFilter(a,null);a.delete();let c=r.angle*Math.PI/180,l={filter:e.FilterMode.Linear,mipmap:e.MipmapMode.None};if(c!==0){let h=e.ImageFilter.MakeMatrixTransform(e.Matrix.rotated(-c),l,o);o.delete(),o=h}let u=e.ImageFilter.MakeBlur(r.length/2,.01,e.TileMode.Decal,o);if(o.delete(),o=u,c!==0){let h=e.ImageFilter.MakeMatrixTransform(e.Matrix.rotated(c),l,o);o.delete(),o=h}if(r.intensity!==1){let h=r.intensity,f=[h,0,0,0,0,0,h,0,0,0,0,0,h,0,0,0,0,0,1,0],p=e.ColorFilter.MakeMatrix(f),m=e.ImageFilter.MakeColorFilter(p,o);p.delete(),o.delete(),o=m}let d=e.ImageFilter.MakeBlend(e.BlendMode.Screen,null,o);return o.delete(),d}};import{resolveEffectAxis as rk,resolveEffectColor as jf}from"@motionscript/core";var nk="vec3(0.2126, 0.7152, 0.0722)";function ik(r,e,t){let n=r==="ramp",i=n?`uniform vec4 u_colors[${t}]; // ramp colours, straight RGBA
|
|
1366
1366
|
uniform float u_stops[${t}]; // their positions, 0-1 ascending
|
|
1367
1367
|
uniform float u_cycles; // ramp traversals across the strength range
|
|
1368
1368
|
uniform float u_phase; // offset along the ramp, in turns`:"",s=r==="solid"?"uniform vec4 u_color; // the glow's colour, straight RGBA":"",o=n?`${e?"float wrap(float x) { return abs(fract(x * 0.5) * 2.0 - 1.0); }":"float wrap(float x) { return fract(x); }"}
|
|
@@ -1378,7 +1378,7 @@ vec3 rampColor(float e) {
|
|
|
1378
1378
|
}
|
|
1379
1379
|
return c;
|
|
1380
1380
|
}`:"",c=r==="none"?` // Already premultiplied, and already thresholded by the prefilter.
|
|
1381
|
-
return pass * u_intensity;`:` float e = clamp(dot(pass.rgb, ${
|
|
1381
|
+
return pass * u_intensity;`:` float e = clamp(dot(pass.rgb, ${nk}) * u_intensity, 0.0, 1.0);
|
|
1382
1382
|
vec3 rgb = ${n?"rampColor(e)":"u_color.rgb"};
|
|
1383
1383
|
return vec4(rgb * e, e);`;return`
|
|
1384
1384
|
uniform shader u_glow; // thresholded, spread and blurred copy of the source
|
|
@@ -1391,63 +1391,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1391
1391
|
vec4 pass = u_glow.eval(fragCoord);
|
|
1392
1392
|
${c}
|
|
1393
1393
|
}
|
|
1394
|
-
`}function
|
|
1395
|
-
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1396
|
-
uniform vec2 u_light; // light source, device px
|
|
1397
|
-
uniform float u_length; // ray reach, fraction of the distance to the light
|
|
1398
|
-
uniform float u_threshold; // 0\u20131 luminance cutoff
|
|
1399
|
-
uniform float u_decay; // per-step falloff
|
|
1400
|
-
uniform float u_intensity; // additive multiplier
|
|
1401
|
-
|
|
1402
|
-
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
1403
|
-
|
|
1404
|
-
/** Straight colour of a tap, zeroed unless it clears the threshold. */
|
|
1405
|
-
vec3 bright(vec2 p) {
|
|
1406
|
-
vec4 c = u_content.eval(p);
|
|
1407
|
-
if (c.a <= 0.0) return vec3(0.0);
|
|
1408
|
-
vec3 base = c.rgb / c.a;
|
|
1409
|
-
float lum = dot(base, LUMA);
|
|
1410
|
-
// Rescale rather than gate, so the rays fade in with the light instead of
|
|
1411
|
-
// switching on at the cutoff.
|
|
1412
|
-
float keep = max(lum - u_threshold, 0.0) / max(1.0 - u_threshold, 0.0001);
|
|
1413
|
-
return base * keep;
|
|
1414
|
-
}
|
|
1415
|
-
|
|
1416
|
-
vec4 main(vec2 fragCoord) {
|
|
1417
|
-
vec4 src = u_content.eval(fragCoord);
|
|
1418
|
-
|
|
1419
|
-
// Step from this pixel toward the light, a fraction of the way each time.
|
|
1420
|
-
vec2 delta = (u_light - fragCoord) * (u_length / ${r}.0);
|
|
1421
|
-
|
|
1422
|
-
// Start each pixel a random fraction of a step along. Marching every pixel
|
|
1423
|
-
// from the same offset makes the sample positions line up into concentric
|
|
1424
|
-
// arcs \u2014 visible banding at any affordable tap count. Dithering the start
|
|
1425
|
-
// trades those arcs for fine noise, which reads as light rather than as
|
|
1426
|
-
// artefact, and costs one hash.
|
|
1427
|
-
float jitter = fract(sin(dot(fragCoord, vec2(12.9898, 78.233))) * 43758.5453);
|
|
1428
|
-
vec2 pos = fragCoord + delta * jitter;
|
|
1429
|
-
|
|
1430
|
-
float weight = 1.0;
|
|
1431
|
-
vec3 rays = vec3(0.0);
|
|
1432
|
-
|
|
1433
|
-
for (int i = 0; i < ${r}; i++) {
|
|
1434
|
-
pos += delta;
|
|
1435
|
-
rays += bright(pos) * weight;
|
|
1436
|
-
weight *= u_decay;
|
|
1437
|
-
}
|
|
1438
|
-
rays = rays / ${r}.0 * u_intensity;
|
|
1439
|
-
|
|
1440
|
-
// Screen onto the source, in straight colour, then re-premultiply.
|
|
1441
|
-
vec3 base = src.a > 0.0 ? src.rgb / src.a : vec3(0.0);
|
|
1442
|
-
vec3 lit = 1.0 - (1.0 - base) * (1.0 - clamp(rays, 0.0, 1.0));
|
|
1443
|
-
|
|
1444
|
-
// Rays land outside the silhouette too \u2014 that is the point of light
|
|
1445
|
-
// streaming past an occluder \u2014 so the alpha grows to carry them.
|
|
1446
|
-
float glow = clamp(max(rays.r, max(rays.g, rays.b)), 0.0, 1.0);
|
|
1447
|
-
float a = max(src.a, glow);
|
|
1448
|
-
return vec4(lit * a, a);
|
|
1449
|
-
}
|
|
1450
|
-
`}function Wb(r,e,t,n){if(!(r.intensity>0)||!(r.length>0)||n.width<=0||n.height<=0)return null;let i=Math.round(Math.max(Nb,Math.min(Vb,r.samples))),s=ne(Hb(i),e);if(!s)return null;let a=n.centerX+(r.center.x-.5)*n.width,o=n.centerY+(r.center.y-.5)*n.height;return s.makeShaderWithChildren([a,o,r.length,r.threshold,r.decay,r.intensity],[t])}var Uf={type:"godRays",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Wb(r,e,t,n)};var qb=6;function jb(r){return`
|
|
1394
|
+
`}function sk(r,e,t){let n=r.channel==="alpha",i=n?0:Math.max(0,Math.min(1,r.threshold)),s=i<1?1/(1-i):1,a=-i*s,o=n?[0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0]:[s,0,0,0,a,0,s,0,0,a,0,0,s,0,a,0,0,0,1,0],c=e.ColorFilter.MakeMatrix(o),l=e.ImageFilter.MakeColorFilter(c,null);c.delete();let u=Math.max(0,r.spread)*t;if(u<=0)return l;let d=e.ImageFilter.MakeDilate(u,u,l);return l.delete(),d}var Kf={type:"glow",sampling:{tileMode:"decal",filterMode:"linear"},renderInputs(r,e,t){if(r.radius<=0&&r.spread<=0||r.intensity<=0)return null;let n=Math.max(0,r.radius)*t.scale/2,i=rk(r.axis);return{blurredSource:{sigmaX:n*i.x,sigmaY:n*i.y,prefilter:sk(r,e,t.scale)}}},makeShader(r,e,t,n,i,s){let a=s?.blurredSource;if(!a)return null;let o=r.colors.length,c=ik(r.tint,r.loopStyle==="mirror",o),l=ue(c,e);if(!l)return null;let u=[r.intensity];if(r.tint==="solid"&&u.push(...jf(r.color)),r.tint==="ramp"){for(let g of r.colors)u.push(...jf(g));let m=0;for(let g=0;g<o;g++)m=Math.max(m,Math.min(1,r.stops[g]??g/Math.max(1,o-1))),u.push(m);u.push(r.cycles,r.phase/360)}let d=l.makeShaderWithChildren(u,[a]);if(r.original==="hidden")return d;let h=Kt(e,r.blend),f=e.Shader.MakeBlend(h,t,d);if(d.delete(),r.original==="behind")return f;let p=e.Shader.MakeBlend(e.BlendMode.SrcOver,f,t);return f.delete(),p}};var ak=6;function ok(r){return`
|
|
1451
1395
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1452
1396
|
|
|
1453
1397
|
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
@@ -1495,94 +1439,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1495
1439
|
|
|
1496
1440
|
return vec4(bestMean * centre.a, centre.a);
|
|
1497
1441
|
}
|
|
1498
|
-
`}function
|
|
1499
|
-
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1500
|
-
uniform shader u_texture; // the overlay image
|
|
1501
|
-
uniform vec2 u_center; // node centre, device px
|
|
1502
|
-
uniform vec2 u_half; // node half-extent, device px
|
|
1503
|
-
uniform vec2 u_texHalf; // texture half-size, texture px
|
|
1504
|
-
uniform float u_scale; // 1 = texture covers the node once
|
|
1505
|
-
uniform float u_cos; // rotation, precomputed
|
|
1506
|
-
uniform float u_sin;
|
|
1507
|
-
uniform float u_amount; // 0\u20131 blend strength
|
|
1508
|
-
uniform float u_blend; // 0 multiply, 1 overlay, 2 screen, 3 softLight
|
|
1509
|
-
|
|
1510
|
-
float blendChannel(float base, float tex) {
|
|
1511
|
-
if (u_blend > 2.5) {
|
|
1512
|
-
// Soft light (Photoshop's formulation), the gentlest of the four.
|
|
1513
|
-
return tex < 0.5
|
|
1514
|
-
? base - (1.0 - 2.0 * tex) * base * (1.0 - base)
|
|
1515
|
-
: base + (2.0 * tex - 1.0) * (sqrt(base) - base);
|
|
1516
|
-
}
|
|
1517
|
-
if (u_blend > 1.5) return 1.0 - (1.0 - base) * (1.0 - tex); // screen
|
|
1518
|
-
if (u_blend > 0.5) { // overlay
|
|
1519
|
-
return base < 0.5 ? 2.0 * base * tex : 1.0 - 2.0 * (1.0 - base) * (1.0 - tex);
|
|
1520
|
-
}
|
|
1521
|
-
return base * tex; // multiply
|
|
1522
|
-
}
|
|
1523
|
-
|
|
1524
|
-
vec4 main(vec2 fragCoord) {
|
|
1525
|
-
vec4 c = u_content.eval(fragCoord);
|
|
1526
|
-
if (c.a <= 0.0) return c;
|
|
1527
|
-
|
|
1528
|
-
// Node-local, rotated, then mapped into the texture's own pixel space.
|
|
1529
|
-
vec2 d = fragCoord - u_center;
|
|
1530
|
-
vec2 r = vec2(d.x * u_cos - d.y * u_sin, d.x * u_sin + d.y * u_cos);
|
|
1531
|
-
vec2 uv = r / max(u_half, vec2(1.0)) * u_scale; // -1..1 across the node
|
|
1532
|
-
vec2 texel = (uv * 0.5 + 0.5) * (u_texHalf * 2.0);
|
|
1533
|
-
|
|
1534
|
-
vec4 t = u_texture.eval(texel);
|
|
1535
|
-
if (t.a <= 0.0) return c; // outside the texture
|
|
1536
|
-
vec3 tex = t.rgb / t.a;
|
|
1537
|
-
|
|
1538
|
-
vec3 base = c.rgb / c.a; // un-premultiply
|
|
1539
|
-
vec3 blended = vec3(
|
|
1540
|
-
blendChannel(base.r, tex.r),
|
|
1541
|
-
blendChannel(base.g, tex.g),
|
|
1542
|
-
blendChannel(base.b, tex.b)
|
|
1543
|
-
);
|
|
1544
|
-
vec3 out_ = mix(base, blended, clamp(u_amount, 0.0, 1.0) * t.a);
|
|
1545
|
-
return vec4(out_ * c.a, c.a); // re-premultiply
|
|
1546
|
-
}
|
|
1547
|
-
`,Yb={multiply:0,overlay:1,screen:2,"soft-light":3,softLight:3},Wf={type:"texture",sampling:{tileMode:"decal",filterMode:"linear"},resources(r,e,t,n){if(!(r.amount>0)||!r.src)return null;let i=ro(r.src,r.scale,e,t,n);return i?[i]:null},makeShader(r,e,t,n,i){let s=i?.[0];if(!s||n.width<=0||n.height<=0)return null;let a=ne(Qb,e);if(!a)return null;let o=r.angle*Math.PI/180,c=no(s);return c?a.makeShaderWithChildren([n.centerX,n.centerY,n.width/2,n.height/2,c.width/2,c.height/2,Math.max(r.scale,.01),Math.cos(o),Math.sin(o),r.amount,Yb[r.blend]??0],[t,s]):null},dispose(){io()}};var Zb=`
|
|
1548
|
-
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1549
|
-
uniform shader u_map; // the displacement map
|
|
1550
|
-
uniform vec2 u_center; // node centre, device px
|
|
1551
|
-
uniform vec2 u_half; // node half-extent, device px
|
|
1552
|
-
uniform vec2 u_amount; // px displacement at full deflection, device px
|
|
1553
|
-
uniform float u_scale; // 1 = map covers the node once
|
|
1554
|
-
uniform float u_cos; // map rotation, precomputed
|
|
1555
|
-
uniform float u_sin;
|
|
1556
|
-
uniform float u_midpoint; // map value meaning "don't move"
|
|
1557
|
-
uniform float u_channel; // 0 rg, 1 luminance, 2 alpha
|
|
1558
|
-
uniform vec2 u_mapHalf; // map half-size, intrinsic map px
|
|
1559
|
-
|
|
1560
|
-
vec4 main(vec2 fragCoord) {
|
|
1561
|
-
// Node-local, rotated, then mapped into the map's own pixel space \u2014 the
|
|
1562
|
-
// same mapping the texture overlay uses, so a map and a texture authored
|
|
1563
|
-
// against the same node line up.
|
|
1564
|
-
vec2 d = fragCoord - u_center;
|
|
1565
|
-
vec2 r = vec2(d.x * u_cos - d.y * u_sin, d.x * u_sin + d.y * u_cos);
|
|
1566
|
-
vec2 uv = r / max(u_half, vec2(1.0)) * u_scale;
|
|
1567
|
-
vec2 texel = (uv * 0.5 + 0.5) * (u_mapHalf * 2.0);
|
|
1568
|
-
|
|
1569
|
-
vec4 m = u_map.eval(texel);
|
|
1570
|
-
if (m.a <= 0.0) return u_content.eval(fragCoord); // nothing here to push with
|
|
1571
|
-
|
|
1572
|
-
vec3 mv = m.rgb / m.a; // un-premultiply
|
|
1573
|
-
vec2 signal;
|
|
1574
|
-
if (u_channel > 1.5) {
|
|
1575
|
-
signal = vec2(m.a);
|
|
1576
|
-
} else if (u_channel > 0.5) {
|
|
1577
|
-
signal = vec2(dot(mv, vec3(0.2126, 0.7152, 0.0722)));
|
|
1578
|
-
} else {
|
|
1579
|
-
signal = mv.rg;
|
|
1580
|
-
}
|
|
1581
|
-
|
|
1582
|
-
vec2 offset = (signal - u_midpoint) * 2.0 * u_amount;
|
|
1583
|
-
return u_content.eval(fragCoord + offset);
|
|
1584
|
-
}
|
|
1585
|
-
`,Jb={rg:0,luminance:1,alpha:2},qf={type:"displace",sampling:{tileMode:"clamp",filterMode:"linear"},resources(r,e,t,n){if(!r.src||r.amount.x===0&&r.amount.y===0)return null;let i=ro(r.src,r.scale,e,t,n);return i?[i]:null},makeShader(r,e,t,n,i){let s=i?.[0];if(!s||n.width<=0||n.height<=0)return null;let a=ne(Zb,e);if(!a)return null;let o=r.angle*Math.PI/180,c=no(s);return c?a.makeShaderWithChildren([n.centerX,n.centerY,n.width/2,n.height/2,r.amount.x*n.scale,r.amount.y*n.scale,Math.max(r.scale,.01),Math.cos(o),Math.sin(o),r.midpoint,Jb[r.channel]??0,c.width/2,c.height/2],[t,s]):null},dispose(){io()}};var ek=`
|
|
1442
|
+
`}function ck(r,e,t,n){let i=Math.round(Math.min(ak,r.radius*n));if(i<1)return null;let s=ue(ok(i),e);return s?s.makeShaderWithChildren([],[t]):null}var $f={type:"oilPaint",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>ck(r,e,t,n.scale)};var lk=`
|
|
1586
1443
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1587
1444
|
uniform vec2 u_center; // ripple origin, device px
|
|
1588
1445
|
uniform vec2 u_amplitude; // peak displacement per axis, device px
|
|
@@ -1603,7 +1460,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1603
1460
|
|
|
1604
1461
|
return u_content.eval(fragCoord + u_amplitude * wave);
|
|
1605
1462
|
}
|
|
1606
|
-
`,
|
|
1463
|
+
`,Xf={type:"wave",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t,n){let{x:i,y:s}=r.amplitude;if(i===0&&s===0||n.width<=0||n.height<=0)return null;let a=ue(lk,e);if(!a)return null;let o=r.angle*Math.PI/180,c=(r.phase%360+360)%360*Math.PI/180,l=n.centerX+(r.center.x-.5)*n.width,u=n.centerY+(r.center.y-.5)*n.height;return a.makeShaderWithChildren([l,u,i*n.scale,s*n.scale,Math.max(r.wavelength,.01)*n.scale,c,Math.cos(o),Math.sin(o),r.shape==="radial"?1:0],[t])}};var uk=`
|
|
1607
1464
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1608
1465
|
uniform vec2 u_center; // vortex centre, device px
|
|
1609
1466
|
uniform vec2 u_half; // node half-extent, device px
|
|
@@ -1625,7 +1482,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1625
1482
|
|
|
1626
1483
|
return u_content.eval(u_center + rotated * half_);
|
|
1627
1484
|
}
|
|
1628
|
-
`,
|
|
1485
|
+
`,Qf={type:"twirl",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t,n){if(r.angle===0||r.radius<=0||n.width<=0||n.height<=0)return null;let i=ue(uk,e);if(!i)return null;let s=n.centerX+(r.center.x-.5)*n.width,a=n.centerY+(r.center.y-.5)*n.height;return i.makeShaderWithChildren([s,a,n.width/2,n.height/2,r.angle*Math.PI/180,r.radius],[t])}};var dk=32,hk=2;function fk(r){return`
|
|
1629
1486
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1630
1487
|
uniform vec2 u_center; // ramp origin, device px
|
|
1631
1488
|
uniform vec2 u_half; // node half-extent, device px
|
|
@@ -1669,7 +1526,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1669
1526
|
}
|
|
1670
1527
|
return sum / float(N + 1);
|
|
1671
1528
|
}
|
|
1672
|
-
`}var
|
|
1529
|
+
`}var Yf={type:"progressiveBlur",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t,n){let i=r.startRadius??0;if(r.radius<=0&&i<=0||n.width<=0||n.height<=0)return null;let s=Math.max(hk,Math.min(dk,Math.round(r.samples))),a=ue(fk(s),e);if(!a)return null;let o=r.angle*Math.PI/180,c=n.centerX+(r.center.x-.5)*n.width,l=n.centerY+(r.center.y-.5)*n.height;return a.makeShaderWithChildren([c,l,n.width/2,n.height/2,Math.cos(o),Math.sin(o),r.radius*n.scale,i*n.scale,r.start,r.end,r.shape==="radial"?1:0],[t])}};var mk=`
|
|
1673
1530
|
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1674
1531
|
uniform vec2 u_center; // fold origin, device px
|
|
1675
1532
|
uniform vec2 u_half; // node half-extent, device px
|
|
@@ -1698,95 +1555,92 @@ vec4 main(vec2 fragCoord) {
|
|
|
1698
1555
|
// reads as a warp rather than as the pattern appearing.
|
|
1699
1556
|
return mix(u_content.eval(fragCoord), folded, u_amount);
|
|
1700
1557
|
}
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
uniform
|
|
1713
|
-
uniform
|
|
1714
|
-
uniform
|
|
1715
|
-
uniform float
|
|
1716
|
-
uniform float
|
|
1717
|
-
uniform float
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
${n}
|
|
1722
|
-
return acc;
|
|
1723
|
-
}
|
|
1724
|
-
`}var Xf={type:"trails",sampling:{tileMode:"decal",filterMode:"linear"},makeShader(r,e,t,n){let i=Math.max(0,Math.min(ak,Math.round(r.echoes)));if(i===0||n.width<=0||n.height<=0)return null;let s=Math.max(r.delay,1e-4),a=n.velocity.x*n.scale,o=n.velocity.y*n.scale,c=n.angularVelocity*Math.PI/180,l=Math.hypot(a,o)*s*i,u=Math.abs(c)*s*i*Math.max(n.width,n.height)/2;if(l+u<ok)return null;let d=ne(ck(i,r.blend),e);if(!d)return null;let h=Math.max(0,Math.min(1,r.decay)),f=Array.from({length:i},(p,m)=>h**(m+1));return d.makeShaderWithChildren([n.centerX,n.centerY,a,o,c,s,...f],[t])}};var lk=.5,uk=.6,dk=.4,hk=8,fk=48,mk=1.5,Qf=.6,pk=.9;function gk(r){return`
|
|
1725
|
-
uniform shader u_backdrop; // what is painted beneath the node
|
|
1726
|
-
uniform shader u_mask; // blurred silhouette: alpha 0.5 on the edge, 1 inside
|
|
1727
|
-
${r?"uniform shader u_soft; // the backdrop, pre-blurred for the frost blend":""}
|
|
1728
|
-
uniform float u_step; // central-difference step for the mask gradient, device px
|
|
1729
|
-
uniform float u_refraction; // sideways pull at the rim, device px
|
|
1730
|
-
uniform float u_dispersion; // per-channel spread, as a share of the pull
|
|
1731
|
-
${r?"uniform float u_frost; // 0-1 blend toward the blurred backdrop":""}
|
|
1732
|
-
uniform vec3 u_light; // unit direction toward the light
|
|
1733
|
-
uniform float u_shininess; // specular exponent
|
|
1734
|
-
uniform float u_gain; // specular multiplier
|
|
1735
|
-
|
|
1736
|
-
float coverage(vec2 p) {
|
|
1737
|
-
return u_mask.eval(p).a;
|
|
1558
|
+
`,Zf={type:"kaleidoscope",sampling:{tileMode:"decal",filterMode:"linear"},makeShader(r,e,t,n){let i=Math.round(r.segments);if(i<2||r.amount<=0||n.width<=0||n.height<=0)return null;let s=ue(mk,e);if(!s)return null;let a=n.centerX+(r.center.x-.5)*n.width,o=n.centerY+(r.center.y-.5)*n.height;return s.makeShaderWithChildren([a,o,n.width/2,n.height/2,2*Math.PI/i,r.angle*Math.PI/180,r.offset,Math.max(0,Math.min(1,r.amount))],[t])}};var pk=1.5,gk=.5,yk=.35,wk=1.4,bk=1,kk=.75,Sk=1.2,xk=.1,Tk=.06,Ak=.7,vk=.3,Jf=.25,jl=7;function _k(r){return`
|
|
1559
|
+
uniform shader u_backdrop; // beneath the node, frosted when asked
|
|
1560
|
+
uniform shader u_field; // alpha: distance inside the outline over u_deepest
|
|
1561
|
+
uniform float u_deepest; // device px a field alpha of 1 stands for
|
|
1562
|
+
uniform float u_bevel; // bevel width, device px
|
|
1563
|
+
uniform float u_base; // glass under the bevel, device px
|
|
1564
|
+
uniform float u_eta; // 1 / refractive index
|
|
1565
|
+
uniform float u_amount; // 0-1 scale on the pull
|
|
1566
|
+
uniform float u_spread; // spectrum spread, share of the pull
|
|
1567
|
+
uniform vec2 u_light; // unit vector toward the light, y-down
|
|
1568
|
+
uniform float u_rim; // rim falloff width, device px
|
|
1569
|
+
uniform float u_lobe; // rim falloff exponent around the outline
|
|
1570
|
+
uniform float u_gain; // rim alpha facing the light
|
|
1571
|
+
uniform float u_far; // rim facing away, share of u_gain
|
|
1572
|
+
uniform float u_shade; // projected-light shading facing the light
|
|
1573
|
+
uniform float u_glow; // and facing away
|
|
1574
|
+
uniform float u_reach; // share of the bevel the shading fades out across
|
|
1575
|
+
|
|
1576
|
+
float dist(vec2 p) {
|
|
1577
|
+
return u_field.eval(p).a * u_deepest;
|
|
1738
1578
|
}
|
|
1739
1579
|
|
|
1740
|
-
vec4 main(vec2
|
|
1741
|
-
float
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
float
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
float slope =
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
vec4 g2 = u_backdrop.eval(fragCoord + offset);
|
|
1763
|
-
vec4 b = u_backdrop.eval(fragCoord + offset - spread);
|
|
1764
|
-
vec4 glass = vec4(r.r, g2.g, b.b, g2.a);
|
|
1580
|
+
vec4 main(vec2 p) {
|
|
1581
|
+
float d = dist(p);
|
|
1582
|
+
vec2 g = vec2(dist(p + vec2(1.0, 0.0)) - dist(p - vec2(1.0, 0.0)),
|
|
1583
|
+
dist(p + vec2(0.0, 1.0)) - dist(p - vec2(0.0, 1.0)));
|
|
1584
|
+
float gl = length(g);
|
|
1585
|
+
// Distance grows inward, so the outward normal is its negated gradient.
|
|
1586
|
+
vec2 n = gl > 1e-4 ? -g / gl : vec2(0.0);
|
|
1587
|
+
|
|
1588
|
+
// Squircle bevel: height h and its slope over the bevel, which is as tall as it is wide.
|
|
1589
|
+
float x = clamp(d / u_bevel, 0.001, 1.0);
|
|
1590
|
+
float y = 1.0 - x;
|
|
1591
|
+
float y4 = y * y * y * y;
|
|
1592
|
+
float h = pow(1.0 - y4, 0.25);
|
|
1593
|
+
float slope = y * y * y * pow(max(1.0 - y4, 1e-6), -0.75);
|
|
1594
|
+
|
|
1595
|
+
// Refract a straight-down ray through the surface normal (n\xB7slope, 1).
|
|
1596
|
+
float cosi = inversesqrt(1.0 + slope * slope);
|
|
1597
|
+
float k = 1.0 - u_eta * u_eta * (1.0 - cosi * cosi);
|
|
1598
|
+
float a = u_eta * cosi - sqrt(max(k, 0.0));
|
|
1599
|
+
float lateral = a * slope * cosi; // along n; negative, so inward
|
|
1600
|
+
float down = a * cosi - u_eta; // negative
|
|
1601
|
+
vec2 pull = n * (lateral / -down) * (u_bevel * h + u_base) * u_amount;
|
|
1765
1602
|
${r?`
|
|
1766
|
-
//
|
|
1767
|
-
//
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
vec4
|
|
1780
|
-
|
|
1603
|
+
// Red bends least and blue most; integrating over the taps with a weight
|
|
1604
|
+
// per channel turns the split into a spectrum rather than three ghosts.
|
|
1605
|
+
vec3 sum = vec3(0.0);
|
|
1606
|
+
vec3 weight = vec3(0.0);
|
|
1607
|
+
float alpha = 0.0;
|
|
1608
|
+
for (int i = 0; i < ${jl}; i++) {
|
|
1609
|
+
float t = float(i) / ${jl-1}.0;
|
|
1610
|
+
vec4 s = u_backdrop.eval(p + pull * (1.0 + u_spread * (t * 2.0 - 1.0)));
|
|
1611
|
+
vec3 w = exp(-pow((vec3(t) - vec3(0.0, 0.5, 1.0)) / 0.3, vec3(2.0)));
|
|
1612
|
+
sum += s.rgb * w;
|
|
1613
|
+
weight += w;
|
|
1614
|
+
alpha += s.a;
|
|
1615
|
+
}
|
|
1616
|
+
vec4 glass = vec4(sum / weight, alpha / ${jl}.0);
|
|
1617
|
+
glass.rgb = min(glass.rgb, vec3(glass.a));
|
|
1618
|
+
`:`
|
|
1619
|
+
vec4 glass = u_backdrop.eval(p + pull);
|
|
1620
|
+
`}
|
|
1621
|
+
float facing = dot(n, u_light);
|
|
1622
|
+
float near = pow(max(facing, 0.0), u_lobe);
|
|
1623
|
+
float far = u_far * pow(max(-facing, 0.0), u_lobe);
|
|
1624
|
+
|
|
1625
|
+
// Light projected through the bevel: it leaves the side facing it a shade
|
|
1626
|
+
// darker and lands on the opposite side, fading out across the bevel.
|
|
1627
|
+
float across = 1.0 - smoothstep(0.0, u_reach, x);
|
|
1628
|
+
glass.rgb *= 1.0 - u_shade * near * across;
|
|
1629
|
+
glass.rgb += (vec3(glass.a) - glass.rgb) * (u_glow * far / u_far * across);
|
|
1630
|
+
|
|
1631
|
+
// A thin rim on the outline, brightest facing the light and again, a little
|
|
1632
|
+
// dimmer, on the side opposite it. White source-over, premultiplied.
|
|
1633
|
+
float spec = clamp(u_gain * (near + far) * (1.0 - smoothstep(0.0, u_rim, d)), 0.0, 1.0);
|
|
1634
|
+
return vec4(spec) + glass * (1.0 - spec);
|
|
1781
1635
|
}
|
|
1782
|
-
`}var
|
|
1636
|
+
`}var em=r=>Math.min(1,Math.max(0,r));function Ck(r,e){return Math.max(0,r.frost)*.5*e.scale}var tm={type:"glass",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop",renderInputs(r,e,t){if(!(r.depth>0))return null;let n=Ck(r,t);return n>.25?{distanceField:!0,blurredSource:n}:{distanceField:!0}},makeShader(r,e,t,n,i,s){let a=s?.distanceField;if(!a)return null;let o=Math.min(Math.max(0,r.depth)*n.scale,a.maxDistance);if(!(o>0))return null;let c=em(r.dispersion/100)*yk,l=em(r.splay/100),u=r.lightAngle*Math.PI/180,d=Math.max(0,r.lightIntensity/100),h=ue(_k(c>0),e);return h?h.makeShaderWithChildren([a.maxDistance,o,gk*o,1/pk,Math.max(0,r.refraction/100),c,Math.sin(u),-Math.cos(u),wk*n.scale,Sk,d*bk,kk,d*xk*(1-Jf*l),d*Tk*(1-Jf*l),Ak+vk*l],[s?.blurredSource??t,a.shader]):null}};var rm={type:"exposure",makeImageFilter(r,e){let t=r.amount,n=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0],i=e.ColorFilter.MakeMatrix(n),s=e.ImageFilter.MakeColorFilter(i,null);return i.delete(),s}};var nm={type:"alpha",makeImageFilter(r,e){let n=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,Math.max(0,Math.min(1,r.amount)),0],i=e.ColorFilter.MakeMatrix(n),s=e.ImageFilter.MakeColorFilter(i,null);return i.delete(),s}};var im={type:"colorMatrix",makeImageFilter(r,e){let t=e.ColorFilter.MakeMatrix(r.matrix),n=e.ImageFilter.MakeColorFilter(t,null);return t.delete(),n}};function Pk(r,e){if(r.length===0)return e;if(e<=r[0][0])return r[0][1];let t=r[r.length-1];if(e>=t[0])return t[1];for(let n=0;n<r.length-1;n++){let[i,s]=r[n],[a,o]=r[n+1];if(e>=i&&e<=a){let c=a===i?0:(e-i)/(a-i);return s+(o-s)*c}}return e}var En=32;function Ek(r){let e=[...r].sort((n,i)=>n[0]-i[0]),t=[];for(let n=0;n<=En;n++){let i=Pk(e,n/En);t.push(Number.isFinite(i)?Math.max(0,Math.min(1,i)):n/En)}return t}function Ik(r){return r.every((e,t)=>Math.abs(e-t/En)<1e-4)}function Mk(r){switch(r){case"r":return[1,0,0,0];case"g":return[0,1,0,0];case"b":return[0,0,1,0];case"a":return[0,0,0,1];default:return[1,1,1,0]}}function Fk(){let r=Array.from({length:En},(e,t)=>` y += (u_curve[${t+1}] - u_curve[${t}]) * clamp(t - ${t}.0, 0.0, 1.0);`).join(`
|
|
1783
1637
|
`);return`
|
|
1784
1638
|
uniform shader u_content;
|
|
1785
1639
|
uniform vec4 u_mask; // 1 on the channels this curve drives
|
|
1786
|
-
uniform float u_curve[${
|
|
1640
|
+
uniform float u_curve[${En+1}]; // the curve, evenly spaced over 0\u20131
|
|
1787
1641
|
|
|
1788
1642
|
vec4 lookup(vec4 c) {
|
|
1789
|
-
vec4 t = clamp(c, 0.0, 1.0) * ${
|
|
1643
|
+
vec4 t = clamp(c, 0.0, 1.0) * ${En}.0;
|
|
1790
1644
|
vec4 y = vec4(u_curve[0]);
|
|
1791
1645
|
${r}
|
|
1792
1646
|
return y;
|
|
@@ -1804,7 +1658,7 @@ vec4 main(vec2 p) {
|
|
|
1804
1658
|
vec4 curved = mix(straight, lookup(straight), u_mask);
|
|
1805
1659
|
return vec4(clamp(curved.rgb, 0.0, 1.0) * curved.a, curved.a);
|
|
1806
1660
|
}
|
|
1807
|
-
`}var
|
|
1661
|
+
`}var sm={type:"curves",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t){let n=Ek(r.points??[]);if(Ik(n))return null;let i=ue(Fk(),e);return i?i.makeShaderWithChildren([...Mk(r.channel??"rgb"),...n],[t]):null}};function Rk(){return[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]}function Bk(r,e){let t=new Array(20).fill(0);for(let n=0;n<4;n++)for(let i=0;i<5;i++){let s=0;for(let a=0;a<4;a++)s+=r[n*5+a]*e[a*5+i];i===4&&(s+=r[n*5+4]),t[n*5+i]=s}return t}function Dk(r){return[1,0,0,0,r,0,1,0,0,r,0,0,1,0,r,0,0,0,1,0]}function Ok(r){let e=.5*(1-r);return[r,0,0,0,e,0,r,0,0,e,0,0,r,0,e,0,0,0,1,0]}function am(r){let e=1-r;return[r+e*.2126,e*.7152,e*.0722,0,0,e*.2126,r+e*.7152,e*.0722,0,0,e*.2126,e*.7152,r+e*.0722,0,0,0,0,0,1,0]}function Lk(r){let e=r*Math.PI/180,t=Math.cos(e),n=Math.sin(e);return[.2126+t*(1-.2126)+n*-.2126,.7152+t*-.7152+n*-.7152,.0722+t*-.0722+n*(1-.0722),0,0,.2126+t*-.2126+n*.143,.7152+t*(1-.7152)+n*.14,.0722+t*-.0722+n*-.283,0,0,.2126+t*-.2126+n*-(1-.2126),.7152+t*-.7152+n*.7152,.0722+t*(1-.0722)+n*.0722,0,0,0,0,0,1,0]}function Uk(r){return[1,0,0,0,r*.1,0,1,0,0,0,0,0,1,0,-r*.1,0,0,0,1,0]}function Nk(r){return[1,0,0,0,r*.05,0,1,0,0,-r*.1,0,0,1,0,r*.05,0,0,0,1,0]}function zk(r){let e=1-.2*r,t=.2*r;return[e,0,0,0,t,0,e,0,0,t,0,0,e,0,t,0,0,0,1,0]}function Vk(r){let e=1+.2*r,t=-.1*r;return[e,0,0,0,t,0,e,0,0,t,0,0,e,0,t,0,0,0,1,0]}var om={type:"colorAdjustment",makeImageFilter(r,e){let t=Rk(),n=!1,i=g=>{t=Bk(g,t),n=!0},s=r.brightness??0;s!==0&&i(Dk(s));let a=r.contrast??1;a!==1&&i(Ok(a));let o=r.saturation??1;o!==1&&i(am(o));let c=((r.hue??0)%360+360)%360;c!==0&&i(Lk(c));let l=r.vibrance??0;l!==0&&i(am(1+l*.7));let u=r.temperature??0;u!==0&&i(Uk(u));let d=r.tint??0;d!==0&&i(Nk(d));let h=r.shadows??0;h!==0&&i(zk(h));let f=r.highlights??0;if(f!==0&&i(Vk(f)),!n)return null;let p=e.ColorFilter.MakeMatrix(t),m=e.ImageFilter.MakeColorFilter(p,null);return p.delete(),m}};var Wk=new Set(["motionBlurResolved"]),Jr=new Map;function qk(r){if(Wk.has(r.type))return;let e=n=>Hk({type:r.type,mode:n});(e("foreground")==="shader"||e("backdrop")==="shader")&&!r.makeShader&&console.warn(`[motionscript] Effect '${r.type}' declares surface 'shader' in core but its renderer handler has no makeShader() \u2014 it will never render.`),r.makeShader&&!r.sampling&&console.warn(`[motionscript] Effect handler '${r.type}' has makeShader() but no sampling mode.`)}function Gk(r,e,t){return r==null||e.clip!==!0?r:t.ImageFilter.MakeBlend(t.BlendMode.SrcIn,null,r)??r}var Se={register(r){qk(r),Jr.set(r.type,r)},alias(r,e){let t=Jr.get(e);if(!t)throw new Error(`Cannot alias "${r}" to unregistered effect "${e}".`);Jr.set(r,t)},get(r){return Jr.get(r)},has(r){return Jr.has(r)},makeImageFilter(r,e,t){let n=Jr.get(r.type);return n?.makeImageFilter?n.makeImageFilter(r,e,t):null},compose(r,e,t){let n=null;for(let i of r){let s=Gk(this.makeImageFilter(i,e,t),i,e);s!=null&&(n=n===null?s:e.ImageFilter.MakeCompose(s,n))}return n},resolveShader(r,e){let t=Jr.get(r.type);if(t?.makeShader&&!(t.handles&&!t.handles(r,e)))return t},isShaderEffect(r,e){return this.resolveShader(r,e)!==void 0},disposeAll(){for(let r of Jr.values())r.dispose?.()}};Se.register(Zh);Se.register(Jh);Se.register(ef);Se.register(tf);Se.register(rf);Se.register(nf);Se.register(sf);Se.register(af);Se.register(cf);Se.register(uf);Se.register(gf);Se.register(yf);Se.register(wf);Se.register(bf);Se.register(kf);Se.register(Sf);Se.register(xf);Se.register(Tf);Se.register(Af);Se.register(vf);Se.register(_f);Se.register(Cf);Se.register(Ef);Se.register(Mf);Se.register(Ff);Se.register(Rf);Se.register(Bf);Se.register(Lf);Se.register(qf);Se.register(Gf);Se.register(Kf);Se.register($f);Se.register(Xf);Se.register(Qf);Se.register(Yf);Se.register(Zf);Se.register(tm);Se.register(mf);Se.alias("sksl","shader");Se.register(pf);Se.register(rm);Se.register(nm);Se.register(im);Se.register(sm);Se.register(om);function cm(r,e,t,n,i){if(!r||!(t>0)||!(n>0))return;let s=Math.max(t,n),a=e[0],o=e[1],c=e[3],l=e[4],u=r[6]??0,d=r[7]??0,h=r[8]??1,f=u!==0||d!==0||h!==1,p=0;if(f&&i){let m=[i.left,i.top,i.right,i.top,i.left,i.bottom,i.right,i.bottom];for(let g=0;g<8;g+=2){let y=jk(r,m[g],m[g+1]);y&&(p=Math.max(p,io(y[0]*a+y[1]*c,y[0]*o+y[1]*l,y[2]*a+y[3]*c,y[2]*o+y[3]*l)))}}if(p===0){let m=r[0],g=r[1],y=r[3],b=r[4],k=f&&h!==0?Math.abs(h):1;p=io((m*a+g*c)/k,(m*o+g*l)/k,(y*a+b*c)/k,(y*o+b*l)/k)}if(!(!Number.isFinite(p)||p<=0))return p*s}function jk(r,e,t){let n=r[6]*e+r[7]*t+r[8];if(!(n>1e-9))return null;let i=(r[0]*e+r[1]*t+r[2])/n,s=(r[3]*e+r[4]*t+r[5])/n;return[(r[0]-i*r[6])/n,(r[1]-i*r[7])/n,(r[3]-s*r[6])/n,(r[4]-s*r[7])/n]}function io(r,e,t,n){let i=r*r+e*e+t*t+n*n,s=r*n-e*t,a=Math.sqrt(Math.max(0,i*i-4*s*s));return Math.sqrt((i+a)/2)}function so(r,e,t,n,i){let s=n>0?e/n:1,a=i>0?t/i:1;return s===1&&a===1?r:[r[0]*s,r[1]*a,r[2],r[3]*s,r[4]*a,r[5],r[6]*s,r[7]*a,r[8]]}function lm(r,e){return e!==void 0&&e>0&&r/e>Math.SQRT2}var ao=class extends qe{applyPaint(e,t){if(!e.src)return Za(t);let n=t.getShapeBounds(),i=t.assets.getImageSize(e.src),s=i?Kl(e,i,n,t):void 0,a=t.assets.getCKImage(e.src,s);if(!a)throw new Kk("image",e.src);let o=Es(a,e,t.canvasKit,n,oo(e),{logical:i,footprint:s,mipmaps:!0});return t.transientPaintObjects.push(o),t.paint.setShader(co(e,t,o)),!0}dispose(){Yh()}};function Xk(r,e){return{centerX:r?(r.left+r.right)/2:0,centerY:r?(r.top+r.bottom)/2:0,width:r?r.right-r.left:0,height:r?r.bottom-r.top:0,scale:1,time:e,velocity:{x:0,y:0},angularVelocity:0}}function Qk(r,e){let t=e.getDeviceMatrix(),n=t?io(t[0],t[1],t[3],t[4]):1;return{...r,width:r.width*n,height:r.height*n,scale:n}}function Kl(r,e,t,n){let i=lo(e.width,e.height,r,t);return cm(n.getDeviceMatrix(),i,e.width,e.height,t)}function oo(r){for(let e of r.preset?.adjustments??[]){let t=Se.resolveShader(e,"foreground");if(t)return t.sampling?.filterMode}}function co(r,e,t){let n=r.preset?.intensity??1,i=(r.preset?.adjustments??[]).filter(d=>$k(d.type));if(i.length===0||n<=0)return e.paint.setImageFilter(null),t;let s=Xk(e.getShapeBounds(),e.elapsed),a=[],o=t,c;for(let d of i){let h=Se.resolveShader(d,"foreground");if(!h){a.push(d);continue}let f=e.effectResources();f&&h.resources&&(c??=Qk(s,e));let p=(f&&h.resources?.(d,e.canvasKit,f,c))??[],m=h.makeShader(d,e.canvasKit,o,s,p);m&&(e.transientPaintObjects.push(m),o=m)}if(n<1&&o!==t){let d=Yk(t,o,n,e);d&&(e.transientPaintObjects.push(d),o=d)}let l=a.length>0?Se.compose(a,e.canvasKit,s):null;l&&e.transientPaintObjects.push(l);let u=n<1&&l?Jk(l,n,e):l;return u&&u!==l&&e.transientPaintObjects.push(u),e.paint.setImageFilter(u),e.clipFilterToShape=u!=null,o}function Yk(r,e,t,n){let i=ue(Zk,n.canvasKit);return i?i.makeShaderWithChildren([t],[r,e]):null}var Zk=`
|
|
1808
1662
|
uniform shader u_dry;
|
|
1809
1663
|
uniform shader u_wet;
|
|
1810
1664
|
uniform float u_t;
|
|
@@ -1812,8 +1666,8 @@ uniform float u_t;
|
|
|
1812
1666
|
vec4 main(vec2 p) {
|
|
1813
1667
|
return mix(u_dry.eval(p), u_wet.eval(p), u_t);
|
|
1814
1668
|
}
|
|
1815
|
-
`;function
|
|
1816
|
-
`?T-1:T;g=T;let _=b.baseline-b.ascent+f,M=b.baseline+b.descent+f,P=[];for(let A=k;A<S;A++)P.push(om(o,r,A,!1)+h);P.push(S>k?om(o,r,S-1,!0)+h:b.left+h),m.push({start:k,end:S,top:_,bottom:M,carets:P})}return o.delete(),c.delete(),l.delete(),m.length===0?null:{lines:m,width:u,height:d}}function om(r,e,t,n){let s=r.getRectsForRange(t,t+1,e.RectHeightStyle.Max,e.RectWidthStyle.Tight)[0]?.rect;return s?n?s[2]:s[0]:0}function Xk(r,e){let t=e.boxHeight??0;if(t<=0)return 0;switch(e.verticalAlign){case"top":return(r-t)/2;case"bottom":return(t-r)/2;default:return 0}}function Qk(r,e,t,n,i){let s=!0;for(let a=r.length-1;a>=e;a--){let o=r[a],c=t[a-e],l=o.glyphs.length;if(s){for(;l>0&&/\s/.test(n[c[l-1]]??"");)l--;l>0&&(s=!1)}let u=i[o.segmentIndex];l===0||u.decoration===void 0||u.decoration==="none"||(o.decoration=Yk(o,l,u.fontSize,u.decoration))}}function Yk(r,e,t,n){let i=r.font.getMetrics(),s=r.font.getGlyphWidths(r.glyphs.subarray(0,e)),a=r.positions[0],o=r.positions[(e-1)*2]+s[e-1],c=r.positions[1];if(n==="underline"){let d=$l(i.underlineThickness)??t/14,h=c+($l(i.underlinePosition)??d);return{left:a,top:h,right:o,bottom:h+d}}let l=$l(i.strikeoutThickness)??t/14,u=c+(i.strikeoutPosition!==void 0&&i.strikeoutPosition<0?i.strikeoutPosition:-t*.26);return{left:a,top:u-l/2,right:o,bottom:u+l/2}}function $l(r){return r!==void 0&&r>0?r:void 0}function Xl(r,e,t){for(let n=0;n<e.length;n++){let i=e[n].text.length;if(i>0&&t>=r[n]&&t<r[n]+i)return n}for(let n=e.length-1;n>=0;n--)if(e[n].text.length>0)return n;return 0}function Ql(r,e,t){Yl(r,e,0,0,t)}function Yl(r,e,t,n,i){r.drawGlyphs(e.glyphs,e.positions,t,n,e.font,i);let s=e.decoration;s&&r.drawRect(Float32Array.of(s.left+t,s.top+n,s.right+t,s.bottom+n),i)}function lm(r,e,t){let{spans:n,lineHeight:i,textAlign:s,width:a}=t,o=n.map(u=>({text:u.text,fontFamily:u.fontFamily,fontSize:u.fontSize,fontWeight:u.fontWeight,fontStyle:u.fontStyle,letterSpacing:u.letterSpacing})),c=Tr(r,e,o,{textAlign:s,lineHeight:i,maxWidth:a>0?a:1/0,boxWidth:a,originX:0,originY:0});return{runs:c.runs.map(u=>({...u,span:n[u.segmentIndex]})),bounds:c.bounds,fonts:c.fonts}}import{withTextDescriptor as gm,isStyleOnlySegment as dx,resolveShapePivot as hx}from"@motionscript/core";import{AUTOFIT_PROBE_SIZE as Zk,withTextDescriptor as Jk}from"@motionscript/core";function Zl(r){let e=r.fontSize==="autofit"?Zk:r.fontSize;return(r.segments??[]).map(t=>({text:t.text,fontFamily:t.fontFamily??r.fontFamily,fontSize:t.fontSize??e,fontWeight:t.fontWeight,fontStyle:t.fontStyle??r.fontStyle,letterSpacing:t.letterSpacing,decoration:t.textDecoration??r.textDecoration}))}function um(r,e,t){let n=Jk(t),i=n.segments??[],s=Zl(n),a=n.wrap&&n.width>0,o=Tr(r,e,s,{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:a?n.width:1/0,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:n.x,originY:n.y});return{runs:o.runs.map(l=>({...l,segment:i[l.segmentIndex]})),bounds:o.bounds,fonts:o.fonts}}function dm(r){let e=r.positions;if(e.length===0)return{x:0,y:0};let t=1/0,n=-1/0,i=1/0,s=-1/0;for(let a=0;a<e.length;a+=2){let o=e[a],c=e[a+1];o<t&&(t=o),o>n&&(n=o),c<i&&(i=c),c>s&&(s=c)}return{x:(t+n)/2,y:(i+s)/2}}import{withTextDescriptor as ex,pathOps as tx}from"@motionscript/core";function rx(r,e){switch(e){case"italic":return r.FontSlant.Italic;case"oblique":return r.FontSlant.Oblique;default:return r.FontSlant.Upright}}function nx(r,e,t){switch(r){case"right":case"end":return t-e;case"center":return(t-e)/2;default:return 0}}var ix=64,Jr=new Map;function sx(r,e){return[r.text,r.fontFamily,e,r.fontWeight,r.fontStyle,r.letterSpacing,r.lineHeight].join("")}function ax(r,e,t,n){let i=sx(t,n),s=Jr.get(i);if(s)return Jr.delete(i),Jr.set(i,s),s.run;let a=ox(r,e,t,n);if(!a)return null;if(Jr.set(i,{run:a.run,fonts:a.fonts}),Jr.size>ix){let o=Jr.keys().next().value;if(o!==void 0){let c=Jr.get(o);if(Jr.delete(o),c)for(let l of c.fonts)l.delete()}}return a.run}function ox(r,e,t,n){let i=[],s=r.FontCollection.Make();s.setDefaultFontManager(e);let a=new r.ParagraphStyle({textStyle:{fontFamilies:[t.fontFamily],fontSize:n},textAlign:r.TextAlign.Left}),o=r.ParagraphBuilder.MakeFromFontCollection(a,s);o.pushStyle(new r.TextStyle({fontFamilies:[t.fontFamily],fontSize:n,fontStyle:{weight:{value:t.fontWeight},slant:rx(r,t.fontStyle)},fontVariations:[{axis:"wght",value:t.fontWeight}],letterSpacing:t.letterSpacing,heightMultiplier:t.lineHeight})),o.addText(t.text.replace(/\s*\n\s*/g," ")),o.pop();let c=o.build();c.layout(1e7);let l=new Map,u=m=>{let g=`${t.fontFamily}@${t.fontWeight}@${t.fontStyle}@${n}`,y=l.get(g);if(y)return m?.delete(),y;let b=hi(r,m,n);return m?.delete(),l.set(g,b),i.push(b),b},h=c.getShapedLines()[0];if(!h){c.delete(),o.delete(),s.delete();for(let m of i)m.delete();return null}let f=0;for(let m of h.runs){let g=m.glyphs.length;g>0&&(f=Math.max(f,m.positions[g*2]))}let p=[];for(let m of h.runs){let g=m.glyphs.length;if(g===0)continue;let y=u(m.typeface);for(let b=0;b<g;b++){let k=m.positions[b*2],T=m.positions[(b+1)*2]-k,S=k+T/2,_=m.positions[b*2+1]-h.baseline;p.push({glyphId:m.glyphs[b],midX:S,advance:T,perp:_,font:y})}}return c.delete(),o.delete(),s.delete(),{run:{glyphs:p,textWidth:f,fontSize:n},fonts:i}}function cx(r,e,t){let n={glyphs:[],bounds:{left:0,top:0,right:0,bottom:0}},i=tx.sampler(e);if(i.length<=0)return n;let s=nx(t,r.textWidth,i.length),a=[],o=1/0,c=1/0,l=-1/0,u=-1/0,d=(p,m)=>{p<o&&(o=p),p>l&&(l=p),m<c&&(c=m),m>u&&(u=m)};for(let p of r.glyphs){let m=p.midX+s;if(m<0||m>i.length)continue;let g=i.frameAt(m);if(!g)continue;let y=g.x+p.perp*-g.ty,b=g.y+p.perp*g.tx,k=Math.atan2(g.ty,g.tx)*180/Math.PI;a.push({glyphId:p.glyphId,x:y,y:b,angle:k,halfAdvance:p.advance/2,font:p.font}),d(y,b)}let h=r.fontSize,f=a.length>0?{left:o-h,top:c-h,right:l+h,bottom:u+h}:{left:0,top:0,right:0,bottom:0};return{glyphs:a,bounds:f}}function hm(r,e,t){let n=ex(t),i={glyphs:[],bounds:{left:0,top:0,right:0,bottom:0}};if(n.text.length===0||n.path==null)return i;let s=n.fontSize==="autofit"?100:n.fontSize,a=ax(r,e,n,s);return a?cx(a,n.path,n.textAlign):i}function fm(r,e,t){for(let n of e)r.save(),r.translate(n.x,n.y),n.angle!==0&&r.rotate(n.angle,0,0),r.drawGlyphs([n.glyphId],new Float32Array([-n.halfAdvance,0]),0,0,n.font,t),r.restore()}var lx={width:0,height:0},ux="";function Jl(r,e){return[r.text,r.fontFamily,r.fontSize,r.fontWeight,r.fontStyle,r.letterSpacing,r.decoration,r.lineHeight,r.textAlign,r.verticalAlign,r.maxWidth,r.boxWidth,r.boxHeight,e].join(ux)}var ho=class{limit;map=new Map;constructor(e=256){this.limit=e}get(e,t){let n=this.map.get(e);if(n)return this.map.delete(e),this.map.set(e,n),n;let i={layout:t()};if(this.map.set(e,i),this.map.size>this.limit){let s=this.map.keys().next().value;if(s!==void 0){let a=this.map.get(s);if(this.map.delete(s),a)for(let o of a.layout.fonts)o.delete()}}return i}dispose(){for(let e of this.map.values())for(let t of e.layout.fonts)t.delete();this.map.clear()}};function eu(r,e,t,n,i,s=0,a="center"){return{text:r.text,fontFamily:r.fontFamily,fontSize:r.fontSize,fontWeight:r.fontWeight,fontStyle:r.fontStyle,letterSpacing:r.letterSpacing,decoration:r.decoration??"none",lineHeight:t,textAlign:e,verticalAlign:a,maxWidth:n,boxWidth:i,boxHeight:a==="center"?0:s}}var mm="center",pm=1;function fo(r,e,t,n,i,s,a,o,c,l){if(i.length===0)return lx;let u={text:i,fontFamily:a,fontSize:s,fontWeight:o,fontStyle:l,letterSpacing:c},d=Jl(eu(u,mm,pm,1/0,0),n),{layout:h}=t.get(d,()=>Tr(r,e,[u],{textAlign:mm,lineHeight:pm,maxWidth:1/0,originX:0,originY:0}));return{width:h.width,height:h.height}}function fx(r,e,t,n,i){let s=n*Math.PI/180,a=Math.cos(s),o=Math.sin(s),c=[{x:r.left,y:r.top},{x:r.right,y:r.top},{x:r.right,y:r.bottom},{x:r.left,y:r.bottom}],l=1/0,u=1/0,d=-1/0,h=-1/0;for(let f of c){let p=(f.x-e)*i,m=(f.y-t)*i,g=e+p*a-m*o,y=t+p*o+m*a;g<l&&(l=g),g>d&&(d=g),y<u&&(u=y),y>h&&(h=y)}return{left:l,top:u,right:d,bottom:h}}function ym(r,e,t){let n=t.fontSize==="autofit",i=n?100:t.fontSize,s=t.wrap&&t.width>0,a=o=>({text:t.text,fontFamily:t.fontFamily,fontSize:o,fontWeight:t.fontWeight,fontStyle:t.fontStyle,letterSpacing:t.letterSpacing,decoration:t.textDecoration});if(n&&t.width>0&&t.height>0){let o=Tr(r,e,[a(i)],{textAlign:t.textAlign,lineHeight:t.lineHeight,maxWidth:1/0,originX:t.x,originY:t.y}),c=o.width>0?t.width/o.width:1,l=o.height>0?t.height/o.height:1,u=i*Math.min(c,l);for(let d of o.fonts)d.delete();s&&u<t.minFontSize?i=t.minFontSize:(i=u,s=!1)}return{segment:a(i),maxWidth:s?t.width:1/0}}function mo(r,e,t){let n=gm(t);if(n.path!=null)return null;let i=n.segments??[];if(i.length>0){if(!i.every(dx))return null;let o=n.wrap&&n.width>0;return uo(r,e,Zl(n),{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:o?n.width:1/0,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:0,originY:0})}let{segment:s,maxWidth:a}=ym(r,e,n);return uo(r,e,s,{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:a,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:0,originY:0})}function wm(r,e,t,n,i,s){let a=gm(n);if(a.path!=null){let F=hm(r,t,n);return{bounds:F.bounds,draw:I=>fm(e,F.glyphs,I)}}let o=a.x,c=a.y,{segment:l,maxWidth:u}=ym(r,t,a),d=Jl(eu(l,a.textAlign,a.lineHeight,u,a.width,a.height,a.verticalAlign),s),{layout:h}=i.get(d,()=>Tr(r,t,[l],{textAlign:a.textAlign,lineHeight:a.lineHeight,maxWidth:u,boxWidth:a.width,boxHeight:a.height,verticalAlign:a.verticalAlign,originX:0,originY:0})),f=hx(a.pivot),p=a.width>0&&a.height>0,m=p?a.width:h.width,g=p?a.height:h.height,y=!p&&f.x!==0?o-f.x*(h.width/2):o,b=!p&&f.y!==0?c+f.y*(h.height/2):c,k=h.bounds,T={left:k.left+y,top:k.top+b,right:k.right+y,bottom:k.bottom+b},S=a.rotation,_=a.scale,M=S!==0||_!==1,P=y+f.x*(m/2),A=b-f.y*(g/2);return M&&(T=fx(T,P,A,S,_)),{bounds:T,isText:!0,draw:F=>{M&&e.save();try{M&&(e.translate(P,A),e.rotate(S,0,0),e.scale(_,_),e.translate(-P,-A));for(let I of h.runs)Yl(e,I,y,b,F)}finally{M&&e.restore()}}}}import{cornerRadiusOps as tu,cornerStyleOps as mx,withRectDescriptor as px}from"@motionscript/core";function Pn(r,e,t,n){let i=0,s=new r.ContourMeasureIter(e,!1,1),a=s.next();for(;a;)i+=a.length(),a.delete(),a=s.next();if(s.delete(),i<=0)return e.copy();let o=t*i,c=n*i,l=[];s=new r.ContourMeasureIter(e,!1,1);let u=0;for(a=s.next();a;){let h=a.length(),f=u,p=u+h;if(p>o&&f<c){let m=Math.max(0,o-f),g=Math.min(h,c-f);l.push(a.getSegment(m,g,!0))}u=p,a.delete(),a=s.next()}if(s.delete(),l.length===0)return r.Path.MakeFromSVGString("M 0 0")??e.copy();if(l.length===1)return l[0];let d=l.map(h=>h.toSVGString());return l.forEach(h=>h.delete()),r.Path.MakeFromSVGString(d.join(" "))??e.copy()}var Tt=class{canvasKit;fullState;inputState;ckPath;_basePath;_geo;getCanvas;get canvas(){return this.getCanvas()}constructor(e,t,n){this.canvasKit=e,this.getCanvas=t,this.inputState=n,this.fullState=this.resolveState(n)}buildSVGAlignInterior(e){return null}_alignInterior;_alignInteriorBuilt=!1;strokeAlignInterior(){if(!this._alignInteriorBuilt){this._alignInteriorBuilt=!0;let e=this.buildSVGAlignInterior(this.geometry);if(e!=null){let t=this.canvasKit.Path.MakeFromSVGString(e);this._alignInterior=t?this.applyShapeTransform(t):void 0}}return this._alignInterior??(this.needsTrim()?this._basePath:void 0)}buildSpreadSVGPath(e,t){return null}hasTrim(){return this.needsTrim()}trimRange(){return this.getTrimRange()}hasShapeTransform(){let e=this.fullState;return(e.rotation??0)!==0||(e.scale??1)!==1}get geometry(){return this._geo??=this.computeGeometry()}ensurePath(){if(this.ckPath)return;let e=this.buildSVGPath(this.geometry),t=this.canvasKit.Path.MakeFromSVGString(e);if(!t){console.warn(`${this.constructor.name}: failed to create path`);return}let n=this.applyShapeTransform(t);if(this.needsTrim()){this._basePath=n;let{start:i,end:s}=this.getTrimRange();this.ckPath=Pn(this.canvasKit,n,i,s)}else this.ckPath=n}applyShapeTransform(e,t){let n=this.fullState,i=n.rotation??0,s=n.scale??1;if(i===0&&s===1)return e;let a=t?t.x:n.x??0,o=t?t.y:n.y??0,c=n.pivot??{x:0,y:0},l=a+c.x*((n.width??0)/2),u=o-c.y*((n.height??0)/2),d=i*Math.PI/180,h=Math.cos(d),f=Math.sin(d),p=h*s,m=-f*s,g=f*s,y=h*s,b=l-p*l-m*u,k=u-g*l-y*u,T=new this.canvasKit.PathBuilder(e);T.transform(p,m,b,g,y,k,0,0,1);let S=T.detachAndDelete();return e.delete(),S}spreadPath(e){let t=this.buildSpreadSVGPath(this.geometry,e);if(t==null)return null;let n=this.canvasKit.Path.MakeFromSVGString(t);return n?this.applyShapeTransform(n):null}_setBasePath(e){this._basePath=e}paintBounds(){if(!this._basePath)return;let e=this._basePath.getBounds();return{left:e[0],top:e[1],right:e[2],bottom:e[3]}}retrim(e,t){let n=this._basePath;if(!n)return;let i=this.fullState;i.start=e,i.end=t,this.ckPath?.delete(),this.ckPath=Pn(this.canvasKit,n,e,t),this._strokePath?.delete(),this._strokePath=void 0,this._strokePathBuilt=!1}_strokePath;_strokePathBuilt=!1;strokePath(){return this._strokePathBuilt||(this._strokePathBuilt=!0,this.ensurePath(),this._strokePath=this.ckPath?this.buildStrokePath(this.ckPath):void 0),this._strokePath}buildStrokePath(e){}deletePaths(){this.ckPath?.delete(),this.ckPath=void 0,this._basePath?.delete(),this._basePath=void 0,this._alignInterior?.delete(),this._alignInterior=void 0,this._alignInteriorBuilt=!1,this._strokePath?.delete(),this._strokePath=void 0,this._strokePathBuilt=!1}draw(e,t){this.ensurePath(),this.ckPath&&this.canvas.drawPath(this.ckPath,e)}strokeDraw(e){let t=this.strokePath()??this.ckPath;t&&this.canvas.drawPath(t,e)}clip(e){this.ensurePath(),this.ckPath&&this.canvas.clipPath(this.ckPath,this.canvasKit.ClipOp.Intersect,!0)}supportsSpread(){return!1}toCurrentShape(e){let t=this;return{draw:n=>t.draw(n,e),strokeDraw:n=>t.strokeDraw(n),get ckPath(){return t.ckPath},get strokePath(){return t.strokePath()},get alignInterior(){return t.strokeAlignInterior()},get paintBounds(){return t.paintBounds()},trimmed:this.needsTrim(),bounds:this.computeBounds(this.geometry),spreadPath:this.supportsSpread()?n=>t.spreadPath(n):void 0}}computeBounds(e){}};function vr(r){return r.radius>0?r.radius:0}function Es(r,e,t,n,i,s,a){return a.radius<=0?"":Is(r,e,t,n,i,s,a.radius,a.radius,a.style)}function Is(r,e,t,n,i,s,a,o,c){let l=r+i*a,u=e+s*a;if(c==="angled")return`L ${l} ${u}`;let h=t*s-n*i<0?1:0;return`A ${o} ${o} 0 0 ${h} ${l} ${u}`}function bm(r,e,t,n,i,s,a,o){let c=vr(i),l=vr(s),u=vr(a),d=vr(o);return[`M ${r+c} ${e}`,`L ${t-l} ${e}`,Es(t,e,-1,0,0,1,s),`L ${t} ${n-u}`,Es(t,n,0,-1,-1,0,a),`L ${r+d} ${n}`,Es(r,n,1,0,0,-1,o),`L ${r} ${e+c}`,Es(r,e,0,1,1,0,i),"Z"].filter(Boolean).join(" ")}var pi=class extends Tt{resolveState(e){return px(e)}computeGeometry(){let e=this.fullState,t=e.width/2,n=e.height/2,i=e.x-t,s=e.y-n,a=e.x+t,o=e.y+n,c=tu.resolve(e.cornerRadius),l=mx.resolve(e.cornerStyle),u={radius:Math.max(0,c.topLeft),style:l.topLeft},d={radius:Math.max(0,c.topRight),style:l.topRight},h={radius:Math.max(0,c.bottomRight),style:l.bottomRight},f={radius:Math.max(0,c.bottomLeft),style:l.bottomLeft},p=km(e.width,e.height,u,d,h,f);u.radius*=p,d.radius*=p,h.radius*=p,f.radius*=p;let m={topLeft:u.radius,topRight:d.radius,bottomRight:h.radius,bottomLeft:f.radius},g=l.topLeft==="rounded"&&l.topRight==="rounded"&&l.bottomRight==="rounded"&&l.bottomLeft==="rounded";return{left:i,top:s,right:a,bottom:o,tl:u,tr:d,br:h,bl:f,isZero:tu.isZero(m),isUniform:tu.isUniform(m),isPlainRounded:g}}buildSVGPath(e){let{left:t,top:n,right:i,bottom:s,tl:a,tr:o,br:c,bl:l,isZero:u}=e;return u?`M ${t} ${n} L ${i} ${n} L ${i} ${s} L ${t} ${s} Z`:bm(t,n,i,s,a,o,c,l)}hasCornerRadius(){return!this.geometry.isZero}supportsSpread(){return!0}buildSpreadSVGPath(e,t){let n=e.left-t,i=e.top-t,s=e.right+t,a=e.bottom+t,o=s-n,c=a-i;if(o<=0||c<=0)return null;let l={...e.tl,radius:Math.max(0,e.tl.radius+t)},u={...e.tr,radius:Math.max(0,e.tr.radius+t)},d={...e.br,radius:Math.max(0,e.br.radius+t)},h={...e.bl,radius:Math.max(0,e.bl.radius+t)},f=km(o,c,l,u,d,h);return l.radius*=f,u.radius*=f,d.radius*=f,h.radius*=f,l.radius===0&&u.radius===0&&d.radius===0&&h.radius===0?`M ${n} ${i} L ${s} ${i} L ${s} ${a} L ${n} ${a} Z`:bm(n,i,s,a,l,u,d,h)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}draw(e,t){let n=this.geometry;if(t&&!this.needsTrim()&&!this.hasShapeTransform()){let i=this.canvasKit,s=i.LTRBRect(n.left,n.top,n.right,n.bottom);if(n.isZero){this.canvas.drawRect(s,e);return}if(n.isUniform&&n.isPlainRounded){this.canvas.drawRRect(i.RRectXY(s,n.tl.radius,n.tl.radius),e);return}}super.draw(e,t)}clip(e){let t=this.geometry,n=this.canvasKit;if(e&&!this.needsTrim()&&!this.hasShapeTransform()){let i=n.LTRBRect(t.left,t.top,t.right,t.bottom);if(t.isZero){this.canvas.clipRect(i,n.ClipOp.Intersect,!0);return}if(t.isUniform&&t.isPlainRounded){this.canvas.clipRRect(n.RRectXY(i,t.tl.radius,t.tl.radius),n.ClipOp.Intersect,!0);return}}super.clip(e)}};function km(r,e,t,n,i,s){let a=vr(t),o=vr(n),c=vr(i),l=vr(s),u=a+o>0?Math.min(1,r/(a+o)):1,d=l+c>0?Math.min(1,r/(l+c)):1,h=a+l>0?Math.min(1,e/(a+l)):1,f=o+c>0?Math.min(1,e/(o+c)):1;return Math.min(u,d,h,f)}import{withEllipseDescriptor as gx}from"@motionscript/core";var en=Math.PI/180,gi=class extends Tt{resolveState(e){return gx(e)}computeGeometry(){let e=this.fullState,t=e.sweep??360;return{cx:e.x,cy:e.y,halfWidth:e.width/2,halfHeight:e.height/2,sweep:t,isFullShape:Math.abs(t)>=360,startAngle:e.startAngle??0,ratio:Math.max(0,Math.min(1,e.ratio??0))}}buildSVGPath(e){let{cx:t,cy:n,halfWidth:i,halfHeight:s,ratio:a}=e;if(a>=1)return"";if(!e.isFullShape)return a<=0?xm(e):Sm(e);let o=Ms(t,n,i,s,0);return a<=0?o:`${o} ${Ms(t,n,i*a,s*a,1)}`}buildSVGAlignInterior(e){return e.isFullShape?e.ratio>=1?Ms(e.cx,e.cy,e.halfWidth,e.halfHeight,0):null:e.ratio>=1||e.ratio<=0?xm(e):Sm(e)}buildStrokePath(e){let t=this._outline();if(!t)return;if(!this.needsTrim())return t.copy();let{start:n,end:i}=this.getTrimRange();return Pn(this.canvasKit,t,n,i)}paintBounds(){let e=this._outline();if(!e)return super.paintBounds();let[t,n,i,s]=e.getBounds();return{left:t,top:n,right:i,bottom:s}}deletePaths(){super.deletePaths(),this._outlinePath?.delete(),this._outlinePath=void 0,this._outlineBuilt=!1}supportsSpread(){return!0}buildSpreadSVGPath(e,t){if(!e.isFullShape||e.ratio>=1)return null;let n=e.halfWidth+t,i=e.halfHeight+t;return n<=0||i<=0?null:Ms(e.cx,e.cy,n,i,0)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){let{cx:t,cy:n,halfWidth:i,halfHeight:s}=e;return{left:t-i,top:n-s,right:t+i,bottom:n+s}}_outlinePath;_outlineBuilt=!1;_outline(){if(!this._outlineBuilt){this._outlineBuilt=!0;let e=this.geometry;if(e.ratio>=1){let t=e.isFullShape?Ms(e.cx,e.cy,e.halfWidth,e.halfHeight,0):yx(e),n=this.canvasKit.Path.MakeFromSVGString(t);this._outlinePath=n?this.applyShapeTransform(n):void 0}}return this._outlinePath}};function Ms(r,e,t,n,i){let s=r-t,a=r+t;return`M ${s} ${e} A ${t} ${n} 0 1 ${i} ${a} ${e} A ${t} ${n} 0 1 ${i} ${s} ${e} Z`}function ru(r){let{cx:e,cy:t,halfWidth:n,halfHeight:i,startAngle:s,sweep:a}=r,o=s+a,c=Math.abs(a)>180?1:0,l=a>0?1:0,u=e+n*Math.cos(s*en),d=t+i*Math.sin(s*en),h=e+n*Math.cos(o*en),f=t+i*Math.sin(o*en);return{start:`${u} ${d}`,arc:`A ${n} ${i} 0 ${c} ${l} ${h} ${f}`}}function yx(r){let{start:e,arc:t}=ru(r);return`M ${e} ${t}`}function xm(r){let{start:e,arc:t}=ru(r);return`M ${r.cx} ${r.cy} L ${e} ${t} Z`}function Sm(r){let{cx:e,cy:t,halfWidth:n,halfHeight:i,startAngle:s,sweep:a,ratio:o}=r,{start:c,arc:l}=ru(r),u=s+a,d=n*o,h=i*o,f=e+d*Math.cos(s*en),p=t+h*Math.sin(s*en),m=e+d*Math.cos(u*en),g=t+h*Math.sin(u*en),y=Math.abs(a)>180?1:0,b=a>0?0:1;return`M ${c} ${l} L ${m} ${g} A ${d} ${h} 0 ${y} ${b} ${f} ${p} Z`}import{withPolygonDescriptor as wx}from"@motionscript/core";function bx(r,e,t,n,i,s,a){let o=2*Math.PI/i,c=-Math.PI/2,l=[];for(let d=0;d<i;d++){let h=c+d*o;l.push([r+t*Math.cos(h),e+n*Math.sin(h)])}if(s<=0){let d=l.map(([h,f],p)=>`${p===0?"M":"L"} ${h} ${f}`);return d.push("Z"),d.join(" ")}let u=[];for(let d=0;d<i;d++){let h=l[(d-1+i)%i],f=l[d],p=l[(d+1)%i],m=h[0]-f[0],g=h[1]-f[1],y=Math.hypot(m,g),b=m/y,k=g/y,T=p[0]-f[0],S=p[1]-f[1],_=Math.hypot(T,S),M=T/_,P=S/_,A=Math.max(-1,Math.min(1,b*M+k*P)),F=Math.acos(A)/2,I=Math.tan(F),O=Math.min(y,_)/2,Q=s/I;Q>O&&(Q=O);let ge=Q*I,be=f[0]+b*Q,J=f[1]+k*Q;u.push(`${u.length===0?"M":"L"} ${be} ${J}`),u.push(Is(f[0],f[1],b,k,M,P,Q,ge,a))}return u.push("Z"),u.join(" ")}var yi=class extends Tt{resolveState(e){return wx(e)}computeGeometry(){let e=this.fullState;return{cx:e.x,cy:e.y,rx:e.width/2,ry:e.height/2,sides:Math.max(3,Math.round(e.sides)),cornerRadius:e.cornerRadius,cornerStyle:e.cornerStyle}}buildSVGPath(e){return bx(e.cx,e.cy,e.rx,e.ry,e.sides,e.cornerRadius,e.cornerStyle)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.cx-e.rx,top:e.cy-e.ry,right:e.cx+e.rx,bottom:e.cy+e.ry}}};import{withPolygramDescriptor as kx}from"@motionscript/core";function xx(r,e,t,n,i,s,a,o){let c=i*2,l=Math.PI/i,u=-Math.PI/2,d=[];for(let f=0;f<c;f++){let p=u+f*l,g=f%2===0?1:s;d.push([r+t*g*Math.cos(p),e+n*g*Math.sin(p)])}if(a<=0){let f=d.map(([p,m],g)=>`${g===0?"M":"L"} ${p} ${m}`);return f.push("Z"),f.join(" ")}let h=[];for(let f=0;f<c;f++){let p=d[f];if(!(f%2===0)){h.push(`${h.length===0?"M":"L"} ${p[0]} ${p[1]}`);continue}let g=d[(f-1+c)%c],y=d[(f+1)%c],b=g[0]-p[0],k=g[1]-p[1],T=Math.hypot(b,k),S=b/T,_=k/T,M=y[0]-p[0],P=y[1]-p[1],A=Math.hypot(M,P),F=M/A,I=P/A,O=Math.max(-1,Math.min(1,S*F+_*I)),Q=Math.acos(O)/2,ge=Math.tan(Q),be=Math.min(T,A)/2,J=a/ge;J>be&&(J=be);let Ae=J*ge,Re=p[0]+S*J,et=p[1]+_*J;h.push(`${h.length===0?"M":"L"} ${Re} ${et}`),h.push(Is(p[0],p[1],S,_,F,I,J,Ae,o))}return h.push("Z"),h.join(" ")}var wi=class extends Tt{resolveState(e){return kx(e)}computeGeometry(){let e=this.fullState;return{cx:e.x,cy:e.y,rx:e.width/2,ry:e.height/2,sides:Math.max(3,Math.round(e.sides)),ratio:Math.max(0,Math.min(1,e.ratio)),cornerRadius:e.cornerRadius,cornerStyle:e.cornerStyle}}buildSVGPath(e){return xx(e.cx,e.cy,e.rx,e.ry,e.sides,e.ratio,e.cornerRadius,e.cornerStyle)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.cx-e.rx,top:e.cy-e.ry,right:e.cx+e.rx,bottom:e.cy+e.ry}}};import{toPathString as Sx,withPathDescriptor as Tx}from"@motionscript/core";var bi=class extends Tt{resolveState(e){return Tx(e)}computeGeometry(){return{svgString:Sx(this.fullState.data),offsetX:0,offsetY:0}}buildSVGPath(e){return e.svgString}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}buildCenteredTransformedTrimmed(e,t,n){let i=this.canvasKit.Path.MakeFromSVGString(e);if(!i){console.warn("PathShape: failed to parse SVG path string:",e);return}let s=new this.canvasKit.PathBuilder(i);s.offset(t,n);let a=s.detachAndDelete();i.delete();let o=this.applyShapeTransform(a,{x:0,y:0});if(this.needsTrim()){this._setBasePath(o);let{start:c,end:l}=this.getTrimRange();return Pn(this.canvasKit,o,c,l)}return o}ensurePath(){if(this.ckPath)return;let e=this.geometry,t=this.canvasKit.Path.MakeFromSVGString(e.svgString);if(!t){console.warn("PathShape: failed to parse SVG path string:",e.svgString);return}let n=this.fullState.centerBounds,[i,s,a,o]=n??t.getBounds();e.offsetX=-(i+(a-i)/2),e.offsetY=-(s+(o-s)/2),t.delete(),this.ckPath=this.buildCenteredTransformedTrimmed(e.svgString,e.offsetX,e.offsetY)}draw(e,t){this.ensurePath(),this.ckPath&&this.canvas.drawPath(this.ckPath,e)}clip(e){this.ensurePath(),this.ckPath&&this.canvas.clipPath(this.ckPath,this.canvasKit.ClipOp.Intersect,!0)}};import{withLineDescriptor as vx}from"@motionscript/core";function Ax(r,e,t){if(r.length===0)return"M 0 0";if(r.length===1)return`M ${r[0].x} ${r[0].y}`;let n=Math.max(0,e),i=[],s=r.length,a=(o,c)=>{let l=c.x-o.x,u=c.y-o.y,d=Math.sqrt(l*l+u*u);return d>0?{dx:l/d,dy:u/d,len:d}:{dx:0,dy:0,len:0}};if(n===0){i.push(`M ${r[0].x} ${r[0].y}`);for(let o=1;o<s;o++)i.push(`L ${r[o].x} ${r[o].y}`)}else{let o=t?s:s-1;for(let c=0;c<=o;c++){let l=r[(c-1+s)%s],u=r[c%s],d=r[(c+1)%s];if(!t&&c===0){i.push(`M ${u.x} ${u.y}`);continue}if(!t&&c===s-1){i.push(`L ${u.x} ${u.y}`);continue}let h=a(l,u),f=a(u,d),p=Math.min(n,h.len/2),m=Math.min(n,f.len/2),g=u.x-h.dx*p,y=u.y-h.dy*p,b=u.x+f.dx*m,k=u.y+f.dy*m;c===0&&t?i.push(`M ${g} ${y}`):i.push(`L ${g} ${y}`),i.push(`Q ${u.x} ${u.y} ${b} ${k}`)}}return t&&i.push("Z"),i.join(" ")}var ki=class extends Tt{resolveState(e){return vx(e)}computeGeometry(){let{points:e,radius:t,closed:n}=this.fullState;return{points:e,radius:t,closed:n}}buildSVGPath(e){return Ax(e.points,e.radius,e.closed)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}ensurePath(){this.fullState.points.length!==0&&super.ensurePath()}};import{pathOps as Tm}from"@motionscript/core";var _x=1,Fs=.001,po=class{canvasKit;getCanvas;getPaint;fills;constructor(e,t,n,i){this.canvasKit=e,this.getCanvas=t,this.getPaint=n,this.fills=i}makeUniformDashEffect(e,t,n=0,i){let s=i??this.measureDashFit(e,t);return s?this.canvasKit.PathEffect.MakeDash(s.scaledDash,n*s.scale):null}measureDashFit(e,t){let n=0,i=!1,s=new this.canvasKit.ContourMeasureIter(e,!1,1),a=s.next();for(;a;)n+=a.length(),a.isClosed()||(i=!0),a.delete(),a=s.next();s.delete();let o=Tm.dashScale(t,{length:n,closed:!0},n);return o===null?null:{scaledDash:t.map(c=>c*o),scale:o,total:n,open:i}}buildDashedPath(e,t,n,i,s){let a=s??this.measureDashFit(e,t);if(!a)return null;let o=new this.canvasKit.PathBuilder,c=new this.canvasKit.ContourMeasureIter(e,!1,1),l=c.next(),u=!1;for(;l;){let d=l.length(),h=l.isClosed()?a.scale:Tm.dashScale(t,{length:d,closed:!1},a.total)??a.scale,f=t.map(M=>M*h),p=f.reduce((M,P)=>M+P,0),m=(n*h%p+p)%p,g=l,y=(M,P)=>{if(P-M>Fs){let A=g.getSegment(M,P,!0);A&&(o.addPath(A),A.delete(),u=!0)}else if(i){let[A,F,I,O]=g.getPosTan(M),Q=M>d-Fs?-Fs:Fs;o.moveTo(A,F),o.lineTo(A+I*Q,F+O*Q),u=!0}},b=0,k=0;for(;k+f[b]<=m&&b<f.length&&!(f[b]<=Fs&&Math.abs(m-k)<1e-6||(k+=f[b],b=(b+1)%f.length,b===0)););let T=f[b]-(m-k),S=b%2===0,_=0;for(;_<d-1e-6;){let M=Math.min(T,d-_);S&&y(_,_+M),_+=M,T-=M,T<=1e-6&&(b=(b+1)%f.length,T=f[b],S=!S)}S&&T<=1e-6&&!l.isClosed()&&y(d,d),l.delete(),l=c.next()}return c.delete(),u?o.detachAndDelete():(o.delete(),null)}ckCap(e){switch(e){case"round":return this.canvasKit.StrokeCap.Round;case"square":return this.canvasKit.StrokeCap.Square;default:return this.canvasKit.StrokeCap.Butt}}ckJoin(e){switch(e){case"round":return this.canvasKit.StrokeJoin.Round;case"bevel":return this.canvasKit.StrokeJoin.Bevel;default:return this.canvasKit.StrokeJoin.Miter}}applyCapJoin(e,t,n){e.setStrokeCap(this.ckCap(n)),e.setStrokeJoin(this.ckJoin(t.join)),e.setStrokeMiter(t.miterLimit)}strokeOpts(e,t,n){return{width:t,cap:this.ckCap(n),join:this.ckJoin(e.join),miter_limit:e.miterLimit}}capPlan(e,t,n){let i=e.startCap??e.cap,s=e.endCap??e.cap,a=n?e.cap:s,o=[];if(!t||i===a&&s===a)return{cap:a,ends:o};let c=new this.canvasKit.ContourMeasureIter(t,!1,1);for(let l=c.next();l;l=c.next()){let u=l.length();!l.isClosed()&&u>0&&(i!==a&&this.pushEnd(o,l.getPosTan(0),-1,i),s!==a&&this.pushEnd(o,l.getPosTan(u),1,s)),l.delete()}return c.delete(),{cap:a,ends:o}}pushEnd(e,[t,n,i,s],a,o){let c=Math.hypot(i,s);c<1e-9||e.push({x:t,y:n,dx:a*i/c,dy:a*s/c,cap:o})}strokeBand(e,t,n,i){let s=e.makeStroked(this.strokeOpts(n,t,i.cap));if(!s||i.ends.length===0)return s;let a=t/2,o=Math.min(a,1)/2,c=i.ends.map(d=>s.contains(d.x-d.dx*o,d.y-d.dy*o)),l=a*1.01+.5,u=s;return i.ends.forEach((d,h)=>{if(i.cap!=="butt"&&(u=this.combine(u,this.endBox(d,l,l),this.canvasKit.PathOp.Difference)),c[h]&&d.cap!=="butt"){let f=d.cap==="round"?this.endDisc(d,a):this.endBox(d,a,a);u=this.combine(u,f,this.canvasKit.PathOp.Union)}}),u}endBox({x:e,y:t,dx:n,dy:i},s,a){let o=-i*a,c=n*a,l=n*s,u=i*s,d=new this.canvasKit.PathBuilder;return d.addPolygon([e+o,t+c,e+o+l,t+c+u,e-o+l,t-c+u,e-o,t-c],!0),d.detachAndDelete()}endDisc({x:e,y:t,dx:n,dy:i},s){let a=Math.atan2(n,-i)*180/Math.PI,o=new this.canvasKit.PathBuilder;return o.addArc([e-s,t-s,e+s,t+s],a,-180),o.close(),o.detachAndDelete()}combine(e,t,n){let i=this.canvasKit.Path.MakeFromOp(e,t,n);return t.delete(),i?(e.delete(),i):e}deviceMetrics(e){let t=e.getTotalMatrix(),n=Math.hypot(t[0],t[3]),i=Math.hypot(t[1],t[4]),s=Math.sqrt(Math.abs(t[0]*t[4]-t[1]*t[3])),a=Math.abs(t[1])>1e-6||Math.abs(t[3])>1e-6;return{sx:n,sy:i,scale:s,rotated:a,tx:t[2],ty:t[5]}}resolveStrokeWidth(e,t,n){if(e<=0||t<=0)return{logical:0,intDeviceWidth:-1};if(n)return{logical:e,intDeviceWidth:-1};let i=e*t;if(i>=2.5)return{logical:e,intDeviceWidth:-1};let s=Math.max(1,Math.round(i));return{logical:s/t,intDeviceWidth:s}}snapPath(e,t,n){if(t<=0||!n)return!1;let i=e.getTotalMatrix();if(Math.abs(i[1])>1e-6||Math.abs(i[3])>1e-6)return!1;let s=i[0],a=i[4],o=i[2],c=i[5];if(s===0||a===0)return!1;let l=n.getBounds(),u=l[2]-l[0],d=l[3]-l[1];if(u<=0||d<=0)return!1;let h=o+s*l[0],f=c+a*l[1],p=o+s*l[2],m=c+a*l[3],g=t%2===0?0:.5,y=Math.round(h-g)+g,b=Math.round(f-g)+g,k=Math.round(p-g)+g,T=Math.round(m-g)+g;if(k-y<1||T-b<1)return!1;let S=(k-y)/(p-h),_=(T-b)/(m-f);if(Math.abs(S-1)<1e-4&&Math.abs(_-1)<1e-4&&Math.abs(y-h)<1e-4&&Math.abs(b-f)<1e-4)return!1;let M=(y-o)/s-S*l[0],P=(b-c)/a-_*l[1];return e.save(),e.concat([S,0,M,0,_,P,0,0,1]),!0}applyStrokes(e,t,n){if(e.length===0)return!1;let i=this.getCanvas(),s=this.getPaint(),a=this.fills.openPass(e.flatMap(c=>c.fill),s,()=>{});s.setStyle(this.canvasKit.PaintStyle.Stroke);let o=this.fills.worldAlpha();for(let c of e){let l=c.weight??1,{scale:u,rotated:d}=this.deviceMetrics(i),{logical:h,intDeviceWidth:f}=this.resolveStrokeWidth(l,u,d);s.setStrokeWidth(h);for(let p of c.fill){let m=(p.opacity??1)*o;for(let g of t){n&&n(p,g);let y=b=>this.drawStrokeBand(i,b,g,c,h,f,u,a.clipFilterToShape);a.drawShape=y,this.fills.applyFill(a,p,m)&&!a.skipDefaultDraw&&y(s),this.fills.endFill(a)}}}return this.fills.closePass(a),s.setStyle(this.canvasKit.PaintStyle.Stroke),s.setStrokeCap(this.canvasKit.StrokeCap.Butt),s.setStrokeJoin(this.canvasKit.StrokeJoin.Miter),s.setStrokeMiter(4),!0}drawStrokeBand(e,t,n,i,s,a,o,c){let l=this.snapPath(e,a,n.ckPath),u=c?this.strokeOutline(n,i,s):null;u&&(e.save(),e.clipPath(u,this.canvasKit.ClipOp.Intersect,!0)),this.drawStroke(e,t,n,i,s,a,o),u&&(e.restore(),u.delete()),l&&e.restore()}strokeOutline(e,t,n){if(e.isText)return null;let i=e.strokePath??e.ckPath;if(!i)return null;let s=t.dash&&t.dash.length>0?this.buildDashedPath(i,t.dash,t.dashOffset??0,t.cap!=="butt"):null,a=this.alignedStrokeBand(s??i,n,t.align??0,e.alignInterior??e.ckPath,t,this.capPlan(t,i,!!s));return s?.delete(),a}drawStroke(e,t,n,i,s,a,o){let c=n.isText?void 0:n.strokePath??n.ckPath,l=n.strokeDraw??n.draw,u=!!(i.dash&&i.dash.length>0),d=this.capPlan(i,c,u);if(this.applyCapJoin(t,i,d.cap),n.isText){this.drawTextUnionStroke(e,t,n,i,s,o);return}let h=u&&c?this.measureDashFit(c,i.dash):null,f=i.align??0,p=n.alignInterior??n.ckPath;if((a>0||d.ends.length>0||h?.open)&&c){let m=u?this.buildDashedPath(c,i.dash,i.dashOffset??0,i.cap!=="butt",h??void 0):c;if(m){let g=this.alignedStrokeBand(m,s,f,p,i,d);if(m!==c&&m.delete(),g){t.setStyle(this.canvasKit.PaintStyle.Fill),e.drawPath(g,t),t.setStyle(this.canvasKit.PaintStyle.Stroke),g.delete();return}}}if(f!==0&&!u&&c){let m=this.alignedStrokeBand(c,s,f,p,i,d);if(m){t.setStyle(this.canvasKit.PaintStyle.Fill),e.drawPath(m,t),t.setStyle(this.canvasKit.PaintStyle.Stroke),m.delete();return}}if(u&&c){let m=this.makeUniformDashEffect(c,i.dash,i.dashOffset??0,h??void 0);if(m){t.setPathEffect(m),f!==0&&a<=0&&p&&this.isClosedPath(p)?this.drawAlignedDashedStroke(e,t,c,p,f):e.drawPath(c,t),t.setPathEffect(null),m.delete();return}}l(t)}alignedStrokeBand(e,t,n,i,s,a){if(n===0||!i||!this.isClosedPath(i))return this.strokeBand(e,t,s,a);let o=t*(1+Math.abs(n)),c=this.strokeBand(e,o,s,a);if(!c)return null;let l=n<0?this.canvasKit.PathOp.Intersect:this.canvasKit.PathOp.Difference,u=this.canvasKit.Path.MakeFromOp(c,i,l);return c.delete(),u}isClosedPath(e){let t=new this.canvasKit.ContourMeasureIter(e,!1,1),n=t.next();if(!n)return t.delete(),!1;let i=!0;for(;n;)n.isClosed()||(i=!1),n.delete(),n=t.next();return t.delete(),i}drawAlignedDashedStroke(e,t,n,i,s){e.save();let a=t.getStrokeWidth();t.setStrokeWidth(a*2);let o=s<0?this.canvasKit.ClipOp.Intersect:this.canvasKit.ClipOp.Difference;e.clipPath(i,o,!0),e.drawPath(n,t),e.restore(),t.setStrokeWidth(a)}drawTextUnionStroke(e,t,n,i,s,a){let o=!!(i.dash&&i.dash.length>0),c=null;o&&(c=this.canvasKit.PathEffect.MakeDash(i.dash,i.dashOffset??0),t.setPathEffect(c));let l=i.align??0;l===0?(t.setStrokeWidth(s),n.draw(t)):(e.saveLayer(),t.setStrokeWidth(s*2),n.draw(t),this.applyTextAlignMask(e,n,l,s,a),e.restore(),t.setStrokeWidth(s)),c&&(t.setPathEffect(null),c.delete())}applyTextAlignMask(e,t,n,i,s){let a=n>0,o=new this.canvasKit.Paint;o.setBlendMode(a?this.canvasKit.BlendMode.DstOut:this.canvasKit.BlendMode.DstIn),e.saveLayer(o);let c=new this.canvasKit.Paint;c.setAntiAlias(!0),c.setColor(this.canvasKit.WHITE),c.setStyle(this.canvasKit.PaintStyle.Fill);let l=s>0?Math.min(_x/s,i):0,u=l>0?a?this.canvasKit.ImageFilter.MakeErode(l,l,null):this.canvasKit.ImageFilter.MakeDilate(l,l,null):null;u&&c.setImageFilter(u),t.draw(c),u&&(c.setImageFilter(null),u.delete()),c.delete(),e.restore(),o.delete()}applyShadows(e,t,n,i,s){if(e.length===0)return;let a=this.getPaint(),o=n.length>0&&n.some(d=>(d.opacity??1)>0),c=i.length>0,l=this.fills.worldAlpha(),u=this.fills.openPass(e.flatMap(d=>d.fill),a,()=>{},1);for(let d of e)d.inner||this.applyDropShadow(d,t,o,c,i,l,u,s);this.fills.closePass(u),a.setStyle(this.canvasKit.PaintStyle.Fill),a.setPathEffect(null),a.setStrokeCap(this.canvasKit.StrokeCap.Butt),a.setStrokeJoin(this.canvasKit.StrokeJoin.Miter),a.setStrokeMiter(4)}applyInnerShadows(e,t,n,i){if(e.length===0)return;let s=this.getPaint(),a=n.length>0&&n.some(l=>(l.opacity??1)>0),o=this.fills.worldAlpha(),c=this.fills.openPass(e.flatMap(l=>l.fill),s,()=>{},1);for(let l of e)l.inner&&this.applyInnerShadow(l,t,a,o,c,i);this.fills.closePass(c),s.setStyle(this.canvasKit.PaintStyle.Fill),s.setPathEffect(null)}applyDropShadow(e,t,n,i,s,a,o,c){let l=this.getCanvas(),u=o.paint,d=e.offset?.x??0,h=e.offset?.y??0,f=e.spread!==0&&n?t.map(m=>m.spreadPath?.(e.spread)??null):null,p=m=>{if(n){m.setStyle(this.canvasKit.PaintStyle.Fill),m.setPathEffect(null);for(let g=0;g<t.length;g++){let y=f?.[g];y?l.drawPath(y,m):t[g].draw(m)}}if(i){m.setStyle(this.canvasKit.PaintStyle.Stroke);for(let g of s){let y=g.weight??1,{scale:b,rotated:k}=this.deviceMetrics(l),{logical:T,intDeviceWidth:S}=this.resolveStrokeWidth(y,b,k);m.setStrokeWidth(T),m.setPathEffect(null);for(let _ of t){let M=this.snapPath(l,S,_.ckPath);this.drawStroke(l,m,_,g,T,S,b),M&&l.restore()}}}};o.drawShape=p;for(let m of e.fill){let g=(m.opacity??1)*a,y=new this.canvasKit.Paint;if(y.setAlphaf(g),e.blur>0){let b=e.blur/2,k=this.canvasKit.ImageFilter.MakeBlur(b,b,this.canvasKit.TileMode.Decal,null);y.setImageFilter(k)}l.save(),l.translate(d,-h),l.saveLayer(y),c&&c(m,null),this.fills.applyFill(o,m,1,!1)&&!o.skipDefaultDraw&&p(u),this.fills.endFill(o),l.restore(),l.restore(),y.delete()}if(f)for(let m of f)m?.delete()}applyInnerShadow(e,t,n,i,s,a){if(!n)return;let o=this.getCanvas(),c=s.paint,l=e.offset?.x??0,u=-(e.offset?.y??0);for(let d of t){if(!d.ckPath)continue;let h=e.spread!==0&&!!d.spreadPath,f=h?d.spreadPath(-e.spread):null,p=f??(h?null:d.ckPath),m=this.buildInnerShadowRegion(p,d.ckPath,l,u,e.blur);if(!m){f?.delete();continue}let g=y=>{y.setStyle(this.canvasKit.PaintStyle.Fill),y.setPathEffect(null),o.drawPath(m,y)};s.drawShape=g;for(let y of e.fill){let b=(y.opacity??1)*i,k=new this.canvasKit.Paint;if(k.setAlphaf(b),e.blur>0){let T=e.blur/2,S=this.canvasKit.ImageFilter.MakeBlur(T,T,this.canvasKit.TileMode.Decal,null);k.setImageFilter(S)}o.save(),o.clipPath(d.ckPath,this.canvasKit.ClipOp.Intersect,!0),o.saveLayer(k),a&&a(y,null),this.fills.applyFill(s,y,1,!1)&&!s.skipDefaultDraw&&g(c),this.fills.endFill(s),o.restore(),o.restore(),k.delete()}m.delete(),f?.delete()}}buildInnerShadowRegion(e,t,n,i,s){let a=t.getBounds(),o=s*2+Math.abs(n)+Math.abs(i)+1,c=new this.canvasKit.PathBuilder;c.addRect([a[0]-o,a[1]-o,a[2]+o,a[3]+o]);let l=c.detachAndDelete();if(!e)return l;let u=new this.canvasKit.PathBuilder(e);u.offset(n,i);let d=u.detachAndDelete(),h=this.canvasKit.Path.MakeFromOp(l,d,this.canvasKit.PathOp.Difference);return l.delete(),d.delete(),h}};var go=class{canvasKit;getCanvas;pathCollectionStack=[];booleanOpStack=[];constructor(e,t){this.canvasKit=e,this.getCanvas=t}dispose(){this.pathCollectionStack=[],this.booleanOpStack=[]}resetPass(){for(let e of this.pathCollectionStack)for(let t of e.paths)t.delete();this.pathCollectionStack=[],this.booleanOpStack=[]}isCollecting(){return this.pathCollectionStack.length>0}contributeToPathCollection(e){if(this.pathCollectionStack.length===0)return;let t=this.pathCollectionStack[this.pathCollectionStack.length-1],n=this.getCanvas().getTotalMatrix(),i=this.canvasKit.Matrix.multiply(t.invBaseMatrix,n),s=new this.canvasKit.PathBuilder;s.addPath(e,i),t.paths.push(s.detachAndDelete())}pushFrame(){let e=Array.from(this.getCanvas().getTotalMatrix()),t=this.canvasKit.Matrix.invert(e)??this.canvasKit.Matrix.identity();this.pathCollectionStack.push({paths:[],invBaseMatrix:t})}popFrame(){let e=this.pathCollectionStack.pop();return e?e.paths:[]}toCanvasKitPathOp(e){switch(e){case"subtract":return this.canvasKit.PathOp.Difference;case"intersect":return this.canvasKit.PathOp.Intersect;case"exclude":return this.canvasKit.PathOp.XOR;default:return this.canvasKit.PathOp.Union}}combinePaths(e,t){if(e.length===0)return null;let n=this.toCanvasKitPathOp(t),i=e[0];for(let s=1;s<e.length;s++){let a=this.canvasKit.Path.MakeFromOp(i,e[s],n);if(i.delete(),e[s].delete(),!a){for(let o=s+1;o<e.length;o++)e[o].delete();return null}i=a}return i}beginBoolean(e){this.pushFrame(),this.booleanOpStack.push(e)}endBoolean(e){let t=this.booleanOpStack.pop()??"union",n=this.popFrame(),i=this.combinePaths(n,t);if(!i)return null;this.contributeToPathCollection(i);let s=e();return{draw:o=>{s.drawPath(i,o)},ckPath:i}}};var yo=class{canvasKit;getCanvas;boolean;maskStack=[];constructor(e,t,n){this.canvasKit=e,this.getCanvas=t,this.boolean=n}dispose(){this.maskStack=[]}resetPass(){this.maskStack=[]}beginMask(e){let t=this.getCanvas(),n=e?.mode??"alpha",i=e?.inverted??!1,s=e?.apply,a=s!=null?new Set(Array.isArray(s)?s:[s]):null;if(n==="vector"){t.save(),this.boolean.pushFrame(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:1});return}if(n==="luminance"){t.saveLayer();let o=new this.canvasKit.Paint,c=this.canvasKit.ColorFilter.MakeMatrix([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,.2126,.7152,.0722,0,0]);o.setColorFilter(c),t.saveLayer(o),o.delete(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:2});return}t.saveLayer(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:2})}getApply(){return this.maskStack[this.maskStack.length-1]?.apply??null}applyMask(e){let t=this.getCanvas(),n=this.maskStack[this.maskStack.length-1];if(!n){console.warn("applyMask() called outside of a mask scope.");return}if(n.mode==="vector"){let s=this.boolean.popFrame(),a=this.boolean.combinePaths(s,"union");if(e(),a){let o=n.inverted?this.canvasKit.ClipOp.Difference:this.canvasKit.ClipOp.Intersect;t.clipPath(a,o,!0),a.delete()}return}n.mode==="luminance"&&t.restore();let i=new this.canvasKit.Paint;i.setBlendMode(n.inverted?this.canvasKit.BlendMode.SrcOut:this.canvasKit.BlendMode.SrcIn),t.saveLayer(i),i.delete(),e()}endMask(){let e=this.maskStack.pop();if(!e)return;let t=this.getCanvas();for(let n=0;n<e.restores;n++)t.restore()}};function wo(r,e){if(r===e)return!0;if(typeof r!="object"||typeof e!="object"||r===null||e===null)return!1;if("x"in r&&"y"in r&&"x"in e&&"y"in e){let n=r,i=e;return n.x===i.x&&n.y===i.y}if(Array.isArray(r)&&Array.isArray(e)){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!wo(r[n],e[n]))return!1;return!0}let t=["topLeft","topRight","bottomRight","bottomLeft"];if(t.every(n=>n in r)&&t.every(n=>n in e)){for(let n of t)if(!wo(r[n],e[n]))return!1;return!0}return!1}function Cx(r){return{left:r[0],top:r[1],right:r[2],bottom:r[3]}}function Px(r,e){let t=Object.keys(r);if(t.length!==Object.keys(e).length)return!1;for(let n of t)if(!wo(r[n],e[n]))return!1;return!0}function Ex(r,e,...t){let n=new Set(t),i=Object.keys(r).filter(a=>!n.has(a)),s=Object.keys(e).filter(a=>!n.has(a));if(i.length!==s.length)return!1;for(let a of i)if(!wo(r[a],e[a]))return!1;return!0}var bo=class{canvasKit;getCanvas;getPaint;fontMgr;paragraphCache;getFontEpoch;shapes=[];paintApplied=!1;pendingShadows=null;boolean;mask;boundsOverride=[];shapeCache=new Map;currentNodeId="";shapeIndex=0;_cachedBounds=null;_boundsDirty=!0;transientPaths=new Set;_measuring=!1;_measureShapes=[];_savedNodeId="";_savedShapeIndex=0;constructor(e,t,n,i,s,a){this.canvasKit=e,this.getCanvas=t,this.getPaint=n,this.fontMgr=i,this.paragraphCache=s,this.getFontEpoch=a,this.boolean=new go(e,t),this.mask=new yo(e,t,this.boolean)}beginNode(e){this.currentNodeId=e,this.shapeIndex=0}reset(){for(let e of this.transientPaths)e.delete();this.transientPaths.clear(),this.shapes=[],this.paintApplied=!1,this.pendingShadows=null,this._boundsDirty=!0,this._cachedBounds=null}storePendingShadows(e){this.pendingShadows=e.length>0?e:null}takePendingShadows(){let e=this.pendingShadows;return this.pendingShadows=null,e}dispose(){this.shapes=[];for(let e of this.transientPaths)e.delete();this.transientPaths.clear();for(let e of this.shapeCache.values())e.shape.deletePaths();this.shapeCache.clear(),this.boolean.dispose(),this.mask.dispose()}resetPass(){this._measuring&&this.endMeasure(),this.reset(),this.boundsOverride.length=0,this.boolean.resetPass(),this.mask.resetPass(),this.currentNodeId="",this.shapeIndex=0}isCollectingPaths(){return this.boolean.isCollecting()}pushBounds(e){this.boundsOverride.push(e)}popBounds(){this.boundsOverride.pop()}getShapeBounds(){if(this.boundsOverride.length>0)return this.boundsOverride[this.boundsOverride.length-1];if(!this._boundsDirty&&this._cachedBounds!==null)return this._cachedBounds;let e=1/0,t=1/0,n=-1/0,i=-1/0;for(let s of this.shapes){let a=s.paintBounds??(s.ckPath?Cx(s.ckPath.getBounds()):s.bounds);a&&(a.left<e&&(e=a.left),a.top<t&&(t=a.top),a.right>n&&(n=a.right),a.bottom>i&&(i=a.bottom))}return this._boundsDirty=!1,this._cachedBounds=isFinite(e)?{left:e,top:t,right:n,bottom:i}:null,this._cachedBounds}addShape(e){this._boundsDirty=!0;let t=!this.boolean.isCollecting(),n=e;if(this.currentNodeId){let i=`${this.currentNodeId}:${this.shapeIndex++}`,s=this.shapeCache.get(i);if(s){let a=s.shape,o=e.inputState,c=a.inputState;if(Px(o,c))n=a;else if(a.hasTrim()&&e.hasTrim()&&Ex(o,c,"start","end")){let{start:l,end:u}=e.trimRange();(s.trimStart!==l||s.trimEnd!==u)&&(a.retrim(l,u),s.trimStart=l,s.trimEnd=u),a.inputState=e.inputState,n=a}else{a.deletePaths();let l=e.hasTrim()?e.trimRange():{start:0,end:1};this.shapeCache.set(i,{shape:e,trimStart:l.start,trimEnd:l.end}),n=e}}else{let a=e.hasTrim()?e.trimRange():{start:0,end:1};this.shapeCache.set(i,{shape:e,trimStart:a.start,trimEnd:a.end})}}n.ensurePath(),this._measuring&&this._measureShapes.push(n),!t&&n.ckPath&&this.boolean.contributeToPathCollection(n.ckPath),this.shapes.push(n.toCurrentShape(t))}rect(e){this.addShape(new pi(this.canvasKit,this.getCanvas,e))}ellipse(e){this.addShape(new gi(this.canvasKit,this.getCanvas,e))}path(e){this.addShape(new bi(this.canvasKit,this.getCanvas,e))}line(e){this.addShape(new ki(this.canvasKit,this.getCanvas,e))}polygon(e){this.addShape(new yi(this.canvasKit,this.getCanvas,e))}polygram(e){this.addShape(new wi(this.canvasKit,this.getCanvas,e))}text(e){this._boundsDirty=!0;let t=wm(this.canvasKit,this.getCanvas(),this.fontMgr,e,this.paragraphCache,this.getFontEpoch());this.shapes.push(t)}cut(){let e=this.shapes.filter(a=>a.ckPath);if(e.length===0)return;let t=e[e.length-1].ckPath.copy(),n=e.slice(0,-1),i;if(n.length===0)t.delete(),i=e[0].ckPath.copy();else{let a=this.boolean.combinePaths(n.map(o=>o.ckPath.copy()),"union");a?i=this.boolean.combinePaths([a,t],"subtract"):(t.delete(),i=null)}for(let a of this.shapes)a.ckPath&&this.transientPaths.has(a.ckPath)&&(a.ckPath.delete(),this.transientPaths.delete(a.ckPath));if(this.shapes=[],this.paintApplied=!1,!i)return;this.transientPaths.add(i);let s=this.getCanvas();this.shapes.push({draw:a=>{s.drawPath(i,a)},ckPath:i})}beginMeasure(){this._savedNodeId=this.currentNodeId,this._savedShapeIndex=this.shapeIndex,this.currentNodeId="",this._measuring=!0,this._measureShapes=[],this.shapes=[]}endMeasure(){for(let e of this._measureShapes)e.deletePaths();this._measureShapes=[],this._measuring=!1,this.currentNodeId=this._savedNodeId,this.shapeIndex=this._savedShapeIndex,this.shapes=[],this._boundsDirty=!0,this._cachedBounds=null}beginNested(){let e={nodeId:this.currentNodeId,shapeIndex:this.shapeIndex,shapes:this.shapes,paintApplied:this.paintApplied,pendingShadows:this.pendingShadows,transientPaths:this.transientPaths};return this.shapes=[],this.paintApplied=!1,this.pendingShadows=null,this.transientPaths=new Set,this._boundsDirty=!0,this._cachedBounds=null,e}endNested(e){for(let t of this.transientPaths)t.delete();this.currentNodeId=e.nodeId,this.shapeIndex=e.shapeIndex,this.shapes=e.shapes,this.paintApplied=e.paintApplied,this.pendingShadows=e.pendingShadows,this.transientPaths=e.transientPaths,this._boundsDirty=!0,this._cachedBounds=null}measureUnionBounds(){let e=1/0,t=1/0,n=-1/0,i=-1/0;for(let s of this.shapes)if(s.ckPath&&!s.ckPath.isEmpty()){let a=s.ckPath.getBounds();a[0]<e&&(e=a[0]),a[1]<t&&(t=a[1]),a[2]>n&&(n=a[2]),a[3]>i&&(i=a[3])}else s.bounds&&(s.bounds.left<e&&(e=s.bounds.left),s.bounds.top<t&&(t=s.bounds.top),s.bounds.right>n&&(n=s.bounds.right),s.bounds.bottom>i&&(i=s.bounds.bottom));return isFinite(e)?{left:e,top:t,right:n,bottom:i}:null}unionStrokeShape(){if(this.shapes.some(a=>a.isText))return null;let e=this.shapes.filter(a=>a.ckPath);if(e.length<2)return null;let t=this.boolean.combinePaths(e.map(a=>a.ckPath.copy()),"union");if(!t)return null;let n=e.some(a=>a.strokePath&&a.strokePath!==a.ckPath||a.trimmed),i;if(n){let a=new this.canvasKit.PathBuilder;for(let o of e)a.addPath(o.strokePath??o.ckPath);i=a.detachAndDelete()}let s=this.getCanvas();return{draw:a=>{s.drawPath(t,a)},strokeDraw:a=>{s.drawPath(i??t,a)},ckPath:t,strokePath:i}}beginBoolean(e){this.boolean.beginBoolean(e)}endBoolean(){let e=this.boolean.endBoolean(this.getCanvas);this.shapes=[],this.paintApplied=!1,e&&this.shapes.push(e)}beginMask(e){this.mask.beginMask(e)}applyMask(){this.mask.applyMask(()=>{this.shapes=[],this.paintApplied=!1})}endMask(){this.mask.endMask()}getMaskApply(){return this.mask.getApply()}};import{AssetNotLoadedError as Ix,resolveVideoTimestamp as Mx}from"@motionscript/core";var ko=class r extends qe{static MAX_ECHOES=32;applyPaint(e,t){if(!e.src)return $a(t);let n=t.assets.getVideoDuration(e.src);if(n===0)throw new Ix("video",e.src);let i=Mx(e,t.elapsed,n),s=t.assets.getVideoSize(e.src),a=t.getShapeBounds(),o=s?Gl(e,s,a,t):void 0,c=t.assets.claimVideoFrame(e.src,i,o);if(!c)return!1;let l=e.preset?.adjustments.find(d=>d.type==="echo");if(l&&l.echoes>0&&l.delay>0)return this.drawEchoStack(e,t,l,c,i,s,o),t.skipDefaultDraw=!0,!0;let u=Ps(c,e,t.canvasKit,a,ao(e),{logical:s});return t.transientPaintObjects.push(u),t.paint.setShader(oo(e,t,u)),!0}drawEchoStack(e,t,n,i,s,a,o){let{paint:c,canvasKit:l}=t,u=n.decay??.5,d=Gt(l,n.blend??"screen"),h=Math.min(Math.max(0,Math.floor(n.echoes)),r.MAX_ECHOES),f=(e.opacity??1)*t.worldAlpha,p=t.getShapeBounds();for(let g=h;g>=1;g--){let y=s-g*n.delay;if(y<0)continue;let b=t.assets.getVideoFrameImage(e.src,y,o);if(!b)continue;t.transientImages.push(b);let k=Ps(b,e,l,p,"linear",{logical:a});t.transientPaintObjects.push(k),c.setShader(k),c.setImageFilter(null),c.setAlphaf(f*Math.pow(u,g)),c.setBlendMode(d),t.drawShape(c)}let m=Ps(i,e,l,p,ao(e),{logical:a});t.transientPaintObjects.push(m),c.setShader(oo(e,t,m)),c.setAlphaf(f),c.setBlendMode(d),t.drawShape(c),c.setShader(null),c.setImageFilter(null),c.setAlphaf(f),c.setBlendMode(e.blend?Gt(l,e.blend):l.BlendMode.SrcOver)}};var tn=class{limit;map=new Map;constructor(e=256){this.limit=e}get(e,t){let n=this.map.get(e);if(n)return this.map.delete(e),this.map.set(e,n),n;let i=t();if(this.map.set(e,i),this.map.size>this.limit){let s=this.map.keys().next().value;s!==void 0&&(this.map.get(s)?.delete(),this.map.delete(s))}return i}dispose(){for(let e of this.map.values())e.delete();this.map.clear()}};function xi(r,e){return e.map(t=>r.Color4f(t[0],t[1],t[2],t[3]))}function vt(r,e){for(let t=0;t<e.length;t++)r.push(e[t].toFixed(4))}function vm(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var xo=class extends qe{cache=new tn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let s=vm(e.start.x,e.start.y,i),a=vm(e.end.x,e.end.y,i),o=["L"];vt(o,s),vt(o,a);for(let u of e.colors)vt(o,u);o.push("|"),vt(o,e.stops);let c=o.join(","),l=this.cache.get(c,()=>{let u=xi(n,e.colors),d=e.stops.length===u.length?e.stops:u.map((h,f)=>f/(u.length-1));return n.Shader.MakeLinearGradient(s,a,u,d,n.TileMode.Clamp)});return t.paint.setShader(l),!0}dispose(){this.cache.dispose()}};function Fx(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var So=class extends qe{cache=new tn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let s=Fx(e.center.x,e.center.y,i),a=["R"];vt(a,s),vt(a,[e.radius]);for(let l of e.colors)vt(a,l);a.push("|"),vt(a,e.stops);let o=a.join(","),c=this.cache.get(o,()=>{let l=xi(n,e.colors),u=e.stops.length===l.length?e.stops:l.map((d,h)=>h/(l.length-1));return n.Shader.MakeRadialGradient(s,e.radius,l,u,n.TileMode.Clamp)});return t.paint.setShader(c),!0}dispose(){this.cache.dispose()}};function Rx(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var To=class extends qe{cache=new tn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let[s,a]=Rx(e.center.x,e.center.y,i),o=e.startAngle??0,c=["C"];vt(c,[s,a,o]);for(let d of e.colors)vt(c,d);c.push("|"),vt(c,e.stops);let l=c.join(","),u=this.cache.get(l,()=>{let d=xi(n,e.colors),h=e.stops.length===d.length?e.stops:d.map((f,p)=>p/(d.length-1));return n.Shader.MakeSweepGradient(s,a,d,h,n.TileMode.Clamp,null,0,o,o+360)});return t.paint.setShader(u),!0}dispose(){this.cache.dispose()}};var Bx=24,Si=new Map;function Dx(r,e){for(Si.set(r,e);Si.size>Bx;){let t=Si.keys().next();if(t.done)break;Si.get(t.value)?.delete?.(),Si.delete(t.value)}}function Ox(r,e,t){let[n,i,s,a]=r.color;return`${e}x${t}|${r.size.x},${r.size.y}|${r.density}|${r.seed}|${n},${i},${s},${a}`}function Am(r,e,t){let n=(r*1664525+1013904223^e*1664525*1664525+1013904223)+t>>>0;return n^=n>>>17,n=Math.imul(n,2654435769)>>>0,n^=n>>>13,n=Math.imul(n,1818371886)>>>0,n^=n>>>16,(n>>>0)/4294967296}function Lx(r,e,t){let[n,i,s,a]=t.color,o=Math.round(n*255),c=Math.round(i*255),l=Math.round(s*255),u=Math.round(a*255),d=Math.max(1,Math.round(t.size.x)),h=Math.max(1,Math.round(t.size.y)),f=Math.min(1,Math.max(0,t.density)),p=Math.round(t.seed),m=new Uint8Array(r*e*4);for(let g=0;g<e;g++){let y=Math.floor(g/h);for(let b=0;b<r;b++){let k=Math.floor(b/d),T=Am(k,y,p),S=(g*r+b)*4;if(T<f){let _=Am(k,y,p+1);m[S]=Math.round(o*_),m[S+1]=Math.round(c*_),m[S+2]=Math.round(l*_),m[S+3]=u}}}return m}var vo=class extends qe{applyPaint(e,t){let n=t.getShapeBounds(),i=n?Math.ceil(n.right-n.left):256,s=n?Math.ceil(n.bottom-n.top):256;if(i<=0||s<=0)return!1;let a=Ox(e,i,s),o=Si.get(a);if(!o){let d=Lx(i,s,e);if(o=t.canvasKit.MakeImage({width:i,height:s,alphaType:t.canvasKit.AlphaType.Unpremul,colorType:t.canvasKit.ColorType.RGBA_8888,colorSpace:t.canvasKit.ColorSpace.SRGB},d,4*i),!o)return!1;Dx(a,o)}let c=n?.left??0,l=n?.top??0,u=[1,0,c,0,1,l,0,0,1];return t.paint.setShader(o.makeShaderOptions(t.canvasKit.TileMode.Repeat,t.canvasKit.TileMode.Repeat,t.canvasKit.FilterMode.Nearest,t.canvasKit.MipmapMode.None,u)),!0}};var Ux=8,zx=`
|
|
1669
|
+
`;function Jk(r,e,t){let n=t.canvasKit,i=n.ColorFilter.MakeMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,e,0]),s=n.ImageFilter.MakeColorFilter(i,r);i.delete();let a=n.ImageFilter.MakeBlend(n.BlendMode.SrcOver,null,s);return s.delete(),a}function lo(r,e,t,n){if(t.matrix)return t.matrix instanceof Float32Array?Array.from(t.matrix):t.matrix.flat();let i=t.zoom??1;if(!n)return[i,0,0,0,i,0,0,0,1];let s=t.fit??"fill",a=n.right-n.left,o=n.bottom-n.top,c=s==="tile"?void 0:t.crop,l=c?c.left*r:0,u=c?c.top*e:0,d=c?r*(1-c.left-c.right):r,h=c?e*(1-c.top-c.bottom):e;if(d<=0||h<=0)return[i,0,n.left,0,i,n.top,0,0,1];let f,p;if(s==="fit"?f=p=Math.min(a/d,o/h):s==="stretch"?(f=a/d,p=o/h):s==="tile"?f=p=1:f=p=Math.max(a/d,o/h),f*=i,p*=i,s==="tile")return[f,0,n.left,0,p,n.top,0,0,1];let m=t.anchor??{x:0,y:0},g=(m.x+1)/2,y=(1-m.y)/2,b=n.left+g*(a-d*f)-l*f,k=n.top+y*(o-h*p)-u*p;return[f,0,b,0,p,k,0,0,1]}function Es(r,e,t,n,i="linear",s={}){let a=e.fit??"fill",o=a!=="fit"&&(e.zoom??1)>=1,c=a==="tile"?t.TileMode.Repeat:o?t.TileMode.Clamp:t.TileMode.Decal,l=r.width(),u=r.height(),d=s.logical?.width||l,h=s.logical?.height||u,f=so(lo(d,h,e,n),d,h,l,u),p=i!=="nearest"&&s.mipmaps===!0&&lm(Math.max(l,u),s.footprint);return r.makeShaderOptions(c,c,i==="nearest"?t.FilterMode.Nearest:t.FilterMode.Linear,p?t.MipmapMode.Linear:t.MipmapMode.None,f)}function rS(r,e,t){let n;return eS(r,i=>{if(!tS(i)||n?.has(i))return;let s=i.static===!0?i.identity:void 0;if(s!==void 0){let o=Is.get(s);if(o){o.used=t,(n??=new Map).set(i,o.raster);return}}let a=e.rasterizeSurface(i.source,i.width,i.height,i.maxPixelRatio??1);a&&((n??=new Map).set(i,a),s!==void 0&&(nS(t),Is.set(s,{raster:a,used:t})))}),n}var Is=new Map;function nS(r){for(let[e,t]of Is)t.used<r-1&&Is.delete(e)}function um(){Is.clear()}var uo=class extends qe{preflight(e,t){let n=`${t.nodeId}#${t.paintSlot(e)}`,i=ci(t.assets);if(!i){Sl(n);return}let s=t.getShapeBounds();if(!s)return;let a=s.right-s.left,o=s.bottom-s.top;if(!(a>0)||!(o>0))return;let c=rS(e.scene,t,i.frameIndex),l=Math.min(e.maxPixelRatio??2,Math.max(t.getDeviceScale(),1)),u=i.render(n,e.scene,Math.max(1,Math.ceil(a*l)),Math.max(1,Math.ceil(o*l)),{antialias:e.antialias!==!1,rasters:c}),d=t.assets.upload3DFrame(n,u.source,u.width,u.height);d&&t.preflighted.set(e,d)}applyPaint(e,t){let n=t.preflighted.get(e);if(!n)return!1;let i=t.canvasKit,s=lo(n.width(),n.height(),{fit:"stretch"},t.getShapeBounds()),a=n.makeShaderOptions(i.TileMode.Decal,i.TileMode.Decal,i.FilterMode.Linear,i.MipmapMode.None,s);return t.paint.setShader(a),t.transientPaintObjects.push(a),!0}};import{requireFontFamily as dm}from"@motionscript/core";function iS(r,e){switch(e){case"italic":return r.FontSlant.Italic;case"oblique":return r.FontSlant.Oblique;default:return r.FontSlant.Upright}}function sS(r,e){switch(e){case"left":return r.TextAlign.Left;case"right":return r.TextAlign.Right;case"justify":return r.TextAlign.Justify;case"start":return r.TextAlign.Start;case"end":return r.TextAlign.End;default:return r.TextAlign.Center}}function fm(r,e,t,n){let i=r.FontCollection.Make();i.setDefaultFontManager(e);let s=new r.ParagraphStyle({textStyle:{fontFamilies:[dm(t[0])],fontSize:t[0].fontSize},textAlign:sS(r,n.textAlign)}),a=r.ParagraphBuilder.MakeFromFontCollection(s,i),o=[],c=0;for(let y of t)o.push(c),a.pushStyle(new r.TextStyle({fontFamilies:[dm(y)],fontSize:y.fontSize,fontStyle:{weight:{value:y.fontWeight},slant:iS(r,y.fontStyle)},fontVariations:[{axis:"wght",value:y.fontWeight}],letterSpacing:y.letterSpacing,heightMultiplier:n.lineHeight})),a.addText(y.text),a.pop(),c+=y.text.length;let l=a.build(),u=isFinite(n.maxWidth)&&n.maxWidth>0;l.layout(u?n.maxWidth:1e7);let d=Math.ceil(l.getMaxIntrinsicWidth())+1,h=u?n.maxWidth:Math.max(d,n.boxWidth??0);l.layout(h);let f=l.getLongestLine(),p=l.getHeight(),m=n.originX-h/2,g=n.originY-p/2+aS(p,n);return{paragraph:l,builder:a,fontCollection:i,segmentStartChar:o,layoutWidth:h,blockWidth:f,blockHeight:p,shiftX:m,shiftY:g}}function Tr(r,e,t,n){let i=[],s=t.every(M=>M.text.length===0);if(t.length===0||s)return{runs:[],bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0,fonts:i};let a=fm(r,e,t,n),{paragraph:o,builder:c,fontCollection:l,segmentStartChar:u,layoutWidth:d,blockWidth:h,blockHeight:f,shiftX:p,shiftY:m}=a,g=new Map,y=(M,C)=>{let _=`${M.fontFamily}@${M.fontWeight}@${M.fontStyle}@${M.fontSize}`,F=g.get(_);if(F)return C?.delete(),F;let E=mi(r,C,M.fontSize);return C?.delete(),g.set(_,E),i.push(E),E},b=[],k=t.map(M=>M.text).join(""),T=t.some(M=>M.decoration!==void 0&&M.decoration!=="none"),x=o.getShapedLines();for(let M of x){let C=b.length,_=[];for(let F of M.runs){let E=F.glyphs.length;if(E===0)continue;let O=y(t[Xl(u,t,F.offsets[0])],F.typeface),Q=0,ye=Xl(u,t,F.offsets[0]),Z=ee=>{let ve=ee-Q;if(ve<=0)return;let Re=new Float32Array(ve*2);for(let et=0;et<ve;et++)Re[et*2]=F.positions[(Q+et)*2]+p,Re[et*2+1]=F.positions[(Q+et)*2+1]+m;b.push({segmentIndex:ye,glyphs:F.glyphs.slice(Q,ee),positions:Re,font:O}),T&&_.push(F.offsets.slice(Q,ee))};for(let ee=1;ee<E;ee++){let ve=Xl(u,t,F.offsets[ee]);ve!==ye&&(Z(ee),Q=ee,ye=ve)}Z(E)}T&&oS(b,C,_,k,t)}let v=h>0&&f>0?{left:p,top:m,right:p+d,bottom:m+f}:{left:0,top:0,right:0,bottom:0};return o.delete(),c.delete(),l.delete(),{runs:b,bounds:v,width:h,height:f,fonts:i}}function ho(r,e,t,n){let i=Array.isArray(t)?t:[t],s=i.map(y=>y.text).join("");if(i.length===0||s.length===0){let y=i[0];if(!y)return null;let b=ho(r,e,{...y,text:"M"},n);if(!b)return null;let k=b.lines[0];return{lines:[{start:0,end:0,top:k.top,bottom:k.bottom,carets:[0]}],width:0,height:b.height}}let a=fm(r,e,i,n),{paragraph:o,builder:c,fontCollection:l,blockWidth:u,blockHeight:d,shiftX:h,shiftY:f}=a,p=o.getLineMetrics(),m=[],g=0;for(let y=0;y<p.length;y++){let b=p[y],k=g,T=y===p.length-1?s.length:Math.min(s.length,Math.max(k,b.endIncludingNewline,b.endIndex,b.endExcludingWhitespaces)),x=T>k&&s[T-1]===`
|
|
1670
|
+
`?T-1:T;g=T;let v=b.baseline-b.ascent+f,M=b.baseline+b.descent+f,C=[];for(let _=k;_<x;_++)C.push(hm(o,r,_,!1)+h);C.push(x>k?hm(o,r,x-1,!0)+h:b.left+h),m.push({start:k,end:x,top:v,bottom:M,carets:C})}return o.delete(),c.delete(),l.delete(),m.length===0?null:{lines:m,width:u,height:d}}function hm(r,e,t,n){let s=r.getRectsForRange(t,t+1,e.RectHeightStyle.Max,e.RectWidthStyle.Tight)[0]?.rect;return s?n?s[2]:s[0]:0}function aS(r,e){let t=e.boxHeight??0;if(t<=0)return 0;switch(e.verticalAlign){case"top":return(r-t)/2;case"bottom":return(t-r)/2;default:return 0}}function oS(r,e,t,n,i){let s=!0;for(let a=r.length-1;a>=e;a--){let o=r[a],c=t[a-e],l=o.glyphs.length;if(s){for(;l>0&&/\s/.test(n[c[l-1]]??"");)l--;l>0&&(s=!1)}let u=i[o.segmentIndex];l===0||u.decoration===void 0||u.decoration==="none"||(o.decoration=cS(o,l,u.fontSize,u.decoration))}}function cS(r,e,t,n){let i=r.font.getMetrics(),s=r.font.getGlyphWidths(r.glyphs.subarray(0,e)),a=r.positions[0],o=r.positions[(e-1)*2]+s[e-1],c=r.positions[1];if(n==="underline"){let d=$l(i.underlineThickness)??t/14,h=c+($l(i.underlinePosition)??d);return{left:a,top:h,right:o,bottom:h+d}}let l=$l(i.strikeoutThickness)??t/14,u=c+(i.strikeoutPosition!==void 0&&i.strikeoutPosition<0?i.strikeoutPosition:-t*.26);return{left:a,top:u-l/2,right:o,bottom:u+l/2}}function $l(r){return r!==void 0&&r>0?r:void 0}function Xl(r,e,t){for(let n=0;n<e.length;n++){let i=e[n].text.length;if(i>0&&t>=r[n]&&t<r[n]+i)return n}for(let n=e.length-1;n>=0;n--)if(e[n].text.length>0)return n;return 0}function Ql(r,e,t){Yl(r,e,0,0,t)}function Yl(r,e,t,n,i){r.drawGlyphs(e.glyphs,e.positions,t,n,e.font,i);let s=e.decoration;s&&r.drawRect(Float32Array.of(s.left+t,s.top+n,s.right+t,s.bottom+n),i)}function mm(r,e,t){let{spans:n,lineHeight:i,textAlign:s,width:a}=t,o=n.map(u=>({text:u.text,fontFamily:u.fontFamily,fontSize:u.fontSize,fontWeight:u.fontWeight,fontStyle:u.fontStyle,letterSpacing:u.letterSpacing})),c=Tr(r,e,o,{textAlign:s,lineHeight:i,maxWidth:a>0?a:1/0,boxWidth:a,originX:0,originY:0});return{runs:c.runs.map(u=>({...u,span:n[u.segmentIndex]})),bounds:c.bounds,fonts:c.fonts}}import{withTextDescriptor as Sm,isStyleOnlySegment as TS,resolveShapePivot as AS}from"@motionscript/core";import{AUTOFIT_PROBE_SIZE as lS,withTextDescriptor as uS}from"@motionscript/core";function Zl(r){let e=r.fontSize==="autofit"?lS:r.fontSize;return(r.segments??[]).map(t=>({text:t.text,fontFamily:t.fontFamily??r.fontFamily,fontSize:t.fontSize??e,fontWeight:t.fontWeight,fontStyle:t.fontStyle??r.fontStyle,letterSpacing:t.letterSpacing,decoration:t.textDecoration??r.textDecoration}))}function pm(r,e,t){let n=uS(t),i=n.segments??[],s=Zl(n),a=n.wrap&&n.width>0,o=Tr(r,e,s,{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:a?n.width:1/0,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:n.x,originY:n.y});return{runs:o.runs.map(l=>({...l,segment:i[l.segmentIndex]})),bounds:o.bounds,fonts:o.fonts}}function gm(r){let e=r.positions;if(e.length===0)return{x:0,y:0};let t=1/0,n=-1/0,i=1/0,s=-1/0;for(let a=0;a<e.length;a+=2){let o=e[a],c=e[a+1];o<t&&(t=o),o>n&&(n=o),c<i&&(i=c),c>s&&(s=c)}return{x:(t+n)/2,y:(i+s)/2}}import{withTextDescriptor as dS,pathOps as hS}from"@motionscript/core";function fS(r,e){switch(e){case"italic":return r.FontSlant.Italic;case"oblique":return r.FontSlant.Oblique;default:return r.FontSlant.Upright}}function mS(r,e,t){switch(r){case"right":case"end":return t-e;case"center":return(t-e)/2;default:return 0}}var pS=64,en=new Map,gS="";function yS(r,e,t){return[r.text,r.fontFamily,e,r.fontWeight,r.fontStyle,r.letterSpacing,r.lineHeight,t].join(gS)}function wS(r,e,t,n,i){let s=yS(t,n,i),a=en.get(s);if(a)return en.delete(s),en.set(s,a),a.run;let o=bS(r,e,t,n);if(!o)return null;if(en.set(s,{run:o.run,fonts:o.fonts}),en.size>pS){let c=en.keys().next().value;if(c!==void 0){let l=en.get(c);if(en.delete(c),l)for(let u of l.fonts)u.delete()}}return o.run}function bS(r,e,t,n){let i=[],s=r.FontCollection.Make();s.setDefaultFontManager(e);let a=new r.ParagraphStyle({textStyle:{fontFamilies:[t.fontFamily],fontSize:n},textAlign:r.TextAlign.Left}),o=r.ParagraphBuilder.MakeFromFontCollection(a,s);o.pushStyle(new r.TextStyle({fontFamilies:[t.fontFamily],fontSize:n,fontStyle:{weight:{value:t.fontWeight},slant:fS(r,t.fontStyle)},fontVariations:[{axis:"wght",value:t.fontWeight}],letterSpacing:t.letterSpacing,heightMultiplier:t.lineHeight})),o.addText(t.text.replace(/\s*\n\s*/g," ")),o.pop();let c=o.build();c.layout(1e7);let l=new Map,u=m=>{let g=`${t.fontFamily}@${t.fontWeight}@${t.fontStyle}@${n}`,y=l.get(g);if(y)return m?.delete(),y;let b=mi(r,m,n);return m?.delete(),l.set(g,b),i.push(b),b},h=c.getShapedLines()[0];if(!h){c.delete(),o.delete(),s.delete();for(let m of i)m.delete();return null}let f=0;for(let m of h.runs){let g=m.glyphs.length;g>0&&(f=Math.max(f,m.positions[g*2]))}let p=[];for(let m of h.runs){let g=m.glyphs.length;if(g===0)continue;let y=u(m.typeface);for(let b=0;b<g;b++){let k=m.positions[b*2],T=m.positions[(b+1)*2]-k,x=k+T/2,v=m.positions[b*2+1]-h.baseline;p.push({glyphId:m.glyphs[b],midX:x,advance:T,perp:v,font:y})}}return c.delete(),o.delete(),s.delete(),{run:{glyphs:p,textWidth:f,fontSize:n},fonts:i}}function kS(r,e,t){let n={glyphs:[],bounds:{left:0,top:0,right:0,bottom:0}},i=hS.sampler(e);if(i.length<=0)return n;let s=mS(t,r.textWidth,i.length),a=[],o=1/0,c=1/0,l=-1/0,u=-1/0,d=(p,m)=>{p<o&&(o=p),p>l&&(l=p),m<c&&(c=m),m>u&&(u=m)};for(let p of r.glyphs){let m=p.midX+s;if(m<0||m>i.length)continue;let g=i.frameAt(m);if(!g)continue;let y=g.x+p.perp*-g.ty,b=g.y+p.perp*g.tx,k=Math.atan2(g.ty,g.tx)*180/Math.PI;a.push({glyphId:p.glyphId,x:y,y:b,angle:k,halfAdvance:p.advance/2,font:p.font}),d(y,b)}let h=r.fontSize,f=a.length>0?{left:o-h,top:c-h,right:l+h,bottom:u+h}:{left:0,top:0,right:0,bottom:0};return{glyphs:a,bounds:f}}function ym(r,e,t,n){let i=dS(t),s={glyphs:[],bounds:{left:0,top:0,right:0,bottom:0}};if(i.text.length===0||i.path==null)return s;let a=i.fontSize==="autofit"?100:i.fontSize,o=wS(r,e,i,a,n);return o?kS(o,i.path,i.textAlign):s}function wm(r,e,t){for(let n of e)r.save(),r.translate(n.x,n.y),n.angle!==0&&r.rotate(n.angle,0,0),r.drawGlyphs([n.glyphId],new Float32Array([-n.halfAdvance,0]),0,0,n.font,t),r.restore()}var SS={width:0,height:0},xS="";function Jl(r,e){return[r.text,r.fontFamily,r.fontSize,r.fontWeight,r.fontStyle,r.letterSpacing,r.decoration,r.lineHeight,r.textAlign,r.verticalAlign,r.maxWidth,r.boxWidth,r.boxHeight,e].join(xS)}var fo=class{limit;ceiling;map=new Map;pass=0;constructor(e=256,t=16384){this.limit=e,this.ceiling=t}get(e,t){let n=this.map.get(e);if(n)return this.map.delete(e),this.map.set(e,n),n.pass=this.pass,n;let i={layout:t(),pass:this.pass};return this.map.set(e,i),this._evict(),i}endPass(){this.pass++,this._evict()}dispose(){for(let e of this.map.values())for(let t of e.layout.fonts)t.delete();this.map.clear()}_evict(){for(;this.map.size>this.limit;){let[e,t]=this.map.entries().next().value;if(t.pass>=this.pass-1&&this.map.size<=this.ceiling)return;this.map.delete(e);for(let n of t.layout.fonts)n.delete()}}};function eu(r,e,t,n,i,s=0,a="center"){return{text:r.text,fontFamily:r.fontFamily,fontSize:r.fontSize,fontWeight:r.fontWeight,fontStyle:r.fontStyle,letterSpacing:r.letterSpacing,decoration:r.decoration??"none",lineHeight:t,textAlign:e,verticalAlign:a,maxWidth:n,boxWidth:i,boxHeight:a==="center"?0:s}}var bm="center",km=1;function mo(r,e,t,n,i,s,a,o,c,l){if(i.length===0)return SS;let u={text:i,fontFamily:a,fontSize:s,fontWeight:o,fontStyle:l,letterSpacing:c},d=Jl(eu(u,bm,km,1/0,0),n),{layout:h}=t.get(d,()=>Tr(r,e,[u],{textAlign:bm,lineHeight:km,maxWidth:1/0,originX:0,originY:0}));return{width:h.width,height:h.height}}function vS(r,e,t,n,i){let s=n*Math.PI/180,a=Math.cos(s),o=Math.sin(s),c=[{x:r.left,y:r.top},{x:r.right,y:r.top},{x:r.right,y:r.bottom},{x:r.left,y:r.bottom}],l=1/0,u=1/0,d=-1/0,h=-1/0;for(let f of c){let p=(f.x-e)*i,m=(f.y-t)*i,g=e+p*a-m*o,y=t+p*o+m*a;g<l&&(l=g),g>d&&(d=g),y<u&&(u=y),y>h&&(h=y)}return{left:l,top:u,right:d,bottom:h}}function xm(r,e,t){let n=t.fontSize==="autofit",i=n?100:t.fontSize,s=t.wrap&&t.width>0,a=o=>({text:t.text,fontFamily:t.fontFamily,fontSize:o,fontWeight:t.fontWeight,fontStyle:t.fontStyle,letterSpacing:t.letterSpacing,decoration:t.textDecoration});if(n&&t.width>0&&t.height>0){let o=Tr(r,e,[a(i)],{textAlign:t.textAlign,lineHeight:t.lineHeight,maxWidth:1/0,originX:t.x,originY:t.y}),c=o.width>0?t.width/o.width:1,l=o.height>0?t.height/o.height:1,u=i*Math.min(c,l);for(let d of o.fonts)d.delete();s&&u<t.minFontSize?i=t.minFontSize:(i=u,s=!1)}return{segment:a(i),maxWidth:s?t.width:1/0}}function po(r,e,t){let n=Sm(t);if(n.path!=null)return null;let i=n.segments??[];if(i.length>0){if(!i.every(TS))return null;let o=n.wrap&&n.width>0;return ho(r,e,Zl(n),{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:o?n.width:1/0,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:0,originY:0})}let{segment:s,maxWidth:a}=xm(r,e,n);return ho(r,e,s,{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:a,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:0,originY:0})}function Tm(r,e,t,n,i,s){let a=Sm(n);if(a.path!=null){let F=ym(r,t,n,s);return{bounds:F.bounds,draw:E=>wm(e,F.glyphs,E)}}let o=a.x,c=a.y,{segment:l,maxWidth:u}=xm(r,t,a),d=Jl(eu(l,a.textAlign,a.lineHeight,u,a.width,a.height,a.verticalAlign),s),{layout:h}=i.get(d,()=>Tr(r,t,[l],{textAlign:a.textAlign,lineHeight:a.lineHeight,maxWidth:u,boxWidth:a.width,boxHeight:a.height,verticalAlign:a.verticalAlign,originX:0,originY:0})),f=AS(a.pivot),p=a.width>0&&a.height>0,m=p?a.width:h.width,g=p?a.height:h.height,y=!p&&f.x!==0?o-f.x*(h.width/2):o,b=!p&&f.y!==0?c+f.y*(h.height/2):c,k=h.bounds,T={left:k.left+y,top:k.top+b,right:k.right+y,bottom:k.bottom+b},x=a.rotation,v=a.scale,M=x!==0||v!==1,C=y+f.x*(m/2),_=b-f.y*(g/2);return M&&(T=vS(T,C,_,x,v)),{bounds:T,isText:!0,draw:F=>{M&&e.save();try{M&&(e.translate(C,_),e.rotate(x,0,0),e.scale(v,v),e.translate(-C,-_));for(let E of h.runs)Yl(e,E,y,b,F)}finally{M&&e.restore()}}}}import{cornerRadiusOps as tu,cornerStyleOps as _S,withRectDescriptor as CS}from"@motionscript/core";function In(r,e,t,n){let i=0,s=new r.ContourMeasureIter(e,!1,1),a=s.next();for(;a;)i+=a.length(),a.delete(),a=s.next();if(s.delete(),i<=0)return e.copy();let o=t*i,c=n*i,l=[];s=new r.ContourMeasureIter(e,!1,1);let u=0;for(a=s.next();a;){let h=a.length(),f=u,p=u+h;if(p>o&&f<c){let m=Math.max(0,o-f),g=Math.min(h,c-f);l.push(a.getSegment(m,g,!0))}u=p,a.delete(),a=s.next()}if(s.delete(),l.length===0)return r.Path.MakeFromSVGString("M 0 0")??e.copy();if(l.length===1)return l[0];let d=l.map(h=>h.toSVGString());return l.forEach(h=>h.delete()),r.Path.MakeFromSVGString(d.join(" "))??e.copy()}var Tt=class{canvasKit;fullState;inputState;ckPath;_basePath;_geo;getCanvas;get canvas(){return this.getCanvas()}constructor(e,t,n){this.canvasKit=e,this.getCanvas=t,this.inputState=n,this.fullState=this.resolveState(n)}buildSVGAlignInterior(e){return null}_alignInterior;_alignInteriorBuilt=!1;strokeAlignInterior(){if(!this._alignInteriorBuilt){this._alignInteriorBuilt=!0;let e=this.buildSVGAlignInterior(this.geometry);if(e!=null){let t=this.canvasKit.Path.MakeFromSVGString(e);this._alignInterior=t?this.applyShapeTransform(t):void 0}}return this._alignInterior??(this.needsTrim()?this._basePath:void 0)}buildSpreadSVGPath(e,t){return null}hasTrim(){return this.needsTrim()}trimRange(){return this.getTrimRange()}hasShapeTransform(){let e=this.fullState;return(e.rotation??0)!==0||(e.scale??1)!==1}get geometry(){return this._geo??=this.computeGeometry()}ensurePath(){if(this.ckPath)return;let e=this.buildSVGPath(this.geometry),t=this.canvasKit.Path.MakeFromSVGString(e);if(!t){console.warn(`${this.constructor.name}: failed to create path`);return}let n=this.applyShapeTransform(t);if(this.needsTrim()){this._basePath=n;let{start:i,end:s}=this.getTrimRange();this.ckPath=In(this.canvasKit,n,i,s)}else this.ckPath=n}applyShapeTransform(e,t){let n=this.fullState,i=n.rotation??0,s=n.scale??1;if(i===0&&s===1)return e;let a=t?t.x:n.x??0,o=t?t.y:n.y??0,c=n.pivot??{x:0,y:0},l=a+c.x*((n.width??0)/2),u=o-c.y*((n.height??0)/2),d=i*Math.PI/180,h=Math.cos(d),f=Math.sin(d),p=h*s,m=-f*s,g=f*s,y=h*s,b=l-p*l-m*u,k=u-g*l-y*u,T=new this.canvasKit.PathBuilder(e);T.transform(p,m,b,g,y,k,0,0,1);let x=T.detachAndDelete();return e.delete(),x}spreadPath(e){let t=this.buildSpreadSVGPath(this.geometry,e);if(t==null)return null;let n=this.canvasKit.Path.MakeFromSVGString(t);return n?this.applyShapeTransform(n):null}_setBasePath(e){this._basePath=e}paintBounds(){if(!this._basePath)return;let e=this._basePath.getBounds();return{left:e[0],top:e[1],right:e[2],bottom:e[3]}}retrim(e,t){let n=this._basePath;if(!n)return;let i=this.fullState;i.start=e,i.end=t,this.ckPath?.delete(),this.ckPath=In(this.canvasKit,n,e,t),this._strokePath?.delete(),this._strokePath=void 0,this._strokePathBuilt=!1}_strokePath;_strokePathBuilt=!1;strokePath(){return this._strokePathBuilt||(this._strokePathBuilt=!0,this.ensurePath(),this._strokePath=this.ckPath?this.buildStrokePath(this.ckPath):void 0),this._strokePath}buildStrokePath(e){}deletePaths(){this.ckPath?.delete(),this.ckPath=void 0,this._basePath?.delete(),this._basePath=void 0,this._alignInterior?.delete(),this._alignInterior=void 0,this._alignInteriorBuilt=!1,this._strokePath?.delete(),this._strokePath=void 0,this._strokePathBuilt=!1}draw(e,t){this.ensurePath(),this.ckPath&&this.canvas.drawPath(this.ckPath,e)}strokeDraw(e){let t=this.strokePath()??this.ckPath;t&&this.canvas.drawPath(t,e)}clip(e){this.ensurePath(),this.ckPath&&this.canvas.clipPath(this.ckPath,this.canvasKit.ClipOp.Intersect,!0)}supportsSpread(){return!1}toCurrentShape(e){let t=this;return{draw:n=>t.draw(n,e),strokeDraw:n=>t.strokeDraw(n),get ckPath(){return t.ckPath},get strokePath(){return t.strokePath()},get alignInterior(){return t.strokeAlignInterior()},get paintBounds(){return t.paintBounds()},trimmed:this.needsTrim(),bounds:this.computeBounds(this.geometry),spreadPath:this.supportsSpread()?n=>t.spreadPath(n):void 0}}computeBounds(e){}};function Ar(r){return r.radius>0?r.radius:0}function Ms(r,e,t,n,i,s,a){return a.radius<=0?"":Fs(r,e,t,n,i,s,a.radius,a.radius,a.style)}function Fs(r,e,t,n,i,s,a,o,c){let l=r+i*a,u=e+s*a;if(c==="angled")return`L ${l} ${u}`;let h=t*s-n*i<0?1:0;return`A ${o} ${o} 0 0 ${h} ${l} ${u}`}function Am(r,e,t,n,i,s,a,o){let c=Ar(i),l=Ar(s),u=Ar(a),d=Ar(o);return[`M ${r+c} ${e}`,`L ${t-l} ${e}`,Ms(t,e,-1,0,0,1,s),`L ${t} ${n-u}`,Ms(t,n,0,-1,-1,0,a),`L ${r+d} ${n}`,Ms(r,n,1,0,0,-1,o),`L ${r} ${e+c}`,Ms(r,e,0,1,1,0,i),"Z"].filter(Boolean).join(" ")}var pi=class extends Tt{resolveState(e){return CS(e)}computeGeometry(){let e=this.fullState,t=e.width/2,n=e.height/2,i=e.x-t,s=e.y-n,a=e.x+t,o=e.y+n,c=tu.resolve(e.cornerRadius),l=_S.resolve(e.cornerStyle),u={radius:Math.max(0,c.topLeft),style:l.topLeft},d={radius:Math.max(0,c.topRight),style:l.topRight},h={radius:Math.max(0,c.bottomRight),style:l.bottomRight},f={radius:Math.max(0,c.bottomLeft),style:l.bottomLeft},p=vm(e.width,e.height,u,d,h,f);u.radius*=p,d.radius*=p,h.radius*=p,f.radius*=p;let m={topLeft:u.radius,topRight:d.radius,bottomRight:h.radius,bottomLeft:f.radius},g=l.topLeft==="rounded"&&l.topRight==="rounded"&&l.bottomRight==="rounded"&&l.bottomLeft==="rounded";return{left:i,top:s,right:a,bottom:o,tl:u,tr:d,br:h,bl:f,isZero:tu.isZero(m),isUniform:tu.isUniform(m),isPlainRounded:g}}buildSVGPath(e){let{left:t,top:n,right:i,bottom:s,tl:a,tr:o,br:c,bl:l,isZero:u}=e;return u?`M ${t} ${n} L ${i} ${n} L ${i} ${s} L ${t} ${s} Z`:Am(t,n,i,s,a,o,c,l)}hasCornerRadius(){return!this.geometry.isZero}supportsSpread(){return!0}buildSpreadSVGPath(e,t){let n=e.left-t,i=e.top-t,s=e.right+t,a=e.bottom+t,o=s-n,c=a-i;if(o<=0||c<=0)return null;let l={...e.tl,radius:Math.max(0,e.tl.radius+t)},u={...e.tr,radius:Math.max(0,e.tr.radius+t)},d={...e.br,radius:Math.max(0,e.br.radius+t)},h={...e.bl,radius:Math.max(0,e.bl.radius+t)},f=vm(o,c,l,u,d,h);return l.radius*=f,u.radius*=f,d.radius*=f,h.radius*=f,l.radius===0&&u.radius===0&&d.radius===0&&h.radius===0?`M ${n} ${i} L ${s} ${i} L ${s} ${a} L ${n} ${a} Z`:Am(n,i,s,a,l,u,d,h)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}draw(e,t){let n=this.geometry;if(t&&!this.needsTrim()&&!this.hasShapeTransform()){let i=this.canvasKit,s=i.LTRBRect(n.left,n.top,n.right,n.bottom);if(n.isZero){this.canvas.drawRect(s,e);return}if(n.isUniform&&n.isPlainRounded){this.canvas.drawRRect(i.RRectXY(s,n.tl.radius,n.tl.radius),e);return}}super.draw(e,t)}clip(e){let t=this.geometry,n=this.canvasKit;if(e&&!this.needsTrim()&&!this.hasShapeTransform()){let i=n.LTRBRect(t.left,t.top,t.right,t.bottom);if(t.isZero){this.canvas.clipRect(i,n.ClipOp.Intersect,!0);return}if(t.isUniform&&t.isPlainRounded){this.canvas.clipRRect(n.RRectXY(i,t.tl.radius,t.tl.radius),n.ClipOp.Intersect,!0);return}}super.clip(e)}};function vm(r,e,t,n,i,s){let a=Ar(t),o=Ar(n),c=Ar(i),l=Ar(s),u=a+o>0?Math.min(1,r/(a+o)):1,d=l+c>0?Math.min(1,r/(l+c)):1,h=a+l>0?Math.min(1,e/(a+l)):1,f=o+c>0?Math.min(1,e/(o+c)):1;return Math.min(u,d,h,f)}import{withEllipseDescriptor as PS}from"@motionscript/core";var tn=Math.PI/180,gi=class extends Tt{resolveState(e){return PS(e)}computeGeometry(){let e=this.fullState,t=e.sweep??360;return{cx:e.x,cy:e.y,halfWidth:e.width/2,halfHeight:e.height/2,sweep:t,isFullShape:Math.abs(t)>=360,startAngle:e.startAngle??0,ratio:Math.max(0,Math.min(1,e.ratio??0))}}buildSVGPath(e){let{cx:t,cy:n,halfWidth:i,halfHeight:s,ratio:a}=e;if(a>=1)return"";if(!e.isFullShape)return a<=0?_m(e):Cm(e);let o=Rs(t,n,i,s,0);return a<=0?o:`${o} ${Rs(t,n,i*a,s*a,1)}`}buildSVGAlignInterior(e){return e.isFullShape?e.ratio>=1?Rs(e.cx,e.cy,e.halfWidth,e.halfHeight,0):null:e.ratio>=1||e.ratio<=0?_m(e):Cm(e)}buildStrokePath(e){let t=this._outline();if(!t)return;if(!this.needsTrim())return t.copy();let{start:n,end:i}=this.getTrimRange();return In(this.canvasKit,t,n,i)}paintBounds(){let e=this._outline();if(!e)return super.paintBounds();let[t,n,i,s]=e.getBounds();return{left:t,top:n,right:i,bottom:s}}deletePaths(){super.deletePaths(),this._outlinePath?.delete(),this._outlinePath=void 0,this._outlineBuilt=!1}supportsSpread(){return!0}buildSpreadSVGPath(e,t){if(!e.isFullShape||e.ratio>=1)return null;let n=e.halfWidth+t,i=e.halfHeight+t;return n<=0||i<=0?null:Rs(e.cx,e.cy,n,i,0)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){let{cx:t,cy:n,halfWidth:i,halfHeight:s}=e;return{left:t-i,top:n-s,right:t+i,bottom:n+s}}_outlinePath;_outlineBuilt=!1;_outline(){if(!this._outlineBuilt){this._outlineBuilt=!0;let e=this.geometry;if(e.ratio>=1){let t=e.isFullShape?Rs(e.cx,e.cy,e.halfWidth,e.halfHeight,0):ES(e),n=this.canvasKit.Path.MakeFromSVGString(t);this._outlinePath=n?this.applyShapeTransform(n):void 0}}return this._outlinePath}};function Rs(r,e,t,n,i){let s=r-t,a=r+t;return`M ${s} ${e} A ${t} ${n} 0 1 ${i} ${a} ${e} A ${t} ${n} 0 1 ${i} ${s} ${e} Z`}function ru(r){let{cx:e,cy:t,halfWidth:n,halfHeight:i,startAngle:s,sweep:a}=r,o=s+a,c=Math.abs(a)>180?1:0,l=a>0?1:0,u=e+n*Math.cos(s*tn),d=t+i*Math.sin(s*tn),h=e+n*Math.cos(o*tn),f=t+i*Math.sin(o*tn);return{start:`${u} ${d}`,arc:`A ${n} ${i} 0 ${c} ${l} ${h} ${f}`}}function ES(r){let{start:e,arc:t}=ru(r);return`M ${e} ${t}`}function _m(r){let{start:e,arc:t}=ru(r);return`M ${r.cx} ${r.cy} L ${e} ${t} Z`}function Cm(r){let{cx:e,cy:t,halfWidth:n,halfHeight:i,startAngle:s,sweep:a,ratio:o}=r,{start:c,arc:l}=ru(r),u=s+a,d=n*o,h=i*o,f=e+d*Math.cos(s*tn),p=t+h*Math.sin(s*tn),m=e+d*Math.cos(u*tn),g=t+h*Math.sin(u*tn),y=Math.abs(a)>180?1:0,b=a>0?0:1;return`M ${c} ${l} L ${m} ${g} A ${d} ${h} 0 ${y} ${b} ${f} ${p} Z`}import{withPolygonDescriptor as IS}from"@motionscript/core";function MS(r,e,t,n,i,s,a){let o=2*Math.PI/i,c=-Math.PI/2,l=[];for(let d=0;d<i;d++){let h=c+d*o;l.push([r+t*Math.cos(h),e+n*Math.sin(h)])}if(s<=0){let d=l.map(([h,f],p)=>`${p===0?"M":"L"} ${h} ${f}`);return d.push("Z"),d.join(" ")}let u=[];for(let d=0;d<i;d++){let h=l[(d-1+i)%i],f=l[d],p=l[(d+1)%i],m=h[0]-f[0],g=h[1]-f[1],y=Math.hypot(m,g),b=m/y,k=g/y,T=p[0]-f[0],x=p[1]-f[1],v=Math.hypot(T,x),M=T/v,C=x/v,_=Math.max(-1,Math.min(1,b*M+k*C)),F=Math.acos(_)/2,E=Math.tan(F),O=Math.min(y,v)/2,Q=s/E;Q>O&&(Q=O);let ye=Q*E,Z=f[0]+b*Q,ee=f[1]+k*Q;u.push(`${u.length===0?"M":"L"} ${Z} ${ee}`),u.push(Fs(f[0],f[1],b,k,M,C,Q,ye,a))}return u.push("Z"),u.join(" ")}var yi=class extends Tt{resolveState(e){return IS(e)}computeGeometry(){let e=this.fullState;return{cx:e.x,cy:e.y,rx:e.width/2,ry:e.height/2,sides:Math.max(3,Math.round(e.sides)),cornerRadius:e.cornerRadius,cornerStyle:e.cornerStyle}}buildSVGPath(e){return MS(e.cx,e.cy,e.rx,e.ry,e.sides,e.cornerRadius,e.cornerStyle)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.cx-e.rx,top:e.cy-e.ry,right:e.cx+e.rx,bottom:e.cy+e.ry}}};import{withPolygramDescriptor as FS}from"@motionscript/core";function RS(r,e,t,n,i,s,a,o){let c=i*2,l=Math.PI/i,u=-Math.PI/2,d=[];for(let f=0;f<c;f++){let p=u+f*l,g=f%2===0?1:s;d.push([r+t*g*Math.cos(p),e+n*g*Math.sin(p)])}if(a<=0){let f=d.map(([p,m],g)=>`${g===0?"M":"L"} ${p} ${m}`);return f.push("Z"),f.join(" ")}let h=[];for(let f=0;f<c;f++){let p=d[f];if(!(f%2===0)){h.push(`${h.length===0?"M":"L"} ${p[0]} ${p[1]}`);continue}let g=d[(f-1+c)%c],y=d[(f+1)%c],b=g[0]-p[0],k=g[1]-p[1],T=Math.hypot(b,k),x=b/T,v=k/T,M=y[0]-p[0],C=y[1]-p[1],_=Math.hypot(M,C),F=M/_,E=C/_,O=Math.max(-1,Math.min(1,x*F+v*E)),Q=Math.acos(O)/2,ye=Math.tan(Q),Z=Math.min(T,_)/2,ee=a/ye;ee>Z&&(ee=Z);let ve=ee*ye,Re=p[0]+x*ee,et=p[1]+v*ee;h.push(`${h.length===0?"M":"L"} ${Re} ${et}`),h.push(Fs(p[0],p[1],x,v,F,E,ee,ve,o))}return h.push("Z"),h.join(" ")}var wi=class extends Tt{resolveState(e){return FS(e)}computeGeometry(){let e=this.fullState;return{cx:e.x,cy:e.y,rx:e.width/2,ry:e.height/2,sides:Math.max(3,Math.round(e.sides)),ratio:Math.max(0,Math.min(1,e.ratio)),cornerRadius:e.cornerRadius,cornerStyle:e.cornerStyle}}buildSVGPath(e){return RS(e.cx,e.cy,e.rx,e.ry,e.sides,e.ratio,e.cornerRadius,e.cornerStyle)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.cx-e.rx,top:e.cy-e.ry,right:e.cx+e.rx,bottom:e.cy+e.ry}}};import{toPathString as BS,withPathDescriptor as DS}from"@motionscript/core";var bi=class extends Tt{resolveState(e){return DS(e)}computeGeometry(){return{svgString:BS(this.fullState.data),offsetX:0,offsetY:0}}buildSVGPath(e){return e.svgString}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}buildCenteredTransformedTrimmed(e,t,n){let i=this.canvasKit.Path.MakeFromSVGString(e);if(!i){console.warn("PathShape: failed to parse SVG path string:",e);return}let s=new this.canvasKit.PathBuilder(i);s.offset(t,n);let a=s.detachAndDelete();i.delete();let o=this.applyShapeTransform(a,{x:0,y:0});if(this.needsTrim()){this._setBasePath(o);let{start:c,end:l}=this.getTrimRange();return In(this.canvasKit,o,c,l)}return o}ensurePath(){if(this.ckPath)return;let e=this.geometry,t=this.canvasKit.Path.MakeFromSVGString(e.svgString);if(!t){console.warn("PathShape: failed to parse SVG path string:",e.svgString);return}let n=this.fullState.centerBounds,[i,s,a,o]=n??t.getBounds();e.offsetX=-(i+(a-i)/2),e.offsetY=-(s+(o-s)/2),t.delete(),this.ckPath=this.buildCenteredTransformedTrimmed(e.svgString,e.offsetX,e.offsetY)}draw(e,t){this.ensurePath(),this.ckPath&&this.canvas.drawPath(this.ckPath,e)}clip(e){this.ensurePath(),this.ckPath&&this.canvas.clipPath(this.ckPath,this.canvasKit.ClipOp.Intersect,!0)}};import{withLineDescriptor as OS}from"@motionscript/core";function LS(r,e,t){if(r.length===0)return"M 0 0";if(r.length===1)return`M ${r[0].x} ${r[0].y}`;let n=Math.max(0,e),i=[],s=r.length,a=(o,c)=>{let l=c.x-o.x,u=c.y-o.y,d=Math.sqrt(l*l+u*u);return d>0?{dx:l/d,dy:u/d,len:d}:{dx:0,dy:0,len:0}};if(n===0){i.push(`M ${r[0].x} ${r[0].y}`);for(let o=1;o<s;o++)i.push(`L ${r[o].x} ${r[o].y}`)}else{let o=t?s:s-1;for(let c=0;c<=o;c++){let l=r[(c-1+s)%s],u=r[c%s],d=r[(c+1)%s];if(!t&&c===0){i.push(`M ${u.x} ${u.y}`);continue}if(!t&&c===s-1){i.push(`L ${u.x} ${u.y}`);continue}let h=a(l,u),f=a(u,d),p=Math.min(n,h.len/2),m=Math.min(n,f.len/2),g=u.x-h.dx*p,y=u.y-h.dy*p,b=u.x+f.dx*m,k=u.y+f.dy*m;c===0&&t?i.push(`M ${g} ${y}`):i.push(`L ${g} ${y}`),i.push(`Q ${u.x} ${u.y} ${b} ${k}`)}}return t&&i.push("Z"),i.join(" ")}var ki=class extends Tt{resolveState(e){return OS(e)}computeGeometry(){let{points:e,radius:t,closed:n}=this.fullState;return{points:e,radius:t,closed:n}}buildSVGPath(e){return LS(e.points,e.radius,e.closed)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}ensurePath(){this.fullState.points.length!==0&&super.ensurePath()}};var vr=new Map;function Fm(r,e,t){let n=[t[0],t[1],0,t[3],t[4],0,0,0,1],i=`${n.slice(0,5).map(o=>o.toFixed(5)).join(",")}|${e.toSVGString()}`,s=vr.get(i);if(s)return vr.delete(i),vr.set(i,s),s;let a=US(r,e,n);if(!a)return null;if(vr.set(i,a),vr.size>16){let[o,c]=vr.entries().next().value;vr.delete(o),c.image.delete()}return a}function Rm(){for(let r of vr.values())r.image.delete();vr.clear()}function US(r,e,t){let[n,i,s,a]=e.getBounds(),o=[n,s,n,s].map((E,O)=>t[0]*E+t[1]*(O<2?i:a)),c=[n,s,n,s].map((E,O)=>t[3]*E+t[4]*(O<2?i:a)),l=2,u=Math.floor(Math.min(...o))-l,d=Math.floor(Math.min(...c))-l,h=Math.ceil(Math.max(...o))+l-u,f=Math.ceil(Math.max(...c))+l-d;if(!(h>l*2)||!(f>l*2))return null;let p=h*f,m=p>15e5?Math.sqrt(15e5/p):1,g=p*m*m<=4e5?2:1,y=Math.max(1,Math.ceil(h*m)),b=Math.max(1,Math.ceil(f*m)),k=y*g,T=b*g,x=m*g,v=NS(r,e,t,k,T,x,u,d);if(!v)return null;let M=g===2?Im(Pm(v,k,T),k,T):Pm(v,k,T),C=0;for(let E=0;E<M.length;E++)M[E]/=x,M[E]>C&&(C=M[E]);if(!(C>0))return null;let _=Float32Array.from(v,E=>E/255);VS(M,g===2?Im(_,k,T):_,y,b,m),WS(M,y,b,C,m);let F=qS(r,M,y,b,C);return F?{image:F,originX:u,originY:d,texel:1/m,maxDistance:C}:null}function NS(r,e,t,n,i,s,a,o){let c=r.MakeSurface(n,i);if(!c)return null;let l=c.getCanvas();l.clear(r.TRANSPARENT),l.scale(s,s),l.translate(-a,-o),l.concat(t);let u=new r.Paint;u.setAntiAlias(!0),u.setColor(r.WHITE),l.drawPath(e,u),u.delete();let d=c.makeImageSnapshot(),h=d.readPixels(0,0,{width:n,height:i,colorType:r.ColorType.RGBA_8888,alphaType:r.AlphaType.Unpremul,colorSpace:r.ColorSpace.SRGB});if(d.delete(),c.delete(),!h)return null;let f=new Uint8Array(n*i);for(let p=0;p<f.length;p++)f[p]=h[p*4+3];return f}var zS=1e20;function Pm(r,e,t){let n=Math.max(e,t),i=new Float64Array(n),s=new Float64Array(n),a=new Int32Array(n),o=new Float64Array(n+1),c=new Float64Array(e*t);for(let u=0;u<e*t;u++)c[u]=r[u]>=128?zS:0;for(let u=0;u<e;u++){for(let d=0;d<t;d++)i[d]=c[d*e+u];Em(i,t,s,a,o);for(let d=0;d<t;d++)c[d*e+u]=s[d]}let l=new Float32Array(e*t);for(let u=0;u<t;u++){for(let d=0;d<e;d++)i[d]=c[u*e+d];Em(i,e,s,a,o);for(let d=0;d<e;d++)l[u*e+d]=s[d]>0?Math.max(0,Math.sqrt(s[d])-.5):0}return l}function Em(r,e,t,n,i){let s=0;n[0]=0,i[0]=-1/0,i[1]=1/0;for(let a=1;a<e;a++){let o=(r[a]+a*a-(r[n[s]]+n[s]*n[s]))/(2*a-2*n[s]);for(;o<=i[s];)s--,o=(r[a]+a*a-(r[n[s]]+n[s]*n[s]))/(2*a-2*n[s]);s++,n[s]=a,i[s]=o,i[s+1]=1/0}s=0;for(let a=0;a<e;a++){for(;i[s+1]<a;)s++;t[a]=(a-n[s])*(a-n[s])+r[n[s]]}}function Im(r,e,t){let n=e/2,i=t/2,s=new Float32Array(n*i);for(let a=0;a<i;a++)for(let o=0;o<n;o++){let c=2*a*e+2*o;s[a*n+o]=(r[c]+r[c+1]+r[c+e]+r[c+e+1])/4}return s}var Bs=2;function VS(r,e,t,n,i){let s=iu(e,t,n,Bs),a=iu(r,t,n,Bs),o=Math.sqrt(Bs*Bs+Bs)/i,c=1.5*o,l=2.5*o;for(let u=0;u<r.length;u++){let d=r[u];if(d<=0)continue;if(d>=l){r[u]=a[u];continue}let h=s[u],f=h>.5?o*HS(Math.min(h,.9999)):0,p=d<=c?0:(d-c)/(l-c);r[u]=f+(a[u]-f)*p*p*(3-2*p)}}function HS(r){let e=Math.sqrt(-2*Math.log(1-r));return e-(2.515517+.802853*e+.010328*e*e)/(1+1.432788*e+.189269*e*e+.001308*e*e*e)}function WS(r,e,t,n,i){let s=Math.max(1,Math.round(n*.08*i)),a=iu(r,e,t,s),o=n*.15,c=n*.6;for(let l=0;l<r.length;l++){let u=r[l];if(u<=o)continue;let d=Math.min(1,(u-o)/(c-o)),h=d*d*(3-2*d);r[l]=u+(a[l]-u)*h}}function iu(r,e,t,n){let i=Float32Array.from(r),s=new Float32Array(r.length);for(let a=0;a<3;a++)Mm(i,s,e,t,n,1,e),Mm(s,i,t,e,n,e,1);return i}function Mm(r,e,t,n,i,s,a){let o=2*i+1;for(let c=0;c<n;c++){let l=c*a,u=0;for(let d=-i;d<=i;d++)u+=r[l+nu(d,t)*s];for(let d=0;d<t;d++)e[l+d*s]=u/o,u+=r[l+nu(d+i+1,t)*s]-r[l+nu(d-i,t)*s]}}var nu=(r,e)=>r<0?0:r>=e?e-1:r;function qS(r,e,t,n,i){let s=new Uint16Array(t*n*4);for(let c=0;c<t*n;c++)s[c*4+3]=jS(Math.min(1,e[c]/i));let a=r.MakeImage({width:t,height:n,colorType:r.ColorType.RGBA_F16,alphaType:r.AlphaType.Premul,colorSpace:r.ColorSpace.SRGB},new Uint8Array(s.buffer),t*8);if(a)return a;let o=new Uint8Array(t*n*4);for(let c=0;c<t*n;c++)o[c*4+3]=Math.round(Math.min(1,e[c]/i)*255);return r.MakeImage({width:t,height:n,colorType:r.ColorType.RGBA_8888,alphaType:r.AlphaType.Premul,colorSpace:r.ColorSpace.SRGB},o,t*4)}var Bm=new Float32Array(1),GS=new Uint32Array(Bm.buffer);function jS(r){Bm[0]=r;let e=GS[0],t=(e>>>23&255)-112,n=e&8388607;return t<=0?t<-10?0:((n|8388608)>>13-t)+1>>1:(t<<10)+(n+4096>>13)}import{isStrokeMarker as Si,pathOps as Nm}from"@motionscript/core";var Om=Math.hypot(1,.5),Dm=.5/Om,KS=1/Om,$S=.35;function su(r){return r==="arrow"||r==="triangle"||r==="stealth"}function Lm(r,e,t){return su(r)?Math.min(e,t/(2*.5)):0}function Um(r,e,t){let n=e/2;switch(r){case"dot":return null;case"triangle":return[0,0,-e,e*.5,-e,-e*.5];case"stealth":return[0,0,-e,e*.5,-e*(1-$S),0,-e,-e*.5];case"arrow":return XS(e,t);case"box":return[-n,-n,n,-n,n,n,-n,n];case"diamond":return[n,0,0,n,-n,0,0,-n];case"bar":return[-t/2,-n,t/2,-n,t/2,n,-t/2,n]}}function XS(r,e){let t=r*.5,n=-r-e*Dm,i=t-e*KS;if(i<=0)return[0,0,-r,t,-r,-t];let s=-e/Dm;return[0,0,-r,t,n,i,s,0,n,-i,-r,-t]}var QS=1,Ds=.001,go=class{canvasKit;getCanvas;getPaint;fills;constructor(e,t,n,i){this.canvasKit=e,this.getCanvas=t,this.getPaint=n,this.fills=i}makeUniformDashEffect(e,t,n=0,i){let s=i??this.measureDashFit(e,t);return s?this.canvasKit.PathEffect.MakeDash(s.scaledDash,n*s.scale):null}measureDashFit(e,t){let n=0,i=!1,s=new this.canvasKit.ContourMeasureIter(e,!1,1),a=s.next();for(;a;)n+=a.length(),a.isClosed()||(i=!0),a.delete(),a=s.next();s.delete();let o=Nm.dashScale(t,{length:n,closed:!0},n);return o===null?null:{scaledDash:t.map(c=>c*o),scale:o,total:n,open:i}}buildDashedPath(e,t,n,i,s){let a=s??this.measureDashFit(e,t);if(!a)return null;let o=new this.canvasKit.PathBuilder,c=new this.canvasKit.ContourMeasureIter(e,!1,1),l=c.next(),u=!1;for(;l;){let d=l.length(),h=l.isClosed()?a.scale:Nm.dashScale(t,{length:d,closed:!1},a.total)??a.scale,f=t.map(M=>M*h),p=f.reduce((M,C)=>M+C,0),m=(n*h%p+p)%p,g=l,y=(M,C)=>{if(C-M>Ds){let _=g.getSegment(M,C,!0);_&&(o.addPath(_),_.delete(),u=!0)}else if(i){let[_,F,E,O]=g.getPosTan(M),Q=M>d-Ds?-Ds:Ds;o.moveTo(_,F),o.lineTo(_+E*Q,F+O*Q),u=!0}},b=0,k=0;for(;k+f[b]<=m&&b<f.length&&!(f[b]<=Ds&&Math.abs(m-k)<1e-6||(k+=f[b],b=(b+1)%f.length,b===0)););let T=f[b]-(m-k),x=b%2===0,v=0;for(;v<d-1e-6;){let M=Math.min(T,d-v);x&&y(v,v+M),v+=M,T-=M,T<=1e-6&&(b=(b+1)%f.length,T=f[b],x=!x)}x&&T<=1e-6&&!l.isClosed()&&y(d,d),l.delete(),l=c.next()}return c.delete(),u?o.detachAndDelete():(o.delete(),null)}ckCap(e){switch(e){case"round":return this.canvasKit.StrokeCap.Round;case"square":return this.canvasKit.StrokeCap.Square;default:return this.canvasKit.StrokeCap.Butt}}ckJoin(e){switch(e){case"round":return this.canvasKit.StrokeJoin.Round;case"bevel":return this.canvasKit.StrokeJoin.Bevel;default:return this.canvasKit.StrokeJoin.Miter}}applyCapJoin(e,t,n){e.setStrokeCap(this.ckCap(n)),e.setStrokeJoin(this.ckJoin(t.join)),e.setStrokeMiter(t.miterLimit)}strokeOpts(e,t,n){return{width:t,cap:this.ckCap(n),join:this.ckJoin(e.join),miter_limit:e.miterLimit}}capPlan(e,t,n,i){let s=e.startCap??e.cap,a=e.endCap??e.cap,o=n?e.cap:Si(a)?"butt":a,c=[];if(!t||s===o&&a===o)return{cap:o,ends:c};let l=(Si(s)?1:0)+(Si(a)?1:0),u=new this.canvasKit.ContourMeasureIter(t,!1,1);for(let d=u.next();d;d=u.next()){let h=d.length();if(!d.isClosed()&&h>0){let f=Math.min(e.capScale*i,h/Math.max(1,l)),p=m=>d.getPosTan(m);s!==o&&this.pushEnd(c,p(0),p(f),-1,s,f,i),a!==o&&this.pushEnd(c,p(h),p(h-f),1,a,f,i)}d.delete()}return u.delete(),{cap:o,ends:c}}pushEnd(e,[t,n,i,s],a,o,c,l,u){let d=o*i,h=o*s;Si(c)&&su(c)&&Math.hypot(t-a[0],n-a[1])>1e-6&&(d=t-a[0],h=n-a[1]);let f=Math.hypot(d,h);f<1e-9||e.push({x:t,y:n,dx:d/f,dy:h/f,cap:c,size:l,weight:u})}strokeBand(e,t,n,i){let s=e.makeStroked(this.strokeOpts(n,t,i.cap));if(!s||i.ends.length===0)return s;let a=t/2,o=Math.min(a,1)/2,c=i.ends.map(d=>s.contains(d.x-d.dx*o,d.y-d.dy*o)),l=a*1.01+.5,u=s;return i.ends.forEach((d,h)=>{if(Si(d.cap)){u=this.addMarker(u,d,d.cap,l,i.cap!=="butt");return}if(i.cap!=="butt"&&(u=this.combine(u,this.endBox(d,l,l),this.canvasKit.PathOp.Difference)),c[h]&&d.cap!=="butt"){let f=d.cap==="round"?this.endDisc(d,a):this.endBox(d,a,a);u=this.combine(u,f,this.canvasKit.PathOp.Union)}}),u}addMarker(e,t,n,i,s){let{x:a,y:o,dx:c,dy:l,size:u,weight:d}=t,h=Lm(n,u,d),f=e;if(h>0||s){let g={...t,x:a-c*h,y:o-l*h};f=this.combine(f,this.endBox(g,h+i,i),this.canvasKit.PathOp.Difference)}let p=Um(n,u,d),m=new this.canvasKit.PathBuilder;if(p){let g=new Array(p.length);for(let y=0;y<p.length;y+=2)g[y]=a+p[y]*c-p[y+1]*l,g[y+1]=o+p[y]*l+p[y+1]*c;m.addPolygon(g,!0)}else m.addCircle(a,o,u/2);return this.combine(f,m.detachAndDelete(),this.canvasKit.PathOp.Union)}endBox({x:e,y:t,dx:n,dy:i},s,a){let o=-i*a,c=n*a,l=n*s,u=i*s,d=new this.canvasKit.PathBuilder;return d.addPolygon([e+o,t+c,e+o+l,t+c+u,e-o+l,t-c+u,e-o,t-c],!0),d.detachAndDelete()}endDisc({x:e,y:t,dx:n,dy:i},s){let a=Math.atan2(n,-i)*180/Math.PI,o=new this.canvasKit.PathBuilder;return o.addArc([e-s,t-s,e+s,t+s],a,-180),o.close(),o.detachAndDelete()}combine(e,t,n){let i=this.canvasKit.Path.MakeFromOp(e,t,n);return t.delete(),i?(e.delete(),i):e}deviceMetrics(e){let t=e.getTotalMatrix(),n=Math.hypot(t[0],t[3]),i=Math.hypot(t[1],t[4]),s=Math.sqrt(Math.abs(t[0]*t[4]-t[1]*t[3])),a=Math.abs(t[1])>1e-6||Math.abs(t[3])>1e-6;return{sx:n,sy:i,scale:s,rotated:a,tx:t[2],ty:t[5]}}resolveStrokeWidth(e,t,n){if(e<=0||t<=0)return{logical:0,intDeviceWidth:-1};if(n)return{logical:e,intDeviceWidth:-1};let i=e*t;if(i>=2.5)return{logical:e,intDeviceWidth:-1};let s=Math.max(1,Math.round(i));return{logical:s/t,intDeviceWidth:s}}snapPath(e,t,n){if(t<=0||!n)return!1;let i=e.getTotalMatrix();if(Math.abs(i[1])>1e-6||Math.abs(i[3])>1e-6)return!1;let s=i[0],a=i[4],o=i[2],c=i[5];if(s===0||a===0)return!1;let l=n.getBounds(),u=l[2]-l[0],d=l[3]-l[1];if(u<=0||d<=0)return!1;let h=o+s*l[0],f=c+a*l[1],p=o+s*l[2],m=c+a*l[3],g=t%2===0?0:.5,y=Math.round(h-g)+g,b=Math.round(f-g)+g,k=Math.round(p-g)+g,T=Math.round(m-g)+g;if(k-y<1||T-b<1)return!1;let x=(k-y)/(p-h),v=(T-b)/(m-f);if(Math.abs(x-1)<1e-4&&Math.abs(v-1)<1e-4&&Math.abs(y-h)<1e-4&&Math.abs(b-f)<1e-4)return!1;let M=(y-o)/s-x*l[0],C=(b-c)/a-v*l[1];return e.save(),e.concat([x,0,M,0,v,C,0,0,1]),!0}applyStrokes(e,t,n){if(e.length===0)return!1;let i=this.getCanvas(),s=this.getPaint(),a=this.fills.openPass(e.flatMap(c=>c.fill),s,()=>{});s.setStyle(this.canvasKit.PaintStyle.Stroke);let o=this.fills.worldAlpha();for(let c of e){let l=c.weight??1,{scale:u,rotated:d}=this.deviceMetrics(i),{logical:h,intDeviceWidth:f}=this.resolveStrokeWidth(l,u,d);s.setStrokeWidth(h);for(let p of c.fill){let m=(p.opacity??1)*o;for(let g of t){n&&n(p,g);let y=b=>this.drawStrokeBand(i,b,g,c,h,f,u,a.clipFilterToShape);a.drawShape=y,this.fills.applyFill(a,p,m)&&!a.skipDefaultDraw&&y(s),this.fills.endFill(a)}}}return this.fills.closePass(a),s.setStyle(this.canvasKit.PaintStyle.Stroke),s.setStrokeCap(this.canvasKit.StrokeCap.Butt),s.setStrokeJoin(this.canvasKit.StrokeJoin.Miter),s.setStrokeMiter(4),!0}drawStrokeBand(e,t,n,i,s,a,o,c){let l=this.snapPath(e,a,n.ckPath),u=c?this.strokeOutline(n,i,s):null;u&&(e.save(),e.clipPath(u,this.canvasKit.ClipOp.Intersect,!0)),this.drawStroke(e,t,n,i,s,a,o),u&&(e.restore(),u.delete()),l&&e.restore()}strokeOutline(e,t,n){if(e.isText)return null;let i=e.strokePath??e.ckPath;if(!i)return null;let s=t.dash&&t.dash.length>0?this.buildDashedPath(i,t.dash,t.dashOffset??0,t.cap!=="butt"):null,a=this.alignedStrokeBand(s??i,n,t.align??0,e.alignInterior??e.ckPath,t,this.capPlan(t,i,!!s,n));return s?.delete(),a}drawStroke(e,t,n,i,s,a,o){let c=n.isText?void 0:n.strokePath??n.ckPath,l=n.strokeDraw??n.draw,u=!!(i.dash&&i.dash.length>0),d=this.capPlan(i,c,u,s);if(this.applyCapJoin(t,i,d.cap),n.isText){this.drawTextUnionStroke(e,t,n,i,s,o);return}let h=u&&c?this.measureDashFit(c,i.dash):null,f=i.align??0,p=n.alignInterior??n.ckPath;if((a>0||d.ends.length>0||h?.open)&&c){let m=u?this.buildDashedPath(c,i.dash,i.dashOffset??0,i.cap!=="butt",h??void 0):c;if(m){let g=this.alignedStrokeBand(m,s,f,p,i,d);if(m!==c&&m.delete(),g){t.setStyle(this.canvasKit.PaintStyle.Fill),e.drawPath(g,t),t.setStyle(this.canvasKit.PaintStyle.Stroke),g.delete();return}}}if(f!==0&&!u&&c){let m=this.alignedStrokeBand(c,s,f,p,i,d);if(m){t.setStyle(this.canvasKit.PaintStyle.Fill),e.drawPath(m,t),t.setStyle(this.canvasKit.PaintStyle.Stroke),m.delete();return}}if(u&&c){let m=this.makeUniformDashEffect(c,i.dash,i.dashOffset??0,h??void 0);if(m){t.setPathEffect(m),f!==0&&a<=0&&p&&this.isClosedPath(p)?this.drawAlignedDashedStroke(e,t,c,p,f):e.drawPath(c,t),t.setPathEffect(null),m.delete();return}}l(t)}alignedStrokeBand(e,t,n,i,s,a){if(n===0||!i||!this.isClosedPath(i)||a.ends.some(p=>Si(p.cap)))return this.strokeBand(e,t,s,a);let o=Math.max(-1,Math.min(1,n)),c=(1+o)*t,l=(1-o)*t,u=(p,m)=>{if(p<=0)return null;let g=this.strokeBand(e,p,s,a);if(!g)return null;let y=this.canvasKit.Path.MakeFromOp(g,i,m);return g.delete(),y},d=u(c,this.canvasKit.PathOp.Difference),h=u(l,this.canvasKit.PathOp.Intersect);if(!d||!h)return d??h;let f=this.canvasKit.Path.MakeFromOp(d,h,this.canvasKit.PathOp.Union);return d.delete(),h.delete(),f}isClosedPath(e){let t=new this.canvasKit.ContourMeasureIter(e,!1,1),n=t.next();if(!n)return t.delete(),!1;let i=!0;for(;n;)n.isClosed()||(i=!1),n.delete(),n=t.next();return t.delete(),i}drawAlignedDashedStroke(e,t,n,i,s){let a=t.getStrokeWidth(),o=Math.max(-1,Math.min(1,s)),c=[[(1+o)*a,this.canvasKit.ClipOp.Difference],[(1-o)*a,this.canvasKit.ClipOp.Intersect]];for(let[l,u]of c)l<=0||(e.save(),t.setStrokeWidth(l),e.clipPath(i,u,!0),e.drawPath(n,t),e.restore());t.setStrokeWidth(a)}drawTextUnionStroke(e,t,n,i,s,a){let o=!!(i.dash&&i.dash.length>0),c=null;o&&(c=this.canvasKit.PathEffect.MakeDash(i.dash,i.dashOffset??0),t.setPathEffect(c));let l=i.align??0;l===0?(t.setStrokeWidth(s),n.draw(t)):Math.abs(l)<1?(this.drawTextPartiallyAlignedStroke(e,t,n,i,s,l),t.setStrokeWidth(s)):(e.saveLayer(),t.setStrokeWidth(s*2),n.draw(t),this.applyTextAlignMask(e,n,l,s,a),e.restore(),t.setStrokeWidth(s)),c&&(t.setPathEffect(null),c.delete())}drawTextPartiallyAlignedStroke(e,t,n,i,s,a){let o=(1+a)*s/2,c=(1-a)*s/2;e.saveLayer(),t.setStrokeWidth(2*Math.max(o,c)),n.draw(t);let l=a>0,u=new this.canvasKit.Paint;u.setBlendMode(this.canvasKit.BlendMode.DstOut),e.saveLayer(u);let d=new this.canvasKit.Paint;d.setAntiAlias(!0),d.setColor(this.canvasKit.WHITE),d.setStyle(this.canvasKit.PaintStyle.Fill),l||(e.drawPaint(d),d.setBlendMode(this.canvasKit.BlendMode.Clear)),n.draw(d),d.setBlendMode(this.canvasKit.BlendMode.Clear),d.setStyle(this.canvasKit.PaintStyle.Stroke),d.setStrokeWidth(2*(l?c:o)),d.setStrokeJoin(this.ckJoin(i.join)),d.setStrokeMiter(i.miterLimit),n.draw(d),d.delete(),e.restore(),u.delete(),e.restore()}applyTextAlignMask(e,t,n,i,s){let a=n>0,o=new this.canvasKit.Paint;o.setBlendMode(a?this.canvasKit.BlendMode.DstOut:this.canvasKit.BlendMode.DstIn),e.saveLayer(o);let c=new this.canvasKit.Paint;c.setAntiAlias(!0),c.setColor(this.canvasKit.WHITE),c.setStyle(this.canvasKit.PaintStyle.Fill);let l=s>0?Math.min(QS/s,i):0,u=l>0?a?this.canvasKit.ImageFilter.MakeErode(l,l,null):this.canvasKit.ImageFilter.MakeDilate(l,l,null):null;u&&c.setImageFilter(u),t.draw(c),u&&(c.setImageFilter(null),u.delete()),c.delete(),e.restore(),o.delete()}applyShadows(e,t,n,i,s){if(e.length===0)return;let a=this.getPaint(),o=n.length>0&&n.some(d=>(d.opacity??1)>0),c=i.length>0,l=this.fills.worldAlpha(),u=this.fills.openShadowPass(e.flatMap(d=>d.fill),a);for(let d of e)d.inner||this.applyDropShadow(d,t,o,c,i,l,u,s);this.fills.closePass(u),a.setStyle(this.canvasKit.PaintStyle.Fill),a.setPathEffect(null),a.setStrokeCap(this.canvasKit.StrokeCap.Butt),a.setStrokeJoin(this.canvasKit.StrokeJoin.Miter),a.setStrokeMiter(4)}applyInnerShadows(e,t,n,i){if(e.length===0)return;let s=this.getPaint(),a=n.length>0&&n.some(l=>(l.opacity??1)>0),o=this.fills.worldAlpha(),c=this.fills.openShadowPass(e.flatMap(l=>l.fill),s);for(let l of e)l.inner&&this.applyInnerShadow(l,t,a,o,c,i);this.fills.closePass(c),s.setStyle(this.canvasKit.PaintStyle.Fill),s.setPathEffect(null)}applyDropShadow(e,t,n,i,s,a,o,c){let l=this.getCanvas(),u=o.paint,d=e.offset?.x??0,h=e.offset?.y??0,f=e.spread!==0&&n?t.map(m=>m.spreadPath?.(e.spread)??null):null,p=m=>{if(n){m.setStyle(this.canvasKit.PaintStyle.Fill),m.setPathEffect(null);for(let g=0;g<t.length;g++){let y=f?.[g];y?l.drawPath(y,m):t[g].draw(m)}}if(i){m.setStyle(this.canvasKit.PaintStyle.Stroke);for(let g of s){let y=g.weight??1,{scale:b,rotated:k}=this.deviceMetrics(l),{logical:T,intDeviceWidth:x}=this.resolveStrokeWidth(y,b,k);m.setStrokeWidth(T),m.setPathEffect(null);for(let v of t){let M=this.snapPath(l,x,v.ckPath);this.drawStroke(l,m,v,g,T,x,b),M&&l.restore()}}}};o.drawShape=p;for(let m of e.fill){let g=(m.opacity??1)*a,y=new this.canvasKit.Paint;if(y.setAlphaf(g),e.blur>0){let b=e.blur/2,k=this.canvasKit.ImageFilter.MakeBlur(b,b,this.canvasKit.TileMode.Decal,null);y.setImageFilter(k)}l.save(),l.translate(d,-h),l.saveLayer(y),c&&c(m,null),this.fills.applyFill(o,m,1,!1)&&!o.skipDefaultDraw&&p(u),this.fills.endFill(o),l.restore(),l.restore(),y.delete()}if(f)for(let m of f)m?.delete()}applyInnerShadow(e,t,n,i,s,a){if(!n)return;let o=this.getCanvas(),c=s.paint,l=e.offset?.x??0,u=-(e.offset?.y??0);for(let d of t){if(!d.ckPath)continue;let h=e.spread!==0&&!!d.spreadPath,f=h?d.spreadPath(-e.spread):null,p=f??(h?null:d.ckPath),m=this.buildInnerShadowRegion(p,d.ckPath,l,u,e.blur);if(!m){f?.delete();continue}let g=y=>{y.setStyle(this.canvasKit.PaintStyle.Fill),y.setPathEffect(null),o.drawPath(m,y)};s.drawShape=g;for(let y of e.fill){let b=(y.opacity??1)*i,k=new this.canvasKit.Paint;if(k.setAlphaf(b),e.blur>0){let T=e.blur/2,x=this.canvasKit.ImageFilter.MakeBlur(T,T,this.canvasKit.TileMode.Decal,null);k.setImageFilter(x)}o.save(),o.clipPath(d.ckPath,this.canvasKit.ClipOp.Intersect,!0),o.saveLayer(k),a&&a(y,null),this.fills.applyFill(s,y,1,!1)&&!s.skipDefaultDraw&&g(c),this.fills.endFill(s),o.restore(),o.restore(),k.delete()}m.delete(),f?.delete()}}buildInnerShadowRegion(e,t,n,i,s){let a=t.getBounds(),o=s*2+Math.abs(n)+Math.abs(i)+1,c=new this.canvasKit.PathBuilder;c.addRect([a[0]-o,a[1]-o,a[2]+o,a[3]+o]);let l=c.detachAndDelete();if(!e)return l;let u=new this.canvasKit.PathBuilder(e);u.offset(n,i);let d=u.detachAndDelete(),h=this.canvasKit.Path.MakeFromOp(l,d,this.canvasKit.PathOp.Difference);return l.delete(),d.delete(),h}};var yo=class{canvasKit;getCanvas;pathCollectionStack=[];booleanOpStack=[];constructor(e,t){this.canvasKit=e,this.getCanvas=t}dispose(){this.pathCollectionStack=[],this.booleanOpStack=[]}resetPass(){for(let e of this.pathCollectionStack)for(let t of e.paths)t.delete();this.pathCollectionStack=[],this.booleanOpStack=[]}isCollecting(){return this.pathCollectionStack.length>0}contributeToPathCollection(e){if(this.pathCollectionStack.length===0)return;let t=this.pathCollectionStack[this.pathCollectionStack.length-1],n=this.getCanvas().getTotalMatrix(),i=this.canvasKit.Matrix.multiply(t.invBaseMatrix,n),s=new this.canvasKit.PathBuilder;s.addPath(e,i),t.paths.push(s.detachAndDelete())}pushFrame(){let e=Array.from(this.getCanvas().getTotalMatrix()),t=this.canvasKit.Matrix.invert(e)??this.canvasKit.Matrix.identity();this.pathCollectionStack.push({paths:[],invBaseMatrix:t})}popFrame(){let e=this.pathCollectionStack.pop();return e?e.paths:[]}toCanvasKitPathOp(e){switch(e){case"subtract":return this.canvasKit.PathOp.Difference;case"intersect":return this.canvasKit.PathOp.Intersect;case"exclude":return this.canvasKit.PathOp.XOR;default:return this.canvasKit.PathOp.Union}}combinePaths(e,t){if(e.length===0)return null;let n=this.toCanvasKitPathOp(t),i=e[0];for(let s=1;s<e.length;s++){let a=this.canvasKit.Path.MakeFromOp(i,e[s],n);if(i.delete(),e[s].delete(),!a){for(let o=s+1;o<e.length;o++)e[o].delete();return null}i=a}return i}beginBoolean(e){this.pushFrame(),this.booleanOpStack.push(e)}endBoolean(e){let t=this.booleanOpStack.pop()??"union",n=this.popFrame(),i=this.combinePaths(n,t);if(!i)return null;this.contributeToPathCollection(i);let s=e();return{draw:o=>{s.drawPath(i,o)},ckPath:i}}};var wo=class{canvasKit;getCanvas;boolean;maskStack=[];constructor(e,t,n){this.canvasKit=e,this.getCanvas=t,this.boolean=n}dispose(){this.maskStack=[]}resetPass(){this.maskStack=[]}beginMask(e){let t=this.getCanvas(),n=e?.mode??"alpha",i=e?.inverted??!1,s=e?.apply,a=s!=null?new Set(Array.isArray(s)?s:[s]):null;if(n==="vector"){t.save(),this.boolean.pushFrame(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:1});return}if(n==="luminance"){t.saveLayer();let o=new this.canvasKit.Paint,c=this.canvasKit.ColorFilter.MakeMatrix([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,.2126,.7152,.0722,0,0]);o.setColorFilter(c),t.saveLayer(o),o.delete(),c.delete(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:2});return}t.saveLayer(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:2})}getApply(){return this.maskStack[this.maskStack.length-1]?.apply??null}applyMask(e){let t=this.getCanvas(),n=this.maskStack[this.maskStack.length-1];if(!n){console.warn("applyMask() called outside of a mask scope.");return}if(n.mode==="vector"){let s=this.boolean.popFrame(),a=this.boolean.combinePaths(s,"union");if(e(),a){let o=n.inverted?this.canvasKit.ClipOp.Difference:this.canvasKit.ClipOp.Intersect;t.clipPath(a,o,!0),a.delete()}return}n.mode==="luminance"&&t.restore();let i=new this.canvasKit.Paint;i.setBlendMode(n.inverted?this.canvasKit.BlendMode.SrcOut:this.canvasKit.BlendMode.SrcIn),t.saveLayer(i),i.delete(),e()}endMask(){let e=this.maskStack.pop();if(!e)return;let t=this.getCanvas();for(let n=0;n<e.restores;n++)t.restore()}};function bo(r,e){if(r===e)return!0;if(typeof r!="object"||typeof e!="object"||r===null||e===null)return!1;if("x"in r&&"y"in r&&"x"in e&&"y"in e){let n=r,i=e;return n.x===i.x&&n.y===i.y}if(Array.isArray(r)&&Array.isArray(e)){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!bo(r[n],e[n]))return!1;return!0}let t=["topLeft","topRight","bottomRight","bottomLeft"];if(t.every(n=>n in r)&&t.every(n=>n in e)){for(let n of t)if(!bo(r[n],e[n]))return!1;return!0}return!1}function YS(r){return{left:r[0],top:r[1],right:r[2],bottom:r[3]}}function ZS(r,e){let t=Object.keys(r);if(t.length!==Object.keys(e).length)return!1;for(let n of t)if(!bo(r[n],e[n]))return!1;return!0}function JS(r,e,...t){let n=new Set(t),i=Object.keys(r).filter(a=>!n.has(a)),s=Object.keys(e).filter(a=>!n.has(a));if(i.length!==s.length)return!1;for(let a of i)if(!bo(r[a],e[a]))return!1;return!0}var ko=class{canvasKit;getCanvas;getPaint;fontMgr;paragraphCache;getFontEpoch;shapes=[];paintApplied=!1;pendingShadows=null;boolean;mask;boundsOverride=[];shapeCache=new Map;currentNodeId="";shapeIndex=0;_cachedBounds=null;_boundsDirty=!0;transientPaths=new Set;_measuring=!1;_measureShapes=[];_savedNodeId="";_savedShapeIndex=0;constructor(e,t,n,i,s,a){this.canvasKit=e,this.getCanvas=t,this.getPaint=n,this.fontMgr=i,this.paragraphCache=s,this.getFontEpoch=a,this.boolean=new yo(e,t),this.mask=new wo(e,t,this.boolean)}beginNode(e){this.currentNodeId=e,this.shapeIndex=0}reset(){for(let e of this.transientPaths)e.delete();this.transientPaths.clear(),this.shapes=[],this.paintApplied=!1,this.pendingShadows=null,this._boundsDirty=!0,this._cachedBounds=null}storePendingShadows(e){this.pendingShadows=e.length>0?e:null}takePendingShadows(){let e=this.pendingShadows;return this.pendingShadows=null,e}dispose(){this.shapes=[];for(let e of this.transientPaths)e.delete();this.transientPaths.clear();for(let e of this.shapeCache.values())e.shape.deletePaths();this.shapeCache.clear(),this.boolean.dispose(),this.mask.dispose()}resetPass(){this._measuring&&this.endMeasure(),this.reset(),this.boundsOverride.length=0,this.boolean.resetPass(),this.mask.resetPass(),this.currentNodeId="",this.shapeIndex=0}isCollectingPaths(){return this.boolean.isCollecting()}pushBounds(e){this.boundsOverride.push(e)}popBounds(){this.boundsOverride.pop()}getShapeBounds(){if(this.boundsOverride.length>0)return this.boundsOverride[this.boundsOverride.length-1];if(!this._boundsDirty&&this._cachedBounds!==null)return this._cachedBounds;let e=1/0,t=1/0,n=-1/0,i=-1/0;for(let s of this.shapes){let a=s.paintBounds??(s.ckPath?YS(s.ckPath.getBounds()):s.bounds);a&&(a.left<e&&(e=a.left),a.top<t&&(t=a.top),a.right>n&&(n=a.right),a.bottom>i&&(i=a.bottom))}return this._boundsDirty=!1,this._cachedBounds=isFinite(e)?{left:e,top:t,right:n,bottom:i}:null,this._cachedBounds}addShape(e){this._boundsDirty=!0;let t=!this.boolean.isCollecting(),n=e;if(this.currentNodeId){let i=`${this.currentNodeId}:${this.shapeIndex++}`,s=this.shapeCache.get(i);if(s){let a=s.shape,o=e.inputState,c=a.inputState;if(ZS(o,c))n=a;else if(a.hasTrim()&&e.hasTrim()&&JS(o,c,"start","end")){let{start:l,end:u}=e.trimRange();(s.trimStart!==l||s.trimEnd!==u)&&(a.retrim(l,u),s.trimStart=l,s.trimEnd=u),a.inputState=e.inputState,n=a}else{a.deletePaths();let l=e.hasTrim()?e.trimRange():{start:0,end:1};this.shapeCache.set(i,{shape:e,trimStart:l.start,trimEnd:l.end}),n=e}}else{let a=e.hasTrim()?e.trimRange():{start:0,end:1};this.shapeCache.set(i,{shape:e,trimStart:a.start,trimEnd:a.end})}}n.ensurePath(),this._measuring&&this._measureShapes.push(n),!t&&n.ckPath&&this.boolean.contributeToPathCollection(n.ckPath),this.shapes.push(n.toCurrentShape(t))}rect(e){this.addShape(new pi(this.canvasKit,this.getCanvas,e))}ellipse(e){this.addShape(new gi(this.canvasKit,this.getCanvas,e))}path(e){this.addShape(new bi(this.canvasKit,this.getCanvas,e))}line(e){this.addShape(new ki(this.canvasKit,this.getCanvas,e))}polygon(e){this.addShape(new yi(this.canvasKit,this.getCanvas,e))}polygram(e){this.addShape(new wi(this.canvasKit,this.getCanvas,e))}text(e){this._boundsDirty=!0;let t=Tm(this.canvasKit,this.getCanvas(),this.fontMgr,e,this.paragraphCache,this.getFontEpoch());this.shapes.push(t)}cut(){let e=this.shapes.filter(a=>a.ckPath);if(e.length===0)return;let t=e[e.length-1].ckPath.copy(),n=e.slice(0,-1),i;if(n.length===0)t.delete(),i=e[0].ckPath.copy();else{let a=this.boolean.combinePaths(n.map(o=>o.ckPath.copy()),"union");a?i=this.boolean.combinePaths([a,t],"subtract"):(t.delete(),i=null)}for(let a of this.shapes)a.ckPath&&this.transientPaths.has(a.ckPath)&&(a.ckPath.delete(),this.transientPaths.delete(a.ckPath));if(this.shapes=[],this.paintApplied=!1,!i)return;this.transientPaths.add(i);let s=this.getCanvas();this.shapes.push({draw:a=>{s.drawPath(i,a)},ckPath:i})}beginMeasure(){this._savedNodeId=this.currentNodeId,this._savedShapeIndex=this.shapeIndex,this.currentNodeId="",this._measuring=!0,this._measureShapes=[],this.shapes=[]}endMeasure(){for(let e of this._measureShapes)e.deletePaths();this._measureShapes=[],this._measuring=!1,this.currentNodeId=this._savedNodeId,this.shapeIndex=this._savedShapeIndex,this.shapes=[],this._boundsDirty=!0,this._cachedBounds=null}beginNested(){let e={nodeId:this.currentNodeId,shapeIndex:this.shapeIndex,shapes:this.shapes,paintApplied:this.paintApplied,pendingShadows:this.pendingShadows,transientPaths:this.transientPaths};return this.shapes=[],this.paintApplied=!1,this.pendingShadows=null,this.transientPaths=new Set,this._boundsDirty=!0,this._cachedBounds=null,e}endNested(e){for(let t of this.transientPaths)t.delete();this.currentNodeId=e.nodeId,this.shapeIndex=e.shapeIndex,this.shapes=e.shapes,this.paintApplied=e.paintApplied,this.pendingShadows=e.pendingShadows,this.transientPaths=e.transientPaths,this._boundsDirty=!0,this._cachedBounds=null}measureUnionBounds(){let e=1/0,t=1/0,n=-1/0,i=-1/0;for(let s of this.shapes)if(s.ckPath&&!s.ckPath.isEmpty()){let a=s.ckPath.getBounds();a[0]<e&&(e=a[0]),a[1]<t&&(t=a[1]),a[2]>n&&(n=a[2]),a[3]>i&&(i=a[3])}else s.bounds&&(s.bounds.left<e&&(e=s.bounds.left),s.bounds.top<t&&(t=s.bounds.top),s.bounds.right>n&&(n=s.bounds.right),s.bounds.bottom>i&&(i=s.bounds.bottom));return isFinite(e)?{left:e,top:t,right:n,bottom:i}:null}unionStrokeShape(){if(this.shapes.some(a=>a.isText))return null;let e=this.shapes.filter(a=>a.ckPath);if(e.length<2)return null;let t=this.boolean.combinePaths(e.map(a=>a.ckPath.copy()),"union");if(!t)return null;let n=e.some(a=>a.strokePath&&a.strokePath!==a.ckPath||a.trimmed||this.hasOpenContour(a.ckPath)),i;if(n){let a=new this.canvasKit.PathBuilder;for(let o of e)a.addPath(o.strokePath??o.ckPath);i=a.detachAndDelete()}let s=this.getCanvas();return{draw:a=>{s.drawPath(t,a)},strokeDraw:a=>{s.drawPath(i??t,a)},ckPath:t,strokePath:i}}hasOpenContour(e){let t=new this.canvasKit.ContourMeasureIter(e,!1,1),n=!1;for(let i=t.next();i&&(i.isClosed()||(n=!0),i.delete(),!n);i=t.next());return t.delete(),n}beginBoolean(e){this.boolean.beginBoolean(e)}endBoolean(){let e=this.boolean.endBoolean(this.getCanvas);this.shapes=[],this.paintApplied=!1,e&&this.shapes.push(e)}beginMask(e){this.mask.beginMask(e)}applyMask(){this.mask.applyMask(()=>{this.shapes=[],this.paintApplied=!1})}endMask(){this.mask.endMask()}getMaskApply(){return this.mask.getApply()}};import{AssetNotLoadedError as ex,resolveVideoTimestamp as tx}from"@motionscript/core";var So=class r extends qe{static MAX_ECHOES=32;applyPaint(e,t){if(!e.src)return Za(t);let n=t.assets.getVideoDuration(e.src);if(n===0)throw new ex("video",e.src);let i=tx(e,t.elapsed,n),s=t.assets.getVideoSize(e.src),a=t.getShapeBounds(),o=s?Kl(e,s,a,t):void 0,c=t.assets.claimVideoFrame(e.src,i,o);if(!c)return!1;let l=e.preset?.adjustments.find(d=>d.type==="echo");if(l&&l.echoes>0&&l.delay>0)return this.drawEchoStack(e,t,l,c,i,s,o),t.skipDefaultDraw=!0,!0;let u=Es(c,e,t.canvasKit,a,oo(e),{logical:s});return t.transientPaintObjects.push(u),t.paint.setShader(co(e,t,u)),!0}drawEchoStack(e,t,n,i,s,a,o){let{paint:c,canvasKit:l}=t,u=n.decay??.5,d=Kt(l,n.blend??"screen"),h=Math.min(Math.max(0,Math.floor(n.echoes)),r.MAX_ECHOES),f=Ya(e,t)*t.worldAlpha,p=t.getShapeBounds();for(let g=h;g>=1;g--){let y=s-g*n.delay;if(y<0)continue;let b=t.assets.getVideoFrameImage(e.src,y,o);if(!b)continue;t.transientImages.push(b);let k=Es(b,e,l,p,"linear",{logical:a});t.transientPaintObjects.push(k),c.setShader(k),c.setImageFilter(null),c.setAlphaf(f*Math.pow(u,g)),c.setBlendMode(d),t.drawShape(c)}let m=Es(i,e,l,p,oo(e),{logical:a});t.transientPaintObjects.push(m),c.setShader(co(e,t,m)),c.setAlphaf(f),c.setBlendMode(d),t.drawShape(c),c.setShader(null),c.setImageFilter(null),c.setAlphaf(f),c.setBlendMode(e.blend?Kt(l,e.blend):l.BlendMode.SrcOver)}};var rn=class{limit;map=new Map;constructor(e=256){this.limit=e}get(e,t){let n=this.map.get(e);if(n)return this.map.delete(e),this.map.set(e,n),n;let i=t();if(this.map.set(e,i),this.map.size>this.limit){let s=this.map.keys().next().value;s!==void 0&&(this.map.get(s)?.delete(),this.map.delete(s))}return i}dispose(){for(let e of this.map.values())e.delete();this.map.clear()}};function xi(r,e){return e.map(t=>r.Color4f(t[0],t[1],t[2],t[3]))}function At(r,e){for(let t=0;t<e.length;t++)r.push(e[t].toFixed(4))}function zm(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var xo=class extends qe{cache=new rn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let s=zm(e.start.x,e.start.y,i),a=zm(e.end.x,e.end.y,i),o=["L"];At(o,s),At(o,a);for(let u of e.colors)At(o,u);o.push("|"),At(o,e.stops);let c=o.join(","),l=this.cache.get(c,()=>{let u=xi(n,e.colors),d=e.stops.length===u.length?e.stops:u.map((h,f)=>f/(u.length-1));return n.Shader.MakeLinearGradient(s,a,u,d,n.TileMode.Clamp)});return t.paint.setShader(l),!0}dispose(){this.cache.dispose()}};function rx(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var To=class extends qe{cache=new rn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let s=rx(e.center.x,e.center.y,i),a=["R"];At(a,s),At(a,[e.radius]);for(let l of e.colors)At(a,l);a.push("|"),At(a,e.stops);let o=a.join(","),c=this.cache.get(o,()=>{let l=xi(n,e.colors),u=e.stops.length===l.length?e.stops:l.map((d,h)=>h/(l.length-1));return n.Shader.MakeRadialGradient(s,e.radius,l,u,n.TileMode.Clamp)});return t.paint.setShader(c),!0}dispose(){this.cache.dispose()}};function nx(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var Ao=class extends qe{cache=new rn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let[s,a]=nx(e.center.x,e.center.y,i),o=e.startAngle??0,c=["C"];At(c,[s,a,o]);for(let d of e.colors)At(c,d);c.push("|"),At(c,e.stops);let l=c.join(","),u=this.cache.get(l,()=>{let d=xi(n,e.colors),h=e.stops.length===d.length?e.stops:d.map((f,p)=>p/(d.length-1));return n.Shader.MakeSweepGradient(s,a,d,h,n.TileMode.Clamp,null,0,o,o+360)});return t.paint.setShader(u),!0}dispose(){this.cache.dispose()}};var ix=24,Ti=new Map;function sx(r,e){for(Ti.set(r,e);Ti.size>ix;){let t=Ti.keys().next();if(t.done)break;Ti.get(t.value)?.delete?.(),Ti.delete(t.value)}}function ax(r,e,t){let[n,i,s,a]=r.color;return`${e}x${t}|${r.size.x},${r.size.y}|${r.density}|${r.seed}|${n},${i},${s},${a}`}function Vm(r,e,t){let n=(r*1664525+1013904223^e*1664525*1664525+1013904223)+t>>>0;return n^=n>>>17,n=Math.imul(n,2654435769)>>>0,n^=n>>>13,n=Math.imul(n,1818371886)>>>0,n^=n>>>16,(n>>>0)/4294967296}function ox(r,e,t){let[n,i,s,a]=t.color,o=Math.round(n*255),c=Math.round(i*255),l=Math.round(s*255),u=Math.round(a*255),d=Math.max(1,Math.round(t.size.x)),h=Math.max(1,Math.round(t.size.y)),f=Math.min(1,Math.max(0,t.density)),p=Math.round(t.seed),m=new Uint8Array(r*e*4);for(let g=0;g<e;g++){let y=Math.floor(g/h);for(let b=0;b<r;b++){let k=Math.floor(b/d),T=Vm(k,y,p),x=(g*r+b)*4;if(T<f){let v=Vm(k,y,p+1);m[x]=Math.round(o*v),m[x+1]=Math.round(c*v),m[x+2]=Math.round(l*v),m[x+3]=u}}}return m}var vo=class extends qe{applyPaint(e,t){let n=t.getShapeBounds(),i=n?Math.ceil(n.right-n.left):256,s=n?Math.ceil(n.bottom-n.top):256;if(i<=0||s<=0)return!1;let a=ax(e,i,s),o=Ti.get(a);if(!o){let h=ox(i,s,e);if(o=t.canvasKit.MakeImage({width:i,height:s,alphaType:t.canvasKit.AlphaType.Unpremul,colorType:t.canvasKit.ColorType.RGBA_8888,colorSpace:t.canvasKit.ColorSpace.SRGB},h,4*i),!o)return!1;sx(a,o)}let c=n?.left??0,l=n?.top??0,u=[1,0,c,0,1,l,0,0,1],d=o.makeShaderOptions(t.canvasKit.TileMode.Repeat,t.canvasKit.TileMode.Repeat,t.canvasKit.FilterMode.Nearest,t.canvasKit.MipmapMode.None,u);return t.paint.setShader(d),t.transientPaintObjects.push(d),!0}};var cx=8,lx=`
|
|
1817
1671
|
vec2 hash2(vec2 p) {
|
|
1818
1672
|
vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
|
|
1819
1673
|
p3 += dot(p3, p3.yzx + 33.33);
|
|
@@ -1870,7 +1724,7 @@ float worleyNoise(vec2 p) {
|
|
|
1870
1724
|
}
|
|
1871
1725
|
return best;
|
|
1872
1726
|
}
|
|
1873
|
-
`;function
|
|
1727
|
+
`;function ux(r,e,t){let i=r==="ridged"?`
|
|
1874
1728
|
float prev = 1.0;
|
|
1875
1729
|
for (int o = 0; o < ${e}; o++) {
|
|
1876
1730
|
float r = 1.0 - abs(simplexNoise(q) * 2.0 - 1.0);
|
|
@@ -1886,7 +1740,7 @@ float worleyNoise(vec2 p) {
|
|
|
1886
1740
|
total += amplitude;
|
|
1887
1741
|
amplitude *= u_gain;
|
|
1888
1742
|
q *= u_lacunarity;
|
|
1889
|
-
}`;return`${
|
|
1743
|
+
}`;return`${lx}
|
|
1890
1744
|
uniform vec2 u_origin; // shape bounds origin, shape-local logical px
|
|
1891
1745
|
uniform vec2 u_size; // shape bounds size, shape-local logical px
|
|
1892
1746
|
uniform vec2 u_frequency; // cycles of the first octave across the shape
|
|
@@ -1933,7 +1787,7 @@ ${i}
|
|
|
1933
1787
|
// would square them.
|
|
1934
1788
|
return vec4(color.rgb * color.a, color.a);
|
|
1935
1789
|
}
|
|
1936
|
-
`}var
|
|
1790
|
+
`}var _o=class extends qe{live=null;replaceLive(e){this.live?.delete(),this.live=e}applyPaint(e,t){let n=t.getShapeBounds();if(!n)return!1;let i=n.right-n.left,s=n.bottom-n.top;if(i<=0||s<=0)return!1;let a=Math.max(2,Math.min(cx,e.colors.length)),o=ue(ux(e.basis,e.octaves,a),t.canvasKit);if(!o)return!1;let c=e.angle*Math.PI/180,l=[],u=[];for(let h=0;h<a;h++){let f=e.colors[Math.min(h,e.colors.length-1)];l.push(f[0],f[1],f[2],f[3]),u.push(e.stops[Math.min(h,e.stops.length-1)]??h/(a-1))}let d=o.makeShader([n.left,n.top,i,s,e.frequency.x,e.frequency.y,e.offset.x,e.offset.y,e.lacunarity,e.gain,e.seed,Math.cos(c),Math.sin(c),e.contrast,...l,...u]);return d?(this.replaceLive(d),t.paint.setShader(d),!0):!1}dispose(){this.replaceLive(null)}};import{coordsMatrix as dx,writeUniforms as hx}from"@motionscript/core";var Co=new Map;function fx(r,e,t){let n=t.canvasKit,i=Co.get(r);if(i&&i.image===e)return i.shader;i?.shader.delete();let s=t.assets.getImageSize(r),a=s?so(Hm,s.width,s.height,e.width(),e.height()):Hm,o=e.makeShaderOptions(n.TileMode.Repeat,n.TileMode.Repeat,n.FilterMode.Linear,n.MipmapMode.None,a);return Co.set(r,{image:e,shader:o}),o}var Hm=[1,0,0,0,1,0,0,0,1],Po=class extends qe{applyPaint(e,t){if(!e.source)return!1;let n=t.getShapeBounds();if(!n)return!1;let i=n.right-n.left,s=n.bottom-n.top;if(i<=0||s<=0)return!1;let a=ue(e.source,t.canvasKit);if(!a)return!1;let o=Ps(a,e.source),c={u_size:[i,s],u_resolution:[i,s],u_origin:[n.left,n.top],u_aspect:i/s,u_time:t.elapsed,get u_scale(){return t.getDeviceScale()}},l=hx(o.slots,o.floats,e.uniforms,c,e.source),u=dx(e.coords,n),d;if(o.children.length>0){let h=this.bindChildren(o.children,e,t);if(!h)return!1;d=a.makeShaderWithChildren(l,h,u)}else e.textures?.length&&Zr("a shader fill supplies textures but its source declares no `uniform shader`."),d=a.makeShader(l,u);return d?(t.transientPaintObjects.push(d),t.paint.setShader(d),!0):!1}bindChildren(e,t,n){let i=[];for(let s of e){if(s.kind!=="shader")return Zr(`a shader fill declares \`uniform ${s.kind} ${s.name}\`, which it cannot bind. Only \`uniform shader\` is supported.`),null;let a=t.textures?.find(c=>c.name===s.name);if(!a)return Zr(`a shader fill declares \`uniform shader ${s.name}\` but no texture of that name was supplied.`),null;let o=n.assets.getCKImage(a.src);if(!o)return null;i.push(fx(a.src,o,n))}return i}dispose(){for(let{shader:e}of Co.values())e.delete();Co.clear()}};var Eo=new Map;function mx(r){let e=r.gap??8,t=r.strokeWidth??1,[n,i,s,a]=r.color??[0,0,0,1];return`${e}|${t}|${n},${i},${s},${a}`}function px(r,e){let t=Math.max(1,Math.round(r.gap??8)),n=r.strokeWidth??1,[i,s,a,o]=r.color??[0,0,0,1],c=e.MakeSurface(t,t);if(!c)return null;let l=new e.Paint;try{let u=c.getCanvas();u.clear(e.TRANSPARENT),l.setAntiAlias(!0),l.setStyle(e.PaintStyle.Stroke),l.setStrokeWidth(n),l.setColor(e.Color(Math.round(i*255),Math.round(s*255),Math.round(a*255),o));let d=n/2;u.drawLine(d,0,d,t,l),c.flush();let h=c.makeImageSnapshot(),f=h?.readPixels(0,0,{width:t,height:t,alphaType:e.AlphaType.Unpremul,colorType:e.ColorType.RGBA_8888,colorSpace:e.ColorSpace.SRGB});return h?.delete(),f?e.MakeImage({width:t,height:t,alphaType:e.AlphaType.Unpremul,colorType:e.ColorType.RGBA_8888,colorSpace:e.ColorSpace.SRGB},new Uint8Array(f),4*t):null}finally{l.delete(),c.delete()}}function gx(r,e,t){let n=r*Math.PI/180,i=Math.cos(n),s=Math.sin(n);return[i,-s,e-i*e+s*t,s,i,t-s*e-i*t,0,0,1]}var Io=class extends qe{applyPaint(e,t){let n=mx(e),i=Eo.get(n);if(!i){let d=px(e,t.canvasKit);if(!d)return!1;i=d,Eo.set(n,i)}let s=t.getShapeBounds(),a=s?.left??0,o=s?.top??0,c=e.angle??-45,l=gx(c,a,o),u=i.makeShaderOptions(t.canvasKit.TileMode.Repeat,t.canvasKit.TileMode.Repeat,t.canvasKit.FilterMode.Linear,t.canvasKit.MipmapMode.None,l);return t.paint.setShader(u),t.transientPaintObjects.push(u),!0}dispose(){for(let e of Eo.values())e.delete();Eo.clear()}};var yx=`
|
|
1937
1791
|
// Declared widest-first \u2014 vec4, then vec2s, then floats.
|
|
1938
1792
|
//
|
|
1939
1793
|
// Skia lays runtime-effect uniforms out with alignment, so a vec4 declared after
|
|
@@ -1965,7 +1819,7 @@ vec4 main(vec2 fragCoord) {
|
|
|
1965
1819
|
float a = u_color.a * cover;
|
|
1966
1820
|
return vec4(u_color.rgb * a, a);
|
|
1967
1821
|
}
|
|
1968
|
-
`,
|
|
1822
|
+
`,Mo=class extends qe{live=null;replaceLive(e){this.live?.delete(),this.live=e}applyPaint(e,t){let n=t.getShapeBounds();if(!n)return!1;let i=ue(yx,t.canvasKit);if(!i)return!1;let s=Math.max(.01,e.spacing),a=i.makeShader([e.color[0],e.color[1],e.color[2],e.color[3],n.left,n.top,e.offset.x,e.offset.y,s,Math.max(0,e.radius),Qa(t)]);return a?(this.replaceLive(a),t.paint.setShader(a),!0):!1}dispose(){this.replaceLive(null)}};var wx=`
|
|
1969
1823
|
// Declared widest-first, so the flat array handed to makeShader needs no padding
|
|
1970
1824
|
// \u2014 see the note on the dot-grid fill's source for what a gap here costs.
|
|
1971
1825
|
uniform vec4 u_color;
|
|
@@ -2012,9 +1866,9 @@ vec4 main(vec2 fragCoord) {
|
|
|
2012
1866
|
float a = u_color.a * cover;
|
|
2013
1867
|
return vec4(u_color.rgb * a, a);
|
|
2014
1868
|
}
|
|
2015
|
-
`,Mo=class extends qe{live=null;replaceLive(e){this.live?.delete(),this.live=e}applyPaint(e,t){let n=t.getShapeBounds();if(!n)return!1;let i=n.right-n.left,s=n.bottom-n.top;if(i<=0||s<=0)return!1;let a=ne($x,t.canvasKit);if(!a)return!1;let o=Math.max(1,Math.round(e.subdivisions)),c=a.makeShader([e.color[0],e.color[1],e.color[2],e.color[3],n.left,n.top,i,s,e.offset.x,e.offset.y,Math.max(1e-4,e.divisions),o,Math.max(0,e.strokeWidth)*.5,Math.max(0,e.subdivisionWidth)*.5,Ka(t)]);return c?(this.replaceLive(c),t.paint.setShader(c),!0):!1}dispose(){this.replaceLive(null)}};var Fo=class extends qe{applyPaint(e,t){return t.paint.setColorComponents(e.color[0],e.color[1],e.color[2],e.color[3]*(e.opacity??1)*t.worldAlpha),t.paint.setShader(null),!0}};var Rs=class{static list=[{name:"solid",renderer:new Fo},{name:"linear-gradient",renderer:new xo},{name:"radial-gradient",renderer:new So},{name:"conic-gradient",renderer:new To},{name:"image",renderer:new so},{name:"video",renderer:new ko},{name:"noise",renderer:new vo},{name:"fractalNoise",renderer:new Ao},{name:"shader",renderer:new Co},{name:"stripe",renderer:new Eo},{name:"dotGrid",renderer:new Io},{name:"grid",renderer:new Mo},{name:"canvas3D",renderer:new lo}];static get(e){return this.list.find(t=>t.name===e)?.renderer}static applyPaint(e,t){let n=this.get(e.type);return n?n.applyPaint(e,t):!1}static preflight(e,t){this.get(e.type)?.preflight?.(e,t)}static disposeRenderers(){for(let{renderer:e}of this.list)e?.dispose()}};var Ro=class{canvasKit;getPaint;getCanvas;getUnionBounds;getSpaceRect;assets;getWorldAlpha;getNodeId;getElapsed;getDeviceScale;rasterizeSurface;effectResources;getDeviceMatrix;slots=new Map;currentBounds=null;constructor(e,t,n,i,s,a,o=()=>1,c=()=>"",l=()=>0,u=()=>1,d=()=>null,h=()=>null,f=()=>null){this.canvasKit=e,this.getPaint=t,this.getCanvas=n,this.getUnionBounds=i,this.getSpaceRect=s,this.assets=a,this.getWorldAlpha=o,this.getNodeId=c,this.getElapsed=l,this.getDeviceScale=u,this.rasterizeSurface=d,this.effectResources=h,this.getDeviceMatrix=f,this.currentBounds=null}worldAlpha(){return this.getWorldAlpha()}beginFrame(){this.slots.clear(),this.preflighted.clear()}paintSlot(e){let t=this.getNodeId(),n=this.slots.get(t);n||(n=new Map,this.slots.set(t,n));let i=n.get(e);if(i!==void 0)return i;let s=n.size;return n.set(e,s),s}unionPath(e){if(e.length<2||e.some(n=>!n.ckPath))return null;let t=e[0].ckPath.copy();for(let n=1;n<e.length;n++){let i=this.canvasKit.Path.MakeFromOp(t,e[n].ckPath,this.canvasKit.PathOp.Union);if(t.delete(),!i)return null;t=i}return t}setCurrentBounds(e){this.currentBounds=e}boundsForSpace(e,t){switch(e){case"parent":case"global":return this.getSpaceRect(e)??this.getUnionBounds();default:return this.getUnionBounds()}}dispose(){}getCanvasKitBlendMode(e){return Gt(this.canvasKit,e)}buildRendererCtx(e,t=this.getWorldAlpha()){let n;return{canvasKit:this.canvasKit,paint:e,assets:this.assets,worldAlpha:t,getShapeBounds:()=>this.currentBounds,nodeId:this.getNodeId(),elapsed:this.getElapsed(),getDeviceScale:this.getDeviceScale,getDeviceMatrix:()=>n===void 0?n=this.getDeviceMatrix():n,paintSlot:i=>this.paintSlot(i),rasterizeSurface:this.rasterizeSurface,effectResources:this.effectResources,preflighted:new Map,transientImages:[],transientPaintObjects:[],clipFilterToShape:!1,drawShape:()=>{},skipDefaultDraw:!1}}preflighted=new Map;preflight(e,t){let n=this.buildRendererCtx(t);n.preflighted=this.preflighted;for(let i of e)this.preflighted.has(i)||(this.currentBounds=this.boundsForSpace(i.space??"local",null),Rs.preflight(i,n));this.currentBounds=null}openPass(e,t,n,i=this.getWorldAlpha()){this.preflight(e,t);let s=this.buildRendererCtx(t,i);return s.preflighted=this.preflighted,s.drawShape=n,s}applyFill(e,t,n,i=!0){let s=e.paint;return s.setAlphaf(n),s.setBlendMode(i&&t.blend?this.getCanvasKitBlendMode(t.blend):this.canvasKit.BlendMode.SrcOver),s.setImageFilter(null),e.skipDefaultDraw=!1,e.clipFilterToShape=!1,Rs.applyPaint(t,e)}endFill(e){let t=e.paint;t.setShader(null),t.setImageFilter(null);for(let n of e.transientImages)n.delete();e.transientImages.length=0;for(let n of e.transientPaintObjects)n.delete();e.transientPaintObjects.length=0}closePass(e){let t=e.paint;this.currentBounds=null,t.setBlendMode(this.canvasKit.BlendMode.SrcOver),t.setAlphaf(1),t.setShader(null),t.setImageFilter(null)}drawShapes(e,t,n=!1){let i=this.unionPath(t),s=()=>{if(i)this.getCanvas().drawPath(i,e);else for(let o of t)o.draw(e)},a=n?i??(t.length===1?t[0].ckPath:null):null;if(a){let o=this.getCanvas();o.save(),o.clipPath(a,this.canvasKit.ClipOp.Intersect,!0),s(),o.restore()}else s();i?.delete()}applyFills(e,t){if(e.length===0)return!1;let n=this.getPaint(),i=this.openPass(e,n,a=>this.drawShapes(a,t,i.clipFilterToShape));n.setStyle(this.canvasKit.PaintStyle.Fill);let s=this.getWorldAlpha();for(let a of e)this.currentBounds=this.boundsForSpace(a.space??"local",null),this.applyFill(i,a,(a.opacity??1)*s)&&!i.skipDefaultDraw&&this.drawShapes(n,t,i.clipFilterToShape),this.endFill(i);return this.closePass(i),!0}};var Em=r=>-(r??0);function Ti(r,e,t){let n=nS(r,e,t),{x:i,y:s,pivot:a}=rS(n,e,t);return{...iS(n),x:i,y:-s,pivot:a}}function nu(r){return Ti(r,r.width??0,r.height??0)}function iu(r){let e=Ti(r,r.width??0,r.height??0);return r.startAngle!=null&&(e.startAngle=-r.startAngle),r.sweep!=null&&(e.sweep=-r.sweep),e}function su(r){return Ti(r,r.width??0,r.height??0)}function au(r){return Ti(r,r.width??0,r.height??0)}function ou(r){let e=r.points?r.points.map(t=>({x:t.x,y:-t.y})):r.points;return{...r,y:Em(r.y),points:e}}function sS(r){return Ti(r,r.width??0,r.height??0)}function aS(r){return Ti(r,r.width??0,r.height??0)}function oS(r){switch(r.type){case"M":case"m":case"L":case"l":case"T":case"t":return{...r,y:-r.y};case"V":case"v":return{...r,y:-r.y};case"H":case"h":return r;case"C":case"c":return{...r,y1:-r.y1,y2:-r.y2,y:-r.y};case"S":case"s":return{...r,y2:-r.y2,y:-r.y};case"Q":case"q":return{...r,y1:-r.y1,y:-r.y};case"A":case"a":return{...r,y:-r.y,sweep:r.sweep===1?0:1};case"Z":case"z":return r}}function cu(r){let e={...r,y:Em(r.y)};if(Array.isArray(r.data)&&(e.data=r.data.map(oS)),r.centerBounds){let[t,n,i,s]=r.centerBounds;e.centerBounds=[t,-s,i,-n]}return e}var cS=()=>{};function lS(r,e){return e==="decal"?r.TileMode.Decal:r.TileMode.Clamp}function Cm(r,e){return e==="nearest"?r.FilterMode.Nearest:r.FilterMode.Linear}function lu(r,e){return{width:r,height:e,centerX:0,centerY:0,scale:1,time:0,velocity:Im,angularVelocity:0}}var Im={x:0,y:0},Pm=4,uS=4;function Mm(r,e){return e>=1?r:r.map(t=>({...t,opacity:(t.opacity??1)*e}))}function dS(r,e){return e>=1?r:r.map(t=>({...t,fill:Mm(t.fill,e)}))}var Bo=class extends Qx{currentCanvas;canvasKit;surface;activeSurface;rasterDepth=0;paint;layerPaint;mounted=!1;isRendering=!1;effectLayerStack=[];worldAlpha=1;worldAlphaStack=[];clipRestoreStack=[];clipShapeStack=[];fillHandler;strokeHandler;shapeHandler;deferredPaintsStack=[];storageAdapter;constructor(e,t){super(),this.canvasKit=e,this.storageAdapter=t,this._makePaints(),this.buildHandlers()}measureText(e,t,n,i=400,s=0,a="normal"){return fo(this.canvasKit,this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),this.storageAdapter.getFontEpoch(),e,t,n,i,s,a)}layoutTextBlock(e){return mo(this.canvasKit,this.storageAdapter.getFontMgr(),e)}buildHandlers(){let e=()=>this.currentCanvas,t=()=>this.paint;this.shapeHandler=new bo(this.canvasKit,e,t,this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),()=>this.storageAdapter.getFontEpoch());let n=()=>this.worldAlpha;this.fillHandler=new Ro(this.canvasKit,t,e,()=>this.shapeHandler.getShapeBounds(),i=>this.spaceRect(i),this.storageAdapter,n,()=>this.currentNodeStack.length>0?this.currentNodeId():"",()=>this.currentRenderState()?.elapsed??0,()=>{let i=this.currentCanvas.getTotalMatrix();return Math.max(Math.hypot(i[0],i[3]),Math.hypot(i[1],i[4]),1)},(i,s,a,o)=>this.rasterizeSurfaceSource(i,s,a,o),()=>this.effectResources(),()=>this.currentCanvas?.getTotalMatrix()??null),this.strokeHandler=new po(this.canvasKit,e,t,this.fillHandler)}pixelRatio=1;view={zoom:1,x:0,y:0};frame=null;clipToFrame=!0;frameBackground="black";executePass(e){if(!this.mounted||!this.surface)return;let t=this.surface.getCanvas();this.currentCanvas=t,this.activeSurface=this.surface,this.currentCanvas.clear(this.frame?this.canvasKit.TRANSPARENT:this.canvasKit.BLACK);let n=t.getSaveCount();this.currentCanvas.save();let i=this.surface.width()/this.pixelRatio,s=this.surface.height()/this.pixelRatio;if(this.currentCanvas.scale(this.pixelRatio,this.pixelRatio),this.currentCanvas.translate(i/2+this.view.x,s/2+this.view.y),this.view.zoom!==1&&this.currentCanvas.scale(this.view.zoom,this.view.zoom),this.frame){let c=this.canvasKit,l=this.frame.width/2,u=this.frame.height/2,d=c.LTRBRect(-l,-u,l,u),h=this.frameBackground==="black";this.clipToFrame?(this.currentCanvas.clipRect(d,c.ClipOp.Intersect,!0),h&&this.currentCanvas.drawColor(c.BLACK,c.BlendMode.Src)):h&&(this.currentCanvas.save(),this.currentCanvas.clipRect(d,c.ClipOp.Intersect,!0),this.currentCanvas.drawColor(c.BLACK,c.BlendMode.Src),this.currentCanvas.restore())}let a=ai(this.storageAdapter);a?.beginFrame(),this.fillHandler.beginFrame(),this.storageAdapter.beginRenderPass(),this.isRendering=!0;let o=!0;try{e(),o=!1}finally{this.isRendering=!1,this._resetPass(t,n,o),a?.sweep(),this.surface.flush(),this.storageAdapter.endRenderPass()}}begin(e){if(!this.currentCanvas)throw new Error("begin() must be called within the draw() method.");super.begin(e),this.shapeHandler.beginNode(e.id),this.shapeHandler.reset(),this.effectLayerStack.push(0),this.worldAlphaStack.push(this.worldAlpha),this.currentCanvas.save()}end(){if(!this.currentCanvas)throw new Error("end() must be called within the draw() method.");let e=this.effectLayerStack.pop()??0;for(let t=0;t<e;t++)this.currentCanvas.restore();this.worldAlpha=this.worldAlphaStack.pop()??1,this.currentCanvas.restore(),super.end()}currentWorldAlpha(){return this.worldAlpha}_resetPass(e,t,n){for(let i of this.effectScopeStack)for(let s of i.captures)s.offscreen.delete();this.effectScopeStack.length=0,this.currentCanvas=e,this.activeSurface=this.surface,e.restoreToCount(t),this.effectLayerStack.length=0,this.worldAlphaStack.length=0,this.worldAlpha=1,this.clipRestoreStack.length=0,this.clipShapeStack.length=0,this.cameraRestoreStack.length=0,this.deferredPaintsStack.length=0,this.rasterDepth=0,this.shapeHandler.resetPass(),this._resetScopes(),n&&(this.paint.delete(),this.layerPaint.delete(),this._makePaints())}_makePaints(){this.paint=new this.canvasKit.Paint,this.paint.setAntiAlias(!0),this.layerPaint=new this.canvasKit.Paint}dispose(){this.fillHandler?.dispose(),this.shapeHandler?.dispose(),this.storageAdapter.dispose(),this.surface&&this.surface.dispose(),this.mounted=!1,this.canvasKit=void 0,this.paint?.delete(),this.paint=void 0,this.layerPaint?.delete(),this.layerPaint=void 0,this.currentCanvas=void 0,this.effectLayerStack.length=0,this.clipRestoreStack.length=0,this.clipShapeStack.length=0,this.deferredPaintsStack.length=0,this.effectScopeStack.length=0,Ga(),Nh(),sm(),vs()?.dispose(),ye.disposeAll(),Qh(),super.dispose()}execute(e){this.executePass(e)}attach(e){this.mounted&&this.detach(),this.surface=e,this.mounted=!0,this.storageAdapter.setSurface(e)}detach(){this.mounted&&(this.storageAdapter.setSurface(null),this.surface.dispose(),this.mounted=!1)}snapshotPixels(){if(!this.mounted){console.warn("snapshotPixels() must be called after attach().");return}this.surface.flush();let e=this.surface.makeImageSnapshot();if(!e)return;let t=this.canvasKit,n=this.frameDeviceRect(),i=n?Math.max(0,Math.round(n.left)):0,s=n?Math.max(0,Math.round(n.top)):0,a=n?Math.max(1,Math.min(e.width()-i,Math.round(n.right-n.left))):e.width(),o=n?Math.max(1,Math.min(e.height()-s,Math.round(n.bottom-n.top))):e.height(),c=e.readPixels(i,s,{width:a,height:o,colorType:t.ColorType.RGBA_8888,alphaType:t.AlphaType.Unpremul,colorSpace:t.ColorSpace.SRGB});if(e.delete(),!!c)return{pixels:new Uint8Array(c),width:a,height:o}}drawGraphics(e){if(!this.isRendering){console.warn("draw() must be called within the draw() method.");return}let t=e.needsGroupLayer(),n=this.worldAlpha,i=this.currentCanvas,s=i.getSaveCount(),a=null,o=null;try{if(t){let d=e.groupOpacity();d<1&&(this.worldAlpha*=d)}let c=e.groupTransform();if(c){let d=this.resolveGroupCenter(e,c.center),h=d.x,f=d.y;i.save(),i.translate(h,f),i.rotate(c.rotation,0,0),i.scale(c.scale,c.scale),i.translate(-h,-f)}let l=e.ops();o=this.buildEffectSegments(e);let u=!1;for(let d=0;d<l.length;d++){let h=o.get(d);h&&(o.delete(d),a=h.filter,this.layerPaint.setAlphaf(1),this.layerPaint.setImageFilter(a),i.saveLayer(this.layerPaint),this.layerPaint.setImageFilter(null),u=!0);let f=l[d];if(f.kind==="effects"){u&&(i.restore(),a?.delete?.(),a=null,u=!1),this.shapeHandler.reset();continue}this.applyOp(f)}}finally{if(i.restoreToCount(s),a?.delete?.(),o)for(let c of o.values())c.filter.delete?.();this.worldAlpha=n}}buildEffectSegments(e){let t=e.ops(),n=new Map,i=0,s=!1,a=o=>o==="rect"||o==="ellipse"||o==="path"||o==="line"||o==="polygon"||o==="polygram"||o==="text"||o==="richText";for(let o=0;o<t.length;o++){let c=t[o];if(a(c.kind)){s&&(i=o,s=!1);continue}if(c.kind==="fill"||c.kind==="stroke"||c.kind==="shadow"){s=!0;continue}if(c.kind==="effects"){let l=this.resolveMotionBlurEffects(c.effects.filter(d=>d.mode!=="backdrop")),u=l.length>0?ye.compose(l,this.canvasKit,lu(this.activeSurface.width(),this.activeSurface.height())):null;u!=null&&n.set(i,{filter:u}),i=o+1,s=!1;continue}}return n}resolveGroupCenter(e,t){if(t!==void 0&&typeof t!="string")return{x:t.x,y:t.y};this.shapeHandler.beginMeasure();for(let l of e.ops())switch(l.kind){case"rect":this.shapeHandler.rect(nu(l.state));break;case"ellipse":this.shapeHandler.ellipse(iu(l.state));break;case"path":this.shapeHandler.path(cu(l.state));break;case"line":this.shapeHandler.line(ou(l.state));break;case"polygon":this.shapeHandler.polygon(su(l.state));break;case"polygram":this.shapeHandler.polygram(au(l.state));break}let n=this.shapeHandler.measureUnionBounds();if(this.shapeHandler.endMeasure(),!n)return{x:0,y:0};let i=(n.left+n.right)/2,s=(n.top+n.bottom)/2;if(t===void 0)return{x:i,y:s};let a=tS.resolve(t),o=(n.right-n.left)/2,c=(n.bottom-n.top)/2;return{x:i+a.x*o,y:s-a.y*c}}applyOp(e){switch(e.kind){case"rect":this._rect(nu(e.state));break;case"ellipse":this._ellipse(iu(e.state));break;case"path":this._path(cu(e.state));break;case"line":this._line(ou(e.state));break;case"polygon":this._polygon(su(e.state));break;case"polygram":this._polygram(au(e.state));break;case"text":this._text(sS(e.state));break;case"richText":this._richText(aS(e.state));break;case"fill":this._fill(e.fills);break;case"stroke":this._stroke(e.strokes);break;case"shadow":this._shadow(e.shadows);break;case"cut":this._cut();break;case"mask":this._maskOp(e.options);break;case"applyMask":this._applyMask();break;case"endMask":this._endMaskOp();break;case"effects":break}}transform(e){if(!this.isRendering)return console.warn("transform() must be called within the draw() method."),this;let t=e.x??0,n=e.y??0,i=e.width??0,s=e.height??0,a=e.opacity??1,o=e.blend??"pass-through",c=e.rotation??0,l=e.scale??1,u=e.effects??[],d=e.pivot??{x:0,y:0},h=e.matrix;if(h)this.currentCanvas.concat([h.a,h.c,h.e,h.b,h.d,h.f,h.g??0,h.h??0,h.i??1]);else{let g=d.x*(i/2),y=-d.y*(s/2);this.currentCanvas.translate(t+g,n+y),this.currentCanvas.rotate(c,0,0),this.currentCanvas.scale(l,l),this.currentCanvas.translate(-g,-y)}let f=u.filter(g=>g.mode!=="backdrop"),p=null;if(f.length>0){let g=this.resolveMotionBlurEffects(f);p=ye.compose(g,this.canvasKit,lu(i,s))}if(o!=="pass-through")this.layerPaint.setAlphaf(this.worldAlpha*(a<1?a:1)),this.layerPaint.setBlendMode(Gt(this.canvasKit,o)),this.layerPaint.setImageFilter(p??null),this.currentCanvas.saveLayer(this.layerPaint),this.layerPaint.setAlphaf(1),this.layerPaint.setBlendMode(this.canvasKit.BlendMode.SrcOver),this.layerPaint.setImageFilter(null),this.effectLayerStack[this.effectLayerStack.length-1]++,this.worldAlpha=1;else{if(p!=null){this.layerPaint.setAlphaf(1),this.layerPaint.setImageFilter(p);let g=this.canvasKit.LTRBRect(-i/2,-s/2,i/2,s/2);this.currentCanvas.saveLayer(this.layerPaint,g),this.layerPaint.setImageFilter(null),this.effectLayerStack[this.effectLayerStack.length-1]++}a<1&&(this.worldAlpha*=a)}return this}resolveMotionBlurEffects(e){let t=!1;for(let s of e)if(s.type==="motionBlur"){t=!0;break}if(!t)return e;let n=this.currentRenderState(),i=[];for(let s of e){if(s.type!=="motionBlur"){i.push(s);continue}let a=n?Zh(s,n.velocity,n.dt):null;a&&i.push(a)}return i}frameDeviceRect(){if(!this.frame||!this.surface)return null;let e=this.pixelRatio,t=this.surface.width()/e/2+this.view.x,n=this.surface.height()/e/2+this.view.y,i=this.frame.width/2*this.view.zoom,s=this.frame.height/2*this.view.zoom;return{left:(t-i)*e,top:(n-s)*e,right:(t+i)*e,bottom:(n+s)*e}}spaceRect(e){if(e==="parent")return this.currentSpaceRects().parent??null;if(e==="global"){let t=this.currentCanvas?.getTotalMatrix();if(!t)return null;let n=this.canvasKit.Matrix.invert(t);if(!n)return null;let i=this.frame&&this.activeSurface===this.surface?this.frameDeviceRect():null;if(i){let l=this.canvasKit.Matrix.mapPoints(n,[i.left,i.top]),u=this.canvasKit.Matrix.mapPoints(n,[i.right,i.bottom]);return{left:Math.min(l[0],u[0]),top:Math.min(l[1],u[1]),right:Math.max(l[0],u[0]),bottom:Math.max(l[1],u[1])}}let s=this.activeSurface.width(),a=this.activeSurface.height(),o=this.canvasKit.Matrix.mapPoints(n,[0,0]),c=this.canvasKit.Matrix.mapPoints(n,[s,a]);return{left:Math.min(o[0],c[0]),top:Math.min(o[1],c[1]),right:Math.max(o[0],c[0]),bottom:Math.max(o[1],c[1])}}return null}_rect(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.rect(e),this.shapeHandler.paintApplied&&this.shapeHandler.reset()}_ellipse(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.ellipse(e)}_path(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.path(e)}_line(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.line(e)}_polygon(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.polygon(e)}_polygram(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.polygram(e)}_text(e){if(this.shapeHandler.paintApplied&&this.shapeHandler.reset(),e.segments&&e.segments.length>0){this._segmentedText(e);return}this.shapeHandler.text(e)}_segmentedText(e){let t=um(this.canvasKit,this.storageAdapter.getFontMgr(),e);this.shapeHandler.pushBounds(t.bounds);try{for(let n of t.runs){if(n.glyphs.length===0||!n.segment)continue;let i=n.segment,s=i.x!==0||i.y!==0||i.scale!==1||i.rotation!==0;if(s){let l=dm(n);this.currentCanvas.save(),this.currentCanvas.translate(i.x,i.y),i.rotation!==0&&this.currentCanvas.rotate(i.rotation,l.x,l.y),i.scale!==1&&(this.currentCanvas.translate(l.x,l.y),this.currentCanvas.scale(i.scale,i.scale),this.currentCanvas.translate(-l.x,-l.y))}let a={isText:!0,draw:l=>Ql(this.currentCanvas,n,l)},o=i.fill?Mm(i.fill,i.opacity):[];o.length>0&&this.fillHandler.applyFills(o,[a]);let c=i.stroke?dS(i.stroke,i.opacity):[];c.length>0&&this.strokeHandler.applyStrokes(c,[a]),s&&this.currentCanvas.restore()}}finally{this.shapeHandler.popBounds();for(let n of t.fonts)n.delete()}}_richText(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset();let t=Yx(e),n=lm(this.canvasKit,this.storageAdapter.getFontMgr(),t);this.shapeHandler.pushBounds(n.bounds);try{for(let i of n.runs){if(i.glyphs.length===0)continue;let s={isText:!0,draw:a=>{Ql(this.currentCanvas,i,a)}};i.span.fill.length>0&&this.fillHandler.applyFills(i.span.fill,[s]),i.span.stroke.length>0&&this.strokeHandler.applyStrokes(i.span.stroke,[s])}}finally{this.shapeHandler.popBounds();for(let i of n.fonts)i.delete()}}_fill(e){let t=Zx.resolve(e);if(t.length===0){this.shapeHandler.paintApplied=!0;return}if(this.shapeHandler.isCollectingPaths()){this.shapeHandler.paintApplied=!0;return}let n=this.shapeHandler.getMaskApply();if(n!==null&&!n.has("fill")){let s=this.deferredPaintsStack[this.deferredPaintsStack.length-1];if(s){s.push({kind:"fill",shapes:[...this.shapeHandler.shapes],fills:t,shadows:this.shapeHandler.takePendingShadows()}),this.shapeHandler.paintApplied=!0;return}}let i=this.shapeHandler.takePendingShadows();if(i){let s=i[0].fill[0]?.space??"local",{shapes:a,dispose:o}=this.strokeShapesForSpace(s);this.strokeHandler.applyShadows(i,a,t,[],this.applyFillSpaceBounds),this.fillHandler.applyFills(t,this.shapeHandler.shapes),this.strokeHandler.applyInnerShadows(i,a,t,this.applyFillSpaceBounds),o()}else this.fillHandler.applyFills(t,this.shapeHandler.shapes);this.shapeHandler.paintApplied=!0}applyFillSpaceBounds=(e,t)=>{this.fillHandler.setCurrentBounds(this.fillHandler.boundsForSpace(e.space??"local",t))};strokeShapesForSpace(e){let t=this.shapeHandler.unionStrokeShape();return t?{shapes:[t],dispose:()=>{t.ckPath?.delete(),t.strokePath&&t.strokePath!==t.ckPath&&t.strokePath.delete()}}:{shapes:this.shapeHandler.shapes,dispose:()=>{}}}_stroke(e){let t=Jx.resolve(e);if(t.length===0)return;if(this.shapeHandler.isCollectingPaths()){this.shapeHandler.paintApplied=!0;return}let n=this.shapeHandler.getMaskApply();if(n!==null&&!n.has("stroke")){let c=this.deferredPaintsStack[this.deferredPaintsStack.length-1];if(c){c.push({kind:"stroke",shapes:[...this.shapeHandler.shapes],strokes:t,shadows:this.shapeHandler.takePendingShadows()}),this.shapeHandler.paintApplied=!0;return}}let i=this.shapeHandler.takePendingShadows();if(i){let c=i[0].fill[0]?.space??"local",{shapes:l,dispose:u}=this.strokeShapesForSpace(c);this.strokeHandler.applyShadows(i,l,[],t,this.applyFillSpaceBounds),u()}let s=t[0].fill[0]?.space??"local",{shapes:a,dispose:o}=this.strokeShapesForSpace(s);this.strokeHandler.applyStrokes(t,a,this.applyFillSpaceBounds),o(),this.shapeHandler.paintApplied=!0}_shadow(e){let t=eS.resolve(e);t.length!==0&&(this.shapeHandler.isCollectingPaths()||this.shapeHandler.storePendingShadows(t))}_cut(){this.shapeHandler.cut()}cameraRestoreStack=[];beginCamera(e,t,n,i){if(!this.isRendering){console.warn("beginCamera() must be called within the draw() method.");return}let s=this.currentCanvas,a=this.canvasKit;if(s.save(),this.clipsCameraViewport(e)){let o=e.x-e.width/2,c=e.y-e.height/2,l=e.x+e.width/2,u=e.y+e.height/2;s.clipRect(a.LTRBRect(o,c,l,u),a.ClipOp.Intersect,!0)}s.save(),s.translate(e.x,e.y),s.rotate(-i,0,0),s.scale(n,n),s.translate(-t.x,t.y),this.cameraRestoreStack.push(2)}clipsCameraViewport(e){let t=this.frame;return this.clipToFrame||!t?!0:!(e.x===0&&e.y===0&&e.width===t.width&&e.height===t.height)}endCamera(){if(!this.isRendering){console.warn("endCamera() must be called within the draw() method.");return}let e=this.cameraRestoreStack.pop()??0;for(let t=0;t<e;t++)this.currentCanvas.restore()}beginClip(e){if(!this.isRendering){console.warn("beginClip() must be called within the draw() method.");return}let t=this.currentCanvas;t.save(),this.clipRestoreStack.push(1),this.clipShapeStack.push(e);let n=e.ops();if(n.length===1&&n[0].kind!=="cut"){let s=this.buildClipShapeOp(n[0]);s&&(s.clip(!0),s.deletePaths());return}let i=this.combineClipPath(e);i&&(t.clipPath(i,this.canvasKit.ClipOp.Intersect,!0),i.delete())}endClip(){if(!this.isRendering){console.warn("endClip() must be called within the draw() method.");return}let e=this.clipRestoreStack.pop()??0;this.clipShapeStack.pop();for(let t=0;t<e;t++)this.currentCanvas.restore()}buildClipShapeOp(e){let t=this.canvasKit,n=()=>this.currentCanvas;switch(e.kind){case"rect":return new pi(t,n,nu(e.state));case"ellipse":return new gi(t,n,iu(e.state));case"polygon":return new yi(t,n,su(e.state));case"polygram":return new wi(t,n,au(e.state));case"path":return new bi(t,n,cu(e.state));case"line":return new ki(t,n,ou(e.state));case"cut":return null}}combineClipPath(e){let t=this.canvasKit,n=[];for(let i of e.ops()){if(i.kind==="cut"){let a=n.pop();if(!a)continue;let o=this.unionPaths(n.splice(0,n.length));if(!o){a.delete();continue}let c=t.Path.MakeFromOp(o,a,t.PathOp.Difference);o.delete(),a.delete(),c&&n.push(c);continue}let s=this.buildClipShapeOp(i);s&&(s.ensurePath(),s.ckPath&&n.push(s.ckPath.copy()),s.deletePaths())}return this.unionPaths(n)}unionPaths(e){let t=this.canvasKit;if(e.length===0)return null;let n=e[0];for(let i=1;i<e.length;i++){let s=t.Path.MakeFromOp(n,e[i],t.PathOp.Union);if(n.delete(),e[i].delete(),!s){for(let a=i+1;a<e.length;a++)e[a].delete();return null}n=s}return n}effectScopeStack=[];beginEffects(e,t,n,i){if(!this.isRendering){console.warn("beginEffects() must be called within the draw() method.");return}let s={canvasRestores:0,captures:[]},a=[],o=[];for(let c of e){let l=ye.resolveShader(c,t);l?o.push({handler:l,effect:c}):a.push(c)}if(t==="backdrop"&&a.length>0&&this.openBackdropFilterLayer(a,n,i)&&s.canvasRestores++,t==="backdrop")for(let{handler:c,effect:l}of o)this.paintBackdropShaderEffect(c,l,n,i);else for(let c=o.length-1;c>=0;c--){let{handler:l,effect:u}=o[c],d=this.openForegroundCapture(l,u,n,i);d&&s.captures.push(d)}this.effectScopeStack.push(s)}endEffects(){if(!this.isRendering){console.warn("endEffects() must be called within the draw() method.");return}let e=this.effectScopeStack.pop();if(e){for(let t=e.captures.length-1;t>=0;t--)this.resolveForegroundCapture(e.captures[t]);for(let t=0;t<e.canvasRestores;t++)this.currentCanvas.restore()}}openBackdropFilterLayer(e,t,n){let i=this.canvasKit,s=ye.compose(e,i,lu(t,n));if(s==null)return!1;let a=this.pixelRatio,o={filter:i.FilterMode.Linear,mipmap:i.MipmapMode.None},c=i.ImageFilter.MakeMatrixTransform(i.Matrix.scaled(1/a,1/a),o,null),l=i.ImageFilter.MakeCompose(s,c),u=i.ImageFilter.MakeMatrixTransform(i.Matrix.scaled(a,a),o,l);return this.currentCanvas.saveLayer(void 0,null,u,void 0,i.TileMode.Clamp),u.delete(),l.delete(),c.delete(),s.delete(),!0}paintBackdropShaderEffect(e,t,n,i){let s=this.canvasKit;if(n<=0||i<=0)return;let a=this.currentCanvas.getTotalMatrix(),o=this.activeSurface.makeImageSnapshot(),c=o.makeShaderOptions(s.TileMode.Clamp,s.TileMode.Clamp,Cm(s,e.sampling.filterMode),s.MipmapMode.None),l=this.shaderGeometry(a,n,i),u=e.resources?.(t,s,this.effectResources(),l)??[],d=this.buildRenderInputs(e,t,l,o,a),h=e.makeShader(t,s,c,l,u,d.shaders);h!=null&&(this.paintShaderInDeviceSpace(h,a),h.delete()),d.dispose(),c.delete(),o.delete()}buildRenderInputs(e,t,n,i,s){let a=e.renderInputs?.(t,this.canvasKit,n);if(!a)return{shaders:{},dispose:cS};let o={},c=[];if(a.silhouette!==void 0){let l=this.silhouetteMask(a.silhouette,s);l&&(o.silhouette=l.shader,c.push(l.dispose))}if(a.blurredSource!==void 0){let l=this.blurredCopy(i,a.blurredSource);typeof a.blurredSource!="number"&&a.blurredSource.prefilter?.delete(),l&&(o.blurredSource=l.shader,c.push(l.dispose))}return{shaders:o,dispose:()=>{for(let l of c)l()}}}silhouetteMask(e,t){let n=this.clipShapeStack[this.clipShapeStack.length-1];if(!n||n.isEmpty())return null;let i=this.canvasKit,s=this.combineClipPath(n);if(!s)return null;let a=this.activeSurface.makeSurface(this.activeSurface.imageInfo());if(!a)return s.delete(),null;let o=a.getCanvas();o.clear(i.TRANSPARENT),o.save(),o.concat(t);let c=new i.Paint;c.setAntiAlias(!0),c.setColor(i.WHITE);let l=e>0?i.MaskFilter.MakeBlur(i.BlurStyle.Normal,e,!1):null;return l&&c.setMaskFilter(l),o.drawPath(s,c),o.restore(),l?.delete(),c.delete(),s.delete(),this.wrapOffscreen(a,i.TileMode.Decal)}blurredCopy(e,t){let n=this.canvasKit,i=this.activeSurface.makeSurface(this.activeSurface.imageInfo());if(!i)return null;let s=typeof t=="number"?t:t.sigmaX,a=typeof t=="number"?t:t.sigmaY,o=typeof t=="number"?void 0:t.prefilter,c=i.getCanvas();c.clear(n.TRANSPARENT);let l=new n.Paint,u=s>0||a>0?n.ImageFilter.MakeBlur(s,a,n.TileMode.Clamp,null):null,d=u&&o?n.ImageFilter.MakeCompose(u,o):null,h=d??u??o??null;return h&&l.setImageFilter(h),c.drawImage(e,0,0,l),d?.delete(),u?.delete(),l.delete(),this.wrapOffscreen(i,n.TileMode.Clamp)}wrapOffscreen(e,t){let n=this.canvasKit,i=e.makeImageSnapshot(),s=i.makeShaderOptions(t,t,n.FilterMode.Linear,n.MipmapMode.None);return{shader:s,dispose:()=>{s.delete(),i.delete(),e.delete()}}}openForegroundCapture(e,t,n,i){let s=this.canvasKit;if(n<=0||i<=0)return null;let a=this.activeSurface.makeSurface(this.activeSurface.imageInfo());if(!a)return null;let o=this.currentCanvas.getTotalMatrix(),c=a.getCanvas();c.save(),c.clear(s.TRANSPARENT),c.concat(o);let l=this.currentCanvas;return this.currentCanvas=c,{handler:e,effect:t,width:n,height:i,savedCanvas:l,offscreen:a,matrix:o}}resolveForegroundCapture(e){let t=this.canvasKit,{handler:n,effect:i,width:s,height:a,savedCanvas:o,offscreen:c,matrix:l}=e;this.currentCanvas.restore(),this.currentCanvas=o;let u=c.makeImageSnapshot(),d=lS(t,n.sampling.tileMode),h=u.makeShaderOptions(d,d,Cm(t,n.sampling.filterMode),t.MipmapMode.None),f=this.shaderGeometry(l,s,a),p=n.resources?.(i,t,this.effectResources(),f)??[],m=this.buildRenderInputs(n,i,f,u,l),g=n.makeShader(i,t,h,f,p,m.shaders),y=g!=null&&i.clip===!0?t.Shader.MakeBlend(t.BlendMode.SrcIn,h,g):null;this.paintShaderInDeviceSpace(y??g??h,l),y?.delete(),g?.delete(),m.dispose(),h.delete(),u.delete(),c.delete()}effectResources(){return{fontMgr:this.storageAdapter.getFontMgr(),fontEpoch:this.storageAdapter.getFontEpoch(),makeSurface:(e,t)=>!(e>0)||!(t>0)?null:this.activeSurface.makeSurface({...this.activeSurface.imageInfo(),width:Math.ceil(e),height:Math.ceil(t)}),getImage:(e,t)=>this.storageAdapter.getCKImage(e,t),getImageSize:e=>this.storageAdapter.getImageSize(e)}}shaderGeometry(e,t,n){let i=Math.hypot(e[0],e[3]),s=Math.hypot(e[1],e[4]),a=this.currentRenderState();return{centerX:e[2],centerY:e[5],width:t*i,height:n*s,scale:i,time:a?.elapsed??0,velocity:a?.velocity??Im,angularVelocity:a?.angularVelocity??0}}paintShaderInDeviceSpace(e,t){let n=this.canvasKit;this.currentCanvas.save();let i=n.Matrix.invert(t);i&&this.currentCanvas.concat(i);let s=new n.Paint;s.setShader(e),s.setAntiAlias(!0),this.currentCanvas.drawRect(n.LTRBRect(0,0,this.activeSurface.width(),this.activeSurface.height()),s),s.delete(),this.currentCanvas.restore()}rasterizeSurfaceSource(e,t,n,i){let s=Xx(e);if(s.kind==="graphics")return this.rasterize(t,n,()=>this.draw(s.graphics),i);let a=s.node;return this.rasterize(t,n,()=>{a.layout({x:0,y:0,width:t,height:n},this),a.render(this)},i)}rasterize(e,t,n,i=1){if(!this.isRendering||!this.surface||!(e>0)||!(t>0))return null;if(this.rasterDepth>=Pm)return console.warn(`rasterize() nested more than ${Pm} deep \u2014 skipping. A Surface2D is most likely nested inside itself via a Canvas3D.`),null;let s=this.canvasKit,a=Math.max(1,Math.min(i,uS)),o=Math.max(1,Math.ceil(e*a)),c=Math.max(1,Math.ceil(t*a)),l=this.activeSurface.makeSurface({...this.activeSurface.imageInfo(),width:o,height:c});if(!l)return null;let u=this.currentCanvas,d=this.activeSurface,h=this.worldAlpha,f=this.shapeHandler.beginNested(),p=l.getCanvas();p.save(),p.clear(s.TRANSPARENT),p.scale(a,a),p.translate(e/2,t/2),this.currentCanvas=p,this.activeSurface=l,this.worldAlpha=1,this.rasterDepth++;try{n()}finally{p.restore(),this.rasterDepth--,this.currentCanvas=u,this.activeSurface=d,this.worldAlpha=h,this.shapeHandler.endNested(f)}l.flush();let m=l.makeImageSnapshot(),g=m?.readPixels(0,0,{width:o,height:c,colorType:s.ColorType.RGBA_8888,alphaType:s.AlphaType.Unpremul,colorSpace:s.ColorSpace.SRGB});return m?.delete(),l.delete(),g?{pixels:new Uint8Array(g),width:o,height:c}:null}beginBoolean(e){if(!this.isRendering){console.warn("beginBoolean() must be called within the draw() method.");return}this.shapeHandler.beginBoolean(e)}endBoolean(){if(!this.isRendering){console.warn("endBoolean() must be called within the draw() method.");return}this.shapeHandler.endBoolean()}beginMask(e){if(!this.isRendering){console.warn("beginMask() must be called within the draw() method.");return}this.shapeHandler.beginMask(e),this.deferredPaintsStack.push([])}applyMask(){if(!this.isRendering){console.warn("applyMask() must be called within the draw() method.");return}this.shapeHandler.applyMask()}endMask(){if(!this.isRendering){console.warn("endMask() must be called within the draw() method.");return}this.shapeHandler.endMask();let e=this.deferredPaintsStack.pop()??[];this.flushDeferredPaints(e)}_maskOp(e){this.beginMask(e)}_applyMask(){this.applyMask()}_endMaskOp(){this.endMask()}flushDeferredPaints(e){for(let t of e)t.kind==="stroke"?(t.shadows&&this.strokeHandler.applyShadows(t.shadows,t.shapes,[],t.strokes,this.applyFillSpaceBounds),this.strokeHandler.applyStrokes(t.strokes,t.shapes,this.applyFillSpaceBounds)):(t.shadows&&this.strokeHandler.applyShadows(t.shadows,t.shapes,t.fills,[],this.applyFillSpaceBounds),this.fillHandler.applyFills(t.fills,t.shapes),t.shadows&&this.strokeHandler.applyInnerShadows(t.shadows,t.shapes,t.fills,this.applyFillSpaceBounds))}};import{AssetManager as Fm,AudioSink as hS,ClipStore as fS,AssetTimeline as mS,renderSettled as pS,SETTLE_PASSES as gS,setTheme as yS,spansCovering as Rm,StateEvaluator as wS,yieldToScheduler as bS}from"@motionscript/core";var Bs=class extends hS{get schedulesAudio(){return!1}has(e){return!0}async append(e,t){}retain(e){}schedule(e){}syncTo(e){}play(e,t,n){}stop(){}};async function Bm({renderContext:r,storageAdapter:e},t,n){await pS(()=>r.execute(t),e,()=>!0)==="exhausted"&&console.warn(`[export] frame ${n} still had pending decodes after ${gS} renders; it may not be exact.`)}function Dm(r){let e=r.getDecodePolicy();return r.setDecodePolicy("exact"),()=>r.setDecodePolicy(e)}function kS(r){let{fps:e,viewport:t}=r;if(e===void 0||t===void 0)throw new Error("Rendering takes a project whose fps and viewport are resolved \u2014 see Session.");return{fps:e,viewport:t}}function Om(r){let{project:e,registry:t,assetCatalog:n,renderContext:i}=r,{fps:s,viewport:a}=kS(e),o=()=>yS(e.theme??r.theme);o();let c=i,l={registry:t,viewport:a,fps:s,assets:n,measurer:c},u={},d=new fS(e,l,{isReady:p=>u.manager?.isReady(p)??!1}),h=new mS(e,l,{store:d}),f=new wS(e,l,d);return{store:d,precomper:h,stateEvaluator:f,measurer:c,fps:s,viewport:a,loads:u,applyTheme:o}}async function Lm(r,e,t){let n=t.flatMap(i=>r.layoutGates(i).filter(s=>!e.isReady(s.src)));n.length>0&&await e.loadRecords(n),r.settleGates(t)}function uu(r){let e=[];for(let t of r.tracks){let n=t.startFrame/r.fps;for(let i of t.audioRequests)e.push({request:i,globalOffset:n})}return e}async function du(r){let{scale:e=1,sink:t,mixer:n,onProgress:i,signal:s,includeAudio:a=!0}=r,o=r,{renderContext:c,storageAdapter:l}=o;if(r.project.tracks.length===0)return;s?.throwIfAborted(),c.pixelRatio=e;let{store:u,precomper:d,stateEvaluator:h,measurer:f,fps:p,viewport:m,loads:g,applyTheme:y}=Om(r),b=Dm(l);try{let k=d.run(),{totalFrames:T,totalDuration:S}=k;Um(u,k,0,T-1);let _=g.manager=new Fm(k,l,new Bs);await Lm(u,_,r.project.tracks.map(O=>O.id));let M=uu(k),P=a&&M.length>0&&n!==void 0;await t.start({width:m.width*e,height:m.height*e,fps:p,totalFrames:T,hasAudio:P});let A=1/p,F=0;l.setPlaying(!0);try{for(let O=0;O<T;O++)s?.throwIfAborted(),await _.loadAt(O),y(),h.stateAt(O),h.layout(f),await Bm(o,()=>h.render(c),O),await t.addFrame(F,A),F+=A,i?.((O+1)/T*(P?.85:1)),(O+1)%4===0&&await bS()}finally{l.setPlaying(!1)}if(P){let O=await n.mix(M,S);O!==null&&t.addAudio&&await t.addAudio(O),i?.(.97)}let I=await t.finalize();return i?.(1),I}finally{b(),h.dispose(),u.dispose()}}var Ds=class extends Error{frame;failures;name="NothingToDrawError";constructor(e,t){let n=t.map(i=>` ${i.trackId}: ${i.message}`).join(`
|
|
1869
|
+
`,Fo=class extends qe{live=null;replaceLive(e){this.live?.delete(),this.live=e}applyPaint(e,t){let n=t.getShapeBounds();if(!n)return!1;let i=n.right-n.left,s=n.bottom-n.top;if(i<=0||s<=0)return!1;let a=ue(wx,t.canvasKit);if(!a)return!1;let o=Math.max(1,Math.round(e.subdivisions)),c=a.makeShader([e.color[0],e.color[1],e.color[2],e.color[3],n.left,n.top,i,s,e.offset.x,e.offset.y,Math.max(1e-4,e.divisions),o,Math.max(0,e.strokeWidth)*.5,Math.max(0,e.subdivisionWidth)*.5,Qa(t)]);return c?(this.replaceLive(c),t.paint.setShader(c),!0):!1}dispose(){this.replaceLive(null)}};var Ro=class extends qe{applyPaint(e,t){return t.paint.setColorComponents(e.color[0],e.color[1],e.color[2],e.color[3]*Ya(e,t)*t.worldAlpha),t.paint.setShader(null),!0}};var Os=class{static list=[{name:"solid",renderer:new Ro},{name:"linear-gradient",renderer:new xo},{name:"radial-gradient",renderer:new To},{name:"conic-gradient",renderer:new Ao},{name:"image",renderer:new ao},{name:"video",renderer:new So},{name:"noise",renderer:new vo},{name:"fractalNoise",renderer:new _o},{name:"shader",renderer:new Po},{name:"stripe",renderer:new Io},{name:"dotGrid",renderer:new Mo},{name:"grid",renderer:new Fo},{name:"canvas3D",renderer:new uo}];static get(e){return this.list.find(t=>t.name===e)?.renderer}static applyPaint(e,t){let n=this.get(e.type);return n?n.applyPaint(e,t):!1}static preflight(e,t){this.get(e.type)?.preflight?.(e,t)}static disposeRenderers(){for(let{renderer:e}of this.list)e?.dispose()}};var Bo=class{canvasKit;getPaint;getCanvas;getUnionBounds;getSpaceRect;assets;getWorldAlpha;getNodeId;getElapsed;getDeviceScale;rasterizeSurface;effectResources;getDeviceMatrix;slots=new Map;currentBounds=null;constructor(e,t,n,i,s,a,o=()=>1,c=()=>"",l=()=>0,u=()=>1,d=()=>null,h=()=>null,f=()=>null){this.canvasKit=e,this.getPaint=t,this.getCanvas=n,this.getUnionBounds=i,this.getSpaceRect=s,this.assets=a,this.getWorldAlpha=o,this.getNodeId=c,this.getElapsed=l,this.getDeviceScale=u,this.rasterizeSurface=d,this.effectResources=h,this.getDeviceMatrix=f,this.currentBounds=null}worldAlpha(){return this.getWorldAlpha()}beginFrame(){this.slots.clear(),this.preflighted.clear()}paintSlot(e){let t=this.getNodeId(),n=this.slots.get(t);n||(n=new Map,this.slots.set(t,n));let i=n.get(e);if(i!==void 0)return i;let s=n.size;return n.set(e,s),s}unionPath(e){if(e.length<2||e.some(n=>!n.ckPath))return null;let t=e[0].ckPath.copy();for(let n=1;n<e.length;n++){let i=this.canvasKit.Path.MakeFromOp(t,e[n].ckPath,this.canvasKit.PathOp.Union);if(t.delete(),!i)return null;t=i}return t}setCurrentBounds(e){this.currentBounds=e}boundsForSpace(e,t){switch(e){case"parent":case"global":return this.getSpaceRect(e)??this.getUnionBounds();default:return this.getUnionBounds()}}dispose(){}getCanvasKitBlendMode(e){return Kt(this.canvasKit,e)}buildRendererCtx(e,t=this.getWorldAlpha()){let n;return{canvasKit:this.canvasKit,paint:e,assets:this.assets,worldAlpha:t,opacityRealised:!1,getShapeBounds:()=>this.currentBounds,nodeId:this.getNodeId(),elapsed:this.getElapsed(),getDeviceScale:this.getDeviceScale,getDeviceMatrix:()=>n===void 0?n=this.getDeviceMatrix():n,paintSlot:i=>this.paintSlot(i),rasterizeSurface:this.rasterizeSurface,effectResources:this.effectResources,preflighted:new Map,transientImages:[],transientPaintObjects:[],clipFilterToShape:!1,drawShape:()=>{},skipDefaultDraw:!1}}preflighted=new Map;preflight(e,t){let n=this.buildRendererCtx(t);n.preflighted=this.preflighted;for(let i of e)this.preflighted.has(i)||(this.currentBounds=this.boundsForSpace(i.space??"local",null),Os.preflight(i,n));this.currentBounds=null}openPass(e,t,n,i=this.getWorldAlpha()){this.preflight(e,t);let s=this.buildRendererCtx(t,i);return s.preflighted=this.preflighted,s.drawShape=n,s}openShadowPass(e,t){let n=this.openPass(e,t,()=>{},1);return n.opacityRealised=!0,n}applyFill(e,t,n,i=!0){let s=e.paint;return s.setAlphaf(n),s.setBlendMode(i&&t.blend?this.getCanvasKitBlendMode(t.blend):this.canvasKit.BlendMode.SrcOver),s.setImageFilter(null),e.skipDefaultDraw=!1,e.clipFilterToShape=!1,Os.applyPaint(t,e)}endFill(e){let t=e.paint;t.setShader(null),t.setImageFilter(null);for(let n of e.transientImages)n.delete();e.transientImages.length=0;for(let n of e.transientPaintObjects)n.delete();e.transientPaintObjects.length=0}closePass(e){let t=e.paint;this.currentBounds=null,t.setBlendMode(this.canvasKit.BlendMode.SrcOver),t.setAlphaf(1),t.setShader(null),t.setImageFilter(null)}drawShapes(e,t,n=!1){let i=this.unionPath(t),s=()=>{if(i)this.getCanvas().drawPath(i,e);else for(let o of t)o.draw(e)},a=n?i??(t.length===1?t[0].ckPath:null):null;if(a){let o=this.getCanvas();o.save(),o.clipPath(a,this.canvasKit.ClipOp.Intersect,!0),s(),o.restore()}else s();i?.delete()}applyFills(e,t){if(e.length===0)return!1;let n=this.getPaint(),i=this.openPass(e,n,a=>this.drawShapes(a,t,i.clipFilterToShape));n.setStyle(this.canvasKit.PaintStyle.Fill);let s=this.getWorldAlpha();for(let a of e)this.currentBounds=this.boundsForSpace(a.space??"local",null),this.applyFill(i,a,(a.opacity??1)*s)&&!i.skipDefaultDraw&&this.drawShapes(n,t,i.clipFilterToShape),this.endFill(i);return this.closePass(i),!0}};var Gm=r=>-(r??0);function Ai(r,e,t){let n=Cx(r,e,t),{x:i,y:s,pivot:a}=_x(n,e,t);return{...Px(n),x:i,y:-s,pivot:a}}function au(r){return Ai(r,r.width??0,r.height??0)}function ou(r){let e=Ai(r,r.width??0,r.height??0);return r.startAngle!=null&&(e.startAngle=-r.startAngle),r.sweep!=null&&(e.sweep=-r.sweep),e}function cu(r){return Ai(r,r.width??0,r.height??0)}function lu(r){return Ai(r,r.width??0,r.height??0)}function uu(r){let e=r.points?r.points.map(t=>({x:t.x,y:-t.y})):r.points;return{...r,y:Gm(r.y),points:e}}function Ex(r){return Ai(r,r.width??0,r.height??0)}function Ix(r){return Ai(r,r.width??0,r.height??0)}function Mx(r){switch(r.type){case"M":case"m":case"L":case"l":case"T":case"t":return{...r,y:-r.y};case"V":case"v":return{...r,y:-r.y};case"H":case"h":return r;case"C":case"c":return{...r,y1:-r.y1,y2:-r.y2,y:-r.y};case"S":case"s":return{...r,y2:-r.y2,y:-r.y};case"Q":case"q":return{...r,y1:-r.y1,y:-r.y};case"A":case"a":return{...r,y:-r.y,sweep:r.sweep===1?0:1};case"Z":case"z":return r}}function du(r){let e={...r,y:Gm(r.y)};if(Array.isArray(r.data)&&(e.data=r.data.map(Mx),r.centerBounds)){let[t,n,i,s]=r.centerBounds;e.centerBounds=[t,-s,i,-n]}return e}var Fx=()=>{};function Rx(r,e){return e==="decal"?r.TileMode.Decal:r.TileMode.Clamp}function Wm(r,e){return e==="nearest"?r.FilterMode.Nearest:r.FilterMode.Linear}function hu(r,e){return{width:r,height:e,centerX:0,centerY:0,scale:1,time:0,velocity:jm,angularVelocity:0}}var jm={x:0,y:0},qm=4,Bx=4;function Km(r,e){return e>=1?r:r.map(t=>({...t,opacity:(t.opacity??1)*e}))}function Dx(r,e){return e>=1?r:r.map(t=>({...t,fill:Km(t.fill,e)}))}var Do=class extends kx{currentCanvas;canvasKit;surface;activeSurface;rasterDepth=0;warnedInertShapeProps=new Set;paint;layerPaint;mounted=!1;isRendering=!1;effectLayerStack=[];worldAlpha=1;worldAlphaStack=[];clipRestoreStack=[];clipShapeStack=[];fillHandler;strokeHandler;shapeHandler;deferredPaintsStack=[];storageAdapter;constructor(e,t){super(),this.canvasKit=e,this.storageAdapter=t,this._makePaints(),this.buildHandlers()}measureText(e,t,n,i=400,s=0,a="normal"){return mo(this.canvasKit,this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),this.storageAdapter.getFontEpoch(),e,t,n,i,s,a)}layoutTextBlock(e){return po(this.canvasKit,this.storageAdapter.getFontMgr(),e)}buildHandlers(){let e=()=>this.currentCanvas,t=()=>this.paint;this.shapeHandler=new ko(this.canvasKit,e,t,this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),()=>this.storageAdapter.getFontEpoch());let n=()=>this.worldAlpha;this.fillHandler=new Bo(this.canvasKit,t,e,()=>this.shapeHandler.getShapeBounds(),i=>this.spaceRect(i),this.storageAdapter,n,()=>this.currentNodeStack.length>0?this.currentNodeId():"",()=>this.currentRenderState()?.elapsed??0,()=>{let i=this.currentCanvas.getTotalMatrix();return Math.max(Math.hypot(i[0],i[3]),Math.hypot(i[1],i[4]),1)},(i,s,a,o)=>this.rasterizeSurfaceSource(i,s,a,o),()=>this.effectResources(),()=>this.currentCanvas?.getTotalMatrix()??null),this.strokeHandler=new go(this.canvasKit,e,t,this.fillHandler)}pixelRatio=1;view={zoom:1,x:0,y:0};frame=null;clipToFrame=!0;frameBackground="black";executePass(e){if(!this.mounted||!this.surface)return;let t=this.surface.getCanvas();this.currentCanvas=t,this.activeSurface=this.surface,this.currentCanvas.clear(this.frame?this.canvasKit.TRANSPARENT:this.canvasKit.BLACK);let n=t.getSaveCount();this.currentCanvas.save();let i=this.surface.width()/this.pixelRatio,s=this.surface.height()/this.pixelRatio;if(this.currentCanvas.scale(this.pixelRatio,this.pixelRatio),this.currentCanvas.translate(i/2+this.view.x,s/2+this.view.y),this.view.zoom!==1&&this.currentCanvas.scale(this.view.zoom,this.view.zoom),this.frame){let c=this.canvasKit,l=this.frame.width/2,u=this.frame.height/2,d=c.LTRBRect(-l,-u,l,u),h=this.frameBackground==="black";this.clipToFrame?(this.currentCanvas.clipRect(d,c.ClipOp.Intersect,!0),h&&this.currentCanvas.drawColor(c.BLACK,c.BlendMode.Src)):h&&(this.currentCanvas.save(),this.currentCanvas.clipRect(d,c.ClipOp.Intersect,!0),this.currentCanvas.drawColor(c.BLACK,c.BlendMode.Src),this.currentCanvas.restore())}let a=ci(this.storageAdapter);a?.beginFrame(),this.fillHandler.beginFrame(),this.storageAdapter.beginRenderPass(),this.isRendering=!0;let o=!0;try{e(),o=!1}finally{this.isRendering=!1,this._resetPass(t,n,o),a?.sweep(),this.surface.flush(),this.storageAdapter.endRenderPass(),this.storageAdapter.getParagraphCache().endPass()}}begin(e){if(!this.currentCanvas)throw new Error("begin() must be called within the draw() method.");super.begin(e),this.shapeHandler.beginNode(e.id),this.shapeHandler.reset(),this.effectLayerStack.push(0),this.worldAlphaStack.push(this.worldAlpha),this.currentCanvas.save()}end(){if(!this.currentCanvas)throw new Error("end() must be called within the draw() method.");let e=this.effectLayerStack.pop()??0;for(let t=0;t<e;t++)this.currentCanvas.restore();this.worldAlpha=this.worldAlphaStack.pop()??1,this.currentCanvas.restore(),super.end()}currentWorldAlpha(){return this.worldAlpha}_resetPass(e,t,n){for(let i of this.effectScopeStack)for(let s of i.captures)s.offscreen.delete();this.effectScopeStack.length=0,this.currentCanvas=e,this.activeSurface=this.surface,e.restoreToCount(t),this.effectLayerStack.length=0,this.worldAlphaStack.length=0,this.worldAlpha=1,this.clipRestoreStack.length=0,this.clipShapeStack.length=0,this.cameraRestoreStack.length=0,this.deferredPaintsStack.length=0,this.rasterDepth=0,this.shapeHandler.resetPass(),this._resetScopes(),n&&(this.paint.delete(),this.layerPaint.delete(),this._makePaints())}_makePaints(){this.paint=new this.canvasKit.Paint,this.paint.setAntiAlias(!0),this.layerPaint=new this.canvasKit.Paint}dispose(){this.fillHandler?.dispose(),this.shapeHandler?.dispose(),this.storageAdapter.dispose(),this.surface&&this.surface.dispose(),this.mounted=!1,this.canvasKit=void 0,this.paint?.delete(),this.paint=void 0,this.layerPaint?.delete(),this.layerPaint=void 0,this.currentCanvas=void 0,this.effectLayerStack.length=0,this.clipRestoreStack.length=0,this.clipShapeStack.length=0,this.deferredPaintsStack.length=0,this.effectScopeStack.length=0,Xa(),Qh(),um(),vs()?.dispose(),Se.disposeAll(),of(),Rm(),super.dispose()}execute(e){this.executePass(e)}attach(e){this.mounted&&this.detach(),this.surface=e,this.mounted=!0,this.storageAdapter.setSurface(e)}detach(){this.mounted&&(this.storageAdapter.setSurface(null),this.surface.dispose(),this.mounted=!1)}snapshotPixels(){if(!this.mounted){console.warn("snapshotPixels() must be called after attach().");return}this.surface.flush();let e=this.surface.makeImageSnapshot();if(!e)return;let t=this.canvasKit,n=this.frameDeviceRect(),i=n?Math.max(0,Math.round(n.left)):0,s=n?Math.max(0,Math.round(n.top)):0,a=n?Math.max(1,Math.min(e.width()-i,Math.round(n.right-n.left))):e.width(),o=n?Math.max(1,Math.min(e.height()-s,Math.round(n.bottom-n.top))):e.height(),c=e.readPixels(i,s,{width:a,height:o,colorType:t.ColorType.RGBA_8888,alphaType:t.AlphaType.Unpremul,colorSpace:t.ColorSpace.SRGB});if(e.delete(),!!c)return{pixels:new Uint8Array(c),width:a,height:o}}drawGraphics(e){if(!this.isRendering){console.warn("draw() must be called within the draw() method.");return}let t=e.needsGroupLayer(),n=this.worldAlpha,i=this.currentCanvas,s=i.getSaveCount(),a=null,o=null;try{if(t){let d=e.groupOpacity();d<1&&(this.worldAlpha*=d)}let c=e.groupTransform();if(c){let d=this.resolveGroupCenter(e,c.center),h=d.x,f=d.y;i.save(),i.translate(h,f),i.rotate(c.rotation,0,0),i.scale(c.scale,c.scale),i.translate(-h,-f)}let l=e.ops();o=this.buildEffectSegments(e);let u=!1;for(let d=0;d<l.length;d++){let h=o.get(d);h&&(o.delete(d),a=h.filter,this.layerPaint.setAlphaf(1),this.layerPaint.setImageFilter(a),i.saveLayer(this.layerPaint),this.layerPaint.setImageFilter(null),u=!0);let f=l[d];if(f.kind==="effects"){u&&(i.restore(),a?.delete?.(),a=null,u=!1),this.shapeHandler.reset();continue}this.applyOp(f)}}finally{if(i.restoreToCount(s),a?.delete?.(),o)for(let c of o.values())c.filter.delete?.();this.worldAlpha=n}}buildEffectSegments(e){let t=e.ops(),n=new Map,i=0,s=!1,a=o=>o==="rect"||o==="ellipse"||o==="path"||o==="line"||o==="polygon"||o==="polygram"||o==="text"||o==="richText";for(let o=0;o<t.length;o++){let c=t[o];if(a(c.kind)){s&&(i=o,s=!1);continue}if(c.kind==="fill"||c.kind==="stroke"||c.kind==="shadow"){s=!0;continue}if(c.kind==="effects"){let l=this.resolveMotionBlurEffects(c.effects.filter(d=>d.mode!=="backdrop")),u=l.length>0?Se.compose(l,this.canvasKit,hu(this.activeSurface.width(),this.activeSurface.height())):null;u!=null&&n.set(i,{filter:u}),i=o+1,s=!1;continue}}return n}resolveGroupCenter(e,t){if(t!==void 0&&typeof t!="string")return{x:t.x,y:t.y};this.shapeHandler.beginMeasure();for(let l of e.ops())switch(l.kind){case"rect":this.shapeHandler.rect(au(l.state));break;case"ellipse":this.shapeHandler.ellipse(ou(l.state));break;case"path":this.shapeHandler.path(du(l.state));break;case"line":this.shapeHandler.line(uu(l.state));break;case"polygon":this.shapeHandler.polygon(cu(l.state));break;case"polygram":this.shapeHandler.polygram(lu(l.state));break}let n=this.shapeHandler.measureUnionBounds();if(this.shapeHandler.endMeasure(),!n)return{x:0,y:0};let i=(n.left+n.right)/2,s=(n.top+n.bottom)/2;if(t===void 0)return{x:i,y:s};let a=vx.resolve(t),o=(n.right-n.left)/2,c=(n.bottom-n.top)/2;return{x:i+a.x*o,y:s-a.y*c}}warnInertShapeProps(e,t){let n={opacity:t.opacity!==void 0&&t.opacity!==1,blend:t.blend!==void 0&&t.blend!=="pass-through"};for(let i of["opacity","blend"])!n[i]||this.warnedInertShapeProps.has(i)||(this.warnedInertShapeProps.add(i),console.warn(`Graphics2D .${e}() was given \`${i}\`, which a shape does not draw. Use Graphics2D.opacity() for the whole group, or the node's own opacity and blend.`))}applyOp(e){switch(e.kind){case"rect":case"ellipse":case"path":case"line":case"polygon":case"polygram":case"text":case"richText":this.warnInertShapeProps(e.kind,e.state)}switch(e.kind){case"rect":this._rect(au(e.state));break;case"ellipse":this._ellipse(ou(e.state));break;case"path":this._path(du(e.state));break;case"line":this._line(uu(e.state));break;case"polygon":this._polygon(cu(e.state));break;case"polygram":this._polygram(lu(e.state));break;case"text":this._text(Ex(e.state));break;case"richText":this._richText(Ix(e.state));break;case"fill":this._fill(e.fills);break;case"stroke":this._stroke(e.strokes);break;case"shadow":this._shadow(e.shadows);break;case"cut":this._cut();break;case"mask":this._maskOp(e.options);break;case"applyMask":this._applyMask();break;case"endMask":this._endMaskOp();break;case"effects":break}}transform(e){if(!this.isRendering)return console.warn("transform() must be called within the draw() method."),this;let t=e.x??0,n=e.y??0,i=e.width??0,s=e.height??0,a=e.opacity??1,o=e.blend??"pass-through",c=e.rotation??0,l=e.scale??1,u=e.effects??[],d=e.pivot??{x:0,y:0},h=e.matrix;if(h)this.currentCanvas.concat([h.a,h.c,h.e,h.b,h.d,h.f,h.g??0,h.h??0,h.i??1]);else{let g=d.x*(i/2),y=-d.y*(s/2);this.currentCanvas.translate(t+g,n+y),this.currentCanvas.rotate(c,0,0),this.currentCanvas.scale(l,l),this.currentCanvas.translate(-g,-y)}let f=u.filter(g=>g.mode!=="backdrop"),p=null;if(f.length>0){let g=this.resolveMotionBlurEffects(f);p=Se.compose(g,this.canvasKit,hu(i,s))}if(o!=="pass-through")this.layerPaint.setAlphaf(this.worldAlpha*(a<1?a:1)),this.layerPaint.setBlendMode(Kt(this.canvasKit,o)),this.layerPaint.setImageFilter(p??null),this.currentCanvas.saveLayer(this.layerPaint),this.layerPaint.setAlphaf(1),this.layerPaint.setBlendMode(this.canvasKit.BlendMode.SrcOver),this.layerPaint.setImageFilter(null),this.effectLayerStack[this.effectLayerStack.length-1]++,this.worldAlpha=1;else{if(p!=null){this.layerPaint.setAlphaf(1),this.layerPaint.setImageFilter(p);let g=this.canvasKit.LTRBRect(-i/2,-s/2,i/2,s/2);this.currentCanvas.saveLayer(this.layerPaint,g),this.layerPaint.setImageFilter(null),this.effectLayerStack[this.effectLayerStack.length-1]++}a<1&&(this.worldAlpha*=a)}return this}resolveMotionBlurEffects(e){let t=!1;for(let s of e)if(s.type==="motionBlur"){t=!0;break}if(!t)return e;let n=this.currentRenderState(),i=[];for(let s of e){if(s.type!=="motionBlur"){i.push(s);continue}let a=n?lf(s,n.velocity,n.dt):null;a&&i.push(a)}return i}frameDeviceRect(){if(!this.frame||!this.surface)return null;let e=this.pixelRatio,t=this.surface.width()/e/2+this.view.x,n=this.surface.height()/e/2+this.view.y,i=this.frame.width/2*this.view.zoom,s=this.frame.height/2*this.view.zoom;return{left:(t-i)*e,top:(n-s)*e,right:(t+i)*e,bottom:(n+s)*e}}spaceRect(e){if(e==="parent")return this.currentSpaceRects().parent??null;if(e==="global"){let t=this.currentCanvas?.getTotalMatrix();if(!t)return null;let n=this.canvasKit.Matrix.invert(t);if(!n)return null;let i=this.frame&&this.activeSurface===this.surface?this.frameDeviceRect():null;if(i){let l=this.canvasKit.Matrix.mapPoints(n,[i.left,i.top]),u=this.canvasKit.Matrix.mapPoints(n,[i.right,i.bottom]);return{left:Math.min(l[0],u[0]),top:Math.min(l[1],u[1]),right:Math.max(l[0],u[0]),bottom:Math.max(l[1],u[1])}}let s=this.activeSurface.width(),a=this.activeSurface.height(),o=this.canvasKit.Matrix.mapPoints(n,[0,0]),c=this.canvasKit.Matrix.mapPoints(n,[s,a]);return{left:Math.min(o[0],c[0]),top:Math.min(o[1],c[1]),right:Math.max(o[0],c[0]),bottom:Math.max(o[1],c[1])}}return null}_rect(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.rect(e),this.shapeHandler.paintApplied&&this.shapeHandler.reset()}_ellipse(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.ellipse(e)}_path(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.path(e)}_line(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.line(e)}_polygon(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.polygon(e)}_polygram(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.polygram(e)}_text(e){if(this.shapeHandler.paintApplied&&this.shapeHandler.reset(),e.segments&&e.segments.length>0){this._segmentedText(e);return}this.shapeHandler.text(e)}_segmentedText(e){let t=pm(this.canvasKit,this.storageAdapter.getFontMgr(),e);this.shapeHandler.pushBounds(t.bounds);try{for(let n of t.runs){if(n.glyphs.length===0||!n.segment)continue;let i=n.segment,s=i.x!==0||i.y!==0||i.scale!==1||i.rotation!==0;if(s){let l=gm(n);this.currentCanvas.save(),this.currentCanvas.translate(i.x,i.y),i.rotation!==0&&this.currentCanvas.rotate(i.rotation,l.x,l.y),i.scale!==1&&(this.currentCanvas.translate(l.x,l.y),this.currentCanvas.scale(i.scale,i.scale),this.currentCanvas.translate(-l.x,-l.y))}let a={isText:!0,draw:l=>Ql(this.currentCanvas,n,l)},o=i.fill?Km(i.fill,i.opacity):[];o.length>0&&this.fillHandler.applyFills(o,[a]);let c=i.stroke?Dx(i.stroke,i.opacity):[];c.length>0&&this.strokeHandler.applyStrokes(c,[a]),s&&this.currentCanvas.restore()}}finally{this.shapeHandler.popBounds();for(let n of t.fonts)n.delete()}}_richText(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset();let t=Sx(e),n=mm(this.canvasKit,this.storageAdapter.getFontMgr(),t);this.shapeHandler.pushBounds(n.bounds);try{for(let i of n.runs){if(i.glyphs.length===0)continue;let s={isText:!0,draw:a=>{Ql(this.currentCanvas,i,a)}};i.span.fill.length>0&&this.fillHandler.applyFills(i.span.fill,[s]),i.span.stroke.length>0&&this.strokeHandler.applyStrokes(i.span.stroke,[s])}}finally{this.shapeHandler.popBounds();for(let i of n.fonts)i.delete()}}_fill(e){let t=xx.resolve(e);if(t.length===0){this.shapeHandler.paintApplied=!0;return}if(this.shapeHandler.isCollectingPaths()){this.shapeHandler.paintApplied=!0;return}let n=this.shapeHandler.getMaskApply();if(n!==null&&!n.has("fill")){let s=this.deferredPaintsStack[this.deferredPaintsStack.length-1];if(s){s.push({kind:"fill",shapes:[...this.shapeHandler.shapes],fills:t,shadows:this.shapeHandler.takePendingShadows()}),this.shapeHandler.paintApplied=!0;return}}let i=this.shapeHandler.takePendingShadows();if(i){let s=i[0].fill[0]?.space??"local",{shapes:a,dispose:o}=this.strokeShapesForSpace(s);this.strokeHandler.applyShadows(i,a,t,[],this.applyFillSpaceBounds),this.fillHandler.applyFills(t,this.shapeHandler.shapes),this.strokeHandler.applyInnerShadows(i,a,t,this.applyFillSpaceBounds),o()}else this.fillHandler.applyFills(t,this.shapeHandler.shapes);this.shapeHandler.paintApplied=!0}applyFillSpaceBounds=(e,t)=>{this.fillHandler.setCurrentBounds(this.fillHandler.boundsForSpace(e.space??"local",t))};strokeShapesForSpace(e){let t=this.shapeHandler.unionStrokeShape();return t?{shapes:[t],dispose:()=>{t.ckPath?.delete(),t.strokePath&&t.strokePath!==t.ckPath&&t.strokePath.delete()}}:{shapes:this.shapeHandler.shapes,dispose:()=>{}}}_stroke(e){let t=Tx.resolve(e);if(t.length===0)return;if(this.shapeHandler.isCollectingPaths()){this.shapeHandler.paintApplied=!0;return}let n=this.shapeHandler.getMaskApply();if(n!==null&&!n.has("stroke")){let c=this.deferredPaintsStack[this.deferredPaintsStack.length-1];if(c){c.push({kind:"stroke",shapes:[...this.shapeHandler.shapes],strokes:t,shadows:this.shapeHandler.takePendingShadows()}),this.shapeHandler.paintApplied=!0;return}}let i=this.shapeHandler.takePendingShadows();if(i){let c=i[0].fill[0]?.space??"local",{shapes:l,dispose:u}=this.strokeShapesForSpace(c);this.strokeHandler.applyShadows(i,l,[],t,this.applyFillSpaceBounds),u()}let s=t[0].fill[0]?.space??"local",{shapes:a,dispose:o}=this.strokeShapesForSpace(s);this.strokeHandler.applyStrokes(t,a,this.applyFillSpaceBounds),o(),this.shapeHandler.paintApplied=!0}_shadow(e){let t=Ax.resolve(e);t.length!==0&&(this.shapeHandler.isCollectingPaths()||this.shapeHandler.storePendingShadows(t))}_cut(){this.shapeHandler.cut()}cameraRestoreStack=[];beginCamera(e,t,n,i){if(!this.isRendering){console.warn("beginCamera() must be called within the draw() method.");return}let s=this.currentCanvas,a=this.canvasKit;if(s.save(),this.clipsCameraViewport(e)){let o=e.x-e.width/2,c=e.y-e.height/2,l=e.x+e.width/2,u=e.y+e.height/2;s.clipRect(a.LTRBRect(o,c,l,u),a.ClipOp.Intersect,!0)}s.save(),s.translate(e.x,e.y),s.rotate(-i,0,0),s.scale(n,n),s.translate(-t.x,t.y),this.cameraRestoreStack.push(2)}clipsCameraViewport(e){let t=this.frame;return this.clipToFrame||!t?!0:!(e.x===0&&e.y===0&&e.width===t.width&&e.height===t.height)}endCamera(){if(!this.isRendering){console.warn("endCamera() must be called within the draw() method.");return}let e=this.cameraRestoreStack.pop()??0;for(let t=0;t<e;t++)this.currentCanvas.restore()}beginClip(e){if(!this.isRendering){console.warn("beginClip() must be called within the draw() method.");return}let t=this.currentCanvas;t.save(),this.clipRestoreStack.push(1),this.clipShapeStack.push(e);let n=e.ops();if(n.length===1&&n[0].kind!=="cut"){let s=this.buildClipShapeOp(n[0]);s&&(s.clip(!0),s.deletePaths());return}let i=this.combineClipPath(e);i&&(t.clipPath(i,this.canvasKit.ClipOp.Intersect,!0),i.delete())}endClip(){if(!this.isRendering){console.warn("endClip() must be called within the draw() method.");return}let e=this.clipRestoreStack.pop()??0;this.clipShapeStack.pop();for(let t=0;t<e;t++)this.currentCanvas.restore()}buildClipShapeOp(e){let t=this.canvasKit,n=()=>this.currentCanvas;switch(e.kind){case"rect":return new pi(t,n,au(e.state));case"ellipse":return new gi(t,n,ou(e.state));case"polygon":return new yi(t,n,cu(e.state));case"polygram":return new wi(t,n,lu(e.state));case"path":return new bi(t,n,du(e.state));case"line":return new ki(t,n,uu(e.state));case"cut":return null}}combineClipPath(e){let t=this.canvasKit,n=[];for(let i of e.ops()){if(i.kind==="cut"){let a=n.pop();if(!a)continue;let o=this.unionPaths(n.splice(0,n.length));if(!o){a.delete();continue}let c=t.Path.MakeFromOp(o,a,t.PathOp.Difference);o.delete(),a.delete(),c&&n.push(c);continue}let s=this.buildClipShapeOp(i);s&&(s.ensurePath(),s.ckPath&&n.push(s.ckPath.copy()),s.deletePaths())}return this.unionPaths(n)}unionPaths(e){let t=this.canvasKit;if(e.length===0)return null;let n=e[0];for(let i=1;i<e.length;i++){let s=t.Path.MakeFromOp(n,e[i],t.PathOp.Union);if(n.delete(),e[i].delete(),!s){for(let a=i+1;a<e.length;a++)e[a].delete();return null}n=s}return n}effectScopeStack=[];beginEffects(e,t,n,i){if(!this.isRendering){console.warn("beginEffects() must be called within the draw() method.");return}let s={canvasRestores:0,captures:[]},a=[],o=[];for(let c of e){let l=Se.resolveShader(c,t);l?o.push({handler:l,effect:c}):a.push(c)}if(t==="backdrop"&&a.length>0&&this.openBackdropFilterLayer(a,n,i)&&s.canvasRestores++,t==="backdrop")for(let{handler:c,effect:l}of o)this.paintBackdropShaderEffect(c,l,n,i);else for(let c=o.length-1;c>=0;c--){let{handler:l,effect:u}=o[c],d=this.openForegroundCapture(l,u,n,i);d&&s.captures.push(d)}this.effectScopeStack.push(s)}endEffects(){if(!this.isRendering){console.warn("endEffects() must be called within the draw() method.");return}let e=this.effectScopeStack.pop();if(e){for(let t=e.captures.length-1;t>=0;t--)this.resolveForegroundCapture(e.captures[t]);for(let t=0;t<e.canvasRestores;t++)this.currentCanvas.restore()}}openBackdropFilterLayer(e,t,n){let i=this.canvasKit,s=Se.compose(e,i,hu(t,n));if(s==null)return!1;let a=this.pixelRatio,o={filter:i.FilterMode.Linear,mipmap:i.MipmapMode.None},c=i.ImageFilter.MakeMatrixTransform(i.Matrix.scaled(1/a,1/a),o,null),l=i.ImageFilter.MakeCompose(s,c),u=i.ImageFilter.MakeMatrixTransform(i.Matrix.scaled(a,a),o,l);return this.currentCanvas.saveLayer(void 0,null,u,void 0,i.TileMode.Clamp),u.delete(),l.delete(),c.delete(),s.delete(),!0}paintBackdropShaderEffect(e,t,n,i){let s=this.canvasKit;if(n<=0||i<=0)return;let a=this.currentCanvas.getTotalMatrix(),o=this.activeSurface.makeImageSnapshot(),c=o.makeShaderOptions(s.TileMode.Clamp,s.TileMode.Clamp,Wm(s,e.sampling.filterMode),s.MipmapMode.None),l=this.shaderGeometry(a,n,i),u=e.resources?.(t,s,this.effectResources(),l)??[],d=this.buildRenderInputs(e,t,l,o,a),h=e.makeShader(t,s,c,l,u,d.shaders);h!=null&&(this.paintShaderInDeviceSpace(h,a),h.delete()),d.dispose(),c.delete(),o.delete()}buildRenderInputs(e,t,n,i,s){let a=e.renderInputs?.(t,this.canvasKit,n);if(!a)return{shaders:{},dispose:Fx};let o={},c=[];if(a.distanceField){let l=this.outlineDistanceField(s);l&&(o.distanceField={shader:l.shader,maxDistance:l.maxDistance},c.push(l.dispose))}if(a.blurredSource!==void 0){let l=this.blurredCopy(i,a.blurredSource);typeof a.blurredSource!="number"&&a.blurredSource.prefilter?.delete(),l&&(o.blurredSource=l.shader,c.push(l.dispose))}return{shaders:o,dispose:()=>{for(let l of c)l()}}}outlineDistanceField(e){let t=this.clipShapeStack[this.clipShapeStack.length-1];if(!t||t.isEmpty())return null;let n=this.canvasKit,i=this.combineClipPath(t);if(!i)return null;let s=Fm(n,i,e);if(i.delete(),!s)return null;let a=n.Matrix.multiply(n.Matrix.translated(e[2]+s.originX,e[5]+s.originY),n.Matrix.scaled(s.texel,s.texel)),o=s.image.makeShaderOptions(n.TileMode.Decal,n.TileMode.Decal,n.FilterMode.Linear,n.MipmapMode.None,a);return{shader:o,maxDistance:s.maxDistance,dispose:()=>o.delete()}}blurredCopy(e,t){let n=this.canvasKit,i=this.activeSurface.makeSurface(this.activeSurface.imageInfo());if(!i)return null;let s=typeof t=="number"?t:t.sigmaX,a=typeof t=="number"?t:t.sigmaY,o=typeof t=="number"?void 0:t.prefilter,c=i.getCanvas();c.clear(n.TRANSPARENT);let l=new n.Paint,u=s>0||a>0?n.ImageFilter.MakeBlur(s,a,n.TileMode.Clamp,null):null,d=u&&o?n.ImageFilter.MakeCompose(u,o):null,h=d??u??o??null;return h&&l.setImageFilter(h),c.drawImage(e,0,0,l),d?.delete(),u?.delete(),l.delete(),this.wrapOffscreen(i,n.TileMode.Clamp)}wrapOffscreen(e,t){let n=this.canvasKit,i=e.makeImageSnapshot(),s=i.makeShaderOptions(t,t,n.FilterMode.Linear,n.MipmapMode.None);return{shader:s,dispose:()=>{s.delete(),i.delete(),e.delete()}}}openForegroundCapture(e,t,n,i){let s=this.canvasKit;if(n<=0||i<=0)return null;let a=this.activeSurface.makeSurface(this.activeSurface.imageInfo());if(!a)return null;let o=this.currentCanvas.getTotalMatrix(),c=a.getCanvas();c.save(),c.clear(s.TRANSPARENT),c.concat(o);let l=this.currentCanvas;return this.currentCanvas=c,{handler:e,effect:t,width:n,height:i,savedCanvas:l,offscreen:a,matrix:o}}resolveForegroundCapture(e){let t=this.canvasKit,{handler:n,effect:i,width:s,height:a,savedCanvas:o,offscreen:c,matrix:l}=e;this.currentCanvas.restore(),this.currentCanvas=o;let u=c.makeImageSnapshot(),d=Rx(t,n.sampling.tileMode),h=u.makeShaderOptions(d,d,Wm(t,n.sampling.filterMode),t.MipmapMode.None),f=this.shaderGeometry(l,s,a),p=n.resources?.(i,t,this.effectResources(),f)??[],m=this.buildRenderInputs(n,i,f,u,l),g=n.makeShader(i,t,h,f,p,m.shaders),y=g!=null&&i.clip===!0?t.Shader.MakeBlend(t.BlendMode.SrcIn,h,g):null;this.paintShaderInDeviceSpace(y??g??h,l),y?.delete(),g?.delete(),m.dispose(),h.delete(),u.delete(),c.delete()}effectResources(){return{fontMgr:this.storageAdapter.getFontMgr(),fontEpoch:this.storageAdapter.getFontEpoch(),makeSurface:(e,t)=>!(e>0)||!(t>0)?null:this.activeSurface.makeSurface({...this.activeSurface.imageInfo(),width:Math.ceil(e),height:Math.ceil(t)}),getImage:(e,t)=>this.storageAdapter.getCKImage(e,t),getImageSize:e=>this.storageAdapter.getImageSize(e)}}shaderGeometry(e,t,n){let i=Math.hypot(e[0],e[3]),s=Math.hypot(e[1],e[4]),a=this.currentRenderState();return{centerX:e[2],centerY:e[5],width:t*i,height:n*s,scale:i,time:a?.elapsed??0,velocity:a?.velocity??jm,angularVelocity:a?.angularVelocity??0}}paintShaderInDeviceSpace(e,t){let n=this.canvasKit;this.currentCanvas.save();let i=n.Matrix.invert(t);i&&this.currentCanvas.concat(i);let s=new n.Paint;s.setShader(e),s.setAntiAlias(!0),this.currentCanvas.drawRect(n.LTRBRect(0,0,this.activeSurface.width(),this.activeSurface.height()),s),s.delete(),this.currentCanvas.restore()}rasterizeSurfaceSource(e,t,n,i){let s=bx(e);if(s.kind==="graphics")return this.rasterize(t,n,()=>this.draw(s.graphics),i);let a=s.node;return this.rasterize(t,n,()=>{a.layout({x:0,y:0,width:t,height:n},this),a.render(this)},i)}rasterize(e,t,n,i=1){if(!this.isRendering||!this.surface||!(e>0)||!(t>0))return null;if(this.rasterDepth>=qm)return console.warn(`rasterize() nested more than ${qm} deep \u2014 skipping. A Surface2D is most likely nested inside itself via a Canvas3D.`),null;let s=this.canvasKit,a=Math.max(1,Math.min(i,Bx)),o=Math.max(1,Math.ceil(e*a)),c=Math.max(1,Math.ceil(t*a)),l=this.activeSurface.makeSurface({...this.activeSurface.imageInfo(),width:o,height:c});if(!l)return null;let u=this.currentCanvas,d=this.activeSurface,h=this.worldAlpha,f=this.shapeHandler.beginNested(),p=l.getCanvas();p.save(),p.clear(s.TRANSPARENT),p.scale(a,a),p.translate(e/2,t/2),this.currentCanvas=p,this.activeSurface=l,this.worldAlpha=1,this.rasterDepth++;try{n()}finally{p.restore(),this.rasterDepth--,this.currentCanvas=u,this.activeSurface=d,this.worldAlpha=h,this.shapeHandler.endNested(f)}l.flush();let m=l.makeImageSnapshot(),g=m?.readPixels(0,0,{width:o,height:c,colorType:s.ColorType.RGBA_8888,alphaType:s.AlphaType.Unpremul,colorSpace:s.ColorSpace.SRGB});return m?.delete(),l.delete(),g?{pixels:new Uint8Array(g),width:o,height:c}:null}beginBoolean(e){if(!this.isRendering){console.warn("beginBoolean() must be called within the draw() method.");return}this.shapeHandler.beginBoolean(e)}endBoolean(){if(!this.isRendering){console.warn("endBoolean() must be called within the draw() method.");return}this.shapeHandler.endBoolean()}beginMask(e){if(!this.isRendering){console.warn("beginMask() must be called within the draw() method.");return}this.shapeHandler.beginMask(e),this.deferredPaintsStack.push([])}applyMask(){if(!this.isRendering){console.warn("applyMask() must be called within the draw() method.");return}this.shapeHandler.applyMask()}endMask(){if(!this.isRendering){console.warn("endMask() must be called within the draw() method.");return}this.shapeHandler.endMask();let e=this.deferredPaintsStack.pop()??[];this.flushDeferredPaints(e)}_maskOp(e){this.beginMask(e)}_applyMask(){this.applyMask()}_endMaskOp(){this.endMask()}flushDeferredPaints(e){for(let t of e)t.kind==="stroke"?(t.shadows&&this.strokeHandler.applyShadows(t.shadows,t.shapes,[],t.strokes,this.applyFillSpaceBounds),this.strokeHandler.applyStrokes(t.strokes,t.shapes,this.applyFillSpaceBounds)):(t.shadows&&this.strokeHandler.applyShadows(t.shadows,t.shapes,t.fills,[],this.applyFillSpaceBounds),this.fillHandler.applyFills(t.fills,t.shapes),t.shadows&&this.strokeHandler.applyInnerShadows(t.shadows,t.shapes,t.fills,this.applyFillSpaceBounds))}};import{AssetManager as $m,AudioSink as Ox,ClipStore as Lx,AssetTimeline as Ux,renderSettled as Nx,SETTLE_PASSES as zx,setTheme as Vx,spansCovering as Xm,StateEvaluator as Hx,yieldToScheduler as Wx}from"@motionscript/core";var Ls=class extends Ox{get schedulesAudio(){return!1}has(e){return!0}async append(e,t){}retain(e){}schedule(e){}syncTo(e){}play(e,t,n){}stop(){}};async function Qm({renderContext:r,storageAdapter:e},t,n){await Nx(()=>r.execute(t),e,()=>!0)==="exhausted"&&console.warn(`[export] frame ${n} still had pending decodes after ${zx} renders; it may not be exact.`)}function Ym(r){let e=r.getDecodePolicy();return r.setDecodePolicy("exact"),()=>r.setDecodePolicy(e)}function qx(r){let{fps:e,viewport:t}=r;if(e===void 0||t===void 0)throw new Error("Rendering takes a project whose fps and viewport are resolved \u2014 see Session.");return{fps:e,viewport:t}}function Gx(r,e){if(!r)return{start:0,end:e};let{start:t,end:n}=r;if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<=t||n>e)throw new RangeError(`Frames ${t} to ${n} are not a range inside this timeline's ${e} frames.`);return{start:t,end:n}}function Zm(r){let{project:e,registry:t,assetCatalog:n,renderContext:i}=r,{fps:s,viewport:a}=qx(e),o=()=>Vx(e.theme??r.theme);o();let c=i,l={registry:t,viewport:a,fps:s,assets:n,measurer:c},u={},d=new Lx(e,l,{isReady:p=>u.manager?.isReady(p)??!1}),h=new Ux(e,l,{store:d}),f=new Hx(e,l,d);return{store:d,precomper:h,stateEvaluator:f,measurer:c,fps:s,viewport:a,loads:u,applyTheme:o}}async function Jm(r,e,t){let n=t.flatMap(i=>r.layoutGates(i).filter(s=>!e.isReady(s.src)));n.length>0&&await e.loadRecords(n),r.settleGates(t)}function fu(r){let e=[];for(let t of r.tracks){let n=t.startFrame/r.fps;for(let i of t.audioRequests)e.push({request:i,globalOffset:n})}return e}async function mu(r){let{scale:e=1,sink:t,mixer:n,onProgress:i,signal:s,includeAudio:a=!0}=r,o=r,{renderContext:c,storageAdapter:l}=o;if(r.project.tracks.length===0)return;s?.throwIfAborted(),c.pixelRatio=e;let{store:u,precomper:d,stateEvaluator:h,measurer:f,fps:p,viewport:m,loads:g,applyTheme:y}=Zm(r),b=Ym(l);try{let{start:k,end:T}=Gx(r.frames,d.result().totalFrames),x=r.frames?u.spans.filter(Z=>Z.startFrame<T&&Z.endFrame>=k).map(Z=>Z.id):r.project.tracks.map(Z=>Z.id);if(r.frames)for(let Z of x)u.discover(Z);let v=r.frames?d.result():d.run(),{totalDuration:M}=v,C=T-k;ep(u,v,k,T-1);let _=g.manager=new $m(v,l,new Ls);await Jm(u,_,x);let F=fu(v),E=a&&!r.frames&&F.length>0&&n!==void 0;await t.start({width:m.width*e,height:m.height*e,fps:p,totalFrames:C,hasAudio:E});let O=1/p,Q=0;l.setPlaying(!0);try{for(let Z=k;Z<T;Z++){s?.throwIfAborted(),await _.loadAt(Z),y(),h.stateAt(Z),h.layout(f),await Qm(o,()=>h.render(c),Z),await t.addFrame(Q,O),Q+=O;let ee=Z-k+1;i?.(ee/C*(E?.85:1)),(Z+1)%4===0&&await Wx()}}finally{l.setPlaying(!1)}if(E){let Z=await n.mix(F,M);Z!==null&&t.addAudio&&await t.addAudio(Z),i?.(.97)}let ye=await t.finalize();return i?.(1),ye}finally{b(),h.dispose(),u.dispose()}}var Us=class extends Error{frame;failures;name="NothingToDrawError";constructor(e,t){let n=t.map(i=>` ${i.trackId}: ${i.message}`).join(`
|
|
2016
1870
|
`);super(`Frame ${e} has nothing to draw \u2014 every track on it failed to build:
|
|
2017
|
-
${n}`),this.frame=e,this.failures=t}};async function hu(r){let{scale:e=1,frame:t,project:n}=r,i=r,{renderContext:s,storageAdapter:a}=i;if(n.tracks.length===0)throw new Error("The project has no tracks to render.");s.pixelRatio=e;let{store:o,precomper:c,stateEvaluator:l,measurer:u,loads:d}=Om(r),h=Dm(a);try{let{totalFrames:f}=c.result(),p=t.kind==="first"?0:t.kind==="last"?f-1:t.frame,m=Math.max(0,Math.min(f-1,Math.floor(p))),g=c.ensureCovering(m);Um(o,g,m);let y=d.manager=new Fm(g,a,new Bs);return await Lm(o,y,Rm(o.spans,m).map(b=>b.id)),await y.loadAt(m),l.stateAt(m),l.layout(u),await Bm(i,()=>l.render(s),m),{frame:m,totalFrames:f}}finally{h(),l.dispose(),o.dispose()}}function Um(r,e,t,n=t){let i=new Map(e.buildErrors.filter(s=>r.failed(s.trackId)).map(s=>[s.trackId,s]));if(i.size!==0)for(let s=t;s<=n;s++){let a=Rm(r.spans,s);if(a.length>0&&a.every(o=>i.has(o.id)))throw new Ds(s,a.map(o=>i.get(o.id)))}}var at=null,zm=!0,vi=new Map,Do=64,Oo=4096;function xS(r,e){let t=new r.WebGLRenderer({antialias:e,alpha:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!0});return t.setClearColor(0,0),t.setPixelRatio(1),Oo=t.capabilities.maxTextureSize??Oo,t}function Nm(r,e){return at&&zm!==e&&(at.dispose(),at.forceContextLoss(),at=null),at||(at=xS(r,e),zm=e,vi.clear()),at}function SS(r,e,t){let n={width:Math.min(Oo,Math.max(1,Math.ceil(e/Do)*Do)),height:Math.min(Oo,Math.max(1,Math.ceil(t/Do)*Do))},i=vi.get(r);if(!i)return vi.set(r,n),n;let s={width:Math.max(i.width,n.width),height:Math.max(i.height,n.height)};return(s.width!==i.width||s.height!==i.height)&&vi.set(r,s),s}function TS(r,e,t,n,i,s,a={}){let o=Nm(r,a.antialias!==!1),c=SS(e,i,s),l=o.getSize(new r.Vector2);return(l.x!==c.width||l.y!==c.height)&&o.setSize(c.width,c.height,!1),o.render(t,n),{source:o.domElement,width:c.width,height:c.height}}function vS(r,e){at&&(at.shadowMap.enabled!==e.shadowsEnabled&&(at.shadowMap.enabled=e.shadowsEnabled,at.shadowMap.needsUpdate=!0),at.shadowMap.type!==e.shadowType&&(at.shadowMap.type=e.shadowType,at.shadowMap.needsUpdate=!0),at.toneMapping=e.toneMapping,at.toneMappingExposure=e.toneMappingExposure)}function AS(){return at}function _S(){at?.dispose(),at?.forceContextLoss(),at=null,vi.clear()}function CS(r){vi.delete(r)}var PS={prepare:(r,e)=>{Nm(r,e.antialias!==!1)},render:TS,applySettings:vS,active:AS,forgetBuffer:CS,dispose:_S};function Vm(){vl(),Fl(PS)}var cr=class extends Bo{constructor(e,t){super(e,t),Vm()}mount(e){let t=this.canvasKit.MakeWebGLCanvasSurface(e);if(!t)throw new Error("Failed to create CanvasKit surface");this.attach(t)}unmount(){this.detach()}screenshot(e="image/png",t){let n=this.snapshotPixels();if(!n)return;let{pixels:i,width:s,height:a}=n,o=document.createElement("canvas");o.width=s,o.height=a;let c=o.getContext("2d");if(c)return c.putImageData(new ImageData(new Uint8ClampedArray(i),s,a),0,0),o.toDataURL(e,t)}};import{StorageAdapter as jv}from"@motionscript/core";function w(r){if(!r)throw new Error("Assertion failed.")}var Ai=r=>{let e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},Ne=r=>r&&r[r.length-1],Ar=r=>r>=0&&r<2**32,Y=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},lr=r=>{let e=Y(r);return(e&1)===0?-(e>>1):e+1>>1};var Ye=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),ve=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),ot=new TextDecoder,_t=new TextEncoder;var yu=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),_r={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},En=yu(_r),Cr={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},In=yu(Cr),Pr={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Mn=yu(Pr),Hm=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,_i=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r),At=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(i=>{let s=!1;e=()=>{s||(i(),this.pending--,s=!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},Wm=/^[0-9a-fA-F]+$/,nn=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),qm=r=>{w(r.length%2===0);let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},wu=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Er=(r,e,t)=>{let n=0,i=r.length-1,s=-1;for(;n<=i;){let a=n+i>>1,o=t(r[a]);o===e?(s=a,i=a-1):o<e?n=a+1:i=a-1}return s},_e=(r,e,t)=>{let n=0,i=r.length-1,s=-1;for(;n<=i;){let a=n+(i-n+1)/2|0;t(r[a])<=e?(s=a,n=a+1):i=a-1}return s},bu=(r,e,t)=>{let n=_e(r,t(e),t);r.splice(n+1,0,e)},nt=()=>{let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}},jm=(r,e)=>{let t=r.indexOf(e);t!==-1&&r.splice(t,1)},ku=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Ci=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},Gm=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Km=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},Ct=r=>{throw new Error(`Unexpected value: ${r}`)},Os=(r,e,t)=>{let n=r.getUint8(e),i=r.getUint8(e+1),s=r.getUint8(e+2);return t?n|i<<8|s<<16:n<<16|i<<8|s};var Ls=(r,e,t,n)=>{t=t>>>0,t=t&16777215,n?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},$m=(r,e,t,n)=>{t=Ze(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),Ls(r,e,t,n)};var Ze=(r,e,t)=>Math.max(e,Math.min(t,r)),Ge="und",Ir=r=>{let e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Us=(r,e)=>Math.round(r/e)*e,Fn=(r,e)=>Math.round(r*e)/e,Uo=(r,e)=>Math.floor(r/e)*e,xu=(r,e)=>Math.floor(r*e)/e,Xm=r=>{let e=0;for(;r;)e++,r>>=1;return e},ES=/^[a-z]{3}$/,Pi=r=>ES.test(r),ur=1e6*(1+Number.EPSILON),Qm=(r,e)=>{let t={...r,...e};if(r.headers||e.headers){let n=r.headers?Lo(r.headers):{},i=e.headers?Lo(e.headers):{},s={...n};Object.entries(i).forEach(([a,o])=>{let c=Object.keys(s).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),t.headers=s}return t},Lo=r=>{if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}if(Array.isArray(r)){let e={};return r.forEach(([t,n])=>{e[t]=n}),e}return r},Ym=async(r,e,t,n,i)=>{let s=0;for(;;)try{return await r(e,t)}catch(a){if(i())throw a;s++;let o=n(s,a,e);if(o===null)throw a;if(we._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await Ws(1e3*o),i())throw a}},Zm=(r,e)=>{let t=r<0?-1:1;r=Math.abs(r);let n=0,i=1,s=1,a=0,o=r;for(;;){let c=Math.floor(o),l=c*s+n,u=c*a+i;if(u>e)return{num:t*s,den:a};if(n=s,i=a,s=l,a=u,o=1/(o-c),!isFinite(o))break}return{num:t*s,den:a}},rn=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},fu=null,sn=()=>fu!==null?fu:fu=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),mu=null,zs=()=>mu!==null?mu:mu=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),pu=null,Ns=()=>pu!==null?pu:pu=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),gu=null,Jm=()=>{if(gu!==null)return gu;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?gu=Number(r[1]):null},Rn=(r,e)=>r!==-1?r:e,zo=(r,e,t,n)=>r<=n&&t<=e,Vs=function*(r){for(let e in r){let t=r[e];t!==void 0&&(yield{key:e,value:t})}};var Hs=r=>{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t};var ep=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},Ei=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Ii=r=>typeof r=="number"&&!Number.isNaN(r),dr=(r,e)=>{if(e.includes("://"))return e;if(r.includes("://")){let o=r.indexOf("?");o!==-1&&(r=r.slice(0,o))}let t;if(e.startsWith("/")){let o=r.indexOf("://");if(o===-1)t=e;else{let c=r.indexOf("/",o+3);c===-1?t=r+e:t=r.slice(0,c)+e}}else{let o=r.lastIndexOf("/");o===-1?t=e:t=r.slice(0,o+1)+e}let n="",i=t.indexOf("://");if(i!==-1){let o=t.indexOf("/",i+3);o!==-1&&(n=t.slice(0,o),t=t.slice(o))}let s=t.split("/"),a=[];for(let o of s)o===".."?a.pop():o!=="."&&a.push(o);return n+a.join("/")},Bn=(r,e)=>{let t=0;for(let n=0;n<r.length;n++)e(r[n])&&t++;return t},Mi=(r,e)=>{let t=-1,n=1/0;for(let i=0;i<r.length;i++){let s=e(r[i]);s<n&&(n=s,t=i)}return t};var Dn=r=>{w(Number.isInteger(r.num)),w(Number.isInteger(r.den)),w(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){let i=e%t;e=t,t=i}let n=e||1;return{num:r.num/n,den:r.den/n}},Su=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};var Ws=r=>new Promise(e=>setTimeout(e,r));var Tu=r=>Array.isArray(r)?r:[r],Nt=class{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);let i={fn:t,once:n?.once??!1};return this._listeners.get(e).add(i),()=>{this._listeners.get(e)?.delete(i)}}_emit(...e){let[t,n]=e,i=this._listeners.get(t);if(i)for(let s of i){try{s.fn(n)}catch(a){console.error(a)}s.once&&i.delete(s)}}};var vu=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");var hr;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(hr||(hr={}));var we=class r{constructor(){}static get level(){return r._level}static set level(e){if(e!==hr.Silent&&e!==hr.Errors&&e!==hr.Warnings&&e!==hr.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");r._level=e}static get _emitter(){return r._emitterInstance??=new Nt}static on(e,t,n){return r._emitter.on(e,t,n)}static _error(...e){r._emitter._emit("error",e),r._level>=hr.Errors&&console.error(...e)}static _warn(...e){r._emitter._emit("warn",e),r._level>=hr.Warnings&&console.warn(...e)}static _info(...e){r._emitter._emit("info",e),r._level>=hr.Info&&console.info(...e)}};we._level=hr.Info;we._emitterInstance=null;var Kt=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}},qs=class{constructor(e,t,n,i){if(this.data=e,this.mimeType=t,this.name=n,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("description, when provided, must be a string.")}},tp=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Kt)&&!(e instanceof qs)&&!vu(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}};var dt={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},rp=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var Ie=class r{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),i=(t&1<<n)>>n;return this.pos++,i}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let i=this.pos;i<n;i++){let s=Math.floor(i/8),a=this.bytes[s],o=7-(i&7);a&=~(1<<o),a|=(t&1<<n-i-1)>>n-i-1<<o,this.bytes[s]=a}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new r(this.bytes);return e.pos=this.pos,e}};var fr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],an=[-1,1,2,3,4,5,6,8],Fi=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new Ie(r),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let n=e.readBits(4),i=null;n===15?i=e.readBits(24):n<fr.length&&(i=fr[n]);let s=e.readBits(4),a=null;return s>=1&&s<=7&&(a=an[s]),{objectType:t,frequencyIndex:n,sampleRate:i,channelConfiguration:s,numberOfChannels:a}},No=r=>{let e=fr.indexOf(r.sampleRate),t=null;e===-1&&(e=15,t=r.sampleRate);let n=an.indexOf(r.numberOfChannels);if(n===-1)throw new TypeError(`Unsupported number of channels: ${r.numberOfChannels}`);let i=13;r.objectType>=32&&(i+=6),e===15&&(i+=24);let s=Math.ceil(i/8),a=new Uint8Array(s),o=new Ie(a);return r.objectType<32?o.writeBits(5,r.objectType):(o.writeBits(5,31),o.writeBits(6,r.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,t),o.writeBits(4,n),a};var gt=["avc","hevc","vp9","av1","vp8"],ht=["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"],Vo=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Vt=[...Vo,...ht],on=["webvtt"],js=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],np=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Mr=[{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}],ip=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],sp=".01.01.01.01.00",ap=".0.110.01.01.01.0",op=(r,e,t,n)=>{if(r==="avc"){let s=Math.ceil(e/16)*Math.ceil(t/16),a=js.find(d=>s<=d.maxMacroblocks&&n<=d.maxBitrate)??Ne(js),o=a?a.level:0,c="64".padStart(2,"0"),l="00",u=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(r==="hevc"){let o=e*t,c=np.find(u=>o<=u.maxPictureSize&&n<=u.maxBitrate)??Ne(np);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){let s=e*t;return`vp09.00.${(Mr.find(c=>s<=c.maxPictureSize&&n<=c.maxBitrate)??Ne(Mr)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){let s=e*t,a=ip.find(l=>s<=l.maxPictureSize&&n<=l.maxBitrate)??Ne(ip);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${r}'.`)};var cp=r=>{let e=r.split("."),i=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(s<<5)+o,l=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,h=0,f=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,g=e[5]?Number(e[5][2]):0,y=(l<<7)+(d<<6)+(h<<5)+(f<<4)+(p<<3)+(m<<2)+g;return[i,c,y,0]},Ri=r=>{let{codec:e,codecDescription:t,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o}=r;if(e==="avc"){if(w(r.avcType!==null),i){let c=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${r.avcType}.${nn(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${nn(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,h,f;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,u=wu(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,h=s.generalLevelIdc,f=[...s.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let m=ve(t),g=m.getUint8(1);c=g>>6&3,l=g&31,u=wu(m.getUint32(2)),d=g>>5&1,h=m.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(m.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=u.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=h;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(m=>m.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let y=r.width*r.height,b=Ne(Mr).level;for(let k of Mr)if(y<=k.maxPictureSize){b=k.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}let c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),u=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),f=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),m=a.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${l}.${u}.${d}`;return g+=`.${h}.${f}.${p}.${m}`,g.endsWith(sp)&&(g=g.slice(0,-sp.length)),g}else if(e==="av1"){if(!o){let k=r.width*r.height,T=Ne(Mr).level;for(let S of Mr)if(k<=S.maxPictureSize){T=S.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=o.profile,l=o.level.toString().padStart(2,"0"),u=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",f=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),p=n?.primaries?_r[n.primaries]:1,m=n?.transfer?Cr[n.transfer]:1,g=n?.matrix?Pr[n.matrix]:1,y=n?.fullRange?1:0,b=`av01.${c}.${l}${u}.${d}`;return b+=`.${h}.${f.toString().padStart(3,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${m.toString().padStart(2,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(ap)&&(b=b.slice(0,-ap.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)},lp=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(ht.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},Bi=r=>{let{codec:e,codecDescription:t,aacCodecInfo:n}=r;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");if(n.isMpeg2)return"mp4a.67";{let i;return n.objectType!==null?i=n.objectType:i=Fi(t).objectType,`mp4a.40.${i}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&ht.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)};var On=48e3,up=/^pcm-([usf])(\d+)(be)?$/,Ht=r=>{if(w(ht.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=up.exec(r);w(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let n=Number(e[2])/8,i=e[3]!=="be",s=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:n,littleEndian:i,silentValue:s}},Fr=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":r==="ulaw"?"ulaw":r==="alaw"?"alaw":up.test(r)?r:r==="webvtt"?"webvtt":null,dp=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},hp=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},IS=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],MS=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,FS=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,RS=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,BS=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,fp=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!IS.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!_i(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=r.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let t=Object.keys(_r);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);let n=Object.keys(Cr);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let i=Object.keys(Pr);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!MS.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!FS.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!RS.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")&&!BS.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},DS=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],mp=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!DS.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!_i(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!ht.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ht.join(", ")}).`)},pp=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var OS=[44100,48e3,32e3],LS=[-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],Ho=1483304551,Wo=1231971951,US=(r,e,t,n,i)=>e===0?0:e===1?Math.floor(144*t/(n<<r))+i:e===2?Math.floor(144*t/n)+i:(Math.floor(12*t/n)+i)*4,gp=(r,e,t,n)=>e===0?0:e===1?144*t/(n<<r):e===2?144*t/n:12*t/n*4,qo=(r,e)=>r===3?e===3?21:36:e===3?13:21,Ks=(r,e)=>{let t=r>>>24,n=r>>>16&255,i=r>>>8&255,s=r&255;if(t!==255&&n!==255&&i!==255&&s!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;n&16?a=n&8?0:1:(a=1,o=1);let c=n>>3&3,l=n>>1&3,u=i>>4&15,d=(i>>2&3)%3,h=i>>1&1,f=s>>6&3,p=s>>4&3,m=s>>3&1,g=s>>2&1,y=s&3,b=LS[a*16*4+l*16+u];if(b===-1)return{header:null,bytesAdvanced:1};let k=b*1e3,T=OS[d]>>a+o,S=US(a,l,k,T,h);if(e!==null&&e<S)return{header:null,bytesAdvanced:1};let _;return c===3?_=l===3?384:1152:l===3?_=384:l===2?_=1152:_=576,{header:{totalSize:S,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:k,frequencyIndex:d,sampleRate:T,channel:f,modeExtension:p,copyright:m,original:g,emphasis:y,audioSamplesInFrame:_},bytesAdvanced:1}};var jo=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t},Gs;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(Gs||(Gs={}));var cn=r=>r===3?1:2;var Ln=[48e3,44100,32e3],Au=[24e3,22050,16e3];var lt;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(lt||(lt={}));var it;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(it||(it={}));var Di=function*(r){let e=0,t=-1;for(;e<r.length-2;){let n=r.indexOf(0,e);if(n===-1||n>=r.length-2)break;e=n;let i=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?i=4:r[e+1]===0&&r[e+2]===1&&(i=3),i===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+i,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},bp=function*(r,e){let t=0,n=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let i;e===1?i=n.getUint8(t):e===2?i=n.getUint16(t,!1):e===3?i=Os(n,t,!1):(w(e===4),i=n.getUint32(t,!1)),t+=e,yield{offset:t,length:i},t+=i}},Cu=(r,e)=>{if(e.description){let i=(Ye(e.description)[4]&3)+1;return bp(r,i)}else return Di(r)},Oi=r=>r&31,Go=r=>{let e=[],t=r.length;for(let n=0;n<t;n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e.push(0,0),n+=2):e.push(r[n]);return new Uint8Array(e)},_u=new Uint8Array([0,0,0,1]),kp=r=>{let e=r.reduce((i,s)=>i+_u.byteLength+s.byteLength,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(_u,n),n+=_u.byteLength,t.set(i,n),n+=i.byteLength;return t},Ko=(r,e)=>{let t=r.reduce((s,a)=>s+e+a.byteLength,0),n=new Uint8Array(t),i=0;for(let s of r){let a=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:a.setUint8(i,s.byteLength);break;case 2:a.setUint16(i,s.byteLength,!1);break;case 3:Ls(a,i,s.byteLength,!1);break;case 4:a.setUint32(i,s.byteLength,!1);break}i+=e,n.set(s,i),i+=s.byteLength}return n},xp=(r,e)=>{if(e.description){let i=(Ye(e.description)[4]&3)+1;return Ko(r,i)}else return kp(r)},Li=r=>{try{let e=[],t=[],n=[];for(let o of Di(r)){let c=r.subarray(o.offset,o.offset+o.length),l=Oi(c[0]);l===lt.SPS?e.push(c):l===lt.PPS?t.push(c):l===lt.SPS_EXT&&n.push(c)}if(e.length===0||t.length===0)return null;let i=e[0],s=Xs(i);w(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(e){return we._error("Error building AVC Decoder Configuration Record:",e),null}},Sp=r=>{let e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(let t of r.sequenceParameterSets){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}e.push(r.pictureParameterSets.length);for(let t of r.pictureParameterSets){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}if(r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144){w(r.chromaFormat!==null),w(r.bitDepthLumaMinus8!==null),w(r.bitDepthChromaMinus8!==null),w(r.sequenceParameterSetExt!==null),e.push(252|r.chromaFormat&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.sequenceParameterSetExt.length);for(let t of r.sequenceParameterSetExt){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}}return new Uint8Array(e)},Tp=r=>{try{let e=ve(r),t=0,n=e.getUint8(t++),i=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let f=0;f<c;f++){let p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}let u=e.getUint8(t++),d=[];for(let f=0;f<u;f++){let p=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+p)),t+=p}let h={configurationVersion:n,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&t+4<=r.length){let f=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,g=e.getUint8(t++);h.chromaFormat=f,h.bitDepthLumaMinus8=p,h.bitDepthChromaMinus8=m;let y=[];for(let b=0;b<g;b++){let k=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+k)),t+=k}h.sequenceParameterSetExt=y}return h}catch(e){return we._error("Error deserializing AVC Decoder Configuration Record:",e),null}},vp={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Xs=r=>{try{let e=new Ie(Go(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();Y(e);let a=1,o=0,c=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=Y(e),a===3&&(l=e.readBits(1)),o=Y(e),c=Y(e),e.skipBits(1),e.readBits(1))){for(let O=0;O<(a!==3?8:12);O++)if(e.readBits(1)){let ge=O<6?16:64,be=8,J=8;for(let Ae=0;Ae<ge;Ae++){if(J!==0){let Re=lr(e);J=(be+Re+256)%256}be=J===0?be:J}}}Y(e);let u=Y(e);if(u===0)Y(e);else if(u===1){e.skipBits(1),lr(e),lr(e);let I=Y(e);for(let O=0;O<I;O++)lr(e)}Y(e),e.skipBits(1);let d=Y(e),h=Y(e),f=16*(d+1),p=16*(h+1),m=f,g=p,y=e.readBits(1);if(y||e.skipBits(1),e.skipBits(1),e.readBits(1)){let I=Y(e),O=Y(e),Q=Y(e),ge=Y(e),be,J;if((l===0?a:0)===0)be=1,J=2-y;else{let Re=a===3?1:2,et=a===1?2:1;be=Re,J=et*(2-y)}m-=be*(I+O),g-=J*(Q+ge)}let k=2,T=2,S=2,_=0,M={num:1,den:1},P=null,A=null;if(e.readBits(1)){if(e.readBits(1)){let et=e.readBits(8);if(et===255)M={num:e.readBits(16),den:e.readBits(16)};else{let Ia=vp[et];Ia&&(M=Ia)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),_=e.readBits(1),e.readBits(1)&&(k=e.readBits(8),T=e.readBits(8),S=e.readBits(8))),e.readBits(1)&&(Y(e),Y(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let J=e.readBits(1);J&&yp(e);let Ae=e.readBits(1);Ae&&yp(e),(J||Ae)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),Y(e),Y(e),Y(e),Y(e),P=Y(e),A=Y(e))}if(P===null){w(A===null);let I=i&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&I)P=0,A=0;else{let O=d+1,Q=h+1,ge=(2-y)*Q,be=js.find(Ae=>Ae.level>=s)??Ne(js),J=Math.min(Math.floor(be.maxDpbMbs/(O*ge)),16);P=J,A=J}}return w(A!==null),{profileIdc:n,constraintFlags:i,levelIdc:s,frameMbsOnlyFlag:y,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:g,pixelAspectRatio:M,colourPrimaries:k,matrixCoefficients:S,transferCharacteristics:T,fullRangeFlag:_,numReorderFrames:P,maxDecFrameBuffering:A}}catch(e){return we._error("Error parsing AVC SPS:",e),null}},yp=r=>{let e=Y(r);r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)Y(r),Y(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},zS=(r,e)=>{if(e.description){let i=(Ye(e.description)[21]&3)+1;return Ko(r,i)}else return kp(r)},$s=(r,e)=>{if(e.description){let i=(Ye(e.description)[21]&3)+1;return bp(r,i)}else return Di(r)},ln=r=>r>>1&63,Pu=r=>{try{let e=new Ie(Go(r));e.skipBits(16),e.readBits(4);let t=e.readBits(3),n=e.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=NS(e,t);Y(e);let u=Y(e),d=0;u===3&&(d=e.readBits(1));let h=Y(e),f=Y(e),p=h,m=f;if(e.readBits(1)){let O=Y(e),Q=Y(e),ge=Y(e),be=Y(e),J=1,Ae=1,Re=d===0?u:0;Re===1?(J=2,Ae=2):Re===2&&(J=2,Ae=1),p-=(O+Q)*J,m-=(ge+be)*Ae}let g=Y(e),y=Y(e);Y(e);let k=e.readBits(1)?0:t,T=0;for(let O=k;O<=t;O++)Y(e),T=Y(e),Y(e);Y(e),Y(e),Y(e),Y(e),Y(e),Y(e),e.readBits(1)&&e.readBits(1)&&VS(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),Y(e),Y(e),e.skipBits(1));let S=Y(e);if(HS(e,S),e.readBits(1)){let O=Y(e);for(let Q=0;Q<O;Q++)Y(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let _=2,M=2,P=2,A=0,F=0,I={num:1,den:1};if(e.readBits(1)){let O=qS(e,t);I=O.pixelAspectRatio,_=O.colourPrimaries,M=O.transferCharacteristics,P=O.matrixCoefficients,A=O.fullRangeFlag,F=O.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:I,colourPrimaries:_,transferCharacteristics:M,matrixCoefficients:P,fullRangeFlag:A,maxDecFrameBuffering:T+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:F}}catch(e){return we._error("Error parsing HEVC SPS:",e),null}},Ui=r=>{try{let e=[],t=[],n=[],i=[];for(let l of Di(r)){let u=r.subarray(l.offset,l.offset+l.length),d=ln(u[0]);d===it.VPS_NUT?e.push(u):d===it.SPS_NUT?t.push(u):d===it.PPS_NUT?n.push(u):(d===it.PREFIX_SEI_NUT||d===it.SUFFIX_SEI_NUT)&&i.push(u)}if(t.length===0||n.length===0)return null;let s=Pu(t[0]);if(!s)return null;let a=0;if(n.length>0){let l=n[0],u=new Ie(Go(l));u.skipBits(16),Y(u),Y(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),Y(u),Y(u),lr(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&Y(u),lr(u),lr(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);let d=u.readBits(1),h=u.readBits(1);!d&&!h?a=0:d&&!h?a=2:!d&&h?a=3:a=0}let o=[...e.length?[{arrayCompleteness:1,nalUnitType:it.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:it.SPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:it.PPS_NUT,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ln(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return we._error("Error building HEVC Decoder Configuration Record:",e),null}},NS=(r,e)=>{let t=r.readBits(2),n=r.readBits(1),i=r.readBits(5),s=0;for(let u=0;u<32;u++)s=s<<1|r.readBits(1);let a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);let o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},VS=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))Y(r);else{let i=Math.min(64,1<<4+(e<<1));e>1&&lr(r);for(let s=0;s<i;s++)lr(r)}},HS=(r,e)=>{let t=[];for(let n=0;n<e;n++)t[n]=WS(r,n,e,t)},WS=(r,e,t,n)=>{let i=0,s=0,a=0;if(e!==0&&(s=r.readBits(1)),s){if(e===t){let c=Y(r);a=e-(c+1)}else a=e-1;r.readBits(1),Y(r);let o=n[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);i=n[a]}else{let o=Y(r),c=Y(r);for(let l=0;l<o;l++)Y(r),r.readBits(1);for(let l=0;l<c;l++)Y(r),r.readBits(1);i=o+c}return i},qS=(r,e)=>{let t=2,n=2,i=2,s=0,a=0,o={num:1,den:1};if(r.readBits(1)){let c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{let l=vp[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),s=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),n=r.readBits(8),i=r.readBits(8))),r.readBits(1)&&(Y(r),Y(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(Y(r),Y(r),Y(r),Y(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&Y(r),r.readBits(1)&&jS(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=Y(r),Y(r),Y(r),Y(r),Y(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},jS=(r,e,t)=>{let n=!1,i=!1,s=!1;e&&(n=r.readBits(1)===1,i=r.readBits(1)===1,(n||i)&&(s=r.readBits(1)===1,s&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),s&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let a=0;a<=t;a++){let o=r.readBits(1)===1,c=!0;o||(c=r.readBits(1)===1);let l=!1;c?Y(r):l=r.readBits(1)===1;let u=1;l||(u=Y(r)+1),n&&wp(r,u,s),i&&wp(r,u,s)}},wp=(r,e,t)=>{for(let n=0;n<e;n++)Y(r),Y(r),t&&(Y(r),Y(r)),r.readBits(1)},Ap=r=>{let e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(let t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(let n of t.nalUnits){e.push(n.length>>8&255),e.push(n.length&255);for(let i=0;i<n.length;i++)e.push(n[i])}}return new Uint8Array(e)};var pt;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(pt||(pt={}));var _p=(r,e)=>{let t=new Set,n=pt.audAllowed;for(let s of $s(r,e)){if(n===pt.noMoreDataAllowed){t.add(s.offset);continue}let a=ln(r[s.offset]);if(n===pt.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?n>pt.audAllowed?o=!0:n=pt.beforeFirstVcl:a<=31?n>pt.afterFirstVcl?o=!0:n=pt.afterFirstVcl:a===36?n!==pt.afterFirstVcl?o=!0:n=pt.eoBitstreamAllowed:a===37?n<pt.afterFirstVcl?o=!0:n=pt.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?n>pt.beforeFirstVcl?o=!0:n=pt.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&n<pt.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;let i=[];for(let s of $s(r,e))t.has(s.offset)||i.push(r.subarray(s.offset,s.offset+s.length));return zS(i,e)},$o=r=>{let e=new Ie(r);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 u=e.readBits(3),d=0,h=0;if(u!==7)if(h=e.readBits(1),s===1||s===3){let M=e.readBits(1),P=e.readBits(1);d=!M&&!P?3:M&&!P?2:1,e.skipBits(1)}else d=1;else d=3,h=1;let f=e.readBits(16),p=e.readBits(16),m=f+1,g=p+1,y=m*g,b=Ne(Mr).level;for(let _ of Mr)if(y<=_.maxPictureSize){b=_.level;break}return{profile:s,level:b,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Cp=function*(r){let e=new Ie(r),t=()=>{let n=0;for(let i=0;i<8;i++){let s=e.readAlignedByte();if(n|=(s&127)<<i*7,!(s&128))break;if(i===7&&s&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),i=e.readBits(1),s=e.readBits(1);e.skipBits(1),i&&e.skipBits(8);let a;if(s){let o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);w(e.pos%8===0),yield{type:n,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Xo=r=>{for(let{type:e,data:t}of Cp(r)){if(e!==1)continue;let n=new Ie(t),i=n.readBits(3),s=n.readBits(1),a=n.readBits(1),o=0,c=0,l=0;if(a)o=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let _=n.readBits(1);_&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let M=n.readBits(5);for(let P=0;P<=M;P++){n.skipBits(12);let A=n.readBits(5);if(P===0&&(o=A),A>7){let I=n.readBits(1);P===0&&(c=I)}if(_&&n.readBits(1)){let O=l+1;n.skipBits(O),n.skipBits(O),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let u=n.readBits(4),d=n.readBits(4),h=u+1;n.skipBits(h);let f=d+1;n.skipBits(f);let p=0;if(a?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!a){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 _=n.readBits(1),M=0;_?M=2:M=n.readBits(1),M>0&&(n.readBits(1)||n.skipBits(1)),S&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let m=n.readBits(1),g=8;i===2&&m?g=n.readBits(1)?12:10:i<=2&&(g=m?10:8);let y=0;i!==1&&(y=n.readBits(1));let b=1,k=1,T=0;return y||(i===0?(b=1,k=1):i===1?(b=0,k=0):g===12&&(b=n.readBits(1),b&&(k=n.readBits(1))),b&&k&&(T=n.readBits(2))),{profile:i,level:o,tier:c,bitDepth:g,monochrome:y,chromaSubsamplingX:b,chromaSubsamplingY:k,chromaSamplePosition:T}}return null},Qo=r=>{let e=ve(r),t=e.getUint8(9),n=e.getUint16(10,!0),i=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18),o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:n,inputSampleRate:i,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},GS=[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],Pp=r=>{let e=r[0]>>3;return{durationInSamples:GS[e]}},Ep=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=r.length,n=new Uint8Array(t);for(let d=0;d<t;d++)n[d]=r[t-1-d];let i=new Ie(n),s=0;for(;i.getBitsLeft()>97;)if(i.readBits(1)===1){s=i.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;i.getBitsLeft()>=97;){let d=i.pos,h=i.readBits(8),f=i.readBits(16),p=i.readBits(16);if(h>63||f!==0||p!==0){i.pos=d;break}if(i.skipBits(1),a++,a>64)break;i.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;i.pos=0,i.skipBits(s);let u=Array(l).fill(0);for(let d=l-1;d>=0;d--)i.skipBits(40),u[d]=i.readBits(1);return{modeBlockflags:u}},dn=(r,e,t)=>{switch(r){case"avc":{for(let n of Cu(t,e)){let i=t[n.offset],s=Oi(i);if(s>=lt.NON_IDR_SLICE&&s<=lt.SLICE_DPC)return"delta";if(s===lt.IDR)return"key";if(s===lt.SEI&&(!Ns()||Jm()>=144)){let a=t.subarray(n.offset,n.offset+n.length),o=Go(a),c=1;do{let l=0;for(;;){let h=o[c++];if(h===void 0||(l+=h,h<255))break}let u=0;for(;;){let h=o[c++];if(h===void 0||(u+=h,h<255))break}if(l===6){let h=new Ie(o);h.pos=8*c;let f=Y(h),p=h.readBits(1);if(f===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(let n of $s(t,e)){let i=ln(t[n.offset]);if(i<it.BLA_W_LP)return"delta";if(i<=it.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let n=new Ie(t);if(n.readBits(2)!==2)return null;let i=n.readBits(1);return(n.readBits(1)<<1)+i===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:i,data:s}of Cp(t))if(i===1){let a=new Ie(s);a.skipBits(4),n=!!a.readBits(1)}else if(i===3||i===6||i===7){if(n)return"key";let a=new Ie(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:Ct(r),w(!1)}},un;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(un||(un={}));var Qs=(r,e)=>{let t=ve(r),n=0,i=t.getUint32(n,!0);n+=4;let s=ot.decode(r.subarray(n,n+i));n+=i,i>0&&(e.raw??={},e.raw.vendor??=s);let a=t.getUint32(n,!0);n+=4;for(let o=0;o<a;o++){let c=t.getUint32(n,!0);n+=4;let l=ot.decode(r.subarray(n,n+c));n+=c;let u=l.indexOf("=");if(u===-1)continue;let d=l.slice(0,u).toUpperCase(),h=l.slice(u+1);switch(e.raw??={},e.raw[d]??=h,d){case"TITLE":e.title??=h;break;case"DESCRIPTION":e.description??=h;break;case"ARTIST":e.artist??=h;break;case"ALBUM":e.album??=h;break;case"ALBUMARTIST":e.albumArtist??=h;break;case"COMMENT":e.comment??=h;break;case"LYRICS":e.lyrics??=h;break;case"TRACKNUMBER":{let f=h.split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"TRACKTOTAL":{let f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{let f=h.split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DISCTOTAL":{let f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{let f=new Date(h);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=h;break;case"METADATA_BLOCK_PICTURE":{let f=Hs(h),p=ve(f),m=p.getUint32(0,!1),g=p.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+g)),b=p.getUint32(8+g,!1),k=ot.decode(f.subarray(12+g,12+g+b)),T=p.getUint32(g+b+28),S=f.subarray(g+b+32,g+b+32+T);e.images??=[],e.images.push({data:S,mimeType:y,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:k||void 0})}break}}};var Ys=[2,1,2,3,3,4,4,5],Yo=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;let e=new Ie(r);e.skipBits(16),e.skipBits(16);let t=e.readBits(2);if(t===3)return null;let n=e.readBits(6),i=e.readBits(5);if(i>8)return null;let s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);let o=e.readBits(1),c=Math.floor(n/2);return{fscod:t,bsid:i,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},Ip=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],Mp=1536,eM=new Uint8Array([5,4,65,67,45,51]),tM=new Uint8Array([5,4,69,65,67,51]),Eu=[1,2,3,6],Zo=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;let e=new Ie(r);e.skipBits(16);let t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;let n=e.readBits(11),i=e.readBits(2),s=0,a;i===3?(s=e.readBits(2),a=3):a=e.readBits(2);let o=e.readBits(3),c=e.readBits(1),l=e.readBits(5);if(l<11||l>16)return null;let u=Eu[a],d;return i<3?d=Ln[i]/1e3:d=Au[s]/1e3,{dataRate:Math.round((n+1)*d/(u*16)),substreams:[{fscod:i,fscod2:s,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},Fp=r=>{if(r.length<2)return null;let e=new Ie(r),t=e.readBits(13),n=e.readBits(3),i=[];for(let s=0;s<=n&&!(Math.ceil(e.pos/8)+3>r.length);s++){let a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);let c=e.readBits(3),l=e.readBits(3),u=e.readBits(1);e.skipBits(3);let d=e.readBits(4),h=0;d>0?h=e.readBits(9):e.skipBits(1),i.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:h})}return i.length===0?null:{dataRate:t,substreams:i}},Jo=r=>{let e=r.substreams[0];return w(e),e.fscod<3?Ln[e.fscod]:e.fscod2!==null&&e.fscod2<3?Au[e.fscod2]:null},ec=r=>{let e=r.substreams[0];w(e);let t=Ys[e.acmod]+e.lfeon;if(e.numDepSub>0){let n=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)e.chanLoc&1<<8-i&&(t+=n[i])}return t};var ct=class{constructor(e){this.input=e}dispose(){}};var st=new Uint8Array(0),Oe=class r{constructor(e,t,n,i,s=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=i,this.sequenceNumber=s,e===st&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<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(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===st}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new r(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');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.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new r(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}};var tc=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings)];t+=`; codecs="${n.join(", ")}"`}return t},rc=r=>{let e=ve(r),t=0,n=e.getUint8(t);t+=1,t+=3;let i=nn(r.subarray(t,t+16));t+=16;let s=null;if(n>0){let o=e.getUint32(t);if(t+=4,o>0){s=[];for(let c=0;c<o;c++)s.push(nn(r.subarray(t,t+16))),t+=16}}let a=e.getUint32(t);return t+=4,{systemId:i,keyIds:s,data:r.slice(t,t+a)}},nc=(r,e)=>r.systemId===e.systemId&&ep(r.data,e.data);var $t=8,Rr=16,Br=r=>{let e=K(r),t=We(r,4),n=8;e===1&&(e=Pt(r),n=16);let s=e-n;return s<0?null:{name:t,totalSize:e,headerSize:n,contentSize:s}},hn=r=>Dr(r)/65536,ic=r=>Dr(r)/1073741824,sc=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;let n=ce(r);if(e|=n&127,(n&128)===0)break}return e},Xt=r=>{let e=Ke(r);return r.skip(2),e=Math.min(e,r.remainingLength),ot.decode(ie(r,e))},Rp=r=>{let e=Br(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;let t=K(r);r.skip(4);let n=ie(r,e.contentSize-8);switch(t){case 1:return ot.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new Kt(n,"image/jpeg");case 14:return new Kt(n,"image/png");case 27:return new Kt(n,"image/bmp");default:return n}};var Qt=16,Or=new Uint32Array(256),zi=new Uint32Array(256),Ni=new Uint32Array(256),Vi=new Uint32Array(256),Hi=new Uint32Array(256),ft=new Uint32Array(256),Bp=new Uint32Array(10),Dp=!1,KS=()=>{let r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let s=0,a=1;s<256;s++)t[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);let n=(s,a)=>s&&a?t[(e[s]+e[a])%255]:0;r[0]=99;for(let s=1;s<256;s++){let a=t[255-e[s]],o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[s]=o}for(let s=0;s<256;s++){let a=r[s],o=r.indexOf(s);Or[s]=a<<24|a<<16|a<<8|a,ft[s]=o<<24|o<<16|o<<8|o;let c=n(o,14),l=n(o,9),u=n(o,13),d=n(o,11),h=c<<24|l<<16|u<<8|d;zi[s]=h,Ni[s]=h>>>8|h<<24,Vi[s]=h>>>16|h<<16,Hi[s]=h>>>24|h<<8}let i=1;for(let s=0;s<10;s++)Bp[s]=i<<24,i=i<<1^(i&128?283:0);Dp=!0},Zs=class{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Qt/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Qt),this.out=new Uint8Array(Qt),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){w(e.byteLength===16),w(t.byteLength===16),Dp||KS();let n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let s=4;s<44;s+=4){let a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^Or[a>>>16&255]&4278190080^Or[a>>>8&255]&16711680^Or[a>>>0&255]&65280^Or[a>>>24&255]&255^Bp[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){let c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){let o=this.roundkey[s+a];this.roundkey[s+a]=zi[Or[o>>>24&255]&255]^Ni[Or[o>>>16&255]&255]^Vi[Or[o>>>8&255]&255]^Hi[Or[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],i=this.inView.getUint32(12,!1)^this.roundkey[3],s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1),l,u,d,h;for(let y=1;y<10;y++){let b=y*4;l=zi[e>>>24]^Ni[i>>>16&255]^Vi[n>>>8&255]^Hi[t&255]^this.roundkey[b],u=zi[t>>>24]^Ni[e>>>16&255]^Vi[i>>>8&255]^Hi[n&255]^this.roundkey[b+1],d=zi[n>>>24]^Ni[t>>>16&255]^Vi[e>>>8&255]^Hi[i&255]^this.roundkey[b+2],h=zi[i>>>24]^Ni[n>>>16&255]^Vi[t>>>8&255]^Hi[e&255]^this.roundkey[b+3],e=l,t=u,n=d,i=h}let f=ft[e>>>24&255]&4278190080^ft[i>>>16&255]&16711680^ft[n>>>8&255]&65280^ft[t>>>0&255]&255^this.roundkey[40],p=ft[t>>>24&255]&4278190080^ft[e>>>16&255]&16711680^ft[i>>>8&255]&65280^ft[n>>>0&255]&255^this.roundkey[41],m=ft[n>>>24&255]&4278190080^ft[t>>>16&255]&16711680^ft[e>>>8&255]&65280^ft[i>>>0&255]&255^this.roundkey[42],g=ft[i>>>24&255]&4278190080^ft[n>>>16&255]&16711680^ft[t>>>8&255]&65280^ft[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,g^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}},Op=(r,e,t)=>{let n=!1,i=0,s=2**16,a=16,o=new Zs;return new ReadableStream({pull:async c=>{n||(o.init(await e()),n=!0);let l=s+a,u=r.requestSliceRange(i,0,l);if(u instanceof Promise&&(u=await u),!u||u.length===0)throw new Error("Invalid ciphertext.");let d=u.length;if(d%16!==0)throw new Error("Invalid ciphertext.");let h=d===l?d-a:d,f=ie(u,h),p=new Uint8Array(h);for(let m=0;m<h;m+=16)o.in.set(f.subarray(m,m+16)),o.decrypt(),p.set(o.out,m);if(h<d)c.enqueue(p),i+=h;else{let m=p[h-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let g=p.subarray(0,h-m);c.enqueue(g),c.close(),t()}},cancel:()=>{t()}})};var ac=class r extends ct{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.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(n=>n.getDecoderConfig().then(i=>i?.codec??null)));return tc({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(n=>n.info?.type==="video"),hasAudio:this.tracks.some(n=>n.info?.type==="audio"),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1;for(;;){let n=this.reader.requestSliceRange(e,$t,Rr);if(n instanceof Promise&&(n=await n),!n)break;let i=e,s=Br(n);if(!s)break;if(s.name==="ftyp"||s.name==="styp"){let a=We(n,4);this.isQuickTime=a==="qt "}else if(s.name==="moov"){let a=this.reader.requestSlice(n.filePos,s.contentSize);if(a instanceof Promise&&(a=await a),!a)break;this.moovSlice=a,this.readContiguousBoxes(this.moovSlice);for(let o of this.tracks){let c=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(c*o.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+s.totalSize;break}else if(s.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');let a=await this.input._initInput._getDemuxer();if(a.constructor!==r)throw new Error("Init input must match the input's format.");await a.readMetadata(),this.movieTimescale=a.movieTimescale,this.movieDurationInTimescale=a.movieDurationInTimescale,this.metadataTags=a.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=a.fragmentTrackDefaults,this.psshBoxes=a.psshBoxes;for(let o of a.tracks){let c={id:o.id,demuxer:this,trackBacking:null,disposition:o.disposition,timescale:o.timescale,durationInMediaTimescale:o.durationInMediaTimescale,durationInMovieTimescale:o.durationInMovieTimescale,rotation:o.rotation,internalCodecId:o.internalCodecId,name:o.name,languageCode:o.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:o.editListPreviousSegmentDurations,editListOffset:o.editListOffset,encryptionInfo:o.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:o.info};if(o.trackBacking){if(w(c.info),c.info.type==="video"&&c.info.width!==-1){let l=c;c.trackBacking=new cc(l),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){let l=c;c.trackBacking=new lc(l),this.tracks.push(c)}}}t=!1;break}e=i+s.totalSize}if(t){w(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);n instanceof Promise&&(n=await n),w(n);let i=K(n),s=this.reader.fileSize-i;if(s>=0&&s<=this.reader.fileSize-Rr){let a=this.reader.requestSliceRange(s,$t,Rr);if(a instanceof Promise&&(a=await a),a){let o=Br(a);if(o&&o.name==="mfra"){let c=this.reader.requestSlice(a.filePos,o.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;w(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&&ht.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){w(e.info?.type==="audio");let s=Ht(e.info.codec),a=[],o=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],d=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let h=0;h<d;h++){let f=l.startSampleIndex+h*l.samplesPerChunk,p=f+l.samplesPerChunk,m=_e(t.sampleTimingEntries,f,P=>P.startIndex),g=t.sampleTimingEntries[m],y=_e(t.sampleTimingEntries,p,P=>P.startIndex),b=t.sampleTimingEntries[y],k=g.startDecodeTimestamp+(f-g.startIndex)*g.delta,S=b.startDecodeTimestamp+(p-b.startIndex)*b.delta-k,_=Ne(a);_&&_.delta===S?_.count++:a.push({startIndex:l.startChunkIndex+h,startDecodeTimestamp:k,count:1,delta:S});let M=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(M)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let s of t.sampleTimingEntries)for(let a=0;a<s.count;a++)t.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(let s of t.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){let o=s.startIndex+a,c=t.presentationTimestamps[o];c&&(c.presentationTimestamp+=s.offset)}t.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let s=0;s<t.presentationTimestamps.length;s++)t.presentationTimestampIndexMap[t.presentationTimestamps[s].sampleIndex]=s}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,$t,Rr);t instanceof Promise&&(t=await t),w(t);let n=Br(t);w(n?.name==="moof");let i=this.reader.requestSlice(e,n.totalSize);i instanceof Promise&&(i=await i),w(i),this.traverseBox(i);let s=this.lastReadFragment;w(s&&s.moofOffset===e);for(let[,a]of s.trackData){let o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){let u=o.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(u)Iu(a,u.timestamp);else{let d=_e(c,s.moofOffset-1,h=>h.moofOffset);if(d!==-1){let h=c[d];Iu(a,h.endTimestamp)}}a.startTimestampIsFinal=!0}let l=_e(c,a.startTimestamp,u=>u.startTimestamp);if((l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){let u=await Np(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let d=0;d<Math.min(a.samples.length,u.length);d++){let h=u[d];a.samples[d].encryption=h}}}return s}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-$t&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-$t;){let n=e.filePos,i=Br(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=n+i.totalSize}}traverseBox(e){let t=e.filePos,n=Br(e);if(!n)return!1;let i=e.filePos,s=t+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mvhd":{let a=ce(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=K(e),this.movieDurationInTimescale=Pt(e)):(e.skip(8),this.movieTimescale=K(e),this.movieDurationInTimescale=K(e))}break;case"trak":{let a={id:-1,demuxer:this,trackBacking:null,disposition:{...dt,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Ge,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(i,n.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){let o=a;a.trackBacking=new cc(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let o=a;a.trackBacking=new lc(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{let a=this.currentTrack;if(!a)break;let o=ce(e),l=!!(Yt(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=K(e),e.skip(4),a.durationInMovieTimescale=K(e);else if(o===1)e.skip(16),a.id=K(e),e.skip(4),a.durationInMovieTimescale=Pt(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);let u=[hn(e),hn(e),ic(e),hn(e),hn(e),ic(e),hn(e),hn(e),ic(e)],d=Ai(Us(YS(u),90));w(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{let a=this.currentTrack;if(!a)break;let o=ce(e);e.skip(3);let c=!1,l=0,u=K(e);for(let d=0;d<u;d++){let h=o===1?Pt(e):K(e),f=o===1?Hp(e):Dr(e),p=hn(e);if(h!==0){if(c){we._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=h;continue}if(p!==1){we._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=l,a.editListOffset=f,c=!0}}}break;case"mdhd":{let a=this.currentTrack;if(!a)break;let o=ce(e);e.skip(3),o===0?(e.skip(8),a.timescale=K(e),a.durationInMediaTimescale=K(e)):o===1&&(e.skip(16),a.timescale=K(e),a.durationInMediaTimescale=Pt(e));let c=Ke(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;Pi(a.languageCode)||(a.languageCode=Ge)}}break;case"hdlr":{let a=this.currentTrack;if(!a)break;e.skip(8);let o=We(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{let a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(i,n.contentSize))}break;case"stsd":{let a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;let o=ce(e);e.skip(3);let c=K(e);for(let l=0;l<c;l++){let u=e.filePos,d=Br(e);if(!d)break;a.internalCodecId=d.name;let h=d.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=Ke(e),a.info.height=Ke(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));let f=h==="encv"?a.frmaCodecString:h;a.frmaCodecString=null,f==="avc1"||f==="avc3"?(a.info.codec="avc",a.info.avcType=f==="avc1"?1:3):f==="hvc1"||f==="hev1"?a.info.codec="hevc":f==="vp08"?a.info.codec="vp8":f==="vp09"?a.info.codec="vp9":f==="av01"?a.info.codec="av1":f===null?we._warn("Unknown encrypted video codec due to missing frma box."):we._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{e.skip(8);let f=Ke(e);e.skip(6);let p=Ke(e),m=Ke(e);e.skip(4);let g=K(e)/65536,y=null;o===0&&f>0&&(f===1?(e.skip(4),m=8*K(e),e.skip(8)):f===2&&(e.skip(4),g=uc(e),p=K(e),e.skip(4),m=K(e),y=K(e),e.skip(8))),a.info.numberOfChannels=p,a.info.sampleRate=g,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));let b=h==="enca"?a.frmaCodecString:h;if(a.frmaCodecString=null,b!=="mp4a")if(b==="opus")a.info.codec="opus",a.info.sampleRate=On;else if(b==="flac")a.info.codec="flac";else if(b==="ulaw")a.info.codec="ulaw";else if(b==="alaw")a.info.codec="alaw";else if(b==="ac-3")a.info.codec="ac3";else if(b==="ec-3")a.info.codec="eac3";else if(b==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(we._warn(`Unsupported sample size ${m} for codec 'twos'.`),a.info.codec=null);else if(b==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(we._warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(b==="raw ")a.info.codec="pcm-u8";else if(b==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(b==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(b==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(b==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(b==="ipcm"){let k=a.info.pcmSampleSize;a.info.pcmLittleEndian?k===16?a.info.codec="pcm-s16":k===24?a.info.codec="pcm-s24":k===32?a.info.codec="pcm-s32":(we._warn(`Invalid ipcm sample size ${k}.`),a.info.codec=null):k===16?a.info.codec="pcm-s16be":k===24?a.info.codec="pcm-s24be":k===32?a.info.codec="pcm-s32be":(we._warn(`Invalid ipcm sample size ${k}.`),a.info.codec=null)}else if(b==="fpcm"){let k=a.info.pcmSampleSize;a.info.pcmLittleEndian?k===32?a.info.codec="pcm-f32":k===64?a.info.codec="pcm-f64":(we._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null):k===32?a.info.codec="pcm-f32be":k===64?a.info.codec="pcm-f64be":(we._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null)}else if(b==="lpcm"&&y!==null){let k=m+7>>3,T=!!(y&1),S=!!(y&2),_=y&4?-1:0;m>0&&m<=64&&(T?m===32&&(a.info.codec=S?"pcm-f32be":"pcm-f32"):_&1<<k-1?k===1?a.info.codec="pcm-s8":k===2?a.info.codec=S?"pcm-s16be":"pcm-s16":k===3?a.info.codec=S?"pcm-s24be":"pcm-s24":k===4&&(a.info.codec=S?"pcm-s32be":"pcm-s32"):k===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&we._warn("Unsupported PCM format.")}else b===null?we._warn("Unknown encrypted audio codec due to missing frma box."):we._warn(`Unsupported audio codec (sample entry type '${d.name}').`)}e.filePos=u+d.totalSize}}break;case"frma":{let a=this.currentTrack;if(!a)break;let c=We(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{let a=this.currentTrack;if(!a)break;e.skip(4);let o=We(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:we._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;let o=ce(e);e.skip(3),e.skip(1);let c=ce(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=ce(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=ce(e),a.encryptionInfo.defaultKid=nn(ie(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){let l=ce(e),u=new Uint8Array(16);u.set(ie(e,l),0),a.encryptionInfo.defaultConstantIv=u}}break;case"avcC":{let a=this.currentTrack;if(!a)break;w(a.info),a.info.codecDescription=ie(e,n.contentSize)}break;case"hvcC":{let a=this.currentTrack;if(!a)break;w(a.info),a.info.codecDescription=ie(e,n.contentSize)}break;case"vpcC":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video"),e.skip(4);let o=ce(e),c=ce(e),l=ce(e),u=l>>4,d=l>>1&7,h=l&1,f=ce(e),p=ce(e),m=ce(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:m}}break;case"av1C":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video"),e.skip(1);let o=ce(e),c=o>>5,l=o&31,u=ce(e),d=u>>7,h=u>>6&1,f=u>>5&1,p=u>>4&1,m=u>>3&1,g=u>>2&1,y=u&3,b=c===2&&h?f?12:10:h?10:8;a.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:b,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:g,chromaSamplePosition:y}}break;case"colr":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video");let o=We(e,4);if(o!=="nclx"&&o!=="nclc")break;let c=Ke(e),l=Ke(e),u=Ke(e),d;o==="nclx"&&(d=!!(ce(e)&128)),a.info.colorSpace={primaries:En[c],transfer:In[l],matrix:Mn[u],fullRange:d}}break;case"pasp":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video");let o=K(e),c=K(e);o>0&&c>0&&(o>c?a.info.squarePixelWidth=Math.round(a.info.width*o/c):a.info.squarePixelHeight=Math.round(a.info.height*c/o))}break;case"wave":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"esds":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(4);let o=ce(e);w(o===3),sc(e),e.skip(2);let c=ce(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){let g=ce(e);e.skip(g)}d&&e.skip(2);let h=ce(e);w(h===4);let f=sc(e),p=e.filePos,m=ce(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":we._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),f>e.filePos-p){let g=ce(e);w(g===5);let y=sc(e);if(a.info.codecDescription=ie(e,y),a.info.codec==="aac"){let b=Fi(a.info.codecDescription);b.numberOfChannels!==null&&(a.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(a.info.sampleRate=b.sampleRate)}}}break;case"enda":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(Ke(e)&255)}break;case"pcmC":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(4);let o=ce(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=ce(e)}break;case"dOps":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(1);let o=ce(e),c=Ke(e),l=K(e),u=Js(e),d=ce(e),h;d!==0?h=ie(e,2+o):h=new Uint8Array(0);let f=new Uint8Array(19+h.byteLength),p=new DataView(f.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,u,!0),p.setUint8(18,d),f.set(h,19),a.info.codecDescription=f,a.info.numberOfChannels=o}break;case"dfLa":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(4);let o=127,c=128,l=e.filePos;for(;e.filePos<s;){let p=ce(e),m=Yt(e);if((p&o)===un.STREAMINFO){e.skip(10);let y=K(e),b=y>>>12,k=(y>>9&7)+1;a.info.sampleRate=b,a.info.numberOfChannels=k,e.skip(20)}else e.skip(m);if(p&c)break}let u=e.filePos;e.filePos=l;let d=ie(e,u-l),h=new Uint8Array(4+d.byteLength);new DataView(h.buffer).setUint32(0,1716281667,!1),h.set(d,4),a.info.codecDescription=h}break;case"dac3":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio");let o=ie(e,3),c=new Ie(o),l=c.readBits(2);c.skipBits(8);let u=c.readBits(3),d=c.readBits(1);l<3&&(a.info.sampleRate=Ln[l]),a.info.numberOfChannels=Ys[u]+d}break;case"dec3":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio");let o=ie(e,n.contentSize),c=Fp(o);if(!c){we._warn("Invalid dec3 box contents, ignoring.");break}let l=Jo(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=ec(c)}break;case"stts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e),c=0,l=0;for(let u=0;u<o;u++){let d=K(e),h=K(e);a.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:d,delta:h}),c+=d,l+=d*h}}break;case"ctts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e),c=0;for(let l=0;l<o;l++){let u=K(e),d=Dr(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e),c=K(e);if(o===0)for(let l=0;l<c;l++){let u=K(e);a.sampleTable.sampleSizes.push(u)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);let o=ce(e),c=K(e),l=ie(e,Math.ceil(c*o/8)),u=new Ie(l);for(let d=0;d<c;d++){let h=u.readBits(o);a.sampleTable.sampleSizes.push(h)}}break;case"stss":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];let o=K(e);for(let c=0;c<o;c++){let l=K(e)-1;a.sampleTable.keySampleIndices.push(l)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e);for(let l=0;l<o;l++){let u=K(e)-1,d=K(e),h=K(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:h})}let c=0;for(let l=0;l<a.sampleTable.sampleToChunk.length;l++)if(a.sampleTable.sampleToChunk[l].startSampleIndex=c,l<a.sampleTable.sampleToChunk.length-1){let d=a.sampleTable.sampleToChunk[l+1].startChunkIndex-a.sampleTable.sampleToChunk[l].startChunkIndex;c+=d*a.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e);for(let c=0;c<o;c++){let l=K(e);a.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e);for(let c=0;c<o;c++){let l=Pt(e);a.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mehd":{let a=ce(e);e.skip(3);let o=a===1?Pt(e):K(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);let a=K(e),o=K(e),c=K(e),l=K(e),u=K(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{let a=ce(e);e.skip(3);let o=K(e),c=this.tracks.find(b=>b.id===o);if(!c)break;let l=K(e),u=(l&48)>>4,d=(l&12)>>2,h=l&3,f=[ce,Ke,Yt,K],p=f[u],m=f[d],g=f[h],y=K(e);for(let b=0;b<y;b++){let k=a===1?Pt(e):K(e),T=a===1?Pt(e):K(e);p(e),m(e),g(e),c.fragmentLookupTable.push({timestamp:k,moofOffset:T})}c.fragmentLookupTable.sort((b,k)=>b.timestamp-k.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){let k=c.fragmentLookupTable[b],T=c.fragmentLookupTable[b+1];k.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(i,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(w(this.currentFragment),this.readContiguousBoxes(e.slice(i,n.contentSize)),this.currentTrack){let a=this.currentFragment.trackData.get(this.currentTrack.id);e:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}a.presentationTimestamps=a.samples.map((u,d)=>({presentationTimestamp:u.presentationTimestamp,sampleIndex:d})).sort((u,d)=>u.presentationTimestamp-d.presentationTimestamp);for(let u=0;u<a.presentationTimestamps.length;u++){let d=a.presentationTimestamps[u],h=a.samples[d.sampleIndex];if(a.firstKeyFrameTimestamp===null&&h.isKeyFrame&&(a.firstKeyFrameTimestamp=h.presentationTimestamp),u<a.presentationTimestamps.length-1){let p=a.presentationTimestamps[u+1].presentationTimestamp-d.presentationTimestamp;h.duration=p}}let o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[Ne(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;let{currentFragmentState:l}=this.currentTrack;w(l),l.startTimestamp!==null&&(Iu(a,l.startTimestamp),a.startTimestampIsFinal=!0),l.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=l.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let a=rc(ie(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{w(this.currentFragment),e.skip(1);let a=Yt(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),u=!!(a&16),d=!!(a&32),h=!!(a&65536),f=!!(a&131072),p=K(e),m=this.tracks.find(y=>y.id===p);if(!m)break;let g=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:g?.defaultSampleDescriptionIndex??null,defaultSampleDuration:g?.defaultSampleDuration??null,defaultSampleSize:g?.defaultSampleSize??null,defaultSampleFlags:g?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=Pt(e):f&&(m.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(m.currentFragmentState.sampleDescriptionIndex=K(e)),l&&(m.currentFragmentState.defaultSampleDuration=K(e)),u&&(m.currentFragmentState.defaultSampleSize=K(e)),d&&(m.currentFragmentState.defaultSampleFlags=K(e)),h&&(m.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let a=this.currentTrack;if(!a)break;w(a.currentFragmentState);let o=ce(e);e.skip(3);let c=o===0?K(e):Pt(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{let a=this.currentTrack;if(!a)break;w(this.currentFragment),w(a.currentFragmentState);let o=ce(e),c=Yt(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),h=!!(c&512),f=!!(c&1024),p=!!(c&2048),m=K(e),g=null;l&&(g=Dr(e));let y=null;u&&(y=K(e));let b;this.currentFragment.trackData.has(a.id)?(b=this.currentFragment.trackData.get(a.id),g!==null&&(b.currentOffset=a.currentFragmentState.baseDataOffset+g)):(b={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(g??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,b));for(let k=0;k<m;k++){let T;d?T=K(e):(w(a.currentFragmentState.defaultSampleDuration!==null),T=a.currentFragmentState.defaultSampleDuration);let S;h?S=K(e):(w(a.currentFragmentState.defaultSampleSize!==null),S=a.currentFragmentState.defaultSampleSize);let _;f?_=K(e):(w(a.currentFragmentState.defaultSampleFlags!==null),_=a.currentFragmentState.defaultSampleFlags),k===0&&y!==null&&(_=y);let M=0;p&&(o===0?M=K(e):M=Dr(e));let P=!(_&65536);b.samples.push({presentationTimestamp:b.currentTimestamp+M,duration:T,byteOffset:b.currentOffset,byteSize:S,isKeyFrame:P,encryption:null}),b.currentOffset+=S,b.currentTimestamp+=T}this.currentFragment.implicitBaseDataOffset=b.currentOffset}break;case"saiz":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),Yt(e)&1){let h=We(e,4),f=K(e);if(h!==a.encryptionInfo.scheme||f!==0)break}let c=ce(e),l=K(e),u=null;c===0&&l>0&&(u=ie(e,l));let d=Up(a);d.defaultSampleInfoSize=c,d.sampleSizes=u,d.sampleCount=l}break;case"saio":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;let o=ce(e);if(Yt(e)&1){let h=We(e,4),f=K(e);if(h!==a.encryptionInfo.scheme||f!==0)break}let l=K(e);if(l===0)break;l>1&&we._warn("Multiple saio entries are not supported; using the first offset only.");let u=o===0?K(e):Number(Pt(e));this.currentFragment&&(u+=this.currentFragment.moofOffset);let d=Up(a);d.offset=u}break;case"senc":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;w(this.currentFragment);let o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);let l=!!(Yt(e)&2),u=K(e),d=a.encryptionInfo.defaultPerSampleIvSize;w(d!==null);for(let h=0;h<Math.min(u,o.samples.length);h++){let f=new Uint8Array(16);d>0?f.set(ie(e,d),0):f.set(a.encryptionInfo.defaultConstantIv,0);let p=null;if(l){let g=Ke(e);p=[];for(let y=0;y<g;y++){let b=Ke(e),k=K(e);p.push({clearLen:b,protectedLen:k})}}let m=o.samples[h];m.encryption={iv:f,subsamples:p}}}break;case"udta":{let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},o.name[0]==="\xA9"?this.metadataTags.raw[o.name]??=Xt(c):this.metadataTags.raw[o.name]??=ie(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=ot.decode(ie(c,o.contentSize)):this.metadataTags.title??=Xt(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Xt(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Xt(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Xt(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Xt(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Xt(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(Xt(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Xt(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Xt(c));break}}}break;case"meta":{if(this.currentTrack)break;let o=K(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(i,n.contentSize)):this.readContiguousBoxes(e.slice(i+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let a=K(e);for(let o=0;o<a;o++){let c=K(e);e.skip(4);let l=ot.decode(ie(e,c-8));this.currentMetadataKeys.set(o+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:o,slice:c}of a){let l=o.name,u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));let d=Rp(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=d,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Kt?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let h=d.split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let h=ve(d),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let h=ve(d),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}},oc=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let i of e.tracks)if(i.trackBacking.getType()===t&&n++,i===this.internalTrack)break;return n}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}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(w(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ir(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Mu(i,n),a=await this.fetchPacketForSampleIndex(s,t);return!Lp(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=_e(c.presentationTimestamps,n,h=>h.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let a=s.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<a.samples.length)return{sampleIndex:i.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,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=$S(i,n),a=await this.fetchPacketForSampleIndex(s,t);return!Lp(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=Ci(c.presentationTimestamps,h=>c.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=n),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=QS(s,n);return this.fetchPacketForSampleIndex(a,t)}let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>i.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{let a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let o=a.samples.findIndex(c=>c.isKeyFrame);return w(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=XS(n,e);if(!i)return null;let s;if(t.metadataOnly)s=st;else{let l=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(l instanceof Promise&&(l=await l),!l)return null;if(s=ie(l,i.sampleSize),this.internalTrack.encryptionAuxInfo){w(this.internalTrack.encryptionInfo);let u=await Np(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<u.length&&(s=await zp(this.internalTrack,u[e],s,null))}}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,c=new Oe(s,i.isKeyFrame?"key":"delta",a,o,e,i.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[t];w(s);let a;if(n.metadataOnly)a=st;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(u instanceof Promise&&(u=await u),!u)return null;a=ie(u,s.byteSize),s.encryption&&(a=await zp(this.internalTrack,s.encryption,a,e))}let o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new Oe(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,n,i,s){let a=this.internalTrack.demuxer,o=null,c=null,l=-1;if(e){let{sampleIndex:g,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,g,s);g!==-1&&(c=e,l=g)}let u=_e(this.internalTrack.fragmentLookupTable,n,g=>g.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,h=_e(this.internalTrack.fragmentPositionCache,n,g=>g.startTimestamp),f=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,p=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let k=o.trackData.get(this.internalTrack.id);if(k&&k.startTimestamp>i)break}let g=a.reader.requestSliceRange(m,$t,Rr);if(g instanceof Promise&&(g=await g),!g)break;let y=m,b=Br(g);if(!b)break;if(b.name==="moof"){o=await a.readFragment(y);let{sampleIndex:k,correctSampleFound:T}=t(o);if(T)return this.fetchPacketInFragment(o,k,s);k!==-1&&(c=o,l=k)}m=y+b.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let g=this.internalTrack.fragmentLookupTable[u-1];w(!g||g.timestamp<d.timestamp);let y=g?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,i,s)}return c?this.fetchPacketInFragment(c,l,s):null}},cc=class extends oc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}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 t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&$o(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Xo(t.data)}let e={codec:Ri(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};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},lc=class extends oc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}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:Bi(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Mu=(r,e)=>{if(r.presentationTimestamps){let t=_e(r.presentationTimestamps,e,n=>n.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{let t=_e(r.sampleTimingEntries,e,i=>i.startDecodeTimestamp);if(t===-1)return-1;let n=r.sampleTimingEntries[t];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},$S=(r,e)=>{if(!r.keySampleIndices)return Mu(r,e);if(r.presentationTimestamps){let t=_e(r.presentationTimestamps,e,n=>n.presentationTimestamp);if(t===-1)return-1;for(let n=t;n>=0;n--){let i=r.presentationTimestamps[n].sampleIndex;if(Er(r.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{let t=Mu(r,e),n=_e(r.keySampleIndices,t,i=>i);return r.keySampleIndices[n]??-1}},XS=(r,e)=>{let t=_e(r.sampleTimingEntries,e,y=>y.startIndex),n=r.sampleTimingEntries[t];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,a=_e(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);let c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=_e(r.sampleToChunk,e,y=>y.startSampleIndex),u=r.sampleToChunk[l];w(u);let d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),h=r.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,p=0,m=h;if(r.sampleSizes.length===1)m+=c*(e-f),p+=c*u.samplesPerChunk;else for(let y=f;y<f+u.samplesPerChunk;y++){let b=r.sampleSizes[y];y<e&&(m+=b),p+=b}let g=n.delta;if(r.presentationTimestamps){let y=r.presentationTimestampIndexMap[e];w(y!==void 0),y<r.presentationTimestamps.length-1&&(g=r.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:m,sampleSize:c,chunkOffset:h,chunkSize:p,isKeyFrame:r.keySampleIndices?Er(r.keySampleIndices,e,y=>y)!==-1:!0}},QS=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=_e(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},Iu=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(let t of r.samples)t.presentationTimestamp+=e;for(let t of r.presentationTimestamps)t.presentationTimestamp+=e},YS=r=>{let[e,t]=r,n=Math.atan2(t,e);return Number.isFinite(n)?n*(180/Math.PI):0},Lp=r=>r.sampleSizes.length===0,Up=r=>r.currentFragmentState?r.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:r.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Np=async(r,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let n=0;if(t.defaultSampleInfoSize>0)n=t.defaultSampleInfoSize*t.sampleCount;else{w(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)n+=t.sampleSizes[o]}let i=r.requestSlice(t.offset,n);if(i instanceof Promise&&(i=await i),!i)throw new Error("Failed to read auxiliary encryption info.");let s=e.defaultPerSampleIvSize;w(s!==null);let a=[];for(let o=0;o<t.sampleCount;o++){let c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],l=new Uint8Array(16);s>0?l.set(ie(i,s),0):l.set(e.defaultConstantIv,0);let u=null;if(c>s){let d=Ke(i);u=[];for(let h=0;h<d;h++){let f=Ke(i),p=K(i);u.push({clearLen:f,protectedLen:p})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},zp=async(r,e,t,n)=>{w(r.encryptionInfo);let i=r.encryptionInfo;w(i.defaultKid!==null);let s=i.defaultKid,a,o=r.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!r.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let c=(async()=>{let l=r.demuxer.psshBoxes;if(n){l=[...l,...n.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(s));for(let d=0;d<l.length-1;d++)for(let h=d+1;h<l.length;h++)nc(l[d],l[h])&&(l.splice(h,1),h--)}let u=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:l});if(!(typeof u=="string"&&u.length===32&&Wm.test(u)||u instanceof Uint8Array&&u.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return u instanceof Uint8Array?u:qm(u)})();r.demuxer.decryptionKeyCache.set(s,c),a=await c}return i.scheme==="cenc"||i.scheme==="cens"?ZS(a,i,e,t):JS(a,i,e,t)},ZS=async(r,e,t,n)=>{let i=new Uint8Array(16);i.set(t.iv,0);let s=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{let m=await crypto.subtle.decrypt({name:"AES-CTR",counter:i,length:64},s,p);return new Uint8Array(m)};if(!t.subsamples)return a(n);w(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);let o=Vp(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock),c=0;for(let p of o)for(let m of p.perSubsample)c+=m.length;let l=new Uint8Array(c),u=0;for(let p of o)for(let m of p.perSubsample)l.set(n.subarray(m.offset,m.offset+m.length),u),u+=m.length;let d=await a(l),h=new Uint8Array(n),f=0;for(let p of o)for(let m of p.perSubsample)h.set(d.subarray(f,f+m.length),m.offset),f+=m.length;return h},JS=(r,e,t,n)=>{let i=new Zs;i.init({key:r,iv:t.iv});let s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(w(s!==null&&a!==null),!t.subsamples){let u=new Uint8Array(n),d=Math.floor(n.length/16);for(let h=0;h<d;h++){let f=h*16;i.in.set(n.subarray(f,f+16)),i.decrypt(),u.set(i.out,f)}return u}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");let o=new Uint8Array(n),c=Vp(t.subsamples,s,a),l=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(let u of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(let d of u.perSubsample){let h=d.length/16;for(let f=0;f<h;f++){let p=d.offset+f*16;i.in.set(n.subarray(p,p+16)),i.decrypt(),o.set(i.out,p)}}}return o},Vp=(r,e,t)=>{let n=[],i=e!==0||t!==0,s=0;for(let a of r){s+=a.clearLen;let o=[];if(!i)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let c=a.protectedLen,l=s;for(;c>0&&!(c<16*e);){let u=16*e;o.push({offset:l,length:u}),l+=u,c-=u;let d=Math.min(16*t,c);l+=d,c-=d}s+=a.protectedLen}n.push({perSubsample:o})}return n};var z;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(z||(z={}));var eT=[z.EBML,z.Segment],Wi=[z.SeekHead,z.Info,z.Cluster,z.Tracks,z.Cues,z.Attachments,z.Chapters,z.Tags],ea=[...eT,...Wi];var Fu=8,Et=2,Zt=2*Fu,Ru=r=>{if(r.remainingLength<1)return null;let e=ce(r);if(r.skip(-1),e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;return r.remainingLength<t?null:t},qi=r=>{if(r.remainingLength<1)return null;let e=ce(r);if(e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;if(r.remainingLength<t-1)return null;let i=e&n-1;for(let s=1;s<t;s++)i*=256,i+=ce(r);return i},Ce=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let n=0;n<e;n++)t*=256,t+=ce(r);return t},Wp=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let n=0;n<e;n++)t<<=8n,t+=BigInt(ce(r));return t};var dc=r=>{let e=Ru(r);return e===null||r.remainingLength<e?null:Ce(r,e)},Bu=r=>{if(r.remainingLength<1)return null;if(ce(r)===255)return;r.skip(-1);let t=qi(r);if(t===null)return null;if(t!==72057594037927940)return t},Jt=r=>{w(r.remainingLength>=Et);let e=dc(r);if(e===null)return null;let t=Bu(r);return t===null?null:{id:e,size:t}},fn=(r,e)=>{let t=ie(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return String.fromCharCode(...t.subarray(0,n))},ji=(r,e)=>{let t=ie(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return ot.decode(t.subarray(0,n))},hc=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?qp(r):uc(r)},fc=async(r,e,t,n)=>{let i=new Set(t),s=e;for(;n===null||s<n;){let a=r.requestSliceRange(s,Et,Zt);if(a instanceof Promise&&(a=await a),!a)break;let o=Jt(a);if(!o)break;if(i.has(o.id))return{pos:s,found:!0};Lr(o.size),s=a.filePos+o.size}return{pos:n!==null&&n>s?n:s,found:!1}},Du=async(r,e,t,n)=>{let s=new Set(t),a=e;for(;a<n;){let o=r.requestSliceRange(a,0,Math.min(65536,n-a));if(o instanceof Promise&&(o=await o),!o||o.length<Fu)break;for(let c=0;c<o.length-Fu;c++){o.filePos=a;let l=dc(o);if(l!==null&&s.has(l))return a;a++}}return null},Bt={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",ac3:"A_AC3",eac3:"A_EAC3","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 Lr(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var jp=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(", ")}"`}return t};var Ur;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Ur||(Ur={}));var mc;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(mc||(mc={}));var ta;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(ta||(ta={}));var Ou=[{id:z.SeekHead,flag:"seekHeadSeen"},{id:z.Info,flag:"infoSeen"},{id:z.Tracks,flag:"tracksSeen"},{id:z.Cues,flag:"cuesSeen"}],Gp=10*2**20,pc=class extends ct{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 getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(n=>n.getDecoderConfig().then(i=>i?.codec??null)));return jp({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Et,Zt);if(t instanceof Promise&&(t=await t),!t)break;let n=Jt(t);if(!n)break;let i=n.id,s=n.size,a=t.filePos;if(i===z.EBML){Lr(s);let o=this.reader.requestSlice(a,s);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(i===z.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(i===z.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await fc(this.reader,a,ea,this.reader.fileSize)).pos-a);let o=Ne(this.segments);o&&(o.elementEndPos=a+s)}Lr(s),e=a+s}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(n,Et,Zt);if(o instanceof Promise&&(o=await o),!o)break;let c=n,l=Jt(o);if(!l||!Wi.includes(l.id)&&l.id!==z.Void){let p=await Du(this.reader,c,Wi,Math.min(this.currentSegment.elementEndPos??1/0,c+Gp));if(p){n=p;continue}else break}let{id:u,size:d}=l,h=o.filePos,f=Ou.findIndex(p=>p.id===u);if(f!==-1){let p=Ou[f].flag;this.currentSegment[p]=!0,Lr(d);let m=this.reader.requestSlice(h,d);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}else if(u===z.Tags||u===z.Attachments){u===z.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Lr(d);let p=this.reader.requestSlice(h,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===z.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;n=h+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let o of this.currentSegment.seekEntries){let c=Ou.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,Et,Zt);if(l instanceof Promise&&(l=await l),!l)continue;let u=Jt(l);if(!u)continue;let{id:d,size:h}=u;if(d!==c.id)continue;Lr(h),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,h);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);let i=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(let o of this.currentSegment.cuePoints){let c=i.get(o.trackId);c&&c.cuePoints.push(o)}for(let o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){let l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,a=-1/0;for(let o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(let o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,Et,Zt);n instanceof Promise&&(n=await n),w(n);let i=e,s=Jt(n);w(s);let a=s.id;w(a===z.Cluster);let o=s.size,c=n.filePos;o===void 0&&(o=(await fc(this.reader,c,ea,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);let u={segment:t,elementStartPos:i,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){let d=this.readContiguousElements(l,ea);u.elementEndPos=d}for(let[,d]of u.trackData){let h=d.track;w(d.blocks.length>0);let f=!1;for(let y=0;y<d.blocks.length;y++){let b=d.blocks[y];b.timestamp+=u.timestamp,f||=b.lacing!==Ur.None}d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){let b=d.presentationTimestamps[y],k=d.blocks[b.blockIndex];if(d.firstKeyFrameTimestamp===null&&k.isKeyFrame&&(d.firstKeyFrameTimestamp=k.timestamp),y<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[y+1];k.duration=T.timestamp-k.timestamp}else k.duration===0&&h.defaultDuration!=null&&k.lacing===Ur.None&&(k.duration=h.defaultDuration)}f&&(this.expandLacedBlocks(d.blocks,h),d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));let p=d.blocks[d.presentationTimestamps[0].blockIndex],m=d.blocks[Ne(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=m.timestamp+m.duration;let g=_e(h.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(g===-1||h.clusterPositionCache[g].elementStartPos!==i)&&h.clusterPositionCache.splice(g+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let i=e.segment.tracks.find(s=>s.id===t);if(!i)return null;n={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let i=e[n];if(i.lacing===Ur.None)continue;i.decoded||(i.data=this.decodeBlockData(t,i.data),i.decoded=!0);let s=yt.tempFromBytes(i.data),a=[],o=ce(s)+1;switch(i.lacing){case Ur.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){let h=ce(s);if(d+=h,h<255){a.push(d),l+=d;break}}}a.push(s.length-(s.bufferPos+l))}break;case Ur.FixedSize:{let l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case Ur.Ebml:{let l=qi(s);w(l!==null);let u=l;a.push(u);let d=u;for(let h=1;h<o-1;h++){let f=s.bufferPos,p=qi(s);w(p!==null);let m=p,y=(1<<(s.bufferPos-f)*7-1)-1,b=m-y;u+=b,a.push(u),d+=u}a.push(s.length-(s.bufferPos+d))}break;default:w(!1)}w(a.length===o),e.splice(n,1);let c=i.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){let u=a[l],d=ie(s,u),h=i.timestamp+c*l/o,f=c/o;e.splice(n+l,0,{timestamp:h,duration:f,isKeyFrame:i.isKeyFrame,data:d,lacing:Ur.None,decoded:!0,mainAdditional:i.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===z.Tags&&!e.tagsSeen)){if(!(t.id===z.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Et,Zt);if(n instanceof Promise&&(n=await n),!n)continue;let i=Jt(n);if(!i||i.id!==t.id)continue;let{size:s}=i;Lr(s),w(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,s);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===z.Tags?e.tagsSeen=!0:t.id===z.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Et;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let n=Jt(e);if(!n||t&&t.includes(n.id))return!1;let{id:i,size:s}=n,a=e.filePos;switch(Lr(s),i){case z.DocType:this.isWebM=fn(e,s)==="webm";break;case z.Seek:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case z.SeekID:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=Ce(e,s)}break;case z.SeekPosition:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=Ce(e,s)}break;case z.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Ce(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case z.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=hc(e,s)}break;case z.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...dt,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==mc.Block||o.data.algorithm!==ta.HeaderStripping)&&(we._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 o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let u=this.currentTrack.info.displayWidth*this.currentTrack.info.height,d=this.currentTrack.info.displayHeight*this.currentTrack.info.width;u>0&&d>0&&(u>d?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*u/d):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*d/u))}this.currentTrack.codecId===Bt.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Bt.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.vp8?this.currentTrack.info.codec="vp8":c===Bt.vp9?this.currentTrack.info.codec="vp9":c===Bt.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack;this.currentTrack.trackBacking=new Lu(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===Bt.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Bt.mp3?this.currentTrack.info.codec="mp3":c===Bt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=On):c===Bt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.eac3?(this.currentTrack.info.codec="eac3",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;this.currentTrack.trackBacking=new Uu(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case z.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=Ce(e,s)}break;case z.TrackType:{if(!this.currentTrack)break;let o=Ce(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case z.FlagEnabled:{if(!this.currentTrack)break;Ce(e,s)||(this.currentTrack=null)}break;case z.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Ce(e,s)}break;case z.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Ce(e,s)}break;case z.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Ce(e,s)}break;case z.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Ce(e,s)}break;case z.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Ce(e,s)}break;case z.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Ce(e,s)}break;case z.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=fn(e,s)}break;case z.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=ie(e,s)}break;case z.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Ce(e,s)}break;case z.Name:{if(!this.currentTrack)break;this.currentTrack.name=ji(e,s)}break;case z.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=fn(e,s),Pi(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Ge)}break;case z.LanguageBCP47:{if(!this.currentTrack)break;let c=fn(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Ge,this.currentTrack.hasLanguageBcp47=!0}break;case z.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case z.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=Ce(e,s)}break;case z.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=Ce(e,s)}break;case z.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=Ce(e,s)}break;case z.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=Ce(e,s)}break;case z.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=Ce(e,s)}break;case z.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=Ce(e,s)===1}break;case z.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,s))}break;case z.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=Mn[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case z.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=Ce(e,s)===2}break;case z.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=In[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case z.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=En[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case z.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case z.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-hc(e,s);try{this.currentTrack.info.rotation=Ai(c)}catch{}}break;case z.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case z.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=hc(e,s)}break;case z.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=Ce(e,s)}break;case z.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=Ce(e,s)}break;case z.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case z.CueTime:this.currentCueTime=Ce(e,s);break;case z.CueTrackPositions:{if(this.currentCueTime===null)break;w(this.currentSegment);let o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case z.CueTrack:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=Ce(e,s)}break;case z.CueClusterPosition:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;w(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+Ce(e,s)}break;case z.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Ce(e,s)}break;case z.SimpleBlock:{if(!this.currentCluster)break;let o=qi(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=Js(e),u=ce(e),d=u>>1&3,h=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(h=!0);let f=ie(e,s-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:h,data:f,lacing:d,decoded:!p,mainAdditional:null})}break;case z.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case z.Block:{if(!this.currentCluster)break;let o=qi(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=Js(e),d=ce(e)>>1&3,h=ie(e,s-(e.filePos-a)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:h,lacing:d,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case z.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case z.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case z.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=ie(e,s)}break;case z.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Ce(e,s)}break;case z.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Ce(e,s)}break;case z.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case z.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case z.Targets:this.readContiguousElements(e.slice(a,s));break;case z.TargetTypeValue:Ce(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case z.TagTrackUID:case z.TagEditionUID:case z.TagChapterUID:case z.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case z.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case z.TagName:this.currentSimpleTagName=ji(e,s);break;case z.TagString:{if(!this.currentSimpleTagName)break;let o=ji(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case z.TagBinary:{if(!this.currentSimpleTagName)break;let o=ie(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case z.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));let o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new qs(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}o.images??=[],o.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 z.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Wp(e,s)}break;case z.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ji(e,s)}break;case z.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=fn(e,s)}break;case z.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=ie(e,s)}break;case z.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ji(e,s)}break;case z.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case z.ContentEncoding:this.currentDecodingInstruction={order:0,scope:mc.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case z.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Ce(e,s)}break;case z.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Ce(e,s)}break;case z.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:ta.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case z.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Ce(e,s)}break;case z.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=ie(e,s)}break;case z.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,t){w(e.decodingInstructions.length>0);let n=t;for(let i of e.decodingInstructions)switch(w(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case ta.HeaderStripping:if(i.data.settings&&i.data.settings.length>0){let s=i.data.settings,a=new Uint8Array(s.length+n.length);a.set(s,0),a.set(n,s.length),n=a}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":n.title??=t;break;case"description":n.description??=t;break;case"artist":n.artist??=t;break;case"album":n.album??=t;break;case"album_artist":n.albumArtist??=t;break;case"genre":n.genre??=t;break;case"comment":n.comment??=t;break;case"lyrics":n.lyrics??=t;break;case"date":{let i=new Date(t);Number.isNaN(i.getTime())||(n.date??=i)}break;case"track_number":case"part_number":{let i=t.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.tracksTotal??=a)}break;case"disc_number":case"disc":{let i=t.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.discsTotal??=a)}break}}},gc=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let i of e.segments)for(let s of i.tracks)if(s.trackBacking.getType()===t&&n++,s===this.internalTrack)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor,n=await this.getFirstPacket({metadataOnly:!0});return t+=n?.timestamp??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Ir(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=_e(s.presentationTimestamps,n,l=>l.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let s=i.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=Ci(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let a=i.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>n.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.blocks.findIndex(o=>o.isKeyFrame);return w(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[t];w(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let a=n.metadataOnly?st:s.data,o=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?st:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);let u=new Oe(a,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,s.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,n,i,s){let{demuxer:a,segment:o}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:y,correctBlockFound:b}=t(e);if(b)return this.fetchPacketInCluster(e,y,s);y!==-1&&(l=e,u=y)}let d=_e(this.internalTrack.cuePoints,n,y=>y.time),h=d!==-1?this.internalTrack.cuePoints[d]:null,f=_e(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,m=Math.max(h?.clusterPosition??0,p?.elementStartPos??0)||null,g;for(e?m===null||e.elementStartPos>=m?(g=e.elementEndPos,c=e):g=m:g=m??o.clusterSeekStartPos;o.elementEndPos===null||g<=o.elementEndPos-Et;){if(c){let P=c.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>i)break}let y=a.reader.requestSliceRange(g,Et,Zt);if(y instanceof Promise&&(y=await y),!y)break;let b=g,k=Jt(y);if(!k||!Wi.includes(k.id)&&k.id!==z.Void){let P=await Du(a.reader,b,Wi,Math.min(o.elementEndPos??1/0,b+Gp));if(P){g=P;continue}else break}let T=k.id,S=k.size,_=y.filePos;if(T===z.Cluster){c=await a.readCluster(b,o),S=c.elementEndPos-_;let{blockIndex:P,correctBlockFound:A}=t(c);if(A)return this.fetchPacketInCluster(c,P,s);P!==-1&&(l=c,u=P)}S===void 0&&(w(T!==z.Cluster),S=(await fc(a.reader,_,ea,o.elementEndPos)).pos-_);let M=_+S;if(o.elementEndPos===null){let P=a.reader.requestSliceRange(M,Et,Zt);if(P instanceof Promise&&(P=await P),!P)break;if(dc(P)===z.Segment){o.elementEndPos=M;break}}g=M}if(h&&(!l||l.elementStartPos<h.clusterPosition)){let y=this.internalTrack.cuePoints[d-1];w(!y||y.time<h.time);let b=y?.time??-1/0;return this.performClusterLookup(null,t,b,i,s)}return l?this.fetchPacketInCluster(l,u,s):null}},Lu=class extends gc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}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;(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({}));let n={codec:Ri({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?Li(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Ui(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?$o(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Xo(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};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}},Uu=class extends gc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}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:Bi({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 ra=async(r,e,t,n=null)=>{let s=e;for(;t===null||s<t;){let a=t!==null?Math.min(65536,t-s):65536,o=r.requestSliceRange(s,4,a);if(o instanceof Promise&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let c=o.filePos,l=K(o),u=r.fileSize!==null?r.fileSize-s:null,d=Ks(l,u);if(d.header&&(!n||d.header.sampleRate===n.sampleRate&&d.header.mpegVersionId===n.mpegVersionId&&d.header.layer===n.layer&&cn(d.header.channel)===cn(n.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};var yc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new At,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.trackBackings=[new zu(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,mt);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}let c=It(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}let e=await ra(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=qo(t.mpegVersionId,t.channel),i=this.reader.requestSlice(e.startPos+n,4);if(i instanceof Promise&&(i=await i),i){let o=K(i);if(o===Ho||o===Wo){if(!this.xingData){let l=this.reader.requestSlice(e.startPos+n+4,12);if(l instanceof Promise&&(l=await l),l){let u=ie(l,12),d=ve(u),h=d.getUint32(0,!1);this.xingData={frameCount:h&Gs.FrameCount?d.getUint32(4,!1):null,fileSize:h&Gs.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,n=!1;for(;;){let i=this.reader.requestSlice(t,mt);if(i instanceof Promise&&(i=await i),!i)break;let s=It(i);if(!s)break;n=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(a instanceof Promise&&(a=await a),!a)break;mn(a,s,this.metadataTags),t=i.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=na){let i=this.reader.requestSlice(this.reader.fileSize-na,na);i instanceof Promise&&(i=await i),w(i),We(i,3)==="TAG"&&Kp(i,this.metadataTags)}return this.metadataTags}finally{e()}}},zu=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(w(e.firstFrameHeader!==null),w(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){let t=gp(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Ge}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return w(this.demuxer.firstFrameHeader),cn(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:cn(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=ie(s,n.dataSize)}return new Oe(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=Er(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Nu=1399285583,tT=79764919,$p=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^tT:e<<1;$p[r]=e>>>0&4294967295}var Xp=r=>{let e=ve(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let i=0;i<r.length;i++){let s=r[i];n=(n<<8^$p[n>>>24^s])>>>0}return e.setUint32(22,t,!0),n},Qp=(r,e,t)=>{let n=0,i=null;if(r.length>0)if(e.codec==="vorbis"){w(e.vorbisInfo);let s=e.vorbisInfo.modeBlockflags.length,o=(1<<Xm(s-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,u=e.vorbisInfo.modeBlockflags[c];if(i=e.vorbisInfo.blocksizes[u],u===1){let d=(o|1)+1,h=r[0]&d?1:0;l=e.vorbisInfo.blocksizes[h]}n=l!==null?l+i>>2:0}else e.codec==="opus"&&(n=Pp(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:i}},Yp=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var pn=27,zn=282,Zp=zn+65025,Gi=r=>{let e=r.filePos;if(Un(r)!==Nu)return null;r.skip(1);let n=ce(r),i=eg(r),s=Un(r),a=Un(r),o=Un(r),c=ce(r),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=ce(r);let u=27+c,d=l.reduce((f,p)=>f+p,0),h=u+d;return{headerStartPos:e,totalSize:h,dataStartPos:e+u,dataSize:d,headerType:n,granulePosition:i,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:l}},Jp=(r,e)=>{for(;r.filePos<e-3;){let t=Un(r),n=t&255,i=t>>>8&255,s=t>>>16&255,a=t>>>24&255,o=79;if(!(n!==o&&i!==o&&s!==o&&a!==o)){if(r.skip(-4),t===Nu)return!0;r.skip(1)}}return!1};var wc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,pn,zn);if(t instanceof Promise&&(t=await t),!t)break;let n=Gi(t);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let t of this.bitstreams){let n=await this.readPacket(t.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,t):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,t),t.codecInfo.codec!==null&&this.trackBackings.push(new Vu(t,this)))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||(n=await this.findNextPacketStart(i),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||i.data[0]!==3||s.data[0]!==5)return;let a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(i.data.length);let c=new Uint8Array(1+a.length+e.data.length+i.data.length+s.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(i.data,1+a.length+e.data.length),c.set(s.data,1+a.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=s;let l=ve(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Ep(s.data).modeBlockflags},Qs(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;let s=Qo(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=On,t.codecInfo.opusInfo={preSkip:s.preSkip},Qs(i.data.subarray(8),this.metadataTags)}async readPacket(e,t){w(t<e.lacingValues.length);let n=0;for(let d=0;d<t;d++)n+=e.lacingValues[d];let i=e,s=n,a=t,o=[];e:for(;;){let d=this.reader.requestSlice(i.dataStartPos,i.dataSize);d instanceof Promise&&(d=await d),w(d);let h=ie(d,i.dataSize);for(;;){if(a===i.lacingValues.length){o.push(h.subarray(n,s));break}let p=i.lacingValues[a];if(s+=p,p<255){o.push(h.subarray(n,s));break e}a++}let f=i.headerStartPos+i.totalSize;for(;;){let p=this.reader.requestSliceRange(f,pn,zn);if(p instanceof Promise&&(p=await p),!p)return null;let m=Gi(p);if(!m)return null;if(i=m,i.serialNumber===e.serialNumber)break;f=i.headerStartPos+i.totalSize}n=0,s=0,a=0}let c=o.reduce((d,h)=>d+h.length,0);if(c===0)return null;let l=new Uint8Array(c),u=0;for(let d=0;d<o.length;d++){let h=o[d];l.set(h,u),u+=h.length}return{data:l,endPage:i,endSegmentIndex:a}}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 i=this.reader.requestSliceRange(n,pn,zn);if(i instanceof Promise&&(i=await i),!i)return null;let s=Gi(i);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.trackBackings.map(t=>t.getDecoderConfig().then(n=>n?.codec??null)));return Yp({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Vu=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new At,this.internalSampleRate=e.codecInfo.codec==="opus"?On:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return w(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return w(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 Ge}getDisposition(){return{...dt,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(w(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:i,vorbisBlockSize:s}=Qp(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new Oe(n.metadataOnly?st:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){w(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(w(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let i=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let i=await this.demuxer.findNextPacketStart(n.packet);if(!i)return null;let s=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=Ir(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;w(this.bitstream.lastMetadataPacket);let i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let s=i.startPage,a=this.demuxer.reader.fileSize,o=[s];e:for(;s.headerStartPos+s.totalSize<a;){let b=s.headerStartPos,k=Math.floor((b+a)/2),T=k;for(;;){let S=Math.min(T+Zp,a-pn),_=this.demuxer.reader.requestSlice(T,S-T);if(_ instanceof Promise&&(_=await _),w(_),!Jp(_,S)){a=k+pn;continue e}let P=this.demuxer.reader.requestSliceRange(_.filePos,pn,zn);P instanceof Promise&&(P=await P),w(P);let A=Gi(P);w(A);let F=!1;if(A.serialNumber===this.bitstream.serialNumber)F=!0;else{let O=this.demuxer.reader.requestSlice(A.headerStartPos,A.totalSize);O instanceof Promise&&(O=await O),w(O);let Q=ie(O,A.totalSize);F=Xp(Q)===A.checksum}if(!F){T=A.headerStartPos+4;continue}if(F&&A.serialNumber!==this.bitstream.serialNumber){T=A.headerStartPos+A.totalSize;continue}if(A.granulePosition===-1){T=A.headerStartPos+A.totalSize;continue}this.granulePositionToTimestampInSamples(A.granulePosition)>n?a=A.headerStartPos:(s=A,o.push(A));continue e}}let c=i.startPage;for(let b of o){if(b.granulePosition===s.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){let b=l.headerStartPos+l.totalSize,k=this.demuxer.reader.requestSliceRange(b,pn,zn);k instanceof Promise&&(k=await k),w(k);let T=Gi(k);w(T),l=T,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}w(l.granulePosition!==-1);let d=null,h,f,p=l,m=0;if(l.headerStartPos===i.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,d=0;else{h=0,f=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;let b={data:st,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(b)){let T=rg(u,l,d);w(T);let S=tg(u,T.page,T.segmentIndex);S&&(l=S.page,d=S.segmentIndex)}else for(;;){let T=rg(u,l,d);if(!T)break;let S=tg(u,T.page,T.segmentIndex);if(!S)break;if(l=S.page,d=S.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,m=T.segmentIndex;break}}}let g=null,y=null;for(;l!==null;){w(d!==null);let b=await this.demuxer.readPacket(l,d);if(!b)break;if(!(l.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);w(S);let _=this.encodedPacketToMetadata.get(S);if(w(_),!f&&b.endPage.headerStartPos===p.headerStartPos&&b.endSegmentIndex===m?(h=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,S=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h-_.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),w(S),_=this.encodedPacketToMetadata.get(S),w(_)):h+=_.durationInSamples,g=S,y=_,f&&(Math.max(h,0)>n||Math.max(_.timestampInSamples,0)===n))break}let T=await this.demuxer.findNextPacketStart(b);if(!T)break;l=T.startPage,d=T.startSegmentIndex}return g}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let i=Ir(e*this.internalSampleRate);e=i/this.internalSampleRate;let s=_e(this.sequentialScanCache,i,c=>c.timestampInSamples),a;if(s!==-1){let c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){let c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;let l=this.encodedPacketToMetadata.get(a);w(l),this.sequentialScanCache.length>0&&w(Ne(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},tg=(r,e,t)=>{let n=e,i=t;e:for(;;){for(i--,i;i>=0;i--)if(n.lacingValues[i]<255){i++;break e}if(w(i===-1),!(n.headerType&1)){i=0;break}let a=ku(r,o=>o.headerStartPos<n.headerStartPos);if(!a)return null;n=a,i=n.lacingValues.length}if(w(i!==-1),i===n.lacingValues.length){let s=r[r.indexOf(n)+1];w(s),n=s,i=0}return{page:n,segmentIndex:i}},rg=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let n=ku(r,i=>i.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var Nr;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Nr||(Nr={}));var bc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],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),w(e);let t=We(e,4),n=t!=="RIFX",i=t==="RF64",s=Vr(e,n),a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(We(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;a===null||u<a;){let h=this.reader.requestSlice(u,8);if(h instanceof Promise&&(h=await h),!h)break;let f=We(h,4),p=Vr(h,n),m=h.filePos;if(i&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(m,p,n);else if(f==="data"){if(l??=p,this.dataStart=h.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let g=this.reader.requestSlice(m,p);if(g instanceof Promise&&(g=await g),!g)break;let y=Wu(g,n);l=Wu(g,n),a=Math.min(y+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(m,p,n):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(m,p);u=m+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new Hu(this))})()}async parseFmtChunk(e,t,n){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let s=$i(i,n),a=$i(i,n),o=Vr(i,n);i.skip(4);let c=$i(i,n),l;if(t===14?l=8:l=$i(i,n),t>=18&&s!==357){let u=$i(i,n),d=t-18;if(Math.min(d,u)>=22&&s===Nr.EXTENSIBLE){i.skip(6);let f=ie(i,16);s=f[0]|f[1]<<8}}(s===Nr.MULAW||s===Nr.ALAW)&&(l=8),this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,n){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let s=We(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+t-8;){i.filePos=a;let o=We(i,4),c=Vr(i,n),l=ie(i,c),u=0;for(let h=0;h<l.length&&l[h]!==0;h++)u++;let d=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=d,o){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let h=d.split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[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 h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"YEAR":{let h=Number.parseInt(d,10);Number.isInteger(h)&&h>0&&(this.metadataTags.date??=new Date(h,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+c+(c&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let i=It(n);if(i){let s=t-mt;if(i.size=Math.min(i.size,s),i.size>0){let a=n.slice(e+mt,i.size);mn(a,i,this.metadataTags)}}}getCodec(){if(w(this.audioInfo),this.audioInfo.format===Nr.MULAW)return"ulaw";if(this.audioInfo.format===Nr.ALAW)return"alaw";if(this.audioInfo.format===Nr.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===Nr.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Ki=2048,Hu=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(w(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return w(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Ge}getDisposition(){return{...dt}}async getPacketAtIndex(e,t){w(e>=0),w(this.demuxer.audioInfo);let n=e*Ki*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let i=Math.min(Ki*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);if(c instanceof Promise&&(c=await c),!c)return null}let s;if(t.metadataOnly)s=st;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);c instanceof Promise&&(c=await c),w(c),s=ie(c,i)}let a=e*Ki/this.demuxer.audioInfo.sampleRate,o=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Oe(s,"key",a,o,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){w(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Ki,(this.demuxer.dataSize-1)/(Ki*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let i=await this.getPacketAtIndex(n,t);if(i)return i;if(n===0)return null;w(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){let a=await this.getNextPacket(s,t);if(!a)break;s=a}return s}getNextPacket(e,t){w(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ki);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Nn=7,er=9,tr=r=>{let e=r.filePos,t=ie(r,9),n=new Ie(t);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let a=n.readBits(1),o=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 u=n.readBits(13);n.skipBits(11);let d=n.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?r.filePos-=2:h=n.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:h,startPos:e}};var ia=1024,kc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new At,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();w(this.firstFrameHeader),this.trackBackings=[new qu(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,mt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let o=It(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Nn,er);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=tr(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=fr[t.samplingFrequencyIndex];w(n!==void 0);let i=ia/n,s={timestamp:this.nextTimestampInSamples/n,duration:i,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=ia,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let n=this.reader.requestSlice(t,mt);if(n instanceof Promise&&(n=await n),!n)break;let i=It(n);if(!i)break;let s=this.reader.requestSlice(n.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;mn(s,i,this.metadataTags),t=n.filePos+i.size}return this.metadataTags}finally{e()}}},qu=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ia}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Ge}getCodec(){return"aac"}getInternalCodecId(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){w(this.demuxer.firstFrameHeader);let e=an[this.demuxer.firstFrameHeader.channelConfiguration];return w(e!==void 0),e}getSampleRate(){w(this.demuxer.firstFrameHeader);let e=fr[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return w(e!==void 0),e}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=ie(s,n.dataSize)}return new Oe(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=Er(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ng=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,ig=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},sg=r=>{let e=0,t=new Ie(ie(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let n=[],i=e-1,s=new Ie(ie(r,i)),a=8-e-1;for(let c=0;c<a;c++)n.unshift(t.readBits(1));for(let c=0;c<i;c++)for(let l=0;l<8;l++){let u=s.readBits(1);l<2||n.unshift(u)}return n.reduce((c,l,u)=>c|l<<u,0)},ag=(r,e)=>{if(e==="uncommon-u16")return Ke(r)+1;if(e==="uncommon-u8")return ce(r)+1;if(typeof e=="number")return e;Ct(e),w(!1)},og=(r,e)=>e==="uncommon-u16"?Ke(r):e==="uncommon-u16-10"?Ke(r)*10:e==="uncommon-u8"?ce(r):typeof e=="number"?e:null,cg=r=>{let t=0;for(let n of r){t^=n;for(let i=0;i<8;i++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var xc=class extends ct{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new At,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),w(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,mt);if(t instanceof Promise&&(t=await t),!t){this.lastSampleLoaded=!0;return}let n=It(t);if(!n)break;let i=this.reader.requestSlice(t.filePos,n.size);i instanceof Promise&&(i=await i),w(i),mn(i,n,this.metadataTags),e=t.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);w(t);let n=ce(t),i=Yt(t),s=(n&128)!==0;switch(n&127){case un.STREAMINFO:{let o=this.reader.requestSlice(e,i);if(o instanceof Promise&&(o=await o),w(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=ie(o,34),l=new Ie(c),u=l.readBits(16),d=l.readBits(16),h=l.readBits(24),f=l.readBits(24),p=l.readBits(20),m=l.readBits(3)+1;l.readBits(5);let g=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:p,totalSamples:g,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:h,maximumFrameSize:f,description:y},this.trackBacking=new ju(this);break}case un.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,i);o instanceof Promise&&(o=await o),w(o),Qs(ie(o,i),this.metadataTags);break}case un.PICTURE:{let o=this.reader.requestSlice(e,i);o instanceof Promise&&(o=await o),w(o);let c=K(o),l=K(o),u=ot.decode(ie(o,l)),d=K(o),h=ot.decode(ie(o,d));o.skip(16);let f=K(o),p=ie(o,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:u,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:h});break}default:break}if(e+=i,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){w(this.audioInfo);let n=6,i=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,o=this.audioInfo.minimumFrameSize||s,l=(this.audioInfo.maximumFrameSize||a)+i,u=await this.reader.requestSliceRange(e,i,l);if(!u)return null;let d=this.readFlacFrameHeader({slice:u,isFirstPacket:t});if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-n)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(ce(u)===255){let f=u.filePos,p=ce(u),m=this.blockingBit===1?249:248;if(p!==m){u.filePos=f;continue}u.skip(-2);let g=u.filePos-e,y=this.readFlacFrameHeader({slice:u,isFirstPacket:!1});if(!y){u.filePos=f;continue}if(this.blockingBit===0){if(y.num-d.num!==1){u.filePos=f;continue}}else if(y.num-d.num!==d.blockSize){u.filePos=f;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:g,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,i=ie(e,4),s=new Ie(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){w(t);let g=s.readBits(1);this.blockingBit=g}else if(this.blockingBit===1){if(w(!t),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(w(!t),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let o=ng(s.readBits(4));if(!o)return null;w(this.audioInfo);let c=ig(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let u=sg(e),d=ag(e,o),h=og(e,c);if(h===null||h!==this.audioInfo.sampleRate)return null;let f=e.filePos-n,p=ce(e);e.skip(-f),e.skip(-1);let m=cg(ie(e,f));return p!==m?null:{num:u,blockSize:d,sampleRate:h}}async advanceReader(){await this.readMetadata(),w(this.lastLoadedPos!==null),w(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(s),t.isLastFrame){this.lastSampleLoaded=!0;return}}},ju=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Ge}getTimeResolution(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(w(this.demuxer.audioInfo),e<0)return null;let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(i===-1){await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[i],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(i,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let o=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;i=ie(o,n.byteSize)}w(this.demuxer.audioInfo);let s=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new Oe(i,"key",s,a,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 lg=r=>{let e="video/MP2T",t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};var dg="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",ug=new Set,Sc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=205,t=this.reader.requestSlice(0,e);t instanceof Promise&&(t=await t),w(t);let n=ie(t,e);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let i=256;this.minReferencePointByteDistance=i*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){let l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===l.pid)){s+=this.packetStride;continue}let u=await this.readSection(s,!0,!c);if(!u)break;let d=3,h=32,f=!1;if(!c&&u.pid!==0&&!(u.payload[0]===0&&u.payload[1]===0&&u.payload[2]===1)){let g=new Ie(u.payload),y=g.readAlignedByte();g.skipBits(8*y),f=g.readBits(8)===2}if(u.pid===0&&!o){let m=new Ie(u.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(14);let y=m.readBits(10);for(m.skipBits(40);8*(y+d)-m.pos>h;){let b=m.readBits(16);m.skipBits(3);let k=m.readBits(13);if(b!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=k}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((u.pid===a||f)&&!c){let m=new Ie(u.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(12);let y=m.readBits(12);m.skipBits(43);let b=m.readBits(13);m.skipBits(6);let k=m.readBits(10);for(m.skipBits(8*k);8*(y+d)-m.pos>h;){let T=m.readBits(8);m.skipBits(3);let S=m.readBits(13);m.skipBits(6);let _=m.readBits(10),M=m.pos+8*_,P=!1,A=!1;for(;m.pos<M;){let I=m.readBits(8),O=m.readBits(8);I===106?P=!0:(I===122||I===204)&&(A=!0),m.skipBits(8*O)}let F=null;switch(T){case 27:case 36:F={type:"video",codec:T===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let I;if(T===3||T===4)I="mp3";else if(T===15)I="aac";else if(T===129)I="ac3";else if(T===135)I="eac3";else throw new Error("Unreachable.");F={type:"audio",codec:I,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:A?F={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:P&&(F={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:ug.has(T)||(we._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),ug.add(T))}F&&this.elementaryStreams.push({demuxer:this,pid:S,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:F,referencePesPackets:[]})}c=!0}else{let m=this.elementaryStreams.find(g=>g.pid===u.pid);e:if(m&&!m.initialized){let g=Xi(u,!0);if(!g)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=u,m.canBeTrustedWithKeyPackets=u.randomAccessIndicator===1,this.input._initInput){let k=(await this.input._initInput._getDemuxer()).elementaryStreams.find(T=>T.pid===u.pid&&T.info.codec===m.info.codec);if(k){m.info=k.info,m.initialized=!0;break e}}let y=new Hn(m,g);if(m.info.type==="video"){for(;;){let b=y;if(b.suppliedPacket=null,await y.markNextPacket(),m.info.codec==="avc"){if(!y.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=Li(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;let k=m.info.avcCodecInfo.sequenceParameterSets[0];w(k);let T=Xs(k);m.info.width=T.displayWidth,m.info.height=T.displayHeight;let S=T.pixelAspectRatio.num,_=T.pixelAspectRatio.den;S>0&&_>0&&(S>_?(m.info.squarePixelWidth=Math.round(m.info.width*S/_),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*_/S))),m.info.colorSpace={primaries:En[T.colourPrimaries],transfer:In[T.transferCharacteristics],matrix:Mn[T.matrixCoefficients],fullRange:!!T.fullRangeFlag},m.info.reorderSize=T.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!y.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=Ui(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;let T=m.info.hevcCodecInfo.arrays.find(_=>_.nalUnitType===it.SPS_NUT).nalUnits[0];w(T);let S=Pu(T);m.info.width=S.displayWidth,m.info.height=S.displayHeight,S.pixelAspectRatio.num>S.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*S.pixelAspectRatio.num/S.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*S.pixelAspectRatio.den/S.pixelAspectRatio.num)),m.info.colorSpace={primaries:En[S.colourPrimaries],transfer:In[S.transferCharacteristics],matrix:Mn[S.matrixCoefficients],fullRange:!!S.fullRangeFlag},m.info.reorderSize=S.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Ri({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await y.markNextPacket(),!y.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){let b=yt.tempFromBytes(y.suppliedPacket.data),k=tr(b);if(!k)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:k.objectType},m.info.numberOfChannels=an[k.channelConfiguration],m.info.sampleRate=fr[k.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){let b=K(yt.tempFromBytes(y.suppliedPacket.data)),k=Ks(b,y.suppliedPacket.data.byteLength);if(!k.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=cn(k.header.channel),m.info.sampleRate=k.header.sampleRate}else if(m.info.codec==="ac3"){let b=Yo(y.suppliedPacket.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Ys[b.acmod]+b.lfeon,m.info.sampleRate=Ln[b.fscod]}else if(m.info.codec==="eac3"){let b=Zo(y.suppliedPacket.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let k=Jo(b);if(k===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=ec(b),m.info.sampleRate=k}else throw new Error("Unhandled.");m.info.decoderConfig={codec:Bi({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let l of this.elementaryStreams)l.info.type==="video"?this.trackBackingEntries.push(new Gu(l)):this.trackBackingEntries.push(new Ku(l))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(n=>n?.codec??null)));return lg(e)}async readSection(e,t,n=!1){let i=e,s=e,a=[],o=0,c=null,l=!0,u=0;for(;;){let h=await this.readPacket(s);if(s+=this.packetStride,!h)break;if(c){if(h.pid!==c.pid){if(n)break;continue}if(h.payloadUnitStartIndicator===1)break}else{if(h.payloadUnitStartIndicator===0)break;c=h}let f=!!(h.adaptationFieldControl&2),p=!!(h.adaptationFieldControl&1),m=0;if(f&&(m=1+h.body[0],h===c&&m>1&&(u=h.body[1]>>6&1)),p&&(m===0?(a.push(h.body),o+=h.body.byteLength):(a.push(h.body.subarray(m)),o+=h.body.byteLength-m)),i=s,!t&&o>=64){l=!1;break}if(Er(this.sectionEndPositions,i,y=>y)!==-1){l=!1;break}}if(l){let h=_e(this.sectionEndPositions,i,f=>f);this.sectionEndPositions.splice(h+1,0,i)}if(!c)return null;let d;if(a.length===1)d=a[0];else{let h=a.reduce((p,m)=>p+m.length,0);d=new Uint8Array(h);let f=0;for(let p of a)d.set(p,f),f+=p.length}return{startPos:e,endPos:t?i:null,pid:c.pid,payload:d,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(ce(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let i=Ke(t),s=i>>15,a=i>>14&1,o=i>>13&1,c=i&8191,l=ce(t),u=l>>6,d=l>>4&3,h=l&15;return{payloadUnitStartIndicator:a,pid:c,adaptationFieldControl:d}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=ie(t,188);if(n[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let s=(n[1]<<8)+n[2],a=s>>15,o=s>>14&1,c=s>>13&1,l=s&8191,u=n[3],d=u>>6,h=u>>4&3,f=u&15;return{payloadUnitStartIndicator:o,pid:l,adaptationFieldControl:h,body:n.subarray(4)}}},Vn=(r,e)=>{if(r.payload.byteLength<3)return null;let t=new Ie(r.payload);if(t.readBits(24)!==1)return null;let i=t.readBits(8);if(t.skipBits(16),i===188||i===190||i===191||i===240||i===241||i===255||i===242||i===248)return null;t.skipBits(8);let s=t.readBits(2);t.skipBits(14);let a=null;if(s===2||s===3)a=0,t.skipBits(4),a+=t.readBits(3)*(1<<30),t.skipBits(1),a+=t.readBits(15)*32768,t.skipBits(1),a+=t.readBits(15);else if(e)throw new Error(dg);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},Xi=(r,e)=>{w(r.endPos!==null);let t=Vn(r,e);if(!t)return null;let n=new Ie(r.payload);n.skipBits(32);let i=n.readBits(16),s=6;n.skipBits(16);let a=n.readBits(8),o=n.pos+8*a;n.pos=o;let c=o/8;w(Number.isInteger(c));let l=r.payload.subarray(c,i>0?s+i:r.payload.byteLength);return{...t,data:l}},Tc=class r{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type,n=0;for(let i of e.trackBackingEntries)if(i.getType()===t&&n++,w(i instanceof r),i.elementaryStream===this.elementaryStream)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Ge}getDisposition(){return{...dt,primary:!1}}getTimeResolution(){return 9e4}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,n){let i;return this.allPacketsAreKeyPackets()?i="key":i=e.randomAccessIndicator===1?"key":"delta",new Oe(n.metadataOnly?st:e.data,i,e.pts/9e4,Math.max(t/9e4,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;w(t);let n=Xi(t,!0);w(n);let i=new Hn(this.elementaryStream,n),s=new sa(this,i),a=await s.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){let u=await n.readNext();if(!u)return null;this.packetBuffers.delete(e);let d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}let i=this.packetSectionStarts.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");let a=await this.elementaryStream.demuxer.readSection(i,!0);w(a);let o=Xi(a,!0);w(o);let c=new Hn(this.elementaryStream,o);n=new sa(this,c);let l=e.sequenceNumber;for(;;){let u=await n.readNext();if(!u)return null;if(u.packet.sequenceNumber>l){let d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type==="key")return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){let i=Ir(e*9e4),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,l=async(T,S,_)=>{let M=T;for(;M<S;){let P=await s.readPacketHeader(M);if(!P)return null;if(P.pid===c&&P.payloadUnitStartIndicator===1){let A=await s.readSection(M,_);if(!A)return null;let F=Vn(A,!1);if(F&&F.pts!==null)return{pesPacketHeader:F,section:A}}M+=s.packetStride}return null},u=this.elementaryStream.firstSection;w(u);let d=Vn(u,!0);if(w(d),i<d.pts)return null;let h,f=this.elementaryStream.referencePesPackets,p=_e(f,i,T=>T.pts),m=p!==-1?f[p]:null;if(m&&i-m.pts<9e4/2)h=m.sectionStartPos;else{let T=0;if(a.fileSize!==null){let S=Math.ceil(a.fileSize/o);if(S>1){let _=0,M=S-1;for(T=_;_<=M;){let P=Math.floor((_+M)/2),A=Uo(P*o,s.packetStride)+d.sectionStartPos,F=A+o,I=await l(A,F,!1);if(!I){M=P-1;continue}I.pesPacketHeader.pts<=i?(T=P,_=P+1):M=P-1}}}h=Uo(T*o,s.packetStride)+d.sectionStartPos}let y=(await l(h,a.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);let b=this.getReorderSize(),k=async(T,S)=>{let _=await s.readSection(T,!0);w(_);let M=Xi(_,!0);w(M);let P=new Hn(this.elementaryStream,M),A=new sa(this,P);for(;!((Ne(A.presentationOrderPackets)?.pts??-1/0)>=i||!await A.readNextPacket()););let F=Ci(A.presentationOrderPackets,S);if(F===-1)return null;let I=A.presentationOrderPackets[F],O=F===0?0:I.pts-A.presentationOrderPackets[F-1].pts;for(;A.decodeOrderPackets[0]!==I;)A.decodeOrderPackets.shift();A.lastDuration=O;let Q=await A.readNext();w(Q);let ge=this.createEncodedPacket(Q.packet,Q.duration,n);return this.packetBuffers.set(ge,A),this.packetSectionStarts.set(ge,Q.packet.sectionStartPos),ge};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let T=y.sectionStartPos+s.packetStride;for(;;){let S=await s.readPacketHeader(T);if(!S)break e;if(S.pid===c&&S.payloadUnitStartIndicator===1){let _=await s.readSection(T,!1);if(_){let M=Vn(_,!1);if(M&&M.pts!==null){if(M.pts>i)break e;y=M,$u(this.elementaryStream,y);break}}}T+=s.packetStride}}e:for(let T=0;T<b+1;T++){let S=y.sectionStartPos-s.packetStride;for(;S>=s.packetOffset;){let _=await s.readPacketHeader(S);if(!_)break e;if(_.pid===c&&_.payloadUnitStartIndicator===1){let M=await s.readSection(S,!1);if(M){let P=Vn(M,!1);if(P&&P.pts!==null){y=P;break}}}S-=s.packetStride}}return k(y.sectionStartPos,T=>T.pts<=i)}else{let T=h,S=null,_=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let M=null,P=T<=d.sectionStartPos,A,F=null;if(P)A=d,F=u;else{let Q=await l(T,a.fileSize??1/0,_);A=Q?.pesPacketHeader??null,F=Q?.section??null}let I=!1,O=0;e:for(;A&&!(S!==null&&A.sectionStartPos>=S);){if(A.pts<=i){let ge;if(this.elementaryStream.canBeTrustedWithKeyPackets)ge=A.randomAccessIndicator===1;else{w(F);let be=Xi(F,!0);w(be);let J=new Hn(this.elementaryStream,be);await J.markNextPacket(),ge=J.suppliedPacket?.randomAccessIndicator===1}ge&&(M=A)}if(A.pts>i&&(I=!0),I&&(O++,O>b))break;let Q=A.sectionStartPos+s.packetStride;for(;;){let ge=await s.readPacketHeader(Q);if(!ge)break e;if(ge.pid===c&&ge.payloadUnitStartIndicator===1){let be=await s.readSection(Q,_);if(be){let J=Vn(be,!1);if(J&&J.pts!==null){A=J,F=be,$u(this.elementaryStream,A);break}}}Q+=s.packetStride}}if(M){let Q=M;if(O===0)e:for(let be=0;be<b;be++){let J=Q.sectionStartPos-s.packetStride;for(;J>=s.packetOffset;){let Ae=await s.readPacketHeader(J);if(!Ae)break e;if(Ae.pid===c&&Ae.payloadUnitStartIndicator===1){let Re=await s.readSection(J,_);if(Re){let et=Vn(Re,!1);if(et&&et.pts!==null){Q=et;break}}}J-=s.packetStride}}let ge=await k(Q.sectionStartPos,be=>be.pts<=i&&be.randomAccessIndicator===1);return w(ge),ge}if(P)return null;S=T,T=Math.max(Uo(T-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},Gu=class extends Tc{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return w(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Ku=class extends Tc{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return w(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},$u=(r,e)=>{let t=r.referencePesPackets,n=_e(t,e.sectionStartPos,i=>i.sectionStartPos);if(n>=0){let i=t[n];if(e.pts<=i.pts)return!1;let s=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-i.sectionStartPos<s)return!1;if(n<t.length-1){let a=t[n+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return t.splice(n+1,0,e),!0},Hn=class{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return w(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let n;if(this.pesPackets.length===0)n=this.startingPesPacket;else{let i=Ne(this.pesPackets).sectionEndPos;for(w(i!==null);;){let s=await this.demuxer.readPacketHeader(i);if(!s)return;if(s.pid===this.pid){let a=await this.demuxer.readSection(i,!0);if(!a)return;let o=Xi(a,!1);if(o){n=o;break}}i+=this.demuxer.packetStride}}this.pesPackets.push(n),this.endPos+=n.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,i=n+e;if(this.currentPos+=e,i<=t.data.byteLength)return t.data.subarray(n,i);let s=new Uint8Array(e);s.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){let t=this.getCurrentPesPacket(),n=this.currentPesPacketPos+t.data.byteLength;if(e<n)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){w(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type==="video"){let t=e.info.codec,n=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");let i=t==="avc"?1:2,s=null,a=!1,o=0;for(;;){let c=this.ensureBuffered(n);if(c instanceof Promise&&(c=await c),c===0)break;let l=this.currentPos,u=this.readBytes(c),d=u.byteLength,h=0;for(;h<d;){let f=u.indexOf(0,h);if(f===-1||f>=d)break;h=f;let p=l+h;if(h+3>=d){this.seekTo(p);break}let m=u[h+1],g=u[h+2],y=u[h+3],b=0;if(m===0&&g===0&&y===1?b=4:m===0&&g===1&&(b=3),b===0){h++;continue}let k=p;s??=k;let T=h+b,S=T+i,_=6;if(S+(t==="avc"?_:1)>d){this.seekTo(p);break}let P=u[T],A,F,I;if(t==="avc")A=Oi(P),F=A===lt.NON_IDR_SLICE||A===lt.SLICE_DPA||A===lt.IDR,I=A===lt.SEI||A===lt.SPS||A===lt.PPS||A===lt.AUD;else{if(A=ln(P),((P&1)<<5|u[T+1]>>3)>0){h+=b;continue}F=A<=it.RASL_R||A>=it.BLA_W_LP&&A<=21,I=A>=it.VPS_NUT&&A<=37||A===it.PREFIX_SEI_NUT||A>=41&&A<=44||A>=48&&A<=55}let O=!1;if(F){let Q;if(t==="avc"){let ge=u.subarray(S,S+_),be=Y(new Ie(ge));Q=!a||be<=o,o=be}else Q=u[S]>>7===1;Q&&(a?O=!0:a=!0)}else I&&a&&(O=!0);if(O){let Q=k-s;return this.seekTo(s),this.supplyPacket(Q,0)}h+=b}if(c<n)break}if(s!==null&&this.endPos>s){let c=this.endPos-s;return this.seekTo(s),this.supplyPacket(c,0)}}else{let t=e.info.codec,n=128;for(;;){let i=this.ensureBuffered(n);i instanceof Promise&&(i=await i);let s=this.currentPos;for(;this.currentPos-s<i;){let a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(er);if(c instanceof Promise&&(c=await c),c<er)return;let l=this.readBytes(er),u=tr(yt.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return d instanceof Promise&&(d=await d),this.supplyPacket(d,Math.round(ia*9e4/e.info.sampleRate))}else this.seekTo(o+1)}else if(t==="mp3"){if(a!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(4);if(c instanceof Promise&&(c=await c),c<4)return;let l=this.readBytes(4),u=ve(l).getUint32(0),d=Ks(u,null);if(d.header){this.seekTo(o);let h=this.ensureBuffered(d.header.totalSize);h instanceof Promise&&(h=await h);let f=d.header.audioSamplesInFrame*9e4/e.info.sampleRate;return this.supplyPacket(h,Math.round(f))}else this.seekTo(o+1)}else if(t==="ac3"){if(a!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}let h=Ip[3*d+u];w(h!==void 0),this.seekTo(o),c=this.ensureBuffered(h),c instanceof Promise&&(c=await c);let f=Math.round(Mp*9e4/e.info.sampleRate);return this.supplyPacket(c,f)}else if(t==="eac3"){if(a!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let d=(((l[2]&7)<<8|l[3])+1)*2,f=l[4]>>6===3?3:l[4]>>4&3,p=Eu[f];this.seekTo(o),c=this.ensureBuffered(d),c instanceof Promise&&(c=await c);let m=p*256,g=Math.round(m*9e4/e.info.sampleRate);return this.supplyPacket(c,g)}else throw new Error("Unhandled.")}if(i<n)break}}}supplyPacket(e,t){let n=this.getCurrentPesPacket(),i;if(this.lastSuppliedPesPacket===n)w(this.nextPts!==null),i=this.nextPts;else{if(n.pts===null)throw new Error(dg);i=n.pts,$u(this.elementaryStream,n)}this.lastSuppliedPesPacket=n,this.nextPts=i+t;let s=n.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),c=n.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){let l=dn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(l)}}this.suppliedPacket={pts:i,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},sa=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),w(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);w(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let i=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(i))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(w(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let t=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[t].pts&&(t=i);let n=this.reorderBuffer[t];this.presentationOrderPackets.push(n),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};var vc="application/vnd.apple.mpegurl",Xu="#EXT-X-STREAM-INF:",Qu="#EXT-X-I-FRAME-STREAM-INF:",Yu="#EXT-X-MEDIA:",aa="#EXTINF:",Zu="#EXT-X-MAP:",Ju="#EXT-X-KEY:",ed="#EXT-X-MEDIA-SEQUENCE:",td="#EXT-X-BYTERANGE:",rd="#EXT-X-PROGRAM-DATE-TIME:",hg="#EXT-X-DISCONTINUITY",nd="#EXT-X-TARGETDURATION:",fg="#EXT-X-ENDLIST",id="#EXT-X-PLAYLIST-TYPE:",mg="#EXT-X-I-FRAMES-ONLY",Ac=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT"),Wr=class{constructor(e){this._attributes={};let t="",n="",i=!1,s=!1;for(let a=0;a<e.length;a++){let o=e[a];o==='"'?s=!s:o==="="&&!i&&!s?i=!0:o===","&&!s?(t&&(this._attributes[t.trim().toLowerCase()]=n),t="",n="",i=!1):i?n+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=n)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}};var _c=class{constructor(e,t,n){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=n}async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(t??=await this.getFirstSegment({}),!t||t.unixEpochTimestamp===null)return null;let n=e-t.timestamp;return t.unixEpochTimestamp+n}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type==="video"){let n=Bn(e,i=>i.getType()==="video")+1;e.push(new Pc(this,t,n))}else if(t.type==="audio"){let n=Bn(e,i=>i.getType()==="audio")+1;e.push(new Ec(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let n=await this.getInputForSegment(this.firstSegment).getTracks();for(let i of n)if(i.type==="video"){let s=Bn(e,a=>a.getType()==="video")+1;e.push(new Pc(this,{id:e.length+1,type:"video"},s))}else if(i.type==="audio"){let s=Bn(e,a=>a.getType()==="audio")+1;e.push(new Ec(this,{id:e.length+1,type:"audio"},s))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(t!==void 0)return t;let n=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,n),n}async getMediaOffset(e,t){let n=e.firstSegment??e,i;if(this.firstSegmentFirstTimestamps.has(n))i=this.firstSegmentFirstTimestamps.get(n);else{let l=this.getInputForSegment(n);i=await this.getFirstTimestampForInput(l),this.firstSegmentFirstTimestamps.set(n,i)}if(n===e)return n.timestamp-i;let s=await this.getFirstTimestampForInput(t),a=e.timestamp-n.timestamp,c=s-i-a;return Math.abs(c)<=Math.min(.25,a)?n.timestamp-i:e.timestamp-s}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}},Cc=class{constructor(e,t,n){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let n=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(i=>i.type===this.decl.type&&i.number===this.number);if(!n)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=n})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),w(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,n){w(e.sequenceNumber>=0),w(this.segmentedInput.firstSegment);let i=await this.segmentedInput.getMediaOffset(t,n.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:Fn(e.timestamp+i,await n.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:n,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),w(this.segmentedInput.firstSegment),w(this.firstInputTrack);let t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,n){let i=this.packetInfos.get(e);if(!i)throw new Error("Packet was not created from this track.");let s=n?await i.track._backing.getNextKeyPacket(i.sourcePacket,t):await i.track._backing.getNextPacket(i.sourcePacket,t);if(s)return this.createAdjustedPacket(s,i.segment,i.track);let a=i.segment;for(;;){let o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;let u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(h=>h.type===i.track.type&&h.number===i.track.number);if(!u){a=o;continue}let d=await u._backing.getFirstPacket(t);return d?this.createAdjustedPacket(d,o,u):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,n){let i=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!i)return null;for(await this.hydrate();i;){let s=this.segmentedInput.getInputForSegment(i),o=(await s.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(i,s),l=e-c,u=n?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!u){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(u,i,o)}return null}},Pc=class extends Cc{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},Ec=class extends Cc{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}};Ei();var sd=0,ad=1/0,rT=null;typeof FinalizationRegistry<"u"&&(rT=new FinalizationRegistry(r=>{r()}));var wt=class extends Nt{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new ut;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,sd,ad),e=this._getFileSize(),w(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ut;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Mc(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Wn(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Wn=class{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");let e=this.source;w(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Ot=class extends wt{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=i=>{if(!(i instanceof wt||i instanceof Wn))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let s=i instanceof wt?i.ref():i;return s.source._usedForHls||=this._usedForHls,s};return t instanceof Promise?t.then(n):n(t)}},od=(r,e)=>r.path===e.path,oa=class extends Ot{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,n,i){if(!this._root){if(!this._rootRequest){let s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{let c=o instanceof wt?o.ref():o;return this._root=c,this._rootRequest=null,c};s instanceof Promise?this._rootRequest=s.then(a):(a(s),w(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,t,n,i))}return this._root.source._read(e,t,n,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},ca=class extends wt{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=Ye(e),this._view=ve(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},la=class extends wt{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Ii(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Ic({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:gg.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,n,i){return this._orchestrator.read(e,t,n,i)}async _runWorker(e){w(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!sn()&&this._options.useStreamReader!==!1?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:i}=await t.read();if(n)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},nT=.5*2**20,iT=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let i=null;try{typeof window<"u"&&typeof window.location<"u"&&(i=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&i!==null&&i!==window.location.origin)return we._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),pg=new Set,ua=class r extends Ot{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Ii(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");let n=e instanceof Request?e.url:e instanceof URL?e.href:e;super(n,a=>new r(a.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??iT,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){let a={...Lo(t.requestInit.headers)},o=Object.keys(a).find(c=>c.toLowerCase()==="range");o!==void 0&&(i=a[o],delete a[o],this._requestInit.headers=a)}if(e instanceof Request){let a=e.headers.get("Range");if(a!==null){i??=a;let o=new Request(e);o.headers.delete("Range"),this._url=o}}if(i!==null){let a=aT(i);a&&(this._offset=a.offset,this._length=a.length)}let s=2;this._orchestrator=new Ic({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:gg.network})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;let e=this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:Ze(e-this._offset,0,this._length??1/0)}_read(e,t,n,i){if(this._length!==null&&t>this._length)return null;let s=this._offset,a=this._orchestrator.read(s+e,s+t,Math.max(s+n,s),s+Math.min(i,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return a instanceof Promise?a.then(o):o(a)}async _runWorker(e){for(;;){let t=new AbortController,n=await Ym(this._options.fetchFn??fetch,this._url,Qm(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(this._orchestrator.fileSize===null){let s=n.headers.get("Content-Range");if(s){let o=/\/(\d+)/.exec(s);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}let a=n.headers.get("Content-Length");a&&this._orchestrator.supplyFileSize(e.currentPos+Number(a))}if(this._fileSizeDetermined=!0,n.status!==206){if(!this._usedForHls){let s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(pg.has(s.origin)||(we._warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),pg.add(s.origin)))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize!==null?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await i.read()}catch(c){if(this._disposed)throw c;let l=this._getRetryDelay(1,c,this._url);if(l!==null){we._error("Error while reading response stream. Attempting to resume.",c),await Ws(1e3*l);break}else throw c}if(e.aborted)continue;let{done:a,value:o}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_dispose(){this._orchestrator.dispose()}},sT=/^bytes=(\d+)-(\d*)$/,aT=r=>{let e=sT.exec(r.trim());if(!e)return null;let t=Number(e[1]),n=e[2]===""?null:Number(e[2]);return n!==null&&n<t?null:{offset:t,length:n!==null?n-t+1:null}};var da=class extends wt{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Ii(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let n=_e(this._cache,e,u=>u.start),i=n!==-1?this._cache[n]:null;if(i&&i.start<=e&&t<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let s=e,a=new Uint8Array(t-e);if(n!==-1)for(let u=n;u<this._cache.length;u++){let d=this._cache[u];if(d.start>=t)break;let h=Math.max(e,d.start);h>s&&this._throwDueToCacheMiss();let f=Math.min(t,d.end);h<f&&(a.set(d.bytes.subarray(h-d.start,f-d.start),h-e),s=f)}if(s===t)return{bytes:a,view:ve(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:o,resolve:c,reject:l}=nt();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else throw u})),o}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,i=this._currentIndex+t.byteLength;this._dispatchRead(n,i);for(let s=0;s<this._pendingSlices.length;s++){let a=this._pendingSlices[s],o=Math.max(n,a.start),c=Math.min(i,a.end);o<c&&(a.bytes.set(t.subarray(o-n,c-n),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:ve(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:n,end:i,bytes:t,view:ve(t),age:0});this._cache.length>0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},gg={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(let i of t){let a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-8388608);if(zo(r,e,a,i.targetPos)){let o=i.targetPos-i.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,i.startPos+u)}}return e=Math.max(e,r+nT),{start:r,end:e}}},Ic=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,n,i){w(!this.disposed);let s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,n),o=Math.min(s.end,this.fileSize??1/0,i);w(a<=e&&t<=o);let c=null,l=_e(this.cache,e,S=>S.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});let d=_e(this.cache,a,S=>S.start),h=c?null:new Uint8Array(t-e),f=0,p=a,m=[];if(d!==-1){for(let S=d;S<this.cache.length;S++){let _=this.cache[S];if(_.start>=o)break;if(_.end<=a)continue;let M=Math.max(a,_.start),P=Math.min(o,_.end);if(w(M<=P),p<M&&m.push({start:p,end:M}),p=P,h){let A=Math.max(e,_.start),F=Math.min(t,_.end);if(A<F){let I=A-e;h.set(_.bytes.subarray(A-_.start,F-_.start),I),I===f&&(f=F-e)}}_.age=this.nextAge++}p<o&&m.push({start:p,end:o})}else m.push({start:a,end:o});if(h&&f>=h.length&&(c={bytes:h,view:ve(h),offset:e}),m.length===0)return w(c),c;let{promise:g,resolve:y,reject:b}=nt(),k=[];for(let S of m){let _=Math.max(e,S.start),M=Math.min(t,S.end);_===S.start&&M===S.end?k.push(S):_<M&&k.push({start:_,end:M})}let T=h&&{start:e,bytes:h,holes:k,resolve:y,reject:b};e:for(let S of m){for(let P of this.workers)if(this.checkHoleAgainstWorker(P,S,T?[T]:[])){this.checkQueuedReadsAgainstWorker(P);continue e}let _=S.end<o||this.fileSize!==null,M=this.createWorker(S.start,S.end,_);if(M)T&&(M.pendingSlices=[T]),this.runWorker(M);else{let P=_e(this.queuedReads,S.start,F=>F.hole.start),A=P!==-1?this.queuedReads[P]:null;for(A&&S.start<=A.hole.end?(A.hole.end=Math.max(A.hole.end,S.end),A.strictTarget&&=_,T&&A.pendingSlices.push(T)):(P++,A={hole:{start:S.start,end:S.end},strictTarget:_,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(P,0,A));P+1<this.queuedReads.length;){let F=this.queuedReads[P+1];if(F.hole.start>A.hole.end)break;A.hole.end=Math.max(A.hole.end,F.hole.end),A.pendingSlices.push(...F.pendingSlices),A.strictTarget&&=F.strictTarget,A.age=Math.min(A.age,F.age),this.queuedReads.splice(P+1,1)}}}return c?g.catch(S=>{if(!this.disposed)throw S}):(w(h),c=g.then(S=>S&&{bytes:S,view:ve(S),offset:e})),c}checkHoleAgainstWorker(e,t,n){if(zo(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let s=0;s<n.length;s++){let a=n[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let n=0;n<this.queuedReads.length;n++){let i=this.queuedReads[n];if(this.checkHoleAgainstWorker(e,i.hole,i.pendingSlices))this.queuedReads.splice(n,1),n--,t=!0;else if(t)break}}createWorker(e,t,n){if(this.workers.length>=this.options.maxWorkerCount){let s=null,a=null;for(let o=0;o<this.workers.length;o++){let c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!s||c.age<s.age)&&(a=o,s=c)}if(s)w(a!==null),w(s.pendingSlices.length===0),this.workers.splice(a,1);else return null}let i={startPos:e,currentPos:e,targetPos:t,strictTarget:n,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){w(!e.running),w(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)throw t}).finally(()=>{if(!(e.running||this.workers.length>=this.options.maxWorkerCount)&&this.queuedReads.length>0){let t=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[t].age&&(t=s);let n=this.queuedReads[t];this.queuedReads.splice(t,1);let i=this.createWorker(n.hole.start,n.hole.end,n.strictTarget);w(i),i.pendingSlices=n.pendingSlices,this.runWorker(i)}})}consolidateEverythingIntoOneWorker(e){let t=new Set(e.pendingSlices);for(let n=0;n<this.workers.length;n++){let i=this.workers[n];if(i!==e){for(let s of i.pendingSlices)t.add(s);i.aborted=!0,i.pendingSlices.length=0,this.workers.splice(n,1),n--}}for(let n=0;n<this.queuedReads.length;n++){let i=this.queuedReads[n];for(let s of i.pendingSlices)t.add(s)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){w(!e.aborted);let n=e.currentPos,i=n+t.length;this.insertIntoCache({start:n,end:i,bytes:t,view:ve(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let s=0;s<e.pendingSlices.length;s++){let a=e.pendingSlices[s],o=Math.max(n,a.start),c=Math.min(i,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-n,c-n),o-a.start);for(let l=0;l<a.holes.length;l++){let u=a.holes[l];n<=u.start&&i>u.start&&(u.start=i),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let a=this.workers[s];e===a||a.running||zo(n,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),s--)}}supplyFileSize(e){w(this.fileSize===null),this.fileSize=e;for(let t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let n=0;n<t.pendingSlices.length;n++){let i=t.pendingSlices[n];for(let s of i.holes)if(s.end>e){i.resolve(null),t.pendingSlices.splice(n,1),n--;break}}}for(let t=0;t<this.queuedReads.length;t++){let n=this.queuedReads[t];if(n.hole.start>=e){for(let i of n.pendingSlices)i.resolve(null);this.queuedReads.splice(t,1),t--}else if(n.hole.end>e){n.hole.end=e,n.strictTarget=!0;for(let i=0;i<n.pendingSlices.length;i++){let s=n.pendingSlices[i];s.start>=e&&(s.resolve(null),n.pendingSlices.splice(i,1),i--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){let t=this.workers.indexOf(e);w(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(let n of e.pendingSlices)n.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=_e(this.cache,e.start,n=>n.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let i=new Uint8Array(e.end-n.start);i.set(n.bytes,0),i.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=i,n.view=ve(i),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let i=this.cache[n];if(e.end<=i.start)break;if(e.end>=i.end){this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length,n--;continue}let s=new Uint8Array(i.end-e.start);s.set(e.bytes,0),s.set(i.bytes,i.start-e.start),this.currentCacheSize-=e.end-i.start,e.bytes=s,e.view=ve(s),e.end=i.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,i=this.cache[0];for(let s=1;s<this.cache.length;s++){let a=this.cache[s];a.age<i.age&&(n=s,i=a)}if(this.currentCacheSize-i.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};var Mc=class extends wt{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:Ze(e-this._offset,0,this._length??1/0)}_read(e,t,n,i){if(this._length!==null&&t>this._length)return null;let s=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+i),a=o=>o?(o.offset-=this._offset,o):null;return s instanceof Promise?s.then(a):a(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}};var yg=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},wg=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n}),oT=/^0[xX][0-9a-fA-F]+$/,cT=/^data:.*;base64,/i,ha=class extends _c{constructor(e,t,n,i){super(e.input,t,n),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=i}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await Ws(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){let k={stack:[],error:void 0,hasError:!1};try{let T=yg(k,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),_=await new gn(T.source).requestEntireFile();w(_),e=Fc(_,_.length,{ignore:Ac}),T.source instanceof Ot&&(this.rootPath=T.source.rootPath)}catch(T){k.error=T,k.hasError=!0}finally{wg(k)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=!1,i=0,s=null,a=null,o=null,c=0,l=null,u=null,d=null,h=null,f=null,p=null,m=!1,g=Ne(this.segments)??null,y=k=>{let T=k.indexOf("@"),S=Number(T===-1?k:k.slice(0,T));if(!Number.isInteger(S)||S<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${k}'.`);let _=null;if(T!==-1&&(_=Number(k.slice(T+1)),!Number.isInteger(_)||_<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${k}'.`);return{length:S,offset:_}},b=k=>{c=k,g&&(w(g.sequenceNumber!==null),g.sequenceNumber<k&&(i=g.timestamp+g.duration,l=g.firstSegment,u=g.initSegment,f=g.lastProgramDateTimeSeconds,s=g.unixEpochTimestamp!==null?g.unixEpochTimestamp+g.duration:null,g=null))};for(let k=0;k<e.length;k++){let T=e[k];if(!n){if(T!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");n=!0;continue}if(!T.startsWith("#")){if(!g){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let S=o;if(S&&S.method==="AES-128"&&!S.iv){let A=new Uint8Array(Qt),F=ve(A);F.setUint32(8,Math.floor(c/2**32)),F.setUint32(12,c),S={...S,iv:A}}let M={path:dr(this.rootPath,T),offset:h?.offset??0,length:h?.length??null},P={timestamp:i,unixEpochTimestamp:s,firstSegment:l,sequenceNumber:c,location:M,duration:a,encryption:S,initSegment:u,lastProgramDateTimeSeconds:f};l??=P,i+=a,s!==null&&(s+=a),this.segments.push(P)}a=null,h===null?d=null:h=null,b(c+1)}if(T.startsWith(aa)){if(g){m=!0;continue}m||(f===null&&c>0&&p!==null&&(i=c*p),m=!0);let S=T.slice(aa.length),_=S.indexOf(","),M=_===-1?S:S.slice(0,_),P=Number(M);if(!Number.isFinite(P)||P<0)throw new Error(`Invalid #EXTINF tag duration '${M}'.`);a=P}else if(T.startsWith(Zu)){let S=new Wr(T.slice(Zu.length)),_=S.get("uri");if(!_)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let M=S.get("byterange"),P=null;if(M!==null&&(P=y(M)),P&&P.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){let F={path:dr(this.rootPath,_),offset:P?.offset??0,length:P?.length??null};if(o?.method==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");u={timestamp:i,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:F,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:f}}a=null,h===null?d=null:h=null}else if(T.startsWith(Ju)){let S=new Wr(T.slice(Ju.length)),_=S.get("method");if(_==="NONE")o=null;else if(_==="AES-128"){let M=S.get("uri");if(!M)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let P=null,A=S.get("iv");if(A){if(!oT.test(A))throw new Error(`Unsupported IV format '${A}'.`);let I=A.slice(2);I=I.padStart(Qt*2,"0"),P=new Uint8Array(Qt);for(let O=0;O<Qt;O++){let Q=-Qt*2+O;P[O]=parseInt(I.slice(Q,Q+2),16)}}let F=S.get("keyformat")??"identity";if(F!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");o={method:"AES-128",keyUri:dr(this.rootPath,M),iv:P,keyFormat:F}}else if(_==="SAMPLE-AES"||_==="SAMPLE-AES-CTR"){let M=S.get("uri");if(!M)throw new Error(`Invalid #EXT-X-KEY: ${_} requires a URI attribute.`);if((S.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let A=null;if(cT.test(M)){let F=M.indexOf(","),I=Hs(M.slice(F+1));if(I.length>=8&&I[4]===112&&I[5]===115&&I[6]===115&&I[7]===104){let O=ve(I).getUint32(0);A=rc(I.subarray(8,Math.min(O,I.length)))}}o={method:_,psshBox:A}}else throw new Error(`Unsupported encryption method '${_}'. If you think this method should be supported, please raise an issue.`)}else if(T.startsWith(ed)){let S=T.slice(ed.length),_=Number(S);if(!Number.isInteger(_)||_<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${S}'.`);b(_)}else if(T.startsWith(td)){let S=y(T.slice(td.length));if(S.offset===null){if(d===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");S.offset=d}h=S,d=S.offset+S.length}else if(T.startsWith(rd)){if(g)continue;let S=T.slice(rd.length),_=Date.parse(S);if(!Number.isFinite(_))continue;let M=_/1e3;if(f===M)continue;if(f===null&&this.segments.length>0){let P=Ne(this.segments),A=P.timestamp+P.duration,F=M-A;for(let I of this.segments)I.unixEpochTimestamp=I.timestamp+F,t&&(I.timestamp=I.unixEpochTimestamp)}f=M,s=M,t&&(i=M)}else if(T===hg)l=null;else if(T.startsWith(nd)){let S=T.slice(nd.length),_=Number(S);if(!Number.isFinite(_)||_<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${S}'.`);this.refreshInterval=_,p=_}else if(T===fg){this.streamHasEnded=!0;break}else T.startsWith(id)&&T.slice(id.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!n)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let i=_e(this.segments,e,a=>a.timestamp);if(i===-1)return null;if(i<this.segments.length-1||this.streamHasEnded||n)return this.segments[i];let s=this.segments[i];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,t){let n=this.segments.indexOf(e);w(n!==-1);let i=n+1,s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return w(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,n=this.inputCache.find(c=>c.segment===t);if(n)return n.age=this.nextInputCacheAge++,n.input;let i=null;(t.initSegment||t.firstSegment)&&(i=this.getInputForSegment(t.initSegment??t.firstSegment));let s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(c=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(c);let l=c.psshBoxes,{psshBox:u}=t.encryption;return(u.keyIds===null||u.keyIds.includes(c.keyId))&&!l.some(d=>nc(d,u))&&(l=[...l,u]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:l})})}},a=new qr({source:new oa(t.location.path,async c=>{w(c.isRoot);let l={...c,isRoot:!1},u,d=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(u=await this.input._getSourceCached(l),d){let f=u.source.slice(t.location.offset,t.location.length??void 0).ref();u.free(),u=f}}else if(t.encryption.method==="AES-128"){let h=t.encryption;w(h.iv);let f=await this.input._getSourceCached(l);if(d){let y=f.source.slice(t.location.offset,t.location.length??void 0).ref();f.free(),f=y}let p=new gn(f.source),m=Op(p,async()=>{let g={stack:[],error:void 0,hasError:!1};try{let y=yg(g,await this.input._getSourceCached({path:h.keyUri,isRoot:!1},bg),!1),k=await new gn(y.source).requestSlice(0,Qt);if(!k)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:ie(k,Qt),iv:h.iv}}catch(y){g.error=y,g.hasError=!0}finally{wg(g)}},()=>{f.free()});u=new da(m).ref()}else w(!1);return u}),formats:this.input._formats.filter(c=>!(c instanceof Qi)),initInput:i??void 0,formatOptions:s});if(a._onFormatDetermined=c=>{if((t.encryption?.method==="SAMPLE-AES"||t.encryption?.method==="SAMPLE-AES-CTR")&&!c._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){let c=Mi(this.inputCache,l=>l.age);w(c!==-1),this.inputCache.splice(c,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}};var Bc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{w(this.input._rootSource instanceof Ot);let e=await this.input._reader.requestEntireFile();w(e);let t=Fc(e,e.length,{ignore:Ac}),{rootPath:n}=this.input._rootSource,i=[],s=[];for(let d=1;d<t.length;d++){let h=t[d];if(h.startsWith(Xu)){let f=d,p=t[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");let m=dr(n,p),g=new Wr(h.slice(Xu.length));if(g.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");i.push({fullPath:m,attributes:g,lineNumber:f,hasOnlyKeyPackets:!1})}else if(h.startsWith(Qu)){let f=new Wr(h.slice(Qu.length)),p=f.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(f.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let g=dr(n,p);i.push({fullPath:g,attributes:f,lineNumber:d,hasOnlyKeyPackets:!0})}else if(h.startsWith(Yu)){let f=new Wr(h.slice(Yu.length));if(f.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(f.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let g=null,y=f.get("uri");y!==null&&(g=dr(n,y)),s.push({fullPath:g,attributes:f,lineNumber:d})}else if(h!==mg){if(h.startsWith(aa)){let f=new ha(this,n,null,t);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}}let a=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(i.map(async(d,h)=>{let f=[],p=d.attributes.get("codecs"),m;if(p)m=p.split(",").map(A=>A.trim());else{let F=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),I=await Promise.all(F.map(async O=>({track:O,codec:await O.getCodec()})));m=await Promise.all(I.filter(O=>O.codec!==null).map(O=>O.track.getDecoderConfig().then(Q=>Q.codec)))}let g=d.attributes.get("video"),y=d.attributes.get("audio"),b=m.some(A=>gt.includes(Fr(A))),k=m.some(A=>Vt.includes(Fr(A)));if(g!==null&&!b){if(!a.includes(g))throw new Error(`Invalid M3U8 file; variant stream references video group "${g}" which is not defined in any #EXT-X-MEDIA tags.`);let A=s.find(F=>{let I=F.attributes.get("group-id"),O=F.attributes.get("type");return I===g&&O.toLowerCase()==="video"});e:if(A){let F=A.attributes.get("uri");if(F===null)break e;let I=dr(n,F),ge=(await this.getSegmentedInputForPath(I).getTrackBackings()).find(J=>J.getType()==="video");if(!ge||await ge.getCodec()===null)break e;let be=await ge.getDecoderConfig().then(J=>J?.codec??null);w(be!==null),m.push(be)}}if(y!==null&&!k){if(!o.includes(y))throw new Error(`Invalid M3U8 file; variant stream references audio group "${y}" which is not defined in any #EXT-X-MEDIA tags.`);let A=s.find(F=>{let I=F.attributes.get("group-id"),O=F.attributes.get("type");return I===y&&O.toLowerCase()==="audio"});e:if(A){let F=A.attributes.get("uri");if(F===null)break e;let I=dr(n,F),ge=(await this.getSegmentedInputForPath(I).getTrackBackings()).find(J=>J.getType()==="audio");if(!ge||await ge.getCodec()===null)break e;let be=await ge.getDecoderConfig().then(J=>J?.codec??null);w(be!==null),m.push(be)}}m=[...new Set(m)];let T=null,S=null,_=d.attributes.getAsNumber("bandwidth");w(_!==null);let M=d.attributes.getAsNumber("average-bandwidth"),P=d.attributes.get("name");for(let A of m){let F=Fr(A);if(F!==null){if(gt.includes(F)){if(T!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");T=A;let I=d.attributes.get("video");if(I===null){let O=d.attributes.get("resolution"),Q=null,ge=null;if(O){let be=O.match(/^(\d+)x(\d+)$/);be&&(Q=Number(be[1]),ge=Number(be[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Ge,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(h),peakBitrate:_,averageBitrate:M,name:P,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:Q,height:ge}})}else{if(!a.includes(I))throw new Error(`Invalid M3U8 file; variant stream references video group "${I}" which is not defined in any #EXT-X-MEDIA tags.`);for(let O of s){let Q=O.attributes.get("group-id"),ge=O.attributes.get("type");if(Q!==I||ge.toLowerCase()!=="video")continue;let be=O.attributes.get("resolution")??d.attributes.get("resolution"),J=null,Ae=null;if(be){let Re=be.match(/^(\d+)x(\d+)$/);Re&&(J=Number(Re[1]),Ae=Number(Re[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:Rc(O.attributes),autoselect:Rc(O.attributes)||kg(O.attributes),languageCode:xg(O.attributes.get("language")),lineNumber:O.lineNumber,fullPath:O.fullPath??d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:O.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:J,height:Ae}})}}}else if(Vt.includes(F)){if(S!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");S=A;let I=d.attributes.get("audio");if(I===null){let O=d.attributes.get("channels"),Q=O!==null?Number(O.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Ge,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(h),peakBitrate:_,averageBitrate:M,name:P,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:Q!==null&&Number.isInteger(Q)&&Q>0?Q:null}})}else{if(!o.includes(I))throw new Error(`Invalid M3U8 file; variant stream references audio group "${I}" which is not defined in any #EXT-X-MEDIA tags.`);for(let O of s){let Q=O.attributes.get("group-id"),ge=O.attributes.get("type");if(Q!==I||ge.toLowerCase()!=="audio")continue;let be=O.attributes.get("channels")??d.attributes.get("channels"),J=be!==null?Number(be.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:Rc(O.attributes),autoselect:Rc(O.attributes)||kg(O.attributes),languageCode:xg(O.attributes.get("language")),lineNumber:O.lineNumber,fullPath:O.fullPath??d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:O.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:J!==null&&Number.isInteger(J)&&J>0?J:null}})}}}}}return f})),l=[],u=d=>{let h=l.find(f=>f.fullPath===d.fullPath&&f.info.type===d.info.type);h?(h.pairingMask|=d.pairingMask,h.default||=d.default,h.autoselect||=d.autoselect,h.lineNumber=Math.min(h.lineNumber,d.lineNumber),d.peakBitrate!==null&&(h.peakBitrate=Math.max(h.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(h.averageBitrate=Math.max(h.averageBitrate??-1/0,d.averageBitrate)),h.languageCode===Ge&&(h.languageCode=d.languageCode)):(d.id=l.length+1,l.push(d))};for(let d of c)for(let h of d)u(h);l.sort((d,h)=>d.lineNumber-h.lineNumber),this.trackBackings=[];for(let d of l)d.info.type==="video"?this.trackBackings.push(new Oc(d)):this.trackBackings.push(new Lc(d));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),w(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(i=>i.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),t=new ha(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return vc}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Dc=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,i=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(i.length===1)t=i[0];else if(this instanceof Oc){for(let s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}else{w(this instanceof Lc);for(let s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...dt,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){w(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},Oc=class extends Dc{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Fr(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},Lc=class extends Dc{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Fr(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},Rc=r=>{let e=r.get("default");if(e===null)return!1;let t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},kg=r=>{let e=r.get("autoselect");if(e===null)return!1;let t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},xg=r=>{if(r===null)return Ge;let e=r.split("-")[0];return e||Ge};var Mt=class{constructor(){this._isIsobmff=!1}},fa=class extends Mt{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);let n=We(t,4);return n!=="ftyp"&&n!=="styp"?null:We(t,4)}_createDemuxer(e){return new ac(e)}},Uc=class extends fa{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!=="qt ";let n=e._reader.requestSlice(4,4);if(n instanceof Promise&&(n=await n),!n)return!1;let i=We(n,4);return i==="moof"||i==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}},zc=class extends fa{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},ma=class extends Mt{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,Zt);if(n instanceof Promise&&(n=await n),!n)return!1;let i=Ru(n);if(i===null||i<1||i>8||Ce(n,i)!==z.EBML)return!1;let a=Bu(n);if(typeof a!="number")return!1;let o=e._reader.requestSlice(n.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;let c=n.filePos;for(;o.filePos<=c+a-Et;){let l=Jt(o);if(!l)break;let{id:u,size:d}=l,h=o.filePos;if(d===void 0)return!1;switch(u){case z.EBMLVersion:if(Ce(o,d)!==1)return!1;break;case z.EBMLReadVersion:if(Ce(o,d)!==1)return!1;break;case z.DocType:if(fn(o,d)!==t)return!1;break;case z.DocTypeVersion:if(Ce(o,d)>4)return!1;break}o.filePos=h+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new pc(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Nc=class extends ma{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Vc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,mt);if(d instanceof Promise&&(d=await d),!d)break;let h=It(d);if(!h)break;t=d.filePos+h.size}let n=await ra(e._reader,t,t+4096);if(!n)return!1;let i=n.header,s=qo(i.mpegVersionId,i.channel),a=e._reader.requestSlice(n.startPos+s,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=K(a);if(o===Ho||o===Wo)return!0;t=n.startPos+n.header.totalSize;let l=await ra(e._reader,t,t+4);if(!l)return!1;let u=l.header;return!(i.channel!==u.channel||i.sampleRate!==u.sampleRate)}_createDemuxer(e){return new yc(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Hc=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=We(t,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(t.skip(4),We(t,4)==="WAVE")}_createDemuxer(e){return new bc(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Wc=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?We(t,4)==="OggS":!1}_createDemuxer(e){return new wc(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},qc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,mt);if(i instanceof Promise&&(i=await i),!i)break;let s=It(i);if(!s)break;t=i.filePos+s.size}let n=e._reader.requestSlice(t,4);return n instanceof Promise&&(n=await n),n?We(n,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new xc(e)}},jc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,mt);if(a instanceof Promise&&(a=await a),!a)break;let o=It(a);if(!o)break;t=a.filePos+o.size}let n=e._reader.requestSliceRange(t,Nn,er);if(n instanceof Promise&&(n=await n),!n)return!1;let i=tr(n);if(!i||(t+=i.frameLength,n=e._reader.requestSliceRange(t,Nn,er),n instanceof Promise&&(n=await n),!n))return!1;let s=tr(n);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new kc(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Gc=class extends Mt{async _canReadInput(e){let t=205,n=e._reader.requestSlice(0,t);if(n instanceof Promise&&(n=await n),!n)return!1;let i=ie(n,t);return i[0]===71&&i[188]===71||i[0]===71&&i[204]===71?!0:i[4]===71&&i[196]===71}_createDemuxer(e){return new Sc(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},Qi=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||!(We(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof Ot))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new Bc(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return vc}},Kc=new Uc,Sg=new zc,Tg=new ma,vg=new Nc,Ag=new Vc,_g=new Hc,Cg=new Wc,Pg=new jc,Eg=new qc,Ig=new Gc,Mg=new Qi,cd=[Mg,Kc,Sg,Tg,vg,_g,Cg,Eg,Ag,Pg,Ig];var Fg=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(r.hls!==void 0){if(!r.hls||typeof r.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(r.hls.offsetTimestampsByDateTime!==void 0&&typeof r.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var lT=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},uT=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});Ei();var Rg=-1/0,Bg=-1/0,ba=null;typeof FinalizationRegistry<"u"&&(ba=new FinalizationRegistry(r=>{let e=performance.now();r.type==="video"?(e-Rg>=1e3&&(we._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."),Rg=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-Bg>=1e3&&(we._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."),Bg=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var jr=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},ld=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],dT=new Set(ld),rr=class r{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!dT.has(t.format))throw new TypeError("init.format must be one of: "+ld.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let i of t.layout){if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(i.offset)||i.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(i.stride)||i.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&Su(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=t._doNotCopy?Ye(e):Ye(e).slice(),this._layout=t.layout??mT(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;let n=t.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new wa(n),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");t?.visibleRect!==void 0&&Su(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new wa(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new r(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*ur),duration:Math.trunc((t.duration??0)*ur)||void 0}),t);let n=0,i=0;if("naturalWidth"in e?(n=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,i=e.videoHeight):"width"in e&&(n=Number(e.width),i=Number(e.height)),!n||!i)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(n,i),a=s.getContext("2d",{alpha:zs(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n,height:i},this.squarePixelWidth=n,this.squarePixelHeight=i,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new wa({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof jr){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!ld.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=Dn({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),ba?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return w(this._data!==null),this._data instanceof jr?new r(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):ga(this._data)?new r(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(w(this._layout),new r(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(ba?.unregister(this),this._data instanceof jr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ga(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Og(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.");return ga(this._data)?this._data.allocationSize(e):Lg(this,e).allocationSize}async copyTo(e,t={}){if(!_i(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Og(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(w(this._data!==null),ga(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof jr){let l={stack:[],error:void 0,hasError:!1};try{let u=lT(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof r))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(u.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${u.format}' instead.`);return await u.copyTo(e,t)}catch(u){l.error=u,l.hasError=!0}finally{uT(l)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let l=this.toVideoFrame(),u=await l.copyTo(e,t);return l.close(),u}let n=Lg(this,t);w(this.format);let i=Ye(e);if(i.byteLength<n.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${n.allocationSize}, Available: ${i.byteLength}`);let s=Xc(this.format),a;if(this._data instanceof jr){let l=this._data.getDataPlanes();if(l instanceof Promise&&(l=await l),!Array.isArray(l)||l.some(u=>!(u.data instanceof Uint8Array)||!Number.isInteger(u.stride)||u.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=l}else if(this._data instanceof Uint8Array)w(this._layout),w(this._layout.length===s.length),a=this._layout.map((l,u)=>{let d=Math.ceil(this.codedHeight/s[u].heightDivisor);return{data:this._data.subarray(l.offset,l.offset+l.stride*d),stride:l.stride}});else{let u=this._data.getContext("2d");w(u);let d=u.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:Ye(d.data),stride:4*this.codedWidth}]}let o=[],c=s.length;for(let l=0;l<c;l++){let u=n.computedLayouts[l],d=a[l].stride,h=a[l].data,f=u.sourceTop*d;f+=u.sourceLeftBytes;let p=u.destinationOffset,m=u.sourceWidthBytes,g={offset:p,stride:u.destinationStride};for(let y=0;y<u.sourceHeight;y++){if(f+m>h.byteLength)throw new Error("Source buffer OOB read.");if(p+m>i.byteLength)throw new Error("Destination buffer OOB write.");let b=h.subarray(f,f+m);i.set(b,p),f+=d,p+=u.destinationStride}o.push(g)}if(t.format!==void 0){let l=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),u=this.format.includes("X")&&t.format.includes("A");if(l||u)for(let d=0;d<n.allocationSize;d+=4){if(l){let h=i[d],f=i[d+2];i[d]=f,i[d+2]=h}u&&(i[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(w(this._data!==null),this._data instanceof jr){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let e=this._data.getDataPlanes();if(e instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let t=e.reduce((a,o)=>a+o.data.byteLength,0),n=new Uint8Array(t),i=0,s=[];for(let a of e)n.set(a.data,i),s.push(i),i+=a.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ga(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,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,i,s,a,o,c,l){let u=0,d=0,h=this.displayWidth,f=this.displayHeight,p=0,m=0,g=this.displayWidth,y=this.displayHeight;if(a!==void 0?(u=t,d=n,h=i,f=s,p=a,m=o,c!==void 0?(g=c,y=l):(g=h,y=f)):(p=t,m=n,i!==void 0&&(g=i,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(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<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(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:h,sHeight:f}=this._rotateSourceRegion(u,d,h,f,this.rotation));let b=this.toCanvasImageSource();e.save();let k=p+g/2,T=m+y/2;e.translate(k,T),e.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:g/y;e.scale(1/S,S),e.drawImage(b,u,d,h,f,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&ka(t.crop,"options.");let n=e.canvas.width,i=e.canvas.height,s=t.rotation??this.rotation,[a,o]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=t.crop;c&&(c=ud(c,a,o));let l,u,d,h,{sx:f,sy:p,sWidth:m,sHeight:g}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,s);if(t.fit==="fill")l=0,u=0,d=n,h=i;else{let[b,k]=t.crop?[t.crop.width,t.crop.height]:[a,o],T=t.fit==="contain"?Math.min(n/b,i/k):Math.max(n/b,i/k);d=b*T,h=k*T,l=(n-d)/2,u=(i-h)/2}e.save();let y=s%180===0?1:d/h;e.translate(n/2,i/2),e.rotate(s*Math.PI/180),e.scale(1/y,y),e.translate(-n/2,-i/2),e.drawImage(this.toCanvasImageSource(),f,p,m,g,l,u,d,h),e.restore()}_rotateSourceRegion(e,t,n,i,s){return s===90?[e,t,n,i]=[t,this.squarePixelHeight-e-n,i,n]:s===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-i]:s===270&&([e,t,n,i]=[this.squarePixelWidth-t-i,e,i,n]),{sx:e,sy:t,sWidth:n,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(w(this._data!==null),this._data instanceof jr||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&ka(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let t=Ai(this.rotation+(e.rotate??0)),[n,i]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=e.crop;s&&(s=ud(s,n,i));let a=s?s.width:n,o=s?s.height:i,c=a/o,l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=o),l=Us(l,e.roundDimensionsTo??1),u=Us(u,e.roundDimensionsTo??1);let d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:s??{left:0,top:0,width:n,height:i},alpha:e.alpha??"keep"};for(let m of hT){let g=m(this,d);if(g instanceof Promise&&(g=await g),g!==null)return g}let h=null,f=!1;for(let m of pa)if(m.canvas.width===d.width&&m.canvas.height===d.height){h=m.canvas,m.age=Dg++;break}if(h===null){if(typeof OffscreenCanvas<"u")h=new OffscreenCanvas(d.width,d.height);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");h=document.createElement("canvas"),h.width=d.width,h.height=d.height}f=!0,pa.length>=fT&&pa.splice(Mi(pa,m=>m.age),1),pa.push({canvas:h,age:Dg++})}let p=h.getContext("2d",{alpha:!0});if(!p)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return d.alpha==="discard"?(p.fillStyle="black",p.fillRect(0,0,d.width,d.height)):f||p.clearRect(0,0,d.width,d.height),this.drawWithFit(p,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new r(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}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}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}},hT=[];var fT=3,pa=[],Dg=0,wa=class{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let t=Object.keys(_r);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);let n=Object.keys(Cr);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(", ")}.`);let i=Object.keys(Pr);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}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}}},ga=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,ud=(r,e,t)=>{let n=Math.min(r.left,e),i=Math.min(r.top,t),s=Math.min(r.width,e-n),a=Math.min(r.height,t-i);return w(s>=0),w(a>=0),{left:n,top:i,width:s,height:a}},ka=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Og=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},mT=(r,e,t)=>{let n=Xc(r),i=[],s=0;for(let a of n){let o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),l=o*a.sampleBytes,u=l*c;i.push({offset:s,stride:l}),s+=u}return i},Xc=r=>{let e=(t,n,i,s,a)=>{let o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:i,heightDivisor:s},{sampleBytes:n,widthDivisor:i,heightDivisor:s}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ct(r),w(!1)}},Lg=(r,e)=>{let t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},n=e.rect,i=pT(t,n,r.codedWidth,r.codedHeight,r.format),s=e.layout,a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return yT(i,a,s)},pT=(r,e,t,n,i)=>{let s={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>n)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!gT(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},gT=(r,e)=>{if(r===null)return!0;let t=Xc(r);for(let n=0;n<t.length;n++){let i=t[n],s=i.widthDivisor,a=i.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},yT=(r,e,t)=>{let n=Xc(e),i=n.length;if(t!==void 0&&t.length!==i)throw new TypeError(`Layout must have ${i} planes.`);let s=0,a=[],o=[];for(let c=0;c<i;c++){let l=n[c],u=l.sampleBytes,d=l.widthDivisor,h=l.heightDivisor,f={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(f.sourceTop=Math.ceil(Math.trunc(r.y||0)/h),f.sourceHeight=Math.ceil(Math.trunc(r.height||0)/h),f.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*u,f.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*u,t!==void 0){let g=t[c];if(g.stride<f.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);f.destinationOffset=g.offset,f.destinationStride=g.stride}else f.destinationOffset=s,f.destinationStride=f.sourceWidthBytes;let m=f.destinationStride*f.sourceHeight+f.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),s=Math.max(s,m);for(let g=0;g<c;g++){let y=a[g];if(!(o[c]<=y.destinationOffset||o[g]<=f.destinationOffset))throw new TypeError("Planes overlap.")}a.push(f)}return{allocationSize:s,computedLayouts:a}},$c=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),qn=class{constructor(){this._referenceCount=0}},mr=class r{get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}constructor(e){if(this._closed=!1,ya(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 instanceof qn){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!$c.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!$c.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let t=e.data.byteLength/(yn(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let i=this.numberOfFrames*this.numberOfChannels*yn(this.format);if(n.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}ba?.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&&!$c.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let i=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(i>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let s=yn(t),a=jn(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?i:i*this.numberOfChannels)*s}copyTo(e,t){if(!_i(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!$c.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{format:n,frameCount:i,frameOffset:s}=t,{planeIndex:a}=t,o=this.format,c=n??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");let h=i!==void 0?i:l-d;if(h>l-d)throw new RangeError("frameCount out of range");let f=yn(c),p=jn(c);if(p&&a>=u)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");let g=(p?h:h*u)*f;if(e.byteLength<g)throw new RangeError("Destination buffer is too small");let y=ve(e),b=zg(c);if(ya(this._data))sn()&&u>2&&c!==o?wT(this._data,y,o,c,u,a,d,h):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:h,format:c});else{let k=Ug(o),T=yn(o),S=jn(o),_;if(this._data instanceof qn){let P=A=>{let F=this._data.getDataPlane(A);if(!(F instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let I=l*T*(S?1:u);if(F.byteLength!==I)throw new TypeError(`Data plane ${A} has invalid size. Expected exactly ${I} bytes, got ${F.byteLength} bytes.`);return F};if(S)if(p)_=P(a),a=0;else{_=new Uint8Array(l*T*u);for(let A=0;A<u;A++){let F=P(A);_.set(F,A*l*T)}}else _=P(0)}else _=this._data;let M=ve(_);for(let P=0;P<h;P++)if(p){let A=P*f,F;S?F=(a*l+(P+d))*T:F=((P+d)*u+a)*T;let I=k(M,F);b(y,A,I)}else for(let A=0;A<u;A++){let I=(P*u+A)*f,O;S?O=(A*l+(P+d))*T:O=((P+d)*u+A)*T;let Q=k(M,O);b(y,I,Q)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof qn){let e=new r(this._data);return e.setTimestamp(this.timestamp),e}else if(ya(this._data)){let e=new r(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endSample must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startSample out of range.");if(t>this.numberOfFrames)throw new RangeError("endSample out of range.");if(t<e)throw new RangeError("endSample must not be less than startSample.");if(this._closed)throw new Error("AudioSample is closed.");let n=t-e,i=yn(this.format),s;if(jn(this.format)){let a=n*i;if(s=new Uint8Array(a*this.numberOfChannels),n>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(s.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:n})}else s=new Uint8Array(n*this.numberOfChannels*i),n>0&&this.copyTo(s,{planeIndex:0,format:this.format,frameOffset:e,frameCount:n});return new r({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(ba?.unregister(this),this._data instanceof qn?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ya(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof qn?this._createAudioDataFromData():ya(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():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()})}_createAudioDataFromData(){if(jn(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(n/i),c=0,l=a;for(;l>0;){let u=Math.min(o,l),d=new Float32Array(i*u);for(let h=0;h<i;h++)e.copyFromChannel(d.subarray(h*u,(h+1)*u),h,c);yield new r({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:i,timestamp:t+c/s,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(n/i),c=0,l=a,u=[];for(;l>0;){let d=Math.min(o,l),h=new Float32Array(i*d);for(let p=0;p<i;p++)e.copyFromChannel(h.subarray(p*d,(p+1)*d),p,c);let f=new r({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:i,timestamp:t+c/s,data:h});u.push(f),c+=d,l-=d}return u}},yn=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},jn=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ug=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},zg=r=>{switch(r){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,Ze((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,Ze(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,Ze(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},ya=r=>typeof AudioData<"u"&&r instanceof AudioData,Ng=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},wT=(r,e,t,n,i,s,a,o)=>{let c=Ug(t),l=zg(n),u=yn(t),d=yn(n),h=jn(t);if(jn(n))if(h){let p=new ArrayBuffer(o*u),m=ve(p);r.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++){let y=g*u,b=g*d,k=c(m,y);l(e,b,k)}}else{let p=new ArrayBuffer(o*i*u),m=ve(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++){let y=(g*i+s)*u,b=g*d,k=c(m,y);l(e,b,k)}}else if(h){let p=o*u,m=new ArrayBuffer(p),g=ve(m);for(let y=0;y<i;y++){r.copyTo(m,{planeIndex:y,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){let k=b*u,T=(b*i+y)*d,S=c(g,k);l(e,T,S)}}}else{let p=new ArrayBuffer(o*i*u),m=ve(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++)for(let y=0;y<i;y++){let b=g*i+y,k=b*u,T=b*d,S=c(m,k);l(e,T,S)}}},Vg=(r,e)=>{let t=r.allocationSize({format:e,planeIndex:0}),n=new ArrayBuffer(t);return r.copyTo(n,{format:e,planeIndex:0}),new mr({data:n,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};var Hg=new Map;var Wg=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!gt.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${gt.join(", ")}.`);if(!(r.bitrate instanceof Lt)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.crop!==void 0&&ka(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");qg(r.codec,r)},qg=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Fr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},dd=r=>{let e=r.bitrate instanceof Lt?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??op(r.codec,r.width,r.height,e),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:e,bitrateMode:r.bitrateMode,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...dp(r.codec)}},jg=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Vt.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${Vt.join(", ")}.`);if(r.bitrate===void 0&&!(ht.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(r.bitrate!==void 0&&!(r.bitrate instanceof Lt)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");bT(r.codec,r)},bT=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Fr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},Gg=r=>{let e=r.bitrate instanceof Lt?r.bitrate._toAudioBitrate(r.codec):r.bitrate;return{codec:r.fullCodecString??lp(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:e,bitrateMode:r.bitrateMode,...hp(r.codec)}},Lt=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,n){let i=t*n,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,c=Math.pow(i/a,.95),d=o*c*s[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(ht.includes(e)||e==="flac")return;let n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let i=n*this._factor;return e==="aac"?i=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-i)<Math.abs(a-i)?o:a):e==="opus"||e==="vorbis"?i=Math.max(6e3,i):e==="mp3"&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-i)<Math.abs(a-i)?o:a)),Math.round(i/1e3)*1e3}},Kg=new Lt(.3),$g=new Lt(.6),Xg=new Lt(1),Qg=new Lt(2),Yg=new Lt(4);var hd=async(r,e={})=>{let{width:t=1280,height:n=720,bitrate:i=1e6,...s}=e;if(!gt.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(n)||n<=0)throw new TypeError("height must be a positive integer.");if(!(i instanceof Lt)&&(!Number.isInteger(i)||i<=0))throw new TypeError("bitrate must be a positive integer or a quality.");qg(r,s);let a=dd({codec:r,width:t,height:n,bitrate:i,framerate:void 0,...s,alpha:"discard"}),o=JSON.stringify(a),c=Hg.get(o);if(c)return c;let l=(async()=>Qc.some(h=>h.supports(r,a))?!0:typeof VideoEncoder>"u"||(t%2===1||n%2===1)&&(r==="avc"||r==="hevc")||!(await VideoEncoder.isConfigSupported(a)).supported?!1:zs()?new Promise(async h=>{try{let f=new VideoEncoder({output:()=>{},error:()=>h(!1)});f.configure(a);let p=new Uint8Array(t*n*4),m=new VideoFrame(p,{format:"RGBA",codedWidth:t,codedHeight:n,timestamp:0});f.encode(m),m.close(),await f.flush(),h(!0)}catch{h(!1)}}):!0)();return Hg.set(o,l),l};var Yc=[],md=[],Qc=[],fd=[];var Zg=r=>{let n=r,i=4096,s=0,a=12,o=0;for(n<0&&(n=-n,s=128),n+=33,n>8191&&(n=8191);(n&i)!==i&&a>=5;)i>>=1,a--;return o=n>>a-4&15,~(s|a-5<<4|o)&255};var Jg=r=>{let t=2048,n=0,i=11,s=0,a=r;for(a<0&&(a=-a,n=128),a>4095&&(a=4095);(a&t)!==t&&i>=5;)t>>=1,i--;return s=a>>(i===4?1:i-4)&15,(n|i-4<<4|s)^85};var Gn=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},Yi=r=>{if(!Ii(r))throw new TypeError("timestamp must be a number.")},pd=(r,e,t)=>t.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let i=await r.determinePacketType(n);return i&&(n.type=i),n}):e,wn=class{constructor(e){if(!(e instanceof Zi))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Gn(e),this._track.input._disposed)throw new ut;return pd(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Gn(e);let t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Yi(e),Gn(t),this._track.input._disposed)throw new ut;return pd(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if(Gn(t),this._track.input._disposed)throw new ut;return pd(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Yi(e),Gn(t),this._track.input._disposed)throw new ut;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(w(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if(Gn(t),this._track.input._disposed)throw new ut;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(w(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof Oe))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof Oe))throw new TypeError("endPacket must be an EncodedPacket.");if(Gn(n),this._track.input._disposed)throw new ut;let i=[],{promise:s,resolve:a}=nt(),{promise:o,resolve:c}=nt(),l=!1,u=!1,d=null,h=[],f=()=>Math.max(2,h.length);(async()=>{let m=e??await this.getFirstPacket(n);for(;m&&!u&&!this._track.input._disposed&&!(t&&m.sequenceNumber>=t?.sequenceNumber);){if(i.length>f()){({promise:o,resolve:c}=nt()),await o;continue}i.push(m),a(),{promise:s,resolve:a}=nt(),m=await this.getNextPacket(m,n)}l=!0,a()})().catch(m=>{d||(d=m,a())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new ut;if(u)return{value:void 0,done:!0};if(d)throw d;if(i.length>0){let m=i.shift(),g=performance.now();for(h.push(g);h.length>0&&g-h[0]>=1e3;)h.shift();return c(),{value:m,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}},gd=class{constructor(e,t){this.onSample=e,this.onError=t}},Zc=class{mediaSamplesInRange(e=-1/0,t=1/0,n){Yi(e),Yi(t);let i=[],s=!1,a=null,{promise:o,resolve:c}=nt(),{promise:l,resolve:u}=nt(),d=!1,h=!1,f=!1,p=null,m={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let b=await this._createDecoder(P=>{if(u(),P.timestamp>=t&&(h=!0),h){P.close();return}a&&(P.timestamp>e?(i.push(a),s=!0):a.close()),P.timestamp>=e&&(i.push(P),s=!0),a=s?null:P,i.length>0&&(c(),{promise:o,resolve:c}=nt())},P=>{p||(p=P,c())}),k=this._createPacketSink(),T=await k.getKeyPacket(e,m)??await k.getFirstKeyPacket(m),S=T,M=k.packets(T??void 0,void 0,m);for(await M.next();S&&!h&&!this._track.input._disposed;){let P=e0(i.length);if(i.length+b.getDecodeQueueSize()>P){({promise:l,resolve:u}=nt()),await l;continue}b.decode(S);let A=await M.next();if(A.done)break;S=A.value}await M.return(),!f&&!this._track.input._disposed&&await b.flush(),b.close(),!s&&a&&i.push(a),d=!0,c()})().catch(b=>{p||(p=b,c())});let g=this._track,y=()=>{a?.close();for(let b of i)b.close()};return{async next(){for(;;){if(g.input._disposed)throw y(),new ut;if(f)return{value:void 0,done:!0};if(p)throw y(),p;if(i.length>0){let b=i.shift();return u(),{value:b,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,h=!0,u(),c(),y(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){Km(e);let n=Gm(e),i=[],s=[],{promise:a,resolve:o}=nt(),{promise:c,resolve:l}=nt(),u=!1,d=!1,h=null,f=y=>{s.push(y),o(),{promise:a,resolve:o}=nt()},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let y=await this._createDecoder(P=>{if(l(),d){P.close();return}let A=0;for(;i.length>0&&P.timestamp-i[0]>-1e-10;)A++,i.shift();if(A>0)for(let F=0;F<A;F++)f(F<A-1?P.clone():P);else P.close()},P=>{h||(h=P,o())}),b=this._createPacketSink(),k=null,T=null,S=-1,_=async()=>{w(T);let P=T;for(y.decode(P);P.sequenceNumber<S;){let A=e0(s.length);for(;s.length+y.getDecodeQueueSize()>A&&!d;)({promise:c,resolve:l}=nt()),await c;if(d)break;let F=await b.getNextPacket(P,p);w(F),y.decode(F),P=F}S=-1},M=async()=>{await y.flush();for(let P=0;P<i.length;P++)f(null);i.length=0};for await(let P of n){if(Yi(P),d||this._track.input._disposed)break;let A=await b.getPacket(P,p),F=A&&await b.getKeyPacket(P,p);if(!F){S!==-1&&(await _(),await M()),f(null),k=null;continue}k&&(F.sequenceNumber!==T.sequenceNumber||A.timestamp<k.timestamp)&&(await _(),await M()),i.push(A.timestamp),S=Math.max(A.sequenceNumber,S),k=A,T=F}!d&&!this._track.input._disposed&&(S!==-1&&await _(),await M()),y.close(),u=!0,o()})().catch(y=>{h||(h=y,o())});let m=this._track,g=()=>{for(let y of s)y?.close()};return{async next(){for(;;){if(m.input._disposed)throw g(),new ut;if(d)return{value:void 0,done:!0};if(h)throw g(),h;if(s.length>0){let y=s.shift();return w(y!==void 0),l(),{value:y,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),g(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}},e0=r=>r===0?40:8,yd=class extends gd{constructor(e,t,n,i,s,a){super(e,t),this.codec=n,this.decoderConfig=i,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new rn,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.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.frameHandlerSerializer=new rn;let o=Yc.find(c=>c.supports(n,i));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof rr))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=u=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();w(d!==void 0),await this.mergeAlpha(u,d)}else this.colorQueue.push(u)}).catch(d=>this.onError(d))};if(n==="avc"&&this.decoderConfig.description&&Ns()){let u=Tp(Ye(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){let d=Xs(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(w(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(w(this.decoder),sn()||bu(this.inputTimestamps,e.timestamp,t=>t),Ns()&&this.currentPacketIndex===0){if(this.codec==="avc"){let t=[];for(let i of Cu(e.data,this.decoderConfig)){let s=Oi(e.data[i.offset]);s===lt.AUD&&(t.length=0),s>=20&&s<=31||t.push(e.data.subarray(i.offset,i.offset+i.length))}let n=xp(t,this.decoderConfig);e=new Oe(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){let t=_p(e.data,this.decoderConfig);t&&(e=new Oe(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new Jc),!this.alphaDecoder){let n=s=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){let a=this.colorQueue.shift();w(a!==void 0),await this.mergeAlpha(a,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 a=this.colorQueue.shift();w(a!==void 0),await this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(a=>this.onError(a))},i=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(s)}catch(a){this.onError(a)}},error:s=>{s.stack=i,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=dn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of $s(e,this.decoderConfig)){let n=ln(e[t.offset]);if(n===it.RASL_N||n===it.RASL_R)return!0}return!1}sampleHandler(e){if(sn()){if(this.sampleQueue.length>0&&e.timestamp>=Ne(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}bu(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();w(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){if(!t){let s=new rr(e);this.sampleHandler(s);return}w(this.merger);let n=await this.merger.update(e,t),i=new rr(n);this.sampleHandler(i)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(w(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await this.frameHandlerSerializer.currentPromise,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),sn()){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()):(w(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}},t0=!1,Jc=class r{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let e=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!r.forceCpu&&e&&!t0)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let t=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!t)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=t,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)}catch(t){this.gl=null,this.canvas=null,t0=!0,we._warn("Falling back to CPU for color/alpha merging.",t)}}async update(e,t){return this.gl?this.updateGpu(e,t):this.updateCpu(e,t)}createProgram(){w(this.gl);let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
1871
|
+
${n}`),this.frame=e,this.failures=t}};async function pu(r){let{scale:e=1,frame:t,project:n}=r,i=r,{renderContext:s,storageAdapter:a}=i;if(n.tracks.length===0)throw new Error("The project has no tracks to render.");s.pixelRatio=e;let{store:o,precomper:c,stateEvaluator:l,measurer:u,loads:d}=Zm(r),h=Ym(a);try{let{totalFrames:f}=c.result(),p=t.kind==="first"?0:t.kind==="last"?f-1:t.frame,m=Math.max(0,Math.min(f-1,Math.floor(p))),g=c.ensureCovering(m);ep(o,g,m);let y=d.manager=new $m(g,a,new Ls);return await Jm(o,y,Xm(o.spans,m).map(b=>b.id)),await y.loadAt(m),l.stateAt(m),l.layout(u),await Qm(i,()=>l.render(s),m),{frame:m,totalFrames:f}}finally{h(),l.dispose(),o.dispose()}}function ep(r,e,t,n=t){let i=new Map(e.buildErrors.filter(s=>r.failed(s.trackId)).map(s=>[s.trackId,s]));if(i.size!==0)for(let s=t;s<=n;s++){let a=Xm(r.spans,s);if(a.length>0&&a.every(o=>i.has(o.id)))throw new Us(s,a.map(o=>i.get(o.id)))}}var at=null,tp=!0,vi=new Map,Oo=64,Lo=4096;function jx(r,e){let t=new r.WebGLRenderer({antialias:e,alpha:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!0});return t.setClearColor(0,0),t.setPixelRatio(1),Lo=t.capabilities.maxTextureSize??Lo,t}function rp(r,e){return at&&tp!==e&&(at.dispose(),at.forceContextLoss(),at=null),at||(at=jx(r,e),tp=e,vi.clear()),at}function Kx(r,e,t){let n={width:Math.min(Lo,Math.max(1,Math.ceil(e/Oo)*Oo)),height:Math.min(Lo,Math.max(1,Math.ceil(t/Oo)*Oo))},i=vi.get(r);if(!i)return vi.set(r,n),n;let s={width:Math.max(i.width,n.width),height:Math.max(i.height,n.height)};return(s.width!==i.width||s.height!==i.height)&&vi.set(r,s),s}function $x(r,e,t,n,i,s,a={}){let o=rp(r,a.antialias!==!1),c=Kx(e,i,s),l=o.getSize(new r.Vector2);return(l.x!==c.width||l.y!==c.height)&&o.setSize(c.width,c.height,!1),o.render(t,n),{source:o.domElement,width:c.width,height:c.height}}function Xx(r,e){at&&(at.shadowMap.enabled!==e.shadowsEnabled&&(at.shadowMap.enabled=e.shadowsEnabled,at.shadowMap.needsUpdate=!0),at.shadowMap.type!==e.shadowType&&(at.shadowMap.type=e.shadowType,at.shadowMap.needsUpdate=!0),at.toneMapping=e.toneMapping,at.toneMappingExposure=e.toneMappingExposure)}function Qx(){return at}function Yx(){at?.dispose(),at?.forceContextLoss(),at=null,vi.clear()}function Zx(r){vi.delete(r)}var Jx={prepare:(r,e)=>{rp(r,e.antialias!==!1)},render:$x,applySettings:Xx,active:Qx,forgetBuffer:Zx,dispose:Yx};function np(){Al(),Rl(Jx)}var cr=class extends Do{constructor(e,t){super(e,t),np()}mount(e){let t=this.canvasKit.MakeWebGLCanvasSurface(e);if(!t)throw new Error("Failed to create CanvasKit surface");this.attach(t)}unmount(){this.detach()}screenshot(e="image/png",t){let n=this.snapshotPixels();if(!n)return;let{pixels:i,width:s,height:a}=n,o=document.createElement("canvas");o.width=s,o.height=a;let c=o.getContext("2d");if(c)return c.putImageData(new ImageData(new Uint8ClampedArray(i),s,a),0,0),o.toDataURL(e,t)}};import{StorageAdapter as gv}from"@motionscript/core";function w(r){if(!r)throw new Error("Assertion failed.")}var _i=r=>{let e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},ze=r=>r&&r[r.length-1],_r=r=>r>=0&&r<2**32,Y=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},lr=r=>{let e=Y(r);return(e&1)===0?-(e>>1):e+1>>1};var Ye=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),Ae=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),ot=new TextDecoder,_t=new TextEncoder;var ku=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Cr={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Mn=ku(Cr),Pr={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Fn=ku(Pr),Er={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Rn=ku(Er),ip=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,Ci=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r),vt=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(i=>{let s=!1;e=()=>{s||(i(),this.pending--,s=!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},sp=/^[0-9a-fA-F]+$/,sn=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),ap=r=>{w(r.length%2===0);let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},Su=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Ir=(r,e,t)=>{let n=0,i=r.length-1,s=-1;for(;n<=i;){let a=n+i>>1,o=t(r[a]);o===e?(s=a,i=a-1):o<e?n=a+1:i=a-1}return s},_e=(r,e,t)=>{let n=0,i=r.length-1,s=-1;for(;n<=i;){let a=n+(i-n+1)/2|0;t(r[a])<=e?(s=a,n=a+1):i=a-1}return s},xu=(r,e,t)=>{let n=_e(r,t(e),t);r.splice(n+1,0,e)},nt=()=>{let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}},op=(r,e)=>{let t=r.indexOf(e);t!==-1&&r.splice(t,1)},Tu=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Pi=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},cp=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},lp=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},Ct=r=>{throw new Error(`Unexpected value: ${r}`)},Ns=(r,e,t)=>{let n=r.getUint8(e),i=r.getUint8(e+1),s=r.getUint8(e+2);return t?n|i<<8|s<<16:n<<16|i<<8|s};var zs=(r,e,t,n)=>{t=t>>>0,t=t&16777215,n?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},up=(r,e,t,n)=>{t=Ze(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),zs(r,e,t,n)};var Ze=(r,e,t)=>Math.max(e,Math.min(t,r)),je="und",Mr=r=>{let e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Vs=(r,e)=>Math.round(r/e)*e,Bn=(r,e)=>Math.round(r*e)/e,No=(r,e)=>Math.floor(r/e)*e,Au=(r,e)=>Math.floor(r*e)/e,dp=r=>{let e=0;for(;r;)e++,r>>=1;return e},eT=/^[a-z]{3}$/,Ei=r=>eT.test(r),ur=1e6*(1+Number.EPSILON),hp=(r,e)=>{let t={...r,...e};if(r.headers||e.headers){let n=r.headers?Uo(r.headers):{},i=e.headers?Uo(e.headers):{},s={...n};Object.entries(i).forEach(([a,o])=>{let c=Object.keys(s).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),t.headers=s}return t},Uo=r=>{if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}if(Array.isArray(r)){let e={};return r.forEach(([t,n])=>{e[t]=n}),e}return r},fp=async(r,e,t,n,i)=>{let s=0;for(;;)try{return await r(e,t)}catch(a){if(i())throw a;s++;let o=n(s,a,e);if(o===null)throw a;if(we._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await js(1e3*o),i())throw a}},mp=(r,e)=>{let t=r<0?-1:1;r=Math.abs(r);let n=0,i=1,s=1,a=0,o=r;for(;;){let c=Math.floor(o),l=c*s+n,u=c*a+i;if(u>e)return{num:t*s,den:a};if(n=s,i=a,s=l,a=u,o=1/(o-c),!isFinite(o))break}return{num:t*s,den:a}},nn=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},gu=null,an=()=>gu!==null?gu:gu=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),yu=null,Hs=()=>yu!==null?yu:yu=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),wu=null,Ws=()=>wu!==null?wu:wu=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),bu=null,pp=()=>{if(bu!==null)return bu;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?bu=Number(r[1]):null},Dn=(r,e)=>r!==-1?r:e,zo=(r,e,t,n)=>r<=n&&t<=e,qs=function*(r){for(let e in r){let t=r[e];t!==void 0&&(yield{key:e,value:t})}};var Gs=r=>{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t};var gp=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},Ii=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Mi=r=>typeof r=="number"&&!Number.isNaN(r),dr=(r,e)=>{if(e.includes("://"))return e;if(r.includes("://")){let o=r.indexOf("?");o!==-1&&(r=r.slice(0,o))}let t;if(e.startsWith("/")){let o=r.indexOf("://");if(o===-1)t=e;else{let c=r.indexOf("/",o+3);c===-1?t=r+e:t=r.slice(0,c)+e}}else{let o=r.lastIndexOf("/");o===-1?t=e:t=r.slice(0,o+1)+e}let n="",i=t.indexOf("://");if(i!==-1){let o=t.indexOf("/",i+3);o!==-1&&(n=t.slice(0,o),t=t.slice(o))}let s=t.split("/"),a=[];for(let o of s)o===".."?a.pop():o!=="."&&a.push(o);return n+a.join("/")},On=(r,e)=>{let t=0;for(let n=0;n<r.length;n++)e(r[n])&&t++;return t},Fi=(r,e)=>{let t=-1,n=1/0;for(let i=0;i<r.length;i++){let s=e(r[i]);s<n&&(n=s,t=i)}return t};var Ln=r=>{w(Number.isInteger(r.num)),w(Number.isInteger(r.den)),w(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){let i=e%t;e=t,t=i}let n=e||1;return{num:r.num/n,den:r.den/n}},vu=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};var js=r=>new Promise(e=>setTimeout(e,r));var _u=r=>Array.isArray(r)?r:[r],Vt=class{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);let i={fn:t,once:n?.once??!1};return this._listeners.get(e).add(i),()=>{this._listeners.get(e)?.delete(i)}}_emit(...e){let[t,n]=e,i=this._listeners.get(t);if(i)for(let s of i){try{s.fn(n)}catch(a){console.error(a)}s.once&&i.delete(s)}}};var Cu=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");var hr;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(hr||(hr={}));var we=class r{constructor(){}static get level(){return r._level}static set level(e){if(e!==hr.Silent&&e!==hr.Errors&&e!==hr.Warnings&&e!==hr.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");r._level=e}static get _emitter(){return r._emitterInstance??=new Vt}static on(e,t,n){return r._emitter.on(e,t,n)}static _error(...e){r._emitter._emit("error",e),r._level>=hr.Errors&&console.error(...e)}static _warn(...e){r._emitter._emit("warn",e),r._level>=hr.Warnings&&console.warn(...e)}static _info(...e){r._emitter._emit("info",e),r._level>=hr.Info&&console.info(...e)}};we._level=hr.Info;we._emitterInstance=null;var $t=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}},Ks=class{constructor(e,t,n,i){if(this.data=e,this.mimeType=t,this.name=n,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("description, when provided, must be a string.")}},yp=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof $t)&&!(e instanceof Ks)&&!Cu(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}};var dt={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},wp=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var Ie=class r{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),i=(t&1<<n)>>n;return this.pos++,i}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let i=this.pos;i<n;i++){let s=Math.floor(i/8),a=this.bytes[s],o=7-(i&7);a&=~(1<<o),a|=(t&1<<n-i-1)>>n-i-1<<o,this.bytes[s]=a}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new r(this.bytes);return e.pos=this.pos,e}};var fr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],on=[-1,1,2,3,4,5,6,8],Ri=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new Ie(r),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let n=e.readBits(4),i=null;n===15?i=e.readBits(24):n<fr.length&&(i=fr[n]);let s=e.readBits(4),a=null;return s>=1&&s<=7&&(a=on[s]),{objectType:t,frequencyIndex:n,sampleRate:i,channelConfiguration:s,numberOfChannels:a}},Vo=r=>{let e=fr.indexOf(r.sampleRate),t=null;e===-1&&(e=15,t=r.sampleRate);let n=on.indexOf(r.numberOfChannels);if(n===-1)throw new TypeError(`Unsupported number of channels: ${r.numberOfChannels}`);let i=13;r.objectType>=32&&(i+=6),e===15&&(i+=24);let s=Math.ceil(i/8),a=new Uint8Array(s),o=new Ie(a);return r.objectType<32?o.writeBits(5,r.objectType):(o.writeBits(5,31),o.writeBits(6,r.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,t),o.writeBits(4,n),a};var gt=["avc","hevc","vp9","av1","vp8"],ht=["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"],Ho=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Ht=[...Ho,...ht],cn=["webvtt"],$s=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],bp=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Fr=[{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}],kp=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Sp=".01.01.01.01.00",xp=".0.110.01.01.01.0",Tp=(r,e,t,n)=>{if(r==="avc"){let s=Math.ceil(e/16)*Math.ceil(t/16),a=$s.find(d=>s<=d.maxMacroblocks&&n<=d.maxBitrate)??ze($s),o=a?a.level:0,c="64".padStart(2,"0"),l="00",u=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(r==="hevc"){let o=e*t,c=bp.find(u=>o<=u.maxPictureSize&&n<=u.maxBitrate)??ze(bp);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){let s=e*t;return`vp09.00.${(Fr.find(c=>s<=c.maxPictureSize&&n<=c.maxBitrate)??ze(Fr)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){let s=e*t,a=kp.find(l=>s<=l.maxPictureSize&&n<=l.maxBitrate)??ze(kp);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${r}'.`)};var Ap=r=>{let e=r.split("."),i=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(s<<5)+o,l=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,h=0,f=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,g=e[5]?Number(e[5][2]):0,y=(l<<7)+(d<<6)+(h<<5)+(f<<4)+(p<<3)+(m<<2)+g;return[i,c,y,0]},Bi=r=>{let{codec:e,codecDescription:t,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o}=r;if(e==="avc"){if(w(r.avcType!==null),i){let c=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${r.avcType}.${sn(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${sn(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,h,f;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,u=Su(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,h=s.generalLevelIdc,f=[...s.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let m=Ae(t),g=m.getUint8(1);c=g>>6&3,l=g&31,u=Su(m.getUint32(2)),d=g>>5&1,h=m.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(m.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=u.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=h;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(m=>m.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let y=r.width*r.height,b=ze(Fr).level;for(let k of Fr)if(y<=k.maxPictureSize){b=k.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}let c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),u=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),f=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),m=a.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${l}.${u}.${d}`;return g+=`.${h}.${f}.${p}.${m}`,g.endsWith(Sp)&&(g=g.slice(0,-Sp.length)),g}else if(e==="av1"){if(!o){let k=r.width*r.height,T=ze(Fr).level;for(let x of Fr)if(k<=x.maxPictureSize){T=x.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=o.profile,l=o.level.toString().padStart(2,"0"),u=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",f=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),p=n?.primaries?Cr[n.primaries]:1,m=n?.transfer?Pr[n.transfer]:1,g=n?.matrix?Er[n.matrix]:1,y=n?.fullRange?1:0,b=`av01.${c}.${l}${u}.${d}`;return b+=`.${h}.${f.toString().padStart(3,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${m.toString().padStart(2,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(xp)&&(b=b.slice(0,-xp.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)},vp=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(ht.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},Di=r=>{let{codec:e,codecDescription:t,aacCodecInfo:n}=r;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");if(n.isMpeg2)return"mp4a.67";{let i;return n.objectType!==null?i=n.objectType:i=Ri(t).objectType,`mp4a.40.${i}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&ht.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)};var Un=48e3,_p=/^pcm-([usf])(\d+)(be)?$/,Wt=r=>{if(w(ht.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=_p.exec(r);w(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let n=Number(e[2])/8,i=e[3]!=="be",s=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:n,littleEndian:i,silentValue:s}},Rr=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":r==="ulaw"?"ulaw":r==="alaw"?"alaw":_p.test(r)?r:r==="webvtt"?"webvtt":null,Cp=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},Pp=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},tT=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],rT=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,nT=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,iT=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,sT=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Ep=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!tT.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!Ci(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=r.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let t=Object.keys(Cr);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);let n=Object.keys(Pr);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let i=Object.keys(Er);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!rT.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!nT.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!iT.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")&&!sT.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},aT=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],Ip=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!aT.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!Ci(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!ht.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ht.join(", ")}).`)},Mp=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var oT=[44100,48e3,32e3],cT=[-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],Wo=1483304551,qo=1231971951,lT=(r,e,t,n,i)=>e===0?0:e===1?Math.floor(144*t/(n<<r))+i:e===2?Math.floor(144*t/n)+i:(Math.floor(12*t/n)+i)*4,Fp=(r,e,t,n)=>e===0?0:e===1?144*t/(n<<r):e===2?144*t/n:12*t/n*4,Go=(r,e)=>r===3?e===3?21:36:e===3?13:21,Qs=(r,e)=>{let t=r>>>24,n=r>>>16&255,i=r>>>8&255,s=r&255;if(t!==255&&n!==255&&i!==255&&s!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;n&16?a=n&8?0:1:(a=1,o=1);let c=n>>3&3,l=n>>1&3,u=i>>4&15,d=(i>>2&3)%3,h=i>>1&1,f=s>>6&3,p=s>>4&3,m=s>>3&1,g=s>>2&1,y=s&3,b=cT[a*16*4+l*16+u];if(b===-1)return{header:null,bytesAdvanced:1};let k=b*1e3,T=oT[d]>>a+o,x=lT(a,l,k,T,h);if(e!==null&&e<x)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:x,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:k,frequencyIndex:d,sampleRate:T,channel:f,modeExtension:p,copyright:m,original:g,emphasis:y,audioSamplesInFrame:v},bytesAdvanced:1}};var jo=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t},Xs;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(Xs||(Xs={}));var ln=r=>r===3?1:2;var Nn=[48e3,44100,32e3],Pu=[24e3,22050,16e3];var lt;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(lt||(lt={}));var it;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(it||(it={}));var Oi=function*(r){let e=0,t=-1;for(;e<r.length-2;){let n=r.indexOf(0,e);if(n===-1||n>=r.length-2)break;e=n;let i=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?i=4:r[e+1]===0&&r[e+2]===1&&(i=3),i===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+i,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},Dp=function*(r,e){let t=0,n=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let i;e===1?i=n.getUint8(t):e===2?i=n.getUint16(t,!1):e===3?i=Ns(n,t,!1):(w(e===4),i=n.getUint32(t,!1)),t+=e,yield{offset:t,length:i},t+=i}},Iu=(r,e)=>{if(e.description){let i=(Ye(e.description)[4]&3)+1;return Dp(r,i)}else return Oi(r)},Li=r=>r&31,Ko=r=>{let e=[],t=r.length;for(let n=0;n<t;n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e.push(0,0),n+=2):e.push(r[n]);return new Uint8Array(e)},Eu=new Uint8Array([0,0,0,1]),Op=r=>{let e=r.reduce((i,s)=>i+Eu.byteLength+s.byteLength,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(Eu,n),n+=Eu.byteLength,t.set(i,n),n+=i.byteLength;return t},$o=(r,e)=>{let t=r.reduce((s,a)=>s+e+a.byteLength,0),n=new Uint8Array(t),i=0;for(let s of r){let a=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:a.setUint8(i,s.byteLength);break;case 2:a.setUint16(i,s.byteLength,!1);break;case 3:zs(a,i,s.byteLength,!1);break;case 4:a.setUint32(i,s.byteLength,!1);break}i+=e,n.set(s,i),i+=s.byteLength}return n},Lp=(r,e)=>{if(e.description){let i=(Ye(e.description)[4]&3)+1;return $o(r,i)}else return Op(r)},Ui=r=>{try{let e=[],t=[],n=[];for(let o of Oi(r)){let c=r.subarray(o.offset,o.offset+o.length),l=Li(c[0]);l===lt.SPS?e.push(c):l===lt.PPS?t.push(c):l===lt.SPS_EXT&&n.push(c)}if(e.length===0||t.length===0)return null;let i=e[0],s=Zs(i);w(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(e){return we._error("Error building AVC Decoder Configuration Record:",e),null}},Up=r=>{let e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(let t of r.sequenceParameterSets){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}e.push(r.pictureParameterSets.length);for(let t of r.pictureParameterSets){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}if(r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144){w(r.chromaFormat!==null),w(r.bitDepthLumaMinus8!==null),w(r.bitDepthChromaMinus8!==null),w(r.sequenceParameterSetExt!==null),e.push(252|r.chromaFormat&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.sequenceParameterSetExt.length);for(let t of r.sequenceParameterSetExt){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}}return new Uint8Array(e)},Np=r=>{try{let e=Ae(r),t=0,n=e.getUint8(t++),i=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let f=0;f<c;f++){let p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}let u=e.getUint8(t++),d=[];for(let f=0;f<u;f++){let p=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+p)),t+=p}let h={configurationVersion:n,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&t+4<=r.length){let f=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,g=e.getUint8(t++);h.chromaFormat=f,h.bitDepthLumaMinus8=p,h.bitDepthChromaMinus8=m;let y=[];for(let b=0;b<g;b++){let k=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+k)),t+=k}h.sequenceParameterSetExt=y}return h}catch(e){return we._error("Error deserializing AVC Decoder Configuration Record:",e),null}},zp={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Zs=r=>{try{let e=new Ie(Ko(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();Y(e);let a=1,o=0,c=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=Y(e),a===3&&(l=e.readBits(1)),o=Y(e),c=Y(e),e.skipBits(1),e.readBits(1))){for(let O=0;O<(a!==3?8:12);O++)if(e.readBits(1)){let ye=O<6?16:64,Z=8,ee=8;for(let ve=0;ve<ye;ve++){if(ee!==0){let Re=lr(e);ee=(Z+Re+256)%256}Z=ee===0?Z:ee}}}Y(e);let u=Y(e);if(u===0)Y(e);else if(u===1){e.skipBits(1),lr(e),lr(e);let E=Y(e);for(let O=0;O<E;O++)lr(e)}Y(e),e.skipBits(1);let d=Y(e),h=Y(e),f=16*(d+1),p=16*(h+1),m=f,g=p,y=e.readBits(1);if(y||e.skipBits(1),e.skipBits(1),e.readBits(1)){let E=Y(e),O=Y(e),Q=Y(e),ye=Y(e),Z,ee;if((l===0?a:0)===0)Z=1,ee=2-y;else{let Re=a===3?1:2,et=a===1?2:1;Z=Re,ee=et*(2-y)}m-=Z*(E+O),g-=ee*(Q+ye)}let k=2,T=2,x=2,v=0,M={num:1,den:1},C=null,_=null;if(e.readBits(1)){if(e.readBits(1)){let et=e.readBits(8);if(et===255)M={num:e.readBits(16),den:e.readBits(16)};else{let Ra=zp[et];Ra&&(M=Ra)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),v=e.readBits(1),e.readBits(1)&&(k=e.readBits(8),T=e.readBits(8),x=e.readBits(8))),e.readBits(1)&&(Y(e),Y(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let ee=e.readBits(1);ee&&Rp(e);let ve=e.readBits(1);ve&&Rp(e),(ee||ve)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),Y(e),Y(e),Y(e),Y(e),C=Y(e),_=Y(e))}if(C===null){w(_===null);let E=i&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&E)C=0,_=0;else{let O=d+1,Q=h+1,ye=(2-y)*Q,Z=$s.find(ve=>ve.level>=s)??ze($s),ee=Math.min(Math.floor(Z.maxDpbMbs/(O*ye)),16);C=ee,_=ee}}return w(_!==null),{profileIdc:n,constraintFlags:i,levelIdc:s,frameMbsOnlyFlag:y,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:g,pixelAspectRatio:M,colourPrimaries:k,matrixCoefficients:x,transferCharacteristics:T,fullRangeFlag:v,numReorderFrames:C,maxDecFrameBuffering:_}}catch(e){return we._error("Error parsing AVC SPS:",e),null}},Rp=r=>{let e=Y(r);r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)Y(r),Y(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},uT=(r,e)=>{if(e.description){let i=(Ye(e.description)[21]&3)+1;return $o(r,i)}else return Op(r)},Ys=(r,e)=>{if(e.description){let i=(Ye(e.description)[21]&3)+1;return Dp(r,i)}else return Oi(r)},un=r=>r>>1&63,Mu=r=>{try{let e=new Ie(Ko(r));e.skipBits(16),e.readBits(4);let t=e.readBits(3),n=e.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=dT(e,t);Y(e);let u=Y(e),d=0;u===3&&(d=e.readBits(1));let h=Y(e),f=Y(e),p=h,m=f;if(e.readBits(1)){let O=Y(e),Q=Y(e),ye=Y(e),Z=Y(e),ee=1,ve=1,Re=d===0?u:0;Re===1?(ee=2,ve=2):Re===2&&(ee=2,ve=1),p-=(O+Q)*ee,m-=(ye+Z)*ve}let g=Y(e),y=Y(e);Y(e);let k=e.readBits(1)?0:t,T=0;for(let O=k;O<=t;O++)Y(e),T=Y(e),Y(e);Y(e),Y(e),Y(e),Y(e),Y(e),Y(e),e.readBits(1)&&e.readBits(1)&&hT(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),Y(e),Y(e),e.skipBits(1));let x=Y(e);if(fT(e,x),e.readBits(1)){let O=Y(e);for(let Q=0;Q<O;Q++)Y(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let v=2,M=2,C=2,_=0,F=0,E={num:1,den:1};if(e.readBits(1)){let O=pT(e,t);E=O.pixelAspectRatio,v=O.colourPrimaries,M=O.transferCharacteristics,C=O.matrixCoefficients,_=O.fullRangeFlag,F=O.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:E,colourPrimaries:v,transferCharacteristics:M,matrixCoefficients:C,fullRangeFlag:_,maxDecFrameBuffering:T+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:F}}catch(e){return we._error("Error parsing HEVC SPS:",e),null}},Ni=r=>{try{let e=[],t=[],n=[],i=[];for(let l of Oi(r)){let u=r.subarray(l.offset,l.offset+l.length),d=un(u[0]);d===it.VPS_NUT?e.push(u):d===it.SPS_NUT?t.push(u):d===it.PPS_NUT?n.push(u):(d===it.PREFIX_SEI_NUT||d===it.SUFFIX_SEI_NUT)&&i.push(u)}if(t.length===0||n.length===0)return null;let s=Mu(t[0]);if(!s)return null;let a=0;if(n.length>0){let l=n[0],u=new Ie(Ko(l));u.skipBits(16),Y(u),Y(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),Y(u),Y(u),lr(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&Y(u),lr(u),lr(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);let d=u.readBits(1),h=u.readBits(1);!d&&!h?a=0:d&&!h?a=2:!d&&h?a=3:a=0}let o=[...e.length?[{arrayCompleteness:1,nalUnitType:it.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:it.SPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:it.PPS_NUT,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:un(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return we._error("Error building HEVC Decoder Configuration Record:",e),null}},dT=(r,e)=>{let t=r.readBits(2),n=r.readBits(1),i=r.readBits(5),s=0;for(let u=0;u<32;u++)s=s<<1|r.readBits(1);let a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);let o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},hT=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))Y(r);else{let i=Math.min(64,1<<4+(e<<1));e>1&&lr(r);for(let s=0;s<i;s++)lr(r)}},fT=(r,e)=>{let t=[];for(let n=0;n<e;n++)t[n]=mT(r,n,e,t)},mT=(r,e,t,n)=>{let i=0,s=0,a=0;if(e!==0&&(s=r.readBits(1)),s){if(e===t){let c=Y(r);a=e-(c+1)}else a=e-1;r.readBits(1),Y(r);let o=n[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);i=n[a]}else{let o=Y(r),c=Y(r);for(let l=0;l<o;l++)Y(r),r.readBits(1);for(let l=0;l<c;l++)Y(r),r.readBits(1);i=o+c}return i},pT=(r,e)=>{let t=2,n=2,i=2,s=0,a=0,o={num:1,den:1};if(r.readBits(1)){let c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{let l=zp[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),s=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),n=r.readBits(8),i=r.readBits(8))),r.readBits(1)&&(Y(r),Y(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(Y(r),Y(r),Y(r),Y(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&Y(r),r.readBits(1)&&gT(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=Y(r),Y(r),Y(r),Y(r),Y(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},gT=(r,e,t)=>{let n=!1,i=!1,s=!1;e&&(n=r.readBits(1)===1,i=r.readBits(1)===1,(n||i)&&(s=r.readBits(1)===1,s&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),s&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let a=0;a<=t;a++){let o=r.readBits(1)===1,c=!0;o||(c=r.readBits(1)===1);let l=!1;c?Y(r):l=r.readBits(1)===1;let u=1;l||(u=Y(r)+1),n&&Bp(r,u,s),i&&Bp(r,u,s)}},Bp=(r,e,t)=>{for(let n=0;n<e;n++)Y(r),Y(r),t&&(Y(r),Y(r)),r.readBits(1)},Vp=r=>{let e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(let t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(let n of t.nalUnits){e.push(n.length>>8&255),e.push(n.length&255);for(let i=0;i<n.length;i++)e.push(n[i])}}return new Uint8Array(e)};var pt;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(pt||(pt={}));var Hp=(r,e)=>{let t=new Set,n=pt.audAllowed;for(let s of Ys(r,e)){if(n===pt.noMoreDataAllowed){t.add(s.offset);continue}let a=un(r[s.offset]);if(n===pt.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?n>pt.audAllowed?o=!0:n=pt.beforeFirstVcl:a<=31?n>pt.afterFirstVcl?o=!0:n=pt.afterFirstVcl:a===36?n!==pt.afterFirstVcl?o=!0:n=pt.eoBitstreamAllowed:a===37?n<pt.afterFirstVcl?o=!0:n=pt.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?n>pt.beforeFirstVcl?o=!0:n=pt.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&n<pt.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;let i=[];for(let s of Ys(r,e))t.has(s.offset)||i.push(r.subarray(s.offset,s.offset+s.length));return uT(i,e)},Xo=r=>{let e=new Ie(r);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 u=e.readBits(3),d=0,h=0;if(u!==7)if(h=e.readBits(1),s===1||s===3){let M=e.readBits(1),C=e.readBits(1);d=!M&&!C?3:M&&!C?2:1,e.skipBits(1)}else d=1;else d=3,h=1;let f=e.readBits(16),p=e.readBits(16),m=f+1,g=p+1,y=m*g,b=ze(Fr).level;for(let v of Fr)if(y<=v.maxPictureSize){b=v.level;break}return{profile:s,level:b,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Wp=function*(r){let e=new Ie(r),t=()=>{let n=0;for(let i=0;i<8;i++){let s=e.readAlignedByte();if(n|=(s&127)<<i*7,!(s&128))break;if(i===7&&s&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),i=e.readBits(1),s=e.readBits(1);e.skipBits(1),i&&e.skipBits(8);let a;if(s){let o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);w(e.pos%8===0),yield{type:n,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Qo=r=>{for(let{type:e,data:t}of Wp(r)){if(e!==1)continue;let n=new Ie(t),i=n.readBits(3),s=n.readBits(1),a=n.readBits(1),o=0,c=0,l=0;if(a)o=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 M=n.readBits(5);for(let C=0;C<=M;C++){n.skipBits(12);let _=n.readBits(5);if(C===0&&(o=_),_>7){let E=n.readBits(1);C===0&&(c=E)}if(v&&n.readBits(1)){let O=l+1;n.skipBits(O),n.skipBits(O),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let u=n.readBits(4),d=n.readBits(4),h=u+1;n.skipBits(h);let f=d+1;n.skipBits(f);let p=0;if(a?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!a){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let x=n.readBits(1);x&&(n.skipBits(1),n.skipBits(1));let v=n.readBits(1),M=0;v?M=2:M=n.readBits(1),M>0&&(n.readBits(1)||n.skipBits(1)),x&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let m=n.readBits(1),g=8;i===2&&m?g=n.readBits(1)?12:10:i<=2&&(g=m?10:8);let y=0;i!==1&&(y=n.readBits(1));let b=1,k=1,T=0;return y||(i===0?(b=1,k=1):i===1?(b=0,k=0):g===12&&(b=n.readBits(1),b&&(k=n.readBits(1))),b&&k&&(T=n.readBits(2))),{profile:i,level:o,tier:c,bitDepth:g,monochrome:y,chromaSubsamplingX:b,chromaSubsamplingY:k,chromaSamplePosition:T}}return null},Yo=r=>{let e=Ae(r),t=e.getUint8(9),n=e.getUint16(10,!0),i=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18),o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:n,inputSampleRate:i,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},yT=[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],qp=r=>{let e=r[0]>>3;return{durationInSamples:yT[e]}},Gp=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=r.length,n=new Uint8Array(t);for(let d=0;d<t;d++)n[d]=r[t-1-d];let i=new Ie(n),s=0;for(;i.getBitsLeft()>97;)if(i.readBits(1)===1){s=i.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;i.getBitsLeft()>=97;){let d=i.pos,h=i.readBits(8),f=i.readBits(16),p=i.readBits(16);if(h>63||f!==0||p!==0){i.pos=d;break}if(i.skipBits(1),a++,a>64)break;i.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;i.pos=0,i.skipBits(s);let u=Array(l).fill(0);for(let d=l-1;d>=0;d--)i.skipBits(40),u[d]=i.readBits(1);return{modeBlockflags:u}},hn=(r,e,t)=>{switch(r){case"avc":{for(let n of Iu(t,e)){let i=t[n.offset],s=Li(i);if(s>=lt.NON_IDR_SLICE&&s<=lt.SLICE_DPC)return"delta";if(s===lt.IDR)return"key";if(s===lt.SEI&&(!Ws()||pp()>=144)){let a=t.subarray(n.offset,n.offset+n.length),o=Ko(a),c=1;do{let l=0;for(;;){let h=o[c++];if(h===void 0||(l+=h,h<255))break}let u=0;for(;;){let h=o[c++];if(h===void 0||(u+=h,h<255))break}if(l===6){let h=new Ie(o);h.pos=8*c;let f=Y(h),p=h.readBits(1);if(f===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(let n of Ys(t,e)){let i=un(t[n.offset]);if(i<it.BLA_W_LP)return"delta";if(i<=it.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let n=new Ie(t);if(n.readBits(2)!==2)return null;let i=n.readBits(1);return(n.readBits(1)<<1)+i===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:i,data:s}of Wp(t))if(i===1){let a=new Ie(s);a.skipBits(4),n=!!a.readBits(1)}else if(i===3||i===6||i===7){if(n)return"key";let a=new Ie(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:Ct(r),w(!1)}},dn;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(dn||(dn={}));var Js=(r,e)=>{let t=Ae(r),n=0,i=t.getUint32(n,!0);n+=4;let s=ot.decode(r.subarray(n,n+i));n+=i,i>0&&(e.raw??={},e.raw.vendor??=s);let a=t.getUint32(n,!0);n+=4;for(let o=0;o<a;o++){let c=t.getUint32(n,!0);n+=4;let l=ot.decode(r.subarray(n,n+c));n+=c;let u=l.indexOf("=");if(u===-1)continue;let d=l.slice(0,u).toUpperCase(),h=l.slice(u+1);switch(e.raw??={},e.raw[d]??=h,d){case"TITLE":e.title??=h;break;case"DESCRIPTION":e.description??=h;break;case"ARTIST":e.artist??=h;break;case"ALBUM":e.album??=h;break;case"ALBUMARTIST":e.albumArtist??=h;break;case"COMMENT":e.comment??=h;break;case"LYRICS":e.lyrics??=h;break;case"TRACKNUMBER":{let f=h.split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"TRACKTOTAL":{let f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{let f=h.split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DISCTOTAL":{let f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{let f=new Date(h);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=h;break;case"METADATA_BLOCK_PICTURE":{let f=Gs(h),p=Ae(f),m=p.getUint32(0,!1),g=p.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+g)),b=p.getUint32(8+g,!1),k=ot.decode(f.subarray(12+g,12+g+b)),T=p.getUint32(g+b+28),x=f.subarray(g+b+32,g+b+32+T);e.images??=[],e.images.push({data:x,mimeType:y,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:k||void 0})}break}}};var ea=[2,1,2,3,3,4,4,5],Zo=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;let e=new Ie(r);e.skipBits(16),e.skipBits(16);let t=e.readBits(2);if(t===3)return null;let n=e.readBits(6),i=e.readBits(5);if(i>8)return null;let s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);let o=e.readBits(1),c=Math.floor(n/2);return{fscod:t,bsid:i,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},jp=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],Kp=1536,yM=new Uint8Array([5,4,65,67,45,51]),wM=new Uint8Array([5,4,69,65,67,51]),Fu=[1,2,3,6],Jo=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;let e=new Ie(r);e.skipBits(16);let t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;let n=e.readBits(11),i=e.readBits(2),s=0,a;i===3?(s=e.readBits(2),a=3):a=e.readBits(2);let o=e.readBits(3),c=e.readBits(1),l=e.readBits(5);if(l<11||l>16)return null;let u=Fu[a],d;return i<3?d=Nn[i]/1e3:d=Pu[s]/1e3,{dataRate:Math.round((n+1)*d/(u*16)),substreams:[{fscod:i,fscod2:s,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},$p=r=>{if(r.length<2)return null;let e=new Ie(r),t=e.readBits(13),n=e.readBits(3),i=[];for(let s=0;s<=n&&!(Math.ceil(e.pos/8)+3>r.length);s++){let a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);let c=e.readBits(3),l=e.readBits(3),u=e.readBits(1);e.skipBits(3);let d=e.readBits(4),h=0;d>0?h=e.readBits(9):e.skipBits(1),i.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:h})}return i.length===0?null:{dataRate:t,substreams:i}},ec=r=>{let e=r.substreams[0];return w(e),e.fscod<3?Nn[e.fscod]:e.fscod2!==null&&e.fscod2<3?Pu[e.fscod2]:null},tc=r=>{let e=r.substreams[0];w(e);let t=ea[e.acmod]+e.lfeon;if(e.numDepSub>0){let n=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)e.chanLoc&1<<8-i&&(t+=n[i])}return t};var ct=class{constructor(e){this.input=e}dispose(){}};var st=new Uint8Array(0),Oe=class r{constructor(e,t,n,i,s=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=i,this.sequenceNumber=s,e===st&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<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(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===st}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new r(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');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.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new r(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}};var rc=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings)];t+=`; codecs="${n.join(", ")}"`}return t},nc=r=>{let e=Ae(r),t=0,n=e.getUint8(t);t+=1,t+=3;let i=sn(r.subarray(t,t+16));t+=16;let s=null;if(n>0){let o=e.getUint32(t);if(t+=4,o>0){s=[];for(let c=0;c<o;c++)s.push(sn(r.subarray(t,t+16))),t+=16}}let a=e.getUint32(t);return t+=4,{systemId:i,keyIds:s,data:r.slice(t,t+a)}},ic=(r,e)=>r.systemId===e.systemId&&gp(r.data,e.data);var Xt=8,Br=16,Dr=r=>{let e=K(r),t=We(r,4),n=8;e===1&&(e=Pt(r),n=16);let s=e-n;return s<0?null:{name:t,totalSize:e,headerSize:n,contentSize:s}},fn=r=>Or(r)/65536,sc=r=>Or(r)/1073741824,ac=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;let n=ce(r);if(e|=n&127,(n&128)===0)break}return e},Qt=r=>{let e=Ke(r);return r.skip(2),e=Math.min(e,r.remainingLength),ot.decode(ie(r,e))},Xp=r=>{let e=Dr(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;let t=K(r);r.skip(4);let n=ie(r,e.contentSize-8);switch(t){case 1:return ot.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new $t(n,"image/jpeg");case 14:return new $t(n,"image/png");case 27:return new $t(n,"image/bmp");default:return n}};var Yt=16,Lr=new Uint32Array(256),zi=new Uint32Array(256),Vi=new Uint32Array(256),Hi=new Uint32Array(256),Wi=new Uint32Array(256),ft=new Uint32Array(256),Qp=new Uint32Array(10),Yp=!1,wT=()=>{let r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let s=0,a=1;s<256;s++)t[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);let n=(s,a)=>s&&a?t[(e[s]+e[a])%255]:0;r[0]=99;for(let s=1;s<256;s++){let a=t[255-e[s]],o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[s]=o}for(let s=0;s<256;s++){let a=r[s],o=r.indexOf(s);Lr[s]=a<<24|a<<16|a<<8|a,ft[s]=o<<24|o<<16|o<<8|o;let c=n(o,14),l=n(o,9),u=n(o,13),d=n(o,11),h=c<<24|l<<16|u<<8|d;zi[s]=h,Vi[s]=h>>>8|h<<24,Hi[s]=h>>>16|h<<16,Wi[s]=h>>>24|h<<8}let i=1;for(let s=0;s<10;s++)Qp[s]=i<<24,i=i<<1^(i&128?283:0);Yp=!0},ta=class{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Yt/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Yt),this.out=new Uint8Array(Yt),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){w(e.byteLength===16),w(t.byteLength===16),Yp||wT();let n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let s=4;s<44;s+=4){let a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^Lr[a>>>16&255]&4278190080^Lr[a>>>8&255]&16711680^Lr[a>>>0&255]&65280^Lr[a>>>24&255]&255^Qp[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){let c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){let o=this.roundkey[s+a];this.roundkey[s+a]=zi[Lr[o>>>24&255]&255]^Vi[Lr[o>>>16&255]&255]^Hi[Lr[o>>>8&255]&255]^Wi[Lr[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],i=this.inView.getUint32(12,!1)^this.roundkey[3],s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1),l,u,d,h;for(let y=1;y<10;y++){let b=y*4;l=zi[e>>>24]^Vi[i>>>16&255]^Hi[n>>>8&255]^Wi[t&255]^this.roundkey[b],u=zi[t>>>24]^Vi[e>>>16&255]^Hi[i>>>8&255]^Wi[n&255]^this.roundkey[b+1],d=zi[n>>>24]^Vi[t>>>16&255]^Hi[e>>>8&255]^Wi[i&255]^this.roundkey[b+2],h=zi[i>>>24]^Vi[n>>>16&255]^Hi[t>>>8&255]^Wi[e&255]^this.roundkey[b+3],e=l,t=u,n=d,i=h}let f=ft[e>>>24&255]&4278190080^ft[i>>>16&255]&16711680^ft[n>>>8&255]&65280^ft[t>>>0&255]&255^this.roundkey[40],p=ft[t>>>24&255]&4278190080^ft[e>>>16&255]&16711680^ft[i>>>8&255]&65280^ft[n>>>0&255]&255^this.roundkey[41],m=ft[n>>>24&255]&4278190080^ft[t>>>16&255]&16711680^ft[e>>>8&255]&65280^ft[i>>>0&255]&255^this.roundkey[42],g=ft[i>>>24&255]&4278190080^ft[n>>>16&255]&16711680^ft[t>>>8&255]&65280^ft[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,g^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}},Zp=(r,e,t)=>{let n=!1,i=0,s=2**16,a=16,o=new ta;return new ReadableStream({pull:async c=>{n||(o.init(await e()),n=!0);let l=s+a,u=r.requestSliceRange(i,0,l);if(u instanceof Promise&&(u=await u),!u||u.length===0)throw new Error("Invalid ciphertext.");let d=u.length;if(d%16!==0)throw new Error("Invalid ciphertext.");let h=d===l?d-a:d,f=ie(u,h),p=new Uint8Array(h);for(let m=0;m<h;m+=16)o.in.set(f.subarray(m,m+16)),o.decrypt(),p.set(o.out,m);if(h<d)c.enqueue(p),i+=h;else{let m=p[h-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let g=p.subarray(0,h-m);c.enqueue(g),c.close(),t()}},cancel:()=>{t()}})};var oc=class r extends ct{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.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(n=>n.getDecoderConfig().then(i=>i?.codec??null)));return rc({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(n=>n.info?.type==="video"),hasAudio:this.tracks.some(n=>n.info?.type==="audio"),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1;for(;;){let n=this.reader.requestSliceRange(e,Xt,Br);if(n instanceof Promise&&(n=await n),!n)break;let i=e,s=Dr(n);if(!s)break;if(s.name==="ftyp"||s.name==="styp"){let a=We(n,4);this.isQuickTime=a==="qt "}else if(s.name==="moov"){let a=this.reader.requestSlice(n.filePos,s.contentSize);if(a instanceof Promise&&(a=await a),!a)break;this.moovSlice=a,this.readContiguousBoxes(this.moovSlice);for(let o of this.tracks){let c=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(c*o.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+s.totalSize;break}else if(s.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');let a=await this.input._initInput._getDemuxer();if(a.constructor!==r)throw new Error("Init input must match the input's format.");await a.readMetadata(),this.movieTimescale=a.movieTimescale,this.movieDurationInTimescale=a.movieDurationInTimescale,this.metadataTags=a.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=a.fragmentTrackDefaults,this.psshBoxes=a.psshBoxes;for(let o of a.tracks){let c={id:o.id,demuxer:this,trackBacking:null,disposition:o.disposition,timescale:o.timescale,durationInMediaTimescale:o.durationInMediaTimescale,durationInMovieTimescale:o.durationInMovieTimescale,rotation:o.rotation,internalCodecId:o.internalCodecId,name:o.name,languageCode:o.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:o.editListPreviousSegmentDurations,editListOffset:o.editListOffset,encryptionInfo:o.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:o.info};if(o.trackBacking){if(w(c.info),c.info.type==="video"&&c.info.width!==-1){let l=c;c.trackBacking=new lc(l),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){let l=c;c.trackBacking=new uc(l),this.tracks.push(c)}}}t=!1;break}e=i+s.totalSize}if(t){w(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);n instanceof Promise&&(n=await n),w(n);let i=K(n),s=this.reader.fileSize-i;if(s>=0&&s<=this.reader.fileSize-Br){let a=this.reader.requestSliceRange(s,Xt,Br);if(a instanceof Promise&&(a=await a),a){let o=Dr(a);if(o&&o.name==="mfra"){let c=this.reader.requestSlice(a.filePos,o.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;w(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&&ht.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){w(e.info?.type==="audio");let s=Wt(e.info.codec),a=[],o=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],d=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let h=0;h<d;h++){let f=l.startSampleIndex+h*l.samplesPerChunk,p=f+l.samplesPerChunk,m=_e(t.sampleTimingEntries,f,C=>C.startIndex),g=t.sampleTimingEntries[m],y=_e(t.sampleTimingEntries,p,C=>C.startIndex),b=t.sampleTimingEntries[y],k=g.startDecodeTimestamp+(f-g.startIndex)*g.delta,x=b.startDecodeTimestamp+(p-b.startIndex)*b.delta-k,v=ze(a);v&&v.delta===x?v.count++:a.push({startIndex:l.startChunkIndex+h,startDecodeTimestamp:k,count:1,delta:x});let M=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(M)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let s of t.sampleTimingEntries)for(let a=0;a<s.count;a++)t.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(let s of t.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){let o=s.startIndex+a,c=t.presentationTimestamps[o];c&&(c.presentationTimestamp+=s.offset)}t.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let s=0;s<t.presentationTimestamps.length;s++)t.presentationTimestampIndexMap[t.presentationTimestamps[s].sampleIndex]=s}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,Xt,Br);t instanceof Promise&&(t=await t),w(t);let n=Dr(t);w(n?.name==="moof");let i=this.reader.requestSlice(e,n.totalSize);i instanceof Promise&&(i=await i),w(i),this.traverseBox(i);let s=this.lastReadFragment;w(s&&s.moofOffset===e);for(let[,a]of s.trackData){let o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){let u=o.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(u)Ru(a,u.timestamp);else{let d=_e(c,s.moofOffset-1,h=>h.moofOffset);if(d!==-1){let h=c[d];Ru(a,h.endTimestamp)}}a.startTimestampIsFinal=!0}let l=_e(c,a.startTimestamp,u=>u.startTimestamp);if((l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){let u=await rg(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let d=0;d<Math.min(a.samples.length,u.length);d++){let h=u[d];a.samples[d].encryption=h}}}return s}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Xt&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Xt;){let n=e.filePos,i=Dr(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=n+i.totalSize}}traverseBox(e){let t=e.filePos,n=Dr(e);if(!n)return!1;let i=e.filePos,s=t+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mvhd":{let a=ce(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=K(e),this.movieDurationInTimescale=Pt(e)):(e.skip(8),this.movieTimescale=K(e),this.movieDurationInTimescale=K(e))}break;case"trak":{let a={id:-1,demuxer:this,trackBacking:null,disposition:{...dt,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:je,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(i,n.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){let o=a;a.trackBacking=new lc(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let o=a;a.trackBacking=new uc(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{let a=this.currentTrack;if(!a)break;let o=ce(e),l=!!(Zt(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=K(e),e.skip(4),a.durationInMovieTimescale=K(e);else if(o===1)e.skip(16),a.id=K(e),e.skip(4),a.durationInMovieTimescale=Pt(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);let u=[fn(e),fn(e),sc(e),fn(e),fn(e),sc(e),fn(e),fn(e),sc(e)],d=_i(Vs(xT(u),90));w(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{let a=this.currentTrack;if(!a)break;let o=ce(e);e.skip(3);let c=!1,l=0,u=K(e);for(let d=0;d<u;d++){let h=o===1?Pt(e):K(e),f=o===1?ig(e):Or(e),p=fn(e);if(h!==0){if(c){we._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=h;continue}if(p!==1){we._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=l,a.editListOffset=f,c=!0}}}break;case"mdhd":{let a=this.currentTrack;if(!a)break;let o=ce(e);e.skip(3),o===0?(e.skip(8),a.timescale=K(e),a.durationInMediaTimescale=K(e)):o===1&&(e.skip(16),a.timescale=K(e),a.durationInMediaTimescale=Pt(e));let c=Ke(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;Ei(a.languageCode)||(a.languageCode=je)}}break;case"hdlr":{let a=this.currentTrack;if(!a)break;e.skip(8);let o=We(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{let a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(i,n.contentSize))}break;case"stsd":{let a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;let o=ce(e);e.skip(3);let c=K(e);for(let l=0;l<c;l++){let u=e.filePos,d=Dr(e);if(!d)break;a.internalCodecId=d.name;let h=d.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=Ke(e),a.info.height=Ke(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));let f=h==="encv"?a.frmaCodecString:h;a.frmaCodecString=null,f==="avc1"||f==="avc3"?(a.info.codec="avc",a.info.avcType=f==="avc1"?1:3):f==="hvc1"||f==="hev1"?a.info.codec="hevc":f==="vp08"?a.info.codec="vp8":f==="vp09"?a.info.codec="vp9":f==="av01"?a.info.codec="av1":f===null?we._warn("Unknown encrypted video codec due to missing frma box."):we._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{e.skip(8);let f=Ke(e);e.skip(6);let p=Ke(e),m=Ke(e);e.skip(4);let g=K(e)/65536,y=null;o===0&&f>0&&(f===1?(e.skip(4),m=8*K(e),e.skip(8)):f===2&&(e.skip(4),g=dc(e),p=K(e),e.skip(4),m=K(e),y=K(e),e.skip(8))),a.info.numberOfChannels=p,a.info.sampleRate=g,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));let b=h==="enca"?a.frmaCodecString:h;if(a.frmaCodecString=null,b!=="mp4a")if(b==="opus")a.info.codec="opus",a.info.sampleRate=Un;else if(b==="flac")a.info.codec="flac";else if(b==="ulaw")a.info.codec="ulaw";else if(b==="alaw")a.info.codec="alaw";else if(b==="ac-3")a.info.codec="ac3";else if(b==="ec-3")a.info.codec="eac3";else if(b==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(we._warn(`Unsupported sample size ${m} for codec 'twos'.`),a.info.codec=null);else if(b==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(we._warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(b==="raw ")a.info.codec="pcm-u8";else if(b==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(b==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(b==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(b==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(b==="ipcm"){let k=a.info.pcmSampleSize;a.info.pcmLittleEndian?k===16?a.info.codec="pcm-s16":k===24?a.info.codec="pcm-s24":k===32?a.info.codec="pcm-s32":(we._warn(`Invalid ipcm sample size ${k}.`),a.info.codec=null):k===16?a.info.codec="pcm-s16be":k===24?a.info.codec="pcm-s24be":k===32?a.info.codec="pcm-s32be":(we._warn(`Invalid ipcm sample size ${k}.`),a.info.codec=null)}else if(b==="fpcm"){let k=a.info.pcmSampleSize;a.info.pcmLittleEndian?k===32?a.info.codec="pcm-f32":k===64?a.info.codec="pcm-f64":(we._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null):k===32?a.info.codec="pcm-f32be":k===64?a.info.codec="pcm-f64be":(we._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null)}else if(b==="lpcm"&&y!==null){let k=m+7>>3,T=!!(y&1),x=!!(y&2),v=y&4?-1:0;m>0&&m<=64&&(T?m===32&&(a.info.codec=x?"pcm-f32be":"pcm-f32"):v&1<<k-1?k===1?a.info.codec="pcm-s8":k===2?a.info.codec=x?"pcm-s16be":"pcm-s16":k===3?a.info.codec=x?"pcm-s24be":"pcm-s24":k===4&&(a.info.codec=x?"pcm-s32be":"pcm-s32"):k===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&we._warn("Unsupported PCM format.")}else b===null?we._warn("Unknown encrypted audio codec due to missing frma box."):we._warn(`Unsupported audio codec (sample entry type '${d.name}').`)}e.filePos=u+d.totalSize}}break;case"frma":{let a=this.currentTrack;if(!a)break;let c=We(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{let a=this.currentTrack;if(!a)break;e.skip(4);let o=We(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:we._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;let o=ce(e);e.skip(3),e.skip(1);let c=ce(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=ce(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=ce(e),a.encryptionInfo.defaultKid=sn(ie(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){let l=ce(e),u=new Uint8Array(16);u.set(ie(e,l),0),a.encryptionInfo.defaultConstantIv=u}}break;case"avcC":{let a=this.currentTrack;if(!a)break;w(a.info),a.info.codecDescription=ie(e,n.contentSize)}break;case"hvcC":{let a=this.currentTrack;if(!a)break;w(a.info),a.info.codecDescription=ie(e,n.contentSize)}break;case"vpcC":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video"),e.skip(4);let o=ce(e),c=ce(e),l=ce(e),u=l>>4,d=l>>1&7,h=l&1,f=ce(e),p=ce(e),m=ce(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:m}}break;case"av1C":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video"),e.skip(1);let o=ce(e),c=o>>5,l=o&31,u=ce(e),d=u>>7,h=u>>6&1,f=u>>5&1,p=u>>4&1,m=u>>3&1,g=u>>2&1,y=u&3,b=c===2&&h?f?12:10:h?10:8;a.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:b,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:g,chromaSamplePosition:y}}break;case"colr":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video");let o=We(e,4);if(o!=="nclx"&&o!=="nclc")break;let c=Ke(e),l=Ke(e),u=Ke(e),d;o==="nclx"&&(d=!!(ce(e)&128)),a.info.colorSpace={primaries:Mn[c],transfer:Fn[l],matrix:Rn[u],fullRange:d}}break;case"pasp":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video");let o=K(e),c=K(e);o>0&&c>0&&(o>c?a.info.squarePixelWidth=Math.round(a.info.width*o/c):a.info.squarePixelHeight=Math.round(a.info.height*c/o))}break;case"wave":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"esds":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(4);let o=ce(e);w(o===3),ac(e),e.skip(2);let c=ce(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){let g=ce(e);e.skip(g)}d&&e.skip(2);let h=ce(e);w(h===4);let f=ac(e),p=e.filePos,m=ce(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":we._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),f>e.filePos-p){let g=ce(e);w(g===5);let y=ac(e);if(a.info.codecDescription=ie(e,y),a.info.codec==="aac"){let b=Ri(a.info.codecDescription);b.numberOfChannels!==null&&(a.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(a.info.sampleRate=b.sampleRate)}}}break;case"enda":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(Ke(e)&255)}break;case"pcmC":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(4);let o=ce(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=ce(e)}break;case"dOps":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(1);let o=ce(e),c=Ke(e),l=K(e),u=ra(e),d=ce(e),h;d!==0?h=ie(e,2+o):h=new Uint8Array(0);let f=new Uint8Array(19+h.byteLength),p=new DataView(f.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,u,!0),p.setUint8(18,d),f.set(h,19),a.info.codecDescription=f,a.info.numberOfChannels=o}break;case"dfLa":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(4);let o=127,c=128,l=e.filePos;for(;e.filePos<s;){let p=ce(e),m=Zt(e);if((p&o)===dn.STREAMINFO){e.skip(10);let y=K(e),b=y>>>12,k=(y>>9&7)+1;a.info.sampleRate=b,a.info.numberOfChannels=k,e.skip(20)}else e.skip(m);if(p&c)break}let u=e.filePos;e.filePos=l;let d=ie(e,u-l),h=new Uint8Array(4+d.byteLength);new DataView(h.buffer).setUint32(0,1716281667,!1),h.set(d,4),a.info.codecDescription=h}break;case"dac3":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio");let o=ie(e,3),c=new Ie(o),l=c.readBits(2);c.skipBits(8);let u=c.readBits(3),d=c.readBits(1);l<3&&(a.info.sampleRate=Nn[l]),a.info.numberOfChannels=ea[u]+d}break;case"dec3":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio");let o=ie(e,n.contentSize),c=$p(o);if(!c){we._warn("Invalid dec3 box contents, ignoring.");break}let l=ec(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=tc(c)}break;case"stts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e),c=0,l=0;for(let u=0;u<o;u++){let d=K(e),h=K(e);a.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:d,delta:h}),c+=d,l+=d*h}}break;case"ctts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e),c=0;for(let l=0;l<o;l++){let u=K(e),d=Or(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e),c=K(e);if(o===0)for(let l=0;l<c;l++){let u=K(e);a.sampleTable.sampleSizes.push(u)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);let o=ce(e),c=K(e),l=ie(e,Math.ceil(c*o/8)),u=new Ie(l);for(let d=0;d<c;d++){let h=u.readBits(o);a.sampleTable.sampleSizes.push(h)}}break;case"stss":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];let o=K(e);for(let c=0;c<o;c++){let l=K(e)-1;a.sampleTable.keySampleIndices.push(l)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e);for(let l=0;l<o;l++){let u=K(e)-1,d=K(e),h=K(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:h})}let c=0;for(let l=0;l<a.sampleTable.sampleToChunk.length;l++)if(a.sampleTable.sampleToChunk[l].startSampleIndex=c,l<a.sampleTable.sampleToChunk.length-1){let d=a.sampleTable.sampleToChunk[l+1].startChunkIndex-a.sampleTable.sampleToChunk[l].startChunkIndex;c+=d*a.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e);for(let c=0;c<o;c++){let l=K(e);a.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=K(e);for(let c=0;c<o;c++){let l=Pt(e);a.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mehd":{let a=ce(e);e.skip(3);let o=a===1?Pt(e):K(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);let a=K(e),o=K(e),c=K(e),l=K(e),u=K(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{let a=ce(e);e.skip(3);let o=K(e),c=this.tracks.find(b=>b.id===o);if(!c)break;let l=K(e),u=(l&48)>>4,d=(l&12)>>2,h=l&3,f=[ce,Ke,Zt,K],p=f[u],m=f[d],g=f[h],y=K(e);for(let b=0;b<y;b++){let k=a===1?Pt(e):K(e),T=a===1?Pt(e):K(e);p(e),m(e),g(e),c.fragmentLookupTable.push({timestamp:k,moofOffset:T})}c.fragmentLookupTable.sort((b,k)=>b.timestamp-k.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){let k=c.fragmentLookupTable[b],T=c.fragmentLookupTable[b+1];k.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(i,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(w(this.currentFragment),this.readContiguousBoxes(e.slice(i,n.contentSize)),this.currentTrack){let a=this.currentFragment.trackData.get(this.currentTrack.id);e:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}a.presentationTimestamps=a.samples.map((u,d)=>({presentationTimestamp:u.presentationTimestamp,sampleIndex:d})).sort((u,d)=>u.presentationTimestamp-d.presentationTimestamp);for(let u=0;u<a.presentationTimestamps.length;u++){let d=a.presentationTimestamps[u],h=a.samples[d.sampleIndex];if(a.firstKeyFrameTimestamp===null&&h.isKeyFrame&&(a.firstKeyFrameTimestamp=h.presentationTimestamp),u<a.presentationTimestamps.length-1){let p=a.presentationTimestamps[u+1].presentationTimestamp-d.presentationTimestamp;h.duration=p}}let o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[ze(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;let{currentFragmentState:l}=this.currentTrack;w(l),l.startTimestamp!==null&&(Ru(a,l.startTimestamp),a.startTimestampIsFinal=!0),l.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=l.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let a=nc(ie(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{w(this.currentFragment),e.skip(1);let a=Zt(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),u=!!(a&16),d=!!(a&32),h=!!(a&65536),f=!!(a&131072),p=K(e),m=this.tracks.find(y=>y.id===p);if(!m)break;let g=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:g?.defaultSampleDescriptionIndex??null,defaultSampleDuration:g?.defaultSampleDuration??null,defaultSampleSize:g?.defaultSampleSize??null,defaultSampleFlags:g?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=Pt(e):f&&(m.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(m.currentFragmentState.sampleDescriptionIndex=K(e)),l&&(m.currentFragmentState.defaultSampleDuration=K(e)),u&&(m.currentFragmentState.defaultSampleSize=K(e)),d&&(m.currentFragmentState.defaultSampleFlags=K(e)),h&&(m.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let a=this.currentTrack;if(!a)break;w(a.currentFragmentState);let o=ce(e);e.skip(3);let c=o===0?K(e):Pt(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{let a=this.currentTrack;if(!a)break;w(this.currentFragment),w(a.currentFragmentState);let o=ce(e),c=Zt(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),h=!!(c&512),f=!!(c&1024),p=!!(c&2048),m=K(e),g=null;l&&(g=Or(e));let y=null;u&&(y=K(e));let b;this.currentFragment.trackData.has(a.id)?(b=this.currentFragment.trackData.get(a.id),g!==null&&(b.currentOffset=a.currentFragmentState.baseDataOffset+g)):(b={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(g??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,b));for(let k=0;k<m;k++){let T;d?T=K(e):(w(a.currentFragmentState.defaultSampleDuration!==null),T=a.currentFragmentState.defaultSampleDuration);let x;h?x=K(e):(w(a.currentFragmentState.defaultSampleSize!==null),x=a.currentFragmentState.defaultSampleSize);let v;f?v=K(e):(w(a.currentFragmentState.defaultSampleFlags!==null),v=a.currentFragmentState.defaultSampleFlags),k===0&&y!==null&&(v=y);let M=0;p&&(o===0?M=K(e):M=Or(e));let C=!(v&65536);b.samples.push({presentationTimestamp:b.currentTimestamp+M,duration:T,byteOffset:b.currentOffset,byteSize:x,isKeyFrame:C,encryption:null}),b.currentOffset+=x,b.currentTimestamp+=T}this.currentFragment.implicitBaseDataOffset=b.currentOffset}break;case"saiz":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),Zt(e)&1){let h=We(e,4),f=K(e);if(h!==a.encryptionInfo.scheme||f!==0)break}let c=ce(e),l=K(e),u=null;c===0&&l>0&&(u=ie(e,l));let d=eg(a);d.defaultSampleInfoSize=c,d.sampleSizes=u,d.sampleCount=l}break;case"saio":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;let o=ce(e);if(Zt(e)&1){let h=We(e,4),f=K(e);if(h!==a.encryptionInfo.scheme||f!==0)break}let l=K(e);if(l===0)break;l>1&&we._warn("Multiple saio entries are not supported; using the first offset only.");let u=o===0?K(e):Number(Pt(e));this.currentFragment&&(u+=this.currentFragment.moofOffset);let d=eg(a);d.offset=u}break;case"senc":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;w(this.currentFragment);let o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);let l=!!(Zt(e)&2),u=K(e),d=a.encryptionInfo.defaultPerSampleIvSize;w(d!==null);for(let h=0;h<Math.min(u,o.samples.length);h++){let f=new Uint8Array(16);d>0?f.set(ie(e,d),0):f.set(a.encryptionInfo.defaultConstantIv,0);let p=null;if(l){let g=Ke(e);p=[];for(let y=0;y<g;y++){let b=Ke(e),k=K(e);p.push({clearLen:b,protectedLen:k})}}let m=o.samples[h];m.encryption={iv:f,subsamples:p}}}break;case"udta":{let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},o.name[0]==="\xA9"?this.metadataTags.raw[o.name]??=Qt(c):this.metadataTags.raw[o.name]??=ie(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=ot.decode(ie(c,o.contentSize)):this.metadataTags.title??=Qt(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Qt(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Qt(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Qt(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Qt(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Qt(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(Qt(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Qt(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Qt(c));break}}}break;case"meta":{if(this.currentTrack)break;let o=K(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(i,n.contentSize)):this.readContiguousBoxes(e.slice(i+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let a=K(e);for(let o=0;o<a;o++){let c=K(e);e.skip(4);let l=ot.decode(ie(e,c-8));this.currentMetadataKeys.set(o+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:o,slice:c}of a){let l=o.name,u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));let d=Xp(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=d,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof $t?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let h=d.split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let h=Ae(d),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let h=Ae(d),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}},cc=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let i of e.tracks)if(i.trackBacking.getType()===t&&n++,i===this.internalTrack)break;return n}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}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(w(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Mr(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Bu(i,n),a=await this.fetchPacketForSampleIndex(s,t);return!Jp(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=_e(c.presentationTimestamps,n,h=>h.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let a=s.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<a.samples.length)return{sampleIndex:i.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,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=bT(i,n),a=await this.fetchPacketForSampleIndex(s,t);return!Jp(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=Pi(c.presentationTimestamps,h=>c.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=n),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ST(s,n);return this.fetchPacketForSampleIndex(a,t)}let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>i.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{let a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let o=a.samples.findIndex(c=>c.isKeyFrame);return w(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=kT(n,e);if(!i)return null;let s;if(t.metadataOnly)s=st;else{let l=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(l instanceof Promise&&(l=await l),!l)return null;if(s=ie(l,i.sampleSize),this.internalTrack.encryptionAuxInfo){w(this.internalTrack.encryptionInfo);let u=await rg(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<u.length&&(s=await tg(this.internalTrack,u[e],s,null))}}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,c=new Oe(s,i.isKeyFrame?"key":"delta",a,o,e,i.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[t];w(s);let a;if(n.metadataOnly)a=st;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(u instanceof Promise&&(u=await u),!u)return null;a=ie(u,s.byteSize),s.encryption&&(a=await tg(this.internalTrack,s.encryption,a,e))}let o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new Oe(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,n,i,s){let a=this.internalTrack.demuxer,o=null,c=null,l=-1;if(e){let{sampleIndex:g,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,g,s);g!==-1&&(c=e,l=g)}let u=_e(this.internalTrack.fragmentLookupTable,n,g=>g.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,h=_e(this.internalTrack.fragmentPositionCache,n,g=>g.startTimestamp),f=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,p=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let k=o.trackData.get(this.internalTrack.id);if(k&&k.startTimestamp>i)break}let g=a.reader.requestSliceRange(m,Xt,Br);if(g instanceof Promise&&(g=await g),!g)break;let y=m,b=Dr(g);if(!b)break;if(b.name==="moof"){o=await a.readFragment(y);let{sampleIndex:k,correctSampleFound:T}=t(o);if(T)return this.fetchPacketInFragment(o,k,s);k!==-1&&(c=o,l=k)}m=y+b.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let g=this.internalTrack.fragmentLookupTable[u-1];w(!g||g.timestamp<d.timestamp);let y=g?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,i,s)}return c?this.fetchPacketInFragment(c,l,s):null}},lc=class extends cc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}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 t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&Xo(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Qo(t.data)}let e={codec:Bi(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};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},uc=class extends cc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}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:Di(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Bu=(r,e)=>{if(r.presentationTimestamps){let t=_e(r.presentationTimestamps,e,n=>n.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{let t=_e(r.sampleTimingEntries,e,i=>i.startDecodeTimestamp);if(t===-1)return-1;let n=r.sampleTimingEntries[t];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},bT=(r,e)=>{if(!r.keySampleIndices)return Bu(r,e);if(r.presentationTimestamps){let t=_e(r.presentationTimestamps,e,n=>n.presentationTimestamp);if(t===-1)return-1;for(let n=t;n>=0;n--){let i=r.presentationTimestamps[n].sampleIndex;if(Ir(r.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{let t=Bu(r,e),n=_e(r.keySampleIndices,t,i=>i);return r.keySampleIndices[n]??-1}},kT=(r,e)=>{let t=_e(r.sampleTimingEntries,e,y=>y.startIndex),n=r.sampleTimingEntries[t];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,a=_e(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);let c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=_e(r.sampleToChunk,e,y=>y.startSampleIndex),u=r.sampleToChunk[l];w(u);let d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),h=r.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,p=0,m=h;if(r.sampleSizes.length===1)m+=c*(e-f),p+=c*u.samplesPerChunk;else for(let y=f;y<f+u.samplesPerChunk;y++){let b=r.sampleSizes[y];y<e&&(m+=b),p+=b}let g=n.delta;if(r.presentationTimestamps){let y=r.presentationTimestampIndexMap[e];w(y!==void 0),y<r.presentationTimestamps.length-1&&(g=r.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:m,sampleSize:c,chunkOffset:h,chunkSize:p,isKeyFrame:r.keySampleIndices?Ir(r.keySampleIndices,e,y=>y)!==-1:!0}},ST=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=_e(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},Ru=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(let t of r.samples)t.presentationTimestamp+=e;for(let t of r.presentationTimestamps)t.presentationTimestamp+=e},xT=r=>{let[e,t]=r,n=Math.atan2(t,e);return Number.isFinite(n)?n*(180/Math.PI):0},Jp=r=>r.sampleSizes.length===0,eg=r=>r.currentFragmentState?r.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:r.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},rg=async(r,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let n=0;if(t.defaultSampleInfoSize>0)n=t.defaultSampleInfoSize*t.sampleCount;else{w(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)n+=t.sampleSizes[o]}let i=r.requestSlice(t.offset,n);if(i instanceof Promise&&(i=await i),!i)throw new Error("Failed to read auxiliary encryption info.");let s=e.defaultPerSampleIvSize;w(s!==null);let a=[];for(let o=0;o<t.sampleCount;o++){let c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],l=new Uint8Array(16);s>0?l.set(ie(i,s),0):l.set(e.defaultConstantIv,0);let u=null;if(c>s){let d=Ke(i);u=[];for(let h=0;h<d;h++){let f=Ke(i),p=K(i);u.push({clearLen:f,protectedLen:p})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},tg=async(r,e,t,n)=>{w(r.encryptionInfo);let i=r.encryptionInfo;w(i.defaultKid!==null);let s=i.defaultKid,a,o=r.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!r.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let c=(async()=>{let l=r.demuxer.psshBoxes;if(n){l=[...l,...n.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(s));for(let d=0;d<l.length-1;d++)for(let h=d+1;h<l.length;h++)ic(l[d],l[h])&&(l.splice(h,1),h--)}let u=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:l});if(!(typeof u=="string"&&u.length===32&&sp.test(u)||u instanceof Uint8Array&&u.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return u instanceof Uint8Array?u:ap(u)})();r.demuxer.decryptionKeyCache.set(s,c),a=await c}return i.scheme==="cenc"||i.scheme==="cens"?TT(a,i,e,t):AT(a,i,e,t)},TT=async(r,e,t,n)=>{let i=new Uint8Array(16);i.set(t.iv,0);let s=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{let m=await crypto.subtle.decrypt({name:"AES-CTR",counter:i,length:64},s,p);return new Uint8Array(m)};if(!t.subsamples)return a(n);w(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);let o=ng(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock),c=0;for(let p of o)for(let m of p.perSubsample)c+=m.length;let l=new Uint8Array(c),u=0;for(let p of o)for(let m of p.perSubsample)l.set(n.subarray(m.offset,m.offset+m.length),u),u+=m.length;let d=await a(l),h=new Uint8Array(n),f=0;for(let p of o)for(let m of p.perSubsample)h.set(d.subarray(f,f+m.length),m.offset),f+=m.length;return h},AT=(r,e,t,n)=>{let i=new ta;i.init({key:r,iv:t.iv});let s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(w(s!==null&&a!==null),!t.subsamples){let u=new Uint8Array(n),d=Math.floor(n.length/16);for(let h=0;h<d;h++){let f=h*16;i.in.set(n.subarray(f,f+16)),i.decrypt(),u.set(i.out,f)}return u}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");let o=new Uint8Array(n),c=ng(t.subsamples,s,a),l=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(let u of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(let d of u.perSubsample){let h=d.length/16;for(let f=0;f<h;f++){let p=d.offset+f*16;i.in.set(n.subarray(p,p+16)),i.decrypt(),o.set(i.out,p)}}}return o},ng=(r,e,t)=>{let n=[],i=e!==0||t!==0,s=0;for(let a of r){s+=a.clearLen;let o=[];if(!i)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let c=a.protectedLen,l=s;for(;c>0&&!(c<16*e);){let u=16*e;o.push({offset:l,length:u}),l+=u,c-=u;let d=Math.min(16*t,c);l+=d,c-=d}s+=a.protectedLen}n.push({perSubsample:o})}return n};var N;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(N||(N={}));var vT=[N.EBML,N.Segment],qi=[N.SeekHead,N.Info,N.Cluster,N.Tracks,N.Cues,N.Attachments,N.Chapters,N.Tags],na=[...vT,...qi];var Du=8,Et=2,Jt=2*Du,Ou=r=>{if(r.remainingLength<1)return null;let e=ce(r);if(r.skip(-1),e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;return r.remainingLength<t?null:t},Gi=r=>{if(r.remainingLength<1)return null;let e=ce(r);if(e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;if(r.remainingLength<t-1)return null;let i=e&n-1;for(let s=1;s<t;s++)i*=256,i+=ce(r);return i},Ce=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let n=0;n<e;n++)t*=256,t+=ce(r);return t},sg=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let n=0;n<e;n++)t<<=8n,t+=BigInt(ce(r));return t};var hc=r=>{let e=Ou(r);return e===null||r.remainingLength<e?null:Ce(r,e)},Lu=r=>{if(r.remainingLength<1)return null;if(ce(r)===255)return;r.skip(-1);let t=Gi(r);if(t===null)return null;if(t!==72057594037927940)return t},er=r=>{w(r.remainingLength>=Et);let e=hc(r);if(e===null)return null;let t=Lu(r);return t===null?null:{id:e,size:t}},mn=(r,e)=>{let t=ie(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return String.fromCharCode(...t.subarray(0,n))},ji=(r,e)=>{let t=ie(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return ot.decode(t.subarray(0,n))},fc=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?ag(r):dc(r)},mc=async(r,e,t,n)=>{let i=new Set(t),s=e;for(;n===null||s<n;){let a=r.requestSliceRange(s,Et,Jt);if(a instanceof Promise&&(a=await a),!a)break;let o=er(a);if(!o)break;if(i.has(o.id))return{pos:s,found:!0};Ur(o.size),s=a.filePos+o.size}return{pos:n!==null&&n>s?n:s,found:!1}},Uu=async(r,e,t,n)=>{let s=new Set(t),a=e;for(;a<n;){let o=r.requestSliceRange(a,0,Math.min(65536,n-a));if(o instanceof Promise&&(o=await o),!o||o.length<Du)break;for(let c=0;c<o.length-Du;c++){o.filePos=a;let l=hc(o);if(l!==null&&s.has(l))return a;a++}}return null},Bt={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",ac3:"A_AC3",eac3:"A_EAC3","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 Ur(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var og=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(", ")}"`}return t};var Nr;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Nr||(Nr={}));var pc;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(pc||(pc={}));var ia;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(ia||(ia={}));var Nu=[{id:N.SeekHead,flag:"seekHeadSeen"},{id:N.Info,flag:"infoSeen"},{id:N.Tracks,flag:"tracksSeen"},{id:N.Cues,flag:"cuesSeen"}],cg=10*2**20,gc=class extends ct{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 getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(n=>n.getDecoderConfig().then(i=>i?.codec??null)));return og({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Et,Jt);if(t instanceof Promise&&(t=await t),!t)break;let n=er(t);if(!n)break;let i=n.id,s=n.size,a=t.filePos;if(i===N.EBML){Ur(s);let o=this.reader.requestSlice(a,s);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(i===N.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(i===N.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await mc(this.reader,a,na,this.reader.fileSize)).pos-a);let o=ze(this.segments);o&&(o.elementEndPos=a+s)}Ur(s),e=a+s}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(n,Et,Jt);if(o instanceof Promise&&(o=await o),!o)break;let c=n,l=er(o);if(!l||!qi.includes(l.id)&&l.id!==N.Void){let p=await Uu(this.reader,c,qi,Math.min(this.currentSegment.elementEndPos??1/0,c+cg));if(p){n=p;continue}else break}let{id:u,size:d}=l,h=o.filePos,f=Nu.findIndex(p=>p.id===u);if(f!==-1){let p=Nu[f].flag;this.currentSegment[p]=!0,Ur(d);let m=this.reader.requestSlice(h,d);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}else if(u===N.Tags||u===N.Attachments){u===N.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ur(d);let p=this.reader.requestSlice(h,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===N.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;n=h+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let o of this.currentSegment.seekEntries){let c=Nu.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,Et,Jt);if(l instanceof Promise&&(l=await l),!l)continue;let u=er(l);if(!u)continue;let{id:d,size:h}=u;if(d!==c.id)continue;Ur(h),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,h);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);let i=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(let o of this.currentSegment.cuePoints){let c=i.get(o.trackId);c&&c.cuePoints.push(o)}for(let o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){let l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,a=-1/0;for(let o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(let o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,Et,Jt);n instanceof Promise&&(n=await n),w(n);let i=e,s=er(n);w(s);let a=s.id;w(a===N.Cluster);let o=s.size,c=n.filePos;o===void 0&&(o=(await mc(this.reader,c,na,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);let u={segment:t,elementStartPos:i,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){let d=this.readContiguousElements(l,na);u.elementEndPos=d}for(let[,d]of u.trackData){let h=d.track;w(d.blocks.length>0);let f=!1;for(let y=0;y<d.blocks.length;y++){let b=d.blocks[y];b.timestamp+=u.timestamp,f||=b.lacing!==Nr.None}d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){let b=d.presentationTimestamps[y],k=d.blocks[b.blockIndex];if(d.firstKeyFrameTimestamp===null&&k.isKeyFrame&&(d.firstKeyFrameTimestamp=k.timestamp),y<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[y+1];k.duration=T.timestamp-k.timestamp}else k.duration===0&&h.defaultDuration!=null&&k.lacing===Nr.None&&(k.duration=h.defaultDuration)}f&&(this.expandLacedBlocks(d.blocks,h),d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));let p=d.blocks[d.presentationTimestamps[0].blockIndex],m=d.blocks[ze(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=m.timestamp+m.duration;let g=_e(h.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(g===-1||h.clusterPositionCache[g].elementStartPos!==i)&&h.clusterPositionCache.splice(g+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let i=e.segment.tracks.find(s=>s.id===t);if(!i)return null;n={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let i=e[n];if(i.lacing===Nr.None)continue;i.decoded||(i.data=this.decodeBlockData(t,i.data),i.decoded=!0);let s=yt.tempFromBytes(i.data),a=[],o=ce(s)+1;switch(i.lacing){case Nr.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){let h=ce(s);if(d+=h,h<255){a.push(d),l+=d;break}}}a.push(s.length-(s.bufferPos+l))}break;case Nr.FixedSize:{let l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case Nr.Ebml:{let l=Gi(s);w(l!==null);let u=l;a.push(u);let d=u;for(let h=1;h<o-1;h++){let f=s.bufferPos,p=Gi(s);w(p!==null);let m=p,y=(1<<(s.bufferPos-f)*7-1)-1,b=m-y;u+=b,a.push(u),d+=u}a.push(s.length-(s.bufferPos+d))}break;default:w(!1)}w(a.length===o),e.splice(n,1);let c=i.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){let u=a[l],d=ie(s,u),h=i.timestamp+c*l/o,f=c/o;e.splice(n+l,0,{timestamp:h,duration:f,isKeyFrame:i.isKeyFrame,data:d,lacing:Nr.None,decoded:!0,mainAdditional:i.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===N.Tags&&!e.tagsSeen)){if(!(t.id===N.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Et,Jt);if(n instanceof Promise&&(n=await n),!n)continue;let i=er(n);if(!i||i.id!==t.id)continue;let{size:s}=i;Ur(s),w(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,s);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===N.Tags?e.tagsSeen=!0:t.id===N.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Et;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let n=er(e);if(!n||t&&t.includes(n.id))return!1;let{id:i,size:s}=n,a=e.filePos;switch(Ur(s),i){case N.DocType:this.isWebM=mn(e,s)==="webm";break;case N.Seek:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case N.SeekID:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=Ce(e,s)}break;case N.SeekPosition:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=Ce(e,s)}break;case N.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Ce(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case N.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=fc(e,s)}break;case N.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...dt,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==pc.Block||o.data.algorithm!==ia.HeaderStripping)&&(we._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 o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let u=this.currentTrack.info.displayWidth*this.currentTrack.info.height,d=this.currentTrack.info.displayHeight*this.currentTrack.info.width;u>0&&d>0&&(u>d?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*u/d):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*d/u))}this.currentTrack.codecId===Bt.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Bt.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.vp8?this.currentTrack.info.codec="vp8":c===Bt.vp9?this.currentTrack.info.codec="vp9":c===Bt.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack;this.currentTrack.trackBacking=new zu(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===Bt.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Bt.mp3?this.currentTrack.info.codec="mp3":c===Bt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Un):c===Bt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.eac3?(this.currentTrack.info.codec="eac3",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;this.currentTrack.trackBacking=new Vu(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case N.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=Ce(e,s)}break;case N.TrackType:{if(!this.currentTrack)break;let o=Ce(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case N.FlagEnabled:{if(!this.currentTrack)break;Ce(e,s)||(this.currentTrack=null)}break;case N.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Ce(e,s)}break;case N.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Ce(e,s)}break;case N.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Ce(e,s)}break;case N.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Ce(e,s)}break;case N.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Ce(e,s)}break;case N.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Ce(e,s)}break;case N.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=mn(e,s)}break;case N.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=ie(e,s)}break;case N.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Ce(e,s)}break;case N.Name:{if(!this.currentTrack)break;this.currentTrack.name=ji(e,s)}break;case N.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=mn(e,s),Ei(this.currentTrack.languageCode)||(this.currentTrack.languageCode=je)}break;case N.LanguageBCP47:{if(!this.currentTrack)break;let c=mn(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=je,this.currentTrack.hasLanguageBcp47=!0}break;case N.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case N.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=Ce(e,s)}break;case N.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=Ce(e,s)}break;case N.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=Ce(e,s)}break;case N.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=Ce(e,s)}break;case N.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=Ce(e,s)}break;case N.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=Ce(e,s)===1}break;case N.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,s))}break;case N.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=Rn[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case N.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=Ce(e,s)===2}break;case N.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=Fn[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case N.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=Mn[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case N.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case N.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-fc(e,s);try{this.currentTrack.info.rotation=_i(c)}catch{}}break;case N.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case N.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=fc(e,s)}break;case N.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=Ce(e,s)}break;case N.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=Ce(e,s)}break;case N.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case N.CueTime:this.currentCueTime=Ce(e,s);break;case N.CueTrackPositions:{if(this.currentCueTime===null)break;w(this.currentSegment);let o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case N.CueTrack:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=Ce(e,s)}break;case N.CueClusterPosition:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;w(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+Ce(e,s)}break;case N.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Ce(e,s)}break;case N.SimpleBlock:{if(!this.currentCluster)break;let o=Gi(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=ra(e),u=ce(e),d=u>>1&3,h=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(h=!0);let f=ie(e,s-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:h,data:f,lacing:d,decoded:!p,mainAdditional:null})}break;case N.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case N.Block:{if(!this.currentCluster)break;let o=Gi(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=ra(e),d=ce(e)>>1&3,h=ie(e,s-(e.filePos-a)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:h,lacing:d,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case N.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case N.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case N.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=ie(e,s)}break;case N.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Ce(e,s)}break;case N.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Ce(e,s)}break;case N.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case N.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case N.Targets:this.readContiguousElements(e.slice(a,s));break;case N.TargetTypeValue:Ce(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case N.TagTrackUID:case N.TagEditionUID:case N.TagChapterUID:case N.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case N.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case N.TagName:this.currentSimpleTagName=ji(e,s);break;case N.TagString:{if(!this.currentSimpleTagName)break;let o=ji(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case N.TagBinary:{if(!this.currentSimpleTagName)break;let o=ie(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case N.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));let o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new Ks(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}o.images??=[],o.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 N.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=sg(e,s)}break;case N.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ji(e,s)}break;case N.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=mn(e,s)}break;case N.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=ie(e,s)}break;case N.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ji(e,s)}break;case N.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case N.ContentEncoding:this.currentDecodingInstruction={order:0,scope:pc.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case N.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Ce(e,s)}break;case N.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Ce(e,s)}break;case N.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:ia.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case N.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Ce(e,s)}break;case N.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=ie(e,s)}break;case N.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,t){w(e.decodingInstructions.length>0);let n=t;for(let i of e.decodingInstructions)switch(w(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case ia.HeaderStripping:if(i.data.settings&&i.data.settings.length>0){let s=i.data.settings,a=new Uint8Array(s.length+n.length);a.set(s,0),a.set(n,s.length),n=a}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":n.title??=t;break;case"description":n.description??=t;break;case"artist":n.artist??=t;break;case"album":n.album??=t;break;case"album_artist":n.albumArtist??=t;break;case"genre":n.genre??=t;break;case"comment":n.comment??=t;break;case"lyrics":n.lyrics??=t;break;case"date":{let i=new Date(t);Number.isNaN(i.getTime())||(n.date??=i)}break;case"track_number":case"part_number":{let i=t.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.tracksTotal??=a)}break;case"disc_number":case"disc":{let i=t.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.discsTotal??=a)}break}}},yc=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let i of e.segments)for(let s of i.tracks)if(s.trackBacking.getType()===t&&n++,s===this.internalTrack)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor,n=await this.getFirstPacket({metadataOnly:!0});return t+=n?.timestamp??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Mr(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=_e(s.presentationTimestamps,n,l=>l.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let s=i.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=Pi(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let a=i.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>n.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.blocks.findIndex(o=>o.isKeyFrame);return w(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[t];w(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let a=n.metadataOnly?st:s.data,o=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?st:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);let u=new Oe(a,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,s.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,n,i,s){let{demuxer:a,segment:o}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:y,correctBlockFound:b}=t(e);if(b)return this.fetchPacketInCluster(e,y,s);y!==-1&&(l=e,u=y)}let d=_e(this.internalTrack.cuePoints,n,y=>y.time),h=d!==-1?this.internalTrack.cuePoints[d]:null,f=_e(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,m=Math.max(h?.clusterPosition??0,p?.elementStartPos??0)||null,g;for(e?m===null||e.elementStartPos>=m?(g=e.elementEndPos,c=e):g=m:g=m??o.clusterSeekStartPos;o.elementEndPos===null||g<=o.elementEndPos-Et;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>i)break}let y=a.reader.requestSliceRange(g,Et,Jt);if(y instanceof Promise&&(y=await y),!y)break;let b=g,k=er(y);if(!k||!qi.includes(k.id)&&k.id!==N.Void){let C=await Uu(a.reader,b,qi,Math.min(o.elementEndPos??1/0,b+cg));if(C){g=C;continue}else break}let T=k.id,x=k.size,v=y.filePos;if(T===N.Cluster){c=await a.readCluster(b,o),x=c.elementEndPos-v;let{blockIndex:C,correctBlockFound:_}=t(c);if(_)return this.fetchPacketInCluster(c,C,s);C!==-1&&(l=c,u=C)}x===void 0&&(w(T!==N.Cluster),x=(await mc(a.reader,v,na,o.elementEndPos)).pos-v);let M=v+x;if(o.elementEndPos===null){let C=a.reader.requestSliceRange(M,Et,Jt);if(C instanceof Promise&&(C=await C),!C)break;if(hc(C)===N.Segment){o.elementEndPos=M;break}}g=M}if(h&&(!l||l.elementStartPos<h.clusterPosition)){let y=this.internalTrack.cuePoints[d-1];w(!y||y.time<h.time);let b=y?.time??-1/0;return this.performClusterLookup(null,t,b,i,s)}return l?this.fetchPacketInCluster(l,u,s):null}},zu=class extends yc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}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;(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({}));let n={codec:Bi({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?Ui(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Ni(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Xo(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Qo(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};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}},Vu=class extends yc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}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:Di({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 sa=async(r,e,t,n=null)=>{let s=e;for(;t===null||s<t;){let a=t!==null?Math.min(65536,t-s):65536,o=r.requestSliceRange(s,4,a);if(o instanceof Promise&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let c=o.filePos,l=K(o),u=r.fileSize!==null?r.fileSize-s:null,d=Qs(l,u);if(d.header&&(!n||d.header.sampleRate===n.sampleRate&&d.header.mpegVersionId===n.mpegVersionId&&d.header.layer===n.layer&&ln(d.header.channel)===ln(n.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};var wc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new vt,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.trackBackings=[new Hu(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,mt);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}let c=It(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}let e=await sa(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Go(t.mpegVersionId,t.channel),i=this.reader.requestSlice(e.startPos+n,4);if(i instanceof Promise&&(i=await i),i){let o=K(i);if(o===Wo||o===qo){if(!this.xingData){let l=this.reader.requestSlice(e.startPos+n+4,12);if(l instanceof Promise&&(l=await l),l){let u=ie(l,12),d=Ae(u),h=d.getUint32(0,!1);this.xingData={frameCount:h&Xs.FrameCount?d.getUint32(4,!1):null,fileSize:h&Xs.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,n=!1;for(;;){let i=this.reader.requestSlice(t,mt);if(i instanceof Promise&&(i=await i),!i)break;let s=It(i);if(!s)break;n=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(a instanceof Promise&&(a=await a),!a)break;pn(a,s,this.metadataTags),t=i.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=aa){let i=this.reader.requestSlice(this.reader.fileSize-aa,aa);i instanceof Promise&&(i=await i),w(i),We(i,3)==="TAG"&&lg(i,this.metadataTags)}return this.metadataTags}finally{e()}}},Hu=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(w(e.firstFrameHeader!==null),w(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){let t=Fp(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return je}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return w(this.demuxer.firstFrameHeader),ln(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:ln(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=ie(s,n.dataSize)}return new Oe(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=Ir(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Wu=1399285583,_T=79764919,ug=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^_T:e<<1;ug[r]=e>>>0&4294967295}var dg=r=>{let e=Ae(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let i=0;i<r.length;i++){let s=r[i];n=(n<<8^ug[n>>>24^s])>>>0}return e.setUint32(22,t,!0),n},hg=(r,e,t)=>{let n=0,i=null;if(r.length>0)if(e.codec==="vorbis"){w(e.vorbisInfo);let s=e.vorbisInfo.modeBlockflags.length,o=(1<<dp(s-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,u=e.vorbisInfo.modeBlockflags[c];if(i=e.vorbisInfo.blocksizes[u],u===1){let d=(o|1)+1,h=r[0]&d?1:0;l=e.vorbisInfo.blocksizes[h]}n=l!==null?l+i>>2:0}else e.codec==="opus"&&(n=qp(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:i}},fg=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var gn=27,Vn=282,mg=Vn+65025,Ki=r=>{let e=r.filePos;if(zn(r)!==Wu)return null;r.skip(1);let n=ce(r),i=gg(r),s=zn(r),a=zn(r),o=zn(r),c=ce(r),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=ce(r);let u=27+c,d=l.reduce((f,p)=>f+p,0),h=u+d;return{headerStartPos:e,totalSize:h,dataStartPos:e+u,dataSize:d,headerType:n,granulePosition:i,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:l}},pg=(r,e)=>{for(;r.filePos<e-3;){let t=zn(r),n=t&255,i=t>>>8&255,s=t>>>16&255,a=t>>>24&255,o=79;if(!(n!==o&&i!==o&&s!==o&&a!==o)){if(r.skip(-4),t===Wu)return!0;r.skip(1)}}return!1};var bc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,gn,Vn);if(t instanceof Promise&&(t=await t),!t)break;let n=Ki(t);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let t of this.bitstreams){let n=await this.readPacket(t.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,t):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,t),t.codecInfo.codec!==null&&this.trackBackings.push(new qu(t,this)))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||(n=await this.findNextPacketStart(i),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||i.data[0]!==3||s.data[0]!==5)return;let a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(i.data.length);let c=new Uint8Array(1+a.length+e.data.length+i.data.length+s.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(i.data,1+a.length+e.data.length),c.set(s.data,1+a.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=s;let l=Ae(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Gp(s.data).modeBlockflags},Js(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;let s=Yo(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=Un,t.codecInfo.opusInfo={preSkip:s.preSkip},Js(i.data.subarray(8),this.metadataTags)}async readPacket(e,t){w(t<e.lacingValues.length);let n=0;for(let d=0;d<t;d++)n+=e.lacingValues[d];let i=e,s=n,a=t,o=[];e:for(;;){let d=this.reader.requestSlice(i.dataStartPos,i.dataSize);d instanceof Promise&&(d=await d),w(d);let h=ie(d,i.dataSize);for(;;){if(a===i.lacingValues.length){o.push(h.subarray(n,s));break}let p=i.lacingValues[a];if(s+=p,p<255){o.push(h.subarray(n,s));break e}a++}let f=i.headerStartPos+i.totalSize;for(;;){let p=this.reader.requestSliceRange(f,gn,Vn);if(p instanceof Promise&&(p=await p),!p)return null;let m=Ki(p);if(!m)return null;if(i=m,i.serialNumber===e.serialNumber)break;f=i.headerStartPos+i.totalSize}n=0,s=0,a=0}let c=o.reduce((d,h)=>d+h.length,0);if(c===0)return null;let l=new Uint8Array(c),u=0;for(let d=0;d<o.length;d++){let h=o[d];l.set(h,u),u+=h.length}return{data:l,endPage:i,endSegmentIndex:a}}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 i=this.reader.requestSliceRange(n,gn,Vn);if(i instanceof Promise&&(i=await i),!i)return null;let s=Ki(i);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.trackBackings.map(t=>t.getDecoderConfig().then(n=>n?.codec??null)));return fg({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},qu=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new vt,this.internalSampleRate=e.codecInfo.codec==="opus"?Un:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return w(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return w(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 je}getDisposition(){return{...dt,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(w(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:i,vorbisBlockSize:s}=hg(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new Oe(n.metadataOnly?st:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){w(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(w(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let i=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let i=await this.demuxer.findNextPacketStart(n.packet);if(!i)return null;let s=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=Mr(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;w(this.bitstream.lastMetadataPacket);let i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let s=i.startPage,a=this.demuxer.reader.fileSize,o=[s];e:for(;s.headerStartPos+s.totalSize<a;){let b=s.headerStartPos,k=Math.floor((b+a)/2),T=k;for(;;){let x=Math.min(T+mg,a-gn),v=this.demuxer.reader.requestSlice(T,x-T);if(v instanceof Promise&&(v=await v),w(v),!pg(v,x)){a=k+gn;continue e}let C=this.demuxer.reader.requestSliceRange(v.filePos,gn,Vn);C instanceof Promise&&(C=await C),w(C);let _=Ki(C);w(_);let F=!1;if(_.serialNumber===this.bitstream.serialNumber)F=!0;else{let O=this.demuxer.reader.requestSlice(_.headerStartPos,_.totalSize);O instanceof Promise&&(O=await O),w(O);let Q=ie(O,_.totalSize);F=dg(Q)===_.checksum}if(!F){T=_.headerStartPos+4;continue}if(F&&_.serialNumber!==this.bitstream.serialNumber){T=_.headerStartPos+_.totalSize;continue}if(_.granulePosition===-1){T=_.headerStartPos+_.totalSize;continue}this.granulePositionToTimestampInSamples(_.granulePosition)>n?a=_.headerStartPos:(s=_,o.push(_));continue e}}let c=i.startPage;for(let b of o){if(b.granulePosition===s.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){let b=l.headerStartPos+l.totalSize,k=this.demuxer.reader.requestSliceRange(b,gn,Vn);k instanceof Promise&&(k=await k),w(k);let T=Ki(k);w(T),l=T,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}w(l.granulePosition!==-1);let d=null,h,f,p=l,m=0;if(l.headerStartPos===i.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,d=0;else{h=0,f=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;let b={data:st,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(b)){let T=wg(u,l,d);w(T);let x=yg(u,T.page,T.segmentIndex);x&&(l=x.page,d=x.segmentIndex)}else for(;;){let T=wg(u,l,d);if(!T)break;let x=yg(u,T.page,T.segmentIndex);if(!x)break;if(l=x.page,d=x.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,m=T.segmentIndex;break}}}let g=null,y=null;for(;l!==null;){w(d!==null);let b=await this.demuxer.readPacket(l,d);if(!b)break;if(!(l.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let x=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);w(x);let v=this.encodedPacketToMetadata.get(x);if(w(v),!f&&b.endPage.headerStartPos===p.headerStartPos&&b.endSegmentIndex===m?(h=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,x=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h-v.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),w(x),v=this.encodedPacketToMetadata.get(x),w(v)):h+=v.durationInSamples,g=x,y=v,f&&(Math.max(h,0)>n||Math.max(v.timestampInSamples,0)===n))break}let T=await this.demuxer.findNextPacketStart(b);if(!T)break;l=T.startPage,d=T.startSegmentIndex}return g}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let i=Mr(e*this.internalSampleRate);e=i/this.internalSampleRate;let s=_e(this.sequentialScanCache,i,c=>c.timestampInSamples),a;if(s!==-1){let c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){let c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;let l=this.encodedPacketToMetadata.get(a);w(l),this.sequentialScanCache.length>0&&w(ze(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},yg=(r,e,t)=>{let n=e,i=t;e:for(;;){for(i--,i;i>=0;i--)if(n.lacingValues[i]<255){i++;break e}if(w(i===-1),!(n.headerType&1)){i=0;break}let a=Tu(r,o=>o.headerStartPos<n.headerStartPos);if(!a)return null;n=a,i=n.lacingValues.length}if(w(i!==-1),i===n.lacingValues.length){let s=r[r.indexOf(n)+1];w(s),n=s,i=0}return{page:n,segmentIndex:i}},wg=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let n=Tu(r,i=>i.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var Vr;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Vr||(Vr={}));var kc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],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),w(e);let t=We(e,4),n=t!=="RIFX",i=t==="RF64",s=Hr(e,n),a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(We(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;a===null||u<a;){let h=this.reader.requestSlice(u,8);if(h instanceof Promise&&(h=await h),!h)break;let f=We(h,4),p=Hr(h,n),m=h.filePos;if(i&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(m,p,n);else if(f==="data"){if(l??=p,this.dataStart=h.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let g=this.reader.requestSlice(m,p);if(g instanceof Promise&&(g=await g),!g)break;let y=ju(g,n);l=ju(g,n),a=Math.min(y+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(m,p,n):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(m,p);u=m+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new Gu(this))})()}async parseFmtChunk(e,t,n){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let s=Xi(i,n),a=Xi(i,n),o=Hr(i,n);i.skip(4);let c=Xi(i,n),l;if(t===14?l=8:l=Xi(i,n),t>=18&&s!==357){let u=Xi(i,n),d=t-18;if(Math.min(d,u)>=22&&s===Vr.EXTENSIBLE){i.skip(6);let f=ie(i,16);s=f[0]|f[1]<<8}}(s===Vr.MULAW||s===Vr.ALAW)&&(l=8),this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,n){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let s=We(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+t-8;){i.filePos=a;let o=We(i,4),c=Hr(i,n),l=ie(i,c),u=0;for(let h=0;h<l.length&&l[h]!==0;h++)u++;let d=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=d,o){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let h=d.split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[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 h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"YEAR":{let h=Number.parseInt(d,10);Number.isInteger(h)&&h>0&&(this.metadataTags.date??=new Date(h,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+c+(c&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let i=It(n);if(i){let s=t-mt;if(i.size=Math.min(i.size,s),i.size>0){let a=n.slice(e+mt,i.size);pn(a,i,this.metadataTags)}}}getCodec(){if(w(this.audioInfo),this.audioInfo.format===Vr.MULAW)return"ulaw";if(this.audioInfo.format===Vr.ALAW)return"alaw";if(this.audioInfo.format===Vr.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===Vr.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},$i=2048,Gu=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(w(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return w(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return je}getDisposition(){return{...dt}}async getPacketAtIndex(e,t){w(e>=0),w(this.demuxer.audioInfo);let n=e*$i*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let i=Math.min($i*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);if(c instanceof Promise&&(c=await c),!c)return null}let s;if(t.metadataOnly)s=st;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);c instanceof Promise&&(c=await c),w(c),s=ie(c,i)}let a=e*$i/this.demuxer.audioInfo.sampleRate,o=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Oe(s,"key",a,o,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){w(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/$i,(this.demuxer.dataSize-1)/($i*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let i=await this.getPacketAtIndex(n,t);if(i)return i;if(n===0)return null;w(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){let a=await this.getNextPacket(s,t);if(!a)break;s=a}return s}getNextPacket(e,t){w(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/$i);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Hn=7,tr=9,rr=r=>{let e=r.filePos,t=ie(r,9),n=new Ie(t);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let a=n.readBits(1),o=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 u=n.readBits(13);n.skipBits(11);let d=n.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?r.filePos-=2:h=n.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:h,startPos:e}};var oa=1024,Sc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new vt,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();w(this.firstFrameHeader),this.trackBackings=[new Ku(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,mt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let o=It(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Hn,tr);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=rr(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=fr[t.samplingFrequencyIndex];w(n!==void 0);let i=oa/n,s={timestamp:this.nextTimestampInSamples/n,duration:i,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=oa,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let n=this.reader.requestSlice(t,mt);if(n instanceof Promise&&(n=await n),!n)break;let i=It(n);if(!i)break;let s=this.reader.requestSlice(n.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;pn(s,i,this.metadataTags),t=n.filePos+i.size}return this.metadataTags}finally{e()}}},Ku=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/oa}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return je}getCodec(){return"aac"}getInternalCodecId(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){w(this.demuxer.firstFrameHeader);let e=on[this.demuxer.firstFrameHeader.channelConfiguration];return w(e!==void 0),e}getSampleRate(){w(this.demuxer.firstFrameHeader);let e=fr[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return w(e!==void 0),e}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=ie(s,n.dataSize)}return new Oe(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=Ir(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var bg=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,kg=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Sg=r=>{let e=0,t=new Ie(ie(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let n=[],i=e-1,s=new Ie(ie(r,i)),a=8-e-1;for(let c=0;c<a;c++)n.unshift(t.readBits(1));for(let c=0;c<i;c++)for(let l=0;l<8;l++){let u=s.readBits(1);l<2||n.unshift(u)}return n.reduce((c,l,u)=>c|l<<u,0)},xg=(r,e)=>{if(e==="uncommon-u16")return Ke(r)+1;if(e==="uncommon-u8")return ce(r)+1;if(typeof e=="number")return e;Ct(e),w(!1)},Tg=(r,e)=>e==="uncommon-u16"?Ke(r):e==="uncommon-u16-10"?Ke(r)*10:e==="uncommon-u8"?ce(r):typeof e=="number"?e:null,Ag=r=>{let t=0;for(let n of r){t^=n;for(let i=0;i<8;i++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var xc=class extends ct{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new vt,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),w(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,mt);if(t instanceof Promise&&(t=await t),!t){this.lastSampleLoaded=!0;return}let n=It(t);if(!n)break;let i=this.reader.requestSlice(t.filePos,n.size);i instanceof Promise&&(i=await i),w(i),pn(i,n,this.metadataTags),e=t.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);w(t);let n=ce(t),i=Zt(t),s=(n&128)!==0;switch(n&127){case dn.STREAMINFO:{let o=this.reader.requestSlice(e,i);if(o instanceof Promise&&(o=await o),w(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=ie(o,34),l=new Ie(c),u=l.readBits(16),d=l.readBits(16),h=l.readBits(24),f=l.readBits(24),p=l.readBits(20),m=l.readBits(3)+1;l.readBits(5);let g=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:p,totalSamples:g,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:h,maximumFrameSize:f,description:y},this.trackBacking=new $u(this);break}case dn.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,i);o instanceof Promise&&(o=await o),w(o),Js(ie(o,i),this.metadataTags);break}case dn.PICTURE:{let o=this.reader.requestSlice(e,i);o instanceof Promise&&(o=await o),w(o);let c=K(o),l=K(o),u=ot.decode(ie(o,l)),d=K(o),h=ot.decode(ie(o,d));o.skip(16);let f=K(o),p=ie(o,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:u,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:h});break}default:break}if(e+=i,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){w(this.audioInfo);let n=6,i=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,o=this.audioInfo.minimumFrameSize||s,l=(this.audioInfo.maximumFrameSize||a)+i,u=await this.reader.requestSliceRange(e,i,l);if(!u)return null;let d=this.readFlacFrameHeader({slice:u,isFirstPacket:t});if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-n)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(ce(u)===255){let f=u.filePos,p=ce(u),m=this.blockingBit===1?249:248;if(p!==m){u.filePos=f;continue}u.skip(-2);let g=u.filePos-e,y=this.readFlacFrameHeader({slice:u,isFirstPacket:!1});if(!y){u.filePos=f;continue}if(this.blockingBit===0){if(y.num-d.num!==1){u.filePos=f;continue}}else if(y.num-d.num!==d.blockSize){u.filePos=f;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:g,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,i=ie(e,4),s=new Ie(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){w(t);let g=s.readBits(1);this.blockingBit=g}else if(this.blockingBit===1){if(w(!t),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(w(!t),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let o=bg(s.readBits(4));if(!o)return null;w(this.audioInfo);let c=kg(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let u=Sg(e),d=xg(e,o),h=Tg(e,c);if(h===null||h!==this.audioInfo.sampleRate)return null;let f=e.filePos-n,p=ce(e);e.skip(-f),e.skip(-1);let m=Ag(ie(e,f));return p!==m?null:{num:u,blockSize:d,sampleRate:h}}async advanceReader(){await this.readMetadata(),w(this.lastLoadedPos!==null),w(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(s),t.isLastFrame){this.lastSampleLoaded=!0;return}}},$u=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return je}getTimeResolution(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(w(this.demuxer.audioInfo),e<0)return null;let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(i===-1){await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[i],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(i,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let o=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;i=ie(o,n.byteSize)}w(this.demuxer.audioInfo);let s=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new Oe(i,"key",s,a,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 vg=r=>{let e="video/MP2T",t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};var Cg="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",_g=new Set,Tc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=205,t=this.reader.requestSlice(0,e);t instanceof Promise&&(t=await t),w(t);let n=ie(t,e);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let i=256;this.minReferencePointByteDistance=i*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){let l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===l.pid)){s+=this.packetStride;continue}let u=await this.readSection(s,!0,!c);if(!u)break;let d=3,h=32,f=!1;if(!c&&u.pid!==0&&!(u.payload[0]===0&&u.payload[1]===0&&u.payload[2]===1)){let g=new Ie(u.payload),y=g.readAlignedByte();g.skipBits(8*y),f=g.readBits(8)===2}if(u.pid===0&&!o){let m=new Ie(u.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(14);let y=m.readBits(10);for(m.skipBits(40);8*(y+d)-m.pos>h;){let b=m.readBits(16);m.skipBits(3);let k=m.readBits(13);if(b!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=k}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((u.pid===a||f)&&!c){let m=new Ie(u.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(12);let y=m.readBits(12);m.skipBits(43);let b=m.readBits(13);m.skipBits(6);let k=m.readBits(10);for(m.skipBits(8*k);8*(y+d)-m.pos>h;){let T=m.readBits(8);m.skipBits(3);let x=m.readBits(13);m.skipBits(6);let v=m.readBits(10),M=m.pos+8*v,C=!1,_=!1;for(;m.pos<M;){let E=m.readBits(8),O=m.readBits(8);E===106?C=!0:(E===122||E===204)&&(_=!0),m.skipBits(8*O)}let F=null;switch(T){case 27:case 36:F={type:"video",codec:T===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let E;if(T===3||T===4)E="mp3";else if(T===15)E="aac";else if(T===129)E="ac3";else if(T===135)E="eac3";else throw new Error("Unreachable.");F={type:"audio",codec:E,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:_?F={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:C&&(F={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:_g.has(T)||(we._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),_g.add(T))}F&&this.elementaryStreams.push({demuxer:this,pid:x,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:F,referencePesPackets:[]})}c=!0}else{let m=this.elementaryStreams.find(g=>g.pid===u.pid);e:if(m&&!m.initialized){let g=Qi(u,!0);if(!g)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=u,m.canBeTrustedWithKeyPackets=u.randomAccessIndicator===1,this.input._initInput){let k=(await this.input._initInput._getDemuxer()).elementaryStreams.find(T=>T.pid===u.pid&&T.info.codec===m.info.codec);if(k){m.info=k.info,m.initialized=!0;break e}}let y=new qn(m,g);if(m.info.type==="video"){for(;;){let b=y;if(b.suppliedPacket=null,await y.markNextPacket(),m.info.codec==="avc"){if(!y.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=Ui(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;let k=m.info.avcCodecInfo.sequenceParameterSets[0];w(k);let T=Zs(k);m.info.width=T.displayWidth,m.info.height=T.displayHeight;let x=T.pixelAspectRatio.num,v=T.pixelAspectRatio.den;x>0&&v>0&&(x>v?(m.info.squarePixelWidth=Math.round(m.info.width*x/v),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*v/x))),m.info.colorSpace={primaries:Mn[T.colourPrimaries],transfer:Fn[T.transferCharacteristics],matrix:Rn[T.matrixCoefficients],fullRange:!!T.fullRangeFlag},m.info.reorderSize=T.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!y.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=Ni(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;let T=m.info.hevcCodecInfo.arrays.find(v=>v.nalUnitType===it.SPS_NUT).nalUnits[0];w(T);let x=Mu(T);m.info.width=x.displayWidth,m.info.height=x.displayHeight,x.pixelAspectRatio.num>x.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*x.pixelAspectRatio.num/x.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*x.pixelAspectRatio.den/x.pixelAspectRatio.num)),m.info.colorSpace={primaries:Mn[x.colourPrimaries],transfer:Fn[x.transferCharacteristics],matrix:Rn[x.matrixCoefficients],fullRange:!!x.fullRangeFlag},m.info.reorderSize=x.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Bi({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await y.markNextPacket(),!y.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){let b=yt.tempFromBytes(y.suppliedPacket.data),k=rr(b);if(!k)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:k.objectType},m.info.numberOfChannels=on[k.channelConfiguration],m.info.sampleRate=fr[k.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){let b=K(yt.tempFromBytes(y.suppliedPacket.data)),k=Qs(b,y.suppliedPacket.data.byteLength);if(!k.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=ln(k.header.channel),m.info.sampleRate=k.header.sampleRate}else if(m.info.codec==="ac3"){let b=Zo(y.suppliedPacket.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=ea[b.acmod]+b.lfeon,m.info.sampleRate=Nn[b.fscod]}else if(m.info.codec==="eac3"){let b=Jo(y.suppliedPacket.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let k=ec(b);if(k===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=tc(b),m.info.sampleRate=k}else throw new Error("Unhandled.");m.info.decoderConfig={codec:Di({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let l of this.elementaryStreams)l.info.type==="video"?this.trackBackingEntries.push(new Xu(l)):this.trackBackingEntries.push(new Qu(l))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(n=>n?.codec??null)));return vg(e)}async readSection(e,t,n=!1){let i=e,s=e,a=[],o=0,c=null,l=!0,u=0;for(;;){let h=await this.readPacket(s);if(s+=this.packetStride,!h)break;if(c){if(h.pid!==c.pid){if(n)break;continue}if(h.payloadUnitStartIndicator===1)break}else{if(h.payloadUnitStartIndicator===0)break;c=h}let f=!!(h.adaptationFieldControl&2),p=!!(h.adaptationFieldControl&1),m=0;if(f&&(m=1+h.body[0],h===c&&m>1&&(u=h.body[1]>>6&1)),p&&(m===0?(a.push(h.body),o+=h.body.byteLength):(a.push(h.body.subarray(m)),o+=h.body.byteLength-m)),i=s,!t&&o>=64){l=!1;break}if(Ir(this.sectionEndPositions,i,y=>y)!==-1){l=!1;break}}if(l){let h=_e(this.sectionEndPositions,i,f=>f);this.sectionEndPositions.splice(h+1,0,i)}if(!c)return null;let d;if(a.length===1)d=a[0];else{let h=a.reduce((p,m)=>p+m.length,0);d=new Uint8Array(h);let f=0;for(let p of a)d.set(p,f),f+=p.length}return{startPos:e,endPos:t?i:null,pid:c.pid,payload:d,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(ce(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let i=Ke(t),s=i>>15,a=i>>14&1,o=i>>13&1,c=i&8191,l=ce(t),u=l>>6,d=l>>4&3,h=l&15;return{payloadUnitStartIndicator:a,pid:c,adaptationFieldControl:d}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=ie(t,188);if(n[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let s=(n[1]<<8)+n[2],a=s>>15,o=s>>14&1,c=s>>13&1,l=s&8191,u=n[3],d=u>>6,h=u>>4&3,f=u&15;return{payloadUnitStartIndicator:o,pid:l,adaptationFieldControl:h,body:n.subarray(4)}}},Wn=(r,e)=>{if(r.payload.byteLength<3)return null;let t=new Ie(r.payload);if(t.readBits(24)!==1)return null;let i=t.readBits(8);if(t.skipBits(16),i===188||i===190||i===191||i===240||i===241||i===255||i===242||i===248)return null;t.skipBits(8);let s=t.readBits(2);t.skipBits(14);let a=null;if(s===2||s===3)a=0,t.skipBits(4),a+=t.readBits(3)*(1<<30),t.skipBits(1),a+=t.readBits(15)*32768,t.skipBits(1),a+=t.readBits(15);else if(e)throw new Error(Cg);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},Qi=(r,e)=>{w(r.endPos!==null);let t=Wn(r,e);if(!t)return null;let n=new Ie(r.payload);n.skipBits(32);let i=n.readBits(16),s=6;n.skipBits(16);let a=n.readBits(8),o=n.pos+8*a;n.pos=o;let c=o/8;w(Number.isInteger(c));let l=r.payload.subarray(c,i>0?s+i:r.payload.byteLength);return{...t,data:l}},Ac=class r{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type,n=0;for(let i of e.trackBackingEntries)if(i.getType()===t&&n++,w(i instanceof r),i.elementaryStream===this.elementaryStream)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return je}getDisposition(){return{...dt,primary:!1}}getTimeResolution(){return 9e4}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,n){let i;return this.allPacketsAreKeyPackets()?i="key":i=e.randomAccessIndicator===1?"key":"delta",new Oe(n.metadataOnly?st:e.data,i,e.pts/9e4,Math.max(t/9e4,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;w(t);let n=Qi(t,!0);w(n);let i=new qn(this.elementaryStream,n),s=new ca(this,i),a=await s.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){let u=await n.readNext();if(!u)return null;this.packetBuffers.delete(e);let d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}let i=this.packetSectionStarts.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");let a=await this.elementaryStream.demuxer.readSection(i,!0);w(a);let o=Qi(a,!0);w(o);let c=new qn(this.elementaryStream,o);n=new ca(this,c);let l=e.sequenceNumber;for(;;){let u=await n.readNext();if(!u)return null;if(u.packet.sequenceNumber>l){let d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type==="key")return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){let i=Mr(e*9e4),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,l=async(T,x,v)=>{let M=T;for(;M<x;){let C=await s.readPacketHeader(M);if(!C)return null;if(C.pid===c&&C.payloadUnitStartIndicator===1){let _=await s.readSection(M,v);if(!_)return null;let F=Wn(_,!1);if(F&&F.pts!==null)return{pesPacketHeader:F,section:_}}M+=s.packetStride}return null},u=this.elementaryStream.firstSection;w(u);let d=Wn(u,!0);if(w(d),i<d.pts)return null;let h,f=this.elementaryStream.referencePesPackets,p=_e(f,i,T=>T.pts),m=p!==-1?f[p]:null;if(m&&i-m.pts<9e4/2)h=m.sectionStartPos;else{let T=0;if(a.fileSize!==null){let x=Math.ceil(a.fileSize/o);if(x>1){let v=0,M=x-1;for(T=v;v<=M;){let C=Math.floor((v+M)/2),_=No(C*o,s.packetStride)+d.sectionStartPos,F=_+o,E=await l(_,F,!1);if(!E){M=C-1;continue}E.pesPacketHeader.pts<=i?(T=C,v=C+1):M=C-1}}}h=No(T*o,s.packetStride)+d.sectionStartPos}let y=(await l(h,a.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);let b=this.getReorderSize(),k=async(T,x)=>{let v=await s.readSection(T,!0);w(v);let M=Qi(v,!0);w(M);let C=new qn(this.elementaryStream,M),_=new ca(this,C);for(;!((ze(_.presentationOrderPackets)?.pts??-1/0)>=i||!await _.readNextPacket()););let F=Pi(_.presentationOrderPackets,x);if(F===-1)return null;let E=_.presentationOrderPackets[F],O=F===0?0:E.pts-_.presentationOrderPackets[F-1].pts;for(;_.decodeOrderPackets[0]!==E;)_.decodeOrderPackets.shift();_.lastDuration=O;let Q=await _.readNext();w(Q);let ye=this.createEncodedPacket(Q.packet,Q.duration,n);return this.packetBuffers.set(ye,_),this.packetSectionStarts.set(ye,Q.packet.sectionStartPos),ye};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let T=y.sectionStartPos+s.packetStride;for(;;){let x=await s.readPacketHeader(T);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){let v=await s.readSection(T,!1);if(v){let M=Wn(v,!1);if(M&&M.pts!==null){if(M.pts>i)break e;y=M,Yu(this.elementaryStream,y);break}}}T+=s.packetStride}}e:for(let T=0;T<b+1;T++){let x=y.sectionStartPos-s.packetStride;for(;x>=s.packetOffset;){let v=await s.readPacketHeader(x);if(!v)break e;if(v.pid===c&&v.payloadUnitStartIndicator===1){let M=await s.readSection(x,!1);if(M){let C=Wn(M,!1);if(C&&C.pts!==null){y=C;break}}}x-=s.packetStride}}return k(y.sectionStartPos,T=>T.pts<=i)}else{let T=h,x=null,v=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let M=null,C=T<=d.sectionStartPos,_,F=null;if(C)_=d,F=u;else{let Q=await l(T,a.fileSize??1/0,v);_=Q?.pesPacketHeader??null,F=Q?.section??null}let E=!1,O=0;e:for(;_&&!(x!==null&&_.sectionStartPos>=x);){if(_.pts<=i){let ye;if(this.elementaryStream.canBeTrustedWithKeyPackets)ye=_.randomAccessIndicator===1;else{w(F);let Z=Qi(F,!0);w(Z);let ee=new qn(this.elementaryStream,Z);await ee.markNextPacket(),ye=ee.suppliedPacket?.randomAccessIndicator===1}ye&&(M=_)}if(_.pts>i&&(E=!0),E&&(O++,O>b))break;let Q=_.sectionStartPos+s.packetStride;for(;;){let ye=await s.readPacketHeader(Q);if(!ye)break e;if(ye.pid===c&&ye.payloadUnitStartIndicator===1){let Z=await s.readSection(Q,v);if(Z){let ee=Wn(Z,!1);if(ee&&ee.pts!==null){_=ee,F=Z,Yu(this.elementaryStream,_);break}}}Q+=s.packetStride}}if(M){let Q=M;if(O===0)e:for(let Z=0;Z<b;Z++){let ee=Q.sectionStartPos-s.packetStride;for(;ee>=s.packetOffset;){let ve=await s.readPacketHeader(ee);if(!ve)break e;if(ve.pid===c&&ve.payloadUnitStartIndicator===1){let Re=await s.readSection(ee,v);if(Re){let et=Wn(Re,!1);if(et&&et.pts!==null){Q=et;break}}}ee-=s.packetStride}}let ye=await k(Q.sectionStartPos,Z=>Z.pts<=i&&Z.randomAccessIndicator===1);return w(ye),ye}if(C)return null;x=T,T=Math.max(No(T-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},Xu=class extends Ac{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return w(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Qu=class extends Ac{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return w(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},Yu=(r,e)=>{let t=r.referencePesPackets,n=_e(t,e.sectionStartPos,i=>i.sectionStartPos);if(n>=0){let i=t[n];if(e.pts<=i.pts)return!1;let s=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-i.sectionStartPos<s)return!1;if(n<t.length-1){let a=t[n+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return t.splice(n+1,0,e),!0},qn=class{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return w(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let n;if(this.pesPackets.length===0)n=this.startingPesPacket;else{let i=ze(this.pesPackets).sectionEndPos;for(w(i!==null);;){let s=await this.demuxer.readPacketHeader(i);if(!s)return;if(s.pid===this.pid){let a=await this.demuxer.readSection(i,!0);if(!a)return;let o=Qi(a,!1);if(o){n=o;break}}i+=this.demuxer.packetStride}}this.pesPackets.push(n),this.endPos+=n.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,i=n+e;if(this.currentPos+=e,i<=t.data.byteLength)return t.data.subarray(n,i);let s=new Uint8Array(e);s.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){let t=this.getCurrentPesPacket(),n=this.currentPesPacketPos+t.data.byteLength;if(e<n)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){w(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type==="video"){let t=e.info.codec,n=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");let i=t==="avc"?1:2,s=null,a=!1,o=0;for(;;){let c=this.ensureBuffered(n);if(c instanceof Promise&&(c=await c),c===0)break;let l=this.currentPos,u=this.readBytes(c),d=u.byteLength,h=0;for(;h<d;){let f=u.indexOf(0,h);if(f===-1||f>=d)break;h=f;let p=l+h;if(h+3>=d){this.seekTo(p);break}let m=u[h+1],g=u[h+2],y=u[h+3],b=0;if(m===0&&g===0&&y===1?b=4:m===0&&g===1&&(b=3),b===0){h++;continue}let k=p;s??=k;let T=h+b,x=T+i,v=6;if(x+(t==="avc"?v:1)>d){this.seekTo(p);break}let C=u[T],_,F,E;if(t==="avc")_=Li(C),F=_===lt.NON_IDR_SLICE||_===lt.SLICE_DPA||_===lt.IDR,E=_===lt.SEI||_===lt.SPS||_===lt.PPS||_===lt.AUD;else{if(_=un(C),((C&1)<<5|u[T+1]>>3)>0){h+=b;continue}F=_<=it.RASL_R||_>=it.BLA_W_LP&&_<=21,E=_>=it.VPS_NUT&&_<=37||_===it.PREFIX_SEI_NUT||_>=41&&_<=44||_>=48&&_<=55}let O=!1;if(F){let Q;if(t==="avc"){let ye=u.subarray(x,x+v),Z=Y(new Ie(ye));Q=!a||Z<=o,o=Z}else Q=u[x]>>7===1;Q&&(a?O=!0:a=!0)}else E&&a&&(O=!0);if(O){let Q=k-s;return this.seekTo(s),this.supplyPacket(Q,0)}h+=b}if(c<n)break}if(s!==null&&this.endPos>s){let c=this.endPos-s;return this.seekTo(s),this.supplyPacket(c,0)}}else{let t=e.info.codec,n=128;for(;;){let i=this.ensureBuffered(n);i instanceof Promise&&(i=await i);let s=this.currentPos;for(;this.currentPos-s<i;){let a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(tr);if(c instanceof Promise&&(c=await c),c<tr)return;let l=this.readBytes(tr),u=rr(yt.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return d instanceof Promise&&(d=await d),this.supplyPacket(d,Math.round(oa*9e4/e.info.sampleRate))}else this.seekTo(o+1)}else if(t==="mp3"){if(a!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(4);if(c instanceof Promise&&(c=await c),c<4)return;let l=this.readBytes(4),u=Ae(l).getUint32(0),d=Qs(u,null);if(d.header){this.seekTo(o);let h=this.ensureBuffered(d.header.totalSize);h instanceof Promise&&(h=await h);let f=d.header.audioSamplesInFrame*9e4/e.info.sampleRate;return this.supplyPacket(h,Math.round(f))}else this.seekTo(o+1)}else if(t==="ac3"){if(a!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}let h=jp[3*d+u];w(h!==void 0),this.seekTo(o),c=this.ensureBuffered(h),c instanceof Promise&&(c=await c);let f=Math.round(Kp*9e4/e.info.sampleRate);return this.supplyPacket(c,f)}else if(t==="eac3"){if(a!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let d=(((l[2]&7)<<8|l[3])+1)*2,f=l[4]>>6===3?3:l[4]>>4&3,p=Fu[f];this.seekTo(o),c=this.ensureBuffered(d),c instanceof Promise&&(c=await c);let m=p*256,g=Math.round(m*9e4/e.info.sampleRate);return this.supplyPacket(c,g)}else throw new Error("Unhandled.")}if(i<n)break}}}supplyPacket(e,t){let n=this.getCurrentPesPacket(),i;if(this.lastSuppliedPesPacket===n)w(this.nextPts!==null),i=this.nextPts;else{if(n.pts===null)throw new Error(Cg);i=n.pts,Yu(this.elementaryStream,n)}this.lastSuppliedPesPacket=n,this.nextPts=i+t;let s=n.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),c=n.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){let l=hn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(l)}}this.suppliedPacket={pts:i,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},ca=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),w(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);w(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let i=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(i))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(w(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let t=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[t].pts&&(t=i);let n=this.reorderBuffer[t];this.presentationOrderPackets.push(n),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};var vc="application/vnd.apple.mpegurl",Zu="#EXT-X-STREAM-INF:",Ju="#EXT-X-I-FRAME-STREAM-INF:",ed="#EXT-X-MEDIA:",la="#EXTINF:",td="#EXT-X-MAP:",rd="#EXT-X-KEY:",nd="#EXT-X-MEDIA-SEQUENCE:",id="#EXT-X-BYTERANGE:",sd="#EXT-X-PROGRAM-DATE-TIME:",Pg="#EXT-X-DISCONTINUITY",ad="#EXT-X-TARGETDURATION:",Eg="#EXT-X-ENDLIST",od="#EXT-X-PLAYLIST-TYPE:",Ig="#EXT-X-I-FRAMES-ONLY",_c=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT"),qr=class{constructor(e){this._attributes={};let t="",n="",i=!1,s=!1;for(let a=0;a<e.length;a++){let o=e[a];o==='"'?s=!s:o==="="&&!i&&!s?i=!0:o===","&&!s?(t&&(this._attributes[t.trim().toLowerCase()]=n),t="",n="",i=!1):i?n+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=n)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}};var Cc=class{constructor(e,t,n){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=n}async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(t??=await this.getFirstSegment({}),!t||t.unixEpochTimestamp===null)return null;let n=e-t.timestamp;return t.unixEpochTimestamp+n}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type==="video"){let n=On(e,i=>i.getType()==="video")+1;e.push(new Ec(this,t,n))}else if(t.type==="audio"){let n=On(e,i=>i.getType()==="audio")+1;e.push(new Ic(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let n=await this.getInputForSegment(this.firstSegment).getTracks();for(let i of n)if(i.type==="video"){let s=On(e,a=>a.getType()==="video")+1;e.push(new Ec(this,{id:e.length+1,type:"video"},s))}else if(i.type==="audio"){let s=On(e,a=>a.getType()==="audio")+1;e.push(new Ic(this,{id:e.length+1,type:"audio"},s))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(t!==void 0)return t;let n=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,n),n}async getMediaOffset(e,t){let n=e.firstSegment??e,i;if(this.firstSegmentFirstTimestamps.has(n))i=this.firstSegmentFirstTimestamps.get(n);else{let l=this.getInputForSegment(n);i=await this.getFirstTimestampForInput(l),this.firstSegmentFirstTimestamps.set(n,i)}if(n===e)return n.timestamp-i;let s=await this.getFirstTimestampForInput(t),a=e.timestamp-n.timestamp,c=s-i-a;return Math.abs(c)<=Math.min(.25,a)?n.timestamp-i:e.timestamp-s}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}},Pc=class{constructor(e,t,n){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let n=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(i=>i.type===this.decl.type&&i.number===this.number);if(!n)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=n})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),w(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,n){w(e.sequenceNumber>=0),w(this.segmentedInput.firstSegment);let i=await this.segmentedInput.getMediaOffset(t,n.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:Bn(e.timestamp+i,await n.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:n,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),w(this.segmentedInput.firstSegment),w(this.firstInputTrack);let t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,n){let i=this.packetInfos.get(e);if(!i)throw new Error("Packet was not created from this track.");let s=n?await i.track._backing.getNextKeyPacket(i.sourcePacket,t):await i.track._backing.getNextPacket(i.sourcePacket,t);if(s)return this.createAdjustedPacket(s,i.segment,i.track);let a=i.segment;for(;;){let o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;let u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(h=>h.type===i.track.type&&h.number===i.track.number);if(!u){a=o;continue}let d=await u._backing.getFirstPacket(t);return d?this.createAdjustedPacket(d,o,u):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,n){let i=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!i)return null;for(await this.hydrate();i;){let s=this.segmentedInput.getInputForSegment(i),o=(await s.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(i,s),l=e-c,u=n?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!u){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(u,i,o)}return null}},Ec=class extends Pc{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},Ic=class extends Pc{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}};Ii();var cd=0,ld=1/0,CT=null;typeof FinalizationRegistry<"u"&&(CT=new FinalizationRegistry(r=>{r()}));var wt=class extends Vt{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new ut;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,cd,ld),e=this._getFileSize(),w(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ut;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Fc(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Gn(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Gn=class{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");let e=this.source;w(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Ot=class extends wt{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=i=>{if(!(i instanceof wt||i instanceof Gn))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let s=i instanceof wt?i.ref():i;return s.source._usedForHls||=this._usedForHls,s};return t instanceof Promise?t.then(n):n(t)}},ud=(r,e)=>r.path===e.path,ua=class extends Ot{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,n,i){if(!this._root){if(!this._rootRequest){let s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{let c=o instanceof wt?o.ref():o;return this._root=c,this._rootRequest=null,c};s instanceof Promise?this._rootRequest=s.then(a):(a(s),w(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,t,n,i))}return this._root.source._read(e,t,n,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},da=class extends wt{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=Ye(e),this._view=Ae(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},ha=class extends wt{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Mi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Mc({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Fg.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,n,i){return this._orchestrator.read(e,t,n,i)}async _runWorker(e){w(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!an()&&this._options.useStreamReader!==!1?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:i}=await t.read();if(n)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},PT=.5*2**20,ET=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let i=null;try{typeof window<"u"&&typeof window.location<"u"&&(i=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&i!==null&&i!==window.location.origin)return we._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),Mg=new Set,fa=class r extends Ot{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Mi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");let n=e instanceof Request?e.url:e instanceof URL?e.href:e;super(n,a=>new r(a.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??ET,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){let a={...Uo(t.requestInit.headers)},o=Object.keys(a).find(c=>c.toLowerCase()==="range");o!==void 0&&(i=a[o],delete a[o],this._requestInit.headers=a)}if(e instanceof Request){let a=e.headers.get("Range");if(a!==null){i??=a;let o=new Request(e);o.headers.delete("Range"),this._url=o}}if(i!==null){let a=MT(i);a&&(this._offset=a.offset,this._length=a.length)}let s=2;this._orchestrator=new Mc({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:Fg.network})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;let e=this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:Ze(e-this._offset,0,this._length??1/0)}_read(e,t,n,i){if(this._length!==null&&t>this._length)return null;let s=this._offset,a=this._orchestrator.read(s+e,s+t,Math.max(s+n,s),s+Math.min(i,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return a instanceof Promise?a.then(o):o(a)}async _runWorker(e){for(;;){let t=new AbortController,n=await fp(this._options.fetchFn??fetch,this._url,hp(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(this._orchestrator.fileSize===null){let s=n.headers.get("Content-Range");if(s){let o=/\/(\d+)/.exec(s);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}let a=n.headers.get("Content-Length");a&&this._orchestrator.supplyFileSize(e.currentPos+Number(a))}if(this._fileSizeDetermined=!0,n.status!==206){if(!this._usedForHls){let s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(Mg.has(s.origin)||(we._warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),Mg.add(s.origin)))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize!==null?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await i.read()}catch(c){if(this._disposed)throw c;let l=this._getRetryDelay(1,c,this._url);if(l!==null){we._error("Error while reading response stream. Attempting to resume.",c),await js(1e3*l);break}else throw c}if(e.aborted)continue;let{done:a,value:o}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_dispose(){this._orchestrator.dispose()}},IT=/^bytes=(\d+)-(\d*)$/,MT=r=>{let e=IT.exec(r.trim());if(!e)return null;let t=Number(e[1]),n=e[2]===""?null:Number(e[2]);return n!==null&&n<t?null:{offset:t,length:n!==null?n-t+1:null}};var ma=class extends wt{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Mi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let n=_e(this._cache,e,u=>u.start),i=n!==-1?this._cache[n]:null;if(i&&i.start<=e&&t<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let s=e,a=new Uint8Array(t-e);if(n!==-1)for(let u=n;u<this._cache.length;u++){let d=this._cache[u];if(d.start>=t)break;let h=Math.max(e,d.start);h>s&&this._throwDueToCacheMiss();let f=Math.min(t,d.end);h<f&&(a.set(d.bytes.subarray(h-d.start,f-d.start),h-e),s=f)}if(s===t)return{bytes:a,view:Ae(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:o,resolve:c,reject:l}=nt();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else throw u})),o}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,i=this._currentIndex+t.byteLength;this._dispatchRead(n,i);for(let s=0;s<this._pendingSlices.length;s++){let a=this._pendingSlices[s],o=Math.max(n,a.start),c=Math.min(i,a.end);o<c&&(a.bytes.set(t.subarray(o-n,c-n),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:Ae(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:n,end:i,bytes:t,view:Ae(t),age:0});this._cache.length>0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},Fg={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(let i of t){let a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-8388608);if(zo(r,e,a,i.targetPos)){let o=i.targetPos-i.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,i.startPos+u)}}return e=Math.max(e,r+PT),{start:r,end:e}}},Mc=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,n,i){w(!this.disposed);let s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,n),o=Math.min(s.end,this.fileSize??1/0,i);w(a<=e&&t<=o);let c=null,l=_e(this.cache,e,x=>x.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});let d=_e(this.cache,a,x=>x.start),h=c?null:new Uint8Array(t-e),f=0,p=a,m=[];if(d!==-1){for(let x=d;x<this.cache.length;x++){let v=this.cache[x];if(v.start>=o)break;if(v.end<=a)continue;let M=Math.max(a,v.start),C=Math.min(o,v.end);if(w(M<=C),p<M&&m.push({start:p,end:M}),p=C,h){let _=Math.max(e,v.start),F=Math.min(t,v.end);if(_<F){let E=_-e;h.set(v.bytes.subarray(_-v.start,F-v.start),E),E===f&&(f=F-e)}}v.age=this.nextAge++}p<o&&m.push({start:p,end:o})}else m.push({start:a,end:o});if(h&&f>=h.length&&(c={bytes:h,view:Ae(h),offset:e}),m.length===0)return w(c),c;let{promise:g,resolve:y,reject:b}=nt(),k=[];for(let x of m){let v=Math.max(e,x.start),M=Math.min(t,x.end);v===x.start&&M===x.end?k.push(x):v<M&&k.push({start:v,end:M})}let T=h&&{start:e,bytes:h,holes:k,resolve:y,reject:b};e:for(let x of m){for(let C of this.workers)if(this.checkHoleAgainstWorker(C,x,T?[T]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}let v=x.end<o||this.fileSize!==null,M=this.createWorker(x.start,x.end,v);if(M)T&&(M.pendingSlices=[T]),this.runWorker(M);else{let C=_e(this.queuedReads,x.start,F=>F.hole.start),_=C!==-1?this.queuedReads[C]:null;for(_&&x.start<=_.hole.end?(_.hole.end=Math.max(_.hole.end,x.end),_.strictTarget&&=v,T&&_.pendingSlices.push(T)):(C++,_={hole:{start:x.start,end:x.end},strictTarget:v,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(C,0,_));C+1<this.queuedReads.length;){let F=this.queuedReads[C+1];if(F.hole.start>_.hole.end)break;_.hole.end=Math.max(_.hole.end,F.hole.end),_.pendingSlices.push(...F.pendingSlices),_.strictTarget&&=F.strictTarget,_.age=Math.min(_.age,F.age),this.queuedReads.splice(C+1,1)}}}return c?g.catch(x=>{if(!this.disposed)throw x}):(w(h),c=g.then(x=>x&&{bytes:x,view:Ae(x),offset:e})),c}checkHoleAgainstWorker(e,t,n){if(zo(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let s=0;s<n.length;s++){let a=n[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let n=0;n<this.queuedReads.length;n++){let i=this.queuedReads[n];if(this.checkHoleAgainstWorker(e,i.hole,i.pendingSlices))this.queuedReads.splice(n,1),n--,t=!0;else if(t)break}}createWorker(e,t,n){if(this.workers.length>=this.options.maxWorkerCount){let s=null,a=null;for(let o=0;o<this.workers.length;o++){let c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!s||c.age<s.age)&&(a=o,s=c)}if(s)w(a!==null),w(s.pendingSlices.length===0),this.workers.splice(a,1);else return null}let i={startPos:e,currentPos:e,targetPos:t,strictTarget:n,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){w(!e.running),w(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)throw t}).finally(()=>{if(!(e.running||this.workers.length>=this.options.maxWorkerCount)&&this.queuedReads.length>0){let t=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[t].age&&(t=s);let n=this.queuedReads[t];this.queuedReads.splice(t,1);let i=this.createWorker(n.hole.start,n.hole.end,n.strictTarget);w(i),i.pendingSlices=n.pendingSlices,this.runWorker(i)}})}consolidateEverythingIntoOneWorker(e){let t=new Set(e.pendingSlices);for(let n=0;n<this.workers.length;n++){let i=this.workers[n];if(i!==e){for(let s of i.pendingSlices)t.add(s);i.aborted=!0,i.pendingSlices.length=0,this.workers.splice(n,1),n--}}for(let n=0;n<this.queuedReads.length;n++){let i=this.queuedReads[n];for(let s of i.pendingSlices)t.add(s)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){w(!e.aborted);let n=e.currentPos,i=n+t.length;this.insertIntoCache({start:n,end:i,bytes:t,view:Ae(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let s=0;s<e.pendingSlices.length;s++){let a=e.pendingSlices[s],o=Math.max(n,a.start),c=Math.min(i,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-n,c-n),o-a.start);for(let l=0;l<a.holes.length;l++){let u=a.holes[l];n<=u.start&&i>u.start&&(u.start=i),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let a=this.workers[s];e===a||a.running||zo(n,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),s--)}}supplyFileSize(e){w(this.fileSize===null),this.fileSize=e;for(let t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let n=0;n<t.pendingSlices.length;n++){let i=t.pendingSlices[n];for(let s of i.holes)if(s.end>e){i.resolve(null),t.pendingSlices.splice(n,1),n--;break}}}for(let t=0;t<this.queuedReads.length;t++){let n=this.queuedReads[t];if(n.hole.start>=e){for(let i of n.pendingSlices)i.resolve(null);this.queuedReads.splice(t,1),t--}else if(n.hole.end>e){n.hole.end=e,n.strictTarget=!0;for(let i=0;i<n.pendingSlices.length;i++){let s=n.pendingSlices[i];s.start>=e&&(s.resolve(null),n.pendingSlices.splice(i,1),i--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){let t=this.workers.indexOf(e);w(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(let n of e.pendingSlices)n.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=_e(this.cache,e.start,n=>n.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let i=new Uint8Array(e.end-n.start);i.set(n.bytes,0),i.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=i,n.view=Ae(i),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let i=this.cache[n];if(e.end<=i.start)break;if(e.end>=i.end){this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length,n--;continue}let s=new Uint8Array(i.end-e.start);s.set(e.bytes,0),s.set(i.bytes,i.start-e.start),this.currentCacheSize-=e.end-i.start,e.bytes=s,e.view=Ae(s),e.end=i.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,i=this.cache[0];for(let s=1;s<this.cache.length;s++){let a=this.cache[s];a.age<i.age&&(n=s,i=a)}if(this.currentCacheSize-i.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};var Fc=class extends wt{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:Ze(e-this._offset,0,this._length??1/0)}_read(e,t,n,i){if(this._length!==null&&t>this._length)return null;let s=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+i),a=o=>o?(o.offset-=this._offset,o):null;return s instanceof Promise?s.then(a):a(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}};var Rg=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},Bg=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n}),FT=/^0[xX][0-9a-fA-F]+$/,RT=/^data:.*;base64,/i,pa=class extends Cc{constructor(e,t,n,i){super(e.input,t,n),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=i}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await js(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){let k={stack:[],error:void 0,hasError:!1};try{let T=Rg(k,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),v=await new yn(T.source).requestEntireFile();w(v),e=Rc(v,v.length,{ignore:_c}),T.source instanceof Ot&&(this.rootPath=T.source.rootPath)}catch(T){k.error=T,k.hasError=!0}finally{Bg(k)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=!1,i=0,s=null,a=null,o=null,c=0,l=null,u=null,d=null,h=null,f=null,p=null,m=!1,g=ze(this.segments)??null,y=k=>{let T=k.indexOf("@"),x=Number(T===-1?k:k.slice(0,T));if(!Number.isInteger(x)||x<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${k}'.`);let v=null;if(T!==-1&&(v=Number(k.slice(T+1)),!Number.isInteger(v)||v<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${k}'.`);return{length:x,offset:v}},b=k=>{c=k,g&&(w(g.sequenceNumber!==null),g.sequenceNumber<k&&(i=g.timestamp+g.duration,l=g.firstSegment,u=g.initSegment,f=g.lastProgramDateTimeSeconds,s=g.unixEpochTimestamp!==null?g.unixEpochTimestamp+g.duration:null,g=null))};for(let k=0;k<e.length;k++){let T=e[k];if(!n){if(T!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");n=!0;continue}if(!T.startsWith("#")){if(!g){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let x=o;if(x&&x.method==="AES-128"&&!x.iv){let _=new Uint8Array(Yt),F=Ae(_);F.setUint32(8,Math.floor(c/2**32)),F.setUint32(12,c),x={...x,iv:_}}let M={path:dr(this.rootPath,T),offset:h?.offset??0,length:h?.length??null},C={timestamp:i,unixEpochTimestamp:s,firstSegment:l,sequenceNumber:c,location:M,duration:a,encryption:x,initSegment:u,lastProgramDateTimeSeconds:f};l??=C,i+=a,s!==null&&(s+=a),this.segments.push(C)}a=null,h===null?d=null:h=null,b(c+1)}if(T.startsWith(la)){if(g){m=!0;continue}m||(f===null&&c>0&&p!==null&&(i=c*p),m=!0);let x=T.slice(la.length),v=x.indexOf(","),M=v===-1?x:x.slice(0,v),C=Number(M);if(!Number.isFinite(C)||C<0)throw new Error(`Invalid #EXTINF tag duration '${M}'.`);a=C}else if(T.startsWith(td)){let x=new qr(T.slice(td.length)),v=x.get("uri");if(!v)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let M=x.get("byterange"),C=null;if(M!==null&&(C=y(M)),C&&C.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){let F={path:dr(this.rootPath,v),offset:C?.offset??0,length:C?.length??null};if(o?.method==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");u={timestamp:i,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:F,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:f}}a=null,h===null?d=null:h=null}else if(T.startsWith(rd)){let x=new qr(T.slice(rd.length)),v=x.get("method");if(v==="NONE")o=null;else if(v==="AES-128"){let M=x.get("uri");if(!M)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let C=null,_=x.get("iv");if(_){if(!FT.test(_))throw new Error(`Unsupported IV format '${_}'.`);let E=_.slice(2);E=E.padStart(Yt*2,"0"),C=new Uint8Array(Yt);for(let O=0;O<Yt;O++){let Q=-Yt*2+O;C[O]=parseInt(E.slice(Q,Q+2),16)}}let F=x.get("keyformat")??"identity";if(F!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");o={method:"AES-128",keyUri:dr(this.rootPath,M),iv:C,keyFormat:F}}else if(v==="SAMPLE-AES"||v==="SAMPLE-AES-CTR"){let M=x.get("uri");if(!M)throw new Error(`Invalid #EXT-X-KEY: ${v} requires a URI attribute.`);if((x.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let _=null;if(RT.test(M)){let F=M.indexOf(","),E=Gs(M.slice(F+1));if(E.length>=8&&E[4]===112&&E[5]===115&&E[6]===115&&E[7]===104){let O=Ae(E).getUint32(0);_=nc(E.subarray(8,Math.min(O,E.length)))}}o={method:v,psshBox:_}}else throw new Error(`Unsupported encryption method '${v}'. If you think this method should be supported, please raise an issue.`)}else if(T.startsWith(nd)){let x=T.slice(nd.length),v=Number(x);if(!Number.isInteger(v)||v<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${x}'.`);b(v)}else if(T.startsWith(id)){let x=y(T.slice(id.length));if(x.offset===null){if(d===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");x.offset=d}h=x,d=x.offset+x.length}else if(T.startsWith(sd)){if(g)continue;let x=T.slice(sd.length),v=Date.parse(x);if(!Number.isFinite(v))continue;let M=v/1e3;if(f===M)continue;if(f===null&&this.segments.length>0){let C=ze(this.segments),_=C.timestamp+C.duration,F=M-_;for(let E of this.segments)E.unixEpochTimestamp=E.timestamp+F,t&&(E.timestamp=E.unixEpochTimestamp)}f=M,s=M,t&&(i=M)}else if(T===Pg)l=null;else if(T.startsWith(ad)){let x=T.slice(ad.length),v=Number(x);if(!Number.isFinite(v)||v<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${x}'.`);this.refreshInterval=v,p=v}else if(T===Eg){this.streamHasEnded=!0;break}else T.startsWith(od)&&T.slice(od.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!n)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let i=_e(this.segments,e,a=>a.timestamp);if(i===-1)return null;if(i<this.segments.length-1||this.streamHasEnded||n)return this.segments[i];let s=this.segments[i];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,t){let n=this.segments.indexOf(e);w(n!==-1);let i=n+1,s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return w(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,n=this.inputCache.find(c=>c.segment===t);if(n)return n.age=this.nextInputCacheAge++,n.input;let i=null;(t.initSegment||t.firstSegment)&&(i=this.getInputForSegment(t.initSegment??t.firstSegment));let s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(c=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(c);let l=c.psshBoxes,{psshBox:u}=t.encryption;return(u.keyIds===null||u.keyIds.includes(c.keyId))&&!l.some(d=>ic(d,u))&&(l=[...l,u]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:l})})}},a=new Gr({source:new ua(t.location.path,async c=>{w(c.isRoot);let l={...c,isRoot:!1},u,d=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(u=await this.input._getSourceCached(l),d){let f=u.source.slice(t.location.offset,t.location.length??void 0).ref();u.free(),u=f}}else if(t.encryption.method==="AES-128"){let h=t.encryption;w(h.iv);let f=await this.input._getSourceCached(l);if(d){let y=f.source.slice(t.location.offset,t.location.length??void 0).ref();f.free(),f=y}let p=new yn(f.source),m=Zp(p,async()=>{let g={stack:[],error:void 0,hasError:!1};try{let y=Rg(g,await this.input._getSourceCached({path:h.keyUri,isRoot:!1},Dg),!1),k=await new yn(y.source).requestSlice(0,Yt);if(!k)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:ie(k,Yt),iv:h.iv}}catch(y){g.error=y,g.hasError=!0}finally{Bg(g)}},()=>{f.free()});u=new ma(m).ref()}else w(!1);return u}),formats:this.input._formats.filter(c=>!(c instanceof Yi)),initInput:i??void 0,formatOptions:s});if(a._onFormatDetermined=c=>{if((t.encryption?.method==="SAMPLE-AES"||t.encryption?.method==="SAMPLE-AES-CTR")&&!c._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){let c=Fi(this.inputCache,l=>l.age);w(c!==-1),this.inputCache.splice(c,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}};var Dc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{w(this.input._rootSource instanceof Ot);let e=await this.input._reader.requestEntireFile();w(e);let t=Rc(e,e.length,{ignore:_c}),{rootPath:n}=this.input._rootSource,i=[],s=[];for(let d=1;d<t.length;d++){let h=t[d];if(h.startsWith(Zu)){let f=d,p=t[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");let m=dr(n,p),g=new qr(h.slice(Zu.length));if(g.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");i.push({fullPath:m,attributes:g,lineNumber:f,hasOnlyKeyPackets:!1})}else if(h.startsWith(Ju)){let f=new qr(h.slice(Ju.length)),p=f.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(f.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let g=dr(n,p);i.push({fullPath:g,attributes:f,lineNumber:d,hasOnlyKeyPackets:!0})}else if(h.startsWith(ed)){let f=new qr(h.slice(ed.length));if(f.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(f.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let g=null,y=f.get("uri");y!==null&&(g=dr(n,y)),s.push({fullPath:g,attributes:f,lineNumber:d})}else if(h!==Ig){if(h.startsWith(la)){let f=new pa(this,n,null,t);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}}let a=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(i.map(async(d,h)=>{let f=[],p=d.attributes.get("codecs"),m;if(p)m=p.split(",").map(_=>_.trim());else{let F=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),E=await Promise.all(F.map(async O=>({track:O,codec:await O.getCodec()})));m=await Promise.all(E.filter(O=>O.codec!==null).map(O=>O.track.getDecoderConfig().then(Q=>Q.codec)))}let g=d.attributes.get("video"),y=d.attributes.get("audio"),b=m.some(_=>gt.includes(Rr(_))),k=m.some(_=>Ht.includes(Rr(_)));if(g!==null&&!b){if(!a.includes(g))throw new Error(`Invalid M3U8 file; variant stream references video group "${g}" which is not defined in any #EXT-X-MEDIA tags.`);let _=s.find(F=>{let E=F.attributes.get("group-id"),O=F.attributes.get("type");return E===g&&O.toLowerCase()==="video"});e:if(_){let F=_.attributes.get("uri");if(F===null)break e;let E=dr(n,F),ye=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(ee=>ee.getType()==="video");if(!ye||await ye.getCodec()===null)break e;let Z=await ye.getDecoderConfig().then(ee=>ee?.codec??null);w(Z!==null),m.push(Z)}}if(y!==null&&!k){if(!o.includes(y))throw new Error(`Invalid M3U8 file; variant stream references audio group "${y}" which is not defined in any #EXT-X-MEDIA tags.`);let _=s.find(F=>{let E=F.attributes.get("group-id"),O=F.attributes.get("type");return E===y&&O.toLowerCase()==="audio"});e:if(_){let F=_.attributes.get("uri");if(F===null)break e;let E=dr(n,F),ye=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(ee=>ee.getType()==="audio");if(!ye||await ye.getCodec()===null)break e;let Z=await ye.getDecoderConfig().then(ee=>ee?.codec??null);w(Z!==null),m.push(Z)}}m=[...new Set(m)];let T=null,x=null,v=d.attributes.getAsNumber("bandwidth");w(v!==null);let M=d.attributes.getAsNumber("average-bandwidth"),C=d.attributes.get("name");for(let _ of m){let F=Rr(_);if(F!==null){if(gt.includes(F)){if(T!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");T=_;let E=d.attributes.get("video");if(E===null){let O=d.attributes.get("resolution"),Q=null,ye=null;if(O){let Z=O.match(/^(\d+)x(\d+)$/);Z&&(Q=Number(Z[1]),ye=Number(Z[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:je,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(h),peakBitrate:v,averageBitrate:M,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:Q,height:ye}})}else{if(!a.includes(E))throw new Error(`Invalid M3U8 file; variant stream references video group "${E}" which is not defined in any #EXT-X-MEDIA tags.`);for(let O of s){let Q=O.attributes.get("group-id"),ye=O.attributes.get("type");if(Q!==E||ye.toLowerCase()!=="video")continue;let Z=O.attributes.get("resolution")??d.attributes.get("resolution"),ee=null,ve=null;if(Z){let Re=Z.match(/^(\d+)x(\d+)$/);Re&&(ee=Number(Re[1]),ve=Number(Re[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:Bc(O.attributes),autoselect:Bc(O.attributes)||Og(O.attributes),languageCode:Lg(O.attributes.get("language")),lineNumber:O.lineNumber,fullPath:O.fullPath??d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:O.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:ee,height:ve}})}}}else if(Ht.includes(F)){if(x!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");x=_;let E=d.attributes.get("audio");if(E===null){let O=d.attributes.get("channels"),Q=O!==null?Number(O.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:je,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:x,pairingMask:1n<<BigInt(h),peakBitrate:v,averageBitrate:M,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:Q!==null&&Number.isInteger(Q)&&Q>0?Q:null}})}else{if(!o.includes(E))throw new Error(`Invalid M3U8 file; variant stream references audio group "${E}" which is not defined in any #EXT-X-MEDIA tags.`);for(let O of s){let Q=O.attributes.get("group-id"),ye=O.attributes.get("type");if(Q!==E||ye.toLowerCase()!=="audio")continue;let Z=O.attributes.get("channels")??d.attributes.get("channels"),ee=Z!==null?Number(Z.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:Bc(O.attributes),autoselect:Bc(O.attributes)||Og(O.attributes),languageCode:Lg(O.attributes.get("language")),lineNumber:O.lineNumber,fullPath:O.fullPath??d.fullPath,fullCodecString:x,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:O.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:ee!==null&&Number.isInteger(ee)&&ee>0?ee:null}})}}}}}return f})),l=[],u=d=>{let h=l.find(f=>f.fullPath===d.fullPath&&f.info.type===d.info.type);h?(h.pairingMask|=d.pairingMask,h.default||=d.default,h.autoselect||=d.autoselect,h.lineNumber=Math.min(h.lineNumber,d.lineNumber),d.peakBitrate!==null&&(h.peakBitrate=Math.max(h.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(h.averageBitrate=Math.max(h.averageBitrate??-1/0,d.averageBitrate)),h.languageCode===je&&(h.languageCode=d.languageCode)):(d.id=l.length+1,l.push(d))};for(let d of c)for(let h of d)u(h);l.sort((d,h)=>d.lineNumber-h.lineNumber),this.trackBackings=[];for(let d of l)d.info.type==="video"?this.trackBackings.push(new Lc(d)):this.trackBackings.push(new Uc(d));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),w(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(i=>i.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),t=new pa(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return vc}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Oc=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,i=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(i.length===1)t=i[0];else if(this instanceof Lc){for(let s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}else{w(this instanceof Uc);for(let s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...dt,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){w(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},Lc=class extends Oc{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Rr(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},Uc=class extends Oc{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Rr(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},Bc=r=>{let e=r.get("default");if(e===null)return!1;let t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},Og=r=>{let e=r.get("autoselect");if(e===null)return!1;let t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},Lg=r=>{if(r===null)return je;let e=r.split("-")[0];return e||je};var Mt=class{constructor(){this._isIsobmff=!1}},ga=class extends Mt{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);let n=We(t,4);return n!=="ftyp"&&n!=="styp"?null:We(t,4)}_createDemuxer(e){return new oc(e)}},Nc=class extends ga{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!=="qt ";let n=e._reader.requestSlice(4,4);if(n instanceof Promise&&(n=await n),!n)return!1;let i=We(n,4);return i==="moof"||i==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}},zc=class extends ga{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},ya=class extends Mt{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,Jt);if(n instanceof Promise&&(n=await n),!n)return!1;let i=Ou(n);if(i===null||i<1||i>8||Ce(n,i)!==N.EBML)return!1;let a=Lu(n);if(typeof a!="number")return!1;let o=e._reader.requestSlice(n.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;let c=n.filePos;for(;o.filePos<=c+a-Et;){let l=er(o);if(!l)break;let{id:u,size:d}=l,h=o.filePos;if(d===void 0)return!1;switch(u){case N.EBMLVersion:if(Ce(o,d)!==1)return!1;break;case N.EBMLReadVersion:if(Ce(o,d)!==1)return!1;break;case N.DocType:if(mn(o,d)!==t)return!1;break;case N.DocTypeVersion:if(Ce(o,d)>4)return!1;break}o.filePos=h+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new gc(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Vc=class extends ya{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Hc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,mt);if(d instanceof Promise&&(d=await d),!d)break;let h=It(d);if(!h)break;t=d.filePos+h.size}let n=await sa(e._reader,t,t+4096);if(!n)return!1;let i=n.header,s=Go(i.mpegVersionId,i.channel),a=e._reader.requestSlice(n.startPos+s,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=K(a);if(o===Wo||o===qo)return!0;t=n.startPos+n.header.totalSize;let l=await sa(e._reader,t,t+4);if(!l)return!1;let u=l.header;return!(i.channel!==u.channel||i.sampleRate!==u.sampleRate)}_createDemuxer(e){return new wc(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Wc=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=We(t,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(t.skip(4),We(t,4)==="WAVE")}_createDemuxer(e){return new kc(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},qc=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?We(t,4)==="OggS":!1}_createDemuxer(e){return new bc(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Gc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,mt);if(i instanceof Promise&&(i=await i),!i)break;let s=It(i);if(!s)break;t=i.filePos+s.size}let n=e._reader.requestSlice(t,4);return n instanceof Promise&&(n=await n),n?We(n,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new xc(e)}},jc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,mt);if(a instanceof Promise&&(a=await a),!a)break;let o=It(a);if(!o)break;t=a.filePos+o.size}let n=e._reader.requestSliceRange(t,Hn,tr);if(n instanceof Promise&&(n=await n),!n)return!1;let i=rr(n);if(!i||(t+=i.frameLength,n=e._reader.requestSliceRange(t,Hn,tr),n instanceof Promise&&(n=await n),!n))return!1;let s=rr(n);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new Sc(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Kc=class extends Mt{async _canReadInput(e){let t=205,n=e._reader.requestSlice(0,t);if(n instanceof Promise&&(n=await n),!n)return!1;let i=ie(n,t);return i[0]===71&&i[188]===71||i[0]===71&&i[204]===71?!0:i[4]===71&&i[196]===71}_createDemuxer(e){return new Tc(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},Yi=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||!(We(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof Ot))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new Dc(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return vc}},$c=new Nc,Ug=new zc,Ng=new ya,zg=new Vc,Vg=new Hc,Hg=new Wc,Wg=new qc,qg=new jc,Gg=new Gc,jg=new Kc,Kg=new Yi,dd=[Kg,$c,Ug,Ng,zg,Hg,Wg,Gg,Vg,qg,jg];var $g=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(r.hls!==void 0){if(!r.hls||typeof r.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(r.hls.offsetTimestampsByDateTime!==void 0&&typeof r.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var BT=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},DT=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});Ii();var Xg=-1/0,Qg=-1/0,xa=null;typeof FinalizationRegistry<"u"&&(xa=new FinalizationRegistry(r=>{let e=performance.now();r.type==="video"?(e-Xg>=1e3&&(we._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."),Xg=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-Qg>=1e3&&(we._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."),Qg=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var jr=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},hd=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],OT=new Set(hd),nr=class r{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!OT.has(t.format))throw new TypeError("init.format must be one of: "+hd.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let i of t.layout){if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(i.offset)||i.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(i.stride)||i.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&vu(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=t._doNotCopy?Ye(e):Ye(e).slice(),this._layout=t.layout??NT(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;let n=t.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new Sa(n),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");t?.visibleRect!==void 0&&vu(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Sa(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new r(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*ur),duration:Math.trunc((t.duration??0)*ur)||void 0}),t);let n=0,i=0;if("naturalWidth"in e?(n=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,i=e.videoHeight):"width"in e&&(n=Number(e.width),i=Number(e.height)),!n||!i)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(n,i),a=s.getContext("2d",{alpha:Hs(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n,height:i},this.squarePixelWidth=n,this.squarePixelHeight=i,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Sa({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof jr){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!hd.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=Ln({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),xa?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return w(this._data!==null),this._data instanceof jr?new r(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):ba(this._data)?new r(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(w(this._layout),new r(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(xa?.unregister(this),this._data instanceof jr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ba(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Zg(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.");return ba(this._data)?this._data.allocationSize(e):Jg(this,e).allocationSize}async copyTo(e,t={}){if(!Ci(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Zg(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(w(this._data!==null),ba(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof jr){let l={stack:[],error:void 0,hasError:!1};try{let u=BT(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof r))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(u.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${u.format}' instead.`);return await u.copyTo(e,t)}catch(u){l.error=u,l.hasError=!0}finally{DT(l)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let l=this.toVideoFrame(),u=await l.copyTo(e,t);return l.close(),u}let n=Jg(this,t);w(this.format);let i=Ye(e);if(i.byteLength<n.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${n.allocationSize}, Available: ${i.byteLength}`);let s=Qc(this.format),a;if(this._data instanceof jr){let l=this._data.getDataPlanes();if(l instanceof Promise&&(l=await l),!Array.isArray(l)||l.some(u=>!(u.data instanceof Uint8Array)||!Number.isInteger(u.stride)||u.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=l}else if(this._data instanceof Uint8Array)w(this._layout),w(this._layout.length===s.length),a=this._layout.map((l,u)=>{let d=Math.ceil(this.codedHeight/s[u].heightDivisor);return{data:this._data.subarray(l.offset,l.offset+l.stride*d),stride:l.stride}});else{let u=this._data.getContext("2d");w(u);let d=u.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:Ye(d.data),stride:4*this.codedWidth}]}let o=[],c=s.length;for(let l=0;l<c;l++){let u=n.computedLayouts[l],d=a[l].stride,h=a[l].data,f=u.sourceTop*d;f+=u.sourceLeftBytes;let p=u.destinationOffset,m=u.sourceWidthBytes,g={offset:p,stride:u.destinationStride};for(let y=0;y<u.sourceHeight;y++){if(f+m>h.byteLength)throw new Error("Source buffer OOB read.");if(p+m>i.byteLength)throw new Error("Destination buffer OOB write.");let b=h.subarray(f,f+m);i.set(b,p),f+=d,p+=u.destinationStride}o.push(g)}if(t.format!==void 0){let l=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),u=this.format.includes("X")&&t.format.includes("A");if(l||u)for(let d=0;d<n.allocationSize;d+=4){if(l){let h=i[d],f=i[d+2];i[d]=f,i[d+2]=h}u&&(i[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(w(this._data!==null),this._data instanceof jr){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let e=this._data.getDataPlanes();if(e instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let t=e.reduce((a,o)=>a+o.data.byteLength,0),n=new Uint8Array(t),i=0,s=[];for(let a of e)n.set(a.data,i),s.push(i),i+=a.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ba(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,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,i,s,a,o,c,l){let u=0,d=0,h=this.displayWidth,f=this.displayHeight,p=0,m=0,g=this.displayWidth,y=this.displayHeight;if(a!==void 0?(u=t,d=n,h=i,f=s,p=a,m=o,c!==void 0?(g=c,y=l):(g=h,y=f)):(p=t,m=n,i!==void 0&&(g=i,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(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<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(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:h,sHeight:f}=this._rotateSourceRegion(u,d,h,f,this.rotation));let b=this.toCanvasImageSource();e.save();let k=p+g/2,T=m+y/2;e.translate(k,T),e.rotate(this.rotation*Math.PI/180);let x=this.rotation%180===0?1:g/y;e.scale(1/x,x),e.drawImage(b,u,d,h,f,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Ta(t.crop,"options.");let n=e.canvas.width,i=e.canvas.height,s=t.rotation??this.rotation,[a,o]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=t.crop;c&&(c=fd(c,a,o));let l,u,d,h,{sx:f,sy:p,sWidth:m,sHeight:g}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,s);if(t.fit==="fill")l=0,u=0,d=n,h=i;else{let[b,k]=t.crop?[t.crop.width,t.crop.height]:[a,o],T=t.fit==="contain"?Math.min(n/b,i/k):Math.max(n/b,i/k);d=b*T,h=k*T,l=(n-d)/2,u=(i-h)/2}e.save();let y=s%180===0?1:d/h;e.translate(n/2,i/2),e.rotate(s*Math.PI/180),e.scale(1/y,y),e.translate(-n/2,-i/2),e.drawImage(this.toCanvasImageSource(),f,p,m,g,l,u,d,h),e.restore()}_rotateSourceRegion(e,t,n,i,s){return s===90?[e,t,n,i]=[t,this.squarePixelHeight-e-n,i,n]:s===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-i]:s===270&&([e,t,n,i]=[this.squarePixelWidth-t-i,e,i,n]),{sx:e,sy:t,sWidth:n,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(w(this._data!==null),this._data instanceof jr||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&Ta(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let t=_i(this.rotation+(e.rotate??0)),[n,i]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=e.crop;s&&(s=fd(s,n,i));let a=s?s.width:n,o=s?s.height:i,c=a/o,l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=o),l=Vs(l,e.roundDimensionsTo??1),u=Vs(u,e.roundDimensionsTo??1);let d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:s??{left:0,top:0,width:n,height:i},alpha:e.alpha??"keep"};for(let m of LT){let g=m(this,d);if(g instanceof Promise&&(g=await g),g!==null)return g}let h=null,f=!1;for(let m of wa)if(m.canvas.width===d.width&&m.canvas.height===d.height){h=m.canvas,m.age=Yg++;break}if(h===null){if(typeof OffscreenCanvas<"u")h=new OffscreenCanvas(d.width,d.height);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");h=document.createElement("canvas"),h.width=d.width,h.height=d.height}f=!0,wa.length>=UT&&wa.splice(Fi(wa,m=>m.age),1),wa.push({canvas:h,age:Yg++})}let p=h.getContext("2d",{alpha:!0});if(!p)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return d.alpha==="discard"?(p.fillStyle="black",p.fillRect(0,0,d.width,d.height)):f||p.clearRect(0,0,d.width,d.height),this.drawWithFit(p,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new r(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}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}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}},LT=[];var UT=3,wa=[],Yg=0,Sa=class{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let t=Object.keys(Cr);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);let n=Object.keys(Pr);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(", ")}.`);let i=Object.keys(Er);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}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}}},ba=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,fd=(r,e,t)=>{let n=Math.min(r.left,e),i=Math.min(r.top,t),s=Math.min(r.width,e-n),a=Math.min(r.height,t-i);return w(s>=0),w(a>=0),{left:n,top:i,width:s,height:a}},Ta=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Zg=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},NT=(r,e,t)=>{let n=Qc(r),i=[],s=0;for(let a of n){let o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),l=o*a.sampleBytes,u=l*c;i.push({offset:s,stride:l}),s+=u}return i},Qc=r=>{let e=(t,n,i,s,a)=>{let o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:i,heightDivisor:s},{sampleBytes:n,widthDivisor:i,heightDivisor:s}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ct(r),w(!1)}},Jg=(r,e)=>{let t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},n=e.rect,i=zT(t,n,r.codedWidth,r.codedHeight,r.format),s=e.layout,a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return HT(i,a,s)},zT=(r,e,t,n,i)=>{let s={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>n)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!VT(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},VT=(r,e)=>{if(r===null)return!0;let t=Qc(r);for(let n=0;n<t.length;n++){let i=t[n],s=i.widthDivisor,a=i.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},HT=(r,e,t)=>{let n=Qc(e),i=n.length;if(t!==void 0&&t.length!==i)throw new TypeError(`Layout must have ${i} planes.`);let s=0,a=[],o=[];for(let c=0;c<i;c++){let l=n[c],u=l.sampleBytes,d=l.widthDivisor,h=l.heightDivisor,f={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(f.sourceTop=Math.ceil(Math.trunc(r.y||0)/h),f.sourceHeight=Math.ceil(Math.trunc(r.height||0)/h),f.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*u,f.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*u,t!==void 0){let g=t[c];if(g.stride<f.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);f.destinationOffset=g.offset,f.destinationStride=g.stride}else f.destinationOffset=s,f.destinationStride=f.sourceWidthBytes;let m=f.destinationStride*f.sourceHeight+f.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),s=Math.max(s,m);for(let g=0;g<c;g++){let y=a[g];if(!(o[c]<=y.destinationOffset||o[g]<=f.destinationOffset))throw new TypeError("Planes overlap.")}a.push(f)}return{allocationSize:s,computedLayouts:a}},Xc=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),jn=class{constructor(){this._referenceCount=0}},mr=class r{get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}constructor(e){if(this._closed=!1,ka(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 instanceof jn){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Xc.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Xc.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let t=e.data.byteLength/(wn(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let i=this.numberOfFrames*this.numberOfChannels*wn(this.format);if(n.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}xa?.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&&!Xc.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let i=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(i>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let s=wn(t),a=Kn(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?i:i*this.numberOfChannels)*s}copyTo(e,t){if(!Ci(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Xc.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{format:n,frameCount:i,frameOffset:s}=t,{planeIndex:a}=t,o=this.format,c=n??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");let h=i!==void 0?i:l-d;if(h>l-d)throw new RangeError("frameCount out of range");let f=wn(c),p=Kn(c);if(p&&a>=u)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");let g=(p?h:h*u)*f;if(e.byteLength<g)throw new RangeError("Destination buffer is too small");let y=Ae(e),b=t0(c);if(ka(this._data))an()&&u>2&&c!==o?WT(this._data,y,o,c,u,a,d,h):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:h,format:c});else{let k=e0(o),T=wn(o),x=Kn(o),v;if(this._data instanceof jn){let C=_=>{let F=this._data.getDataPlane(_);if(!(F instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let E=l*T*(x?1:u);if(F.byteLength!==E)throw new TypeError(`Data plane ${_} has invalid size. Expected exactly ${E} bytes, got ${F.byteLength} bytes.`);return F};if(x)if(p)v=C(a),a=0;else{v=new Uint8Array(l*T*u);for(let _=0;_<u;_++){let F=C(_);v.set(F,_*l*T)}}else v=C(0)}else v=this._data;let M=Ae(v);for(let C=0;C<h;C++)if(p){let _=C*f,F;x?F=(a*l+(C+d))*T:F=((C+d)*u+a)*T;let E=k(M,F);b(y,_,E)}else for(let _=0;_<u;_++){let E=(C*u+_)*f,O;x?O=(_*l+(C+d))*T:O=((C+d)*u+_)*T;let Q=k(M,O);b(y,E,Q)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof jn){let e=new r(this._data);return e.setTimestamp(this.timestamp),e}else if(ka(this._data)){let e=new r(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endSample must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startSample out of range.");if(t>this.numberOfFrames)throw new RangeError("endSample out of range.");if(t<e)throw new RangeError("endSample must not be less than startSample.");if(this._closed)throw new Error("AudioSample is closed.");let n=t-e,i=wn(this.format),s;if(Kn(this.format)){let a=n*i;if(s=new Uint8Array(a*this.numberOfChannels),n>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(s.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:n})}else s=new Uint8Array(n*this.numberOfChannels*i),n>0&&this.copyTo(s,{planeIndex:0,format:this.format,frameOffset:e,frameCount:n});return new r({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(xa?.unregister(this),this._data instanceof jn?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ka(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof jn?this._createAudioDataFromData():ka(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():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()})}_createAudioDataFromData(){if(Kn(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(n/i),c=0,l=a;for(;l>0;){let u=Math.min(o,l),d=new Float32Array(i*u);for(let h=0;h<i;h++)e.copyFromChannel(d.subarray(h*u,(h+1)*u),h,c);yield new r({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:i,timestamp:t+c/s,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(n/i),c=0,l=a,u=[];for(;l>0;){let d=Math.min(o,l),h=new Float32Array(i*d);for(let p=0;p<i;p++)e.copyFromChannel(h.subarray(p*d,(p+1)*d),p,c);let f=new r({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:i,timestamp:t+c/s,data:h});u.push(f),c+=d,l-=d}return u}},wn=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Kn=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},e0=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},t0=r=>{switch(r){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,Ze((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,Ze(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,Ze(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},ka=r=>typeof AudioData<"u"&&r instanceof AudioData,r0=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},WT=(r,e,t,n,i,s,a,o)=>{let c=e0(t),l=t0(n),u=wn(t),d=wn(n),h=Kn(t);if(Kn(n))if(h){let p=new ArrayBuffer(o*u),m=Ae(p);r.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++){let y=g*u,b=g*d,k=c(m,y);l(e,b,k)}}else{let p=new ArrayBuffer(o*i*u),m=Ae(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++){let y=(g*i+s)*u,b=g*d,k=c(m,y);l(e,b,k)}}else if(h){let p=o*u,m=new ArrayBuffer(p),g=Ae(m);for(let y=0;y<i;y++){r.copyTo(m,{planeIndex:y,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){let k=b*u,T=(b*i+y)*d,x=c(g,k);l(e,T,x)}}}else{let p=new ArrayBuffer(o*i*u),m=Ae(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++)for(let y=0;y<i;y++){let b=g*i+y,k=b*u,T=b*d,x=c(m,k);l(e,T,x)}}},n0=(r,e)=>{let t=r.allocationSize({format:e,planeIndex:0}),n=new ArrayBuffer(t);return r.copyTo(n,{format:e,planeIndex:0}),new mr({data:n,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};var i0=new Map;var s0=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!gt.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${gt.join(", ")}.`);if(!(r.bitrate instanceof Lt)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.crop!==void 0&&Ta(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");a0(r.codec,r)},a0=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Rr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},md=r=>{let e=r.bitrate instanceof Lt?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??Tp(r.codec,r.width,r.height,e),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:e,bitrateMode:r.bitrateMode,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...Cp(r.codec)}},o0=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Ht.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${Ht.join(", ")}.`);if(r.bitrate===void 0&&!(ht.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(r.bitrate!==void 0&&!(r.bitrate instanceof Lt)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");qT(r.codec,r)},qT=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Rr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},c0=r=>{let e=r.bitrate instanceof Lt?r.bitrate._toAudioBitrate(r.codec):r.bitrate;return{codec:r.fullCodecString??vp(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:e,bitrateMode:r.bitrateMode,...Pp(r.codec)}},Lt=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,n){let i=t*n,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,c=Math.pow(i/a,.95),d=o*c*s[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(ht.includes(e)||e==="flac")return;let n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let i=n*this._factor;return e==="aac"?i=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-i)<Math.abs(a-i)?o:a):e==="opus"||e==="vorbis"?i=Math.max(6e3,i):e==="mp3"&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-i)<Math.abs(a-i)?o:a)),Math.round(i/1e3)*1e3}},l0=new Lt(.3),u0=new Lt(.6),d0=new Lt(1),h0=new Lt(2),f0=new Lt(4);var pd=async(r,e={})=>{let{width:t=1280,height:n=720,bitrate:i=1e6,...s}=e;if(!gt.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(n)||n<=0)throw new TypeError("height must be a positive integer.");if(!(i instanceof Lt)&&(!Number.isInteger(i)||i<=0))throw new TypeError("bitrate must be a positive integer or a quality.");a0(r,s);let a=md({codec:r,width:t,height:n,bitrate:i,framerate:void 0,...s,alpha:"discard"}),o=JSON.stringify(a),c=i0.get(o);if(c)return c;let l=(async()=>Yc.some(h=>h.supports(r,a))?!0:typeof VideoEncoder>"u"||(t%2===1||n%2===1)&&(r==="avc"||r==="hevc")||!(await VideoEncoder.isConfigSupported(a)).supported?!1:Hs()?new Promise(async h=>{try{let f=new VideoEncoder({output:()=>{},error:()=>h(!1)});f.configure(a);let p=new Uint8Array(t*n*4),m=new VideoFrame(p,{format:"RGBA",codedWidth:t,codedHeight:n,timestamp:0});f.encode(m),m.close(),await f.flush(),h(!0)}catch{h(!1)}}):!0)();return i0.set(o,l),l};var Zc=[],yd=[],Yc=[],gd=[];var m0=r=>{let n=r,i=4096,s=0,a=12,o=0;for(n<0&&(n=-n,s=128),n+=33,n>8191&&(n=8191);(n&i)!==i&&a>=5;)i>>=1,a--;return o=n>>a-4&15,~(s|a-5<<4|o)&255};var p0=r=>{let t=2048,n=0,i=11,s=0,a=r;for(a<0&&(a=-a,n=128),a>4095&&(a=4095);(a&t)!==t&&i>=5;)t>>=1,i--;return s=a>>(i===4?1:i-4)&15,(n|i-4<<4|s)^85};var $n=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},Zi=r=>{if(!Mi(r))throw new TypeError("timestamp must be a number.")},wd=(r,e,t)=>t.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let i=await r.determinePacketType(n);return i&&(n.type=i),n}):e,bn=class{constructor(e){if(!(e instanceof Ji))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if($n(e),this._track.input._disposed)throw new ut;return wd(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){$n(e);let t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Zi(e),$n(t),this._track.input._disposed)throw new ut;return wd(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if($n(t),this._track.input._disposed)throw new ut;return wd(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Zi(e),$n(t),this._track.input._disposed)throw new ut;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(w(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if($n(t),this._track.input._disposed)throw new ut;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(w(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof Oe))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof Oe))throw new TypeError("endPacket must be an EncodedPacket.");if($n(n),this._track.input._disposed)throw new ut;let i=[],{promise:s,resolve:a}=nt(),{promise:o,resolve:c}=nt(),l=!1,u=!1,d=null,h=[],f=()=>Math.max(2,h.length);(async()=>{let m=e??await this.getFirstPacket(n);for(;m&&!u&&!this._track.input._disposed&&!(t&&m.sequenceNumber>=t?.sequenceNumber);){if(i.length>f()){({promise:o,resolve:c}=nt()),await o;continue}i.push(m),a(),{promise:s,resolve:a}=nt(),m=await this.getNextPacket(m,n)}l=!0,a()})().catch(m=>{d||(d=m,a())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new ut;if(u)return{value:void 0,done:!0};if(d)throw d;if(i.length>0){let m=i.shift(),g=performance.now();for(h.push(g);h.length>0&&g-h[0]>=1e3;)h.shift();return c(),{value:m,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}},bd=class{constructor(e,t){this.onSample=e,this.onError=t}},Jc=class{mediaSamplesInRange(e=-1/0,t=1/0,n){Zi(e),Zi(t);let i=[],s=!1,a=null,{promise:o,resolve:c}=nt(),{promise:l,resolve:u}=nt(),d=!1,h=!1,f=!1,p=null,m={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let b=await this._createDecoder(C=>{if(u(),C.timestamp>=t&&(h=!0),h){C.close();return}a&&(C.timestamp>e?(i.push(a),s=!0):a.close()),C.timestamp>=e&&(i.push(C),s=!0),a=s?null:C,i.length>0&&(c(),{promise:o,resolve:c}=nt())},C=>{p||(p=C,c())}),k=this._createPacketSink(),T=await k.getKeyPacket(e,m)??await k.getFirstKeyPacket(m),x=T,M=k.packets(T??void 0,void 0,m);for(await M.next();x&&!h&&!this._track.input._disposed;){let C=g0(i.length);if(i.length+b.getDecodeQueueSize()>C){({promise:l,resolve:u}=nt()),await l;continue}b.decode(x);let _=await M.next();if(_.done)break;x=_.value}await M.return(),!f&&!this._track.input._disposed&&await b.flush(),b.close(),!s&&a&&i.push(a),d=!0,c()})().catch(b=>{p||(p=b,c())});let g=this._track,y=()=>{a?.close();for(let b of i)b.close()};return{async next(){for(;;){if(g.input._disposed)throw y(),new ut;if(f)return{value:void 0,done:!0};if(p)throw y(),p;if(i.length>0){let b=i.shift();return u(),{value:b,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,h=!0,u(),c(),y(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){lp(e);let n=cp(e),i=[],s=[],{promise:a,resolve:o}=nt(),{promise:c,resolve:l}=nt(),u=!1,d=!1,h=null,f=y=>{s.push(y),o(),{promise:a,resolve:o}=nt()},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let y=await this._createDecoder(C=>{if(l(),d){C.close();return}let _=0;for(;i.length>0&&C.timestamp-i[0]>-1e-10;)_++,i.shift();if(_>0)for(let F=0;F<_;F++)f(F<_-1?C.clone():C);else C.close()},C=>{h||(h=C,o())}),b=this._createPacketSink(),k=null,T=null,x=-1,v=async()=>{w(T);let C=T;for(y.decode(C);C.sequenceNumber<x;){let _=g0(s.length);for(;s.length+y.getDecodeQueueSize()>_&&!d;)({promise:c,resolve:l}=nt()),await c;if(d)break;let F=await b.getNextPacket(C,p);w(F),y.decode(F),C=F}x=-1},M=async()=>{await y.flush();for(let C=0;C<i.length;C++)f(null);i.length=0};for await(let C of n){if(Zi(C),d||this._track.input._disposed)break;let _=await b.getPacket(C,p),F=_&&await b.getKeyPacket(C,p);if(!F){x!==-1&&(await v(),await M()),f(null),k=null;continue}k&&(F.sequenceNumber!==T.sequenceNumber||_.timestamp<k.timestamp)&&(await v(),await M()),i.push(_.timestamp),x=Math.max(_.sequenceNumber,x),k=_,T=F}!d&&!this._track.input._disposed&&(x!==-1&&await v(),await M()),y.close(),u=!0,o()})().catch(y=>{h||(h=y,o())});let m=this._track,g=()=>{for(let y of s)y?.close()};return{async next(){for(;;){if(m.input._disposed)throw g(),new ut;if(d)return{value:void 0,done:!0};if(h)throw g(),h;if(s.length>0){let y=s.shift();return w(y!==void 0),l(),{value:y,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),g(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}},g0=r=>r===0?40:8,kd=class extends bd{constructor(e,t,n,i,s,a){super(e,t),this.codec=n,this.decoderConfig=i,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new nn,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.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.frameHandlerSerializer=new nn;let o=Zc.find(c=>c.supports(n,i));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof nr))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=u=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();w(d!==void 0),await this.mergeAlpha(u,d)}else this.colorQueue.push(u)}).catch(d=>this.onError(d))};if(n==="avc"&&this.decoderConfig.description&&Ws()){let u=Np(Ye(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){let d=Zs(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(w(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(w(this.decoder),an()||xu(this.inputTimestamps,e.timestamp,t=>t),Ws()&&this.currentPacketIndex===0){if(this.codec==="avc"){let t=[];for(let i of Iu(e.data,this.decoderConfig)){let s=Li(e.data[i.offset]);s===lt.AUD&&(t.length=0),s>=20&&s<=31||t.push(e.data.subarray(i.offset,i.offset+i.length))}let n=Lp(t,this.decoderConfig);e=new Oe(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){let t=Hp(e.data,this.decoderConfig);t&&(e=new Oe(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new el),!this.alphaDecoder){let n=s=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){let a=this.colorQueue.shift();w(a!==void 0),await this.mergeAlpha(a,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 a=this.colorQueue.shift();w(a!==void 0),await this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(a=>this.onError(a))},i=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(s)}catch(a){this.onError(a)}},error:s=>{s.stack=i,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=hn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of Ys(e,this.decoderConfig)){let n=un(e[t.offset]);if(n===it.RASL_N||n===it.RASL_R)return!0}return!1}sampleHandler(e){if(an()){if(this.sampleQueue.length>0&&e.timestamp>=ze(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}xu(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();w(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){if(!t){let s=new nr(e);this.sampleHandler(s);return}w(this.merger);let n=await this.merger.update(e,t),i=new nr(n);this.sampleHandler(i)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(w(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await this.frameHandlerSerializer.currentPromise,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),an()){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()):(w(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}},y0=!1,el=class r{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let e=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!r.forceCpu&&e&&!y0)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let t=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!t)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=t,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)}catch(t){this.gl=null,this.canvas=null,y0=!0,we._warn("Falling back to CPU for color/alpha merging.",t)}}async update(e,t){return this.gl?this.updateGpu(e,t):this.updateCpu(e,t)}createProgram(){w(this.gl);let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2018
1872
|
in vec2 a_position;
|
|
2019
1873
|
in vec2 a_texCoord;
|
|
2020
1874
|
out vec2 v_texCoord;
|
|
@@ -2036,8 +1890,8 @@ ${n}`),this.frame=e,this.failures=t}};async function hu(r){let{scale:e=1,frame:t
|
|
|
2036
1890
|
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
2037
1891
|
fragColor = vec4(color, alpha);
|
|
2038
1892
|
}
|
|
2039
|
-
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){w(this.gl);let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){w(this.gl),w(this.program);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){w(this.gl);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}updateGpu(e,t){w(this.gl),w(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let n=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),n}updateCpu(e,t){if(!this.worker){let s=new Blob([`(${kT.toString()})()`],{type:"application/javascript"}),a=URL.createObjectURL(s);this.worker=new Worker(a),URL.revokeObjectURL(a),this.worker.addEventListener("message",o=>{let c=o.data,l=this.pendingRequests.get(c.id);l&&(this.pendingRequests.delete(c.id),"error"in c?l.reject(new Error(c.error)):l.resolve(c.frame))}),this.worker.addEventListener("error",o=>{let c=new Error(o.message||"Color/alpha merge worker error.");for(let l of this.pendingRequests.values())l.reject(c);this.pendingRequests.clear()})}let n=this.nextRequestId++,i=nt();return this.pendingRequests.set(n,i),this.worker.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),i.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=new Error("Color/alpha merger closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};Jc.forceCpu=!0;var kT=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{let{id:l,color:u,alpha:d}=c.data;t=t.then(async()=>{try{let h=await n(u,d);self.postMessage({id:l,frame:h},{transfer:[h]})}catch(h){self.postMessage({id:l,error:h.message})}finally{u.close(),d.close()}})});let n=async(c,l)=>{let u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let h=u.includes("P10"),f=u.includes("P12"),p=d.includes("P10"),m=d.includes("P12");if(p!==h||m!==f)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);let g=c.codedWidth,y=c.codedHeight;if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await i(c,l,g,y,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await s(c,l,g,y,u);if(u==="NV12")return await a(c,l,g,y);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},i=async(c,l,u,d,h)=>{let f=u*d,p=new Uint8Array(f*4);await c.copyTo(p);let m=await o(l,u,d,1);for(let b=0,k=3;b<f;b++,k+=4)p[k]=m[b];let y={format:h==="RGBX"||h==="RGBA"?"RGBA":"BGRA",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},s=async(c,l,u,d,h)=>{let f=h.includes("P10"),p=h.includes("P12"),m=f||p?2:1,g,y;h.startsWith("I420")?(g=Math.ceil(u/2),y=Math.ceil(d/2)):h.startsWith("I422")?(g=Math.ceil(u/2),y=d):(g=u,y=d);let b=u*d,k=g*y,T=b*m,S=k*m,_=b*m,M=T+2*S+_,P=new Uint8Array(M);await c.copyTo(P);let A=await o(l,u,d,m),F=T+2*S;P.set(A,F);let O={format:h.slice(0,4)+"A"+h.slice(4),codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[P.buffer]};return new VideoFrame(P,O)},a=async(c,l,u,d)=>{let h=u*d,f=Math.ceil(u/2),p=Math.ceil(d/2),m=f*p,g=c.allocationSize();(!e||e.byteLength!==g)&&(e=new Uint8Array(g)),await c.copyTo(e);let y=new Uint8Array(h+2*m+h);y.set(e.subarray(0,h),0);let b=h,k=h+m,T=h;for(let M=0;M<m;M++)y[b+M]=e[T+M*2],y[k+M]=e[T+M*2+1];let S=await o(l,u,d,1);y.set(S,h+2*m);let _={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,_)},o=async(c,l,u,d)=>{let h=c.allocationSize();(!r||r.byteLength!==h)&&(r=new Uint8Array(h)),await c.copyTo(r);let f=c.format;if(f==="RGBA"||f==="BGRA"||f==="RGBX"||f==="BGRX"){let p=f==="RGBA"||f==="RGBX"?0:2,m=l*u;for(let g=0;g<m;g++)r[g]=r[g*4+p];return r.subarray(0,m)}else return r.subarray(0,l*u*d)}},xT=r=>{if(!r||typeof r!="object")throw new TypeError("decoderOptions must be an object.");if(r.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r.optimizeForLatency!==void 0&&typeof r.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")},xa=class extends Zc{constructor(e,t={}){if(!(e instanceof Kn))throw new TypeError("videoTrack must be an InputVideoTrack.");xT(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=await this._track.getCodec(),i=await this._track.getRotation(),s=await this._track.getDecoderConfig(),a=await this._track.getTimeResolution();return w(n&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new yd(e,t,n,s,i,a)}_createPacketSink(){return new wn(this._track)}async getSample(e,t={}){Yi(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}};var Zi=class r{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Kn}isAudioTrack(){return this instanceof Ji}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Xe(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Xe(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Xe(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Xe(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Xe(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),n=(t?.timestamp??0)+(t?.duration??0);return Fn(n,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new wn(this),i=1/0,s=-1/0,a=0,o=0;for await(let c of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=s)break;i=Math.min(i,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-i)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(s-i)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(bn({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(bn({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(bn({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(bn({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(bn({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=wd(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=wd(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=wd(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},Xe=(r,e,t)=>{if(r instanceof Promise)throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},wd=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{let t=i=>{if(typeof i!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return i},n=r(e);return n instanceof Promise?n.then(t):t(n)}:void 0},Kn=class extends Zi{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Xe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Xe(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Xe(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Xe(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Xe(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Xe(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Dn({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Dn({num:Xe(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Xe(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Xe(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Xe(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let i=Xe(e,"displayWidth","getDisplayWidth");if(i!==null)return i}let n=Xe(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Xe(n,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let i=Xe(e,"displayHeight","getDisplayHeight");if(i!==null)return i}let n=Xe(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Xe(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return w(t!==null),Yc.some(i=>i.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return we._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let t=await this.getCodec();if(t===null)return null;let n=await this.getDecoderConfig();return w(n),dn(t,n,e.data)}},Ji=class extends Zi{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Xe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Xe(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Xe(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return w(t!==null),md.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return we._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}};var bd=r=>-(r??-1/0),es=r=>-r,ts=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{let t=i=>{if(typeof i!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return i},n=r.filter(e);return n instanceof Promise?n.then(t):t(n)}:void 0,sortBy:r.sortBy?e=>{let t=i=>{if(typeof i!="number"&&(!Array.isArray(i)||!i.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return i},n=r.sortBy(e);return n instanceof Promise?n.then(t):t(n)}:void 0}},bn=(r,e)=>({filter:r?.filter||e?.filter?t=>{let n=r?.filter?.(t)??!0,i=s=>s===!1?!1:e?.filter?.(t)??!0;return n instanceof Promise?n.then(i):i(n)}:void 0,sortBy:r?.sortBy||e?.sortBy?t=>{let n=r?.sortBy?.(t)??[],i=e?.sortBy?.(t)??[],s=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([a,o])=>s(a,o)):s(n,i)}:void 0}),el=async(r,e)=>{let t=r;if(e?.filter){let a=r.map(c=>e.filter(c));if(a.some(c=>c instanceof Promise)){let c=await Promise.all(a);t=r.filter((l,u)=>c[u])}else t=r.filter((c,l)=>a[l])}if(!e?.sortBy)return t;let n=t.map(a=>e.sortBy(a)),s=n.some(a=>a instanceof Promise)?await Promise.all(n):n;return t.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{let c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){let h=c[d]??0,f=l[d]??0;if(h!==f)return h-f}return 0}).map(a=>a.track)};Ei();var ST=1,bg=2,qr=class r extends Nt{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof Mt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof wt||e.source instanceof Wn))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof wt&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof r))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&Fg(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof wt?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){w(this._rootSource instanceof Ot);let t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=ST){let n=this._sourceCache.find(a=>a.cacheGroup===t&&od(a.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let i=this._sourceCachePromises.find(a=>a.cacheGroup===t&&od(a.request,e));if(i)return i.promise.then(a=>a.sourceRef.source.ref());let s=(async()=>{let a=await this._getSourceUncached(e);if(Bn(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){let d=Mi(this._sourceCache,f=>f.cacheGroup===t&&f.sourceRef.source._refCount===1?f.age:1/0);w(d!==-1);let h=this._sourceCache[d];this._sourceCache.splice(d,1),h.sourceRef.free(),jm(this._sourceRefs,h.sourceRef)}this._sourceRefs.push(a);let l=this._sourceCachePromises.findIndex(d=>d.request===e);return w(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(a=>{let o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new gn(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new Sa})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),w(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Sa)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(i=>i!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(i=>i.getFirstTimestamp()));return Math.min(...n)}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(s=>s!==null);if(n.length===0)return 0;let i=await Promise.all(n.map(s=>s.computeDuration(t)));return Math.max(...i)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(a=>a!==null),s=(await Promise.all(n.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=ts(e);let n=(await this._getTrackBackings()).map(i=>this._wrapBackingAsTrack(i));return el(n,e)}async getVideoTracks(e){e&&=ts(e);let n=(await this.getTracks()).filter(i=>i.isVideoTrack());return el(n,e)}async getAudioTracks(e){e&&=ts(e);let n=(await this.getTracks()).filter(i=>i.isAudioTrack());return el(n,e)}async getPrimaryVideoTrack(e){e&&=ts(e);let t=bn(e,{sortBy:async i=>[es((await i.getDisposition()).default),es(await i.hasPairableAudioTrack()),es(!await i.hasOnlyKeyPackets()),bd(await i.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=ts(e);let t=await this.getPrimaryVideoTrack(),n=bn(e,{sortBy:async s=>[es(!t||s.canBePairedWith(t)),es((await s.getDisposition()).default),bd(await s.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let i=e.getType()==="video"?new Kn(this,e):new Ji(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},Sa=class extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}},ut=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var gn=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new ut;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let s=new Uint8Array(0);return new yt(s,ve(s),0,e,e)}let n=e+t,i=this.source._read(e,n,sd,ad);return i instanceof Promise?i.then(s=>s?new yt(s.bytes,s.view,s.offset,e,n):null):i?new yt(i.bytes,i.view,i.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new ut;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Ze(this.fileSizeNonStrict-e,t,n));{let i=this.requestSlice(e,n),s=a=>a||(w(this.fileSizeNonStrict!==null),this.requestSlice(e,Ze(this.fileSizeNonStrict-e,t,n)));return i instanceof Promise?i.then(s):s(i)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let e=1024;return(async()=>{let t=[],n=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(n,0,e);if(a instanceof Promise&&(a=await a),!a||a.length===0)break;let o=ie(a,a.length);t.push(o),n+=a.length}let i=new Uint8Array(n),s=0;for(let a of t)i.set(a,s),s+=a.length;return new yt(i,ve(i),0,0,n)})()}},yt=class r{constructor(e,t,n,i,s){this.bytes=e,this.view=t,this.offset=n,this.start=i,this.end=s,this.bufferPos=i-n}static tempFromBytes(e){return new r(e,ve(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new r(this.bytes,this.view,this.offset,e,e+t)}},Ft=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},ie=(r,e)=>{Ft(r,e);let t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},ce=r=>(Ft(r,1),r.view.getUint8(r.bufferPos++)),$i=(r,e)=>{Ft(r,2);let t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},Ke=r=>{Ft(r,2);let e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},Yt=r=>{Ft(r,3);let e=Os(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},Js=r=>{Ft(r,2);let e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Vr=(r,e)=>{Ft(r,4);let t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},K=r=>{Ft(r,4);let e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},Un=r=>{Ft(r,4);let e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Dr=r=>{Ft(r,4);let e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},TT=r=>{Ft(r,4);let e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},Wu=(r,e)=>{let t,n;return e?(t=Vr(r,!0),n=Vr(r,!0)):(n=Vr(r,!1),t=Vr(r,!1)),n*4294967296+t},Pt=r=>{let e=K(r),t=K(r);return e*4294967296+t},Hp=r=>{let e=Dr(r),t=K(r);return e*4294967296+t},eg=r=>{let e=Un(r);return TT(r)*4294967296+e},qp=r=>{Ft(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},uc=r=>{Ft(r,8);let e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},We=(r,e)=>{Ft(r,e);let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},Fc=(r,e,t)=>ot.decode(ie(r,e)).split(`
|
|
2040
|
-
`).map(s=>s.trim()).filter(s=>s.length>0&&!t?.ignore?.(s));var $n;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})($n||($n={}));var ns;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(ns||(ns={}));var na=128,mt=10,is=["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"],Kp=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=ie(r,na-3),r.filePos=t;let n=rs(r,30);n&&(e.title??=n);let i=rs(r,30);i&&(e.artist??=i);let s=rs(r,30);s&&(e.album??=s);let a=rs(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(String(o)));let c=ie(r,30),l;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(e.trackNumber??=d),r.skip(-30),l=rs(r,28),r.skip(2)}else r.skip(-30),l=rs(r,30);l&&(e.comment??=l);let u=ce(r);u<is.length&&(e.genre??=is[u])},rs=(r,e)=>{let t=ie(r,e),n=Rn(t.indexOf(0),t.length),i=t.subarray(0,n),s="";for(let a=0;a<i.length;a++)s+=String.fromCharCode(i[a]);return s.trimEnd()},It=r=>{let e=r.filePos,t=We(r,3),n=ce(r),i=ce(r),s=ce(r),a=K(r);if(t!=="ID3"||n===255||i===255||(a&2155905152)!==0)return r.filePos=e,null;let o=jo(a);return s&$n.Footer&&(o+=mt),{majorVersion:n,revision:i,flags:s,size:o}},mn=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){we._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=e.flags&$n.Footer?e.size-mt:e.size,i=ie(r,n),s=new kd(e,i);if(e.flags&$n.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&$n.ExtendedHeader){let a=s.readU32();e.majorVersion===3?s.pos+=a:s.pos+=a-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){let a=s.readId3V2Frame();if(!a)break;let o=s.pos,c=s.pos+a.size,l=!1,u=!1,d=!1;if(e.majorVersion===3?(l=!!(a.flags&64),u=!!(a.flags&128)):e.majorVersion===4&&(l=!!(a.flags&4),u=!!(a.flags&8),d=!!(a.flags&2)||!!(e.flags&$n.Unsynchronisation)),l){we._warn(`Skipping encrypted ID3v2 frame ${a.id}`),s.pos=c;continue}if(u){we._warn(`Skipping compressed ID3v2 frame ${a.id}`),s.pos=c;continue}if(d&&s.ununsynchronizeRegion(s.pos,c),t.raw??={},a.id==="TXXX"){let h=t.raw.TXXX??={},f=s.readId3V2TextEncoding(),p=s.readId3V2Text(f,c),m=s.readId3V2Text(f,c);h[p]??=m}else a.id[0]==="T"?t.raw[a.id]??=s.readId3V2EncodingAndText(c):t.raw[a.id]??=s.readBytes(a.size);switch(s.pos=o,a.id){case"TIT2":case"TT2":t.title??=s.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":t.description??=s.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":t.artist??=s.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":t.album??=s.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":t.albumArtist??=s.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{let f=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(t.tracksTotal??=m)}break;case"TPOS":case"TPA":{let f=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(t.discsTotal??=m)}break;case"TCON":case"TCO":{let h=s.readId3V2EncodingAndText(c),f=/^\((\d+)\)/.exec(h);if(f){let p=Number.parseInt(f[1]);if(is[p]!==void 0){t.genre??=is[p];break}}if(f=/^\d+$/.exec(h),f){let p=Number.parseInt(f[0]);if(is[p]!==void 0){t.genre??=is[p];break}}t.genre??=h}break;case"TDRC":case"TDAT":{let h=s.readId3V2EncodingAndText(c),f=new Date(h);Number.isNaN(f.getTime())||(t.date??=f)}break;case"TYER":case"TYE":{let h=s.readId3V2EncodingAndText(c),f=Number.parseInt(h,10);Number.isInteger(f)&&(t.date??=new Date(String(f)))}break;case"USLT":case"ULT":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,c),t.lyrics??=s.readId3V2Text(h,c)}break;case"COMM":case"COM":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,c),t.comment??=s.readId3V2Text(h,c)}break;case"APIC":case"PIC":{let h=s.readId3V2TextEncoding(),f;if(e.majorVersion===2){let y=s.readAscii(3);f=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else f=s.readId3V2Text(h,c);let p=s.readU8(),m=s.readId3V2Text(h,c).trimEnd(),g=c-s.pos;if(g>=0){let y=s.readBytes(g);t.images||(t.images=[]),t.images.push({data:y,mimeType:f,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=a.size;break}s.pos=c}},kd=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let a=e;a<t;a++){let o=this.bytes[a];n.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}let i=this.bytes.subarray(0,e),s=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+n.length+s.length),this.bytes.set(i,0),this.bytes.set(n,i.length),this.bytes.set(s,i.length+n.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),n=this.header.majorVersion===4?jo(t):t,i=this.readU16(),s=this.pos,a=o=>{let c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;let l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!a(n)){let o=this.header.majorVersion===4?t:jo(t);a(o)&&(n=o)}return this.pos=s,{id:e,size:n,flags:i}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,i=this.readBytes(t-this.pos);switch(e){case ns.ISO_8859_1:{let s="";for(let a=0;a<i.length;a++){let o=i[a];if(o===0){this.pos=n+a+1;break}s+=String.fromCharCode(o)}return s}case ns.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){let s=new TextDecoder("utf-16le"),a=Rn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else if(i[0]===254&&i[1]===255){let s=new TextDecoder("utf-16be"),a=Rn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else{let s=Rn(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),ot.decode(i.subarray(0,s))}case ns.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),a=Rn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(0,a))}case ns.UTF_8:{let s=Rn(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),ot.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var tl=class{constructor(e){this.mutex=new At,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let i=this.trackTimestampInfo.get(e);if(i){if(n&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),i.maxTimestampBeforeLastKeyPacket!==null&&t<i.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);i.maxTimestamp=Math.max(i.maxTimestamp,t)}else{if(!n)throw new Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,i)}}};var xd=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var r0=r=>{let e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),n=Math.floor(r%(60*1e3)/1e3),i=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+i.toString().padStart(3,"0")};var Xn=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let s of e.children)s&&this.writeBox(s);let n=this.writer.getPos(),i=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);w(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},Pe=new Uint8Array(8),qt=new DataView(Pe.buffer),Je=r=>[(r%256+256)%256],Se=r=>(qt.setUint16(0,r,!1),[Pe[0],Pe[1]]),Ad=r=>(qt.setInt16(0,r,!1),[Pe[0],Pe[1]]),s0=r=>(qt.setUint32(0,r,!1),[Pe[1],Pe[2],Pe[3]]),j=r=>(qt.setUint32(0,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),Gr=r=>(qt.setInt32(0,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),yr=r=>(qt.setUint32(0,Math.floor(r/2**32),!1),qt.setUint32(4,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3],Pe[4],Pe[5],Pe[6],Pe[7]]),vT=r=>(qt.setInt32(0,Math.floor(r/2**32),!1),qt.setUint32(4,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3],Pe[4],Pe[5],Pe[6],Pe[7]]),a0=r=>(qt.setInt16(0,2**8*r,!1),[Pe[0],Pe[1]]),ir=r=>(qt.setInt32(0,2**16*r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),Sd=r=>(qt.setInt32(0,2**30*r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),Td=(r,e)=>{let t=[],n=r;do{let i=n&127;n>>=7,t.length>0&&(i|=128),t.push(i),e!==void 0&&e--}while(n>0||e);return t.reverse()},je=(r,e=!1)=>{let t=Array(r.length).fill(null).map((n,i)=>r.charCodeAt(i));return e&&t.push(0),t},o0=r=>{let e=r*(Math.PI/180),t=Math.round(Math.cos(e)),n=Math.round(Math.sin(e));return[t,n,0,-n,t,0,0,0,1]},c0=o0(0),l0=r=>[ir(r[0]),ir(r[1]),Sd(r[2]),ir(r[3]),ir(r[4]),Sd(r[5]),ir(r[6]),ir(r[7]),Sd(r[8])],ke=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),Ve=(r,e,t,n,i)=>ke(r,[Je(e),s0(t),n??[]],i),u0=r=>r.isQuickTime?ke("ftyp",[je("qt "),j(512),je("qt ")]):r.fragmented?r.cmaf?ke("ftyp",[je("iso5"),j(512),je("iso5"),je("iso6"),je("mp41"),je("cmfc"),je("dash")]):ke("ftyp",[je("iso5"),j(512),je("iso5"),je("iso6"),je("mp41")]):ke("ftyp",[je("isom"),j(512),je("isom"),r.holdsAvc?je("avc1"):[],je("mp41")]),_d=()=>ke("styp",[je("iso5"),j(0),je("iso5"),je("iso6"),je("mp41"),je("cmfc"),je("dash")]),Cd=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),Ve("sidx",1,0,[j(1),j(Wt),yr($e(r.minWrittenTimestamp,Wt)),yr(0),Se(0),Se(1),j(e&2147483647),j($e(t,Wt)),j(0)])},Ta=r=>({type:"mdat",largeSize:r}),d0=r=>({type:"free",size:r}),ss=r=>ke("moov",void 0,[AT(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>_T(e,r.creationTime)),r.isFragmented?dv(r.trackDatas):null,kv(r)]),AT=(r,e)=>{let t=Math.max(0,...e.map(a=>$e(rl(a),Wt)+$e(a.startTimestampOffset??0,Wt))),n=Math.max(0,...e.map(a=>a.track.id))+1,i=!Ar(r)||!Ar(t),s=i?yr:j;return Ve("mvhd",+i,0,[s(r),s(r),j(Wt),s(t),ir(1),a0(1),Array(10).fill(0),l0(c0),Array(24).fill(0),j(n)])},rl=r=>{if(r.samples.length===0)return 0;let e=1/0,t=-1/0;for(let n=0;n<r.samples.length;n++){let i=r.samples[n];i.timestamp<e&&(e=i.timestamp),i.timestamp+i.duration>t&&(t=i.timestamp+i.duration)}return e===1/0?0:t-e},_T=(r,e)=>{let t=k0(r),n=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return ke("trak",void 0,[CT(r,e),n?PT(r,r.startTimestampOffset):null,ET(r,e),t.name!==void 0?ke("udta",void 0,[ke("name",[..._t.encode(t.name)])]):null])},CT=(r,e)=>{let t=$e(rl(r),Wt)+$e(r.startTimestampOffset??0,Wt),n=!Ar(e)||!Ar(t),i=n?yr:j,s;if(r.type==="video"){let o=r.track.metadata.rotation;s=o0(o??0)}else s=c0;let a=2;return r.track.metadata.disposition?.default!==!1&&(a|=1),Ve("tkhd",+n,a,[i(e),i(e),j(r.track.id),j(0),i(t),Array(8).fill(0),Se(0),Se(r.track.id),a0(r.type==="audio"?1:0),Se(0),l0(s),ir(r.type==="video"?r.info.width:0),ir(r.type==="video"?r.info.height:0)])},PT=(r,e)=>{let t=$e(e,Wt),n=$e(rl(r),Wt),i=!Ar(t)||!Ar(n),s=i?yr:j,a=i?vT:Gr;return ke("edts",void 0,[Ve("elst",i?1:0,0,[j(2),s(t),a(-1),ir(1),s(n),a(0),ir(1)])])},ET=(r,e)=>ke("mdia",void 0,[IT(r,e),Pd(!0,MT[r.type],FT[r.type]),RT(r)]),IT=(r,e)=>{let t=$e(rl(r),r.timescale),n=!Ar(e)||!Ar(t),i=n?yr:j;return Ve("mdhd",+n,0,[i(e),i(e),j(r.timescale),i(t),Se(b0(r.track.metadata.languageCode??Ge)),Se(0)])},MT={video:"vide",audio:"soun",subtitle:"text"},FT={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Pd=(r,e,t,n="\0\0\0\0")=>Ve("hdlr",0,0,[r?je("mhlr"):j(0),je(e),je(n),j(0),j(0),je(t,!0)]),RT=r=>ke("minf",void 0,[LT[r.type](),UT(),VT(r)]),BT=()=>Ve("vmhd",0,1,[Se(0),Se(0),Se(0),Se(0)]),DT=()=>Ve("smhd",0,0,[Se(0),Se(0)]),OT=()=>Ve("nmhd",0,0),LT={video:BT,audio:DT,subtitle:OT},UT=()=>ke("dinf",void 0,[zT()]),zT=()=>Ve("dref",0,0,[j(1)],[NT()]),NT=()=>Ve("url ",0,1),VT=r=>{let e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return ke("stbl",void 0,[HT(r),iv(r),e?lv(r):null,e?uv(r):null,av(r),ov(r),cv(r),sv(r)])},HT=r=>{let e;if(r.type==="video")e=WT(vv(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){let t=w0(r.track.source._codec,r.muxer.isQuickTime);w(t),e=XT(t,r)}else r.type==="subtitle"&&(e=rv(Cv[r.track.source._codec],r));return w(e),Ve("stsd",0,0,[j(1)],[e])},WT=(r,e)=>ke(r,[Array(6).fill(0),Se(1),Se(0),Se(0),Array(12).fill(0),Se(e.info.width),Se(e.info.height),j(4718592),j(4718592),j(0),Se(1),Array(32).fill(0),Se(24),Ad(65535)],[Av[e.track.source._codec](e),qT(e),Hm(e.info.decoderConfig.colorSpace)?jT(e):null]),qT=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:ke("pasp",[j(r.info.pixelAspectRatio.num),j(r.info.pixelAspectRatio.den)]),jT=r=>ke("colr",[je(r.muxer.isQuickTime?"nclc":"nclx"),Se(_r[r.info.decoderConfig.colorSpace.primaries]),Se(Cr[r.info.decoderConfig.colorSpace.transfer]),Se(Pr[r.info.decoderConfig.colorSpace.matrix]),r.muxer.isQuickTime?[]:Je((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),GT=r=>r.info.decoderConfig&&ke("avcC",[...Ye(r.info.decoderConfig.description)]),KT=r=>r.info.decoderConfig&&ke("hvcC",[...Ye(r.info.decoderConfig.description)]),n0=r=>{if(!r.info.decoderConfig)return null;let e=r.info.decoderConfig,t=e.codec.split("."),n=Number(t[1]),i=Number(t[2]),s=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(s<<4)+(a<<1)+o,l=t[5]?Number(t[5]):e.colorSpace?.primaries?_r[e.colorSpace.primaries]:2,u=t[6]?Number(t[6]):e.colorSpace?.transfer?Cr[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):e.colorSpace?.matrix?Pr[e.colorSpace.matrix]:2;return Ve("vpcC",1,0,[Je(n),Je(i),Je(c),Je(l),Je(u),Je(d),Se(0)])},$T=r=>ke("av1C",cp(r.info.decoderConfig.codec)),XT=(r,e)=>{let t=0,n,i=16,s=ht.includes(e.track.source._codec);if(s){let a=e.track.source._codec,{sampleSize:o}=Ht(a);i=8*o,i>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)n=[Array(6).fill(0),Se(1),Se(t),Se(0),j(0),Se(e.info.numberOfChannels),Se(i),Se(0),Se(0),Se(e.info.sampleRate<2**16?e.info.sampleRate:0),Se(0)];else{let a=s?0:-2;n=[Array(6).fill(0),Se(1),Se(t),Se(0),j(0),Se(e.info.numberOfChannels),Se(Math.min(i,16)),Ad(a),Se(0),Se(e.info.sampleRate<2**16?e.info.sampleRate:0),Se(0),s?[j(1),j(i/8),j(e.info.numberOfChannels*i/8)]:[j(0),j(0),j(0)],j(2)]}return ke(r,n,[_v(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},vd=r=>{let e;switch(r.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let t=[...Je(e),...Je(21),...s0(0),...j(0),...j(0)];if(r.info.decoderConfig.description){let n=Ye(r.info.decoderConfig.description);t=[...t,...Je(5),...Td(n.byteLength),...n]}return t=[...Se(1),...Je(0),...Je(4),...Td(t.length),...t,...Je(6),...Je(1),...Je(2)],t=[...Je(3),...Td(t.length),...t],Ve("esds",0,0,t)},kn=r=>ke("wave",void 0,[QT(r),YT(r),ke("\0\0\0\0")]),QT=r=>ke("frma",[je(w0(r.track.source._codec,r.muxer.isQuickTime))]),YT=r=>{let{littleEndian:e}=Ht(r.track.source._codec);return ke("enda",[Se(+e)])},ZT=r=>{let e=r.info.numberOfChannels,t=3840,n=r.info.sampleRate,i=0,s=0,a=new Uint8Array(0),o=r.info.decoderConfig?.description;if(o){w(o.byteLength>=18);let c=Ye(o),l=Qo(c);e=l.outputChannelCount,t=l.preSkip,n=l.inputSampleRate,i=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return ke("dOps",[Je(0),Je(e),Se(t),j(n),Ad(i),Je(s),...a])},JT=r=>{let e=r.info.decoderConfig?.description;w(e);let t=Ye(e);return Ve("dfLa",0,0,[...t.subarray(4)])},pr=r=>{let{littleEndian:e,sampleSize:t}=Ht(r.track.source._codec),n=+e;return Ve("pcmC",0,0,[Je(n),Je(8*t)])},ev=r=>{let e=Yo(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let t=new Uint8Array(3),n=new Ie(t);return n.writeBits(2,e.fscod),n.writeBits(5,e.bsid),n.writeBits(3,e.bsmod),n.writeBits(3,e.acmod),n.writeBits(1,e.lfeon),n.writeBits(5,e.bitRateCode),n.writeBits(5,0),ke("dac3",[...t])},tv=r=>{let e=Zo(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(let a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;let n=Math.ceil(t/8),i=new Uint8Array(n),s=new Ie(i);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(let a of e.substreams)s.writeBits(2,a.fscod),s.writeBits(5,a.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,a.bsmod),s.writeBits(3,a.acmod),s.writeBits(1,a.lfeon),s.writeBits(3,0),s.writeBits(4,a.numDepSub),a.numDepSub>0?s.writeBits(9,a.chanLoc):s.writeBits(1,0);return ke("dec3",[...i])},rv=(r,e)=>ke(r,[Array(6).fill(0),Se(1)],[Pv[e.track.source._codec](e)]),nv=r=>ke("vttC",[..._t.encode(r.info.config.description)]);var iv=r=>Ve("stts",0,0,[j(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[j(e.sampleCount),j(e.sampleDelta)])]),sv=r=>{if(r.samples.every(t=>t.type==="key"))return null;let e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return Ve("stss",0,0,[j(e.length),e.map(([t])=>j(t+1))])},av=r=>Ve("stsc",0,0,[j(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[j(e.firstChunk),j(e.samplesPerChunk),j(1)])]),ov=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){let{sampleSize:e}=Ht(r.track.source._codec);return Ve("stsz",0,0,[j(e*r.info.numberOfChannels),j(r.samples.reduce((t,n)=>t+$e(n.duration,r.timescale),0))])}return Ve("stsz",0,0,[j(0),j(r.samples.length),r.samples.map(e=>j(e.size))])},cv=r=>r.finalizedChunks.length>0&&Ne(r.finalizedChunks).offset>=2**32?Ve("co64",0,0,[j(r.finalizedChunks.length),r.finalizedChunks.map(e=>yr(e.offset))]):Ve("stco",0,0,[j(r.finalizedChunks.length),r.finalizedChunks.map(e=>j(e.offset))]),lv=r=>Ve("ctts",1,0,[j(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[j(e.sampleCount),Gr(e.sampleCompositionTimeOffset)])]),uv=r=>{let e=1/0,t=-1/0,n=1/0,i=-1/0;w(r.compositionTimeOffsetTable.length>0),w(r.samples.length>0);for(let a=0;a<r.compositionTimeOffsetTable.length;a++){let o=r.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<r.samples.length;a++){let o=r.samples[a];n=Math.min(n,$e(o.timestamp,r.timescale)),i=Math.max(i,$e(o.timestamp+o.duration,r.timescale))}let s=Math.max(-e,0);return i>=2**31?null:Ve("cslg",0,0,[Gr(s),Gr(e),Gr(t),Gr(n),Gr(i)])},dv=r=>ke("mvex",void 0,r.map(hv)),hv=r=>Ve("trex",0,0,[j(r.track.id),j(1),j(0),j(0),j(0)]),Ed=(r,e)=>ke("moof",void 0,[fv(r),...e.map(mv)]),fv=r=>Ve("mfhd",0,0,[j(r)]),h0=r=>{let e=0,t=0,n=0,i=0,s=r.type==="delta";return t|=+s,s?e|=1:e|=2,e<<24|t<<16|n<<8|i},mv=r=>ke("traf",void 0,[pv(r),gv(r),yv(r)]),pv=r=>{w(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let t=r.currentChunk.samples[1]??r.currentChunk.samples[0],n={duration:t.timescaleUnitsToNextSample,size:t.size,flags:h0(t)};return Ve("tfhd",0,e,[j(r.track.id),j(n.duration),j(n.size),j(n.flags)])},gv=r=>(w(r.currentChunk),Ve("tfdt",1,0,[yr($e(r.currentChunk.startTimestamp,r.timescale))])),yv=r=>{w(r.currentChunk);let e=r.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(m=>m.size),n=r.currentChunk.samples.map(h0),i=r.currentChunk.samples.map(m=>$e(m.timestamp-m.decodeTimestamp,r.timescale)),s=new Set(e),a=new Set(t),o=new Set(n),c=new Set(i),l=o.size===2&&n[0]!==n[1],u=s.size>1,d=a.size>1,h=!l&&o.size>1,f=c.size>1||[...c].some(m=>m!==0),p=0;return p|=1,p|=4*+l,p|=256*+u,p|=512*+d,p|=1024*+h,p|=2048*+f,Ve("trun",1,p,[j(r.currentChunk.samples.length),j(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?j(n[0]):[],r.currentChunk.samples.map((m,g)=>[u?j(e[g]):[],d?j(t[g]):[],h?j(n[g]):[],f?Gr(i[g]):[]])])},f0=r=>ke("mfra",void 0,[...r.map(wv),bv()]),wv=(r,e)=>Ve("tfra",1,0,[j(r.track.id),j(63),j(r.finalizedChunks.length),r.finalizedChunks.map(n=>[yr($e(n.samples[0].timestamp,r.timescale)),yr(n.moofOffset),j(e+1),j(1),j(1)])]),bv=()=>Ve("mfro",0,0,[j(0)]),m0=()=>ke("vtte"),p0=(r,e,t,n,i)=>ke("vttc",void 0,[i!==null?ke("vsid",[Gr(i)]):null,t!==null?ke("iden",[..._t.encode(t)]):null,e!==null?ke("ctim",[..._t.encode(r0(e))]):null,n!==null?ke("sttg",[..._t.encode(n)]):null,ke("payl",[..._t.encode(r)])]),g0=r=>ke("vtta",[..._t.encode(r)]),kv=r=>{let e=[],t=r.format._options.metadataFormat??"auto",n=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){let i=Sv(n);i&&e.push(i)}else if(t==="mdta"){let i=Tv(n);i&&e.push(i)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&xv(e,r.output._metadataTags);return e.length===0?null:ke("udta",void 0,e)},xv=(r,e)=>{for(let{key:t,value:n}of Vs(e))switch(t){case"title":r.push(gr("\xA9nam",n));break;case"description":r.push(gr("\xA9des",n));break;case"artist":r.push(gr("\xA9ART",n));break;case"album":r.push(gr("\xA9alb",n));break;case"albumArtist":r.push(gr("albr",n));break;case"genre":r.push(gr("\xA9gen",n));break;case"date":r.push(gr("\xA9day",n.toISOString().slice(0,10)));break;case"comment":r.push(gr("\xA9cmt",n));break;case"lyrics":r.push(gr("\xA9lyr",n));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Ct(t)}if(e.raw)for(let t in e.raw){let n=e.raw[t];n==null||t.length!==4||r.some(i=>i.type===t)||(typeof n=="string"?r.push(gr(t,n)):n instanceof Uint8Array&&r.push(ke(t,Array.from(n))))}},gr=(r,e)=>{let t=_t.encode(e);return ke(r,[Se(t.length),Se(b0("und")),Array.from(t)])},i0={"image/jpeg":13,"image/png":14,"image/bmp":27},y0=(r,e)=>{let t=[];for(let{key:n,value:i}of Vs(r))switch(n){case"title":t.push({key:e?"title":"\xA9nam",value:nr(i)});break;case"description":t.push({key:e?"description":"\xA9des",value:nr(i)});break;case"artist":t.push({key:e?"artist":"\xA9ART",value:nr(i)});break;case"album":t.push({key:e?"album":"\xA9alb",value:nr(i)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:nr(i)});break;case"comment":t.push({key:e?"comment":"\xA9cmt",value:nr(i)});break;case"genre":t.push({key:e?"genre":"\xA9gen",value:nr(i)});break;case"lyrics":t.push({key:e?"lyrics":"\xA9lyr",value:nr(i)});break;case"date":t.push({key:e?"date":"\xA9day",value:nr(i.toISOString().slice(0,10))});break;case"images":for(let s of i)s.kind==="coverFront"&&t.push({key:"covr",value:ke("data",[j(i0[s.mimeType]??0),j(0),Array.from(s.data)])});break;case"trackNumber":if(e){let s=r.tracksTotal!==void 0?`${i}/${r.tracksTotal}`:i.toString();t.push({key:"track",value:nr(s)})}else t.push({key:"trkn",value:ke("data",[j(0),j(0),Se(0),Se(i),Se(r.tracksTotal??0),Se(0)])});break;case"discNumber":e||t.push({key:"disc",value:ke("data",[j(0),j(0),Se(0),Se(i),Se(r.discsTotal??0),Se(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Ct(n)}if(r.raw)for(let n in r.raw){let i=r.raw[n];i==null||!e&&n.length!==4||t.some(s=>s.key===n)||(typeof i=="string"?t.push({key:n,value:nr(i)}):i instanceof Uint8Array?t.push({key:n,value:ke("data",[j(0),j(0),Array.from(i)])}):i instanceof Kt&&t.push({key:n,value:ke("data",[j(i0[i.mimeType]??0),j(0),Array.from(i.data)])}))}return t},Sv=r=>{let e=y0(r,!1);return e.length===0?null:Ve("meta",0,0,void 0,[Pd(!1,"mdir","","appl"),ke("ilst",void 0,e.map(t=>ke(t.key,void 0,[t.value])))])},Tv=r=>{let e=y0(r,!0);return e.length===0?null:ke("meta",void 0,[Pd(!1,"mdta",""),Ve("keys",0,0,[j(e.length)],e.map(t=>ke("mdta",[..._t.encode(t.key)]))),ke("ilst",void 0,e.map((t,n)=>{let i=String.fromCharCode(...j(n+1));return ke(i,void 0,[t.value])}))])},nr=r=>ke("data",[j(1),j(0),..._t.encode(r)]),vv=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},Av={avc:GT,hevc:KT,vp8:n0,vp9:n0,av1:$T},w0=(r,e)=>{switch(r){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(r){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(r){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},_v=(r,e)=>{switch(r){case"aac":return vd;case"mp3":return vd;case"opus":return ZT;case"vorbis":return vd;case"flac":return JT;case"ac3":return ev;case"eac3":return tv}if(e)switch(r){case"pcm-s24":return kn;case"pcm-s24be":return kn;case"pcm-s32":return kn;case"pcm-s32be":return kn;case"pcm-f32":return kn;case"pcm-f32be":return kn;case"pcm-f64":return kn;case"pcm-f64be":return kn}else switch(r){case"pcm-s16":return pr;case"pcm-s16be":return pr;case"pcm-s24":return pr;case"pcm-s24be":return pr;case"pcm-s32":return pr;case"pcm-s32be":return pr;case"pcm-f32":return pr;case"pcm-f32be":return pr;case"pcm-f64":return pr;case"pcm-f64be":return pr}return null},Cv={webvtt:"wvtt"},Pv={webvtt:nv},b0=r=>{w(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};var Qn=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){w(!this.started),this.target._start(),this.started=!0}write(e){w(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return w(this.started&&!this.finalized),this.target._flush()}async finalize(){w(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,i=this.trackedWrites.byteLength;for(;i<n;)i*=2;if(i!==this.trackedWrites.byteLength){let s=new Uint8Array(i);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}};var Rt=class extends Nt{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new nl(this,e)}},Id=2**16,Md=2**32,sr=class extends Rt{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Id,{maxByteLength:Md})}catch{this._buffer=new ArrayBuffer(Id),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Id);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Md)throw new Error(`ArrayBuffer exceeded maximum size of ${Md} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let n=new ArrayBuffer(t),i=new Uint8Array(n);i.set(this._bytes,0),this._buffer=n,this._bytes=i}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},Ev=2**24,Iv=2,va=class extends Rt{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??Ev}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){let n=t-this._lastWriteEnd;this._write(new Uint8Array(n),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(w(this._streamWriter),this._sections.length===0)return;let e=[],t=[...this._sections].sort((n,i)=>n.start-i.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let n=1;n<t.length;n++){let i=e[e.length-1],s=t[n];s.start<=i.start+i.size?i.size=Math.max(i.size,s.start+s.data.byteLength-i.start):e.push({start:s.start,size:s.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let i of this._sections)n.start<=i.start&&i.start<n.start+n.size&&n.data.set(i.data,i.start-n.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(n.data,n.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&n.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data,position:n.start}).catch(i=>{this._writeError??=i}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let n=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);n===-1&&(n=this._createChunk(t));let i=this._chunks[n],s=t-i.start,a=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));i.data.set(a,s);let o={start:s,end:s+a.byteLength};if(this._insertSectionIntoChunk(i,o),i.written[0].start===0&&i.written[0].end===this._chunkSize&&(i.shouldFlush=!0),this._chunks.length>Iv){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let n=0,i=e.written.length-1,s=-1;for(;n<=i;){let a=Math.floor(n+(i-n+1)/2);e.written[a].start<=t.start?(n=a+1,s=a):i=a-1}for(e.written.splice(s+1,0,t),(s===-1||e.written[s].end<t.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((i,s)=>i.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){w(this._streamWriter);for(let t=0;t<this._chunks.length;t++){let n=this._chunks[t];if(!(!n.shouldFlush&&!e)){for(let i of n.written){let s=n.start+i.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data.subarray(i.start,i.end),position:s}).catch(a=>{this._writeError??=a}),this._lastFlushEnd=n.start+i.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;w(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}};var nl=class extends Rt{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},Yn=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}};var Wt=57600,Mv=2082844800,k0=r=>{let e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},$e=(r,e,t=!0)=>{let n=r*e;return t?Math.round(n):n},il=class extends tl{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new sr,this.auxWriter=new Qn(this.auxTarget,!1),this.auxBoxWriter=new Xn(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=nt(),this.creationTime=Math.floor(Date.now()/1e3)+Mv,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof os,this.isCmaf=t instanceof as,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof as?1/0:1)}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":n instanceof sr),this.boxWriter=new Xn(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof sr?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let n=await this.output._getInitTarget(),i=new Qn(n,!0);i.start(),this.initWriter=i,this.initBoxWriter=new Xn(i)}let t=this.output._tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(w(n),this.format._options.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(u0({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:i,start:s}=n.writer.stopTrackingWrites();this.format._options.onFtyp(i,s)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output._tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(w(this.writer),w(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ta(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return tc({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,n){let i=this.trackDatas.find(h=>h.track===e);if(i)return i;fp(n),w(n),w(n.decoderConfig);let s={...n.decoderConfig};w(s.codedWidth!==void 0),w(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){let h=Li(t.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=Sp(h),a=!0}else if(e.source._codec==="hevc"&&!s.description){let h=Ui(t.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=Ap(h),a=!0}let o=Zm(1/(e.metadata.frameRate??Wt),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:Dn({num:c*s.codedHeight,den:l*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:u,decoderConfig:s,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((h,f)=>h.track.id-f.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let i=this.trackDatas.find(c=>c.track===e);if(i)return i;mp(n),w(n),w(n.decoderConfig);let s={...n.decoderConfig},a=!1;if(e.source._codec==="aac"&&!s.description){let c=tr(yt.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=fr[c.samplingFrequencyIndex],u=an[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=No({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),a=!0}let o={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ht.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;pp(t),w(t),w(t.config);let i={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,t,n),a=t.data;if(s.info.requiresAnnexBTransformation){let c=[...Di(a)].map(l=>a.subarray(l.offset,l.offset+l.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=Ko(c,4)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=this.createSampleForTrack(s,a,t.timestamp,t.duration,t.type);await this.registerSample(s,o)}finally{i()}}async addEncodedAudioPacket(e,t,n){let i=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,t,n),a=t.data;if(s.info.requiresAdtsStripping){let u=tr(yt.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");let d=u.crcCheck===null?Nn:er;a=a.subarray(d)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(s.info.requiresPcmTransformation){let d=Ht(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(c=a.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let h=o-s.info.expectedNextPcmPacketTimestamp;if(h<.01)o=s.info.expectedNextPcmPacketTimestamp;else{let f=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,h);o=s.info.expectedNextPcmPacketTimestamp+f}}s.info.expectedNextPcmPacketTimestamp=o+c}let l=this.createSampleForTrack(s,a,o,c,t.type);await this.registerSample(s,l)}finally{i()}}async padWithSilence(e,t,n){let i=$e(n,e.timescale);if(n=i/e.timescale,i>0){let{sampleSize:s,silentValue:a}=Ht(e.info.decoderConfig.codec),o=i*e.info.numberOfChannels,c=new Uint8Array(s*o).fill(a),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,n,"key");await this.registerSample(e,l)}return n}async addSubtitleCue(e,t,n){let i=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,t.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(t),await this.processWebVTTCues(s,t.timestamp))}finally{i()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let l of e.cueQueue)w(l.timestamp<=t),w(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);let i=[...n].sort((l,u)=>l-u),s=i[0],a=i[1]??s;if(t<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let l=m0();this.auxBoxWriter.writeBox(l);let u=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let u=e.cueQueue[l];if(u.timestamp>=a)break;xd.lastIndex=0;let d=xd.test(u.text),h=u.timestamp+u.duration,f=e.cueToSourceId.get(u);if(f===void 0&&a<h&&(f=e.nextSourceId++,e.cueToSourceId.set(u,f)),u.notes){let m=g0(u.notes);this.auxBoxWriter.writeBox(m)}let p=p0(u.text,d?s:null,u.identifier??null,u.settings??null,f??null);this.auxBoxWriter.writeBox(p),h===a&&e.cueQueue.splice(l--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,a-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,i,s){return{timestamp:n,decodeTimestamp:n,duration:i,data:t,size:t.byteLength,type:s,timescaleUnitsToNextSample:$e(i,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let i=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let a=e.timestampProcessingQueue[s],o=$e(a.duration,e.timescale);i+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:i,sampleDelta:1});else{let s=Ne(e.timeToSampleTable);s.sampleCount+=i}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(i=>i.timestamp).sort((i,s)=>i-s);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let i=0;i<e.timestampProcessingQueue.length;i++){let s=e.timestampProcessingQueue[i];s.decodeTimestamp=n[i];let a=$e(s.timestamp-s.decodeTimestamp,e.timescale),o=$e(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){w(e.lastSample);let c=$e(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(w(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=Ne(e.timeToSampleTable);if(w(u),u.sampleCount===1){u.sampleDelta=l;let h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===l&&(h.sampleCount++,e.timeToSampleTable.pop(),u=h)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let d=Ne(e.compositionTimeOffsetTable);w(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=$e(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,w(e.lastSample),w(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){w(t.type==="key");let i=$e(t.timestamp,e.timescale,!1),s=Math.round(i-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){let i=e.track.metadata.maximumPacketCount;if(w(i!==void 0),e.samples.length>i)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${i}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let i=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(a=>{if(e===a)return t.type==="key";let o=a.sampleQueue[0];return o?o.type==="key":a.closed});i>=this.minimumFragmentDuration&&s&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=i>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),w(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(w(!this.isFragmented),w(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((n,i)=>n+$e(i.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Ne(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)w(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(w(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<n&&(t=s,n=s.sampleQueue[0].timestamp)}if(!t)break;let i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!this.isCmaf){w(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let f=this.initBoxWriter??this.boxWriter;w(f),this.format._options.onMoov&&f.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let p=ss(this);if(f.writeBox(p),this.format._options.onMoov){let{data:m,start:g}=f.writer.stopTrackingWrites();this.format._options.onMoov(m,g)}if(this.isCmaf){w(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Xn(this.writer);let m=this.boxWriter.measureBox(_d()),g=this.boxWriter.measureBox(Cd(this,0));this.segmentHeaderSize=m+g,this.writer.seek(this.segmentHeaderSize)}}w(this.writer),w(this.boxWriter);let n=this.trackDatas.filter(f=>f.currentChunk),i=Ed(t,n),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(i),o=a+$t,c=1/0;for(let f of n){f.currentChunk.offset=o,f.currentChunk.moofOffset=s;for(let p of f.currentChunk.samples)o+=p.size;c=Math.min(c,f.currentChunk.startTimestamp)}let l=o-a,u=l>=2**32;if(u)for(let f of n)f.currentChunk.offset+=Rr-$t;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=Ed(t,n);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,p,c)}w(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=Ta(u);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(a+(u?Rr:$t));for(let f of n)for(let p of f.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){let{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,p)}for(let f of n)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(w(this.writer),w(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let n=ss(this),s=this.boxWriter.measureBox(n)+this.computeSampleTableSizeUpperBound()+4096;w(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ta(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){w(this.fastStart==="reserve");let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;w(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let t=this.trackDatas.filter(i=>i.type===e);if(t.length===0)continue;if(!t.some(i=>i.track.metadata.disposition?.default!==!1)){let i=t[0];i.track.metadata.disposition={...i.track.metadata.disposition,default:!0}}}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let t of this.trackDatas){await this.finalizeCurrentChunk(t),w(t.startTimestampOffset!==null);for(let n=0;n<t.samples.length;n++){let i=t.samples[n];i.timestamp-=t.startTimestampOffset,i.decodeTimestamp-=t.startTimestampOffset}}if(w(this.writer),w(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Ta(!1);let t;for(let i=0;i<2;i++){let s=ss(this),a=this.boxWriter.measureBox(s);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(let c of this.finalizedChunks){c.offset=o;for(let{data:l}of c.samples)w(l),o+=l.byteLength,t+=l.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let n=ss(this);if(this.boxWriter.writeBox(n),this.format._options.onMoov){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(i,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(let i of this.finalizedChunks)for(let s of i.samples)w(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(i,s)}}else if(this.isFragmented)if(this.isCmaf){let t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(_d()),this.boxWriter.writeBox(Cd(this,t))}else{let t=this.writer.getPos(),n=f0(this.trackDatas);this.boxWriter.writeBox(n);let i=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{w(this.mdat);let t=this.boxWriter.offsets.get(this.mdat);w(t!==void 0);let n=this.writer.getPos()-t;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}let i=ss(this);if(this.fastStart==="reserve"){w(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(d0(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}};var sl=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){w(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(n,i)=>n[i*e]:e===1&&t===4?this.channelMixer=(n,i,s)=>n[i*e]*+(s<2):e===1&&t===6?this.channelMixer=(n,i,s)=>n[i*e]*+(s===2):e===2&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return .5*(n[s]+n[s+1])}:e===2&&t===4?this.channelMixer=(n,i,s)=>n[i*e+s]*+(s<2):e===2&&t===6?this.channelMixer=(n,i,s)=>n[i*e+s]*+(s<2):e===4&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return .25*(n[s]+n[s+1]+n[s+2]+n[s+3])}:e===4&&t===2?this.channelMixer=(n,i,s)=>{let a=i*e;return .5*(n[a+s]+n[a+s+2])}:e===4&&t===6?this.channelMixer=(n,i,s)=>{let a=i*e;return s<2?n[a+s]:s===2||s===3?0:n[a+s-2]}:e===6&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return Math.SQRT1_2*(n[s]+n[s+1])+n[s+2]+.5*(n[s+4]+n[s+5])}:e===6&&t===2?this.channelMixer=(n,i,s)=>{let a=i*e;return n[a+s]+Math.SQRT1_2*(n[a+2]+n[a+s+4])}:e===6&&t===4?this.channelMixer=(n,i,s)=>{let a=i*e;return s<2?n[a+s]+Math.SQRT1_2*n[a+2]:n[a+s+2]}:this.channelMixer=(n,i,s)=>s<e?n[i*e+s]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let n=new Float32Array(t);n.set(this.tempSourceBuffer),this.tempSourceBuffer=n}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),w(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:"f32"}),i=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(i,{planeIndex:0,format:"f32"});let s=e.timestamp-this.startTime,a=s+e.duration,o=Math.floor(s*this.targetSampleRate),c=Math.ceil(a*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let u=l-this.bufferStartFrame;w(u<this.bufferSizeInFrames);let f=(l/this.targetSampleRate-s)*this.sourceSampleRate,p=Math.floor(f),m=Math.ceil(f),g=f-p;for(let y=0;y<this.targetNumberOfChannels;y++){let b=0,k=0;p>=0&&p<e.numberOfFrames&&(b=this.channelMixer(i,p,y)),m>=0&&m<e.numberOfFrames&&(k=this.channelMixer(i,m,y));let T=b+g*(k-b),S=u*this.targetNumberOfChannels+y;this.outputBuffer[S]+=T}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;w(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new mr({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}};var cs=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Zn=class extends cs{constructor(e){if(super(),this._connectedTrack=null,!gt.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${gt.join(", ")}.`);this._codec=e}},Fd=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Aa=class extends Zn{constructor(e){super(e)}add(e,t){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Fd(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},Rd=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new rn,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.closed=!1,this.lastMuxerPromise=Promise.resolve()}async add(e,t,n){let i=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let s=this.encodingConfig,a=s.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.crop!==void 0||s.transform?.force===!0||o&&a!=="passThrough"){let d=s.transform?.width,h=s.transform?.height,f=s.transform?.fit??"fill";o&&a!=="passThrough"&&(w(this.outputWidth),w(this.outputHeight),w(a!=="deny"),d=this.outputWidth,h=this.outputHeight,f=a);let p=await e.transform({width:d,height:h,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,fit:f,alpha:s.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),t&&e.close(),e=p,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let u=s.transform?.frameRate;if(u!==void 0){let d=e.timestamp+e.duration,h=xu(e.timestamp,u);if(this.frameRateLastSample!==null)if(h<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(h,n);e===i&&(e=e.clone(),t=!0),e.setTimestamp(h),e.setDuration(1/u),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=h,this.frameRateLastEndTimestamp=d}await this.processAndEncode(e,n)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig,i;if(n.transform?.process){let s=n.transform.process(e);if(s instanceof Promise&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]),i=s.map(a=>a instanceof rr?a:typeof VideoFrame<"u"&&a instanceof VideoFrame?new rr(a):new rr(a,{timestamp:e.timestamp,duration:e.duration}))}else i=[e];try{for(let s of i){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(s),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed)break;let a=this.encodingConfig.keyFrameInterval??2,o=Math.floor(s.timestamp/a),c={...s.encodeOptions,...t},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:a===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(s),this.customEncoder){this.customEncoderQueueSize++;let u=s.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).then(()=>this.customEncoderQueueSize--).catch(h=>this.error??=h).finally(()=>{u.close()});this.customEncoderQueueSize>=4&&await d}else{w(this.encoder);let u=s.toVideoFrame(),d=_e(this.preciseTimings,u.timestamp,f=>f.microsecondTimestamp),h=d!==-1?this.preciseTimings[d]:null;if(h&&h.microsecondTimestamp===u.timestamp?(h.timestamp!==s.timestamp&&(h.timestampIsValid=!1),h.duration!==s.duration&&(h.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:s.timestamp,duration:s.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(u,l),u.close();else if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(u,l),u.close();else{let p=u.displayWidth,m=u.displayHeight;this.splitter||(this.splitter=new al(p,m));let{colorFrame:g,alphaFrame:y}=await this.splitter.update(u);this.alphaFrameQueue.push(y),this.encoder.encode(g,l),g.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let s of i)s!==e&&s.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;w(this.frameRateLastSample);let i=Math.round((e-this.frameRateLastTimestamp)*n);for(let s=1;s<i;s++){let a=this.frameRateLastSample.clone();a.setTimestamp(this.frameRateLastTimestamp+s/n),a.setDuration(1/n),await this.processAndEncode(a,t),a.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=dd({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=Qc.find(i=>i.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(i,s)=>{if(!(i instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(s!==void 0&&(!s||typeof s!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Fd(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,s),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,s).catch(a=>{this.error??=a})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(t.alpha="discard",this.encodingConfig.alpha==="keep"&&(t.latencyMode="quality"),(t.width%2===1||t.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let a=[],o=[],c=0,l=0,u=(h,f,p)=>{let m={};if(f){let T=new Uint8Array(f.byteLength);f.copyTo(T),m.alpha=T}let g=Oe.fromEncodedChunk(h,m),y=_e(this.preciseTimings,h.timestamp,T=>T.microsecondTimestamp),b=y!==-1?this.preciseTimings[y]:null,k=null;this.emittedEncoderPackets===0&&g.type==="delta"&&p?.decoderConfig&&(k=dn(this.encodingConfig.codec,p.decoderConfig,g.data)),(b&&b.microsecondTimestamp===h.timestamp||k!==null)&&(g=g.clone({timestamp:b?.timestampIsValid?b.timestamp:void 0,duration:b?.durationIsValid?b.duration:void 0,type:k??void 0})),Fd(this.source._connectedTrack,g),this.encodingConfig.onEncodedPacket?.(g,p),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,g,p).catch(T=>{this.error??=T}),this.emittedEncoderPackets++},d=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(h,f)=>{if(!this.alphaEncoder){u(h,null,f);return}let p=this.alphaFrameQueue.shift();w(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:h.type==="key"}),l++,p.close(),a.push({chunk:h,meta:f})):l===0?u(h,null,f):(o.push(c+l),a.push({chunk:h,meta:f}))},error:h=>{h.stack=d,this.error??=h}}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){let h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(f,p)=>{l--;let m=a.shift();for(w(m!==void 0),u(m.chunk,f,m.meta),c++;o.length>0&&o[0]===c;){o.shift();let g=a.shift();w(g!==void 0),u(g.chunk,null,g.meta)}},error:f=>{f.stack=h,this.error??=f}}),this.alphaEncoder.configure(t)}}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){let t=this.encodingConfig.transform.frameRate,n=xu(this.frameRateLastEndTimestamp,t);await this.padFrameRate(n)}this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},x0=!1,al=class r{constructor(e,t){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let n=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!r.forceCpu&&n&&!x0)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);let i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(i){this.gl=null,this.canvas=null,x0=!0,we._warn("Falling back to CPU for color/alpha splitting.",i)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){w(this.gl),w(this.canvas),(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.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);let t=this.runColorProgram(e),n=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:n}}createVertexShader(){return w(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
1893
|
+
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){w(this.gl);let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){w(this.gl),w(this.program);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){w(this.gl);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}updateGpu(e,t){w(this.gl),w(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let n=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),n}updateCpu(e,t){if(!this.worker){let s=new Blob([`(${GT.toString()})()`],{type:"application/javascript"}),a=URL.createObjectURL(s);this.worker=new Worker(a),URL.revokeObjectURL(a),this.worker.addEventListener("message",o=>{let c=o.data,l=this.pendingRequests.get(c.id);l&&(this.pendingRequests.delete(c.id),"error"in c?l.reject(new Error(c.error)):l.resolve(c.frame))}),this.worker.addEventListener("error",o=>{let c=new Error(o.message||"Color/alpha merge worker error.");for(let l of this.pendingRequests.values())l.reject(c);this.pendingRequests.clear()})}let n=this.nextRequestId++,i=nt();return this.pendingRequests.set(n,i),this.worker.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),i.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=new Error("Color/alpha merger closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};el.forceCpu=!0;var GT=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{let{id:l,color:u,alpha:d}=c.data;t=t.then(async()=>{try{let h=await n(u,d);self.postMessage({id:l,frame:h},{transfer:[h]})}catch(h){self.postMessage({id:l,error:h.message})}finally{u.close(),d.close()}})});let n=async(c,l)=>{let u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let h=u.includes("P10"),f=u.includes("P12"),p=d.includes("P10"),m=d.includes("P12");if(p!==h||m!==f)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);let g=c.codedWidth,y=c.codedHeight;if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await i(c,l,g,y,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await s(c,l,g,y,u);if(u==="NV12")return await a(c,l,g,y);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},i=async(c,l,u,d,h)=>{let f=u*d,p=new Uint8Array(f*4);await c.copyTo(p);let m=await o(l,u,d,1);for(let b=0,k=3;b<f;b++,k+=4)p[k]=m[b];let y={format:h==="RGBX"||h==="RGBA"?"RGBA":"BGRA",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},s=async(c,l,u,d,h)=>{let f=h.includes("P10"),p=h.includes("P12"),m=f||p?2:1,g,y;h.startsWith("I420")?(g=Math.ceil(u/2),y=Math.ceil(d/2)):h.startsWith("I422")?(g=Math.ceil(u/2),y=d):(g=u,y=d);let b=u*d,k=g*y,T=b*m,x=k*m,v=b*m,M=T+2*x+v,C=new Uint8Array(M);await c.copyTo(C);let _=await o(l,u,d,m),F=T+2*x;C.set(_,F);let O={format:h.slice(0,4)+"A"+h.slice(4),codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,O)},a=async(c,l,u,d)=>{let h=u*d,f=Math.ceil(u/2),p=Math.ceil(d/2),m=f*p,g=c.allocationSize();(!e||e.byteLength!==g)&&(e=new Uint8Array(g)),await c.copyTo(e);let y=new Uint8Array(h+2*m+h);y.set(e.subarray(0,h),0);let b=h,k=h+m,T=h;for(let M=0;M<m;M++)y[b+M]=e[T+M*2],y[k+M]=e[T+M*2+1];let x=await o(l,u,d,1);y.set(x,h+2*m);let v={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,v)},o=async(c,l,u,d)=>{let h=c.allocationSize();(!r||r.byteLength!==h)&&(r=new Uint8Array(h)),await c.copyTo(r);let f=c.format;if(f==="RGBA"||f==="BGRA"||f==="RGBX"||f==="BGRX"){let p=f==="RGBA"||f==="RGBX"?0:2,m=l*u;for(let g=0;g<m;g++)r[g]=r[g*4+p];return r.subarray(0,m)}else return r.subarray(0,l*u*d)}},jT=r=>{if(!r||typeof r!="object")throw new TypeError("decoderOptions must be an object.");if(r.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r.optimizeForLatency!==void 0&&typeof r.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")},Aa=class extends Jc{constructor(e,t={}){if(!(e instanceof Xn))throw new TypeError("videoTrack must be an InputVideoTrack.");jT(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=await this._track.getCodec(),i=await this._track.getRotation(),s=await this._track.getDecoderConfig(),a=await this._track.getTimeResolution();return w(n&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new kd(e,t,n,s,i,a)}_createPacketSink(){return new bn(this._track)}async getSample(e,t={}){Zi(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}};var Ji=class r{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Xn}isAudioTrack(){return this instanceof es}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Xe(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Xe(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Xe(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Xe(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Xe(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),n=(t?.timestamp??0)+(t?.duration??0);return Bn(n,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new bn(this),i=1/0,s=-1/0,a=0,o=0;for await(let c of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=s)break;i=Math.min(i,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-i)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(s-i)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(kn({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(kn({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(kn({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(kn({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(kn({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Sd(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Sd(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Sd(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},Xe=(r,e,t)=>{if(r instanceof Promise)throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},Sd=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{let t=i=>{if(typeof i!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return i},n=r(e);return n instanceof Promise?n.then(t):t(n)}:void 0},Xn=class extends Ji{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Xe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Xe(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Xe(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Xe(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Xe(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Xe(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Ln({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Ln({num:Xe(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Xe(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Xe(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Xe(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let i=Xe(e,"displayWidth","getDisplayWidth");if(i!==null)return i}let n=Xe(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Xe(n,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let i=Xe(e,"displayHeight","getDisplayHeight");if(i!==null)return i}let n=Xe(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Xe(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return w(t!==null),Zc.some(i=>i.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return we._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let t=await this.getCodec();if(t===null)return null;let n=await this.getDecoderConfig();return w(n),hn(t,n,e.data)}},es=class extends Ji{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Xe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Xe(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Xe(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return w(t!==null),yd.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return we._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}};var xd=r=>-(r??-1/0),ts=r=>-r,rs=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{let t=i=>{if(typeof i!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return i},n=r.filter(e);return n instanceof Promise?n.then(t):t(n)}:void 0,sortBy:r.sortBy?e=>{let t=i=>{if(typeof i!="number"&&(!Array.isArray(i)||!i.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return i},n=r.sortBy(e);return n instanceof Promise?n.then(t):t(n)}:void 0}},kn=(r,e)=>({filter:r?.filter||e?.filter?t=>{let n=r?.filter?.(t)??!0,i=s=>s===!1?!1:e?.filter?.(t)??!0;return n instanceof Promise?n.then(i):i(n)}:void 0,sortBy:r?.sortBy||e?.sortBy?t=>{let n=r?.sortBy?.(t)??[],i=e?.sortBy?.(t)??[],s=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([a,o])=>s(a,o)):s(n,i)}:void 0}),tl=async(r,e)=>{let t=r;if(e?.filter){let a=r.map(c=>e.filter(c));if(a.some(c=>c instanceof Promise)){let c=await Promise.all(a);t=r.filter((l,u)=>c[u])}else t=r.filter((c,l)=>a[l])}if(!e?.sortBy)return t;let n=t.map(a=>e.sortBy(a)),s=n.some(a=>a instanceof Promise)?await Promise.all(n):n;return t.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{let c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){let h=c[d]??0,f=l[d]??0;if(h!==f)return h-f}return 0}).map(a=>a.track)};Ii();var KT=1,Dg=2,Gr=class r extends Vt{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof Mt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof wt||e.source instanceof Gn))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof wt&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof r))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&$g(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof wt?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){w(this._rootSource instanceof Ot);let t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=KT){let n=this._sourceCache.find(a=>a.cacheGroup===t&&ud(a.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let i=this._sourceCachePromises.find(a=>a.cacheGroup===t&&ud(a.request,e));if(i)return i.promise.then(a=>a.sourceRef.source.ref());let s=(async()=>{let a=await this._getSourceUncached(e);if(On(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){let d=Fi(this._sourceCache,f=>f.cacheGroup===t&&f.sourceRef.source._refCount===1?f.age:1/0);w(d!==-1);let h=this._sourceCache[d];this._sourceCache.splice(d,1),h.sourceRef.free(),op(this._sourceRefs,h.sourceRef)}this._sourceRefs.push(a);let l=this._sourceCachePromises.findIndex(d=>d.request===e);return w(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(a=>{let o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new yn(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new va})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),w(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof va)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(i=>i!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(i=>i.getFirstTimestamp()));return Math.min(...n)}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(s=>s!==null);if(n.length===0)return 0;let i=await Promise.all(n.map(s=>s.computeDuration(t)));return Math.max(...i)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(a=>a!==null),s=(await Promise.all(n.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=rs(e);let n=(await this._getTrackBackings()).map(i=>this._wrapBackingAsTrack(i));return tl(n,e)}async getVideoTracks(e){e&&=rs(e);let n=(await this.getTracks()).filter(i=>i.isVideoTrack());return tl(n,e)}async getAudioTracks(e){e&&=rs(e);let n=(await this.getTracks()).filter(i=>i.isAudioTrack());return tl(n,e)}async getPrimaryVideoTrack(e){e&&=rs(e);let t=kn(e,{sortBy:async i=>[ts((await i.getDisposition()).default),ts(await i.hasPairableAudioTrack()),ts(!await i.hasOnlyKeyPackets()),xd(await i.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=rs(e);let t=await this.getPrimaryVideoTrack(),n=kn(e,{sortBy:async s=>[ts(!t||s.canBePairedWith(t)),ts((await s.getDisposition()).default),xd(await s.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let i=e.getType()==="video"?new Xn(this,e):new es(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},va=class extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}},ut=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var yn=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new ut;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let s=new Uint8Array(0);return new yt(s,Ae(s),0,e,e)}let n=e+t,i=this.source._read(e,n,cd,ld);return i instanceof Promise?i.then(s=>s?new yt(s.bytes,s.view,s.offset,e,n):null):i?new yt(i.bytes,i.view,i.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new ut;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Ze(this.fileSizeNonStrict-e,t,n));{let i=this.requestSlice(e,n),s=a=>a||(w(this.fileSizeNonStrict!==null),this.requestSlice(e,Ze(this.fileSizeNonStrict-e,t,n)));return i instanceof Promise?i.then(s):s(i)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let e=1024;return(async()=>{let t=[],n=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(n,0,e);if(a instanceof Promise&&(a=await a),!a||a.length===0)break;let o=ie(a,a.length);t.push(o),n+=a.length}let i=new Uint8Array(n),s=0;for(let a of t)i.set(a,s),s+=a.length;return new yt(i,Ae(i),0,0,n)})()}},yt=class r{constructor(e,t,n,i,s){this.bytes=e,this.view=t,this.offset=n,this.start=i,this.end=s,this.bufferPos=i-n}static tempFromBytes(e){return new r(e,Ae(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new r(this.bytes,this.view,this.offset,e,e+t)}},Ft=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},ie=(r,e)=>{Ft(r,e);let t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},ce=r=>(Ft(r,1),r.view.getUint8(r.bufferPos++)),Xi=(r,e)=>{Ft(r,2);let t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},Ke=r=>{Ft(r,2);let e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},Zt=r=>{Ft(r,3);let e=Ns(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},ra=r=>{Ft(r,2);let e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Hr=(r,e)=>{Ft(r,4);let t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},K=r=>{Ft(r,4);let e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},zn=r=>{Ft(r,4);let e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Or=r=>{Ft(r,4);let e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},$T=r=>{Ft(r,4);let e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},ju=(r,e)=>{let t,n;return e?(t=Hr(r,!0),n=Hr(r,!0)):(n=Hr(r,!1),t=Hr(r,!1)),n*4294967296+t},Pt=r=>{let e=K(r),t=K(r);return e*4294967296+t},ig=r=>{let e=Or(r),t=K(r);return e*4294967296+t},gg=r=>{let e=zn(r);return $T(r)*4294967296+e},ag=r=>{Ft(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},dc=r=>{Ft(r,8);let e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},We=(r,e)=>{Ft(r,e);let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},Rc=(r,e,t)=>ot.decode(ie(r,e)).split(`
|
|
1894
|
+
`).map(s=>s.trim()).filter(s=>s.length>0&&!t?.ignore?.(s));var Qn;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Qn||(Qn={}));var is;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(is||(is={}));var aa=128,mt=10,ss=["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"],lg=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=ie(r,aa-3),r.filePos=t;let n=ns(r,30);n&&(e.title??=n);let i=ns(r,30);i&&(e.artist??=i);let s=ns(r,30);s&&(e.album??=s);let a=ns(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(String(o)));let c=ie(r,30),l;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(e.trackNumber??=d),r.skip(-30),l=ns(r,28),r.skip(2)}else r.skip(-30),l=ns(r,30);l&&(e.comment??=l);let u=ce(r);u<ss.length&&(e.genre??=ss[u])},ns=(r,e)=>{let t=ie(r,e),n=Dn(t.indexOf(0),t.length),i=t.subarray(0,n),s="";for(let a=0;a<i.length;a++)s+=String.fromCharCode(i[a]);return s.trimEnd()},It=r=>{let e=r.filePos,t=We(r,3),n=ce(r),i=ce(r),s=ce(r),a=K(r);if(t!=="ID3"||n===255||i===255||(a&2155905152)!==0)return r.filePos=e,null;let o=jo(a);return s&Qn.Footer&&(o+=mt),{majorVersion:n,revision:i,flags:s,size:o}},pn=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){we._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=e.flags&Qn.Footer?e.size-mt:e.size,i=ie(r,n),s=new Td(e,i);if(e.flags&Qn.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Qn.ExtendedHeader){let a=s.readU32();e.majorVersion===3?s.pos+=a:s.pos+=a-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){let a=s.readId3V2Frame();if(!a)break;let o=s.pos,c=s.pos+a.size,l=!1,u=!1,d=!1;if(e.majorVersion===3?(l=!!(a.flags&64),u=!!(a.flags&128)):e.majorVersion===4&&(l=!!(a.flags&4),u=!!(a.flags&8),d=!!(a.flags&2)||!!(e.flags&Qn.Unsynchronisation)),l){we._warn(`Skipping encrypted ID3v2 frame ${a.id}`),s.pos=c;continue}if(u){we._warn(`Skipping compressed ID3v2 frame ${a.id}`),s.pos=c;continue}if(d&&s.ununsynchronizeRegion(s.pos,c),t.raw??={},a.id==="TXXX"){let h=t.raw.TXXX??={},f=s.readId3V2TextEncoding(),p=s.readId3V2Text(f,c),m=s.readId3V2Text(f,c);h[p]??=m}else a.id[0]==="T"?t.raw[a.id]??=s.readId3V2EncodingAndText(c):t.raw[a.id]??=s.readBytes(a.size);switch(s.pos=o,a.id){case"TIT2":case"TT2":t.title??=s.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":t.description??=s.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":t.artist??=s.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":t.album??=s.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":t.albumArtist??=s.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{let f=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(t.tracksTotal??=m)}break;case"TPOS":case"TPA":{let f=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(t.discsTotal??=m)}break;case"TCON":case"TCO":{let h=s.readId3V2EncodingAndText(c),f=/^\((\d+)\)/.exec(h);if(f){let p=Number.parseInt(f[1]);if(ss[p]!==void 0){t.genre??=ss[p];break}}if(f=/^\d+$/.exec(h),f){let p=Number.parseInt(f[0]);if(ss[p]!==void 0){t.genre??=ss[p];break}}t.genre??=h}break;case"TDRC":case"TDAT":{let h=s.readId3V2EncodingAndText(c),f=new Date(h);Number.isNaN(f.getTime())||(t.date??=f)}break;case"TYER":case"TYE":{let h=s.readId3V2EncodingAndText(c),f=Number.parseInt(h,10);Number.isInteger(f)&&(t.date??=new Date(String(f)))}break;case"USLT":case"ULT":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,c),t.lyrics??=s.readId3V2Text(h,c)}break;case"COMM":case"COM":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,c),t.comment??=s.readId3V2Text(h,c)}break;case"APIC":case"PIC":{let h=s.readId3V2TextEncoding(),f;if(e.majorVersion===2){let y=s.readAscii(3);f=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else f=s.readId3V2Text(h,c);let p=s.readU8(),m=s.readId3V2Text(h,c).trimEnd(),g=c-s.pos;if(g>=0){let y=s.readBytes(g);t.images||(t.images=[]),t.images.push({data:y,mimeType:f,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=a.size;break}s.pos=c}},Td=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let a=e;a<t;a++){let o=this.bytes[a];n.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}let i=this.bytes.subarray(0,e),s=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+n.length+s.length),this.bytes.set(i,0),this.bytes.set(n,i.length),this.bytes.set(s,i.length+n.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),n=this.header.majorVersion===4?jo(t):t,i=this.readU16(),s=this.pos,a=o=>{let c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;let l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!a(n)){let o=this.header.majorVersion===4?t:jo(t);a(o)&&(n=o)}return this.pos=s,{id:e,size:n,flags:i}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,i=this.readBytes(t-this.pos);switch(e){case is.ISO_8859_1:{let s="";for(let a=0;a<i.length;a++){let o=i[a];if(o===0){this.pos=n+a+1;break}s+=String.fromCharCode(o)}return s}case is.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){let s=new TextDecoder("utf-16le"),a=Dn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else if(i[0]===254&&i[1]===255){let s=new TextDecoder("utf-16be"),a=Dn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else{let s=Dn(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),ot.decode(i.subarray(0,s))}case is.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),a=Dn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(0,a))}case is.UTF_8:{let s=Dn(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),ot.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var rl=class{constructor(e){this.mutex=new vt,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let i=this.trackTimestampInfo.get(e);if(i){if(n&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),i.maxTimestampBeforeLastKeyPacket!==null&&t<i.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);i.maxTimestamp=Math.max(i.maxTimestamp,t)}else{if(!n)throw new Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,i)}}};var Ad=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var w0=r=>{let e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),n=Math.floor(r%(60*1e3)/1e3),i=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+i.toString().padStart(3,"0")};var Yn=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let s of e.children)s&&this.writeBox(s);let n=this.writer.getPos(),i=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);w(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},Pe=new Uint8Array(8),Gt=new DataView(Pe.buffer),Je=r=>[(r%256+256)%256],xe=r=>(Gt.setUint16(0,r,!1),[Pe[0],Pe[1]]),Pd=r=>(Gt.setInt16(0,r,!1),[Pe[0],Pe[1]]),S0=r=>(Gt.setUint32(0,r,!1),[Pe[1],Pe[2],Pe[3]]),G=r=>(Gt.setUint32(0,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),Kr=r=>(Gt.setInt32(0,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),yr=r=>(Gt.setUint32(0,Math.floor(r/2**32),!1),Gt.setUint32(4,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3],Pe[4],Pe[5],Pe[6],Pe[7]]),XT=r=>(Gt.setInt32(0,Math.floor(r/2**32),!1),Gt.setUint32(4,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3],Pe[4],Pe[5],Pe[6],Pe[7]]),x0=r=>(Gt.setInt16(0,2**8*r,!1),[Pe[0],Pe[1]]),sr=r=>(Gt.setInt32(0,2**16*r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),vd=r=>(Gt.setInt32(0,2**30*r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),_d=(r,e)=>{let t=[],n=r;do{let i=n&127;n>>=7,t.length>0&&(i|=128),t.push(i),e!==void 0&&e--}while(n>0||e);return t.reverse()},Ge=(r,e=!1)=>{let t=Array(r.length).fill(null).map((n,i)=>r.charCodeAt(i));return e&&t.push(0),t},T0=r=>{let e=r*(Math.PI/180),t=Math.round(Math.cos(e)),n=Math.round(Math.sin(e));return[t,n,0,-n,t,0,0,0,1]},A0=T0(0),v0=r=>[sr(r[0]),sr(r[1]),vd(r[2]),sr(r[3]),sr(r[4]),vd(r[5]),sr(r[6]),sr(r[7]),vd(r[8])],be=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),Ve=(r,e,t,n,i)=>be(r,[Je(e),S0(t),n??[]],i),_0=r=>r.isQuickTime?be("ftyp",[Ge("qt "),G(512),Ge("qt ")]):r.fragmented?r.cmaf?be("ftyp",[Ge("iso5"),G(512),Ge("iso5"),Ge("iso6"),Ge("mp41"),Ge("cmfc"),Ge("dash")]):be("ftyp",[Ge("iso5"),G(512),Ge("iso5"),Ge("iso6"),Ge("mp41")]):be("ftyp",[Ge("isom"),G(512),Ge("isom"),r.holdsAvc?Ge("avc1"):[],Ge("mp41")]),Ed=()=>be("styp",[Ge("iso5"),G(0),Ge("iso5"),Ge("iso6"),Ge("mp41"),Ge("cmfc"),Ge("dash")]),Id=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),Ve("sidx",1,0,[G(1),G(qt),yr($e(r.minWrittenTimestamp,qt)),yr(0),xe(0),xe(1),G(e&2147483647),G($e(t,qt)),G(0)])},_a=r=>({type:"mdat",largeSize:r}),C0=r=>({type:"free",size:r}),as=r=>be("moov",void 0,[QT(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>YT(e,r.creationTime)),r.isFragmented?OA(r.trackDatas):null,GA(r)]),QT=(r,e)=>{let t=Math.max(0,...e.map(a=>$e(nl(a),qt)+$e(a.startTimestampOffset??0,qt))),n=Math.max(0,...e.map(a=>a.track.id))+1,i=!_r(r)||!_r(t),s=i?yr:G;return Ve("mvhd",+i,0,[s(r),s(r),G(qt),s(t),sr(1),x0(1),Array(10).fill(0),v0(A0),Array(24).fill(0),G(n)])},nl=r=>{if(r.samples.length===0)return 0;let e=1/0,t=-1/0;for(let n=0;n<r.samples.length;n++){let i=r.samples[n];i.timestamp<e&&(e=i.timestamp),i.timestamp+i.duration>t&&(t=i.timestamp+i.duration)}return e===1/0?0:t-e},YT=(r,e)=>{let t=O0(r),n=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return be("trak",void 0,[ZT(r,e),n?JT(r,r.startTimestampOffset):null,eA(r,e),t.name!==void 0?be("udta",void 0,[be("name",[..._t.encode(t.name)])]):null])},ZT=(r,e)=>{let t=$e(nl(r),qt)+$e(r.startTimestampOffset??0,qt),n=!_r(e)||!_r(t),i=n?yr:G,s;if(r.type==="video"){let o=r.track.metadata.rotation;s=T0(o??0)}else s=A0;let a=2;return r.track.metadata.disposition?.default!==!1&&(a|=1),Ve("tkhd",+n,a,[i(e),i(e),G(r.track.id),G(0),i(t),Array(8).fill(0),xe(0),xe(r.track.id),x0(r.type==="audio"?1:0),xe(0),v0(s),sr(r.type==="video"?r.info.width:0),sr(r.type==="video"?r.info.height:0)])},JT=(r,e)=>{let t=$e(e,qt),n=$e(nl(r),qt),i=!_r(t)||!_r(n),s=i?yr:G,a=i?XT:Kr;return be("edts",void 0,[Ve("elst",i?1:0,0,[G(2),s(t),a(-1),sr(1),s(n),a(0),sr(1)])])},eA=(r,e)=>be("mdia",void 0,[tA(r,e),Md(!0,rA[r.type],nA[r.type]),iA(r)]),tA=(r,e)=>{let t=$e(nl(r),r.timescale),n=!_r(e)||!_r(t),i=n?yr:G;return Ve("mdhd",+n,0,[i(e),i(e),G(r.timescale),i(t),xe(D0(r.track.metadata.languageCode??je)),xe(0)])},rA={video:"vide",audio:"soun",subtitle:"text"},nA={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Md=(r,e,t,n="\0\0\0\0")=>Ve("hdlr",0,0,[r?Ge("mhlr"):G(0),Ge(e),Ge(n),G(0),G(0),Ge(t,!0)]),iA=r=>be("minf",void 0,[cA[r.type](),lA(),hA(r)]),sA=()=>Ve("vmhd",0,1,[xe(0),xe(0),xe(0),xe(0)]),aA=()=>Ve("smhd",0,0,[xe(0),xe(0)]),oA=()=>Ve("nmhd",0,0),cA={video:sA,audio:aA,subtitle:oA},lA=()=>be("dinf",void 0,[uA()]),uA=()=>Ve("dref",0,0,[G(1)],[dA()]),dA=()=>Ve("url ",0,1),hA=r=>{let e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return be("stbl",void 0,[fA(r),EA(r),e?BA(r):null,e?DA(r):null,MA(r),FA(r),RA(r),IA(r)])},fA=r=>{let e;if(r.type==="video")e=mA(XA(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){let t=B0(r.track.source._codec,r.muxer.isQuickTime);w(t),e=kA(t,r)}else r.type==="subtitle"&&(e=CA(ZA[r.track.source._codec],r));return w(e),Ve("stsd",0,0,[G(1)],[e])},mA=(r,e)=>be(r,[Array(6).fill(0),xe(1),xe(0),xe(0),Array(12).fill(0),xe(e.info.width),xe(e.info.height),G(4718592),G(4718592),G(0),xe(1),Array(32).fill(0),xe(24),Pd(65535)],[QA[e.track.source._codec](e),pA(e),ip(e.info.decoderConfig.colorSpace)?gA(e):null]),pA=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:be("pasp",[G(r.info.pixelAspectRatio.num),G(r.info.pixelAspectRatio.den)]),gA=r=>be("colr",[Ge(r.muxer.isQuickTime?"nclc":"nclx"),xe(Cr[r.info.decoderConfig.colorSpace.primaries]),xe(Pr[r.info.decoderConfig.colorSpace.transfer]),xe(Er[r.info.decoderConfig.colorSpace.matrix]),r.muxer.isQuickTime?[]:Je((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),yA=r=>r.info.decoderConfig&&be("avcC",[...Ye(r.info.decoderConfig.description)]),wA=r=>r.info.decoderConfig&&be("hvcC",[...Ye(r.info.decoderConfig.description)]),b0=r=>{if(!r.info.decoderConfig)return null;let e=r.info.decoderConfig,t=e.codec.split("."),n=Number(t[1]),i=Number(t[2]),s=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(s<<4)+(a<<1)+o,l=t[5]?Number(t[5]):e.colorSpace?.primaries?Cr[e.colorSpace.primaries]:2,u=t[6]?Number(t[6]):e.colorSpace?.transfer?Pr[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):e.colorSpace?.matrix?Er[e.colorSpace.matrix]:2;return Ve("vpcC",1,0,[Je(n),Je(i),Je(c),Je(l),Je(u),Je(d),xe(0)])},bA=r=>be("av1C",Ap(r.info.decoderConfig.codec)),kA=(r,e)=>{let t=0,n,i=16,s=ht.includes(e.track.source._codec);if(s){let a=e.track.source._codec,{sampleSize:o}=Wt(a);i=8*o,i>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)n=[Array(6).fill(0),xe(1),xe(t),xe(0),G(0),xe(e.info.numberOfChannels),xe(i),xe(0),xe(0),xe(e.info.sampleRate<2**16?e.info.sampleRate:0),xe(0)];else{let a=s?0:-2;n=[Array(6).fill(0),xe(1),xe(t),xe(0),G(0),xe(e.info.numberOfChannels),xe(Math.min(i,16)),Pd(a),xe(0),xe(e.info.sampleRate<2**16?e.info.sampleRate:0),xe(0),s?[G(1),G(i/8),G(e.info.numberOfChannels*i/8)]:[G(0),G(0),G(0)],G(2)]}return be(r,n,[YA(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Cd=r=>{let e;switch(r.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let t=[...Je(e),...Je(21),...S0(0),...G(0),...G(0)];if(r.info.decoderConfig.description){let n=Ye(r.info.decoderConfig.description);t=[...t,...Je(5),..._d(n.byteLength),...n]}return t=[...xe(1),...Je(0),...Je(4),..._d(t.length),...t,...Je(6),...Je(1),...Je(2)],t=[...Je(3),..._d(t.length),...t],Ve("esds",0,0,t)},Sn=r=>be("wave",void 0,[SA(r),xA(r),be("\0\0\0\0")]),SA=r=>be("frma",[Ge(B0(r.track.source._codec,r.muxer.isQuickTime))]),xA=r=>{let{littleEndian:e}=Wt(r.track.source._codec);return be("enda",[xe(+e)])},TA=r=>{let e=r.info.numberOfChannels,t=3840,n=r.info.sampleRate,i=0,s=0,a=new Uint8Array(0),o=r.info.decoderConfig?.description;if(o){w(o.byteLength>=18);let c=Ye(o),l=Yo(c);e=l.outputChannelCount,t=l.preSkip,n=l.inputSampleRate,i=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return be("dOps",[Je(0),Je(e),xe(t),G(n),Pd(i),Je(s),...a])},AA=r=>{let e=r.info.decoderConfig?.description;w(e);let t=Ye(e);return Ve("dfLa",0,0,[...t.subarray(4)])},pr=r=>{let{littleEndian:e,sampleSize:t}=Wt(r.track.source._codec),n=+e;return Ve("pcmC",0,0,[Je(n),Je(8*t)])},vA=r=>{let e=Zo(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let t=new Uint8Array(3),n=new Ie(t);return n.writeBits(2,e.fscod),n.writeBits(5,e.bsid),n.writeBits(3,e.bsmod),n.writeBits(3,e.acmod),n.writeBits(1,e.lfeon),n.writeBits(5,e.bitRateCode),n.writeBits(5,0),be("dac3",[...t])},_A=r=>{let e=Jo(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(let a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;let n=Math.ceil(t/8),i=new Uint8Array(n),s=new Ie(i);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(let a of e.substreams)s.writeBits(2,a.fscod),s.writeBits(5,a.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,a.bsmod),s.writeBits(3,a.acmod),s.writeBits(1,a.lfeon),s.writeBits(3,0),s.writeBits(4,a.numDepSub),a.numDepSub>0?s.writeBits(9,a.chanLoc):s.writeBits(1,0);return be("dec3",[...i])},CA=(r,e)=>be(r,[Array(6).fill(0),xe(1)],[JA[e.track.source._codec](e)]),PA=r=>be("vttC",[..._t.encode(r.info.config.description)]);var EA=r=>Ve("stts",0,0,[G(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[G(e.sampleCount),G(e.sampleDelta)])]),IA=r=>{if(r.samples.every(t=>t.type==="key"))return null;let e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return Ve("stss",0,0,[G(e.length),e.map(([t])=>G(t+1))])},MA=r=>Ve("stsc",0,0,[G(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[G(e.firstChunk),G(e.samplesPerChunk),G(1)])]),FA=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){let{sampleSize:e}=Wt(r.track.source._codec);return Ve("stsz",0,0,[G(e*r.info.numberOfChannels),G(r.samples.reduce((t,n)=>t+$e(n.duration,r.timescale),0))])}return Ve("stsz",0,0,[G(0),G(r.samples.length),r.samples.map(e=>G(e.size))])},RA=r=>r.finalizedChunks.length>0&&ze(r.finalizedChunks).offset>=2**32?Ve("co64",0,0,[G(r.finalizedChunks.length),r.finalizedChunks.map(e=>yr(e.offset))]):Ve("stco",0,0,[G(r.finalizedChunks.length),r.finalizedChunks.map(e=>G(e.offset))]),BA=r=>Ve("ctts",1,0,[G(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[G(e.sampleCount),Kr(e.sampleCompositionTimeOffset)])]),DA=r=>{let e=1/0,t=-1/0,n=1/0,i=-1/0;w(r.compositionTimeOffsetTable.length>0),w(r.samples.length>0);for(let a=0;a<r.compositionTimeOffsetTable.length;a++){let o=r.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<r.samples.length;a++){let o=r.samples[a];n=Math.min(n,$e(o.timestamp,r.timescale)),i=Math.max(i,$e(o.timestamp+o.duration,r.timescale))}let s=Math.max(-e,0);return i>=2**31?null:Ve("cslg",0,0,[Kr(s),Kr(e),Kr(t),Kr(n),Kr(i)])},OA=r=>be("mvex",void 0,r.map(LA)),LA=r=>Ve("trex",0,0,[G(r.track.id),G(1),G(0),G(0),G(0)]),Fd=(r,e)=>be("moof",void 0,[UA(r),...e.map(NA)]),UA=r=>Ve("mfhd",0,0,[G(r)]),P0=r=>{let e=0,t=0,n=0,i=0,s=r.type==="delta";return t|=+s,s?e|=1:e|=2,e<<24|t<<16|n<<8|i},NA=r=>be("traf",void 0,[zA(r),VA(r),HA(r)]),zA=r=>{w(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let t=r.currentChunk.samples[1]??r.currentChunk.samples[0],n={duration:t.timescaleUnitsToNextSample,size:t.size,flags:P0(t)};return Ve("tfhd",0,e,[G(r.track.id),G(n.duration),G(n.size),G(n.flags)])},VA=r=>(w(r.currentChunk),Ve("tfdt",1,0,[yr($e(r.currentChunk.startTimestamp,r.timescale))])),HA=r=>{w(r.currentChunk);let e=r.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(m=>m.size),n=r.currentChunk.samples.map(P0),i=r.currentChunk.samples.map(m=>$e(m.timestamp-m.decodeTimestamp,r.timescale)),s=new Set(e),a=new Set(t),o=new Set(n),c=new Set(i),l=o.size===2&&n[0]!==n[1],u=s.size>1,d=a.size>1,h=!l&&o.size>1,f=c.size>1||[...c].some(m=>m!==0),p=0;return p|=1,p|=4*+l,p|=256*+u,p|=512*+d,p|=1024*+h,p|=2048*+f,Ve("trun",1,p,[G(r.currentChunk.samples.length),G(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?G(n[0]):[],r.currentChunk.samples.map((m,g)=>[u?G(e[g]):[],d?G(t[g]):[],h?G(n[g]):[],f?Kr(i[g]):[]])])},E0=r=>be("mfra",void 0,[...r.map(WA),qA()]),WA=(r,e)=>Ve("tfra",1,0,[G(r.track.id),G(63),G(r.finalizedChunks.length),r.finalizedChunks.map(n=>[yr($e(n.samples[0].timestamp,r.timescale)),yr(n.moofOffset),G(e+1),G(1),G(1)])]),qA=()=>Ve("mfro",0,0,[G(0)]),I0=()=>be("vtte"),M0=(r,e,t,n,i)=>be("vttc",void 0,[i!==null?be("vsid",[Kr(i)]):null,t!==null?be("iden",[..._t.encode(t)]):null,e!==null?be("ctim",[..._t.encode(w0(e))]):null,n!==null?be("sttg",[..._t.encode(n)]):null,be("payl",[..._t.encode(r)])]),F0=r=>be("vtta",[..._t.encode(r)]),GA=r=>{let e=[],t=r.format._options.metadataFormat??"auto",n=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){let i=KA(n);i&&e.push(i)}else if(t==="mdta"){let i=$A(n);i&&e.push(i)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&jA(e,r.output._metadataTags);return e.length===0?null:be("udta",void 0,e)},jA=(r,e)=>{for(let{key:t,value:n}of qs(e))switch(t){case"title":r.push(gr("\xA9nam",n));break;case"description":r.push(gr("\xA9des",n));break;case"artist":r.push(gr("\xA9ART",n));break;case"album":r.push(gr("\xA9alb",n));break;case"albumArtist":r.push(gr("albr",n));break;case"genre":r.push(gr("\xA9gen",n));break;case"date":r.push(gr("\xA9day",n.toISOString().slice(0,10)));break;case"comment":r.push(gr("\xA9cmt",n));break;case"lyrics":r.push(gr("\xA9lyr",n));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Ct(t)}if(e.raw)for(let t in e.raw){let n=e.raw[t];n==null||t.length!==4||r.some(i=>i.type===t)||(typeof n=="string"?r.push(gr(t,n)):n instanceof Uint8Array&&r.push(be(t,Array.from(n))))}},gr=(r,e)=>{let t=_t.encode(e);return be(r,[xe(t.length),xe(D0("und")),Array.from(t)])},k0={"image/jpeg":13,"image/png":14,"image/bmp":27},R0=(r,e)=>{let t=[];for(let{key:n,value:i}of qs(r))switch(n){case"title":t.push({key:e?"title":"\xA9nam",value:ir(i)});break;case"description":t.push({key:e?"description":"\xA9des",value:ir(i)});break;case"artist":t.push({key:e?"artist":"\xA9ART",value:ir(i)});break;case"album":t.push({key:e?"album":"\xA9alb",value:ir(i)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:ir(i)});break;case"comment":t.push({key:e?"comment":"\xA9cmt",value:ir(i)});break;case"genre":t.push({key:e?"genre":"\xA9gen",value:ir(i)});break;case"lyrics":t.push({key:e?"lyrics":"\xA9lyr",value:ir(i)});break;case"date":t.push({key:e?"date":"\xA9day",value:ir(i.toISOString().slice(0,10))});break;case"images":for(let s of i)s.kind==="coverFront"&&t.push({key:"covr",value:be("data",[G(k0[s.mimeType]??0),G(0),Array.from(s.data)])});break;case"trackNumber":if(e){let s=r.tracksTotal!==void 0?`${i}/${r.tracksTotal}`:i.toString();t.push({key:"track",value:ir(s)})}else t.push({key:"trkn",value:be("data",[G(0),G(0),xe(0),xe(i),xe(r.tracksTotal??0),xe(0)])});break;case"discNumber":e||t.push({key:"disc",value:be("data",[G(0),G(0),xe(0),xe(i),xe(r.discsTotal??0),xe(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Ct(n)}if(r.raw)for(let n in r.raw){let i=r.raw[n];i==null||!e&&n.length!==4||t.some(s=>s.key===n)||(typeof i=="string"?t.push({key:n,value:ir(i)}):i instanceof Uint8Array?t.push({key:n,value:be("data",[G(0),G(0),Array.from(i)])}):i instanceof $t&&t.push({key:n,value:be("data",[G(k0[i.mimeType]??0),G(0),Array.from(i.data)])}))}return t},KA=r=>{let e=R0(r,!1);return e.length===0?null:Ve("meta",0,0,void 0,[Md(!1,"mdir","","appl"),be("ilst",void 0,e.map(t=>be(t.key,void 0,[t.value])))])},$A=r=>{let e=R0(r,!0);return e.length===0?null:be("meta",void 0,[Md(!1,"mdta",""),Ve("keys",0,0,[G(e.length)],e.map(t=>be("mdta",[..._t.encode(t.key)]))),be("ilst",void 0,e.map((t,n)=>{let i=String.fromCharCode(...G(n+1));return be(i,void 0,[t.value])}))])},ir=r=>be("data",[G(1),G(0),..._t.encode(r)]),XA=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},QA={avc:yA,hevc:wA,vp8:b0,vp9:b0,av1:bA},B0=(r,e)=>{switch(r){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(r){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(r){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},YA=(r,e)=>{switch(r){case"aac":return Cd;case"mp3":return Cd;case"opus":return TA;case"vorbis":return Cd;case"flac":return AA;case"ac3":return vA;case"eac3":return _A}if(e)switch(r){case"pcm-s24":return Sn;case"pcm-s24be":return Sn;case"pcm-s32":return Sn;case"pcm-s32be":return Sn;case"pcm-f32":return Sn;case"pcm-f32be":return Sn;case"pcm-f64":return Sn;case"pcm-f64be":return Sn}else switch(r){case"pcm-s16":return pr;case"pcm-s16be":return pr;case"pcm-s24":return pr;case"pcm-s24be":return pr;case"pcm-s32":return pr;case"pcm-s32be":return pr;case"pcm-f32":return pr;case"pcm-f32be":return pr;case"pcm-f64":return pr;case"pcm-f64be":return pr}return null},ZA={webvtt:"wvtt"},JA={webvtt:PA},D0=r=>{w(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};var Zn=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){w(!this.started),this.target._start(),this.started=!0}write(e){w(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return w(this.started&&!this.finalized),this.target._flush()}async finalize(){w(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,i=this.trackedWrites.byteLength;for(;i<n;)i*=2;if(i!==this.trackedWrites.byteLength){let s=new Uint8Array(i);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}};var Rt=class extends Vt{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new il(this,e)}},Rd=2**16,Bd=2**32,ar=class extends Rt{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Rd,{maxByteLength:Bd})}catch{this._buffer=new ArrayBuffer(Rd),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Rd);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Bd)throw new Error(`ArrayBuffer exceeded maximum size of ${Bd} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let n=new ArrayBuffer(t),i=new Uint8Array(n);i.set(this._bytes,0),this._buffer=n,this._bytes=i}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},ev=2**24,tv=2,Ca=class extends Rt{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??ev}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){let n=t-this._lastWriteEnd;this._write(new Uint8Array(n),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(w(this._streamWriter),this._sections.length===0)return;let e=[],t=[...this._sections].sort((n,i)=>n.start-i.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let n=1;n<t.length;n++){let i=e[e.length-1],s=t[n];s.start<=i.start+i.size?i.size=Math.max(i.size,s.start+s.data.byteLength-i.start):e.push({start:s.start,size:s.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let i of this._sections)n.start<=i.start&&i.start<n.start+n.size&&n.data.set(i.data,i.start-n.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(n.data,n.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&n.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data,position:n.start}).catch(i=>{this._writeError??=i}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let n=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);n===-1&&(n=this._createChunk(t));let i=this._chunks[n],s=t-i.start,a=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));i.data.set(a,s);let o={start:s,end:s+a.byteLength};if(this._insertSectionIntoChunk(i,o),i.written[0].start===0&&i.written[0].end===this._chunkSize&&(i.shouldFlush=!0),this._chunks.length>tv){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let n=0,i=e.written.length-1,s=-1;for(;n<=i;){let a=Math.floor(n+(i-n+1)/2);e.written[a].start<=t.start?(n=a+1,s=a):i=a-1}for(e.written.splice(s+1,0,t),(s===-1||e.written[s].end<t.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((i,s)=>i.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){w(this._streamWriter);for(let t=0;t<this._chunks.length;t++){let n=this._chunks[t];if(!(!n.shouldFlush&&!e)){for(let i of n.written){let s=n.start+i.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data.subarray(i.start,i.end),position:s}).catch(a=>{this._writeError??=a}),this._lastFlushEnd=n.start+i.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;w(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}};var il=class extends Rt{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},Jn=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}};var qt=57600,rv=2082844800,O0=r=>{let e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},$e=(r,e,t=!0)=>{let n=r*e;return t?Math.round(n):n},sl=class extends rl{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new ar,this.auxWriter=new Zn(this.auxTarget,!1),this.auxBoxWriter=new Yn(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=nt(),this.creationTime=Math.floor(Date.now()/1e3)+rv,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof cs,this.isCmaf=t instanceof os,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof os?1/0:1)}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":n instanceof ar),this.boxWriter=new Yn(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof ar?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let n=await this.output._getInitTarget(),i=new Zn(n,!0);i.start(),this.initWriter=i,this.initBoxWriter=new Yn(i)}let t=this.output._tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(w(n),this.format._options.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(_0({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:i,start:s}=n.writer.stopTrackingWrites();this.format._options.onFtyp(i,s)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output._tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(w(this.writer),w(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=_a(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return rc({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,n){let i=this.trackDatas.find(h=>h.track===e);if(i)return i;Ep(n),w(n),w(n.decoderConfig);let s={...n.decoderConfig};w(s.codedWidth!==void 0),w(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){let h=Ui(t.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=Up(h),a=!0}else if(e.source._codec==="hevc"&&!s.description){let h=Ni(t.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=Vp(h),a=!0}let o=mp(1/(e.metadata.frameRate??qt),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:Ln({num:c*s.codedHeight,den:l*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:u,decoderConfig:s,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((h,f)=>h.track.id-f.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let i=this.trackDatas.find(c=>c.track===e);if(i)return i;Ip(n),w(n),w(n.decoderConfig);let s={...n.decoderConfig},a=!1;if(e.source._codec==="aac"&&!s.description){let c=rr(yt.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=fr[c.samplingFrequencyIndex],u=on[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=Vo({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),a=!0}let o={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ht.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Mp(t),w(t),w(t.config);let i={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,t,n),a=t.data;if(s.info.requiresAnnexBTransformation){let c=[...Oi(a)].map(l=>a.subarray(l.offset,l.offset+l.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=$o(c,4)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=this.createSampleForTrack(s,a,t.timestamp,t.duration,t.type);await this.registerSample(s,o)}finally{i()}}async addEncodedAudioPacket(e,t,n){let i=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,t,n),a=t.data;if(s.info.requiresAdtsStripping){let u=rr(yt.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");let d=u.crcCheck===null?Hn:tr;a=a.subarray(d)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(s.info.requiresPcmTransformation){let d=Wt(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(c=a.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let h=o-s.info.expectedNextPcmPacketTimestamp;if(h<.01)o=s.info.expectedNextPcmPacketTimestamp;else{let f=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,h);o=s.info.expectedNextPcmPacketTimestamp+f}}s.info.expectedNextPcmPacketTimestamp=o+c}let l=this.createSampleForTrack(s,a,o,c,t.type);await this.registerSample(s,l)}finally{i()}}async padWithSilence(e,t,n){let i=$e(n,e.timescale);if(n=i/e.timescale,i>0){let{sampleSize:s,silentValue:a}=Wt(e.info.decoderConfig.codec),o=i*e.info.numberOfChannels,c=new Uint8Array(s*o).fill(a),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,n,"key");await this.registerSample(e,l)}return n}async addSubtitleCue(e,t,n){let i=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,t.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(t),await this.processWebVTTCues(s,t.timestamp))}finally{i()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let l of e.cueQueue)w(l.timestamp<=t),w(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);let i=[...n].sort((l,u)=>l-u),s=i[0],a=i[1]??s;if(t<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let l=I0();this.auxBoxWriter.writeBox(l);let u=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let u=e.cueQueue[l];if(u.timestamp>=a)break;Ad.lastIndex=0;let d=Ad.test(u.text),h=u.timestamp+u.duration,f=e.cueToSourceId.get(u);if(f===void 0&&a<h&&(f=e.nextSourceId++,e.cueToSourceId.set(u,f)),u.notes){let m=F0(u.notes);this.auxBoxWriter.writeBox(m)}let p=M0(u.text,d?s:null,u.identifier??null,u.settings??null,f??null);this.auxBoxWriter.writeBox(p),h===a&&e.cueQueue.splice(l--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,a-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,i,s){return{timestamp:n,decodeTimestamp:n,duration:i,data:t,size:t.byteLength,type:s,timescaleUnitsToNextSample:$e(i,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let i=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let a=e.timestampProcessingQueue[s],o=$e(a.duration,e.timescale);i+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:i,sampleDelta:1});else{let s=ze(e.timeToSampleTable);s.sampleCount+=i}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(i=>i.timestamp).sort((i,s)=>i-s);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let i=0;i<e.timestampProcessingQueue.length;i++){let s=e.timestampProcessingQueue[i];s.decodeTimestamp=n[i];let a=$e(s.timestamp-s.decodeTimestamp,e.timescale),o=$e(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){w(e.lastSample);let c=$e(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(w(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=ze(e.timeToSampleTable);if(w(u),u.sampleCount===1){u.sampleDelta=l;let h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===l&&(h.sampleCount++,e.timeToSampleTable.pop(),u=h)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let d=ze(e.compositionTimeOffsetTable);w(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=$e(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,w(e.lastSample),w(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){w(t.type==="key");let i=$e(t.timestamp,e.timescale,!1),s=Math.round(i-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){let i=e.track.metadata.maximumPacketCount;if(w(i!==void 0),e.samples.length>i)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${i}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let i=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(a=>{if(e===a)return t.type==="key";let o=a.sampleQueue[0];return o?o.type==="key":a.closed});i>=this.minimumFragmentDuration&&s&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=i>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),w(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(w(!this.isFragmented),w(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((n,i)=>n+$e(i.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||ze(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)w(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(w(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<n&&(t=s,n=s.sampleQueue[0].timestamp)}if(!t)break;let i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!this.isCmaf){w(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let f=this.initBoxWriter??this.boxWriter;w(f),this.format._options.onMoov&&f.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let p=as(this);if(f.writeBox(p),this.format._options.onMoov){let{data:m,start:g}=f.writer.stopTrackingWrites();this.format._options.onMoov(m,g)}if(this.isCmaf){w(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Yn(this.writer);let m=this.boxWriter.measureBox(Ed()),g=this.boxWriter.measureBox(Id(this,0));this.segmentHeaderSize=m+g,this.writer.seek(this.segmentHeaderSize)}}w(this.writer),w(this.boxWriter);let n=this.trackDatas.filter(f=>f.currentChunk),i=Fd(t,n),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(i),o=a+Xt,c=1/0;for(let f of n){f.currentChunk.offset=o,f.currentChunk.moofOffset=s;for(let p of f.currentChunk.samples)o+=p.size;c=Math.min(c,f.currentChunk.startTimestamp)}let l=o-a,u=l>=2**32;if(u)for(let f of n)f.currentChunk.offset+=Br-Xt;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=Fd(t,n);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,p,c)}w(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=_a(u);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(a+(u?Br:Xt));for(let f of n)for(let p of f.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){let{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,p)}for(let f of n)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(w(this.writer),w(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let n=as(this),s=this.boxWriter.measureBox(n)+this.computeSampleTableSizeUpperBound()+4096;w(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=_a(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){w(this.fastStart==="reserve");let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;w(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let t=this.trackDatas.filter(i=>i.type===e);if(t.length===0)continue;if(!t.some(i=>i.track.metadata.disposition?.default!==!1)){let i=t[0];i.track.metadata.disposition={...i.track.metadata.disposition,default:!0}}}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let t of this.trackDatas){await this.finalizeCurrentChunk(t),w(t.startTimestampOffset!==null);for(let n=0;n<t.samples.length;n++){let i=t.samples[n];i.timestamp-=t.startTimestampOffset,i.decodeTimestamp-=t.startTimestampOffset}}if(w(this.writer),w(this.boxWriter),this.fastStart==="in-memory"){this.mdat=_a(!1);let t;for(let i=0;i<2;i++){let s=as(this),a=this.boxWriter.measureBox(s);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(let c of this.finalizedChunks){c.offset=o;for(let{data:l}of c.samples)w(l),o+=l.byteLength,t+=l.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let n=as(this);if(this.boxWriter.writeBox(n),this.format._options.onMoov){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(i,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(let i of this.finalizedChunks)for(let s of i.samples)w(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(i,s)}}else if(this.isFragmented)if(this.isCmaf){let t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(Ed()),this.boxWriter.writeBox(Id(this,t))}else{let t=this.writer.getPos(),n=E0(this.trackDatas);this.boxWriter.writeBox(n);let i=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{w(this.mdat);let t=this.boxWriter.offsets.get(this.mdat);w(t!==void 0);let n=this.writer.getPos()-t;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}let i=as(this);if(this.fastStart==="reserve"){w(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(C0(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}};var al=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){w(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(n,i)=>n[i*e]:e===1&&t===4?this.channelMixer=(n,i,s)=>n[i*e]*+(s<2):e===1&&t===6?this.channelMixer=(n,i,s)=>n[i*e]*+(s===2):e===2&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return .5*(n[s]+n[s+1])}:e===2&&t===4?this.channelMixer=(n,i,s)=>n[i*e+s]*+(s<2):e===2&&t===6?this.channelMixer=(n,i,s)=>n[i*e+s]*+(s<2):e===4&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return .25*(n[s]+n[s+1]+n[s+2]+n[s+3])}:e===4&&t===2?this.channelMixer=(n,i,s)=>{let a=i*e;return .5*(n[a+s]+n[a+s+2])}:e===4&&t===6?this.channelMixer=(n,i,s)=>{let a=i*e;return s<2?n[a+s]:s===2||s===3?0:n[a+s-2]}:e===6&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return Math.SQRT1_2*(n[s]+n[s+1])+n[s+2]+.5*(n[s+4]+n[s+5])}:e===6&&t===2?this.channelMixer=(n,i,s)=>{let a=i*e;return n[a+s]+Math.SQRT1_2*(n[a+2]+n[a+s+4])}:e===6&&t===4?this.channelMixer=(n,i,s)=>{let a=i*e;return s<2?n[a+s]+Math.SQRT1_2*n[a+2]:n[a+s+2]}:this.channelMixer=(n,i,s)=>s<e?n[i*e+s]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let n=new Float32Array(t);n.set(this.tempSourceBuffer),this.tempSourceBuffer=n}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),w(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:"f32"}),i=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(i,{planeIndex:0,format:"f32"});let s=e.timestamp-this.startTime,a=s+e.duration,o=Math.floor(s*this.targetSampleRate),c=Math.ceil(a*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let u=l-this.bufferStartFrame;w(u<this.bufferSizeInFrames);let f=(l/this.targetSampleRate-s)*this.sourceSampleRate,p=Math.floor(f),m=Math.ceil(f),g=f-p;for(let y=0;y<this.targetNumberOfChannels;y++){let b=0,k=0;p>=0&&p<e.numberOfFrames&&(b=this.channelMixer(i,p,y)),m>=0&&m<e.numberOfFrames&&(k=this.channelMixer(i,m,y));let T=b+g*(k-b),x=u*this.targetNumberOfChannels+y;this.outputBuffer[x]+=T}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;w(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new mr({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}};var ls=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},ei=class extends ls{constructor(e){if(super(),this._connectedTrack=null,!gt.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${gt.join(", ")}.`);this._codec=e}},Dd=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Pa=class extends ei{constructor(e){super(e)}add(e,t){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Dd(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},Od=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new nn,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.closed=!1,this.lastMuxerPromise=Promise.resolve()}async add(e,t,n){let i=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let s=this.encodingConfig,a=s.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.crop!==void 0||s.transform?.force===!0||o&&a!=="passThrough"){let d=s.transform?.width,h=s.transform?.height,f=s.transform?.fit??"fill";o&&a!=="passThrough"&&(w(this.outputWidth),w(this.outputHeight),w(a!=="deny"),d=this.outputWidth,h=this.outputHeight,f=a);let p=await e.transform({width:d,height:h,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,fit:f,alpha:s.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),t&&e.close(),e=p,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let u=s.transform?.frameRate;if(u!==void 0){let d=e.timestamp+e.duration,h=Au(e.timestamp,u);if(this.frameRateLastSample!==null)if(h<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(h,n);e===i&&(e=e.clone(),t=!0),e.setTimestamp(h),e.setDuration(1/u),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=h,this.frameRateLastEndTimestamp=d}await this.processAndEncode(e,n)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig,i;if(n.transform?.process){let s=n.transform.process(e);if(s instanceof Promise&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]),i=s.map(a=>a instanceof nr?a:typeof VideoFrame<"u"&&a instanceof VideoFrame?new nr(a):new nr(a,{timestamp:e.timestamp,duration:e.duration}))}else i=[e];try{for(let s of i){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(s),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed)break;let a=this.encodingConfig.keyFrameInterval??2,o=Math.floor(s.timestamp/a),c={...s.encodeOptions,...t},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:a===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(s),this.customEncoder){this.customEncoderQueueSize++;let u=s.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).then(()=>this.customEncoderQueueSize--).catch(h=>this.error??=h).finally(()=>{u.close()});this.customEncoderQueueSize>=4&&await d}else{w(this.encoder);let u=s.toVideoFrame(),d=_e(this.preciseTimings,u.timestamp,f=>f.microsecondTimestamp),h=d!==-1?this.preciseTimings[d]:null;if(h&&h.microsecondTimestamp===u.timestamp?(h.timestamp!==s.timestamp&&(h.timestampIsValid=!1),h.duration!==s.duration&&(h.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:s.timestamp,duration:s.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(u,l),u.close();else if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(u,l),u.close();else{let p=u.displayWidth,m=u.displayHeight;this.splitter||(this.splitter=new ol(p,m));let{colorFrame:g,alphaFrame:y}=await this.splitter.update(u);this.alphaFrameQueue.push(y),this.encoder.encode(g,l),g.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let s of i)s!==e&&s.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;w(this.frameRateLastSample);let i=Math.round((e-this.frameRateLastTimestamp)*n);for(let s=1;s<i;s++){let a=this.frameRateLastSample.clone();a.setTimestamp(this.frameRateLastTimestamp+s/n),a.setDuration(1/n),await this.processAndEncode(a,t),a.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=md({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=Yc.find(i=>i.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(i,s)=>{if(!(i instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(s!==void 0&&(!s||typeof s!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Dd(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,s),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,s).catch(a=>{this.error??=a})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(t.alpha="discard",this.encodingConfig.alpha==="keep"&&(t.latencyMode="quality"),(t.width%2===1||t.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let a=[],o=[],c=0,l=0,u=(h,f,p)=>{let m={};if(f){let T=new Uint8Array(f.byteLength);f.copyTo(T),m.alpha=T}let g=Oe.fromEncodedChunk(h,m),y=_e(this.preciseTimings,h.timestamp,T=>T.microsecondTimestamp),b=y!==-1?this.preciseTimings[y]:null,k=null;this.emittedEncoderPackets===0&&g.type==="delta"&&p?.decoderConfig&&(k=hn(this.encodingConfig.codec,p.decoderConfig,g.data)),(b&&b.microsecondTimestamp===h.timestamp||k!==null)&&(g=g.clone({timestamp:b?.timestampIsValid?b.timestamp:void 0,duration:b?.durationIsValid?b.duration:void 0,type:k??void 0})),Dd(this.source._connectedTrack,g),this.encodingConfig.onEncodedPacket?.(g,p),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,g,p).catch(T=>{this.error??=T}),this.emittedEncoderPackets++},d=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(h,f)=>{if(!this.alphaEncoder){u(h,null,f);return}let p=this.alphaFrameQueue.shift();w(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:h.type==="key"}),l++,p.close(),a.push({chunk:h,meta:f})):l===0?u(h,null,f):(o.push(c+l),a.push({chunk:h,meta:f}))},error:h=>{h.stack=d,this.error??=h}}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){let h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(f,p)=>{l--;let m=a.shift();for(w(m!==void 0),u(m.chunk,f,m.meta),c++;o.length>0&&o[0]===c;){o.shift();let g=a.shift();w(g!==void 0),u(g.chunk,null,g.meta)}},error:f=>{f.stack=h,this.error??=f}}),this.alphaEncoder.configure(t)}}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){let t=this.encodingConfig.transform.frameRate,n=Au(this.frameRateLastEndTimestamp,t);await this.padFrameRate(n)}this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},L0=!1,ol=class r{constructor(e,t){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let n=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!r.forceCpu&&n&&!L0)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);let i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(i){this.gl=null,this.canvas=null,L0=!0,we._warn("Falling back to CPU for color/alpha splitting.",i)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){w(this.gl),w(this.canvas),(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.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);let t=this.runColorProgram(e),n=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:n}}createVertexShader(){return w(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2041
1895
|
in vec2 a_position;
|
|
2042
1896
|
in vec2 a_texCoord;
|
|
2043
1897
|
out vec2 v_texCoord;
|
|
@@ -2101,8 +1955,8 @@ ${n}`),this.frame=e,this.failures=t}};async function hu(r){let{scale:e=1,frame:t
|
|
|
2101
1955
|
|
|
2102
1956
|
fragColor = result;
|
|
2103
1957
|
}
|
|
2104
|
-
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){w(this.gl);let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||we._error("Shader compile error:",this.gl.getShaderInfoLog(n)),n}createVAO(){w(this.gl),w(this.colorProgram);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){w(this.gl);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}runColorProgram(e){return w(this.gl),w(this.canvas),this.gl.useProgram(this.colorProgram),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),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}runAlphaProgram(e){w(this.gl),w(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),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);let{width:t,height:n}=this.canvas,i=Math.ceil(t/2)*Math.ceil(n/2),s=t*n+i*2,a=Math.ceil(s/(t*4)),o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,s),w(o[t*n]===128),w(o[o.length-1]===128);let c={format:"I420",codedWidth:t,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}updateCpu(e){if(!this.worker){let i=new Blob([`(${Fv.toString()})()`],{type:"application/javascript"}),s=URL.createObjectURL(i);this.worker=new Worker(s),URL.revokeObjectURL(s),this.worker.addEventListener("message",a=>{let o=a.data,c=this.pendingRequests.get(o.id);c&&(this.pendingRequests.delete(o.id),"error"in o?c.reject(new Error(o.error)):c.resolve({colorFrame:o.colorFrame,alphaFrame:o.alphaFrame}))}),this.worker.addEventListener("error",a=>{let o=new Error(a.message||"Color/alpha splitter worker error.");for(let c of this.pendingRequests.values())c.reject(o);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=nt();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=new Error("Color/alpha splitter closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};al.forceCpu=!0;var Fv=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",s=>{let{id:a,sourceFrame:o}=s.data;e=e.then(async()=>{try{let{colorFrame:c,alphaFrame:l}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});let t=async s=>{let a=s.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=s.codedWidth,c=s.codedHeight,l=s.allocationSize();if((!r||r.byteLength!==l)&&(r=new Uint8Array(l)),await s.copyTo(r),a==="RGBA"||a==="BGRA")return n(r,o,c,a,s);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return i(r,o,c,a,s);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},n=(s,a,o,c,l)=>{let u=a*o,d=Math.ceil(a/2),h=Math.ceil(o/2),f=u+d*h*2,p=new Uint8Array(f);for(let b=0,k=3;b<u;b++,k+=4)p[b]=s[k];p.fill(128,u);let m=new VideoFrame(s,{format:c==="RGBA"?"RGBX":"BGRX",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),g={format:"I420",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[p.buffer]},y=new VideoFrame(p,g);return{colorFrame:m,alphaFrame:y}},i=(s,a,o,c,l)=>{let u=c.includes("P10"),d=c.includes("P12"),h=u||d?2:1,f,p;c.startsWith("I420")?(f=Math.ceil(a/2),p=Math.ceil(o/2)):c.startsWith("I422")?(f=Math.ceil(a/2),p=o):(f=a,p=o);let m=a*o,g=f*p,y=m*h,b=g*h,k=m*h,T=y+b*2,S=c.replace("A",""),_=Math.ceil(a/2),M=Math.ceil(o/2),P=_*M,A=P*h,F=k+2*A,I=new Uint8Array(F),O=T;I.set(s.subarray(O,O+k),0);let Q=k,ge=u?512:d?2048:128;h===1?I.fill(ge,Q):new Uint16Array(I.buffer,Q,2*P).fill(ge);let be=u?"I420P10":d?"I420P12":"I420",J=new VideoFrame(s.subarray(0,T),{format:S,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),Ae={format:be,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[I.buffer]},Re=new VideoFrame(I,Ae);return{colorFrame:J,alphaFrame:Re}}};var _a=class extends Zn{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");Wg(t),super(t.codec),this._encoder=new Rd(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");let i=new rr(this._canvas,{timestamp:e,duration:t});return this._encoder.add(i,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var ls=class extends cs{constructor(e){if(super(),this._connectedTrack=null,!Vt.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Vt.join(", ")}.`);this._codec=e}};var Bd=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new rn,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new sl({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,onSample:async s=>{await this.processAndEncode(s,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&Ng(e.format)!==n.transform.sampleFormat){let i=Vg(e,n.transform.sampleFormat);t&&e.close(),e=i,t=!0}if(n.transform?.process){let i=n.transform.process(e);if(i instanceof Promise&&(i=await i),i===null)return;Array.isArray(i)||(i=[i]);for(let s of i){if(!(s instanceof mr))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(s,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed)return;{let n=Math.round(e.timestamp*e.sampleRate),i=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=i;else{let s=n-this.lastEndSampleIndex;if(s>=64){let a=new mr({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let n=e.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(n)).then(()=>this.customEncoderQueueSize--).catch(s=>this.error??=s).finally(()=>{n.close()});this.customEncoderQueueSize>=4&&await i,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{w(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(i=>this.encoder.addEventListener("dequeue",i,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){w(this.outputSampleSize),w(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:i,sampleRate:s,timestamp:a}=e,o=2048,c=[];for(let h=0;h<i;h+=o){let f=Math.min(o,e.numberOfFrames-h),p=f*n*this.outputSampleSize,m=new ArrayBuffer(p),g=new DataView(m);c.push({frameCount:f,view:g})}let l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let h=0;h<n;h++){e.copyTo(u,{planeIndex:h,format:"f32-planar"});for(let f=0;f<c.length;f++){let{frameCount:p,view:m}=c[f];for(let g=0;g<p;g++)this.writeOutputValue(m,(g*n+h)*this.outputSampleSize,u[f*o+g])}}t&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:s}};for(let h=0;h<c.length;h++){let{frameCount:f,view:p}=c[h],m=p.buffer,g=h*o,y=new Oe(new Uint8Array(m),"key",a+g/s,f/s);this.encodingConfig.onEncodedPacket?.(y,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,y,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,i=Gg({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(i);let s=fd.find(a=>a.supports(this.encodingConfig.codec,i));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(a,o)=>{if(!(a instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,o),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,o).catch(c=>{this.error??=c})},await this.customEncoder.init();else if(ht.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.numberOfChannels} channels, ${i.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let o=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let d=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?d=!0:d=Fi(Ye(l.decoderConfig.description)).objectType===0,d){let h=Number(Ne(i.codec.split(".")));l.decoderConfig.description=No({objectType:h,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}let u=Oe.fromEncodedChunk(c);u=u.clone({timestamp:Fn(u.timestamp,i.sampleRate),duration:c.duration!=null?Fn(u.duration,i.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(u,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,l).catch(d=>{this.error??=d})},error:c=>{c.stack=o,this.error??=c}}),this.encoder.configure(i)}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:i}=Ht(e);switch(this.outputSampleSize=n,n){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,Ze((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,Ze(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{let c=Ze(Math.floor(o*32767),-32768,32767);s.setUint8(a,Zg(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{let c=Ze(Math.floor(o*32767),-32768,32767);s.setUint8(a,Jg(c))}:w(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,Ze((o+1)*32767.5,0,65535),i):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,Ze(Math.round(o*32767),-32768,32767),i):w(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>Ls(s,a,Ze((o+1)*83886075e-1,0,16777215),i):t==="signed"?this.writeOutputValue=(s,a,o)=>$m(s,a,Ze(Math.round(o*8388607),-8388608,8388607),i):w(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,Ze((o+1)*21474836475e-1,0,4294967295),i):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,Ze(Math.round(o*2147483647),-2147483648,2147483647),i):t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat32(a,o,i):w(!1);break;case 8:t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat64(a,o,i):w(!1);break;default:Ct(n),w(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}};var Jn=class extends ls{constructor(e){jg(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Bd(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let t=mr._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let n of t)await this._encoder.add(n,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var Ca=class extends cs{constructor(e){if(super(),this._connectedTrack=null,!on.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${on.join(", ")}.`);this._codec=e}};var us=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>gt.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Vt.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>on.includes(e))}_codecUnsupportedHint(e){return""}},ds=class extends us{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new il(e,this)}},xn=class extends ds{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...gt,...Vo,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...on]}_codecUnsupportedHint(e){return new os().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},as=class extends ds{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...gt,...Vo,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...on]}},os=class extends ds{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...gt,...Vt]}_codecUnsupportedHint(e){return new xn().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}};var Rv=["video","audio","subtitle"],hs=class r{constructor(e,t,n,i,s){this.id=e,this.output=t,this.type=n,this.source=i,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;let t=Tu(this.metadata.group),n=Tu(e.metadata.group);for(let i of t)if(this.type!==e.type&&n.some(o=>i===o)||n.some(o=>i._pairedGroups.has(o)))return!0;return!1}},ol=class extends hs{constructor(e,t,n,i){super(e,t,"video",n,i)}},cl=class extends hs{constructor(e,t,n,i){super(e,t,"audio",n,i)}},ll=class extends hs{constructor(e,t,n,i){super(e,t,"subtitle",n,i)}},fs=class r{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}},Dd=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!Pi(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&rp(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof fs)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof fs))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},ei=class extends Nt{get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new fs,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new At,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof us))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Rt||e.target instanceof Yn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Rt&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Rt)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Rt&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){w(this._target instanceof Yn);let t=this._target.getTarget(e),n=i=>{if(!(i instanceof Rt))throw new TypeError("getTarget must return a Target.");return i};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){w(this._target instanceof Yn);let t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(w(this._initTarget!==null),this._initTarget instanceof Rt)return this._initTarget;let e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Rt)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=i=>(this.state==="canceled"?i._close():this._rememberTarget(i),this._emit("target",{target:i,request:e,isRoot:!0}),this._rootTarget=i,i);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new Qn(t,typeof e=="boolean"?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Zn))throw new TypeError("source must be a VideoSource.");if(Dd(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ol(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof ls))throw new TypeError("source must be an AudioSource.");Dd(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new cl(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Ca))throw new TypeError("source must be a SubtitleSource.");Dd(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ll(this._tracks.length+1,this,e,n))}setMetadataTags(e){if(tp(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let t=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),i=t[e.type].max;if(n===i)throw new Error(i===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${i} ${e.type} track${i===1?"":"s"}.`);let s=t.total.max;if(this._tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){let a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){let e=this.format.getSupportedTrackCounts();for(let n of Rv){let i=this._tracks.reduce((a,o)=>a+(o.type===n?1:0),0),s=e[n].min;if(i<s)throw new Error(s===e[n].max?`${this.format._name} requires exactly ${s} ${n} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${n} track${s===1?"":"s"}.`)}let t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(we._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let n=await this._mutex.acquire();try{await this._muxer.start();let i=this._tracks.map(s=>s.source._start());await Promise.all(i)}finally{n()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return we._warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&we._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let t=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(n=>n._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(we._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{let t=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){let n=await this._rootWriterPromise;n.finalized||(await n.flush(),await n.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}};var S0=Symbol.for("mediabunny loaded");globalThis[S0]&&we._error(`[WARNING]
|
|
2105
|
-
Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[S0]=!0;var Bv=(()=>{let r=[];for(let e=0;;e++){let t=Math.round(64*2**(e/2));if(t>4096)break;r.push(t)}return r})();function ms(r,e){if(e)return 4096;let t=Math.max(1,Math.round(Math.max(r.width,r.height)));return Math.min(t,4096)}function Kr(r,e){let t=Number.isFinite(r)?Math.max(0,r):e;if(t>=e)return e;let n=e/Math.SQRT2;for(let i of Bv){if(i>=n)return e;if(i>=t)return i}return e}function Pa(r){return Kr(0,r)}function ps(r,e){let t=Math.max(e.width,e.height,1),n=r/t;return{width:Math.max(1,Math.round(e.width*n)),height:Math.max(1,Math.round(e.height*n))}}var Dv=512*1024*1024,Ov=2e3,Od=5e3,Lv=3e4,Uv=6e4,zv=3,Nv=2,Vv=16*1024*1024,ul=class{_host;_budget;_policy="interactive";_entries=new Map;_pass=0;_inflight=0;constructor(e,t=Dv){this._host=e,this._budget=t}get policy(){return this._policy}setPolicy(e){this._policy=e}has(e){return(this._entries.get(e)?.levels.length??0)>0}intrinsicSize(e){return this._entries.get(e)?.intrinsic??null}load(e){let t=this._entry(e);return t.levels.length>0?Promise.resolve():(t.loading??=this._host.decode(e,(n,i)=>(this._learn(t,n,i),this._policy==="exact"?Pa(t.cap):t.lastDemand!==void 0?this._interactiveEdge(t,t.lastDemand):Kr(Math.min(Math.max(n.width,n.height),this._host.surfaceEdge()),t.cap))).then(n=>{this._learn(t,n.intrinsic,n.vector),this._add(t,n),this._enforceBudget()}).finally(()=>{t.loading=null,this._pump()}),t.loading)}beginPass(){this._pass++}select(e,t){let n=this._entry(e),i=this._host.now(),s=t!==void 0&&Number.isFinite(t)&&t>0?t:1/0;if(n.levels.length===0)return Number.isFinite(s)&&(n.lastDemand=Math.max(n.lastDemand??0,s)),n.missedPass=this._pass,null;let a=Math.min(s,n.cap);n.passNeed=Math.max(n.passNeed,a),n.passDraws++,n.lastUsed=i;let o;if(this._policy==="exact"){let c=Kr(a,n.cap),l=n.levels.find(u=>u.edge===c);!l&&!n.failed.has(c)&&n.wanted.add(c),o=l??Hv(n.levels,c)}else o=n.levels.find(c=>c.edge>=a)??n.levels[n.levels.length-1],o.edge<2*a&&(n.passAllOver=!1);return o.lastSelected=i,o.selectedPass=this._pass,o}endPass(){let e=this._host.now();for(let t of this._entries.values()){let n=t.levels[t.levels.length-1];if(t.passDraws>0&&n)if(t.lastDemand=t.passNeed,this._policy==="exact"){for(let i of t.wanted)this._request(t,i,!1);t.wanted.clear()}else t.short=n.edge<t.passNeed,t.short?this._request(t,this._interactiveEdge(t,t.passNeed),!0):t.queue=t.queue.filter(i=>i<=n.edge),t.passAllOver&&!T0(n)?(t.overSince??=e,e-t.overSince>=Od&&this._request(t,this._interactiveEdge(t,t.passNeed),!0)):t.overSince=null;else t.short=!1;t.passNeed=0,t.passDraws=0,t.passAllOver=!0,this._ageOut(t,e)}this._enforceBudget(),this._pump()}hasPending(){for(let e of this._entries.values())if(this._blocks(e))return!0;return!1}async warm(){if(this._policy==="interactive"){let t=!1;for(let n=0;n<64;n++){let i=[...this._entries.values()].filter(s=>this._blocks(s)).map(s=>s.loading);if(i.length===0)break;t=!0,await Promise.all(i.map(s=>s.catch(()=>{})))}return t}let e=!1;for(let t of this._entries.values()){for(let n of t.wanted)this._request(t,n,!1);t.wanted.clear()}this._pump();for(let t=0;t<64;t++){let n=[...this._entries.values()].map(i=>i.job??i.loading).filter(i=>i!==null);if(n.length===0)break;e=!0,await Promise.all(n.map(i=>i.catch(()=>{}))),this._pump()}return e}hasUpgrades(){if(this._policy!=="interactive")return!1;for(let e of this._entries.values())if(this._upgrading(e))return!0;return!1}async warmUpgrades(){let e=!1;for(let t=0;t<64&&this._policy==="interactive";t++){this._pump();let n=[...this._entries.values()].filter(a=>this._upgrading(a));if(n.length===0)break;let i=n.flatMap(a=>a.job?[a.job]:[]),s=i.length>0?i:[...this._entries.values()].flatMap(a=>a.job?[a.job]:[]);if(s.length===0)break;await Promise.all(s.map(a=>a.catch(()=>{}))),i.length>0&&(e=!0)}return e}stats(){let e=0,t=0,n=0;for(let i of this._entries.values()){e+=i.levels.length;for(let s of i.levels)t+=gs(s);n+=this._host.sourceBytes(i.src)}return{sources:this._entries.size,levels:e,levelBytes:t,sourceBytes:n,inflight:this._inflight}}levelsOf(e){return this._entries.get(e)?.levels??[]}dispose(){for(let e of this._entries.values()){for(let t of e.levels)this._host.released(e.src,t);e.levels=[],e.queue=[]}this._entries.clear()}_entry(e){let t=this._entries.get(e);return t||(t={src:e,intrinsic:null,vector:!1,cap:1,levels:[],lastDemand:void 0,lastUsed:this._host.now(),passNeed:0,passDraws:0,passAllOver:!0,overSince:null,wanted:new Set,queue:[],job:null,failed:new Set,loading:null,missedPass:-1,short:!1},this._entries.set(e,t)),t}_blocks(e){return this._policy==="exact"?e.job!==null||e.queue.length>0||e.wanted.size>0||e.loading!==null:e.levels.length===0&&e.missedPass===this._pass&&e.loading!==null}_upgrading(e){return e.short&&e.levels.length>0&&(e.job!==null||e.queue.length>0)}_interactiveEdge(e,t){return Kr(Math.min(t*Nv,e.cap),e.cap)}_learn(e,t,n){e.intrinsic={width:t.width,height:t.height},e.vector=n,e.cap=ms(t,n)}_add(e,t){let n=e.levels.findIndex(s=>s.edge===t.edge);n>=0&&(this._host.released(e.src,e.levels[n]),e.levels.splice(n,1));let i={edge:t.edge,width:t.width,height:t.height,pixels:t.pixels,gpu:null,lastSelected:this._host.now(),selectedPass:this._pass};e.levels.push(i),e.levels.sort((s,a)=>s.edge-a.edge)}_request(e,t,n){e.failed.has(t)||!e.intrinsic||e.levels.some(i=>i.edge===t)||(n?e.queue=[t]:e.queue.includes(t)||e.queue.push(t))}_pump(){for(let e of this._entries.values()){if(this._inflight>=zv)return;if(e.job||e.loading)continue;let t=this._nextEdge(e);if(t===void 0)continue;let n=t;this._inflight++,e.job=this._host.decode(e.src,()=>n).then(i=>{if(this._learn(e,i.intrinsic,i.vector),!this._entries.has(e.src)){this._host.released(e.src,{...i,gpu:null,lastSelected:0,selectedPass:0});return}this._add(e,i),this._enforceBudget()},i=>{e.failed.add(n),this._host.onError?.(e.src,i)}).finally(()=>{this._inflight--,e.job=null,this._pump()})}}_nextEdge(e){for(let t=e.queue.shift();t!==void 0;t=e.queue.shift()){if(this._policy==="interactive"&&e.lastDemand!==void 0){let n=Math.min(e.lastDemand,e.cap),i=e.levels[e.levels.length-1];if(i&&t>i.edge&&i.edge>=n)continue;t<n&&(t=this._interactiveEdge(e,n))}if(!e.failed.has(t)&&!e.levels.some(n=>n.edge===t))return t}}_ageOut(e,t){if(e.levels.length<=1)return;let n=e.levels[e.levels.length-1],i=e.levels.filter(s=>t-s.lastSelected<Ov||s===n&&T0(s));if(i.length!==e.levels.length){i.length===0&&i.push(e.levels.reduce((s,a)=>a.lastSelected>s.lastSelected?a:s));for(let s of e.levels)i.includes(s)||this._host.released(e.src,s);e.levels=i}}_total(){let e=0;for(let t of this._entries.values()){for(let n of t.levels)e+=gs(n);e+=this._host.sourceBytes(t.src)}return e}_enforceBudget(){let e=this._total();if(e<=this._budget)return;let t=this._host.now(),n=[];for(let i of this._entries.values()){let s=i.levels.some(a=>a.selectedPass>=this._pass);i.levels.forEach((a,o)=>{a.selectedPass>=this._pass||!s&&o===0||n.push({entry:i,level:a})})}n.sort((i,s)=>i.level.lastSelected-s.level.lastSelected||gs(s.level)-gs(i.level));for(let{entry:i,level:s}of n){if(e<=this._budget)return;i.levels.length<=1||(i.levels=i.levels.filter(a=>a!==s),this._host.released(i.src,s),e-=gs(s))}if(this._policy==="interactive")for(let i of this._entries.values()){if(i.lastDemand===void 0)continue;let s=Kr(i.lastDemand,i.cap),a=i.levels[i.levels.length-1];a&&a.edge>s&&this._request(i,s,!0)}for(let i of this._entries.values()){if(e<=this._budget)break;if(t-i.lastUsed<Lv||i.levels.length===0)continue;let s=i.levels[0];for(let o of i.levels.slice(1))this._host.released(i.src,o),e-=gs(o);i.levels=[s];let a=Pa(i.cap);s.edge>a&&this._request(i,a,!0)}for(let i of this._entries.values()){if(e<=this._budget)break;if(t-i.lastUsed<Uv)continue;let s=this._host.sourceBytes(i.src);s!==0&&(this._host.dropSource(i.src),e-=s)}}};function gs(r){return r.width*r.height*4*(r.gpu?2:1)}function T0(r){return r.width*r.height*4<=Vv}function Hv(r,e){let t=r[0];for(let n of r){let i=Math.abs(Math.log(n.edge/e)),s=Math.abs(Math.log(t.edge/e));(i<s||i===s&&n.edge>t.edge)&&(t=n)}return t}var Wv=512*1024*1024,v0=96,A0=32;function _0(r){if(!r||!(r.width>0)||!(r.height>0))return{forward:v0,back:A0};let e=Wv/(r.width*r.height*4);return{forward:Math.max(4,Math.min(v0,Math.floor(e*.75))),back:Math.max(1,Math.min(A0,Math.floor(e*.25)))}}var dl=class{level;_cap;_passNeed=0;_passDraws=0;_passAllOver=!0;_overSince=null;constructor(e,t,n,i){this._cap=ms(e,!1),this.level=t==="exact"?Pa(this._cap):Kr(n??Math.min(Math.max(e.width,e.height),i),this._cap)}get cap(){return this._cap}note(e){let t=e!==void 0&&Number.isFinite(e)&&e>0?Math.min(e,this._cap):this._cap;this._passNeed=Math.max(this._passNeed,t),this._passDraws++,this.level<2*t&&(this._passAllOver=!1)}accepts(e,t){return e===void 0?!0:t==="exact"?e===this.level:e>=this.level}endPass(e,t,n){let i=this._passDraws,s=this._passNeed,a=this._passAllOver;if(this._passDraws=0,this._passNeed=0,this._passAllOver=!0,i===0)return!1;let o=Kr(s,this._cap),c=this.level;return e==="exact"?this.level=o:this.level<s?(this.level=o,this._overSince=null):a&&!t?(this._overSince??=n,n-this._overSince>=Od&&(this.level=o,this._overSince=null)):this._overSince=null,this.level!==c}};function C0(r){let{data:e}=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Gv(r){return/\.svg(?:[?#]|$)/i.test(r)}var Kv={image:[(r,e)=>r.getImageMeta(e)],video:[(r,e)=>r.getVideoMeta(e)],media:[(r,e)=>r.getAudioMeta(e),(r,e)=>r.getVideoMeta(e)]},jt=class r extends jv{canvasKit;fontMgr;disposed=!1;surface=null;videoSessions=new Map;videoFrames=new Map;videoEchoFrames=new Map;videoPlayhead=new Map;pendingVideoFrames=new Map;pendingEchoFrames=new Map;echoDecodes=new Map;videoFrameClaims=new Map;videoAltSlots=new Map;videoDemand=new Map;playing=!1;decodePolicy="interactive";images;imageSources=new Map;reportedImageErrors=new Set;audioBuffers=new Map;audioCtx=null;fps;registeredFontFamilies=new Set;unknownFontFamilies=new Set;paragraphCache=new ho;fontEpoch=0;static ECHO_CACHE_LIMIT=48;static ALT_SLOT_LIMIT=16;constructor(e,t,n,i){super(t,n),this.canvasKit=e,this.fps=i,this.fontMgr=e.TypefaceFontProvider.Make(),this.images=new ul({now:()=>performance.now(),decode:(s,a)=>this.decodeImage(s,a),released:(s,a)=>{a.gpu?.delete(),a.gpu=null},sourceBytes:s=>this.imageSources.get(s)?.bytes??0,dropSource:s=>this.imageSources.delete(s),surfaceEdge:()=>this.surfaceEdge(),onError:(s,a)=>{this.disposed||this.reportedImageErrors.has(s)||(this.reportedImageErrors.add(s),console.error(`[WebStorageAdapter] image decode failed for ${s}:`,a))}})}getCanvasKit(){return this.canvasKit}setCatalog(e){super.setCatalog(e),this.unknownFontFamilies.clear()}setDecodePolicy(e){this.decodePolicy=e,this.images.setPolicy(e)}getDecodePolicy(){return this.decodePolicy}hasPendingDecodes(){return this.pendingVideoFrames.size>0||this.pendingEchoFrames.size>0||this.echoDecodes.size>0||Sl()||this.images.hasPending()}async warmPendingDecodes(){let[e,t]=await Promise.all([this.warmVideo(),this.images.warm()]);return e||t}hasPendingUpgrades(){return this.images.hasUpgrades()}warmPendingUpgrades(){return this.images.warmUpgrades()}warmPendingVideo(){return this.warmPendingDecodes()}_decodeStats(){let e=0,t=0,n=0,i=new Set,s=a=>{for(let{bitmap:o}of a.values())i.has(o)||(i.add(o),n+=(o.width??0)*(o.height??0)*4)};for(let a of this.videoFrames.values())e+=a.size,s(a);for(let a of this.videoEchoFrames.values())t+=a.size,s(a);return{images:this.images.stats(),video:{sessions:this.videoSessions.size,windowFrames:e,echoFrames:t,frameBytes:n}}}async loadImage(e){await this.images.load(e)}getCKImage(e,t){let n=this.images.select(e,t);return n?(n.gpu??=this.makeCKImageFromPixels(n.pixels,n.width,n.height),n.gpu):null}getImagePixels(e,t){return this.images.select(e,t)}getImageSize(e){return this.images.intrinsicSize(e)??this.catalogImageSize(e)}catalogImageSize(e){try{let t=this.catalog.getImageMeta(e);return t.width>0&&t.height>0?{width:t.width,height:t.height}:null}catch{return null}}async decodeImage(e,t){let n=this.assetUrl(e,"image");if(Gv(n)){let u=await this.svgSource(e,n),d=u.natural,h=t(d,!0),f=ps(h,d),m=new OffscreenCanvas(f.width,f.height).getContext("2d",{willReadFrequently:!0});if(!m)throw new Error(`loadImage(${e}): could not get 2d context`);return m.drawImage(u.svg,0,0,f.width,f.height),{pixels:C0(m.getImageData(0,0,f.width,f.height)),...f,intrinsic:d,vector:!0,edge:h}}let i=await this.rasterSource(e,n),s=this.catalogImageSize(e),a=null;s||(a=await createImageBitmap(i),s={width:a.width,height:a.height});let o=t(s,!1),c=o>=ms(s,!1)&&Math.max(s.width,s.height)<=4096,l;if(c)l=a??await createImageBitmap(i);else{let u=ps(o,s);try{l=await createImageBitmap(a??i,{resizeWidth:u.width,resizeHeight:u.height,resizeQuality:"high"})}finally{a?.close()}}try{let d=new OffscreenCanvas(l.width,l.height).getContext("2d",{willReadFrequently:!0});if(!d)throw new Error(`loadImage(${e}): could not get 2d context`);return d.drawImage(l,0,0),{pixels:C0(d.getImageData(0,0,l.width,l.height)),width:l.width,height:l.height,intrinsic:s,vector:!1,edge:o}}finally{l.close()}}async rasterSource(e,t){let n=this.imageSources.get(e);if(n?.blob)return n.blob;let i=await this.fetchBlob(t);return this.imageSources.set(e,{blob:i,bytes:i.size}),i}async svgSource(e,t){let n=this.imageSources.get(e);if(n?.svg&&n.natural)return n;let i=await(await this.fetchBlob(t)).text(),s=new Image;s.decoding="sync",await new Promise((c,l)=>{s.onload=()=>c(),s.onerror=()=>l(new Error(`loadImage(${e}): failed to decode SVG`)),s.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(i)}`});let a={width:s.naturalWidth>0?s.naturalWidth:300,height:s.naturalHeight>0?s.naturalHeight:300},o={svg:s,natural:a,bytes:i.length};return this.imageSources.set(e,o),o}surfaceEdge(){let e=this.surface;return e&&typeof e.width=="function"&&typeof e.height=="function"?Math.max(e.width(),e.height()):Math.max(this.viewport.width,this.viewport.height)}async fetchBlob(e){let t=await gl(e);return t||Zd(e)}assetUrl(e,t){let n=Kv[t];for(let i of n)try{let s=i(this.catalog,e).src;if(s)return s}catch{}return e}canvas3DTextures=new Map;upload3DFrame(e,t,n,i){let s=this.surface;if(!s)return null;let a={width:n,height:i,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB},o=this.canvas3DTextures.get(e);if(o&&(o.width()!==n||o.height()!==i)&&(o.delete(),this.canvas3DTextures.delete(e),o=void 0),!o){let c=s.makeImageFromTextureSource(t,a,!1);return c?(this.canvas3DTextures.set(e,c),c):null}return s.updateTextureFromSource(o,t,!1),o}release3DTexture(e){this.canvas3DTextures.get(e)?.delete(),this.canvas3DTextures.delete(e)}setSurface(e){if(e!==this.surface){for(let t of this.videoSessions.values())t.textureImage?.delete(),t.textureImage=null,t.uploadedTs=null,t.uploadedBitmap=null;this.clearVideoAltSlots();for(let t of this.canvas3DTextures.values())t.delete();this.canvas3DTextures.clear(),this.surface=e}}setPlaying(e){this.playing=e}beginRenderPass(){this.videoFrameClaims.clear(),this.images.beginPass()}endRenderPass(){this.images.endPass();let e=performance.now();for(let[t,n]of this.videoSessions){if(!(n.levels?.endPass(this.decodePolicy,this.playing,e)??!1))continue;this.videoDemand.set(t,n.levels.level);let s=ps(n.levels.level,n.intrinsic);n.width=s.width,n.height=s.height,(this.videoFrameClaims.get(t)??[]).forEach((o,c)=>{let l=o*n.frameStep;if(c===0)this.pendingVideoFrames.has(t)||this.pendingVideoFrames.set(t,l);else{let u=this.pendingEchoFrames.get(t);u||(u=new Set,this.pendingEchoFrames.set(t,u)),u.add(l)}}),this.playing&&this.driveSequentialDecode(t,this.videoPlayhead.get(t)??0)}}async loadVideo(e,t,n,i=0,s){if(this.videoSessions.has(e))return;let a=this.assetUrl(e,"video"),o=await gl(a),c=new qr({formats:cd,source:o?new la(o):new ua(a)}),l=await c.getPrimaryVideoTrack();if(!l)throw c.dispose(),new Error(`loadVideo(${e}): no video track found`);let u=new xa(l),d=await c.computeDuration(),h=await this.probeFirstFrame(u),f=this.catalogVideoSize(e)??await this.trackDisplaySize(l,h),p=new dl(f,this.decodePolicy,this.videoDemand.get(e),this.surfaceEdge()),m=ps(p.level,f);this.videoSessions.set(e,{input:c,sink:u,durationSec:d,frameStep:h.frameStep,width:m.width,height:m.height,intrinsic:f,levels:p,canvas:null,textureImage:null,uploadedTs:null,decoding:!1}),this.videoFrames.set(e,new Map),await this.decodeAt(e,i)}getVideoSize(e){return this.videoSessions.get(e)?.intrinsic??this.catalogVideoSize(e)}catalogVideoSize(e){try{let t=this.catalog.getVideoMeta(e);return t.width>0&&t.height>0?{width:t.width,height:t.height}:null}catch{return null}}async trackDisplaySize(e,t){try{let n=await e.getDisplayWidth(),i=await e.getDisplayHeight();if(n>0&&i>0)return{width:n,height:i}}catch{}return{width:Math.max(1,t.width),height:Math.max(1,t.height)}}getVideoFrame(e,t){let n=this.videoSessions.get(e),i=this.videoFrames.get(e);if(!n||!i||!this.surface)return null;Number.isFinite(t)||(t=0),this.videoPlayhead.set(e,t);let s=this.nearestDecoded(i,t,n.frameStep),a=this.quantizeTs(t,n.frameStep);return!!s&&this.quantizeTs(s.timestamp,n.frameStep)===a&&this.accepts(n,s)?this.playing&&this.driveSequentialDecode(e,t):(this.pendingVideoFrames.set(e,t),this.playing&&this.driveSequentialDecode(e,t)),s?this.uploadFrame(e,n,s):null}claimVideoFrame(e,t,n){let i=this.videoSessions.get(e);if(!i||!this.surface)return null;Number.isFinite(t)||(t=0),i.levels?.note(n);let s=this.quantizeTs(t,i.frameStep),a=this.videoFrameClaims.get(e);a||(a=[],this.videoFrameClaims.set(e,a));let o=a.indexOf(s);if(o===0)return i.textureImage;if(o>0)return this.videoAltSlots.get(e)?.[o-1]?.image??null;if(a.length===0){let u=this.getVideoFrame(e,t);return u&&a.push(i.uploadedTs??s),u}let c=Math.min(a.length-1,r.ALT_SLOT_LIMIT-1),l=this.uploadAltFrame(e,i,t,c);return l&&a.push(s),l}clearVideoAltSlots(){for(let e of this.videoAltSlots.values())for(let t of e)t.image?.delete();this.videoAltSlots.clear()}uploadAltFrame(e,t,n,i){if(!this.surface)return null;let a=this.decodedFrameFor(e,t,n);if(!a)return null;let o=this.videoAltSlots.get(e);o||(o=[],this.videoAltSlots.set(e,o));let c=o[i];c||(c={image:null,uploadedTs:null},o[i]=c);let l=this.quantizeTs(a.timestamp,t.frameStep);return c.image&&c.uploadedTs===l&&(c.bitmap===void 0||c.bitmap===a.bitmap)||(this.uploadInto(c,a,t),c.uploadedTs=c.image?l:null),c.image}uploadInto(e,t,n){let i=this.surface,s=t.bitmap.width||n.width,a=t.bitmap.height||n.height;e.image&&(e.width!==s||e.height!==a)&&(e.image.delete(),e.image=null),e.image?i.updateTextureFromSource(e.image,t.bitmap):e.image=i.makeImageFromTextureSource(t.bitmap,{width:s,height:a,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB}),e.width=s,e.height=a,e.bitmap=e.image?t.bitmap:null}decodedFrameFor(e,t,n){let i=t.frameStep,s=Math.max(0,Math.min(n,t.durationSec)),a=f=>this.accepts(t,f),o=this.videoEchoFrames.get(e),c=this.videoFrames.get(e),l=this.nearestWithin(o,s,i,a)??this.nearestWithin(c,s,i,a);if(l)return l;let u=this.pendingEchoFrames.get(e);u||(u=new Set,this.pendingEchoFrames.set(e,u)),u.add(s),this.playing&&this.decodeEchoFrameAt(e,s);let d=o?this.nearestDecoded(o,s,i):null,h=c?this.nearestDecoded(c,s,i):null;return d?h?Math.abs(d.timestamp-s)<=Math.abs(h.timestamp-s)?d:h:d:h}getVideoDuration(e){return this.videoSessions.get(e)?.durationSec??0}getVideoFrameImage(e,t,n){let i=this.videoSessions.get(e);if(!i||!this.surface||!Number.isFinite(t))return null;i.levels?.note(n);let s=Math.max(0,Math.min(t,i.durationSec)),a=i.frameStep,o=l=>this.accepts(i,l),c=this.nearestWithin(this.videoEchoFrames.get(e),s,a,o)??this.nearestWithin(this.videoFrames.get(e),s,a,o);if(!c){let l=this.pendingEchoFrames.get(e);return l||(l=new Set,this.pendingEchoFrames.set(e,l)),l.add(s),null}return this.surface.makeImageFromTextureSource(c.bitmap,{width:c.bitmap.width||i.width,height:c.bitmap.height||i.height,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB})}uploadFrame(e,t,n){if(!this.surface)return null;let i=this.quantizeTs(n.timestamp,t.frameStep);if(t.textureImage&&t.uploadedTs===i&&(t.uploadedBitmap==null||t.uploadedBitmap===n.bitmap))return t.textureImage;let s={image:t.textureImage,uploadedTs:t.uploadedTs,width:t.textureWidth,height:t.textureHeight};return this.uploadInto(s,n,t),t.textureImage=s.image,t.textureWidth=s.width,t.textureHeight=s.height,t.uploadedBitmap=s.bitmap,t.uploadedTs=t.textureImage?i:null,t.textureImage}accepts(e,t){return e.levels?e.levels.accepts(t.level,this.decodePolicy):!0}async warmVideo(){let e=[...this.pendingVideoFrames];this.pendingVideoFrames.clear();let t=[...this.pendingEchoFrames].flatMap(([s,a])=>[...a].map(o=>[s,o]));this.pendingEchoFrames.clear();let n=await Tl(),i=[...this.echoDecodes.values()];return e.length===0&&t.length===0&&i.length===0?n:(await Promise.all([...e.map(([s,a])=>this.decodeAt(s,a)),...t.map(([s,a])=>this.decodeEchoFrameAt(s,a)),...i]),!0)}driveSequentialDecode(e,t){let n=this.videoSessions.get(e);if(!n||n.decoding||!n.sink||!this.videoFrames.get(e))return;let i=n.frameStep,{forward:s}=this.windowFrames(n),a=Math.min(n.durationSec,t+s*i);t>=a||(n.decoding=!0,(async()=>{try{for await(let o of n.sink.samples(t,a+i)){let c=this.videoFrames.get(e);if(this.disposed||!c){o.close();break}let l=this.quantizeTs(o.timestamp,i),u=c.get(l);u&&this.accepts(n,u)?o.close():this.storeFrame(e,c,l,await this.snapshot(n,o));let d=this.videoPlayhead.get(e)??t;if(!this.playing||d<t-i||d>a)break}this.evictVideoWindow(e,this.videoPlayhead.get(e)??t,i)}catch(o){this.disposed||console.error(`[WebStorageAdapter] sequential decode failed for ${e}:`,o)}finally{n.decoding=!1}})())}async decodeAt(e,t){let n=this.videoSessions.get(e);if(!n||!Number.isFinite(t))return;let i=Math.max(0,Math.min(t,n.durationSec)),s=this.quantizeTs(i,n.frameStep),a=this.videoFrames.get(e),o=a?.get(s);if(!(!a||o&&this.accepts(n,o)))try{let c=await n.sink.getSample(i);if(!c)return;if(this.disposed){c.close();return}let l=await this.snapshot(n,c),u=this.videoFrames.get(e);if(!u){l.bitmap.close();return}this.storeFrame(e,u,this.quantizeTs(l.timestamp,n.frameStep),l),this.evictVideoWindow(e,i,n.frameStep)}catch(c){this.disposed||console.error(`[WebStorageAdapter] video decode failed for ${e}@${i}:`,c)}}storeFrame(e,t,n,i){let s=this.videoSessions.get(e),a=t.get(n);if(a&&s&&this.accepts(s,a)&&!this.accepts(s,i)){i.bitmap.close();return}a&&a!==i&&this.videoEchoFrames.get(e)?.get(n)!==a&&a.bitmap.close(),t.set(n,i)}decodeEchoFrameAt(e,t){let n=this.videoSessions.get(e);if(!n||!Number.isFinite(t))return Promise.resolve();let i=Math.max(0,Math.min(t,n.durationSec)),s=this.quantizeTs(i,n.frameStep),a=this.videoEchoFrames.get(e)?.get(s);if(a&&this.accepts(n,a))return Promise.resolve();let o=`${e}#${s}`,c=this.echoDecodes.get(o);if(c)return c;let l=this.decodeEchoFrameNow(e,n,i,s).finally(()=>this.echoDecodes.delete(o));return this.echoDecodes.set(o,l),l}async decodeEchoFrameNow(e,t,n,i){let s=this.videoEchoFrames.get(e),a=this.videoFrames.get(e)?.get(i);try{if(s||(s=new Map,this.videoEchoFrames.set(e,s)),a&&this.accepts(t,a))this.replaceEcho(e,s,i,a);else{let o=await t.sink.getSample(n);if(!o)return;if(this.disposed){o.close();return}let c=await this.snapshot(t,o);if(s=this.videoEchoFrames.get(e),!s){c.bitmap.close();return}this.replaceEcho(e,s,this.quantizeTs(c.timestamp,t.frameStep),c)}this.trimEchoCache(e)}catch(o){this.disposed||console.error(`[WebStorageAdapter] echo decode failed for ${e}@${n}:`,o)}}replaceEcho(e,t,n,i){let s=t.get(n);s&&s!==i&&this.videoFrames.get(e)?.get(n)!==s&&s.bitmap.close(),t.set(n,i)}trimEchoCache(e){let t=this.videoEchoFrames.get(e);if(t)for(;t.size>r.ECHO_CACHE_LIMIT;){let n=t.keys().next().value;if(n===void 0)break;let i=t.get(n);i&&this.videoFrames.get(e)?.get(n)!==i&&i.bitmap.close(),t.delete(n)}}snapshot(e,t){let n=e.levels.level,{width:i,height:s}=ps(n,e.intrinsic);try{let a=e.canvas;(!a||a.width!==i||a.height!==s)&&(a=new OffscreenCanvas(i,s),e.canvas=a);let o=a.getContext("2d");if(!o)throw new Error("video snapshot: could not get 2d context");o.imageSmoothingEnabled=!0,o.imageSmoothingQuality="high",o.clearRect(0,0,i,s),t.drawWithFit(o,{fit:"fill"});let c=createImageBitmap(a),l=t.timestamp;return c.then(u=>({timestamp:l,bitmap:u,level:n}))}finally{t.close()}}windowFrames(e){return _0(e?{width:e.width,height:e.height}:null)}evictVideoWindow(e,t,n){let i=this.videoFrames.get(e);if(!i)return;let{forward:s,back:a}=this.windowFrames(this.videoSessions.get(e)),o=t-a*n,c=t+s*n,l=this.videoEchoFrames.get(e);for(let[u,d]of i)(d.timestamp<o||d.timestamp>c)&&(l?.get(u)!==d&&d.bitmap.close(),i.delete(u))}nearestDecoded(e,t,n){let i=e.get(this.quantizeTs(t,n));if(i)return i;let s=null,a=1/0;for(let o of e.values()){let c=Math.abs(o.timestamp-t);c<a&&(a=c,s=o)}return s}quantizeTs(e,t){return Math.round(e/t)}nearestWithin(e,t,n,i){if(!e||e.size===0)return null;let s=null,a=1/0;for(let o of e.values()){if(i&&!i(o))continue;let c=Math.abs(o.timestamp-t);c<a&&(a=c,s=o)}return s&&a<=n?s:null}async probeFirstFrame(e){try{let t=await e.getSample(0);if(!t)for await(let n of e.samples()){t=n;break}if(t){let n={frameStep:t.duration>0?t.duration:.03333333333333333,width:t.displayWidth,height:t.displayHeight};return t.close(),n}}catch{}return{frameStep:1/30,width:1,height:1}}makeCKImageFromPixels(e,t,n){return this.canvasKit.MakeImage({width:t,height:n,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB},e,4*t)}async loadAudio(e,t,n,i=0,s){if(this.audioBuffers.has(e))return;this.audioCtx||(this.audioCtx=new AudioContext);let a=await(await this.fetchBlob(this.assetUrl(e,"media"))).arrayBuffer(),o=await this.audioCtx.decodeAudioData(a);this.audioBuffers.set(e,o)}async fetchAudioData(e){return(await this.fetchBlob(this.assetUrl(e,"media"))).arrayBuffer()}getAudioBuffer(e){return this.audioBuffers.get(e)??null}async loadFont(e,t,n){if(this.registeredFontFamilies.has(t))return!0;let i=this.catalog.getFontFamilyMetas(t);if(i.length===0)return this.unknownFontFamilies.has(t)||(this.unknownFontFamilies.add(t),console.warn(`[WebStorageAdapter] No font manifest entry for "${e}"; shaping against the fallback face. Add it to the manifest font record.`)),!1;let s=[...new Set(i.map(o=>o.src))],a=await Promise.all(s.map(async o=>(await this.fetchBlob(o)).arrayBuffer()));for(let o of a)this.fontMgr.registerFont(new Uint8Array(o),t);return this.registeredFontFamilies.add(t),this.unknownFontFamilies.delete(t),this.fontEpoch++,!0}getFontMgr(){return this.fontMgr}getParagraphCache(){return this.paragraphCache}getFontEpoch(){return this.fontEpoch}dispose(){if(this.disposed)return;this.disposed=!0,this.paragraphCache.dispose(),this.images.dispose(),this.imageSources.clear();for(let t of this.canvas3DTextures.values())t.delete();this.canvas3DTextures.clear();let e=new Set;for(let t of this.videoFrames.values())for(let{bitmap:n}of t.values())n.close(),e.add(n);this.videoFrames.clear();for(let t of this.videoEchoFrames.values())for(let{bitmap:n}of t.values())e.has(n)||n.close();this.videoEchoFrames.clear();for(let t of this.videoSessions.values())t.textureImage?.delete(),t.input.dispose();this.videoSessions.clear(),this.clearVideoAltSlots(),this.videoPlayhead.clear(),this.videoFrameClaims.clear(),this.pendingVideoFrames.clear(),this.pendingEchoFrames.clear(),this.echoDecodes.clear(),this.surface=null,this.audioBuffers.clear(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close(),this.audioCtx=null,super.dispose()}};import $v from"@motionscript/canvaskit";var Ld=null,hl=null;function Xv(){return new URL("@motionscript/canvaskit/canvaskit.wasm",import.meta.url).href}async function $r(r){if(Ld)return Ld;if(hl)return hl;let e=r??Xv();return hl=$v({locateFile:()=>e}).then(t=>(Ld=t,t)),hl}import{ManifestAssetCatalog as Qv,Registry as Yv,resolveProjectDocument as Zv}from"@motionscript/core";var Xr={viewport:{width:1920,height:1080},fps:60};var Jv=.2,eA=2e6,tA=1e8;function P0(r,e,t){let n=r*e*t*Jv;return Math.round(Math.min(tA,Math.max(eA,n)))}var rA=192e3,nA=1,iA=2,sA={image:{},video:{},audio:{},font:{}},Ud=class{audioOptions;target=new sr;output;video;audio=null;constructor(e,t,n,i={},s={},a="avc"){this.audioOptions=s;let o=n.width!==e.width||n.height!==e.height;this.video=new _a(e,{codec:a,bitrate:i.bitrate??P0(n.width,n.height,t),hardwareAcceleration:i.hardwareAcceleration??"no-preference",keyFrameInterval:i.keyFrameInterval??nA,latencyMode:i.latencyMode??"quality",contentHint:i.contentHint??"detail",...i.bitrateMode!==void 0&&{bitrateMode:i.bitrateMode},...o&&{transform:{width:n.width,height:n.height,fit:"fill"}}}),this.output=new ei({format:new xn,target:this.target})}async start(e){this.output.addVideoTrack(this.video,{frameRate:e.fps}),e.hasAudio&&(this.audio=new Jn({codec:"aac",bitrate:this.audioOptions.bitrate??rA}),this.output.addAudioTrack(this.audio)),await this.output.start()}async addFrame(e,t){await this.video.add(e,t)}async addAudio(e){this.audio&&await this.audio.add(e)}async finalize(){this.video.close(),this.audio?.close(),await this.output.finalize();let e=this.target.buffer;if(!e)throw new Error("Export produced no data");return new Uint8Array(e)}};function fl(r){let e=Math.round(r);return e%2===0?e:e+1}var aA=8192;function oA(r,e){let t=Math.max(e.width,e.height),n=Math.max(1,Math.round(r));for(;n>1&&t*n>aA;)n--;return n}async function cA(r,e,t){if(!r||r==="avc")return"avc";try{if(await hd(r,{width:e.width,height:e.height,bitrate:P0(e.width,e.height,t)}))return r}catch{}return console.warn(`[motion-script] No ${r} encoder available; exporting as H.264 instead.`),"avc"}async function zd(r){let{document:e,registry:t=new Yv,scale:n=1,filename:i="export.mp4",manifest:s=sA,theme:a,includeAudio:o=!0,video:c,audio:l={},onProgress:u,signal:d,wasmUrl:h,supersample:f=iA,returnBytes:p=!1}=r,m=Zv(e,r,Xr);if(m.tracks.length===0)return;d?.throwIfAborted();let g=m.viewport,y=m.fps,b={width:fl(g.width*n),height:fl(g.height*n)},k=oA(f,b),T=n*k,S=document.createElement("canvas");S.width=fl(g.width*T),S.height=fl(g.height*T),S.style.display="none",document.body.appendChild(S);let _=await $r(h),M=new Qv(s),P=new jt(_,M,g,y),A=new cr(_,P);A.mount(S);let F=await cA(c?.codec,b,y),I;try{I=await du({project:m,registry:t,theme:a,scale:T,includeAudio:o,renderContext:A,storageAdapter:P,assetCatalog:M,sink:new Ud(S,y,b,c,l,F),mixer:new Jd(l.sampleRate,M),onProgress:u,signal:d})}finally{A.dispose(),document.body.removeChild(S)}if(!I)return;if(p)return I;let O=new Blob([I.buffer],{type:"video/mp4"}),Q=URL.createObjectURL(O),ge=document.createElement("a");ge.href=Q,ge.download=i,document.body.appendChild(ge),ge.click(),document.body.removeChild(ge),URL.revokeObjectURL(Q)}import{resolveProjectDocument as fA}from"@motionscript/core";import{ManifestAssetCatalog as E0,Registry as lA,resolveProjectDocument as uA}from"@motionscript/core";var dA={image:{},video:{},audio:{},font:{}};function hA(r,e){if(r?.time!==void 0)return{kind:"frame",frame:Math.round(r.time*e)};let t=r?.frame;return t===void 0||t==="first"?{kind:"first"}:t==="last"?{kind:"last"}:typeof t=="number"?{kind:"frame",frame:t}:t}function I0(r){return r==="jpeg"?"image/jpeg":"image/png"}var ys=class{canvas;renderContext;storageAdapter;catalog;canvasKit;ownsCanvas;viewportValue;fpsValue;scaleValue;surfaceScale;manifest;theme;registry;disposed=!1;constructor(e,t){this.canvasKit=e,this.viewportValue=t.viewport??Xr.viewport,this.fpsValue=t.fps??Xr.fps,this.scaleValue=t.scale??1,this.surfaceScale=this.scaleValue,this.manifest=t.manifest??dA,this.theme=t.theme,this.registry=t.registry??new lA,this.ownsCanvas=t.canvas===void 0,this.canvas=t.canvas??document.createElement("canvas"),this.ownsCanvas&&(this.canvas.style.display="none",document.body.appendChild(this.canvas)),this.sizeCanvas(),this.catalog=new E0(this.manifest),this.storageAdapter=new jt(e,this.catalog,this.viewportValue,this.fpsValue),this.renderContext=new cr(e,this.storageAdapter),this.renderContext.mount(this.canvas)}get viewport(){return this.viewportValue}get fps(){return this.fpsValue}get scale(){return this.scaleValue}async render(e,t){this.assertLive();let n=t?.scale??this.scaleValue;n!==this.surfaceScale&&this.remount(n);let i=uA(e,{viewport:this.viewportValue},{viewport:this.viewportValue,fps:this.fpsValue});return hu({project:i,registry:this.registry,theme:this.theme,scale:n,renderContext:this.renderContext,storageAdapter:this.storageAdapter,assetCatalog:this.catalog,frame:hA(t,i.fps)})}setTheme(e){this.theme=e}setManifest(e){this.assertLive(),this.manifest=e,this.catalog=new E0(e),this.storageAdapter.setCatalog(this.catalog)}setViewport(e){this.assertLive(),!(e.width===this.viewportValue.width&&e.height===this.viewportValue.height)&&(this.viewportValue=e,this.renderContext.dispose(),this.storageAdapter=new jt(this.canvasKit,this.catalog,e,this.fpsValue),this.renderContext=new cr(this.canvasKit,this.storageAdapter),this.remount(this.scaleValue))}async toBytes(e){let t=await this.toBlob(e);return new Uint8Array(await t.arrayBuffer())}toBlob(e){let t=this.snapshotToCanvas(),{format:n="png",quality:i=.92}=e??{};return new Promise((s,a)=>{t.toBlob(o=>o?s(o):a(new Error("Still encode produced no data.")),I0(n),i)})}toDataURL(e){let{format:t="png",quality:n=.92}=e??{};return this.snapshotToCanvas().toDataURL(I0(t),n)}dispose(){this.disposed||(this.disposed=!0,this.renderContext.dispose(),this.ownsCanvas&&this.canvas.remove())}snapshotToCanvas(){this.assertLive();let e=this.renderContext.snapshotPixels();if(!e)throw new Error("Nothing has been rendered yet.");let t=document.createElement("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");if(!n)throw new Error("Still encode: could not get a 2d context.");return n.putImageData(new ImageData(new Uint8ClampedArray(e.pixels),e.width,e.height),0,0),t}sizeCanvas(){this.canvas.width=this.viewportValue.width*this.surfaceScale,this.canvas.height=this.viewportValue.height*this.surfaceScale}remount(e){this.surfaceScale=e,this.sizeCanvas(),this.renderContext.mount(this.canvas)}assertLive(){if(this.disposed)throw new Error("This StillRenderer has been disposed.")}};async function Nd(r={}){let e=await $r(r.wasmUrl);return new ys(e,r)}async function mA(r){let{registry:e,scale:t,manifest:n,theme:i,wasmUrl:s,frame:a,format:o="png",quality:c=.92}=r,l=fA(r.document,r,Xr);if(l.tracks.length===0)throw new Error("The project has no tracks to screenshot.");let u=await Nd({viewport:l.viewport,fps:l.fps,scale:t,manifest:n,theme:i,wasmUrl:s,registry:e});try{return{...await u.render(l,{frame:a}),bytes:await u.toBytes({format:o,quality:c})}}finally{u.dispose()}}var ws=class extends Error{segment;constructor(e,t){super(t),this.segment=e,this.name="ConcatMismatchError"}};function pA(r,e){if(r.codec!==e.codec||r.codedWidth!==e.codedWidth||r.codedHeight!==e.codedHeight)return!1;let t=M0(r.description),n=M0(e.description);if(t===null||n===null)return t===n;if(t.length!==n.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==n[i])return!1;return!0}function M0(r){return r?ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r):null}var gA=192e3;async function yA(r,e={}){if(r.length===0)throw new Error("concatVideoSegments: no segments");if(r.length===1&&!e.audio&&!e.stream)return r[0];let t=[];for(let l=0;l<r.length;l++){let d=await new qr({source:new ca(r[l]),formats:[Kc]}).getPrimaryVideoTrack();if(!d)throw new ws(l,`Segment ${l} has no video track.`);let h=await d.getDecoderConfig();if(!h)throw new ws(l,`Segment ${l} has no decoder configuration.`);if(t.length>0&&!pA(t[0].config,h))throw new ws(l,`Segment ${l} was encoded differently from segment 0 (${t[0].config.codec} ${t[0].config.codedWidth}x${t[0].config.codedHeight} vs ${h.codec} ${h.codedWidth}x${h.codedHeight}); joining them would decode as garbage.`);t.push({track:d,config:h,duration:await d.computeDuration()})}let n=e.stream?new va(e.stream):new sr,i=new ei({format:new xn,target:n}),s=new Aa(t[0].track.codec);i.addVideoTrack(s);let a=e.audio?new Jn({codec:"aac",bitrate:e.audioBitrate??gA}):null;a&&i.addAudioTrack(a),await i.start();let o=0;for(let l of t){let u=!0;for await(let d of new wn(l.track).packets())await s.add(d.clone({timestamp:d.timestamp+o}),u?{decoderConfig:l.config}:void 0),u=!1;o+=l.duration}if(a&&e.audio&&await a.add(e.audio),s.close(),a?.close(),await i.finalize(),e.stream)return new Uint8Array(0);let c=n.buffer;if(!c)throw new Error("concatVideoSegments produced no data");return new Uint8Array(c)}import{ManifestAssetCatalog as wA,AssetTimeline as bA,Registry as kA,resolveProjectDocument as xA}from"@motionscript/core";var ml=class{storageAdapter;constructor(e){this.storageAdapter=e}measureText(e,t,n,i=400,s=0,a="normal"){return fo(this.storageAdapter.getCanvasKit(),this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),this.storageAdapter.getFontEpoch(),e,t,n,i,s,a)}layoutTextBlock(e){return mo(this.storageAdapter.getCanvasKit(),this.storageAdapter.getFontMgr(),e)}};var ti=class extends ml{};var SA={image:{},video:{},audio:{},font:{}};async function TA(r){let{registry:e=new kA,manifest:t=SA,sampleRate:n,wasmUrl:i}=r,s=xA(r.document,r,Xr);if(s.tracks.length===0)return null;let a=s.viewport,o=s.fps,c=await $r(i),l=new wA(t),u=new jt(c,l,a,o),d=new ti(u),h=new bA(s,{registry:e,viewport:a,fps:o,assets:l,measurer:d},{assets:!1});try{let f=h.run(),p=uu(f);return p.length===0?null:await yl(p,f.totalDuration,{sampleRate:n,catalog:l})}finally{h.dispose(),u.dispose()}}import{Ticker as vA}from"@motionscript/core";var Ea=class extends vA{context;ownsContext;fps;playStartCtxTime=0;seekOffset=0;speed=1;reverse=!1;rafId=null;silentSource=null;constructor(e){super(),this.context=e.context??new AudioContext,this.ownsContext=!e.context,this.fps=e.fps}getContext(){return this.context}seek(e){let t=Math.max(0,Math.min(e,this.duration));this.seekOffset=t,this.playStartCtxTime=this.context.currentTime,this.setCurrentTime(t)}async play(e=1,t=!1){this.speed=e,this.reverse=t,this.seekOffset=this.currentTime,this.context.state==="suspended"&&await this.context.resume(),this.playStartCtxTime=this.context.currentTime,this.startSilentTicker(),super.play(e,t),this.startLoop()}pause(){this.seekOffset=this.currentTime,this.stopLoop(),this.stopSilentTicker(),this.context.state==="running"&&this.context.suspend(),super.pause()}startSilentTicker(){this.stopSilentTicker();let e=Math.max(.001,this.duration-this.seekOffset),t=this.context.sampleRate,n=this.context.createBuffer(1,Math.ceil(e*t),t),i=this.context.createBufferSource();i.buffer=n,i.connect(this.context.destination),i.start(),this.silentSource=i}stopSilentTicker(){if(this.silentSource){try{this.silentSource.onended=null,this.silentSource.stop(),this.silentSource.disconnect()}catch{}this.silentSource=null}}startLoop(){if(this.rafId!==null)return;let e=1/this.fps,t=this.currentTime,n=async()=>{let i=(this.context.currentTime-this.playStartCtxTime)*this.speed,s=this.reverse?this.seekOffset-i:this.seekOffset+i,a=Math.max(0,Math.min(s,this.duration)),o=this.reverse?a<=0:a>=this.duration,c=Math.abs(a-t)>=e;if(this.setCurrentTime(a,c||o),c&&(t=a,await this.tick()),o){this.rafId=null;return}this.rafId!==null&&(this.rafId=requestAnimationFrame(n))};this.rafId=requestAnimationFrame(n)}stopLoop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}dispose(){this.stopLoop(),this.stopSilentTicker(),this.ownsContext&&this.context.close(),super.dispose()}};import{Engine as IA}from"@motionscript/core";var pl=cy(F0(),1);import*as AA from"@motionscript/core/sdk";import*as _A from"@motionscript/core/jsx/jsx-runtime";function CA(){return new URL("esbuild-wasm/esbuild.wasm",import.meta.url).href}var PA;function EA(r){return PA??=(async()=>(await pl.initialize({wasmURL:r??CA()}),async e=>{let{code:t}=await pl.transform(e,{loader:"tsx",format:"cjs",target:"es2020",jsx:"automatic",jsxImportSource:"@motionscript/sdk",tsconfigRaw:{compilerOptions:{experimentalDecorators:!0}}});return t}))()}function R0(r,e){return{sdk:r?.sdk??AA,jsxRuntime:r?.jsxRuntime??_A,modules:r?.modules,compile:r?.compile??(async t=>(await EA(e))(t))}}var Hd=class{canvasKit;defaults;wasmUrl;still=null;stillRegistry=null;stillQueue=Promise.resolve();constructor(e,t,n){this.canvasKit=e,this.defaults=t,this.wasmUrl=n}async exportVideo(e){let t=e.encode??{};return zd({document:e.project,registry:e.registry,scale:e.scale,manifest:e.manifest,includeAudio:e.includeAudio,video:t.video??this.defaults.video,audio:t.audio??this.defaults.audio,supersample:t.supersample,filename:t.filename,returnBytes:t.download!==!0,onProgress:e.onProgress,signal:e.signal,wasmUrl:this.wasmUrl})}exportStill(e){let t=this.stillQueue.then(()=>this.drawStill(e));return this.stillQueue=t.catch(()=>{}),t}dispose(){this.still?.dispose(),this.still=null}async drawStill(e){let t=this.renderer(e),n=await t.render(e.project,{scale:e.scale,...MA(e.frame)});return{bytes:await t.toBytes({format:e.format,quality:e.quality}),frame:n.frame,totalFrames:n.totalFrames}}renderer(e){let{project:t,registry:n}=e;if(t.viewport===void 0||t.fps===void 0)throw new Error("exportStill takes a project whose fps and viewport are resolved \u2014 see Session.");return this.still&&this.stillRegistry!==n&&this.dispose(),this.still??=new ys(this.canvasKit,{viewport:t.viewport,fps:t.fps,manifest:e.manifest,registry:n}),this.stillRegistry=n,this.still.setViewport(t.viewport),e.manifest&&this.still.setManifest(e.manifest),this.still}};function MA(r){return r.kind==="frame"?{frame:r.frame}:{frame:r.kind}}async function FA(r={}){let e=r.nodes,t=Array.isArray(e)?e.filter(l=>typeof l!="string"):e,n=Array.isArray(e)?e.filter(l=>typeof l=="string"):[],i=R0(r.dynamicNodes,r.compilerWasmUrl),s=await $r(r.wasmUrl),a=new Hd(s,{video:r.video,audio:r.audio},r.wasmUrl),o={createStorageAdapter({catalog:l,viewport:u,fps:d}){return new jt(s,l,u,d)},createRenderContext(l){return new cr(s,l)},createMeasureContext(l){return new ti(l)},createAudioSink(){return new wl},createTicker(l,u){return new Ea({context:u.getContext(),fps:l})},createExporter(){return a},dispose(){a.dispose()}},c=new IA(o,{...r,nodes:t,dynamicNodes:i});for(let l of n)await c.registerNode(l);return c}export{As as Canvas3DBackend,ws as ConcatMismatchError,ye as EffectRegistry,Ds as NothingToDrawError,Qg as QUALITY_HIGH,$g as QUALITY_LOW,Xg as QUALITY_MEDIUM,Yg as QUALITY_VERY_HIGH,Kg as QUALITY_VERY_LOW,ys as StillRenderer,wl as WebAudioPlayer,ti as WebMeasureContext,cr as WebRenderContext,jt as WebStorageAdapter,Ea as WebTicker,ai as canvas3DBackend,yA as concatVideoSegments,FA as createBrowserEngine,Nd as createStillRenderer,Ga as disposeCanvas3DBackend,uy as encodeWav,mA as exportScreenshot,zd as exportVideo,$r as getCanvasKit,Ts as loadCanvas3D,yl as mixAudio,TA as mixTimelineAudio,ly as setAssetByteSource};
|
|
1958
|
+
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){w(this.gl);let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||we._error("Shader compile error:",this.gl.getShaderInfoLog(n)),n}createVAO(){w(this.gl),w(this.colorProgram);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){w(this.gl);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}runColorProgram(e){return w(this.gl),w(this.canvas),this.gl.useProgram(this.colorProgram),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),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}runAlphaProgram(e){w(this.gl),w(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),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);let{width:t,height:n}=this.canvas,i=Math.ceil(t/2)*Math.ceil(n/2),s=t*n+i*2,a=Math.ceil(s/(t*4)),o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,s),w(o[t*n]===128),w(o[o.length-1]===128);let c={format:"I420",codedWidth:t,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}updateCpu(e){if(!this.worker){let i=new Blob([`(${nv.toString()})()`],{type:"application/javascript"}),s=URL.createObjectURL(i);this.worker=new Worker(s),URL.revokeObjectURL(s),this.worker.addEventListener("message",a=>{let o=a.data,c=this.pendingRequests.get(o.id);c&&(this.pendingRequests.delete(o.id),"error"in o?c.reject(new Error(o.error)):c.resolve({colorFrame:o.colorFrame,alphaFrame:o.alphaFrame}))}),this.worker.addEventListener("error",a=>{let o=new Error(a.message||"Color/alpha splitter worker error.");for(let c of this.pendingRequests.values())c.reject(o);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=nt();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=new Error("Color/alpha splitter closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};ol.forceCpu=!0;var nv=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",s=>{let{id:a,sourceFrame:o}=s.data;e=e.then(async()=>{try{let{colorFrame:c,alphaFrame:l}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});let t=async s=>{let a=s.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=s.codedWidth,c=s.codedHeight,l=s.allocationSize();if((!r||r.byteLength!==l)&&(r=new Uint8Array(l)),await s.copyTo(r),a==="RGBA"||a==="BGRA")return n(r,o,c,a,s);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return i(r,o,c,a,s);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},n=(s,a,o,c,l)=>{let u=a*o,d=Math.ceil(a/2),h=Math.ceil(o/2),f=u+d*h*2,p=new Uint8Array(f);for(let b=0,k=3;b<u;b++,k+=4)p[b]=s[k];p.fill(128,u);let m=new VideoFrame(s,{format:c==="RGBA"?"RGBX":"BGRX",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),g={format:"I420",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[p.buffer]},y=new VideoFrame(p,g);return{colorFrame:m,alphaFrame:y}},i=(s,a,o,c,l)=>{let u=c.includes("P10"),d=c.includes("P12"),h=u||d?2:1,f,p;c.startsWith("I420")?(f=Math.ceil(a/2),p=Math.ceil(o/2)):c.startsWith("I422")?(f=Math.ceil(a/2),p=o):(f=a,p=o);let m=a*o,g=f*p,y=m*h,b=g*h,k=m*h,T=y+b*2,x=c.replace("A",""),v=Math.ceil(a/2),M=Math.ceil(o/2),C=v*M,_=C*h,F=k+2*_,E=new Uint8Array(F),O=T;E.set(s.subarray(O,O+k),0);let Q=k,ye=u?512:d?2048:128;h===1?E.fill(ye,Q):new Uint16Array(E.buffer,Q,2*C).fill(ye);let Z=u?"I420P10":d?"I420P12":"I420",ee=new VideoFrame(s.subarray(0,T),{format:x,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),ve={format:Z,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[E.buffer]},Re=new VideoFrame(E,ve);return{colorFrame:ee,alphaFrame:Re}}};var Ea=class extends ei{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");s0(t),super(t.codec),this._encoder=new Od(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");let i=new nr(this._canvas,{timestamp:e,duration:t});return this._encoder.add(i,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var us=class extends ls{constructor(e){if(super(),this._connectedTrack=null,!Ht.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ht.join(", ")}.`);this._codec=e}};var Ld=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new nn,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new al({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,onSample:async s=>{await this.processAndEncode(s,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&r0(e.format)!==n.transform.sampleFormat){let i=n0(e,n.transform.sampleFormat);t&&e.close(),e=i,t=!0}if(n.transform?.process){let i=n.transform.process(e);if(i instanceof Promise&&(i=await i),i===null)return;Array.isArray(i)||(i=[i]);for(let s of i){if(!(s instanceof mr))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(s,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed)return;{let n=Math.round(e.timestamp*e.sampleRate),i=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=i;else{let s=n-this.lastEndSampleIndex;if(s>=64){let a=new mr({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let n=e.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(n)).then(()=>this.customEncoderQueueSize--).catch(s=>this.error??=s).finally(()=>{n.close()});this.customEncoderQueueSize>=4&&await i,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{w(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(i=>this.encoder.addEventListener("dequeue",i,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){w(this.outputSampleSize),w(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:i,sampleRate:s,timestamp:a}=e,o=2048,c=[];for(let h=0;h<i;h+=o){let f=Math.min(o,e.numberOfFrames-h),p=f*n*this.outputSampleSize,m=new ArrayBuffer(p),g=new DataView(m);c.push({frameCount:f,view:g})}let l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let h=0;h<n;h++){e.copyTo(u,{planeIndex:h,format:"f32-planar"});for(let f=0;f<c.length;f++){let{frameCount:p,view:m}=c[f];for(let g=0;g<p;g++)this.writeOutputValue(m,(g*n+h)*this.outputSampleSize,u[f*o+g])}}t&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:s}};for(let h=0;h<c.length;h++){let{frameCount:f,view:p}=c[h],m=p.buffer,g=h*o,y=new Oe(new Uint8Array(m),"key",a+g/s,f/s);this.encodingConfig.onEncodedPacket?.(y,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,y,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,i=c0({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(i);let s=gd.find(a=>a.supports(this.encodingConfig.codec,i));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(a,o)=>{if(!(a instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,o),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,o).catch(c=>{this.error??=c})},await this.customEncoder.init();else if(ht.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.numberOfChannels} channels, ${i.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let o=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let d=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?d=!0:d=Ri(Ye(l.decoderConfig.description)).objectType===0,d){let h=Number(ze(i.codec.split(".")));l.decoderConfig.description=Vo({objectType:h,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}let u=Oe.fromEncodedChunk(c);u=u.clone({timestamp:Bn(u.timestamp,i.sampleRate),duration:c.duration!=null?Bn(u.duration,i.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(u,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,l).catch(d=>{this.error??=d})},error:c=>{c.stack=o,this.error??=c}}),this.encoder.configure(i)}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:i}=Wt(e);switch(this.outputSampleSize=n,n){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,Ze((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,Ze(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{let c=Ze(Math.floor(o*32767),-32768,32767);s.setUint8(a,m0(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{let c=Ze(Math.floor(o*32767),-32768,32767);s.setUint8(a,p0(c))}:w(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,Ze((o+1)*32767.5,0,65535),i):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,Ze(Math.round(o*32767),-32768,32767),i):w(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>zs(s,a,Ze((o+1)*83886075e-1,0,16777215),i):t==="signed"?this.writeOutputValue=(s,a,o)=>up(s,a,Ze(Math.round(o*8388607),-8388608,8388607),i):w(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,Ze((o+1)*21474836475e-1,0,4294967295),i):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,Ze(Math.round(o*2147483647),-2147483648,2147483647),i):t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat32(a,o,i):w(!1);break;case 8:t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat64(a,o,i):w(!1);break;default:Ct(n),w(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}};var ti=class extends us{constructor(e){o0(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Ld(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let t=mr._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let n of t)await this._encoder.add(n,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var Ia=class extends ls{constructor(e){if(super(),this._connectedTrack=null,!cn.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${cn.join(", ")}.`);this._codec=e}};var ds=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>gt.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ht.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>cn.includes(e))}_codecUnsupportedHint(e){return""}},hs=class extends ds{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new sl(e,this)}},xn=class extends hs{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...gt,...Ho,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...cn]}_codecUnsupportedHint(e){return new cs().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},os=class extends hs{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...gt,...Ho,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...cn]}},cs=class extends hs{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...gt,...Ht]}_codecUnsupportedHint(e){return new xn().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}};var iv=["video","audio","subtitle"],fs=class r{constructor(e,t,n,i,s){this.id=e,this.output=t,this.type=n,this.source=i,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;let t=_u(this.metadata.group),n=_u(e.metadata.group);for(let i of t)if(this.type!==e.type&&n.some(o=>i===o)||n.some(o=>i._pairedGroups.has(o)))return!0;return!1}},cl=class extends fs{constructor(e,t,n,i){super(e,t,"video",n,i)}},ll=class extends fs{constructor(e,t,n,i){super(e,t,"audio",n,i)}},ul=class extends fs{constructor(e,t,n,i){super(e,t,"subtitle",n,i)}},ms=class r{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}},Ud=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!Ei(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&wp(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof ms)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof ms))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},ri=class extends Vt{get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new ms,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new vt,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof ds))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Rt||e.target instanceof Jn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Rt&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Rt)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Rt&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){w(this._target instanceof Jn);let t=this._target.getTarget(e),n=i=>{if(!(i instanceof Rt))throw new TypeError("getTarget must return a Target.");return i};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){w(this._target instanceof Jn);let t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(w(this._initTarget!==null),this._initTarget instanceof Rt)return this._initTarget;let e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Rt)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=i=>(this.state==="canceled"?i._close():this._rememberTarget(i),this._emit("target",{target:i,request:e,isRoot:!0}),this._rootTarget=i,i);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new Zn(t,typeof e=="boolean"?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof ei))throw new TypeError("source must be a VideoSource.");if(Ud(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new cl(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof us))throw new TypeError("source must be an AudioSource.");Ud(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ll(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Ia))throw new TypeError("source must be a SubtitleSource.");Ud(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ul(this._tracks.length+1,this,e,n))}setMetadataTags(e){if(yp(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let t=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),i=t[e.type].max;if(n===i)throw new Error(i===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${i} ${e.type} track${i===1?"":"s"}.`);let s=t.total.max;if(this._tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){let a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){let e=this.format.getSupportedTrackCounts();for(let n of iv){let i=this._tracks.reduce((a,o)=>a+(o.type===n?1:0),0),s=e[n].min;if(i<s)throw new Error(s===e[n].max?`${this.format._name} requires exactly ${s} ${n} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${n} track${s===1?"":"s"}.`)}let t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(we._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let n=await this._mutex.acquire();try{await this._muxer.start();let i=this._tracks.map(s=>s.source._start());await Promise.all(i)}finally{n()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return we._warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&we._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let t=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(n=>n._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(we._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{let t=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){let n=await this._rootWriterPromise;n.finalized||(await n.flush(),await n.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}};var U0=Symbol.for("mediabunny loaded");globalThis[U0]&&we._error(`[WARNING]
|
|
1959
|
+
Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[U0]=!0;var sv=(()=>{let r=[];for(let e=0;;e++){let t=Math.round(64*2**(e/2));if(t>4096)break;r.push(t)}return r})();function ps(r,e){if(e)return 4096;let t=Math.max(1,Math.round(Math.max(r.width,r.height)));return Math.min(t,4096)}function $r(r,e){let t=Number.isFinite(r)?Math.max(0,r):e;if(t>=e)return e;let n=e/Math.SQRT2;for(let i of sv){if(i>=n)return e;if(i>=t)return i}return e}function Ma(r){return $r(0,r)}function gs(r,e){let t=Math.max(e.width,e.height,1),n=r/t;return{width:Math.max(1,Math.round(e.width*n)),height:Math.max(1,Math.round(e.height*n))}}var av=512*1024*1024,ov=2e3,Nd=5e3,cv=3e4,lv=6e4,uv=3,dv=2,hv=16*1024*1024,dl=class{_host;_budget;_policy="interactive";_entries=new Map;_pass=0;_inflight=0;constructor(e,t=av){this._host=e,this._budget=t}get policy(){return this._policy}setPolicy(e){this._policy=e}has(e){return(this._entries.get(e)?.levels.length??0)>0}intrinsicSize(e){return this._entries.get(e)?.intrinsic??null}load(e){let t=this._entry(e);return t.levels.length>0?Promise.resolve():(t.loading??=this._host.decode(e,(n,i)=>(this._learn(t,n,i),this._policy==="exact"?Ma(t.cap):t.lastDemand!==void 0?this._interactiveEdge(t,t.lastDemand):$r(Math.min(Math.max(n.width,n.height),this._host.surfaceEdge()),t.cap))).then(n=>{this._learn(t,n.intrinsic,n.vector),this._add(t,n),this._enforceBudget()}).finally(()=>{t.loading=null,this._pump()}),t.loading)}beginPass(){this._pass++}select(e,t){let n=this._entry(e),i=this._host.now(),s=t!==void 0&&Number.isFinite(t)&&t>0?t:1/0;if(n.levels.length===0)return Number.isFinite(s)&&(n.lastDemand=Math.max(n.lastDemand??0,s)),n.missedPass=this._pass,null;let a=Math.min(s,n.cap);n.passNeed=Math.max(n.passNeed,a),n.passDraws++,n.lastUsed=i;let o;if(this._policy==="exact"){let c=$r(a,n.cap),l=n.levels.find(u=>u.edge===c);!l&&!n.failed.has(c)&&n.wanted.add(c),o=l??fv(n.levels,c)}else o=n.levels.find(c=>c.edge>=a)??n.levels[n.levels.length-1],o.edge<2*a&&(n.passAllOver=!1);return o.lastSelected=i,o.selectedPass=this._pass,o}endPass(){let e=this._host.now();for(let t of this._entries.values()){let n=t.levels[t.levels.length-1];if(t.passDraws>0&&n)if(t.lastDemand=t.passNeed,this._policy==="exact"){for(let i of t.wanted)this._request(t,i,!1);t.wanted.clear()}else t.short=n.edge<t.passNeed,t.short?this._request(t,this._interactiveEdge(t,t.passNeed),!0):t.queue=t.queue.filter(i=>i<=n.edge),t.passAllOver&&!N0(n)?(t.overSince??=e,e-t.overSince>=Nd&&this._request(t,this._interactiveEdge(t,t.passNeed),!0)):t.overSince=null;else t.short=!1;t.passNeed=0,t.passDraws=0,t.passAllOver=!0,this._ageOut(t,e)}this._enforceBudget(),this._pump()}hasPending(){for(let e of this._entries.values())if(this._blocks(e))return!0;return!1}async warm(){if(this._policy==="interactive"){let t=!1;for(let n=0;n<64;n++){let i=[...this._entries.values()].filter(s=>this._blocks(s)).map(s=>s.loading);if(i.length===0)break;t=!0,await Promise.all(i.map(s=>s.catch(()=>{})))}return t}let e=!1;for(let t of this._entries.values()){for(let n of t.wanted)this._request(t,n,!1);t.wanted.clear()}this._pump();for(let t=0;t<64;t++){let n=[...this._entries.values()].map(i=>i.job??i.loading).filter(i=>i!==null);if(n.length===0)break;e=!0,await Promise.all(n.map(i=>i.catch(()=>{}))),this._pump()}return e}hasUpgrades(){if(this._policy!=="interactive")return!1;for(let e of this._entries.values())if(this._upgrading(e))return!0;return!1}async warmUpgrades(){let e=!1;for(let t=0;t<64&&this._policy==="interactive";t++){this._pump();let n=[...this._entries.values()].filter(a=>this._upgrading(a));if(n.length===0)break;let i=n.flatMap(a=>a.job?[a.job]:[]),s=i.length>0?i:[...this._entries.values()].flatMap(a=>a.job?[a.job]:[]);if(s.length===0)break;await Promise.all(s.map(a=>a.catch(()=>{}))),i.length>0&&(e=!0)}return e}stats(){let e=0,t=0,n=0;for(let i of this._entries.values()){e+=i.levels.length;for(let s of i.levels)t+=ys(s);n+=this._host.sourceBytes(i.src)}return{sources:this._entries.size,levels:e,levelBytes:t,sourceBytes:n,inflight:this._inflight}}levelsOf(e){return this._entries.get(e)?.levels??[]}dispose(){for(let e of this._entries.values()){for(let t of e.levels)this._host.released(e.src,t);e.levels=[],e.queue=[]}this._entries.clear()}_entry(e){let t=this._entries.get(e);return t||(t={src:e,intrinsic:null,vector:!1,cap:1,levels:[],lastDemand:void 0,lastUsed:this._host.now(),passNeed:0,passDraws:0,passAllOver:!0,overSince:null,wanted:new Set,queue:[],job:null,failed:new Set,loading:null,missedPass:-1,short:!1},this._entries.set(e,t)),t}_blocks(e){return this._policy==="exact"?e.job!==null||e.queue.length>0||e.wanted.size>0||e.loading!==null:e.levels.length===0&&e.missedPass===this._pass&&e.loading!==null}_upgrading(e){return e.short&&e.levels.length>0&&(e.job!==null||e.queue.length>0)}_interactiveEdge(e,t){return $r(Math.min(t*dv,e.cap),e.cap)}_learn(e,t,n){e.intrinsic={width:t.width,height:t.height},e.vector=n,e.cap=ps(t,n)}_add(e,t){let n=e.levels.findIndex(s=>s.edge===t.edge);n>=0&&(this._host.released(e.src,e.levels[n]),e.levels.splice(n,1));let i={edge:t.edge,width:t.width,height:t.height,pixels:t.pixels,gpu:null,lastSelected:this._host.now(),selectedPass:this._pass};e.levels.push(i),e.levels.sort((s,a)=>s.edge-a.edge)}_request(e,t,n){e.failed.has(t)||!e.intrinsic||e.levels.some(i=>i.edge===t)||(n?e.queue=[t]:e.queue.includes(t)||e.queue.push(t))}_pump(){for(let e of this._entries.values()){if(this._inflight>=uv)return;if(e.job||e.loading)continue;let t=this._nextEdge(e);if(t===void 0)continue;let n=t;this._inflight++,e.job=this._host.decode(e.src,()=>n).then(i=>{if(this._learn(e,i.intrinsic,i.vector),!this._entries.has(e.src)){this._host.released(e.src,{...i,gpu:null,lastSelected:0,selectedPass:0});return}this._add(e,i),this._enforceBudget()},i=>{e.failed.add(n),this._host.onError?.(e.src,i)}).finally(()=>{this._inflight--,e.job=null,this._pump()})}}_nextEdge(e){for(let t=e.queue.shift();t!==void 0;t=e.queue.shift()){if(this._policy==="interactive"&&e.lastDemand!==void 0){let n=Math.min(e.lastDemand,e.cap),i=e.levels[e.levels.length-1];if(i&&t>i.edge&&i.edge>=n)continue;t<n&&(t=this._interactiveEdge(e,n))}if(!e.failed.has(t)&&!e.levels.some(n=>n.edge===t))return t}}_ageOut(e,t){if(e.levels.length<=1)return;let n=e.levels[e.levels.length-1],i=e.levels.filter(s=>t-s.lastSelected<ov||s===n&&N0(s));if(i.length!==e.levels.length){i.length===0&&i.push(e.levels.reduce((s,a)=>a.lastSelected>s.lastSelected?a:s));for(let s of e.levels)i.includes(s)||this._host.released(e.src,s);e.levels=i}}_total(){let e=0;for(let t of this._entries.values()){for(let n of t.levels)e+=ys(n);e+=this._host.sourceBytes(t.src)}return e}_enforceBudget(){let e=this._total();if(e<=this._budget)return;let t=this._host.now(),n=[];for(let i of this._entries.values()){let s=i.levels.some(a=>a.selectedPass>=this._pass);i.levels.forEach((a,o)=>{a.selectedPass>=this._pass||!s&&o===0||n.push({entry:i,level:a})})}n.sort((i,s)=>i.level.lastSelected-s.level.lastSelected||ys(s.level)-ys(i.level));for(let{entry:i,level:s}of n){if(e<=this._budget)return;i.levels.length<=1||(i.levels=i.levels.filter(a=>a!==s),this._host.released(i.src,s),e-=ys(s))}if(this._policy==="interactive")for(let i of this._entries.values()){if(i.lastDemand===void 0)continue;let s=$r(i.lastDemand,i.cap),a=i.levels[i.levels.length-1];a&&a.edge>s&&this._request(i,s,!0)}for(let i of this._entries.values()){if(e<=this._budget)break;if(t-i.lastUsed<cv||i.levels.length===0)continue;let s=i.levels[0];for(let o of i.levels.slice(1))this._host.released(i.src,o),e-=ys(o);i.levels=[s];let a=Ma(i.cap);s.edge>a&&this._request(i,a,!0)}for(let i of this._entries.values()){if(e<=this._budget)break;if(t-i.lastUsed<lv)continue;let s=this._host.sourceBytes(i.src);s!==0&&(this._host.dropSource(i.src),e-=s)}}};function ys(r){return r.width*r.height*4*(r.gpu?2:1)}function N0(r){return r.width*r.height*4<=hv}function fv(r,e){let t=r[0];for(let n of r){let i=Math.abs(Math.log(n.edge/e)),s=Math.abs(Math.log(t.edge/e));(i<s||i===s&&n.edge>t.edge)&&(t=n)}return t}var mv=512*1024*1024,z0=96,V0=32;function H0(r){if(!r||!(r.width>0)||!(r.height>0))return{forward:z0,back:V0};let e=mv/(r.width*r.height*4);return{forward:Math.max(4,Math.min(z0,Math.floor(e*.75))),back:Math.max(1,Math.min(V0,Math.floor(e*.25)))}}var hl=class{level;_cap;_passNeed=0;_passDraws=0;_passAllOver=!0;_overSince=null;constructor(e,t,n,i){this._cap=ps(e,!1),this.level=t==="exact"?Ma(this._cap):$r(n??Math.min(Math.max(e.width,e.height),i),this._cap)}get cap(){return this._cap}note(e){let t=e!==void 0&&Number.isFinite(e)&&e>0?Math.min(e,this._cap):this._cap;this._passNeed=Math.max(this._passNeed,t),this._passDraws++,this.level<2*t&&(this._passAllOver=!1)}accepts(e,t){return e===void 0?!0:t==="exact"?e===this.level:e>=this.level}endPass(e,t,n){let i=this._passDraws,s=this._passNeed,a=this._passAllOver;if(this._passDraws=0,this._passNeed=0,this._passAllOver=!0,i===0)return!1;let o=$r(s,this._cap),c=this.level;return e==="exact"?this.level=o:this.level<s?(this.level=o,this._overSince=null):a&&!t?(this._overSince??=n,n-this._overSince>=Nd&&(this.level=o,this._overSince=null)):this._overSince=null,this.level!==c}};function W0(r){let{data:e}=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function yv(r){return/\.svg(?:[?#]|$)/i.test(r)}var wv={image:[(r,e)=>r.getImageMeta(e)],video:[(r,e)=>r.getVideoMeta(e)],media:[(r,e)=>r.getAudioMeta(e),(r,e)=>r.getVideoMeta(e)]},jt=class r extends gv{canvasKit;fontMgr;disposed=!1;surface=null;videoSessions=new Map;videoFrames=new Map;videoEchoFrames=new Map;videoPlayhead=new Map;pendingVideoFrames=new Map;pendingEchoFrames=new Map;echoDecodes=new Map;videoFrameClaims=new Map;videoAltSlots=new Map;videoDemand=new Map;playing=!1;decodePolicy="interactive";images;imageSources=new Map;reportedImageErrors=new Set;audioBuffers=new Map;audioCtx=null;fps;registeredFontFamilies=new Set;unknownFontFamilies=new Set;paragraphCache=new fo;fontEpoch=0;static ECHO_CACHE_LIMIT=48;static ALT_SLOT_LIMIT=16;constructor(e,t,n,i){super(t,n),this.canvasKit=e,this.fps=i,this.fontMgr=e.TypefaceFontProvider.Make(),this.images=new dl({now:()=>performance.now(),decode:(s,a)=>this.decodeImage(s,a),released:(s,a)=>{a.gpu?.delete(),a.gpu=null},sourceBytes:s=>this.imageSources.get(s)?.bytes??0,dropSource:s=>this.imageSources.delete(s),surfaceEdge:()=>this.surfaceEdge(),onError:(s,a)=>{this.disposed||this.reportedImageErrors.has(s)||(this.reportedImageErrors.add(s),console.error(`[WebStorageAdapter] image decode failed for ${s}:`,a))}})}getCanvasKit(){return this.canvasKit}setCatalog(e){super.setCatalog(e),this.unknownFontFamilies.clear()}setDecodePolicy(e){this.decodePolicy=e,this.images.setPolicy(e)}getDecodePolicy(){return this.decodePolicy}hasPendingDecodes(){return this.pendingVideoFrames.size>0||this.pendingEchoFrames.size>0||this.echoDecodes.size>0||xl()||this.images.hasPending()}async warmPendingDecodes(){let[e,t]=await Promise.all([this.warmVideo(),this.images.warm()]);return e||t}hasPendingUpgrades(){return this.images.hasUpgrades()}warmPendingUpgrades(){return this.images.warmUpgrades()}warmPendingVideo(){return this.warmPendingDecodes()}_decodeStats(){let e=0,t=0,n=0,i=new Set,s=a=>{for(let{bitmap:o}of a.values())i.has(o)||(i.add(o),n+=(o.width??0)*(o.height??0)*4)};for(let a of this.videoFrames.values())e+=a.size,s(a);for(let a of this.videoEchoFrames.values())t+=a.size,s(a);return{images:this.images.stats(),video:{sessions:this.videoSessions.size,windowFrames:e,echoFrames:t,frameBytes:n}}}async loadImage(e){await this.images.load(e)}getCKImage(e,t){let n=this.images.select(e,t);return n?(n.gpu??=this.makeCKImageFromPixels(n.pixels,n.width,n.height),n.gpu):null}getImagePixels(e,t){return this.images.select(e,t)}getImageSize(e){return this.images.intrinsicSize(e)??this.catalogImageSize(e)}catalogImageSize(e){try{let t=this.catalog.getImageMeta(e);return t.width>0&&t.height>0?{width:t.width,height:t.height}:null}catch{return null}}async decodeImage(e,t){let n=this.assetUrl(e,"image");if(yv(n)){let u=await this.svgSource(e,n),d=u.natural,h=t(d,!0),f=gs(h,d),m=new OffscreenCanvas(f.width,f.height).getContext("2d",{willReadFrequently:!0});if(!m)throw new Error(`loadImage(${e}): could not get 2d context`);return m.drawImage(u.svg,0,0,f.width,f.height),{pixels:W0(m.getImageData(0,0,f.width,f.height)),...f,intrinsic:d,vector:!0,edge:h}}let i=await this.rasterSource(e,n),s=this.catalogImageSize(e),a=null;s||(a=await createImageBitmap(i),s={width:a.width,height:a.height});let o=t(s,!1),c=o>=ps(s,!1)&&Math.max(s.width,s.height)<=4096,l;if(c)l=a??await createImageBitmap(i);else{let u=gs(o,s);try{l=await createImageBitmap(a??i,{resizeWidth:u.width,resizeHeight:u.height,resizeQuality:"high"})}finally{a?.close()}}try{let d=new OffscreenCanvas(l.width,l.height).getContext("2d",{willReadFrequently:!0});if(!d)throw new Error(`loadImage(${e}): could not get 2d context`);return d.drawImage(l,0,0),{pixels:W0(d.getImageData(0,0,l.width,l.height)),width:l.width,height:l.height,intrinsic:s,vector:!1,edge:o}}finally{l.close()}}async rasterSource(e,t){let n=this.imageSources.get(e);if(n?.blob)return n.blob;let i=await this.fetchBlob(t);return this.imageSources.set(e,{blob:i,bytes:i.size}),i}async svgSource(e,t){let n=this.imageSources.get(e);if(n?.svg&&n.natural)return n;let i=await(await this.fetchBlob(t)).text(),s=new Image;s.decoding="sync",await new Promise((c,l)=>{s.onload=()=>c(),s.onerror=()=>l(new Error(`loadImage(${e}): failed to decode SVG`)),s.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(i)}`});let a={width:s.naturalWidth>0?s.naturalWidth:300,height:s.naturalHeight>0?s.naturalHeight:300},o={svg:s,natural:a,bytes:i.length};return this.imageSources.set(e,o),o}surfaceEdge(){let e=this.surface;return e&&typeof e.width=="function"&&typeof e.height=="function"?Math.max(e.width(),e.height()):Math.max(this.viewport.width,this.viewport.height)}async fetchBlob(e){let t=await gl(e);return t||th(e)}assetUrl(e,t){let n=wv[t];for(let i of n)try{let s=i(this.catalog,e).src;if(s)return s}catch{}return e}canvas3DTextures=new Map;upload3DFrame(e,t,n,i){let s=this.surface;if(!s)return null;let a={width:n,height:i,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB},o=this.canvas3DTextures.get(e);if(o&&(o.width()!==n||o.height()!==i)&&(o.delete(),this.canvas3DTextures.delete(e),o=void 0),!o){let c=s.makeImageFromTextureSource(t,a,!1);return c?(this.canvas3DTextures.set(e,c),c):null}return s.updateTextureFromSource(o,t,!1),o}release3DTexture(e){this.canvas3DTextures.get(e)?.delete(),this.canvas3DTextures.delete(e)}setSurface(e){if(e!==this.surface){for(let t of this.videoSessions.values())t.textureImage?.delete(),t.textureImage=null,t.uploadedTs=null,t.uploadedBitmap=null;this.clearVideoAltSlots();for(let t of this.canvas3DTextures.values())t.delete();this.canvas3DTextures.clear(),this.surface=e}}setPlaying(e){this.playing=e}beginRenderPass(){this.videoFrameClaims.clear(),this.images.beginPass()}endRenderPass(){this.images.endPass();let e=performance.now();for(let[t,n]of this.videoSessions){if(!(n.levels?.endPass(this.decodePolicy,this.playing,e)??!1))continue;this.videoDemand.set(t,n.levels.level);let s=gs(n.levels.level,n.intrinsic);n.width=s.width,n.height=s.height,(this.videoFrameClaims.get(t)??[]).forEach((o,c)=>{let l=o*n.frameStep;if(c===0)this.pendingVideoFrames.has(t)||this.pendingVideoFrames.set(t,l);else{let u=this.pendingEchoFrames.get(t);u||(u=new Set,this.pendingEchoFrames.set(t,u)),u.add(l)}}),this.playing&&this.driveSequentialDecode(t,this.videoPlayhead.get(t)??0)}}async loadVideo(e,t,n,i=0,s){if(this.videoSessions.has(e))return;let a=this.assetUrl(e,"video"),o=await gl(a),c=new Gr({formats:dd,source:o?new ha(o):new fa(a)}),l=await c.getPrimaryVideoTrack();if(!l)throw c.dispose(),new Error(`loadVideo(${e}): no video track found`);let u=new Aa(l),d=await c.computeDuration(),h=await this.probeFirstFrame(u),f=this.catalogVideoSize(e)??await this.trackDisplaySize(l,h),p=new hl(f,this.decodePolicy,this.videoDemand.get(e),this.surfaceEdge()),m=gs(p.level,f);this.videoSessions.set(e,{input:c,sink:u,durationSec:d,frameStep:h.frameStep,width:m.width,height:m.height,intrinsic:f,levels:p,canvas:null,textureImage:null,uploadedTs:null,decoding:!1}),this.videoFrames.set(e,new Map),await this.decodeAt(e,i)}getVideoSize(e){return this.videoSessions.get(e)?.intrinsic??this.catalogVideoSize(e)}catalogVideoSize(e){try{let t=this.catalog.getVideoMeta(e);return t.width>0&&t.height>0?{width:t.width,height:t.height}:null}catch{return null}}async trackDisplaySize(e,t){try{let n=await e.getDisplayWidth(),i=await e.getDisplayHeight();if(n>0&&i>0)return{width:n,height:i}}catch{}return{width:Math.max(1,t.width),height:Math.max(1,t.height)}}getVideoFrame(e,t){let n=this.videoSessions.get(e),i=this.videoFrames.get(e);if(!n||!i||!this.surface)return null;Number.isFinite(t)||(t=0),this.videoPlayhead.set(e,t);let s=this.nearestDecoded(i,t,n.frameStep),a=this.quantizeTs(t,n.frameStep);return!!s&&this.quantizeTs(s.timestamp,n.frameStep)===a&&this.accepts(n,s)?this.playing&&this.driveSequentialDecode(e,t):(this.pendingVideoFrames.set(e,t),this.playing&&this.driveSequentialDecode(e,t)),s?this.uploadFrame(e,n,s):null}claimVideoFrame(e,t,n){let i=this.videoSessions.get(e);if(!i||!this.surface)return null;Number.isFinite(t)||(t=0),i.levels?.note(n);let s=this.quantizeTs(t,i.frameStep),a=this.videoFrameClaims.get(e);a||(a=[],this.videoFrameClaims.set(e,a));let o=a.indexOf(s);if(o===0)return i.textureImage;if(o>0)return this.videoAltSlots.get(e)?.[o-1]?.image??null;if(a.length===0){let u=this.getVideoFrame(e,t);return u&&a.push(i.uploadedTs??s),u}let c=Math.min(a.length-1,r.ALT_SLOT_LIMIT-1),l=this.uploadAltFrame(e,i,t,c);return l&&a.push(s),l}clearVideoAltSlots(){for(let e of this.videoAltSlots.values())for(let t of e)t.image?.delete();this.videoAltSlots.clear()}uploadAltFrame(e,t,n,i){if(!this.surface)return null;let a=this.decodedFrameFor(e,t,n);if(!a)return null;let o=this.videoAltSlots.get(e);o||(o=[],this.videoAltSlots.set(e,o));let c=o[i];c||(c={image:null,uploadedTs:null},o[i]=c);let l=this.quantizeTs(a.timestamp,t.frameStep);return c.image&&c.uploadedTs===l&&(c.bitmap===void 0||c.bitmap===a.bitmap)||(this.uploadInto(c,a,t),c.uploadedTs=c.image?l:null),c.image}uploadInto(e,t,n){let i=this.surface,s=t.bitmap.width||n.width,a=t.bitmap.height||n.height;e.image&&(e.width!==s||e.height!==a)&&(e.image.delete(),e.image=null),e.image?i.updateTextureFromSource(e.image,t.bitmap):e.image=i.makeImageFromTextureSource(t.bitmap,{width:s,height:a,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB}),e.width=s,e.height=a,e.bitmap=e.image?t.bitmap:null}decodedFrameFor(e,t,n){let i=t.frameStep,s=Math.max(0,Math.min(n,t.durationSec)),a=f=>this.accepts(t,f),o=this.videoEchoFrames.get(e),c=this.videoFrames.get(e),l=this.nearestWithin(o,s,i,a)??this.nearestWithin(c,s,i,a);if(l)return l;let u=this.pendingEchoFrames.get(e);u||(u=new Set,this.pendingEchoFrames.set(e,u)),u.add(s),this.playing&&this.decodeEchoFrameAt(e,s);let d=o?this.nearestDecoded(o,s,i):null,h=c?this.nearestDecoded(c,s,i):null;return d?h?Math.abs(d.timestamp-s)<=Math.abs(h.timestamp-s)?d:h:d:h}getVideoDuration(e){return this.videoSessions.get(e)?.durationSec??0}getVideoFrameImage(e,t,n){let i=this.videoSessions.get(e);if(!i||!this.surface||!Number.isFinite(t))return null;i.levels?.note(n);let s=Math.max(0,Math.min(t,i.durationSec)),a=i.frameStep,o=l=>this.accepts(i,l),c=this.nearestWithin(this.videoEchoFrames.get(e),s,a,o)??this.nearestWithin(this.videoFrames.get(e),s,a,o);if(!c){let l=this.pendingEchoFrames.get(e);return l||(l=new Set,this.pendingEchoFrames.set(e,l)),l.add(s),null}return this.surface.makeImageFromTextureSource(c.bitmap,{width:c.bitmap.width||i.width,height:c.bitmap.height||i.height,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB})}uploadFrame(e,t,n){if(!this.surface)return null;let i=this.quantizeTs(n.timestamp,t.frameStep);if(t.textureImage&&t.uploadedTs===i&&(t.uploadedBitmap==null||t.uploadedBitmap===n.bitmap))return t.textureImage;let s={image:t.textureImage,uploadedTs:t.uploadedTs,width:t.textureWidth,height:t.textureHeight};return this.uploadInto(s,n,t),t.textureImage=s.image,t.textureWidth=s.width,t.textureHeight=s.height,t.uploadedBitmap=s.bitmap,t.uploadedTs=t.textureImage?i:null,t.textureImage}accepts(e,t){return e.levels?e.levels.accepts(t.level,this.decodePolicy):!0}async warmVideo(){let e=[...this.pendingVideoFrames];this.pendingVideoFrames.clear();let t=[...this.pendingEchoFrames].flatMap(([s,a])=>[...a].map(o=>[s,o]));this.pendingEchoFrames.clear();let n=await Tl(),i=[...this.echoDecodes.values()];return e.length===0&&t.length===0&&i.length===0?n:(await Promise.all([...e.map(([s,a])=>this.decodeAt(s,a)),...t.map(([s,a])=>this.decodeEchoFrameAt(s,a)),...i]),!0)}driveSequentialDecode(e,t){let n=this.videoSessions.get(e);if(!n||n.decoding||!n.sink||!this.videoFrames.get(e))return;let i=n.frameStep,{forward:s}=this.windowFrames(n),a=Math.min(n.durationSec,t+s*i);t>=a||(n.decoding=!0,(async()=>{try{for await(let o of n.sink.samples(t,a+i)){let c=this.videoFrames.get(e);if(this.disposed||!c){o.close();break}let l=this.quantizeTs(o.timestamp,i),u=c.get(l);u&&this.accepts(n,u)?o.close():this.storeFrame(e,c,l,await this.snapshot(n,o));let d=this.videoPlayhead.get(e)??t;if(!this.playing||d<t-i||d>a)break}this.evictVideoWindow(e,this.videoPlayhead.get(e)??t,i)}catch(o){this.disposed||console.error(`[WebStorageAdapter] sequential decode failed for ${e}:`,o)}finally{n.decoding=!1}})())}async decodeAt(e,t){let n=this.videoSessions.get(e);if(!n||!Number.isFinite(t))return;let i=Math.max(0,Math.min(t,n.durationSec)),s=this.quantizeTs(i,n.frameStep),a=this.videoFrames.get(e),o=a?.get(s);if(!(!a||o&&this.accepts(n,o)))try{let c=await n.sink.getSample(i);if(!c)return;if(this.disposed){c.close();return}let l=await this.snapshot(n,c),u=this.videoFrames.get(e);if(!u){l.bitmap.close();return}this.storeFrame(e,u,this.quantizeTs(l.timestamp,n.frameStep),l),this.evictVideoWindow(e,i,n.frameStep)}catch(c){this.disposed||console.error(`[WebStorageAdapter] video decode failed for ${e}@${i}:`,c)}}storeFrame(e,t,n,i){let s=this.videoSessions.get(e),a=t.get(n);if(a&&s&&this.accepts(s,a)&&!this.accepts(s,i)){i.bitmap.close();return}a&&a!==i&&this.videoEchoFrames.get(e)?.get(n)!==a&&a.bitmap.close(),t.set(n,i)}decodeEchoFrameAt(e,t){let n=this.videoSessions.get(e);if(!n||!Number.isFinite(t))return Promise.resolve();let i=Math.max(0,Math.min(t,n.durationSec)),s=this.quantizeTs(i,n.frameStep),a=this.videoEchoFrames.get(e)?.get(s);if(a&&this.accepts(n,a))return Promise.resolve();let o=`${e}#${s}`,c=this.echoDecodes.get(o);if(c)return c;let l=this.decodeEchoFrameNow(e,n,i,s).finally(()=>this.echoDecodes.delete(o));return this.echoDecodes.set(o,l),l}async decodeEchoFrameNow(e,t,n,i){let s=this.videoEchoFrames.get(e),a=this.videoFrames.get(e)?.get(i);try{if(s||(s=new Map,this.videoEchoFrames.set(e,s)),a&&this.accepts(t,a))this.replaceEcho(e,s,i,a);else{let o=await t.sink.getSample(n);if(!o)return;if(this.disposed){o.close();return}let c=await this.snapshot(t,o);if(s=this.videoEchoFrames.get(e),!s){c.bitmap.close();return}this.replaceEcho(e,s,this.quantizeTs(c.timestamp,t.frameStep),c)}this.trimEchoCache(e)}catch(o){this.disposed||console.error(`[WebStorageAdapter] echo decode failed for ${e}@${n}:`,o)}}replaceEcho(e,t,n,i){let s=t.get(n);s&&s!==i&&this.videoFrames.get(e)?.get(n)!==s&&s.bitmap.close(),t.set(n,i)}trimEchoCache(e){let t=this.videoEchoFrames.get(e);if(t)for(;t.size>r.ECHO_CACHE_LIMIT;){let n=t.keys().next().value;if(n===void 0)break;let i=t.get(n);i&&this.videoFrames.get(e)?.get(n)!==i&&i.bitmap.close(),t.delete(n)}}snapshot(e,t){let n=e.levels.level,{width:i,height:s}=gs(n,e.intrinsic);try{let a=e.canvas;(!a||a.width!==i||a.height!==s)&&(a=new OffscreenCanvas(i,s),e.canvas=a);let o=a.getContext("2d");if(!o)throw new Error("video snapshot: could not get 2d context");o.imageSmoothingEnabled=!0,o.imageSmoothingQuality="high",o.clearRect(0,0,i,s),t.drawWithFit(o,{fit:"fill"});let c=createImageBitmap(a),l=t.timestamp;return c.then(u=>({timestamp:l,bitmap:u,level:n}))}finally{t.close()}}windowFrames(e){return H0(e?{width:e.width,height:e.height}:null)}evictVideoWindow(e,t,n){let i=this.videoFrames.get(e);if(!i)return;let{forward:s,back:a}=this.windowFrames(this.videoSessions.get(e)),o=t-a*n,c=t+s*n,l=this.videoEchoFrames.get(e);for(let[u,d]of i)(d.timestamp<o||d.timestamp>c)&&(l?.get(u)!==d&&d.bitmap.close(),i.delete(u))}nearestDecoded(e,t,n){let i=e.get(this.quantizeTs(t,n));if(i)return i;let s=null,a=1/0;for(let o of e.values()){let c=Math.abs(o.timestamp-t);c<a&&(a=c,s=o)}return s}quantizeTs(e,t){return Math.round(e/t)}nearestWithin(e,t,n,i){if(!e||e.size===0)return null;let s=null,a=1/0;for(let o of e.values()){if(i&&!i(o))continue;let c=Math.abs(o.timestamp-t);c<a&&(a=c,s=o)}return s&&a<=n?s:null}async probeFirstFrame(e){try{let t=await e.getSample(0);if(!t)for await(let n of e.samples()){t=n;break}if(t){let n={frameStep:t.duration>0?t.duration:.03333333333333333,width:t.displayWidth,height:t.displayHeight};return t.close(),n}}catch{}return{frameStep:1/30,width:1,height:1}}makeCKImageFromPixels(e,t,n){return this.canvasKit.MakeImage({width:t,height:n,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB},e,4*t)}async loadAudio(e,t,n,i=0,s){if(this.audioBuffers.has(e))return;this.audioCtx||(this.audioCtx=new AudioContext);let a=await(await this.fetchBlob(this.assetUrl(e,"media"))).arrayBuffer(),o=await this.audioCtx.decodeAudioData(a);this.audioBuffers.set(e,o)}async fetchAudioData(e){return(await this.fetchBlob(this.assetUrl(e,"media"))).arrayBuffer()}getAudioBuffer(e){return this.audioBuffers.get(e)??null}async loadFont(e,t,n){if(this.registeredFontFamilies.has(t))return!0;let i=this.catalog.getFontFamilyMetas(t);if(i.length===0)return this.decodePolicy==="interactive"&&!this.unknownFontFamilies.has(t)&&(this.unknownFontFamilies.add(t),console.warn(`[WebStorageAdapter] No font manifest entry for "${e}"; shaping against the fallback face. Add it to the manifest font record.`)),!1;let s=[...new Set(i.map(o=>o.src))],a=await Promise.all(s.map(async o=>(await this.fetchBlob(o)).arrayBuffer()));for(let o of a)this.fontMgr.registerFont(new Uint8Array(o),t);return this.registeredFontFamilies.add(t),this.unknownFontFamilies.delete(t),this.fontEpoch++,!0}getFontMgr(){return this.fontMgr}getParagraphCache(){return this.paragraphCache}getFontEpoch(){return this.fontEpoch}dispose(){if(this.disposed)return;this.disposed=!0,this.paragraphCache.dispose(),this.images.dispose(),this.imageSources.clear();for(let t of this.canvas3DTextures.values())t.delete();this.canvas3DTextures.clear();let e=new Set;for(let t of this.videoFrames.values())for(let{bitmap:n}of t.values())n.close(),e.add(n);this.videoFrames.clear();for(let t of this.videoEchoFrames.values())for(let{bitmap:n}of t.values())e.has(n)||n.close();this.videoEchoFrames.clear();for(let t of this.videoSessions.values())t.textureImage?.delete(),t.input.dispose();this.videoSessions.clear(),this.clearVideoAltSlots(),this.videoPlayhead.clear(),this.videoFrameClaims.clear(),this.pendingVideoFrames.clear(),this.pendingEchoFrames.clear(),this.echoDecodes.clear(),this.surface=null,this.audioBuffers.clear(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close(),this.audioCtx=null,super.dispose()}};import bv from"@motionscript/canvaskit";var zd=null,fl=null;function kv(){return new URL("@motionscript/canvaskit/canvaskit.wasm",import.meta.url).href}async function Xr(r){if(zd)return zd;if(fl)return fl;let e=r??kv();return fl=bv({locateFile:()=>e}).then(t=>(zd=t,t)),fl}import{DEFAULT_OUTPUT as Sv,ManifestAssetCatalog as xv,Registry as Tv,resolveProjectDocument as Av}from"@motionscript/core";var vv=.2,_v=2e6,Cv=1e8;function G0(r,e,t){let n=r*e*t*vv;return Math.round(Math.min(Cv,Math.max(_v,n)))}var Pv=192e3,Ev=1,Iv=2,Mv={image:{},video:{},audio:{},font:{}},Vd=class{audioOptions;target=new ar;output;video;audio=null;constructor(e,t,n,i={},s={},a="avc"){this.audioOptions=s;let o=n.width!==e.width||n.height!==e.height;this.video=new Ea(e,{codec:a,bitrate:i.bitrate??G0(n.width,n.height,t),hardwareAcceleration:i.hardwareAcceleration??"no-preference",keyFrameInterval:i.keyFrameInterval??Ev,latencyMode:i.latencyMode??"quality",contentHint:i.contentHint??"detail",...i.bitrateMode!==void 0&&{bitrateMode:i.bitrateMode},...o&&{transform:{width:n.width,height:n.height,fit:"fill"}}}),this.output=new ri({format:new xn,target:this.target})}async start(e){this.output.addVideoTrack(this.video,{frameRate:e.fps}),e.hasAudio&&(this.audio=new ti({codec:"aac",bitrate:this.audioOptions.bitrate??Pv}),this.output.addAudioTrack(this.audio)),await this.output.start()}async addFrame(e,t){await this.video.add(e,t)}async addAudio(e){this.audio&&await this.audio.add(e)}async finalize(){this.video.close(),this.audio?.close(),await this.output.finalize();let e=this.target.buffer;if(!e)throw new Error("Export produced no data");return new Uint8Array(e)}};function q0(r){let e=Math.round(r);return e%2===0?e:e+1}var Fv=8192;function Rv(r,e){let t=Math.max(e.width,e.height),n=Math.max(1,Math.round(r));for(;n>1&&t*n>Fv;)n--;return n}async function Bv(r,e,t){if(!r||r==="avc")return"avc";try{if(await pd(r,{width:e.width,height:e.height,bitrate:G0(e.width,e.height,t)}))return r}catch{}return console.warn(`[motionscript] No ${r} encoder available; exporting as H.264 instead.`),"avc"}async function Hd(r){let{document:e,registry:t=new Tv,scale:n=1,filename:i="export.mp4",manifest:s=Mv,theme:a,includeAudio:o=!0,video:c,audio:l={},frames:u,onProgress:d,signal:h,wasmUrl:f,supersample:p=Iv,returnBytes:m=!1}=r,g=Av(e,r,Sv);if(g.tracks.length===0)return;h?.throwIfAborted();let y=g.viewport,b=g.fps,k={width:q0(y.width*n),height:q0(y.height*n)},T=Rv(p,k),x=n*T,v=document.createElement("canvas");v.width=k.width*T,v.height=k.height*T,v.style.display="none",document.body.appendChild(v);let M=await Xr(f),C=new xv(s),_=new jt(M,C,y,b),F=new cr(M,_);F.mount(v);let E=await Bv(c?.codec,k,b),O;try{O=await mu({project:g,registry:t,theme:a,scale:x,includeAudio:o,frames:u,renderContext:F,storageAdapter:_,assetCatalog:C,sink:new Vd(v,b,k,c,l,E),mixer:new rh(l.sampleRate,C),onProgress:d,signal:h})}finally{F.dispose(),document.body.removeChild(v)}if(!O)return;if(m)return O;let Q=new Blob([O.buffer],{type:"video/mp4"}),ye=URL.createObjectURL(Q),Z=document.createElement("a");Z.href=ye,Z.download=i,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(ye)}import{DEFAULT_OUTPUT as zv,resolveProjectDocument as Vv}from"@motionscript/core";import{DEFAULT_OUTPUT as j0,ManifestAssetCatalog as K0,frameSpecAtTime as Dv,Registry as Ov,resolveProjectDocument as Lv}from"@motionscript/core";var Uv={image:{},video:{},audio:{},font:{}};function Nv(r,e){if(r?.time!==void 0)return Dv(r.time,e);let t=r?.frame;return t===void 0||t==="first"?{kind:"first"}:t==="last"?{kind:"last"}:typeof t=="number"?{kind:"frame",frame:t}:t}function $0(r){return r==="jpeg"?"image/jpeg":"image/png"}var ws=class{canvas;renderContext;storageAdapter;catalog;canvasKit;ownsCanvas;viewportValue;fpsValue;scaleValue;surfaceScale;manifest;theme;registry;disposed=!1;drawn=!1;constructor(e,t){this.canvasKit=e,this.viewportValue=t.viewport??j0.viewport,this.fpsValue=t.fps??j0.fps,this.scaleValue=t.scale??1,this.surfaceScale=this.scaleValue,this.manifest=t.manifest??Uv,this.theme=t.theme,this.registry=t.registry??new Ov,this.ownsCanvas=t.canvas===void 0,this.canvas=t.canvas??document.createElement("canvas"),this.ownsCanvas&&(this.canvas.style.display="none",document.body.appendChild(this.canvas)),this.sizeCanvas(),this.catalog=new K0(this.manifest),this.storageAdapter=new jt(e,this.catalog,this.viewportValue,this.fpsValue),this.renderContext=new cr(e,this.storageAdapter),this.renderContext.mount(this.canvas)}get viewport(){return this.viewportValue}get fps(){return this.fpsValue}get scale(){return this.scaleValue}async render(e,t){this.assertLive();let n=t?.scale??this.scaleValue;n!==this.surfaceScale&&this.remount(n);let i=Lv(e,{viewport:this.viewportValue},{viewport:this.viewportValue,fps:this.fpsValue}),s=await pu({project:i,registry:this.registry,theme:this.theme,scale:n,renderContext:this.renderContext,storageAdapter:this.storageAdapter,assetCatalog:this.catalog,frame:Nv(t,i.fps)});return this.drawn=!0,s}setTheme(e){this.theme=e}setManifest(e){this.assertLive(),this.manifest=e,this.catalog=new K0(e),this.storageAdapter.setCatalog(this.catalog)}setViewport(e){this.assertLive(),!(e.width===this.viewportValue.width&&e.height===this.viewportValue.height)&&(this.viewportValue=e,this.renderContext.dispose(),this.storageAdapter=new jt(this.canvasKit,this.catalog,e,this.fpsValue),this.renderContext=new cr(this.canvasKit,this.storageAdapter),this.remount(this.scaleValue))}async toBytes(e){let t=await this.toBlob(e);return new Uint8Array(await t.arrayBuffer())}toBlob(e){let t=this.snapshotToCanvas(),{format:n="png",quality:i=.92}=e??{};return new Promise((s,a)=>{t.toBlob(o=>o?s(o):a(new Error("Still encode produced no data.")),$0(n),i)})}toDataURL(e){let{format:t="png",quality:n=.92}=e??{};return this.snapshotToCanvas().toDataURL($0(t),n)}dispose(){this.disposed||(this.disposed=!0,this.renderContext.dispose(),this.ownsCanvas&&this.canvas.remove())}snapshotToCanvas(){this.assertLive();let e=this.drawn?this.renderContext.snapshotPixels():void 0;if(!e)throw new Error("Nothing has been rendered yet.");let t=document.createElement("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");if(!n)throw new Error("Still encode: could not get a 2d context.");return n.putImageData(new ImageData(new Uint8ClampedArray(e.pixels),e.width,e.height),0,0),t}sizeCanvas(){this.canvas.width=this.viewportValue.width*this.surfaceScale,this.canvas.height=this.viewportValue.height*this.surfaceScale}remount(e){this.surfaceScale=e,this.drawn=!1,this.sizeCanvas(),this.renderContext.mount(this.canvas)}assertLive(){if(this.disposed)throw new Error("This StillRenderer has been disposed.")}};async function Wd(r={}){let e=await Xr(r.wasmUrl);return new ws(e,r)}async function Hv(r){let{registry:e,scale:t,manifest:n,theme:i,wasmUrl:s,frame:a,format:o="png",quality:c=.92}=r,l=Vv(r.document,r,zv);if(l.tracks.length===0)throw new Error("The project has no tracks to screenshot.");let u=await Wd({viewport:l.viewport,fps:l.fps,scale:t,manifest:n,theme:i,wasmUrl:s,registry:e});try{return{...await u.render(l,{frame:a}),bytes:await u.toBytes({format:o,quality:c})}}finally{u.dispose()}}var bs=class extends Error{segment;constructor(e,t){super(t),this.segment=e,this.name="ConcatMismatchError"}};function Wv(r,e){if(r.codec!==e.codec||r.codedWidth!==e.codedWidth||r.codedHeight!==e.codedHeight)return!1;let t=X0(r.description),n=X0(e.description);if(t===null||n===null)return t===n;if(t.length!==n.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==n[i])return!1;return!0}function X0(r){return r?ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r):null}var qv=192e3;async function Gv(r,e={}){if(r.length===0)throw new Error("concatVideoSegments: no segments");if(r.length===1&&!e.audio&&!e.stream)return r[0];let t=[];for(let l=0;l<r.length;l++){let d=await new Gr({source:new da(r[l]),formats:[$c]}).getPrimaryVideoTrack();if(!d)throw new bs(l,`Segment ${l} has no video track.`);let h=await d.getDecoderConfig();if(!h)throw new bs(l,`Segment ${l} has no decoder configuration.`);if(t.length>0&&!Wv(t[0].config,h))throw new bs(l,`Segment ${l} was encoded differently from segment 0 (${t[0].config.codec} ${t[0].config.codedWidth}x${t[0].config.codedHeight} vs ${h.codec} ${h.codedWidth}x${h.codedHeight}); joining them would decode as garbage.`);t.push({track:d,config:h,duration:await d.computeDuration()})}let n=e.stream?new Ca(e.stream):new ar,i=new ri({format:new xn,target:n}),s=new Pa(t[0].track.codec);i.addVideoTrack(s);let a=e.audio?new ti({codec:"aac",bitrate:e.audioBitrate??qv}):null;a&&i.addAudioTrack(a),await i.start();let o=0;for(let l of t){let u=!0;for await(let d of new bn(l.track).packets())await s.add(d.clone({timestamp:d.timestamp+o}),u?{decoderConfig:l.config}:void 0),u=!1;o+=l.duration}if(a&&e.audio&&await a.add(e.audio),s.close(),a?.close(),await i.finalize(),e.stream)return new Uint8Array(0);let c=n.buffer;if(!c)throw new Error("concatVideoSegments produced no data");return new Uint8Array(c)}import{DEFAULT_OUTPUT as jv,ManifestAssetCatalog as Kv,AssetTimeline as $v,Registry as Xv,resolveProjectDocument as Qv}from"@motionscript/core";var ml=class{storageAdapter;constructor(e){this.storageAdapter=e}measureText(e,t,n,i=400,s=0,a="normal"){return mo(this.storageAdapter.getCanvasKit(),this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),this.storageAdapter.getFontEpoch(),e,t,n,i,s,a)}layoutTextBlock(e){return po(this.storageAdapter.getCanvasKit(),this.storageAdapter.getFontMgr(),e)}};var ni=class extends ml{};var Yv={image:{},video:{},audio:{},font:{}};async function Zv(r){let{registry:e=new Xv,manifest:t=Yv,sampleRate:n,wasmUrl:i}=r,s=Qv(r.document,r,jv);if(s.tracks.length===0)return null;let a=s.viewport,o=s.fps,c=await Xr(i),l=new Kv(t),u=new jt(c,l,a,o),d=new ni(u),h=new $v(s,{registry:e,viewport:a,fps:o,assets:l,measurer:d},{assets:!1});try{let f=h.run(),p=fu(f);return p.length===0?null:await yl(p,f.totalDuration,{sampleRate:n,catalog:l})}finally{h.dispose(),u.dispose()}}import{Ticker as Jv}from"@motionscript/core";var Fa=class extends Jv{context;ownsContext;fps;playStartCtxTime=0;seekOffset=0;speed=1;reverse=!1;rafId=null;seekEpoch=0;silentSource=null;constructor(e){super(),this.context=e.context??new AudioContext,this.ownsContext=!e.context,this.fps=e.fps}getContext(){return this.context}seek(e){let t=Math.max(0,Math.min(e,this.duration));this.seekOffset=t,this.playStartCtxTime=this.context.currentTime,this.seekEpoch++,this.setCurrentTime(t)}play(e=1,t=!1){this.speed=e,this.reverse=t,this.seekOffset=this.currentTime,this.context.state==="suspended"&&this.context.resume().then(()=>{!this.isPlaying&&this.context.state==="running"&&this.context.suspend()},n=>{console.error("[WebTicker] The audio context could not resume:",n),this.pause()}),this.playStartCtxTime=this.context.currentTime,this.startSilentTicker(),super.play(e,t),this.startLoop()}pause(){this.seekOffset=this.currentTime,this.stopLoop(),this.stopSilentTicker(),this.context.state==="running"&&this.context.suspend(),super.pause()}startSilentTicker(){this.stopSilentTicker();let e=Math.max(.001,this.duration-this.seekOffset),t=this.context.sampleRate,n=this.context.createBuffer(1,Math.ceil(e*t),t),i=this.context.createBufferSource();i.buffer=n,i.connect(this.context.destination),i.start(),this.silentSource=i}stopSilentTicker(){if(this.silentSource){try{this.silentSource.onended=null,this.silentSource.stop(),this.silentSource.disconnect()}catch{}this.silentSource=null}}position(){let e=(this.context.currentTime-this.playStartCtxTime)*this.speed,t=this.reverse?this.seekOffset-e:this.seekOffset+e,n=Math.max(0,Math.min(t,this.duration));return{time:n,ended:this.reverse?n<=0:n>=this.duration}}startLoop(){if(this.rafId!==null)return;let e=1/this.fps,t=this.currentTime,n=async()=>{let i=this.seekEpoch,s=this.position(),a=s.ended,c=Math.abs(s.time-t)>=e||a;this.setCurrentTime(s.time,c);let l=()=>{this.seekEpoch!==i&&(i=this.seekEpoch,t=this.currentTime,a=this.position().ended)};if(l(),c&&(t=this.currentTime,await this.tick(),l()),this.rafId!==null){if(a){this.pause();return}this.rafId=requestAnimationFrame(n)}};this.rafId=requestAnimationFrame(n)}stopLoop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}dispose(){this.stopLoop(),this.stopSilentTicker(),this.ownsContext&&this.context.close(),super.dispose()}};import{Engine as s1}from"@motionscript/core";var pl=_y(Q0(),1);import*as e1 from"@motionscript/core/sdk";import*as t1 from"@motionscript/core/jsx/jsx-runtime";function r1(){return new URL("esbuild-wasm/esbuild.wasm",import.meta.url).href}var n1;function i1(r){return n1??=(async()=>(await pl.initialize({wasmURL:r??r1()}),async e=>{let{code:t}=await pl.transform(e,{loader:"tsx",format:"cjs",target:"es2020",jsx:"automatic",jsxImportSource:"@motionscript/sdk",tsconfigRaw:{compilerOptions:{experimentalDecorators:!0}}});return t}))()}function Y0(r,e){return{sdk:r?.sdk??e1,jsxRuntime:r?.jsxRuntime??t1,modules:r?.modules,compile:r?.compile??(async t=>(await i1(e))(t))}}var Gd=class{canvasKit;defaults;wasmUrl;still=null;stillRegistry=null;stillQueue=Promise.resolve();constructor(e,t,n){this.canvasKit=e,this.defaults=t,this.wasmUrl=n}async exportVideo(e){let t=e.encode??{};return Hd({document:e.project,registry:e.registry,scale:e.scale,manifest:e.manifest,includeAudio:e.includeAudio,frames:e.frames,video:t.video??this.defaults.video,audio:t.audio??this.defaults.audio,supersample:t.supersample,filename:t.filename,returnBytes:t.download!==!0,onProgress:e.onProgress,signal:e.signal,wasmUrl:this.wasmUrl})}exportStill(e){let t=this.stillQueue.then(()=>this.drawStill(e));return this.stillQueue=t.catch(()=>{}),t}dispose(){this.still?.dispose(),this.still=null}async drawStill(e){let t=this.renderer(e),n=await t.render(e.project,{scale:e.scale,...a1(e.frame)});return{bytes:await t.toBytes({format:e.format,quality:e.quality}),frame:n.frame,totalFrames:n.totalFrames}}renderer(e){let{project:t,registry:n}=e;if(t.viewport===void 0||t.fps===void 0)throw new Error("exportStill takes a project whose fps and viewport are resolved \u2014 see Session.");return this.still&&this.stillRegistry!==n&&this.dispose(),this.still??=new ws(this.canvasKit,{viewport:t.viewport,fps:t.fps,manifest:e.manifest,registry:n}),this.stillRegistry=n,this.still.setViewport(t.viewport),e.manifest&&this.still.setManifest(e.manifest),this.still}};function a1(r){return r.kind==="frame"?{frame:r.frame}:{frame:r.kind}}async function o1(r={}){let e=r.nodes,t=Array.isArray(e)?e.filter(l=>typeof l!="string"):e,n=Array.isArray(e)?e.filter(l=>typeof l=="string"):[],i=Y0(r.dynamicNodes,r.compilerWasmUrl),s=await Xr(r.wasmUrl),a=new Gd(s,{video:r.video,audio:r.audio},r.wasmUrl),o={createStorageAdapter({catalog:l,viewport:u,fps:d}){return new jt(s,l,u,d)},createRenderContext(l){return new cr(s,l)},createMeasureContext(l){return new ni(l)},createAudioSink(){return new wl},createTicker(l,u){return new Fa({context:u.getContext(),fps:l})},createExporter(){return a},dispose(){a.dispose()}},c=new s1(o,{...r,nodes:t,dynamicNodes:i});for(let l of n)await c.registerNode(l);return c}export{_s as Canvas3DBackend,bs as ConcatMismatchError,Se as EffectRegistry,Us as NothingToDrawError,h0 as QUALITY_HIGH,u0 as QUALITY_LOW,d0 as QUALITY_MEDIUM,f0 as QUALITY_VERY_HIGH,l0 as QUALITY_VERY_LOW,ws as StillRenderer,wl as WebAudioPlayer,ni as WebMeasureContext,cr as WebRenderContext,jt as WebStorageAdapter,Fa as WebTicker,ci as canvas3DBackend,Gv as concatVideoSegments,o1 as createBrowserEngine,Wd as createStillRenderer,Xa as disposeCanvas3DBackend,Py as encodeWav,Hv as exportScreenshot,Hd as exportVideo,Xr as getCanvasKit,As as loadCanvas3D,yl as mixAudio,Zv as mixTimelineAudio,Cy as setAssetByteSource};
|
|
2106
1960
|
/*! Bundled license information:
|
|
2107
1961
|
|
|
2108
1962
|
mediabunny/dist/modules/src/misc.js:
|