@motionscript/browser 0.0.0-stage → 0.1.0-alpha.0
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 +5 -0
- package/LICENSE +201 -0
- package/README.md +68 -3
- package/dist/asset-bytes.d.ts +50 -0
- package/dist/asset-bytes.d.ts.map +1 -0
- package/dist/asset-bytes.js +60 -0
- package/dist/asset-bytes.js.map +1 -0
- package/dist/audio/bus-graph.d.ts +43 -0
- package/dist/audio/bus-graph.d.ts.map +1 -0
- package/dist/audio/bus-graph.js +104 -0
- package/dist/audio/bus-graph.js.map +1 -0
- package/dist/audio/filter-graph.d.ts +58 -0
- package/dist/audio/filter-graph.d.ts.map +1 -0
- package/dist/audio/filter-graph.js +235 -0
- package/dist/audio/filter-graph.js.map +1 -0
- package/dist/audio/index.d.ts +5 -0
- package/dist/audio/index.d.ts.map +1 -0
- package/dist/audio/index.js +12 -0
- package/dist/audio/index.js.map +1 -0
- package/dist/audio/mixer.d.ts +59 -0
- package/dist/audio/mixer.d.ts.map +1 -0
- package/dist/audio/mixer.js +193 -0
- package/dist/audio/mixer.js.map +1 -0
- package/dist/audio/player.d.ts +49 -0
- package/dist/audio/player.d.ts.map +1 -0
- package/dist/audio/player.js +226 -0
- package/dist/audio/player.js.map +1 -0
- package/dist/browser/audio.js +2 -0
- package/dist/browser/audio.js.map +7 -0
- package/dist/browser/chunks/GLTFLoader-PGXD4V5B.js +2 -0
- package/dist/browser/chunks/GLTFLoader-PGXD4V5B.js.map +7 -0
- package/dist/browser/chunks/SkeletonUtils-XYDMTGTM.js +2 -0
- package/dist/browser/chunks/SkeletonUtils-XYDMTGTM.js.map +7 -0
- package/dist/browser/chunks/chunk-CTLBXZSU.js +4119 -0
- package/dist/browser/chunks/chunk-CTLBXZSU.js.map +7 -0
- package/dist/browser/chunks/chunk-FQ32PDIU.js +2 -0
- package/dist/browser/chunks/chunk-FQ32PDIU.js.map +7 -0
- package/dist/browser/chunks/chunk-FY3BTKY4.js +2 -0
- package/dist/browser/chunks/chunk-FY3BTKY4.js.map +7 -0
- package/dist/browser/chunks/chunk-NSFLRI4P.js +2 -0
- package/dist/browser/chunks/chunk-NSFLRI4P.js.map +7 -0
- package/dist/browser/chunks/three.module-Z4EOVUWF.js +2 -0
- package/dist/browser/chunks/three.module-Z4EOVUWF.js.map +7 -0
- package/dist/browser/esbuild.wasm +0 -0
- package/dist/browser/index.js +2172 -0
- package/dist/browser/index.js.map +7 -0
- package/dist/browser/manifest.json +15 -0
- package/dist/concat.d.ts +95 -0
- package/dist/concat.d.ts.map +1 -0
- package/dist/concat.js +174 -0
- package/dist/concat.js.map +1 -0
- package/dist/decode/image-levels.d.ts +137 -0
- package/dist/decode/image-levels.d.ts.map +1 -0
- package/dist/decode/image-levels.js +477 -0
- package/dist/decode/image-levels.js.map +1 -0
- package/dist/decode/levels.d.ts +37 -0
- package/dist/decode/levels.d.ts.map +1 -0
- package/dist/decode/levels.js +68 -0
- package/dist/decode/levels.js.map +1 -0
- package/dist/decode/video-levels.d.ts +37 -0
- package/dist/decode/video-levels.d.ts.map +1 -0
- package/dist/decode/video-levels.js +95 -0
- package/dist/decode/video-levels.js.map +1 -0
- package/dist/dynamic-nodes.d.ts +9 -0
- package/dist/dynamic-nodes.d.ts.map +1 -0
- package/dist/dynamic-nodes.js +56 -0
- package/dist/dynamic-nodes.js.map +1 -0
- package/dist/engine.d.ts +59 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +171 -0
- package/dist/engine.js.map +1 -0
- package/dist/exporter.d.ts +163 -0
- package/dist/exporter.d.ts.map +1 -0
- package/dist/exporter.js +263 -0
- package/dist/exporter.js.map +1 -0
- package/dist/getter.d.ts +10 -0
- package/dist/getter.d.ts.map +1 -0
- package/dist/getter.js +38 -0
- package/dist/getter.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +72 -0
- package/dist/index.js.map +1 -0
- package/dist/measure-context.d.ts +12 -0
- package/dist/measure-context.d.ts.map +1 -0
- package/dist/measure-context.js +12 -0
- package/dist/measure-context.js.map +1 -0
- package/dist/mix-timeline-audio.d.ts +42 -0
- package/dist/mix-timeline-audio.d.ts.map +1 -0
- package/dist/mix-timeline-audio.js +63 -0
- package/dist/mix-timeline-audio.js.map +1 -0
- package/dist/output.d.ts +7 -0
- package/dist/output.d.ts.map +1 -0
- package/dist/output.js +6 -0
- package/dist/output.js.map +1 -0
- package/dist/render-context.d.ts +30 -0
- package/dist/render-context.d.ts.map +1 -0
- package/dist/render-context.js +55 -0
- package/dist/render-context.js.map +1 -0
- package/dist/screenshot.d.ts +45 -0
- package/dist/screenshot.d.ts.map +1 -0
- package/dist/screenshot.js +32 -0
- package/dist/screenshot.js.map +1 -0
- package/dist/still.d.ts +151 -0
- package/dist/still.d.ts.map +1 -0
- package/dist/still.js +222 -0
- package/dist/still.js.map +1 -0
- package/dist/storage-adapter.d.ts +367 -0
- package/dist/storage-adapter.d.ts.map +1 -0
- package/dist/storage-adapter.js +1278 -0
- package/dist/storage-adapter.js.map +1 -0
- package/dist/three/renderer.d.ts +48 -0
- package/dist/three/renderer.d.ts.map +1 -0
- package/dist/three/renderer.js +177 -0
- package/dist/three/renderer.js.map +1 -0
- package/dist/ticker.d.ts +42 -0
- package/dist/ticker.d.ts.map +1 -0
- package/dist/ticker.js +143 -0
- package/dist/ticker.js.map +1 -0
- package/package.json +74 -3
|
@@ -0,0 +1,2172 @@
|
|
|
1
|
+
import{c as ml,d as Xd,e as sy,f as pl}from"./chunks/chunk-NSFLRI4P.js";import{a as ny,b as iy}from"./chunks/chunk-FY3BTKY4.js";var _0=ny((H3,Ud)=>{(r=>{"use strict";var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,s=(x,v)=>{for(var I in v)e(x,I,{get:v[I],enumerable:!0})},a=(x,v,I,L)=>{if(v&&typeof v=="object"||typeof v=="function")for(let G of n(v))!i.call(x,G)&&G!==I&&e(x,G,{get:()=>v[G],enumerable:!(L=t(v,G))||L.enumerable});return x},o=x=>a(e({},"__esModule",{value:!0}),x),c=(x,v,I)=>new Promise((L,G)=>{var $=B=>{try{se(I.next(B))}catch(te){G(te)}},H=B=>{try{se(I.throw(B))}catch(te){G(te)}},se=B=>B.done?L(B.value):Promise.resolve(B.value).then($,H);se((I=I.apply(x,v)).next())}),l={};s(l,{analyzeMetafile:()=>G0,analyzeMetafileSync:()=>Q0,build:()=>H0,buildSync:()=>K0,context:()=>W0,default:()=>ey,formatMessages:()=>j0,formatMessagesSync:()=>X0,initialize:()=>Z0,stop:()=>Y0,transform:()=>q0,transformSync:()=>$0,version:()=>V0}),r.exports=o(l);function u(x){let v=L=>{if(L===null)I.write8(0);else if(typeof L=="boolean")I.write8(1),I.write8(+L);else if(typeof L=="number")I.write8(2),I.write32(L|0);else if(typeof L=="string")I.write8(3),I.write(f(L));else if(L instanceof Uint8Array)I.write8(4),I.write(L);else if(L instanceof Array){I.write8(5),I.write32(L.length);for(let G of L)v(G)}else{let G=Object.keys(L);I.write8(6),I.write32(G.length);for(let $ of G)I.write(f($)),v(L[$])}},I=new h;return I.write32(0),I.write32(x.id<<1|+!x.isRequest),v(x.value),y(I.buf,I.len-4,0),I.buf.subarray(0,I.len)}function d(x){let v=()=>{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(v());return se}case 6:{let H=I.read32(),se={};for(let B=0;B<H;B++)se[p(I.read())]=v();return se}default:throw new Error("Invalid packet")}},I=new h(x),L=I.read32(),G=(L&1)===0;L>>>=1;let $=v();if(I.ptr!==x.length)throw new Error("Invalid packet");return{id:L,isRequest:G,value:$}}var h=class{constructor(x=new Uint8Array(1024)){this.buf=x,this.len=0,this.ptr=0}_write(x){if(this.len+x>this.buf.length){let v=new Uint8Array((this.len+x)*2);v.set(this.buf),this.buf=v}return this.len+=x,this.len-x}write8(x){let v=this._write(1);this.buf[v]=x}write32(x){let v=this._write(4);y(this.buf,x,v)}write(x){let v=this._write(4+x.length);y(this.buf,x.length,v),this.buf.set(x,v+4)}_read(x){if(this.ptr+x>this.buf.length)throw new Error("Invalid packet");return this.ptr+=x,this.ptr-x}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let x=this.read32(),v=new Uint8Array(x),I=this._read(v.length);return v.set(this.buf.subarray(I,I+x)),v}},f,p,m;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let x=new TextEncoder,v=new TextDecoder;f=I=>x.encode(I),p=I=>v.decode(I),m='new TextEncoder().encode("")'}else if(typeof Buffer<"u")f=x=>Buffer.from(x),p=x=>{let{buffer:v,byteOffset:I,byteLength:L}=x;return Buffer.from(v,I,L).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
|
+
|
|
3
|
+
This indicates that your JavaScript environment is broken. You cannot use
|
|
4
|
+
esbuild in this environment because esbuild relies on this invariant. This
|
|
5
|
+
is not a problem with esbuild. You need to fix your environment instead.
|
|
6
|
+
`);function g(x,v){return(x[v++]|x[v++]<<8|x[v++]<<16|x[v++]<<24)>>>0}function y(x,v,I){x[I++]=v,x[I++]=v>>8,x[I++]=v>>16,x[I++]=v>>24}var b=String.fromCharCode;function k(x,v,I){let L=x[v],G=1,$=0;for(let H=0;H<v;H++)x[H]===10?(G++,$=0):$++;throw new SyntaxError(I||(v===x.length?"Unexpected end of input while parsing JSON":L>=32&&L<=126?`Unexpected character ${b(L)} in JSON at position ${v} (line ${G}, column ${$})`:`Unexpected byte 0x${L.toString(16)} in JSON at position ${v} (line ${G}, column ${$})`))}function T(x){if(!(x instanceof Uint8Array))throw new Error("JSON input must be a Uint8Array");let v=[],I=[],L=[],G=x.length,$=null,H=0,se,B=0;for(;B<G;){let te=x[B++];if(te<=32)continue;let ae;switch(H===2&&$===null&&te!==34&&te!==125&&k(x,--B),te){case 116:{(x[B++]!==114||x[B++]!==117||x[B++]!==101)&&k(x,--B),ae=!0;break}case 102:{(x[B++]!==97||x[B++]!==108||x[B++]!==115||x[B++]!==101)&&k(x,--B),ae=!1;break}case 110:{(x[B++]!==117||x[B++]!==108||x[B++]!==108)&&k(x,--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 de=B;for(ae=b(te),te=x[B];;){switch(te){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(te),te=x[++B];continue}}break}ae=+ae,isNaN(ae)&&k(x,--de,"Invalid number");break}case 34:{for(ae="";B>=G&&k(x,G),te=x[B++],te!==34;)if(te===92)switch(x[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 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($),I.push(se),L.push(H),$=null,se=ae,H=1;continue}case 123:{ae={},v.push($),I.push(se),L.push(H),$=null,se=ae,H=2;continue}case 93:{H!==1&&k(x,--B),ae=se,$=v.pop(),se=I.pop(),H=L.pop();break}case 125:{H!==2&&k(x,--B),ae=se,$=v.pop(),se=I.pop(),H=L.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,A="warning",M="silent";function P(x,v){let I=[];for(let L of x){if(bt(L,v),L.indexOf(",")>=0)throw new Error(`Invalid ${v}: ${L}`);I.push(L)}return I.join(",")}var _=()=>null,F=x=>typeof x=="boolean"?null:"a boolean",E=x=>typeof x=="string"?null:"a string",U=x=>x instanceof RegExp?null:"a RegExp object",Q=x=>typeof x=="number"&&x===(x|0)?null:"an integer",xe=x=>typeof x=="number"&&x===(x|0)&&x>=0&&x<=65535?null:"a valid port number",we=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",Pa=x=>x instanceof WebAssembly.Module?null:"a WebAssembly.Module",Nd=x=>typeof x=="object"&&!Array.isArray(x)?null:"an object or null",Vd=x=>typeof x=="string"||typeof x=="boolean"?null:"a string or a boolean",I0=x=>typeof x=="string"||typeof x=="object"&&x!==null&&!Array.isArray(x)?null:"a string or an object",Hd=x=>typeof x=="string"||Array.isArray(x)&&x.every(v=>typeof v=="string")?null:"a string or an array of strings",Wd=x=>typeof x=="string"||x instanceof Uint8Array?null:"a string or a Uint8Array",M0=x=>typeof x=="string"||x instanceof URL?null:"a string or a URL";function R(x,v,I,L){let G=x[I];if(v[I+""]=!0,G===void 0)return;let $=L(G);if($!==null)throw new Error(`${S(I)} must be ${$}`);return G}function tt(x,v,I){for(let L in x)if(!(L in v))throw new Error(`Invalid option ${I}: ${S(L)}`)}function F0(x){let v=Object.create(null),I=R(x,v,"wasmURL",M0),L=R(x,v,"wasmModule",Pa),G=R(x,v,"worker",F);return tt(x,v,"in initialize() call"),{wasmURL:I,wasmModule:L,worker:G}}function qd(x){let v;if(x!==void 0){v=Object.create(null);for(let I in x){let L=x[I];if(typeof L=="string"||L===!1)v[I]=L;else throw new Error(`Expected ${S(I)} in mangle cache to map to either a string or false`)}}return v}function Ea(x,v,I,L,G){let $=R(v,I,"color",F),H=R(v,I,"logLevel",E),se=R(v,I,"logLimit",Q),B=R(v,I,"logStyle",E);$!==void 0?x.push(`--color=${$}`):L&&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,I){if(typeof x!="string")throw new Error(`Expected value for ${v}${I!==void 0?" "+S(I):""} to be a string, got ${typeof x} instead`);return x}function jd(x,v,I){let L=R(v,I,"legalComments",E),G=R(v,I,"sourceRoot",E),$=R(v,I,"sourcesContent",F),H=R(v,I,"target",Hd),se=R(v,I,"format",E),B=R(v,I,"globalName",E),te=R(v,I,"mangleProps",U),ae=R(v,I,"reserveProps",U),de=R(v,I,"mangleQuoted",F),Be=R(v,I,"minify",F),Ee=R(v,I,"minifySyntax",F),Le=R(v,I,"minifyWhitespace",F),Ue=R(v,I,"minifyIdentifiers",F),pe=R(v,I,"lineLimit",Q),Qe=R(v,I,"drop",Ae),me=R(v,I,"dropLabels",Ae),fe=R(v,I,"charset",E),Z=R(v,I,"treeShaking",F),q=R(v,I,"ignoreAnnotations",F),D=R(v,I,"jsx",E),V=R(v,I,"jsxFactory",E),W=R(v,I,"jsxFragment",E),ee=R(v,I,"jsxImportSource",E),le=R(v,I,"jsxDev",F),N=R(v,I,"jsxSideEffects",F),X=R(v,I,"define",Re),oe=R(v,I,"logOverride",Re),Te=R(v,I,"supported",Re),C=R(v,I,"pure",Ae),O=R(v,I,"keepNames",F),re=R(v,I,"platform",E),he=R(v,I,"tsconfigRaw",I0),Me=R(v,I,"absPaths",Ae);if(L&&x.push(`--legal-comments=${L}`),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=${Fa(te)}`),ae&&x.push(`--reserve-props=${Fa(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")}`);O&&x.push("--keep-names")}function R0(x,v,I,L,G){var $;let H=[],se=[],B=Object.create(null),te=null,ae=null;Ea(H,v,B,I,L),jd(H,v,B);let de=R(v,B,"sourcemap",Vd),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",E),Qe=R(v,B,"outdir",E),me=R(v,B,"outbase",E),fe=R(v,B,"tsconfig",E),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",E),le=R(v,B,"alias",Re),N=R(v,B,"loader",Re),X=R(v,B,"outExtension",Re),oe=R(v,B,"publicPath",E),Te=R(v,B,"entryNames",E),C=R(v,B,"chunkNames",E),O=R(v,B,"assetNames",E),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",E),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}`),O&&H.push(`--asset-names=${O}`),D&&H.push(`--main-fields=${P(D,"main field")}`),V&&H.push(`--conditions=${P(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(he)for(let ke in he){if(ke.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${ke}`);H.push(`--banner:${ke}=${bt(he[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(re)for(let ke of re)H.push(`--inject:${bt(ke,"inject")}`);if(N)for(let ke in N){if(ke.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${ke}`);H.push(`--loader:${ke}=${bt(N[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(ue)if(Array.isArray(ue))for(let ke=0,kr=ue.length;ke<kr;ke++){let Ut=ue[ke];if(typeof Ut=="object"&&Ut!==null){let ar=Object.create(null),xr=R(Ut,ar,"in",E),zt=R(Ut,ar,"out",E);if(tt(Ut,ar,"in entry point at index "+ke),xr===void 0)throw new Error('Missing property "in" for entry point at index '+ke);if(zt===void 0)throw new Error('Missing property "out" for entry point at index '+ke);se.push([zt,xr])}else se.push(["",bt(Ut,"entry point at index "+ke)])}else for(let ke in ue)se.push([ke,bt(ue[ke],"entry point",ke)]);if(De){let ke=Object.create(null),kr=R(De,ke,"contents",Wd),Ut=R(De,ke,"resolveDir",E),ar=R(De,ke,"sourcefile",E),xr=R(De,ke,"loader",E);tt(De,ke,'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 ke of q)ke+="",br.push(ke);return{entries:se,flags:H,write:Fe,stdinContents:te,stdinResolveDir:ae,absWorkingDir:ze,nodePaths:br,mangleCache:qd(rt)}}function B0(x,v,I,L){let G=[],$=Object.create(null);Ea(G,v,$,I,L),jd(G,v,$);let H=R(v,$,"sourcemap",Vd),se=R(v,$,"sourcefile",E),B=R(v,$,"loader",E),te=R(v,$,"banner",E),ae=R(v,$,"footer",E),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:qd(de)}}function D0(x){let v={},I={didClose:!1,reason:""},L={},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=>{I.didClose=!0,fe&&(I.reason=": "+(fe.message||fe));let Z="The service was stopped"+I.reason;for(let q in L)L[q](Z,null);L={}},ae=(fe,Z,q)=>{if(I.didClose)return q("The service is no longer running"+I.reason,null);let D=G++;L[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(I.didClose)throw new Error("The service is no longer running"+I.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=L[Z.id];delete L[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(),O0(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=Gd(),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}=B0(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,(O,re)=>{if(O)return ee(new Error(O),null);let he=ni(re.errors,le),Me=ni(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(ks("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{Ea(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(ks("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",E),le=R(D,W,"color",F),N=R(D,W,"terminalWidth",Q),X=R(D,W,"logStyle",E);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 O0(x,v,I,L,G,$,H,se,B,te,ae){let de=Gd(),Be=x==="context",Ee=(pe,Qe)=>{let me=[];try{Ea(me,se,{},B,A)}catch{}let fe=Sn(pe,$,de,void 0,Qe);I(G,{command:"error",flags:me,error:fe},()=>{fe.detail=de.load(fe.detail),ae(ks(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"),"");L0(v,I,L,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}=R0(x,se,B,A,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=(O,re)=>{let he={errors:ni(O.errors,de),warnings:ni(O.warnings,de),outputFiles:void 0,metafile:void 0,mangleCache:void 0},Me=he.errors.slice(),ue=he.warnings.slice();O.outputFiles&&(he.outputFiles=O.outputFiles.map(z0)),O.metafile&&O.metafile.length&&(he.metafile=N0(O.metafile)),O.mangleCache&&(he.mangleCache=O.mangleCache),O.writeToStdout!==void 0&&console.log(p(O.writeToStdout).replace(/\n$/,"")),Qe(he,(ze,De)=>{if(Me.length>0||ze.length>0){let Fe=ks("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"]=(O,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,L(O,Fe),he()})})),I(G,X,(O,re)=>{if(O)return ae(new Error(O),null);if(!Be)return oe(re,(ue,ze)=>(me(),ae(ue,ze)));if(re.errors.length>0)return ae(ks("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=()=>{I(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),I(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",xe),rt=R(ue,Fe,"host",E),br=R(ue,Fe,"servedir",E),ke=R(ue,Fe,"keyfile",E),kr=R(ue,Fe,"certfile",E),Ut=R(ue,Fe,"fallback",E),ar=R(ue,Fe,"cors",Re),xr=R(ue,Fe,"onRequest",we);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),ke!==void 0&&(zt.keyfile=ke),kr!==void 0&&(zt.certfile=kr),Ut!==void 0&&(zt.fallback=Ut),ar){let Ss={},ii=R(ar,Ss,"origin",Hd);tt(ar,Ss,'on "cors" object'),Array.isArray(ii)?zt.corsOrigin=ii:ii!==void 0&&(zt.corsOrigin=[ii])}I(G,zt,(Ss,ii)=>{if(Ss)return De(new Error(Ss));xr&&(H["serve-request"]=(ty,ry)=>{xr(ry.args),L(ty,{})}),ze(ii)})}),cancel:()=>new Promise(ue=>{if(he)return ue();I(G,{command:"cancel",key:v},()=>{ue()})}),dispose:()=>new Promise(ue=>{if(he)return ue();he=!0,I(G,{command:"dispose",key:v},()=>{ue(),me(),G.unref()})})};G.ref(),ae(null,Me)})}}var L0=(x,v,I,L,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",E);if(typeof D!="string"||D==="")throw new Error(`Plugin at index ${Ue} is missing a name`);try{let V=R(Z,q,"setup",we);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",E),C=R(X,oe,"importer",E),O=R(X,oe,"namespace",E),re=R(X,oe,"resolveDir",E),he=R(X,oe,"kind",E),Me=R(X,oe,"pluginData",_),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),O!=null&&(Fe.namespace=O),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=U0(ue,"with")),v(L,Fe,(kt,rt)=>{kt!==null?De(new Error(kt)):ze({errors:ni(rt.errors,B),warnings:ni(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=Ia(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=Ia(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=Ia(new Error(oe),G,"onResolve"),C={},O=R(N,C,"filter",U),re=R(N,C,"namespace",E);if(tt(N,C,`in onResolve() call for plugin ${S(D)}`),O==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:Fa(O),namespace:re||""})},onLoad(N,X){let oe='This error came from the "onLoad" callback registered here:',Te=Ia(new Error(oe),G,"onLoad"),C={},O=R(N,C,"filter",U),re=R(N,C,"namespace",E);if(tt(N,C,`in onLoad() call for plugin ${S(D)}`),O==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:Fa(O),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))}}))),I(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",E),Te=R(N,X,"path",E),C=R(N,X,"namespace",E),O=R(N,X,"suffix",E),re=R(N,X,"external",F),he=R(N,X,"sideEffects",F),Me=R(N,X,"pluginData",_),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),O!=null&&(D.suffix=O),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=Ma(De,"watchFiles")),Fe!=null&&(D.watchDirs=Ma(Fe,"watchDirs"));break}}catch(N){D={id:le,errors:[Sn(N,G,B,ee&&ee(),V)]};break}I(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",E),Te=R(N,X,"contents",Wd),C=R(N,X,"resolveDir",E),O=R(N,X,"pluginData",_),re=R(N,X,"loader",E),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),O!=null&&(D.pluginData=B.store(O)),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=Ma(ue,"watchFiles")),ze!=null&&(D.watchDirs=Ma(ze,"watchDirs"));break}}catch(N){D={id:le,errors:[Sn(N,G,B,ee&&ee(),V)]};break}I(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),O=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)),O!=null&&(X=wr(O,"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 Gd(){let x=new Map,v=0;return{clear(){x.clear()},load(I){return x.get(I)},store(I){if(I===void 0)return-1;let L=v++;return x.set(L,I),L}}}function Ia(x,v,I){let L,G=!1;return()=>{if(G)return L;G=!0;try{let $=(x.stack+"").split(`
|
|
8
|
+
`);$.splice(1,1);let H=Kd(v,$,I);if(H)return L={text:x.message,location:H},L}catch{}}}function Sn(x,v,I,L,G){let $="Internal error",H=null;try{$=(x&&x.message||x)+""}catch{}try{H=Kd(v,(x.stack+"").split(`
|
|
9
|
+
`),"")}catch{}return{id:"",pluginName:G,text:$,location:H,notes:L?[L]:[],detail:I?I.store(x):-1}}function Kd(x,v,I){let L=" at ";if(x.readFileSync&&!v[0].startsWith(L)&&v[1].startsWith(L))for(let G=1;G<v.length;G++){let $=v[G];if($.startsWith(L))for($=$.slice(L.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=x.readFileSync(H[1],"utf8")}catch{break}let B=se.split(/\r\n|\r|\n|\u2028|\u2029/)[+H[2]-1]||"",te=+H[3]-1,ae=B.slice(te,te+I.length)===I?I.length:0;return{file:H[1],namespace:"file",line:+H[2],column:f(B.slice(0,te)).length,length:f(B.slice(te,te+ae)).length,lineText:B+`
|
|
10
|
+
`+v.slice(1).join(`
|
|
11
|
+
`),suggestion:""}}break}}return null}function ks(x,v,I){let L=5;x+=v.length<1?"":` with ${v.length} error${v.length<2?"":"s"}:`+v.slice(0,L+1).map(($,H)=>{if(H===L)return`
|
|
12
|
+
...`;if(!$.location)return`
|
|
13
|
+
error: ${$.text}`;let{file:se,line:B,column:te}=$.location,ae=$.pluginName?`[plugin: ${$.pluginName}] `:"";return`
|
|
14
|
+
${se}:${B}:${te}: ERROR: ${ae}${$.text}`}).join("");let G=new Error(x);for(let[$,H]of[["errors",v],["warnings",I]])Object.defineProperty(G,$,{configurable:!0,enumerable:!0,get:()=>H,set:se=>Object.defineProperty(G,$,{configurable:!0,enumerable:!0,value:se})});return G}function ni(x,v){for(let I of x)I.detail=v.load(I.detail);return x}function $d(x,v,I){if(x==null)return null;let L={},G=R(x,L,"file",E),$=R(x,L,"namespace",E),H=R(x,L,"line",Q),se=R(x,L,"column",Q),B=R(x,L,"length",Q),te=R(x,L,"lineText",E),ae=R(x,L,"suggestion",E);if(tt(x,L,v),te){let de=te.slice(0,(se&&se>0?se:0)+(B&&B>0?B:0)+(I&&I>0?I:80));!/[\x7F-\uFFFF]/.test(de)&&!/\n/.test(te)&&(te=de)}return{file:G||"",namespace:$||"",line:H||0,column:se||0,length:B||0,lineText:te||"",suggestion:ae||""}}function wr(x,v,I,L,G){let $=[],H=0;for(let se of x){let B={},te=R(se,B,"id",E),ae=R(se,B,"pluginName",E),de=R(se,B,"text",E),Be=R(se,B,"location",Nd),Ee=R(se,B,"notes",J),Le=R(se,B,"detail",_),Ue=`in element ${H} of "${v}"`;tt(se,B,Ue);let pe=[];if(Ee)for(let Qe of Ee){let me={},fe=R(Qe,me,"text",E),Z=R(Qe,me,"location",Nd);tt(Qe,me,Ue),pe.push({text:fe||"",location:$d(Z,Ue,G)})}$.push({id:te||"",pluginName:ae||L,text:de||"",location:$d(Be,Ue,G),notes:pe,detail:I?I.store(Le):-1}),H++}return $}function Ma(x,v){let I=[];for(let L of x){if(typeof L!="string")throw new Error(`${S(v)} must be an array of strings`);I.push(L)}return I}function U0(x,v){let I=Object.create(null);for(let L in x){let G=x[L];if(typeof G!="string")throw new Error(`key ${S(L)} in object ${S(v)} must be a string`);I[L]=G}return I}function z0({path:x,contents:v,hash:I}){let L=null;return{path:x,contents:v,hash:I,get text(){let G=this.contents;return(L===null||G!==v)&&(v=G,L=p(G)),L}}}function Fa(x){let v=x.source;return x.flags&&(v=`(?${x.flags})${v}`),v}function N0(x){let v;try{v=p(x)}catch{return T(x)}return JSON.parse(v)}var V0="0.28.2",H0=x=>xs().build(x),W0=x=>xs().context(x),q0=(x,v)=>xs().transform(x,v),j0=(x,v)=>xs().formatMessages(x,v),G0=(x,v)=>xs().analyzeMetafile(x,v),K0=()=>{throw new Error('The "buildSync" API only works in node')},$0=()=>{throw new Error('The "transformSync" API only works in node')},X0=()=>{throw new Error('The "formatMessagesSync" API only works in node')},Q0=()=>{throw new Error('The "analyzeMetafileSync" API only works in node')},Y0=()=>(Ra&&Ra(),Promise.resolve()),Tn,Ra,Ba,xs=()=>{if(Ba)return Ba;throw Tn?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')},Z0=x=>{x=F0(x||{});let v=x.wasmURL,I=x.wasmModule,L=x.worker!==!1;if(!v&&!I)throw new Error('Must provide either the "wasmURL" option or the "wasmModule" option');if(Tn)throw new Error('Cannot call "initialize" more than once');return Tn=J0(v||"",I,L),Tn.catch(()=>{Tn=void 0}),Tn},J0=(x,v,I)=>c(null,null,function*(){let L,G,$=new Promise(de=>G=de);if(I){let de=new Blob([`onmessage=((postMessage) => {
|
|
15
|
+
// Copyright 2018 The Go Authors. All rights reserved.
|
|
16
|
+
// Use of this source code is governed by a BSD-style
|
|
17
|
+
// license that can be found in the LICENSE file.
|
|
18
|
+
var __async = (__this, __arguments, generator) => {
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
var fulfilled = (value) => {
|
|
21
|
+
try {
|
|
22
|
+
step(generator.next(value));
|
|
23
|
+
} catch (e) {
|
|
24
|
+
reject(e);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
var rejected = (value) => {
|
|
28
|
+
try {
|
|
29
|
+
step(generator.throw(value));
|
|
30
|
+
} catch (e) {
|
|
31
|
+
reject(e);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
35
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
let onmessage;
|
|
39
|
+
let globalThis = {};
|
|
40
|
+
for (let o = self; o; o = Object.getPrototypeOf(o))
|
|
41
|
+
for (let k of Object.getOwnPropertyNames(o))
|
|
42
|
+
if (!(k in globalThis))
|
|
43
|
+
Object.defineProperty(globalThis, k, { get: () => self[k] });
|
|
44
|
+
"use strict";
|
|
45
|
+
(() => {
|
|
46
|
+
const enosys = () => {
|
|
47
|
+
const err = new Error("not implemented");
|
|
48
|
+
err.code = "ENOSYS";
|
|
49
|
+
return err;
|
|
50
|
+
};
|
|
51
|
+
if (!globalThis.fs) {
|
|
52
|
+
let outputBuf = "";
|
|
53
|
+
globalThis.fs = {
|
|
54
|
+
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 },
|
|
55
|
+
// unused
|
|
56
|
+
writeSync(fd, buf) {
|
|
57
|
+
outputBuf += decoder.decode(buf);
|
|
58
|
+
const nl = outputBuf.lastIndexOf("\\n");
|
|
59
|
+
if (nl != -1) {
|
|
60
|
+
console.log(outputBuf.substring(0, nl));
|
|
61
|
+
outputBuf = outputBuf.substring(nl + 1);
|
|
62
|
+
}
|
|
63
|
+
return buf.length;
|
|
64
|
+
},
|
|
65
|
+
write(fd, buf, offset, length, position, callback) {
|
|
66
|
+
if (offset !== 0 || length !== buf.length || position !== null) {
|
|
67
|
+
callback(enosys());
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const n = this.writeSync(fd, buf);
|
|
71
|
+
callback(null, n);
|
|
72
|
+
},
|
|
73
|
+
chmod(path, mode, callback) {
|
|
74
|
+
callback(enosys());
|
|
75
|
+
},
|
|
76
|
+
chown(path, uid, gid, callback) {
|
|
77
|
+
callback(enosys());
|
|
78
|
+
},
|
|
79
|
+
close(fd, callback) {
|
|
80
|
+
callback(enosys());
|
|
81
|
+
},
|
|
82
|
+
fchmod(fd, mode, callback) {
|
|
83
|
+
callback(enosys());
|
|
84
|
+
},
|
|
85
|
+
fchown(fd, uid, gid, callback) {
|
|
86
|
+
callback(enosys());
|
|
87
|
+
},
|
|
88
|
+
fstat(fd, callback) {
|
|
89
|
+
callback(enosys());
|
|
90
|
+
},
|
|
91
|
+
fsync(fd, callback) {
|
|
92
|
+
callback(null);
|
|
93
|
+
},
|
|
94
|
+
ftruncate(fd, length, callback) {
|
|
95
|
+
callback(enosys());
|
|
96
|
+
},
|
|
97
|
+
lchown(path, uid, gid, callback) {
|
|
98
|
+
callback(enosys());
|
|
99
|
+
},
|
|
100
|
+
link(path, link, callback) {
|
|
101
|
+
callback(enosys());
|
|
102
|
+
},
|
|
103
|
+
lstat(path, callback) {
|
|
104
|
+
callback(enosys());
|
|
105
|
+
},
|
|
106
|
+
mkdir(path, perm, callback) {
|
|
107
|
+
callback(enosys());
|
|
108
|
+
},
|
|
109
|
+
open(path, flags, mode, callback) {
|
|
110
|
+
callback(enosys());
|
|
111
|
+
},
|
|
112
|
+
read(fd, buffer, offset, length, position, callback) {
|
|
113
|
+
callback(enosys());
|
|
114
|
+
},
|
|
115
|
+
readdir(path, callback) {
|
|
116
|
+
callback(enosys());
|
|
117
|
+
},
|
|
118
|
+
readlink(path, callback) {
|
|
119
|
+
callback(enosys());
|
|
120
|
+
},
|
|
121
|
+
rename(from, to, callback) {
|
|
122
|
+
callback(enosys());
|
|
123
|
+
},
|
|
124
|
+
rmdir(path, callback) {
|
|
125
|
+
callback(enosys());
|
|
126
|
+
},
|
|
127
|
+
stat(path, callback) {
|
|
128
|
+
callback(enosys());
|
|
129
|
+
},
|
|
130
|
+
symlink(path, link, callback) {
|
|
131
|
+
callback(enosys());
|
|
132
|
+
},
|
|
133
|
+
truncate(path, length, callback) {
|
|
134
|
+
callback(enosys());
|
|
135
|
+
},
|
|
136
|
+
unlink(path, callback) {
|
|
137
|
+
callback(enosys());
|
|
138
|
+
},
|
|
139
|
+
utimes(path, atime, mtime, callback) {
|
|
140
|
+
callback(enosys());
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
if (!globalThis.process) {
|
|
145
|
+
globalThis.process = {
|
|
146
|
+
getuid() {
|
|
147
|
+
return -1;
|
|
148
|
+
},
|
|
149
|
+
getgid() {
|
|
150
|
+
return -1;
|
|
151
|
+
},
|
|
152
|
+
geteuid() {
|
|
153
|
+
return -1;
|
|
154
|
+
},
|
|
155
|
+
getegid() {
|
|
156
|
+
return -1;
|
|
157
|
+
},
|
|
158
|
+
getgroups() {
|
|
159
|
+
throw enosys();
|
|
160
|
+
},
|
|
161
|
+
pid: -1,
|
|
162
|
+
ppid: -1,
|
|
163
|
+
umask() {
|
|
164
|
+
throw enosys();
|
|
165
|
+
},
|
|
166
|
+
cwd() {
|
|
167
|
+
throw enosys();
|
|
168
|
+
},
|
|
169
|
+
chdir() {
|
|
170
|
+
throw enosys();
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
if (!globalThis.path) {
|
|
175
|
+
globalThis.path = {
|
|
176
|
+
resolve(...pathSegments) {
|
|
177
|
+
return pathSegments.join("/");
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
if (!globalThis.crypto) {
|
|
182
|
+
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
|
|
183
|
+
}
|
|
184
|
+
if (!globalThis.performance) {
|
|
185
|
+
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
|
|
186
|
+
}
|
|
187
|
+
if (!globalThis.TextEncoder) {
|
|
188
|
+
throw new Error("globalThis.TextEncoder is not available, polyfill required");
|
|
189
|
+
}
|
|
190
|
+
if (!globalThis.TextDecoder) {
|
|
191
|
+
throw new Error("globalThis.TextDecoder is not available, polyfill required");
|
|
192
|
+
}
|
|
193
|
+
const encoder = new TextEncoder("utf-8");
|
|
194
|
+
const decoder = new TextDecoder("utf-8");
|
|
195
|
+
globalThis.Go = class {
|
|
196
|
+
constructor() {
|
|
197
|
+
this.argv = ["js"];
|
|
198
|
+
this.env = {};
|
|
199
|
+
this.exit = (code) => {
|
|
200
|
+
if (code !== 0) {
|
|
201
|
+
console.warn("exit code:", code);
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
this._exitPromise = new Promise((resolve) => {
|
|
205
|
+
this._resolveExitPromise = resolve;
|
|
206
|
+
});
|
|
207
|
+
this._pendingEvent = null;
|
|
208
|
+
this._scheduledTimeouts = /* @__PURE__ */ new Map();
|
|
209
|
+
this._nextCallbackTimeoutID = 1;
|
|
210
|
+
const setInt64 = (addr, v) => {
|
|
211
|
+
this.mem.setUint32(addr + 0, v, true);
|
|
212
|
+
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
|
|
213
|
+
};
|
|
214
|
+
const setInt32 = (addr, v) => {
|
|
215
|
+
this.mem.setUint32(addr + 0, v, true);
|
|
216
|
+
};
|
|
217
|
+
const getInt64 = (addr) => {
|
|
218
|
+
const low = this.mem.getUint32(addr + 0, true);
|
|
219
|
+
const high = this.mem.getInt32(addr + 4, true);
|
|
220
|
+
return low + high * 4294967296;
|
|
221
|
+
};
|
|
222
|
+
const loadValue = (addr) => {
|
|
223
|
+
const f = this.mem.getFloat64(addr, true);
|
|
224
|
+
if (f === 0) {
|
|
225
|
+
return void 0;
|
|
226
|
+
}
|
|
227
|
+
if (!isNaN(f)) {
|
|
228
|
+
return f;
|
|
229
|
+
}
|
|
230
|
+
const id = this.mem.getUint32(addr, true);
|
|
231
|
+
return this._values[id];
|
|
232
|
+
};
|
|
233
|
+
const storeValue = (addr, v) => {
|
|
234
|
+
const nanHead = 2146959360;
|
|
235
|
+
if (typeof v === "number" && v !== 0) {
|
|
236
|
+
if (isNaN(v)) {
|
|
237
|
+
this.mem.setUint32(addr + 4, nanHead, true);
|
|
238
|
+
this.mem.setUint32(addr, 0, true);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
this.mem.setFloat64(addr, v, true);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (v === void 0) {
|
|
245
|
+
this.mem.setFloat64(addr, 0, true);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
let id = this._ids.get(v);
|
|
249
|
+
if (id === void 0) {
|
|
250
|
+
id = this._idPool.pop();
|
|
251
|
+
if (id === void 0) {
|
|
252
|
+
id = this._values.length;
|
|
253
|
+
}
|
|
254
|
+
this._values[id] = v;
|
|
255
|
+
this._goRefCounts[id] = 0;
|
|
256
|
+
this._ids.set(v, id);
|
|
257
|
+
}
|
|
258
|
+
this._goRefCounts[id]++;
|
|
259
|
+
let typeFlag = 0;
|
|
260
|
+
switch (typeof v) {
|
|
261
|
+
case "object":
|
|
262
|
+
if (v !== null) {
|
|
263
|
+
typeFlag = 1;
|
|
264
|
+
}
|
|
265
|
+
break;
|
|
266
|
+
case "string":
|
|
267
|
+
typeFlag = 2;
|
|
268
|
+
break;
|
|
269
|
+
case "symbol":
|
|
270
|
+
typeFlag = 3;
|
|
271
|
+
break;
|
|
272
|
+
case "function":
|
|
273
|
+
typeFlag = 4;
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
|
|
277
|
+
this.mem.setUint32(addr, id, true);
|
|
278
|
+
};
|
|
279
|
+
const loadSlice = (addr) => {
|
|
280
|
+
const array = getInt64(addr + 0);
|
|
281
|
+
const len = getInt64(addr + 8);
|
|
282
|
+
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
|
|
283
|
+
};
|
|
284
|
+
const loadSliceOfValues = (addr) => {
|
|
285
|
+
const array = getInt64(addr + 0);
|
|
286
|
+
const len = getInt64(addr + 8);
|
|
287
|
+
const a = new Array(len);
|
|
288
|
+
for (let i = 0; i < len; i++) {
|
|
289
|
+
a[i] = loadValue(array + i * 8);
|
|
290
|
+
}
|
|
291
|
+
return a;
|
|
292
|
+
};
|
|
293
|
+
const loadString = (addr) => {
|
|
294
|
+
const saddr = getInt64(addr + 0);
|
|
295
|
+
const len = getInt64(addr + 8);
|
|
296
|
+
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
|
|
297
|
+
};
|
|
298
|
+
const testCallExport = (a, b) => {
|
|
299
|
+
this._inst.exports.testExport0();
|
|
300
|
+
return this._inst.exports.testExport(a, b);
|
|
301
|
+
};
|
|
302
|
+
const timeOrigin = Date.now() - performance.now();
|
|
303
|
+
this.importObject = {
|
|
304
|
+
_gotest: {
|
|
305
|
+
add: (a, b) => a + b,
|
|
306
|
+
callExport: testCallExport
|
|
307
|
+
},
|
|
308
|
+
gojs: {
|
|
309
|
+
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
|
|
310
|
+
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
|
|
311
|
+
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
|
|
312
|
+
// This changes the SP, thus we have to update the SP used by the imported function.
|
|
313
|
+
// func wasmExit(code int32)
|
|
314
|
+
"runtime.wasmExit": (sp) => {
|
|
315
|
+
sp >>>= 0;
|
|
316
|
+
const code = this.mem.getInt32(sp + 8, true);
|
|
317
|
+
this.exited = true;
|
|
318
|
+
delete this._inst;
|
|
319
|
+
delete this._values;
|
|
320
|
+
delete this._goRefCounts;
|
|
321
|
+
delete this._ids;
|
|
322
|
+
delete this._idPool;
|
|
323
|
+
this.exit(code);
|
|
324
|
+
},
|
|
325
|
+
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
|
|
326
|
+
"runtime.wasmWrite": (sp) => {
|
|
327
|
+
sp >>>= 0;
|
|
328
|
+
const fd = getInt64(sp + 8);
|
|
329
|
+
const p = getInt64(sp + 16);
|
|
330
|
+
const n = this.mem.getInt32(sp + 24, true);
|
|
331
|
+
globalThis.fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
|
|
332
|
+
},
|
|
333
|
+
// func resetMemoryDataView()
|
|
334
|
+
"runtime.resetMemoryDataView": (sp) => {
|
|
335
|
+
sp >>>= 0;
|
|
336
|
+
this.mem = new DataView(this._inst.exports.mem.buffer);
|
|
337
|
+
},
|
|
338
|
+
// func nanotime1() int64
|
|
339
|
+
"runtime.nanotime1": (sp) => {
|
|
340
|
+
sp >>>= 0;
|
|
341
|
+
setInt64(sp + 8, (timeOrigin + performance.now()) * 1e6);
|
|
342
|
+
},
|
|
343
|
+
// func walltime() (sec int64, nsec int32)
|
|
344
|
+
"runtime.walltime": (sp) => {
|
|
345
|
+
sp >>>= 0;
|
|
346
|
+
const msec = (/* @__PURE__ */ new Date()).getTime();
|
|
347
|
+
setInt64(sp + 8, msec / 1e3);
|
|
348
|
+
this.mem.setInt32(sp + 16, msec % 1e3 * 1e6, true);
|
|
349
|
+
},
|
|
350
|
+
// func scheduleTimeoutEvent(delay int64) int32
|
|
351
|
+
"runtime.scheduleTimeoutEvent": (sp) => {
|
|
352
|
+
sp >>>= 0;
|
|
353
|
+
const id = this._nextCallbackTimeoutID;
|
|
354
|
+
this._nextCallbackTimeoutID++;
|
|
355
|
+
this._scheduledTimeouts.set(id, setTimeout(
|
|
356
|
+
() => {
|
|
357
|
+
this._resume();
|
|
358
|
+
while (this._scheduledTimeouts.has(id)) {
|
|
359
|
+
console.warn("scheduleTimeoutEvent: missed timeout event");
|
|
360
|
+
this._resume();
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
getInt64(sp + 8)
|
|
364
|
+
));
|
|
365
|
+
this.mem.setInt32(sp + 16, id, true);
|
|
366
|
+
},
|
|
367
|
+
// func clearTimeoutEvent(id int32)
|
|
368
|
+
"runtime.clearTimeoutEvent": (sp) => {
|
|
369
|
+
sp >>>= 0;
|
|
370
|
+
const id = this.mem.getInt32(sp + 8, true);
|
|
371
|
+
clearTimeout(this._scheduledTimeouts.get(id));
|
|
372
|
+
this._scheduledTimeouts.delete(id);
|
|
373
|
+
},
|
|
374
|
+
// func getRandomData(r []byte)
|
|
375
|
+
"runtime.getRandomData": (sp) => {
|
|
376
|
+
sp >>>= 0;
|
|
377
|
+
crypto.getRandomValues(loadSlice(sp + 8));
|
|
378
|
+
},
|
|
379
|
+
// func finalizeRef(v ref)
|
|
380
|
+
"syscall/js.finalizeRef": (sp) => {
|
|
381
|
+
sp >>>= 0;
|
|
382
|
+
const id = this.mem.getUint32(sp + 8, true);
|
|
383
|
+
this._goRefCounts[id]--;
|
|
384
|
+
if (this._goRefCounts[id] === 0) {
|
|
385
|
+
const v = this._values[id];
|
|
386
|
+
this._values[id] = null;
|
|
387
|
+
this._ids.delete(v);
|
|
388
|
+
this._idPool.push(id);
|
|
389
|
+
}
|
|
390
|
+
},
|
|
391
|
+
// func stringVal(value string) ref
|
|
392
|
+
"syscall/js.stringVal": (sp) => {
|
|
393
|
+
sp >>>= 0;
|
|
394
|
+
storeValue(sp + 24, loadString(sp + 8));
|
|
395
|
+
},
|
|
396
|
+
// func valueGet(v ref, p string) ref
|
|
397
|
+
"syscall/js.valueGet": (sp) => {
|
|
398
|
+
sp >>>= 0;
|
|
399
|
+
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
|
|
400
|
+
sp = this._inst.exports.getsp() >>> 0;
|
|
401
|
+
storeValue(sp + 32, result);
|
|
402
|
+
},
|
|
403
|
+
// func valueSet(v ref, p string, x ref)
|
|
404
|
+
"syscall/js.valueSet": (sp) => {
|
|
405
|
+
sp >>>= 0;
|
|
406
|
+
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
|
|
407
|
+
},
|
|
408
|
+
// func valueDelete(v ref, p string)
|
|
409
|
+
"syscall/js.valueDelete": (sp) => {
|
|
410
|
+
sp >>>= 0;
|
|
411
|
+
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
|
|
412
|
+
},
|
|
413
|
+
// func valueIndex(v ref, i int) ref
|
|
414
|
+
"syscall/js.valueIndex": (sp) => {
|
|
415
|
+
sp >>>= 0;
|
|
416
|
+
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
|
|
417
|
+
},
|
|
418
|
+
// valueSetIndex(v ref, i int, x ref)
|
|
419
|
+
"syscall/js.valueSetIndex": (sp) => {
|
|
420
|
+
sp >>>= 0;
|
|
421
|
+
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
|
|
422
|
+
},
|
|
423
|
+
// func valueCall(v ref, m string, args []ref) (ref, bool)
|
|
424
|
+
"syscall/js.valueCall": (sp) => {
|
|
425
|
+
sp >>>= 0;
|
|
426
|
+
try {
|
|
427
|
+
const v = loadValue(sp + 8);
|
|
428
|
+
const m = Reflect.get(v, loadString(sp + 16));
|
|
429
|
+
const args = loadSliceOfValues(sp + 32);
|
|
430
|
+
const result = Reflect.apply(m, v, args);
|
|
431
|
+
sp = this._inst.exports.getsp() >>> 0;
|
|
432
|
+
storeValue(sp + 56, result);
|
|
433
|
+
this.mem.setUint8(sp + 64, 1);
|
|
434
|
+
} catch (err) {
|
|
435
|
+
sp = this._inst.exports.getsp() >>> 0;
|
|
436
|
+
storeValue(sp + 56, err);
|
|
437
|
+
this.mem.setUint8(sp + 64, 0);
|
|
438
|
+
}
|
|
439
|
+
},
|
|
440
|
+
// func valueInvoke(v ref, args []ref) (ref, bool)
|
|
441
|
+
"syscall/js.valueInvoke": (sp) => {
|
|
442
|
+
sp >>>= 0;
|
|
443
|
+
try {
|
|
444
|
+
const v = loadValue(sp + 8);
|
|
445
|
+
const args = loadSliceOfValues(sp + 16);
|
|
446
|
+
const result = Reflect.apply(v, void 0, args);
|
|
447
|
+
sp = this._inst.exports.getsp() >>> 0;
|
|
448
|
+
storeValue(sp + 40, result);
|
|
449
|
+
this.mem.setUint8(sp + 48, 1);
|
|
450
|
+
} catch (err) {
|
|
451
|
+
sp = this._inst.exports.getsp() >>> 0;
|
|
452
|
+
storeValue(sp + 40, err);
|
|
453
|
+
this.mem.setUint8(sp + 48, 0);
|
|
454
|
+
}
|
|
455
|
+
},
|
|
456
|
+
// func valueNew(v ref, args []ref) (ref, bool)
|
|
457
|
+
"syscall/js.valueNew": (sp) => {
|
|
458
|
+
sp >>>= 0;
|
|
459
|
+
try {
|
|
460
|
+
const v = loadValue(sp + 8);
|
|
461
|
+
const args = loadSliceOfValues(sp + 16);
|
|
462
|
+
const result = Reflect.construct(v, args);
|
|
463
|
+
sp = this._inst.exports.getsp() >>> 0;
|
|
464
|
+
storeValue(sp + 40, result);
|
|
465
|
+
this.mem.setUint8(sp + 48, 1);
|
|
466
|
+
} catch (err) {
|
|
467
|
+
sp = this._inst.exports.getsp() >>> 0;
|
|
468
|
+
storeValue(sp + 40, err);
|
|
469
|
+
this.mem.setUint8(sp + 48, 0);
|
|
470
|
+
}
|
|
471
|
+
},
|
|
472
|
+
// func valueLength(v ref) int
|
|
473
|
+
"syscall/js.valueLength": (sp) => {
|
|
474
|
+
sp >>>= 0;
|
|
475
|
+
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
|
|
476
|
+
},
|
|
477
|
+
// valuePrepareString(v ref) (ref, int)
|
|
478
|
+
"syscall/js.valuePrepareString": (sp) => {
|
|
479
|
+
sp >>>= 0;
|
|
480
|
+
const str = encoder.encode(String(loadValue(sp + 8)));
|
|
481
|
+
storeValue(sp + 16, str);
|
|
482
|
+
setInt64(sp + 24, str.length);
|
|
483
|
+
},
|
|
484
|
+
// valueLoadString(v ref, b []byte)
|
|
485
|
+
"syscall/js.valueLoadString": (sp) => {
|
|
486
|
+
sp >>>= 0;
|
|
487
|
+
const str = loadValue(sp + 8);
|
|
488
|
+
loadSlice(sp + 16).set(str);
|
|
489
|
+
},
|
|
490
|
+
// func valueInstanceOf(v ref, t ref) bool
|
|
491
|
+
"syscall/js.valueInstanceOf": (sp) => {
|
|
492
|
+
sp >>>= 0;
|
|
493
|
+
this.mem.setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16) ? 1 : 0);
|
|
494
|
+
},
|
|
495
|
+
// func copyBytesToGo(dst []byte, src ref) (int, bool)
|
|
496
|
+
"syscall/js.copyBytesToGo": (sp) => {
|
|
497
|
+
sp >>>= 0;
|
|
498
|
+
const dst = loadSlice(sp + 8);
|
|
499
|
+
const src = loadValue(sp + 32);
|
|
500
|
+
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
|
|
501
|
+
this.mem.setUint8(sp + 48, 0);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const toCopy = src.subarray(0, dst.length);
|
|
505
|
+
dst.set(toCopy);
|
|
506
|
+
setInt64(sp + 40, toCopy.length);
|
|
507
|
+
this.mem.setUint8(sp + 48, 1);
|
|
508
|
+
},
|
|
509
|
+
// func copyBytesToJS(dst ref, src []byte) (int, bool)
|
|
510
|
+
"syscall/js.copyBytesToJS": (sp) => {
|
|
511
|
+
sp >>>= 0;
|
|
512
|
+
const dst = loadValue(sp + 8);
|
|
513
|
+
const src = loadSlice(sp + 16);
|
|
514
|
+
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
|
|
515
|
+
this.mem.setUint8(sp + 48, 0);
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const toCopy = src.subarray(0, dst.length);
|
|
519
|
+
dst.set(toCopy);
|
|
520
|
+
setInt64(sp + 40, toCopy.length);
|
|
521
|
+
this.mem.setUint8(sp + 48, 1);
|
|
522
|
+
},
|
|
523
|
+
"debug": (value) => {
|
|
524
|
+
console.log(value);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
run(instance) {
|
|
530
|
+
return __async(this, null, function* () {
|
|
531
|
+
if (!(instance instanceof WebAssembly.Instance)) {
|
|
532
|
+
throw new Error("Go.run: WebAssembly.Instance expected");
|
|
533
|
+
}
|
|
534
|
+
this._inst = instance;
|
|
535
|
+
this.mem = new DataView(this._inst.exports.mem.buffer);
|
|
536
|
+
this._values = [
|
|
537
|
+
// JS values that Go currently has references to, indexed by reference id
|
|
538
|
+
NaN,
|
|
539
|
+
0,
|
|
540
|
+
null,
|
|
541
|
+
true,
|
|
542
|
+
false,
|
|
543
|
+
globalThis,
|
|
544
|
+
this
|
|
545
|
+
];
|
|
546
|
+
this._goRefCounts = new Array(this._values.length).fill(Infinity);
|
|
547
|
+
this._ids = /* @__PURE__ */ new Map([
|
|
548
|
+
// mapping from JS values to reference ids
|
|
549
|
+
[0, 1],
|
|
550
|
+
[null, 2],
|
|
551
|
+
[true, 3],
|
|
552
|
+
[false, 4],
|
|
553
|
+
[globalThis, 5],
|
|
554
|
+
[this, 6]
|
|
555
|
+
]);
|
|
556
|
+
this._idPool = [];
|
|
557
|
+
this.exited = false;
|
|
558
|
+
let offset = 4096;
|
|
559
|
+
const strPtr = (str) => {
|
|
560
|
+
const ptr = offset;
|
|
561
|
+
const bytes = encoder.encode(str + "\\0");
|
|
562
|
+
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
|
|
563
|
+
offset += bytes.length;
|
|
564
|
+
if (offset % 8 !== 0) {
|
|
565
|
+
offset += 8 - offset % 8;
|
|
566
|
+
}
|
|
567
|
+
return ptr;
|
|
568
|
+
};
|
|
569
|
+
const argc = this.argv.length;
|
|
570
|
+
const argvPtrs = [];
|
|
571
|
+
this.argv.forEach((arg) => {
|
|
572
|
+
argvPtrs.push(strPtr(arg));
|
|
573
|
+
});
|
|
574
|
+
argvPtrs.push(0);
|
|
575
|
+
const keys = Object.keys(this.env).sort();
|
|
576
|
+
keys.forEach((key) => {
|
|
577
|
+
argvPtrs.push(strPtr(\`\${key}=\${this.env[key]}\`));
|
|
578
|
+
});
|
|
579
|
+
argvPtrs.push(0);
|
|
580
|
+
const argv = offset;
|
|
581
|
+
argvPtrs.forEach((ptr) => {
|
|
582
|
+
this.mem.setUint32(offset, ptr, true);
|
|
583
|
+
this.mem.setUint32(offset + 4, 0, true);
|
|
584
|
+
offset += 8;
|
|
585
|
+
});
|
|
586
|
+
const wasmMinDataAddr = 4096 + 8192;
|
|
587
|
+
if (offset >= wasmMinDataAddr) {
|
|
588
|
+
throw new Error("total length of command line and environment variables exceeds limit");
|
|
589
|
+
}
|
|
590
|
+
this._inst.exports.run(argc, argv);
|
|
591
|
+
if (this.exited) {
|
|
592
|
+
this._resolveExitPromise();
|
|
593
|
+
}
|
|
594
|
+
yield this._exitPromise;
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
_resume() {
|
|
598
|
+
if (this.exited) {
|
|
599
|
+
throw new Error("Go program has already exited");
|
|
600
|
+
}
|
|
601
|
+
this._inst.exports.resume();
|
|
602
|
+
if (this.exited) {
|
|
603
|
+
this._resolveExitPromise();
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
_makeFuncWrapper(id) {
|
|
607
|
+
const go = this;
|
|
608
|
+
return function() {
|
|
609
|
+
const event = { id, this: this, args: arguments };
|
|
610
|
+
go._pendingEvent = event;
|
|
611
|
+
go._resume();
|
|
612
|
+
return event.result;
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
};
|
|
616
|
+
})();
|
|
617
|
+
onmessage = ({ data: wasm }) => {
|
|
618
|
+
let decoder = new TextDecoder();
|
|
619
|
+
let fs = globalThis.fs;
|
|
620
|
+
let stderr = "";
|
|
621
|
+
fs.writeSync = (fd, buffer) => {
|
|
622
|
+
if (fd === 1) {
|
|
623
|
+
postMessage(buffer);
|
|
624
|
+
} else if (fd === 2) {
|
|
625
|
+
stderr += decoder.decode(buffer);
|
|
626
|
+
let parts = stderr.split("\\n");
|
|
627
|
+
if (parts.length > 1) console.log(parts.slice(0, -1).join("\\n"));
|
|
628
|
+
stderr = parts[parts.length - 1];
|
|
629
|
+
} else {
|
|
630
|
+
throw new Error("Bad write");
|
|
631
|
+
}
|
|
632
|
+
return buffer.length;
|
|
633
|
+
};
|
|
634
|
+
let stdin = [];
|
|
635
|
+
let resumeStdin;
|
|
636
|
+
let stdinPos = 0;
|
|
637
|
+
onmessage = ({ data }) => {
|
|
638
|
+
if (data.length > 0) {
|
|
639
|
+
stdin.push(data);
|
|
640
|
+
if (resumeStdin) resumeStdin();
|
|
641
|
+
}
|
|
642
|
+
return go;
|
|
643
|
+
};
|
|
644
|
+
fs.read = (fd, buffer, offset, length, position, callback) => {
|
|
645
|
+
if (fd !== 0 || offset !== 0 || length !== buffer.length || position !== null) {
|
|
646
|
+
throw new Error("Bad read");
|
|
647
|
+
}
|
|
648
|
+
if (stdin.length === 0) {
|
|
649
|
+
resumeStdin = () => fs.read(fd, buffer, offset, length, position, callback);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
let first = stdin[0];
|
|
653
|
+
let count = Math.max(0, Math.min(length, first.length - stdinPos));
|
|
654
|
+
buffer.set(first.subarray(stdinPos, stdinPos + count), offset);
|
|
655
|
+
stdinPos += count;
|
|
656
|
+
if (stdinPos === first.length) {
|
|
657
|
+
stdin.shift();
|
|
658
|
+
stdinPos = 0;
|
|
659
|
+
}
|
|
660
|
+
callback(null, count);
|
|
661
|
+
};
|
|
662
|
+
let go = new globalThis.Go();
|
|
663
|
+
go.argv = ["", \`--service=\${"0.28.2"}\`];
|
|
664
|
+
tryToInstantiateModule(wasm, go).then(
|
|
665
|
+
(instance) => {
|
|
666
|
+
postMessage(null);
|
|
667
|
+
go.run(instance);
|
|
668
|
+
},
|
|
669
|
+
(error) => {
|
|
670
|
+
postMessage(error);
|
|
671
|
+
}
|
|
672
|
+
);
|
|
673
|
+
return go;
|
|
674
|
+
};
|
|
675
|
+
function tryToInstantiateModule(wasm, go) {
|
|
676
|
+
return __async(this, null, function* () {
|
|
677
|
+
if (wasm instanceof WebAssembly.Module) {
|
|
678
|
+
return WebAssembly.instantiate(wasm, go.importObject);
|
|
679
|
+
}
|
|
680
|
+
const res = yield fetch(wasm);
|
|
681
|
+
if (!res.ok) throw new Error(\`Failed to download \${JSON.stringify(wasm)}\`);
|
|
682
|
+
if ("instantiateStreaming" in WebAssembly && /^application\\/wasm($|;)/i.test(res.headers.get("Content-Type") || "")) {
|
|
683
|
+
const result2 = yield WebAssembly.instantiateStreaming(res, go.importObject);
|
|
684
|
+
return result2.instance;
|
|
685
|
+
}
|
|
686
|
+
const bytes = yield res.arrayBuffer();
|
|
687
|
+
const result = yield WebAssembly.instantiate(bytes, go.importObject);
|
|
688
|
+
return result.instance;
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
return (m) => onmessage(m);
|
|
692
|
+
})(postMessage)`],{type:"text/javascript"});L=new Worker(URL.createObjectURL(de))}else{let de=(Ee=>{var Le=(me,fe,Z)=>new Promise((q,D)=>{var V=le=>{try{ee(Z.next(le))}catch(N){D(N)}},W=le=>{try{ee(Z.throw(le))}catch(N){D(N)}},ee=le=>le.done?q(le.value):Promise.resolve(le.value).then(V,W);ee((Z=Z.apply(me,fe)).next())});let Ue,pe={};for(let me=self;me;me=Object.getPrototypeOf(me))for(let fe of Object.getOwnPropertyNames(me))fe in pe||Object.defineProperty(pe,fe,{get:()=>self[fe]});(()=>{let me=()=>{let q=new Error("not implemented");return q.code="ENOSYS",q};if(!pe.fs){let q="";pe.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+=Z.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,ee,le,N){if(W!==0||ee!==V.length||le!==null){N(me());return}let X=this.writeSync(D,V);N(null,X)},chmod(D,V,W){W(me())},chown(D,V,W,ee){ee(me())},close(D,V){V(me())},fchmod(D,V,W){W(me())},fchown(D,V,W,ee){ee(me())},fstat(D,V){V(me())},fsync(D,V){V(null)},ftruncate(D,V,W){W(me())},lchown(D,V,W,ee){ee(me())},link(D,V,W){W(me())},lstat(D,V){V(me())},mkdir(D,V,W){W(me())},open(D,V,W,ee){ee(me())},read(D,V,W,ee,le,N){N(me())},readdir(D,V){V(me())},readlink(D,V){V(me())},rename(D,V,W){W(me())},rmdir(D,V){V(me())},stat(D,V){V(me())},symlink(D,V,W){W(me())},truncate(D,V,W){W(me())},unlink(D,V){V(me())},utimes(D,V,W,ee){ee(me())}}}if(pe.process||(pe.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw me()},pid:-1,ppid:-1,umask(){throw me()},cwd(){throw me()},chdir(){throw me()}}),pe.path||(pe.path={resolve(...q){return q.join("/")}}),!pe.crypto)throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");if(!pe.performance)throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");if(!pe.TextEncoder)throw new Error("globalThis.TextEncoder is not available, polyfill required");if(!pe.TextDecoder)throw new Error("globalThis.TextDecoder is not available, polyfill required");let fe=new TextEncoder("utf-8"),Z=new TextDecoder("utf-8");pe.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=C=>{C!==0&&console.warn("exit code:",C)},this._exitPromise=new Promise(C=>{this._resolveExitPromise=C}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let q=(C,O)=>{this.mem.setUint32(C+0,O,!0),this.mem.setUint32(C+4,Math.floor(O/4294967296),!0)},D=(C,O)=>{this.mem.setUint32(C+0,O,!0)},V=C=>{let O=this.mem.getUint32(C+0,!0),re=this.mem.getInt32(C+4,!0);return O+re*4294967296},W=C=>{let O=this.mem.getFloat64(C,!0);if(O===0)return;if(!isNaN(O))return O;let re=this.mem.getUint32(C,!0);return this._values[re]},ee=(C,O)=>{if(typeof O=="number"&&O!==0){if(isNaN(O)){this.mem.setUint32(C+4,2146959360,!0),this.mem.setUint32(C,0,!0);return}this.mem.setFloat64(C,O,!0);return}if(O===void 0){this.mem.setFloat64(C,0,!0);return}let he=this._ids.get(O);he===void 0&&(he=this._idPool.pop(),he===void 0&&(he=this._values.length),this._values[he]=O,this._goRefCounts[he]=0,this._ids.set(O,he)),this._goRefCounts[he]++;let Me=0;switch(typeof O){case"object":O!==null&&(Me=1);break;case"string":Me=2;break;case"symbol":Me=3;break;case"function":Me=4;break}this.mem.setUint32(C+4,2146959360|Me,!0),this.mem.setUint32(C,he,!0)},le=C=>{let O=V(C+0),re=V(C+8);return new Uint8Array(this._inst.exports.mem.buffer,O,re)},N=C=>{let O=V(C+0),re=V(C+8),he=new Array(re);for(let Me=0;Me<re;Me++)he[Me]=W(O+Me*8);return he},X=C=>{let O=V(C+0),re=V(C+8);return Z.decode(new DataView(this._inst.exports.mem.buffer,O,re))},oe=(C,O)=>(this._inst.exports.testExport0(),this._inst.exports.testExport(C,O)),Te=Date.now()-performance.now();this.importObject={_gotest:{add:(C,O)=>C+O,callExport:oe},gojs:{"runtime.wasmExit":C=>{C>>>=0;let O=this.mem.getInt32(C+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(O)},"runtime.wasmWrite":C=>{C>>>=0;let O=V(C+8),re=V(C+16),he=this.mem.getInt32(C+24,!0);pe.fs.writeSync(O,new Uint8Array(this._inst.exports.mem.buffer,re,he))},"runtime.resetMemoryDataView":C=>{C>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":C=>{C>>>=0,q(C+8,(Te+performance.now())*1e6)},"runtime.walltime":C=>{C>>>=0;let O=new Date().getTime();q(C+8,O/1e3),this.mem.setInt32(C+16,O%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":C=>{C>>>=0;let O=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(O,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(O);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},V(C+8))),this.mem.setInt32(C+16,O,!0)},"runtime.clearTimeoutEvent":C=>{C>>>=0;let O=this.mem.getInt32(C+8,!0);clearTimeout(this._scheduledTimeouts.get(O)),this._scheduledTimeouts.delete(O)},"runtime.getRandomData":C=>{C>>>=0,crypto.getRandomValues(le(C+8))},"syscall/js.finalizeRef":C=>{C>>>=0;let O=this.mem.getUint32(C+8,!0);if(this._goRefCounts[O]--,this._goRefCounts[O]===0){let re=this._values[O];this._values[O]=null,this._ids.delete(re),this._idPool.push(O)}},"syscall/js.stringVal":C=>{C>>>=0,ee(C+24,X(C+8))},"syscall/js.valueGet":C=>{C>>>=0;let O=Reflect.get(W(C+8),X(C+16));C=this._inst.exports.getsp()>>>0,ee(C+32,O)},"syscall/js.valueSet":C=>{C>>>=0,Reflect.set(W(C+8),X(C+16),W(C+32))},"syscall/js.valueDelete":C=>{C>>>=0,Reflect.deleteProperty(W(C+8),X(C+16))},"syscall/js.valueIndex":C=>{C>>>=0,ee(C+24,Reflect.get(W(C+8),V(C+16)))},"syscall/js.valueSetIndex":C=>{C>>>=0,Reflect.set(W(C+8),V(C+16),W(C+24))},"syscall/js.valueCall":C=>{C>>>=0;try{let O=W(C+8),re=Reflect.get(O,X(C+16)),he=N(C+32),Me=Reflect.apply(re,O,he);C=this._inst.exports.getsp()>>>0,ee(C+56,Me),this.mem.setUint8(C+64,1)}catch(O){C=this._inst.exports.getsp()>>>0,ee(C+56,O),this.mem.setUint8(C+64,0)}},"syscall/js.valueInvoke":C=>{C>>>=0;try{let O=W(C+8),re=N(C+16),he=Reflect.apply(O,void 0,re);C=this._inst.exports.getsp()>>>0,ee(C+40,he),this.mem.setUint8(C+48,1)}catch(O){C=this._inst.exports.getsp()>>>0,ee(C+40,O),this.mem.setUint8(C+48,0)}},"syscall/js.valueNew":C=>{C>>>=0;try{let O=W(C+8),re=N(C+16),he=Reflect.construct(O,re);C=this._inst.exports.getsp()>>>0,ee(C+40,he),this.mem.setUint8(C+48,1)}catch(O){C=this._inst.exports.getsp()>>>0,ee(C+40,O),this.mem.setUint8(C+48,0)}},"syscall/js.valueLength":C=>{C>>>=0,q(C+16,parseInt(W(C+8).length))},"syscall/js.valuePrepareString":C=>{C>>>=0;let O=fe.encode(String(W(C+8)));ee(C+16,O),q(C+24,O.length)},"syscall/js.valueLoadString":C=>{C>>>=0;let O=W(C+8);le(C+16).set(O)},"syscall/js.valueInstanceOf":C=>{C>>>=0,this.mem.setUint8(C+24,W(C+8)instanceof W(C+16)?1:0)},"syscall/js.copyBytesToGo":C=>{C>>>=0;let O=le(C+8),re=W(C+32);if(!(re instanceof Uint8Array||re instanceof Uint8ClampedArray)){this.mem.setUint8(C+48,0);return}let he=re.subarray(0,O.length);O.set(he),q(C+40,he.length),this.mem.setUint8(C+48,1)},"syscall/js.copyBytesToJS":C=>{C>>>=0;let O=W(C+8),re=le(C+16);if(!(O instanceof Uint8Array||O instanceof Uint8ClampedArray)){this.mem.setUint8(C+48,0);return}let he=re.subarray(0,O.length);O.set(he),q(C+40,he.length),this.mem.setUint8(C+48,1)},debug:C=>{console.log(C)}}}}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,pe,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[pe,5],[this,6]]),this._idPool=[],this.exited=!1;let D=4096,V=oe=>{let Te=D,C=fe.encode(oe+"\0");return new Uint8Array(this.mem.buffer,D,C.length).set(C),D+=C.length,D%8!==0&&(D+=8-D%8),Te},W=this.argv.length,ee=[];this.argv.forEach(oe=>{ee.push(V(oe))}),ee.push(0),Object.keys(this.env).sort().forEach(oe=>{ee.push(V(`${oe}=${this.env[oe]}`))}),ee.push(0);let N=D;if(ee.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,N),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:me})=>{let fe=new TextDecoder,Z=pe.fs,q="";Z.writeSync=(le,N)=>{if(le===1)Ee(N);else if(le===2){q+=fe.decode(N);let X=q.split(`
|
|
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 O=D[0],re=Math.max(0,Math.min(oe,O.length-W));N.set(O.subarray(W,W+re),X),W+=re,W===O.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=>L.onmessage({data:Ee})),Be;L={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});L.onmessage=({data:de})=>{L.onmessage=({data:Be})=>te(Be),de?se(de):H()},L.postMessage(v||new URL(x,location.href).toString());let{readFromStdout:te,service:ae}=D0({writeToStdin(de){L.postMessage(de)},isSync:!1,hasFS:!1,esbuild:l});yield B,Ra=()=>{L.terminate(),Tn=void 0,Ra=void 0,Ba=void 0},Ba={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)})})}}),ey=l})(typeof Ud=="object"?Ud:{set exports(r){(typeof self<"u"?self:this).esbuild=r}})});import{resolveSurfaceSource as qx,CanvasRenderContext2D as jx,withRichTextDescriptor as Gx,fillOps as Kx,strokeOps as $x,shadowOps as Xx,alignmentOps as Qx,resolveShapeAlignment as Yx,resolvePivotPosition as Zx,stripShapeAlignmentKeys as Jx}from"@motionscript/core";import{canvas3DResourceKey as Yd,parseCanvas3DResourceKey as ay,registerCanvas3DResourceLoader as oy,registerCanvas3DWarmup as cy}from"@motionscript/core";var gl=null,Qd=null,Da=new Set,Ts=new Map;function yl(){return gl}function vs(){return gl?Promise.resolve():(Qd??=import("./chunks/three.module-Z4EOVUWF.js").then(r=>(gl=r,r)),Qd.then(()=>{}))}function wl(r){Da.add(r)}function bl(){return Da.size>0||Ts.size>0}function Zd(r,e){Ts.set(r,e)}async function kl(){let r=!1;for(let e=0;e<4&&!(Da.size===0&&Ts.size===0);e++){Da.clear();let t=[...Ts];Ts.clear(),await vs(),t.length>0&&await Promise.all(t.map(([n])=>Jd(n))),r=!0}return r}var Oa=new Map;async function Jd(r){let e=ay(r);if(e?.kind!=="gltf")return;let t=await ly(e.src);t&&Oa.set(r,t)}function vn(r){return Oa.get(Yd("gltf",r))??null}async function ly(r){try{let[,e,t]=await Promise.all([vs(),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 uy(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 xl(){cy(vs),oy(async(r,e)=>{let t=Yd(r,e);await Jd(t);let n=Oa.get(t);return n?()=>{Oa.delete(t),uy(n)}:()=>{}})}import{canvas3DResourceKey as qy}from"@motionscript/core";var eh=null;function Sl(r){eh=r}function An(){return eh}import{parseColor as th}from"@motionscript/core";function He(r){return r*(Math.PI/180)}function rh(r,e){switch(e){case"back":return r.BackSide;case"both":return r.DoubleSide;default:return r.FrontSide}}function nh(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 Tl(r,e){switch(e){case"repeat":return r.RepeatWrapping;case"mirror":return r.MirroredRepeatWrapping;default:return r.ClampToEdgeWrapping}}function ih(r,e){return e==="nearest"?r.NearestFilter:r.LinearFilter}function sh(r,e){return e==="nearest"?r.NearestFilter:r.LinearMipmapLinearFilter}function ah(r,e){return e==="linear"?r.LinearSRGBColorSpace:r.SRGBColorSpace}function oh(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 ch(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"?th(t):t;return e.setRGB(n,i,s,r.SRGBColorSpace),a}function vl(r,e){let t=new r.Color;return xt(r,t,e),t}function Al(r){let[,,,e]=typeof r=="string"?th(r):r;return e}import{cylinderRadii as dy,evaluateParametric as lh,evaluateRoundedBox as hy,resolveBevel3D as fy,resolveVector3 as uh,segmentsOf as St,toPathString as my}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?_l(r,hy({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]=dy(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 gy(r,e.shape,e.radius??1,e.segments===void 0?0:t)}case"extrude":return yy(r,e);case"lathe":{let[t]=St(e.segments,[12]);return new r.LatheGeometry(e.points.map(n=>Sy(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=>xy(r,i)),e.closed??!1),t,e.radius??1,n,e.closed??!1)}case"buffer":return _l(r,e);case"parametric":return _l(r,lh(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 py(vn(e.src)?.scene,e.node)?.geometry.clone()??new r.BufferGeometry;default:return new r.BufferGeometry}}function py(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 gy(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 yy(r,e){let t=e.path,n=typeof t=="object"&&"toPathState"in t?t.toPathState().data:t,i=wy(r,my(n));if(i.length===0)return new r.BufferGeometry;let[s]=St(e.segments,[12]),a=fy(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 wy(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 _l(r,e){let t=new r.BufferGeometry;return t.setAttribute("position",new r.BufferAttribute(Ua(e.position),3)),e.normal&&t.setAttribute("normal",new r.BufferAttribute(Ua(e.normal),3)),e.uv&&t.setAttribute("uv",new r.BufferAttribute(Ua(e.uv),2)),e.color&&t.setAttribute("color",new r.BufferAttribute(Ua(e.color),3)),e.index&&t.setIndex(new r.BufferAttribute(ky(e.index),1)),e.computeNormals&&!e.normal&&t.computeVertexNormals(),t}function dh(r,e){if(!La(r,"position",e.position,3)||!La(r,"normal",e.normal,3)||!La(r,"uv",e.uv,2)||!La(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 La(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;by(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 hh(r){return r.type==="parametric"?!0:r.type!=="buffer"?!1:r.staticData!==!0}function fh(r){return r.type==="parametric"?lh(r):r}function by(r){return ArrayBuffer.isView(r)?!0:Array.isArray(r)&&r.length>4}function Ua(r){return r instanceof Float32Array?r:new Float32Array(Array.from(r))}function ky(r){return r instanceof Uint32Array?r:new Uint32Array(Array.from(r))}function xy(r,e){let t=uh(e);return new r.Vector3(t.x,t.y,t.z)}function Sy(r,e){let t=uh(e);return new r.Vector2(t.x,t.y)}import{STRUCTURAL_MATERIAL_KEYS as gh}from"@motionscript/core";var Pl=["map","alphaMap","aoMap","normalMap","displacementMap","envMap","lightMap","emissionMap","roughnessMap","metalnessMap","specularMap","gradientMap","matcap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap"],Cl={emission:"emissive",emissionStrength:"emissiveIntensity",emissionMap:"emissiveMap"},Ty=new Set(["normalMap","roughnessMap","metalnessMap","aoMap","displacementMap","alphaMap","clearcoatRoughnessMap","clearcoatNormalMap","transmissionMap","thicknessMap"]),mh=["color","emission","specular","sheenColor","specularColor","attenuationColor"];function vy(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&&Al(e.color)<1}function Ay(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 _y(r,e);default:return new r.MeshStandardMaterial}}function _y(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=Ay(r,e);return si(r,n,e,t,!0),n}function si(r,e,t,n,i=!1){let s=t,a=e,o;for(let l of mh){let u=s[l];if(u===void 0)continue;let d=Cl[l]??l,h=a[d];if(h&&typeof h=="object"&&"setRGB"in h?xt(r,h,u):a[d]=vl(r,u),l==="color"){let f=Al(u);f<1&&(o=f)}}for(let l of Object.keys(s)){if(l==="type"||l==="params"||mh.includes(l)||Pl.includes(l)||l==="uniforms"||l==="vertex"||l==="fragment"||l==="defines"||l==="raw"||l==="extends"||!i&&gh.includes(l)||l==="transparent")continue;let u=s[l];if(u!==void 0)switch(l){case"faces":e.side=rh(r,u);break;case"shading":a.flatShading=u==="flat";break;case"blend":e.blending=nh(r,u);break;case"normalScale":Cy(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[Cl[l]??l]=u;break}}o!==void 0&&s.opacity===void 0&&(e.opacity=o);let c=vy(t);!e.transparent&&c&&(e.transparent=!0,e.needsUpdate=!0),s.depthWrite===void 0&&(e.depthWrite=!c);for(let l of Pl){let u=s[l];u!==void 0&&(a[Cl[l]??l]=n.resolve(u,Ty.has(l)?"linear":"srgb"))}if(t.type==="shader"&&Py(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 Cy(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 Py(r,e,t,n){if(t)for(let i of Object.keys(t)){let s=Ey(r,t[i],n),a=e.uniforms[i];a?a.value=s:e.uniforms[i]={value:s}}}function Ey(r,e,t){if(typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return Iy(e)?t.resolve(e,"srgb"):vl(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 Iy(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 gh){let i=e[n];i!==void 0&&t.push(`${n}=${JSON.stringify(i)}`)}for(let n of Pl)e[n]!==void 0&&t.push(`+${n}`);return r.type==="shader"&&(t.push(`v=${ph(r.vertex)}`,`f=${ph(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 ph(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 yh,resolveVector3 as My}from"@motionscript/core";var Fy=4*Math.PI;function wh(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 bh(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"?Fy: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=My(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 kh(r,e,t){if(!("shadow"in r)||!r.shadow)return;let n=e.shadow,i=n===void 0?null:yh(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??Ry(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 Ry(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 xh(r){let e=r.shadow,t=e!==void 0&&yh(e)!==null,n=[r.type];return t&&n.push("shadow"),r.params&&n.push(`params=${JSON.stringify(r.params)}`),n.join("|")}import{resolveCameraPlacement as Ly}from"@motionscript/core";import{resolveVector3 as za,shadowCasts as By,shadowReceives as Dy}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;return}if(e.position!==void 0){let t=za(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=za(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=za(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?Oy(r,e.rotation):r.rotation.set(0,0,0);r.visible=e.visible!==!1,r.castShadow=By(e.shadow),r.receiveShadow=Dy(e.shadow),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder)}function Oy(r,e){let t=za(e),n=e?.order;r.rotation.set(He(t.x),He(t.y),He(t.z),n??"XYZ")}function Sh(r,e,t){return t.type==="perspective"?e instanceof r.PerspectiveCamera:e instanceof r.OrthographicCamera}function El(r,e){return e?.type==="orthographic"?new r.OrthographicCamera:new r.PerspectiveCamera}function Th(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=Uy(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=Ly(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 Uy(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 zy}from"@motionscript/core";function vh(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 Ah(r,e,t,n){if(!t){e.environment?.dispose(),e.environment=null,e.background=null;return}let i=Ny(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}=zy(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 Ny(r,e,t,n){if(t.preset===void 0||!n)return null;let i=e.userData.__roomEnvironment;if(i)return i;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=o.texture,o.texture}function _h(r){return vn(r)?.clone()??null}function Ch(r){return vn(r)!==null}function Ph(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=Hy(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=Wy(o.time,c.duration)}return a.mixer.update(0),a}function Eh(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=Vy(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 Ih(r){return r?Object.keys(r).sort().map(e=>`${e}=${JSON.stringify(r[e])}`).join("&"):""}function Vy(r,e,t){return r[e]!==void 0?e:t!==void 0&&r[t]!==void 0?t:null}function Hy(r,e){return e===void 0?r[0]:typeof e=="number"?r[e]:r.find(t=>t.name===e)}function Wy(r,e){if(!Number.isFinite(r)||e<=0)return 0;let t=r%e;return t<0?t+e:t}var Na=class{three;scene;camera;cache=new Map;frame=0;constructor(e){this.three=e,this.scene=new e.Scene,this.camera=El(e,null)}sync(e,t,n,i){this.frame++;let s=this.three,a=[-1],o=[this.scene],c=[""],l=new Map,u=[],d=null,h=!1;for(let b of e.ops()){if(b.kind==="pop"){o.length>1&&(o.pop(),a.pop(),c.pop());continue}a[a.length-1]++;let k=c[c.length-1],T=o[o.length-1];if(b.kind==="push"){let M=k?`${k}.${a[a.length-1]}`:String(a[a.length-1]),P=this.resolveGroup(M,b.transform,T);o.push(P),a.push(-1),c.push(b.transform?.key?`@${b.transform.key}`:M);continue}if(b.kind==="camera"){d={descriptor:b.camera,parent:T},h=!0;continue}let S=Gy(b),A=this.resolveDrawable(b,jy(k,b,S,l),T,i,S);A&&b.kind==="light"&&u.push({light:A.object,descriptor:b.light})}this.sweep();let f=this.sceneBounds();for(let{light:b,descriptor:k}of u)kh(b,k,f);d&&this.resolveCamera(d.descriptor,t,n,d.parent,f),vh(s,this.scene,e.fogDescriptor());let p=An();Ah(s,this.scene,e.environmentDescriptor(),p?.active()??null);let m=e.shadowSettings(),g=e.toneSettings(),y=oh(s,m?.quality);p?.applySettings(s,{shadowsEnabled:m?.enabled===!0,shadowType:y.type,toneMapping:ch(s,g?.mapping),toneMappingExposure:g?.exposure??1});for(let{light:b}of u){let k=b.shadow;k&&k.mapSize.x!==y.mapSize&&(k.mapSize.set(y.mapSize,y.mapSize),k.map?.dispose(),k.map=null)}return h||this.resolveCamera(null,t,n,this.scene,f),{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&&$y(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 wh(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=_h(e.src);return i||Zd(qy("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(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),si(i,s.material,t.material,n),this.writeInstances(s,t.instances,t.colors);break}case"sprite":si(i,e.object.material,t.material,n);break;case"light":bh(i,e.object,t.light);break;case"model":e.modelPlayback=Ph(i,e.object,t.src,t.animation,e.modelPlayback),Eh(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++)si(this.three,e[s],t[s],n);return}!Array.isArray(e)&&!Array.isArray(t)&&si(this.three,e,t,n)}refreshDynamicGeometry(e,t,n){if(!hh(t))return;if(t.type==="parametric"&&t.revision!==void 0){if(n.parametricRevision===t.revision)return;n.parametricRevision=t.revision}let i=fh(t);dh(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++)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&&!Sh(a,this.camera,e)&&(this.camera=El(a,e)),Th(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(),Mh(e.object))}dispose(){for(let t of this.cache.values())this.discard(t);this.cache.clear(),this.scene.userData.__roomEnvironment?.dispose(),this.scene.userData.__roomEnvironment=void 0,this.scene.environment=null,this.scene.clear()}};function jy(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 Gy(r){switch(r.kind){case"mesh":return{geometrySig:_n(r.geometry),materialSig:Ky(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:xh(r.light)};case"model":return{geometrySig:`${r.src}|${Ch(r.src)?"1":"0"}`,materialSig:Ih(r.override)};default:return{}}}function Ky(r){return Array.isArray(r)?r.map(Cn).join("&"):Cn(r)}function $y(r,e){return r.geometrySig===e.geometrySig&&r.materialSig===e.materialSig&&r.lightSig===e.lightSig&&r.count===e.count}function Mh(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])Mh(n)}import{isDataTexture3D as Bh,isSurfaceTexture3D as Dh,resolveTexture3D as Xy}from"@motionscript/core";var or=new Map,Fl=new Map,Il=0,Va=class{three;assets;surfaceOwner="";rasters;constructor(e,t){this.three=e,this.assets=t}beginFrame(){Il++}setRasters(e,t){this.surfaceOwner=e,this.rasters=t}resolve(e,t){let n=Xy(e),i=Qy(e,t,this.surfaceOwner);if(Dh(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(!Bh(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=Fl.get(e);n||Fl.set(e,n=new Map),n.set(t,Il);for(let[i,s]of n)s>=Il-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(Rh(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=Rh(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=Tl(i,s.wrapS),e.wrapT=Tl(i,s.wrapT),e.magFilter=ih(i,s.magFilter),e.minFilter=sh(i,s.minFilter),e.colorSpace=ah(i,s.colorSpace??n),s.repeat){let[a,o]=Ml(s.repeat);e.repeat.set(a,o)}if(s.offset){let[a,o]=Ml(s.offset);e.offset.set(a,o)}if(s.center){let[a,o]=Ml(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 Qy(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 Bh(r)&&i.push(`data=${r.width}x${r.height}`),Dh(r)&&i.push(`owner=${t}`,`sfc=${Zy(r)}`),i.push(`cs=${e}`),i.join("|")}var Fh=new WeakMap,Yy=0;function Zy(r){if(r.identity!==void 0)return r.identity;let e=r.source,t=Fh.get(e);return t===void 0&&(t=`s${Yy++}`,Fh.set(e,t)),t}function Ml(r){return Array.isArray(r)?[r[0],r[1]]:[r.x,r.y]}function Rh(r){return r instanceof Uint8Array?r:new Uint8Array(Array.from(r))}function Oh(){for(let r of or.values())r.texture.dispose();or.clear(),Fl.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 Va(e,t)}render(e,t,n,i,s={}){let a=this.graphs.get(e);a||(a=new Na(this.three),this.graphs.set(e,a)),this.touched.add(e),this.textures.setRasters(e,s.rasters);let{scene:o,camera:c}=a.sync(t,n,i,this.textures);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}},Ha=null;function oi(r){let e=yl();if(!e)return null;let t=An();return t?(Ha??=new As(e,r,t),Ha):null}function Wa(){Ha?.dispose(),Ha=null}import{forEachTexture3D as zk,isSurfaceTexture3D as Nk}from"@motionscript/core";function qa(r){return 1/Math.max(r.getDeviceScale(),1e-4)}var qe=class{dispose(){}};import{AssetNotLoadedError as Fk,isPixelFilter as Rk}from"@motionscript/core";var Jy=[224,224,224],ew=[200,200,200],_s=null;function tw(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?Jy:ew,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 ja(r){let e=r.canvasKit;if(_s??=tw(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 Lh(){_s?.delete(),_s=null}import{effectSurface as Pk}from"@motionscript/core";var Uh={type:"blur",makeImageFilter(r,e){let t=r.radius/2;return e.ImageFilter.MakeBlur(t,t,e.TileMode.Decal,null)}};var zh={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 Nh={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 Vh={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 Hh={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 Wh={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 qh={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 rw=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],ci=.2126,li=.7152,ui=.0722;function nw(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*ci-1,2*li,2*ui,0,0,2*ci,2*li-1,2*ui,0,0,2*ci,2*li,2*ui-1,0,0,0,0,0,1,0];case"luminance":return[1-2*ci,-2*li,-2*ui,0,1,-2*ci,1-2*li,-2*ui,0,1,-2*ci,-2*li,1-2*ui,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 jh={type:"invert",makeImageFilter(r,e){let t=Math.max(0,Math.min(1,r.strength));if(t===0)return null;let n=nw(r.channel),i=rw.map((o,c)=>o+(n[c]-o)*t),s=e.ColorFilter.MakeMatrix(i),a=e.ImageFilter.MakeColorFilter(s,null);return s.delete(),a}};var di=new Map,iw=64,Rl=!1;function ne(r,e){let t=di.get(r);if(t)return t;let n=e.RuntimeEffect.Make(r,i=>{console.warn("[SkSL] Compilation error:",i)});return n&&di.set(r,n),di.size>iw&&!Rl&&(Rl=!0,console.warn(`[SkSL] ${di.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 Gh(){for(let r of di.values())r.delete();di.clear(),Rl=!1}import{resolveEffectAxis as sw}from"@motionscript/core";function hi(r,e){return r.mode==="backdrop"?[0,0]:[e.centerX-e.width/2,e.centerY-e.height/2]}var aw=`
|
|
696
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
697
|
+
uniform vec2 u_origin; // node box top-left, device px (0,0 on a backdrop)
|
|
698
|
+
uniform vec2 u_offset; // max displacement per axis, device px
|
|
699
|
+
|
|
700
|
+
float hash(vec2 p, float salt) {
|
|
701
|
+
return fract(sin(dot(p, vec2(127.1, 311.7)) + salt) * 43758.5453);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
vec4 main(vec2 fragCoord) {
|
|
705
|
+
// Quantised to the pixel so one pixel gets one offset. An unquantised hash
|
|
706
|
+
// of a continuous coordinate takes a different value at every sample, which
|
|
707
|
+
// reads as static rather than as a smear.
|
|
708
|
+
vec2 cell = floor(fragCoord - u_origin);
|
|
709
|
+
vec2 jitter = vec2(hash(cell, 0.0), hash(cell, 37.13)) * 2.0 - 1.0;
|
|
710
|
+
return u_content.eval(fragCoord + jitter * u_offset);
|
|
711
|
+
}
|
|
712
|
+
`;function ow(r,e,t,n,i=[0,0]){if(!(r.strength>0))return null;let s=ne(aw,e);if(!s)return null;let a=sw(r.axis),o=r.strength*n;return s.makeShaderWithChildren([i[0],i[1],o*a.x,o*a.y],[t])}var Kh={type:"scatter",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>ow(r,e,t,n.scale,hi(r,n))};import{resolveEffectAxis as cw,resolveMotionBlurAlignment as lw}from"@motionscript/core";var uw=32,dw=64;function $h(r,e,t){if(t<=0||r.strength<=0||r.length<=0)return null;let n=cw(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:lw(r.alignment),samples:r.samples}}var Xh={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),dw);return c>uw?fw(r,e,n,i,a,o,c):hw(r,e,n,i,a,o)}};function hw(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 fw(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 gw,writeUniforms as yw}from"@motionscript/core";function Gt(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 mw,parseShaderChildren as pw}from"@motionscript/core";var Qh=new WeakMap;function Cs(r,e){let t=Qh.get(r);if(t)return t;let n={slots:mw(r),floats:r.getUniformFloatCount(),children:pw(e)};return Qh.set(r,n),n}var Ga=new Set;function Yr(r){Ga.has(r)||(Ga.size>512&&Ga.clear(),Ga.add(r),console.warn(`[SkSL] ${r}`))}var Yh="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 bw={};function Zh(r,e,t){return yw(r.slots,r.floats,gw(e.uniforms),t,e.source)}function kw(r,e){let t=[];for(let n of r.children){if(n.name===Yh&&n.kind==="shader"){t.push(e);continue}return Yr(`a backdrop shader effect declares "${n.name}", which nothing supplies \u2014 an effect can only sample "${Yh}".`),null}return t}var Jh={type:"shader",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop"&&r.mode==="backdrop",makeShader(r,e,t,n){let i=ne(r.source,e);if(!i)return null;let s=Cs(i,r.source),a=Zh(s,r,ww(n)),o=kw(s,t);if(!o)return null;let c=i.makeShaderWithChildren(a,o);return c||(Yr(`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=ne(r.source,e);if(!t)return null;let n=Cs(t,r.source);if(n.children.length>0)return Yr(`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(Zh(n,r,bw));if(!i)return null;let s=e.ImageFilter.MakeShader(i);i.delete();let a=Gt(e,r.blendMode??"screen"),o=e.ImageFilter.MakeBlend(a,null,s);return s.delete(),o}};var Dl=new WeakMap,Ol=new Set;function xw(r,e){let t=Dl.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]=Bl(r.table[f]),a[p+1]=Bl(r.table[f+1]),a[p+2]=Bl(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 Dl.set(r.table,l),Ol.add(l),c}function Bl(r){return Number.isFinite(r)?Math.max(0,Math.min(255,Math.round(r*255))):0}var Sw=`
|
|
713
|
+
uniform shader u_content;
|
|
714
|
+
uniform shader u_lut;
|
|
715
|
+
uniform float u_size;
|
|
716
|
+
uniform float u_amount;
|
|
717
|
+
|
|
718
|
+
vec3 lookup(vec3 c) {
|
|
719
|
+
float n = u_size;
|
|
720
|
+
vec3 q = clamp(c, 0.0, 1.0) * (n - 1.0);
|
|
721
|
+
|
|
722
|
+
float b0 = floor(q.b);
|
|
723
|
+
float b1 = min(b0 + 1.0, n - 1.0);
|
|
724
|
+
float fb = q.b - b0;
|
|
725
|
+
|
|
726
|
+
// Texel centres inside a tile: red spans [0.5, n-0.5], so linear filtering
|
|
727
|
+
// interpolates red and green and never reaches the neighbouring slice.
|
|
728
|
+
vec2 uv = vec2(q.r + 0.5, q.g + 0.5);
|
|
729
|
+
|
|
730
|
+
vec3 lo = u_lut.eval(vec2(uv.x + b0 * n, uv.y)).rgb;
|
|
731
|
+
vec3 hi = u_lut.eval(vec2(uv.x + b1 * n, uv.y)).rgb;
|
|
732
|
+
return mix(lo, hi, fb);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
vec4 main(vec2 p) {
|
|
736
|
+
vec4 src = u_content.eval(p);
|
|
737
|
+
// Nothing to grade, and dividing by zero alpha would make a NaN that spreads.
|
|
738
|
+
if (src.a <= 0.0) return src;
|
|
739
|
+
|
|
740
|
+
// The lookup is defined on straight colour; the shader is handed (and must
|
|
741
|
+
// return) premultiplied.
|
|
742
|
+
vec3 rgb = src.rgb / src.a;
|
|
743
|
+
vec3 graded = mix(rgb, lookup(rgb), clamp(u_amount, 0.0, 1.0));
|
|
744
|
+
return vec4(graded * src.a, src.a);
|
|
745
|
+
}
|
|
746
|
+
`,ef={type:"lut",sampling:{tileMode:"clamp",filterMode:"linear"},resources(r,e){let t=xw(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=ne(Sw,e);return a?a.makeShaderWithChildren([r.size,r.amount],[t,s]):null},dispose(){for(let{image:r,shader:e}of Ol)e.delete(),r.delete();Ol.clear(),Dl=new WeakMap}};var Tw=`
|
|
747
|
+
uniform shader u_content; // snapshot of the source (node content, or backdrop)
|
|
748
|
+
uniform vec2 u_center; // node centre, device px
|
|
749
|
+
uniform vec2 u_half; // node half-extent (halfWidth, halfHeight), device px
|
|
750
|
+
uniform float u_strength; // + bulge (barrel), \u2212 pinch (pincushion)
|
|
751
|
+
|
|
752
|
+
vec4 main(vec2 fragCoord) {
|
|
753
|
+
vec2 p = (fragCoord - u_center) / max(u_half, vec2(1.0));
|
|
754
|
+
float r = length(p);
|
|
755
|
+
float k = u_strength > 0.0 ? u_strength * 2.0 : u_strength * 0.8;
|
|
756
|
+
float scale = 1.0 + k;
|
|
757
|
+
vec2 distorted = p * (1.0 + k * r * r) / scale;
|
|
758
|
+
vec2 samplePos = u_center + distorted * u_half;
|
|
759
|
+
return u_content.eval(samplePos);
|
|
760
|
+
}
|
|
761
|
+
`;function vw(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=ne(Tw,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 tf={type:"bulge",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>vw(r,e,t,n.centerX,n.centerY,n.width,n.height)};var Aw=`
|
|
762
|
+
uniform shader u_backdrop;
|
|
763
|
+
uniform vec2 u_center; // lens centre, device px
|
|
764
|
+
uniform float u_scale; // magnification factor (1 = none, 2 = 2x)
|
|
765
|
+
|
|
766
|
+
vec4 main(vec2 fragCoord) {
|
|
767
|
+
vec2 samplePos = u_center + (fragCoord - u_center) / max(u_scale, 0.001);
|
|
768
|
+
return u_backdrop.eval(samplePos);
|
|
769
|
+
}
|
|
770
|
+
`;function _w(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=ne(Aw,e);return u?u.makeShaderWithChildren([c,l,o],[t]):null}var rf={type:"magnify",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop",makeShader:(r,e,t,n)=>_w(r,e,t,n.centerX,n.centerY,n.width,n.height)};var Cw=`
|
|
771
|
+
uniform shader u_content; // snapshot of the node's own content (premultiplied)
|
|
772
|
+
uniform float u_level; // number of brightness bands per channel (>= 2)
|
|
773
|
+
|
|
774
|
+
vec4 main(vec2 fragCoord) {
|
|
775
|
+
vec4 c = u_content.eval(fragCoord);
|
|
776
|
+
float a = c.a;
|
|
777
|
+
if (a <= 0.0) return vec4(0.0);
|
|
778
|
+
|
|
779
|
+
vec3 base = c.rgb / a; // un-premultiply to straight colour
|
|
780
|
+
float L = max(floor(u_level + 0.5), 2.0);
|
|
781
|
+
vec3 q = min(floor(base * L), L - 1.0) / (L - 1.0);
|
|
782
|
+
q = clamp(q, 0.0, 1.0);
|
|
783
|
+
return vec4(q * a, a); // re-premultiply
|
|
784
|
+
}
|
|
785
|
+
`;function Pw(r,e,t){if(r.levels<2)return null;let n=ne(Cw,e);return n?n.makeShaderWithChildren([r.levels],[t]):null}var nf={type:"posterize",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>Pw(r,e,t)};import{resolveEffectColor as Ew}from"@motionscript/core";var Ll=[12,16,24,32,40],Iw=3;function Mw(r){let e=2*Math.PI*r/Iw;return Ll.find(t=>t>=e)??Ll[Ll.length-1]}function Fw(r,e){let t=r!=="inside",n=r!=="outside",i=r!=="outside",s=(2*Math.PI/e).toFixed(8);return`
|
|
786
|
+
uniform shader u_content; // snapshot of the node's own content (premultiplied)
|
|
787
|
+
${t?"uniform float u_radiusOut; // dilate distance, device px":""}
|
|
788
|
+
${n?"uniform float u_radiusIn; // erode distance, device px":""}
|
|
789
|
+
uniform vec4 u_color; // band colour, straight RGBA
|
|
790
|
+
|
|
791
|
+
vec4 main(vec2 fragCoord) {
|
|
792
|
+
vec4 src = u_content.eval(fragCoord);
|
|
793
|
+
${r==="outside"?` if (src.a >= 1.0) return src; // fully inside: no outward band here
|
|
794
|
+
`:r==="inside"?` if (src.a <= 0.0) return src; // fully outside: no inward band here
|
|
795
|
+
`:""}
|
|
796
|
+
float dilated = src.a;
|
|
797
|
+
float eroded = src.a;
|
|
798
|
+
for (int i = 0; i < ${e}; i++) {
|
|
799
|
+
float angle = float(i) * ${s};
|
|
800
|
+
vec2 dir = vec2(cos(angle), sin(angle));
|
|
801
|
+
${t?" dilated = max(dilated, u_content.eval(fragCoord + dir * u_radiusOut).a);":""}
|
|
802
|
+
${n?` eroded = min(eroded, u_content.eval(fragCoord + dir * u_radiusIn).a);
|
|
803
|
+
eroded = min(eroded, u_content.eval(fragCoord + dir * u_radiusIn * 0.5).a);`:""}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
float ring = clamp(dilated - eroded, 0.0, 1.0);
|
|
807
|
+
float bandAlpha = ring * u_color.a;
|
|
808
|
+
vec4 band = vec4(u_color.rgb * bandAlpha, bandAlpha); // premultiplied
|
|
809
|
+
|
|
810
|
+
// Source-over of whichever layer this position puts on top.
|
|
811
|
+
vec4 top = ${i?"band":"src"};
|
|
812
|
+
vec4 bottom = ${i?"src":"band"};
|
|
813
|
+
return top + bottom * (1.0 - top.a);
|
|
814
|
+
}
|
|
815
|
+
`}function Rw(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 Bw(r,e,t,n){let i=r.width*n,s=Ew(r.color);if(!(i>0)||s[3]<=0)return null;let a=Rw(r.position,i),o=Fw(r.position,Mw(Math.max(a.out,a.in))),c=ne(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 sf={type:"outline",sampling:{tileMode:"decal",filterMode:"linear"},handles:(r,e)=>e==="foreground",makeShader:(r,e,t,n)=>Bw(r,e,t,n.scale)};import{resolveEffectColor as Dw}from"@motionscript/core";var Ul=[2,3,4,6],zl=12,Ow=4;function Lw(r){let e=r/Ow;return Ul.find(t=>t>=e)??Ul[Ul.length-1]}function Uw(r,e){let t=(2*Math.PI/zl).toFixed(8),n=e?`
|
|
816
|
+
float silhouette(vec2 p) {
|
|
817
|
+
float a = u_content.eval(p).a;
|
|
818
|
+
for (int i = 0; i < ${zl}; i++) {
|
|
819
|
+
float t = float(i) * ${t};
|
|
820
|
+
a = max(a, u_content.eval(p + vec2(cos(t), sin(t)) * u_spread).a);
|
|
821
|
+
}
|
|
822
|
+
return a;
|
|
823
|
+
}`:`
|
|
824
|
+
float silhouette(vec2 p) {
|
|
825
|
+
return u_content.eval(p).a;
|
|
826
|
+
}`;return`
|
|
827
|
+
uniform shader u_content; // snapshot of the node's own content (premultiplied)
|
|
828
|
+
uniform vec2 u_offset; // shadow displacement, device px (y already flipped)
|
|
829
|
+
uniform float u_sigma; // blur sigma, device px
|
|
830
|
+
uniform vec4 u_color; // shadow colour, straight RGBA
|
|
831
|
+
${e?"uniform float u_spread; // dilate distance, device px":""}
|
|
832
|
+
${n}
|
|
833
|
+
|
|
834
|
+
vec4 main(vec2 fragCoord) {
|
|
835
|
+
vec4 src = u_content.eval(fragCoord);
|
|
836
|
+
|
|
837
|
+
// Where this pixel's shadow is cast *from*.
|
|
838
|
+
vec2 origin = fragCoord - u_offset;
|
|
839
|
+
|
|
840
|
+
float shadowAlpha;
|
|
841
|
+
if (u_sigma <= 0.0) {
|
|
842
|
+
shadowAlpha = silhouette(origin);
|
|
843
|
+
} else {
|
|
844
|
+
// Centre tap carries the peak of the kernel.
|
|
845
|
+
float sum = silhouette(origin);
|
|
846
|
+
float weight = 1.0;
|
|
847
|
+
for (int r = 1; r <= ${r}; r++) {
|
|
848
|
+
// Rings span out to 3\u03C3, where a gaussian has all but ~1% of its mass.
|
|
849
|
+
float radius = (3.0 * u_sigma * float(r)) / float(${r});
|
|
850
|
+
float w = exp(-(radius * radius) / (2.0 * u_sigma * u_sigma));
|
|
851
|
+
for (int i = 0; i < ${zl}; i++) {
|
|
852
|
+
float t = float(i) * ${t};
|
|
853
|
+
sum += silhouette(origin + vec2(cos(t), sin(t)) * radius) * w;
|
|
854
|
+
weight += w;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
shadowAlpha = sum / weight;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
float a = clamp(shadowAlpha, 0.0, 1.0) * u_color.a;
|
|
861
|
+
vec4 shadow = vec4(u_color.rgb * a, a); // premultiplied
|
|
862
|
+
|
|
863
|
+
// Source-over of the content on top of its own shadow.
|
|
864
|
+
return src + shadow * (1.0 - src.a);
|
|
865
|
+
}
|
|
866
|
+
`}function zw(r,e,t,n){let i=Dw(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=Uw(Lw(o),c>0),u=ne(l,e);if(!u)return null;let d=[s,a,o,...i];return c>0&&d.push(c),u.makeShaderWithChildren(d,[t])}var af={type:"dropShadow",sampling:{tileMode:"decal",filterMode:"linear"},handles:(r,e)=>e==="foreground",makeShader:(r,e,t,n)=>zw(r,e,t,n.scale)};import{resolveEffectColor as Nw}from"@motionscript/core";var Vw=`
|
|
867
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
868
|
+
uniform vec2 u_center; // box centre, device px
|
|
869
|
+
uniform vec2 u_half; // box half-extent, device px
|
|
870
|
+
uniform vec4 u_color; // tint colour, straight RGBA (alpha scales the tint)
|
|
871
|
+
uniform float u_amount; // tint strength at the outside
|
|
872
|
+
uniform float u_radius; // normalised radius where the ramp starts
|
|
873
|
+
uniform float u_softness; // normalised ramp width
|
|
874
|
+
|
|
875
|
+
vec4 main(vec2 fragCoord) {
|
|
876
|
+
vec4 c = u_content.eval(fragCoord);
|
|
877
|
+
if (c.a <= 0.0) return c;
|
|
878
|
+
|
|
879
|
+
vec2 p = (fragCoord - u_center) / max(u_half, vec2(1.0));
|
|
880
|
+
float r = length(p);
|
|
881
|
+
|
|
882
|
+
float inner = u_radius;
|
|
883
|
+
float outer = u_radius + max(u_softness, 0.001);
|
|
884
|
+
float falloff = smoothstep(inner, outer, r) * u_amount * u_color.a;
|
|
885
|
+
|
|
886
|
+
vec3 base = c.rgb / c.a; // un-premultiply
|
|
887
|
+
vec3 tinted = mix(base, u_color.rgb, clamp(falloff, 0.0, 1.0));
|
|
888
|
+
return vec4(tinted * c.a, c.a); // re-premultiply
|
|
889
|
+
}
|
|
890
|
+
`;function Hw(r,e,t,n){let i=Nw(r.color);if(r.amount<=0||i[3]<=0||n.width<=0||n.height<=0)return null;let s=ne(Vw,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 of={type:"vignette",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Hw(r,e,t,n)};var Ww=`
|
|
891
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
892
|
+
uniform vec2 u_origin; // node box top-left, device px (0,0 on a backdrop)
|
|
893
|
+
uniform float u_amount; // noise amplitude, 0\u20131
|
|
894
|
+
uniform float u_size; // grain cell size, device px
|
|
895
|
+
uniform float u_seed; // field offset
|
|
896
|
+
uniform float u_colored; // 1 = per-channel speckle, 0 = luminance noise
|
|
897
|
+
|
|
898
|
+
float hash(vec2 cell, float seed) {
|
|
899
|
+
return fract(sin(dot(cell, vec2(127.1, 311.7)) + seed * 13.7) * 43758.5453);
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
vec4 main(vec2 fragCoord) {
|
|
903
|
+
vec4 c = u_content.eval(fragCoord);
|
|
904
|
+
if (c.a <= 0.0) return c;
|
|
905
|
+
|
|
906
|
+
vec2 cell = floor((fragCoord - u_origin) / max(u_size, 1.0));
|
|
907
|
+
float n = hash(cell, u_seed) - 0.5;
|
|
908
|
+
vec3 noise = vec3(n);
|
|
909
|
+
if (u_colored > 0.5) {
|
|
910
|
+
noise = vec3(
|
|
911
|
+
n,
|
|
912
|
+
hash(cell + vec2(37.0, 17.0), u_seed) - 0.5,
|
|
913
|
+
hash(cell + vec2(11.0, 91.0), u_seed) - 0.5
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
vec3 base = c.rgb / c.a; // un-premultiply
|
|
918
|
+
vec3 grained = clamp(base + noise * u_amount, 0.0, 1.0);
|
|
919
|
+
return vec4(grained * c.a, c.a); // re-premultiply
|
|
920
|
+
}
|
|
921
|
+
`;function qw(r,e,t,n,i,s=[0,0]){if(!(r.amount>0))return null;let a=ne(Ww,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 cf={type:"grain",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>qw(r,e,t,n.scale,n.time,hi(r,n))};var jw=`
|
|
922
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
923
|
+
uniform float u_amount; // edge-contrast boost
|
|
924
|
+
uniform float u_radius; // tap spacing, device px
|
|
925
|
+
|
|
926
|
+
vec4 main(vec2 fragCoord) {
|
|
927
|
+
vec4 c = u_content.eval(fragCoord);
|
|
928
|
+
if (c.a <= 0.0) return c;
|
|
929
|
+
|
|
930
|
+
float r = max(u_radius, 0.5);
|
|
931
|
+
vec4 sum = c * 4.0;
|
|
932
|
+
sum += u_content.eval(fragCoord + vec2( r, 0.0)) * 2.0;
|
|
933
|
+
sum += u_content.eval(fragCoord + vec2(-r, 0.0)) * 2.0;
|
|
934
|
+
sum += u_content.eval(fragCoord + vec2(0.0, r)) * 2.0;
|
|
935
|
+
sum += u_content.eval(fragCoord + vec2(0.0, -r)) * 2.0;
|
|
936
|
+
sum += u_content.eval(fragCoord + vec2( r, r));
|
|
937
|
+
sum += u_content.eval(fragCoord + vec2( r, -r));
|
|
938
|
+
sum += u_content.eval(fragCoord + vec2(-r, r));
|
|
939
|
+
sum += u_content.eval(fragCoord + vec2(-r, -r));
|
|
940
|
+
vec4 blurred = sum / 16.0;
|
|
941
|
+
|
|
942
|
+
vec3 base = c.rgb / c.a;
|
|
943
|
+
vec3 reference = blurred.a > 0.0 ? blurred.rgb / blurred.a : base;
|
|
944
|
+
vec3 sharpened = clamp(base + (base - reference) * u_amount, 0.0, 1.0);
|
|
945
|
+
return vec4(sharpened * c.a, c.a);
|
|
946
|
+
}
|
|
947
|
+
`;function Gw(r,e,t,n){if(r.amount===0)return null;let i=ne(jw,e);return i?i.makeShaderWithChildren([r.amount,Math.max(r.radius,0)*n],[t]):null}var lf={type:"sharpen",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Gw(r,e,t,n.scale)};var Kw={sobel:0,prewitt:1,laplacian:2},$w=`
|
|
948
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
949
|
+
uniform float u_strength; // magnitude multiplier
|
|
950
|
+
uniform float u_kernel; // 0 = sobel, 1 = prewitt, 2 = laplacian
|
|
951
|
+
uniform float u_colored; // 1 = per-channel edges, 0 = luminance
|
|
952
|
+
uniform float u_step; // tap spacing, device px
|
|
953
|
+
|
|
954
|
+
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
955
|
+
|
|
956
|
+
vec4 main(vec2 fragCoord) {
|
|
957
|
+
float s = max(u_step, 1.0);
|
|
958
|
+
|
|
959
|
+
vec4 c11 = u_content.eval(fragCoord);
|
|
960
|
+
vec3 c00 = u_content.eval(fragCoord + vec2(-s, -s)).rgb;
|
|
961
|
+
vec3 c01 = u_content.eval(fragCoord + vec2(0.0, -s)).rgb;
|
|
962
|
+
vec3 c02 = u_content.eval(fragCoord + vec2( s, -s)).rgb;
|
|
963
|
+
vec3 c10 = u_content.eval(fragCoord + vec2(-s, 0.0)).rgb;
|
|
964
|
+
vec3 c12 = u_content.eval(fragCoord + vec2( s, 0.0)).rgb;
|
|
965
|
+
vec3 c20 = u_content.eval(fragCoord + vec2(-s, s)).rgb;
|
|
966
|
+
vec3 c21 = u_content.eval(fragCoord + vec2(0.0, s)).rgb;
|
|
967
|
+
vec3 c22 = u_content.eval(fragCoord + vec2( s, s)).rgb;
|
|
968
|
+
|
|
969
|
+
// Sobel weights its middle tap twice as heavily as Prewitt does.
|
|
970
|
+
float w = u_kernel < 0.5 ? 2.0 : 1.0;
|
|
971
|
+
vec3 gx = (c02 + c12 * w + c22) - (c00 + c10 * w + c20);
|
|
972
|
+
vec3 gy = (c20 + c21 * w + c22) - (c00 + c01 * w + c02);
|
|
973
|
+
vec3 gradient = sqrt(gx * gx + gy * gy);
|
|
974
|
+
vec3 laplacian = abs(c11.rgb * 4.0 - c01 - c10 - c12 - c21);
|
|
975
|
+
|
|
976
|
+
vec3 e = u_kernel < 1.5 ? gradient : laplacian;
|
|
977
|
+
vec3 edge = u_colored > 0.5 ? e : vec3(dot(e, LUMA));
|
|
978
|
+
edge = clamp(edge * u_strength, 0.0, 1.0);
|
|
979
|
+
|
|
980
|
+
float a = max(c11.a, max(edge.r, max(edge.g, edge.b)));
|
|
981
|
+
return vec4(edge * a, a);
|
|
982
|
+
}
|
|
983
|
+
`;function Xw(r,e,t,n){if(!(r.strength>0))return null;let i=ne($w,e);return i?i.makeShaderWithChildren([r.strength,Kw[r.kernel]??0,r.colored?1:0,n],[t]):null}var uf={type:"edges",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>Xw(r,e,t,n.scale)};var Qw=`
|
|
984
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
985
|
+
uniform float u_level; // 0\u20131 cut point
|
|
986
|
+
uniform float u_smoothness; // 0\u20131 ramp width
|
|
987
|
+
|
|
988
|
+
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
989
|
+
|
|
990
|
+
vec4 main(vec2 fragCoord) {
|
|
991
|
+
vec4 c = u_content.eval(fragCoord);
|
|
992
|
+
if (c.a <= 0.0) return c;
|
|
993
|
+
|
|
994
|
+
vec3 base = c.rgb / c.a; // un-premultiply
|
|
995
|
+
float l = dot(base, LUMA);
|
|
996
|
+
|
|
997
|
+
float halfWidth = max(u_smoothness, 0.0) * 0.5;
|
|
998
|
+
float v = halfWidth <= 0.0
|
|
999
|
+
? step(u_level, l)
|
|
1000
|
+
: smoothstep(u_level - halfWidth, u_level + halfWidth, l);
|
|
1001
|
+
|
|
1002
|
+
return vec4(vec3(v) * c.a, c.a); // re-premultiply
|
|
1003
|
+
}
|
|
1004
|
+
`;function Yw(r,e,t){let n=ne(Qw,e);return n?n.makeShaderWithChildren([r.level,r.smoothness],[t]):null}var df={type:"threshold",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>Yw(r,e,t)};var Zw=2,Jw=32;function eb(r){return`
|
|
1005
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1006
|
+
uniform vec2 u_center; // blur centre, device px
|
|
1007
|
+
uniform float u_amount; // smear length, 0\u20131
|
|
1008
|
+
uniform float u_spin; // 1 = rotate about the centre, 0 = scale away from it
|
|
1009
|
+
|
|
1010
|
+
vec4 main(vec2 fragCoord) {
|
|
1011
|
+
vec2 offset = fragCoord - u_center;
|
|
1012
|
+
vec4 acc = vec4(0.0);
|
|
1013
|
+
|
|
1014
|
+
for (int i = 0; i < ${r}; i++) {
|
|
1015
|
+
float t = float(i) / ${r-1}.0 - 0.5;
|
|
1016
|
+
vec2 samplePos;
|
|
1017
|
+
if (u_spin > 0.5) {
|
|
1018
|
+
float angle = t * u_amount * 1.5707963; // a quarter turn at amount = 1
|
|
1019
|
+
float ca = cos(angle);
|
|
1020
|
+
float sa = sin(angle);
|
|
1021
|
+
samplePos = u_center + vec2(offset.x * ca - offset.y * sa,
|
|
1022
|
+
offset.x * sa + offset.y * ca);
|
|
1023
|
+
} else {
|
|
1024
|
+
samplePos = u_center + offset * (1.0 + t * u_amount);
|
|
1025
|
+
}
|
|
1026
|
+
acc += u_content.eval(samplePos);
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
return acc / ${r}.0;
|
|
1030
|
+
}
|
|
1031
|
+
`}function tb(r,e,t,n){if(!(r.amount>0)||n.width<=0||n.height<=0)return null;let i=Math.round(Math.max(Zw,Math.min(Jw,r.samples))),s=ne(eb(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 hf={type:"radialBlur",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>tb(r,e,t,n)};var rb={dot:0,line:1,cross:2},nb={mono:0,rgb:1,cmyk:2},ib=`
|
|
1032
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1033
|
+
uniform vec2 u_center; // grid anchor, device px
|
|
1034
|
+
uniform float u_size; // cell pitch, device px
|
|
1035
|
+
uniform float u_angle; // screen rotation, radians
|
|
1036
|
+
uniform float u_shape; // 0 = dot, 1 = line, 2 = cross
|
|
1037
|
+
uniform float u_separation; // 0 = mono, 1 = rgb, 2 = cmyk
|
|
1038
|
+
|
|
1039
|
+
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
1040
|
+
|
|
1041
|
+
// Screen-plate angles, relative to u_angle. Shared by the RGB and CMYK paths.
|
|
1042
|
+
const float ANGLE_A = 0.2617994; // +15\xB0
|
|
1043
|
+
const float ANGLE_B = 1.3089969; // +75\xB0
|
|
1044
|
+
const float ANGLE_C = 0.0; // 0\xB0
|
|
1045
|
+
const float ANGLE_K = 0.7853982; // +45\xB0
|
|
1046
|
+
|
|
1047
|
+
/**
|
|
1048
|
+
* The screen cell 'fragCoord' falls in, on the plate turned by 'offset'.
|
|
1049
|
+
* xy = this pixel's offset from the cell centre, in screen space (where the mark
|
|
1050
|
+
* is drawn); zw = that same centre mapped back to content space (where the
|
|
1051
|
+
* cell's one tone is resolved).
|
|
1052
|
+
*/
|
|
1053
|
+
vec4 screenCell(vec2 fragCoord, float offset) {
|
|
1054
|
+
float a = u_angle + offset;
|
|
1055
|
+
float ca = cos(a);
|
|
1056
|
+
float sa = sin(a);
|
|
1057
|
+
vec2 d = fragCoord - u_center;
|
|
1058
|
+
vec2 q = vec2(d.x * ca - d.y * sa, d.x * sa + d.y * ca);
|
|
1059
|
+
|
|
1060
|
+
float pitch = max(u_size, 1.0);
|
|
1061
|
+
float h = pitch * 0.5;
|
|
1062
|
+
vec2 cell = mod(q + h, pitch) - h;
|
|
1063
|
+
|
|
1064
|
+
vec2 qc = q - cell; // centre, screen space
|
|
1065
|
+
vec2 dc = vec2(qc.x * ca + qc.y * sa, -qc.x * sa + qc.y * ca); // rotate back
|
|
1066
|
+
return vec4(cell, u_center + dc);
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
/**
|
|
1070
|
+
* The cell's tone: the mean of a 2x2 grid at its quartile points.
|
|
1071
|
+
*
|
|
1072
|
+
* Not a single tap at the centre. A cell covers pitch\xB2 pixels, and one tap can
|
|
1073
|
+
* only ever be one of them \u2014 everything else in the cell is dropped, so fine
|
|
1074
|
+
* detail flickers in and out depending on whether it happened to land under the
|
|
1075
|
+
* sample. Four taps at \xB1pitch/4 is the cheap standard box approximation (exact
|
|
1076
|
+
* for content that ramps linearly across the cell) and is what puts detail back
|
|
1077
|
+
* without giving up one-tone-per-cell.
|
|
1078
|
+
*
|
|
1079
|
+
* The offsets are rotated with the plate so the sample grid follows the screen
|
|
1080
|
+
* rather than the pixel axes. Taps landing outside the silhouette are skipped:
|
|
1081
|
+
* a cell straddling the edge would otherwise average toward transparent black,
|
|
1082
|
+
* read as full ink, and ring the artwork in a dark fringe. A cell with no valid
|
|
1083
|
+
* tap at all falls back to the pixel's own colour.
|
|
1084
|
+
*/
|
|
1085
|
+
vec3 cellTone(vec2 centre, float offset, vec3 fallback) {
|
|
1086
|
+
float a = u_angle + offset;
|
|
1087
|
+
float ca = cos(a);
|
|
1088
|
+
float sa = sin(a);
|
|
1089
|
+
float o = max(u_size, 1.0) * 0.25;
|
|
1090
|
+
|
|
1091
|
+
vec3 sum = vec3(0.0);
|
|
1092
|
+
float n = 0.0;
|
|
1093
|
+
for (int i = 0; i < 4; i++) {
|
|
1094
|
+
vec2 t = vec2((i == 1 || i == 3) ? o : -o, (i < 2) ? -o : o);
|
|
1095
|
+
vec2 d = vec2(t.x * ca + t.y * sa, -t.x * sa + t.y * ca);
|
|
1096
|
+
vec4 s = u_content.eval(centre + d);
|
|
1097
|
+
if (s.a <= 0.0) continue;
|
|
1098
|
+
sum += s.rgb / s.a;
|
|
1099
|
+
n += 1.0;
|
|
1100
|
+
}
|
|
1101
|
+
return n > 0.0 ? sum / n : fallback;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
/** Ink coverage (0-1) for 'tone', given this pixel's offset from its cell centre. */
|
|
1105
|
+
float coverage(vec2 cell, float tone) {
|
|
1106
|
+
float pitch = max(u_size, 1.0);
|
|
1107
|
+
float h = pitch * 0.5;
|
|
1108
|
+
|
|
1109
|
+
float ink = 1.0 - clamp(tone, 0.0, 1.0);
|
|
1110
|
+
// At least a full pixel of edge ramp. Below that a lattice of hard-edged
|
|
1111
|
+
// marks aliases against the pixel grid, which is exactly the shimmer a
|
|
1112
|
+
// small pitch used to show.
|
|
1113
|
+
float aa = max(pitch * 0.08, 1.25);
|
|
1114
|
+
|
|
1115
|
+
if (u_shape < 0.5) {
|
|
1116
|
+
// Area-linear dot: radius \u221D \u221A(ink), scaled so full ink covers the cell.
|
|
1117
|
+
float radius = sqrt(ink) * h * 1.35;
|
|
1118
|
+
return 1.0 - smoothstep(radius - aa, radius + aa, length(cell));
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
float bar = ink * h;
|
|
1122
|
+
float horizontal = 1.0 - smoothstep(bar - aa, bar + aa, abs(cell.y));
|
|
1123
|
+
if (u_shape < 1.5) return horizontal;
|
|
1124
|
+
|
|
1125
|
+
float vertical = 1.0 - smoothstep(bar - aa, bar + aa, abs(cell.x));
|
|
1126
|
+
return max(horizontal, vertical);
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
/**
|
|
1130
|
+
* Ink amounts for a colour: cyan, magenta, yellow in xyz, black in w.
|
|
1131
|
+
*
|
|
1132
|
+
* Pulling the common darkness out into a K plate is the whole point of the
|
|
1133
|
+
* four-plate path: without it a neutral tone prints three overlapping mid-dots
|
|
1134
|
+
* (which is what 'rgb' does, and why it reads as colour noise on anything grey).
|
|
1135
|
+
* With K carrying it, a neutral prints one black dot and almost no colour, and
|
|
1136
|
+
* paper stays paper.
|
|
1137
|
+
*/
|
|
1138
|
+
vec4 separate(vec3 base) {
|
|
1139
|
+
float k = 1.0 - max(base.r, max(base.g, base.b));
|
|
1140
|
+
float inv = max(1.0 - k, 0.0001); // guard pure black
|
|
1141
|
+
// C = (1 \u2212 R \u2212 K) / (1 \u2212 K), and likewise M, Y. The division rescales what's
|
|
1142
|
+
// left after K has taken the common darkness, so the channel that was
|
|
1143
|
+
// brightest ends up with no ink at all.
|
|
1144
|
+
vec3 cmy = clamp((vec3(1.0) - base - vec3(k)) / inv, 0.0, 1.0);
|
|
1145
|
+
return vec4(cmy, k);
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
vec4 main(vec2 fragCoord) {
|
|
1149
|
+
vec4 c = u_content.eval(fragCoord);
|
|
1150
|
+
if (c.a <= 0.0) return c;
|
|
1151
|
+
|
|
1152
|
+
vec3 here = c.rgb / c.a; // un-premultiply
|
|
1153
|
+
vec3 screened;
|
|
1154
|
+
|
|
1155
|
+
if (u_separation > 1.5) {
|
|
1156
|
+
vec4 cellC = screenCell(fragCoord, ANGLE_A);
|
|
1157
|
+
vec4 cellM = screenCell(fragCoord, ANGLE_B);
|
|
1158
|
+
vec4 cellY = screenCell(fragCoord, ANGLE_C);
|
|
1159
|
+
vec4 cellK = screenCell(fragCoord, ANGLE_K);
|
|
1160
|
+
|
|
1161
|
+
// 'separate' gives ink amounts; 'coverage' takes tone, so pass 1 - ink.
|
|
1162
|
+
float dotC = coverage(cellC.xy, 1.0 - separate(cellTone(cellC.zw, ANGLE_A, here)).x);
|
|
1163
|
+
float dotM = coverage(cellM.xy, 1.0 - separate(cellTone(cellM.zw, ANGLE_B, here)).y);
|
|
1164
|
+
float dotY = coverage(cellY.xy, 1.0 - separate(cellTone(cellY.zw, ANGLE_C, here)).z);
|
|
1165
|
+
float dotK = coverage(cellK.xy, 1.0 - separate(cellTone(cellK.zw, ANGLE_K, here)).w);
|
|
1166
|
+
|
|
1167
|
+
// Subtractive: each ink absorbs its complementary channel \u2014 cyan takes
|
|
1168
|
+
// red, magenta green, yellow blue \u2014 and black takes all three.
|
|
1169
|
+
screened = vec3(1.0 - dotC, 1.0 - dotM, 1.0 - dotY) * (1.0 - dotK);
|
|
1170
|
+
} else if (u_separation > 0.5) {
|
|
1171
|
+
vec4 cellR = screenCell(fragCoord, ANGLE_A);
|
|
1172
|
+
vec4 cellG = screenCell(fragCoord, ANGLE_B);
|
|
1173
|
+
vec4 cellB = screenCell(fragCoord, ANGLE_C);
|
|
1174
|
+
|
|
1175
|
+
screened = vec3(
|
|
1176
|
+
1.0 - coverage(cellR.xy, cellTone(cellR.zw, ANGLE_A, here).r),
|
|
1177
|
+
1.0 - coverage(cellG.xy, cellTone(cellG.zw, ANGLE_B, here).g),
|
|
1178
|
+
1.0 - coverage(cellB.xy, cellTone(cellB.zw, ANGLE_C, here).b)
|
|
1179
|
+
);
|
|
1180
|
+
} else {
|
|
1181
|
+
vec4 cell = screenCell(fragCoord, ANGLE_C);
|
|
1182
|
+
screened = vec3(1.0 - coverage(cell.xy, dot(cellTone(cell.zw, ANGLE_C, here), LUMA)));
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
return vec4(clamp(screened, 0.0, 1.0) * c.a, c.a); // re-premultiply
|
|
1186
|
+
}
|
|
1187
|
+
`;function sb(r,e,t,n){let i=r.size*n.scale;if(!(i>=1))return null;let s=ne(ib,e);return s?s.makeShaderWithChildren([n.centerX,n.centerY,i,r.angle*Math.PI/180,rb[r.shape]??0,nb[r.separation]??0],[t]):null}var ff={type:"halftone",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>sb(r,e,t,n)};var ab="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 ob="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ka=null;function mf(){if(Ka)return Ka;let r=ab.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|ob.indexOf(r[s]),n+=6,n>=8&&(n-=8,e[i++]=t>>n&255);return Ka=e.subarray(0,i),Ka}function cb(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
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1189
|
+
${t?`uniform shader u_noise; // 64x64 blue-noise thresholds, tiled
|
|
1190
|
+
`:""}uniform vec2 u_origin; // node box top-left, device px (0,0 on a backdrop)
|
|
1191
|
+
uniform float u_levels; // output tones per channel (>= 2)
|
|
1192
|
+
uniform float u_scale; // pattern cell size, device px
|
|
1193
|
+
uniform float u_monochrome; // 1 = dither luminance, 0 = per channel
|
|
1194
|
+
|
|
1195
|
+
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
1196
|
+
${t?"":`
|
|
1197
|
+
/** Bayer 2\xD72 threshold in [0,1) for an integer cell coordinate. */
|
|
1198
|
+
float bayer2(vec2 c) {
|
|
1199
|
+
vec2 a = floor(c);
|
|
1200
|
+
return fract(a.x * 0.5 + a.y * a.y * 0.75);
|
|
1201
|
+
}
|
|
1202
|
+
`}
|
|
1203
|
+
vec4 main(vec2 fragCoord) {
|
|
1204
|
+
vec4 c = u_content.eval(fragCoord);
|
|
1205
|
+
if (c.a <= 0.0) return c;
|
|
1206
|
+
|
|
1207
|
+
vec2 cell = floor((fragCoord - u_origin) / max(u_scale, 1.0));
|
|
1208
|
+
float threshold = ${n};
|
|
1209
|
+
|
|
1210
|
+
vec3 base = c.rgb / c.a; // un-premultiply
|
|
1211
|
+
if (u_monochrome > 0.5) base = vec3(dot(base, LUMA));
|
|
1212
|
+
|
|
1213
|
+
float steps = max(u_levels, 2.0) - 1.0;
|
|
1214
|
+
vec3 dithered = clamp(floor(base * steps + threshold) / steps, 0.0, 1.0);
|
|
1215
|
+
return vec4(dithered * c.a, c.a); // re-premultiply
|
|
1216
|
+
}
|
|
1217
|
+
`}var Xa=new WeakMap,Nl=new Set;function lb(r){let e=Xa.get(r);if(e!==void 0)return e?.shader??null;let t=mf(),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 Xa.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 Xa.set(r,a),Nl.add(a),s}function ub(r,e,t,n,i=[0,0]){if(r.levels>=256)return null;let s=r.noise==="blue"?lb(e):null,a=r.noise==="blue"&&s?"blue":"bayer",o=ne(cb(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 pf={type:"dither",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>ub(r,e,t,n.scale,hi(r,n)),dispose(){for(let{image:r,shader:e}of Nl)e.delete(),r.delete();Nl.clear(),Xa=new WeakMap}};import{resolveEffectColor as gf}from"@motionscript/core";var db=.2126,hb=.7152,fb=.0722;function mb(r,e,t){let n=Math.max(0,Math.min(1,r)),i=c=>{let l=(t[c]-e[c])*n;return[l*db,l*hb,l*fb,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 yf={type:"duotone",makeImageFilter(r,e){if(r.amount<=0)return null;let t=mb(r.amount,gf(r.shadows),gf(r.highlights)),n=e.ColorFilter.MakeMatrix(t),i=e.ImageFilter.MakeColorFilter(n,null);return n.delete(),i}};var pb=`
|
|
1218
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1219
|
+
uniform vec2 u_red; // red plane offset, device px
|
|
1220
|
+
uniform vec2 u_green; // green plane offset, device px
|
|
1221
|
+
uniform vec2 u_blue; // blue plane offset, device px
|
|
1222
|
+
|
|
1223
|
+
// Straight (un-premultiplied) colour of one tap, plus its alpha.
|
|
1224
|
+
vec4 tap(vec2 p) {
|
|
1225
|
+
vec4 c = u_content.eval(p);
|
|
1226
|
+
return c.a > 0.0 ? vec4(c.rgb / c.a, c.a) : vec4(0.0);
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
vec4 main(vec2 fragCoord) {
|
|
1230
|
+
vec4 r = tap(fragCoord - u_red);
|
|
1231
|
+
vec4 g = tap(fragCoord - u_green);
|
|
1232
|
+
vec4 b = tap(fragCoord - u_blue);
|
|
1233
|
+
|
|
1234
|
+
float a = max(r.a, max(g.a, b.a));
|
|
1235
|
+
if (a <= 0.0) return vec4(0.0);
|
|
1236
|
+
|
|
1237
|
+
vec3 straight = vec3(r.r, g.g, b.b);
|
|
1238
|
+
return vec4(straight * a, a); // re-premultiply
|
|
1239
|
+
}
|
|
1240
|
+
`;function gb(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=ne(pb,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 wf={type:"rgbShift",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>gb(r,e,t,n.scale)};var yb=`
|
|
1241
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1242
|
+
uniform vec2 u_center; // band origin, device px
|
|
1243
|
+
uniform float u_spacing; // period, device px
|
|
1244
|
+
uniform float u_thickness; // 0\u20131 share of the period the band covers
|
|
1245
|
+
uniform float u_darkness; // 0\u20131 how far the band darkens
|
|
1246
|
+
uniform float u_offset; // band phase, device px
|
|
1247
|
+
uniform float u_cos; // band axis, precomputed
|
|
1248
|
+
uniform float u_sin;
|
|
1249
|
+
|
|
1250
|
+
vec4 main(vec2 fragCoord) {
|
|
1251
|
+
vec4 c = u_content.eval(fragCoord);
|
|
1252
|
+
if (c.a <= 0.0) return c;
|
|
1253
|
+
|
|
1254
|
+
vec2 d = fragCoord - u_center;
|
|
1255
|
+
float across = -d.x * u_sin + d.y * u_cos; // distance along the band normal
|
|
1256
|
+
|
|
1257
|
+
float period = max(u_spacing, 1.0);
|
|
1258
|
+
float phase = mod(across + u_offset, period) / period; // 0\u20131 within the period
|
|
1259
|
+
|
|
1260
|
+
// Dark band centred on phase 0.5, 'thickness' wide, with a half-pixel ramp.
|
|
1261
|
+
// ('half' is an SkSL type, so the local can't be called that.)
|
|
1262
|
+
float reach = clamp(u_thickness, 0.0, 1.0) * 0.5;
|
|
1263
|
+
float aa = 0.5 / period;
|
|
1264
|
+
float band = smoothstep(0.5 - reach - aa, 0.5 - reach + aa, phase)
|
|
1265
|
+
- smoothstep(0.5 + reach - aa, 0.5 + reach + aa, phase);
|
|
1266
|
+
|
|
1267
|
+
float lit = 1.0 - band * clamp(u_darkness, 0.0, 1.0);
|
|
1268
|
+
return vec4(c.rgb * lit, c.a); // premultiplied: scaling rgb dims, keeps alpha
|
|
1269
|
+
}
|
|
1270
|
+
`;function wb(r,e,t,n){let i=r.spacing*n.scale;if(!(r.darkness>0)||!(i>=1))return null;let s=ne(yb,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 bf={type:"scanlines",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>wb(r,e,t,n)};import{resolveEffectAxis as bb}from"@motionscript/core";var kb=`
|
|
1271
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1272
|
+
uniform vec2 u_center; // band origin, device px
|
|
1273
|
+
uniform float u_amount; // max displacement, device px
|
|
1274
|
+
uniform float u_size; // band thickness, device px
|
|
1275
|
+
uniform float u_density; // 0\u20131 share of bands that move
|
|
1276
|
+
uniform float u_seed; // field offset
|
|
1277
|
+
uniform vec2 u_axis; // per-axis slide weight
|
|
1278
|
+
|
|
1279
|
+
float hash(float band, float salt) {
|
|
1280
|
+
return fract(sin(band * 78.233 + salt + u_seed * 13.7) * 43758.5453);
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
vec4 main(vec2 fragCoord) {
|
|
1284
|
+
vec2 d = fragCoord - u_center;
|
|
1285
|
+
|
|
1286
|
+
// Bands are cut across the slide direction: an x-slide tears horizontal rows.
|
|
1287
|
+
float across = u_axis.x >= u_axis.y ? d.y : d.x;
|
|
1288
|
+
float band = floor(across / max(u_size, 1.0));
|
|
1289
|
+
|
|
1290
|
+
float moves = step(1.0 - clamp(u_density, 0.0, 1.0), hash(band, 0.0));
|
|
1291
|
+
float shift = (hash(band, 37.0) * 2.0 - 1.0) * u_amount * moves;
|
|
1292
|
+
|
|
1293
|
+
return u_content.eval(fragCoord - u_axis * shift);
|
|
1294
|
+
}
|
|
1295
|
+
`;function xb(r,e,t,n){if(!(r.amount>0)||!(r.density>0))return null;let i=ne(kb,e);if(!i)return null;let s=bb(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 kf={type:"blockDisplace",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>xb(r,e,t,n)};var xf={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 Sf(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 Sb(r){return`
|
|
1296
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1297
|
+
uniform float u_bits; // bits per channel (palette 'none' only)
|
|
1298
|
+
uniform float u_amount; // 0\u20131 blend toward the crushed colour
|
|
1299
|
+
|
|
1300
|
+
vec4 main(vec2 fragCoord) {
|
|
1301
|
+
vec4 c = u_content.eval(fragCoord);
|
|
1302
|
+
if (c.a <= 0.0) return c;
|
|
1303
|
+
|
|
1304
|
+
vec3 base = clamp(c.rgb / c.a, 0.0, 1.0); // un-premultiply
|
|
1305
|
+
${r==="none"?`
|
|
1306
|
+
// Even quantization to 2^bits steps per channel.
|
|
1307
|
+
float steps = max(exp2(clamp(u_bits, 1.0, 8.0)) - 1.0, 1.0);
|
|
1308
|
+
vec3 crushed = floor(base * steps + 0.5) / steps;`:`
|
|
1309
|
+
// Nearest entry of the ${r} palette, by squared distance.
|
|
1310
|
+
vec3 crushed = ${Sf(xf[r][0])};
|
|
1311
|
+
float bestDist = dot(base - crushed, base - crushed);
|
|
1312
|
+
${xf[r].slice(1).map(t=>` { vec3 p = ${Sf(t)}; float d = dot(base - p, base - p);
|
|
1313
|
+
if (d < bestDist) { bestDist = d; crushed = p; } }`).join(`
|
|
1314
|
+
`)}`}
|
|
1315
|
+
|
|
1316
|
+
vec3 out_ = mix(base, crushed, clamp(u_amount, 0.0, 1.0));
|
|
1317
|
+
return vec4(out_ * c.a, c.a); // re-premultiply
|
|
1318
|
+
}
|
|
1319
|
+
`}function Tb(r,e,t){if(!(r.amount>0)||r.palette==="none"&&r.bits>=8)return null;let n=ne(Sb(r.palette),e);return n?n.makeShaderWithChildren([r.bits,r.amount],[t]):null}var Tf={type:"bitCrush",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>Tb(r,e,t)};import{resolveAsciiCharset as _f,resolveEffectColor as Cf}from"@motionscript/core";function vb(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 Vl(r,e,t,n,i=!1){return e.matchFamilyStyle(t,vb(r,n,i))}function fi(r,e,t){let n=new r.Font(e,t);return n.setSubpixel(!0),n.setHinting(r.FontHinting.None),n.setLinearMetrics(!0),n}var Ab=64,vf=256,Hl=r=>Math.max(4,Math.min(Ab,Math.round(r))),Af=r=>Math.min([...r].length,vf),_b=(r,e)=>`${e}|${r.cell}|${r.fontFamily}|${r.fontWeight}|${r.charset}`,Qa=class{entries=new Map;get(e,t,n){let i=_b(e,n.fontEpoch),s=this.entries.get(i);if(s!==void 0)return s;let a=Pb(e,t,n);return this.entries.set(i,a),a}dispose(){for(let e of this.entries.values())e?.dispose();this.entries.clear()}};function Cb(r,e,t){let n=Vl(e,t.fontMgr,r.fontFamily,r.fontWeight);if(n)return n;if(t.fontMgr.countFamilies()>0){let i=t.fontMgr.getFamilyName(0),s=Vl(e,t.fontMgr,i,r.fontWeight);if(s)return s}return null}function Pb(r,e,t){let n=[...r.charset].slice(0,vf);if(n.length===0)return null;let i=Hl(r.cell),s=t.makeSurface(i*n.length,i);if(!s)return null;let a=fi(e,Cb(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(`[motion-script] 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 Eb=2,Pf=r=>Hl(Math.max(8,r*Eb)),Ib=`
|
|
1320
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1321
|
+
uniform shader u_atlas; // charset baked darkest-first, one row of cells
|
|
1322
|
+
uniform vec2 u_center; // cell grid anchor, device px
|
|
1323
|
+
uniform float u_cell; // cell size, device px
|
|
1324
|
+
uniform float u_count; // glyphs in the atlas
|
|
1325
|
+
uniform float u_atlasCell; // atlas cell edge, texture px
|
|
1326
|
+
uniform vec4 u_ink; // glyph colour, straight RGBA
|
|
1327
|
+
uniform vec4 u_background; // colour behind the glyphs, straight RGBA
|
|
1328
|
+
uniform float u_colored; // 1 = tint each glyph with its own cell's colour
|
|
1329
|
+
|
|
1330
|
+
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
1331
|
+
|
|
1332
|
+
vec4 main(vec2 fragCoord) {
|
|
1333
|
+
float cell = max(u_cell, 2.0);
|
|
1334
|
+
|
|
1335
|
+
// Locate this pixel's cell, and where inside it the pixel sits (0\u20131).
|
|
1336
|
+
vec2 fromOrigin = fragCoord - u_center;
|
|
1337
|
+
vec2 index = floor(fromOrigin / cell);
|
|
1338
|
+
vec2 cellOrigin = u_center + index * cell;
|
|
1339
|
+
vec2 within = clamp((fragCoord - cellOrigin) / cell, 0.0, 1.0);
|
|
1340
|
+
|
|
1341
|
+
vec4 src = u_content.eval(cellOrigin + cell * 0.5);
|
|
1342
|
+
if (src.a <= 0.0) return vec4(0.0);
|
|
1343
|
+
|
|
1344
|
+
vec3 base = src.rgb / src.a; // un-premultiply
|
|
1345
|
+
float tone = clamp(dot(base, LUMA), 0.0, 1.0);
|
|
1346
|
+
|
|
1347
|
+
// The ramp runs least-ink to most-ink, which is dark-to-light only while the
|
|
1348
|
+
// ink is brighter than what's behind it. Flip for a dark-on-light (paper)
|
|
1349
|
+
// scheme so a dark cell stays dark either way, and a custom ramp never has
|
|
1350
|
+
// to be written twice.
|
|
1351
|
+
float inkLum = dot(u_ink.rgb, LUMA);
|
|
1352
|
+
float bgLum = dot(u_background.rgb, LUMA);
|
|
1353
|
+
float ramp = inkLum >= bgLum ? tone : 1.0 - tone;
|
|
1354
|
+
|
|
1355
|
+
float glyph = clamp(floor(ramp * u_count), 0.0, u_count - 1.0);
|
|
1356
|
+
vec2 atlasPos = vec2((glyph + within.x) * u_atlasCell, within.y * u_atlasCell);
|
|
1357
|
+
float coverage = clamp(u_atlas.eval(atlasPos).r, 0.0, 1.0);
|
|
1358
|
+
|
|
1359
|
+
vec3 ink = u_colored > 0.5 ? base : u_ink.rgb;
|
|
1360
|
+
vec3 straight = mix(u_background.rgb, ink, coverage);
|
|
1361
|
+
float alpha = mix(u_background.a, u_ink.a, coverage) * src.a;
|
|
1362
|
+
|
|
1363
|
+
return vec4(straight * alpha, alpha); // re-premultiply
|
|
1364
|
+
}
|
|
1365
|
+
`,If={type:"ascii",sampling:{tileMode:"decal",filterMode:"nearest"},resources(r,e,t){let n=_f(r.charset);if(n.length===0)return null;let i=Ef.get({charset:n,fontFamily:r.fontFamily,fontWeight:400,cell:Pf(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=ne(Ib,e);if(!o)return null;let c=Cf(r.ink),l=Cf(r.background);return o.makeShaderWithChildren([n.centerX,n.centerY,a,Af(_f(r.charset)),Pf(r.size),...c,...l,r.colored?1:0],[t,s])},dispose(){Ef.dispose()}},Ef=new Qa;var Mf={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 Mb,resolveEffectColor as Ff}from"@motionscript/core";var Fb="vec3(0.2126, 0.7152, 0.0722)";function Rb(r,e,t){let n=r==="ramp",i=n?`uniform vec4 u_colors[${t}]; // ramp colours, straight RGBA
|
|
1366
|
+
uniform float u_stops[${t}]; // their positions, 0-1 ascending
|
|
1367
|
+
uniform float u_cycles; // ramp traversals across the strength range
|
|
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); }"}
|
|
1369
|
+
|
|
1370
|
+
/** The ramp colour at strength \`e\`, straight RGB. */
|
|
1371
|
+
vec3 rampColor(float e) {
|
|
1372
|
+
float u = wrap(e * u_cycles + u_phase);
|
|
1373
|
+
vec3 c = u_colors[0].rgb;
|
|
1374
|
+
for (int i = 1; i < ${t}; i++) {
|
|
1375
|
+
float span = max(u_stops[i] - u_stops[i - 1], 1e-5);
|
|
1376
|
+
float t = clamp((u - u_stops[i - 1]) / span, 0.0, 1.0);
|
|
1377
|
+
c = mix(c, u_colors[i].rgb, t);
|
|
1378
|
+
}
|
|
1379
|
+
return c;
|
|
1380
|
+
}`:"",c=r==="none"?` // Already premultiplied, and already thresholded by the prefilter.
|
|
1381
|
+
return pass * u_intensity;`:` float e = clamp(dot(pass.rgb, ${Fb}) * u_intensity, 0.0, 1.0);
|
|
1382
|
+
vec3 rgb = ${n?"rampColor(e)":"u_color.rgb"};
|
|
1383
|
+
return vec4(rgb * e, e);`;return`
|
|
1384
|
+
uniform shader u_glow; // thresholded, spread and blurred copy of the source
|
|
1385
|
+
uniform float u_intensity; // brightness of the glow
|
|
1386
|
+
${s}
|
|
1387
|
+
${i}
|
|
1388
|
+
${o}
|
|
1389
|
+
|
|
1390
|
+
vec4 main(vec2 fragCoord) {
|
|
1391
|
+
vec4 pass = u_glow.eval(fragCoord);
|
|
1392
|
+
${c}
|
|
1393
|
+
}
|
|
1394
|
+
`}function Bb(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 Rf={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=Mb(r.axis);return{blurredSource:{sigmaX:n*i.x,sigmaY:n*i.y,prefilter:Bb(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=Rb(r.tint,r.loopStyle==="mirror",o),l=ne(c,e);if(!l)return null;let u=[r.intensity];if(r.tint==="solid"&&u.push(...Ff(r.color)),r.tint==="ramp"){for(let g of r.colors)u.push(...Ff(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=Gt(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 Db=4,Ob=48;function Lb(r){return`
|
|
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 Ub(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(Db,Math.min(Ob,r.samples))),s=ne(Lb(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 Bf={type:"godRays",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Ub(r,e,t,n)};var zb=6;function Nb(r){return`
|
|
1451
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1452
|
+
|
|
1453
|
+
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
1454
|
+
|
|
1455
|
+
vec4 main(vec2 fragCoord) {
|
|
1456
|
+
vec4 centre = u_content.eval(fragCoord);
|
|
1457
|
+
if (centre.a <= 0.0) return centre;
|
|
1458
|
+
|
|
1459
|
+
vec3 bestMean = centre.rgb / centre.a;
|
|
1460
|
+
float bestVar = 1e9;
|
|
1461
|
+
|
|
1462
|
+
// Four quadrants: (-r..0,-r..0), (0..r,-r..0), (-r..0,0..r), (0..r,0..r).
|
|
1463
|
+
for (int q = 0; q < 4; q++) {
|
|
1464
|
+
float sx = (q == 1 || q == 3) ? 1.0 : -1.0;
|
|
1465
|
+
float sy = (q == 2 || q == 3) ? 1.0 : -1.0;
|
|
1466
|
+
|
|
1467
|
+
vec3 sum = vec3(0.0);
|
|
1468
|
+
float sumL = 0.0;
|
|
1469
|
+
float sumL2 = 0.0;
|
|
1470
|
+
float n = 0.0;
|
|
1471
|
+
|
|
1472
|
+
for (int y = 0; y <= ${r}; y++) {
|
|
1473
|
+
for (int x = 0; x <= ${r}; x++) {
|
|
1474
|
+
vec4 s = u_content.eval(fragCoord + vec2(float(x) * sx, float(y) * sy));
|
|
1475
|
+
// Skip anything outside the silhouette, or the window would be
|
|
1476
|
+
// pulled toward transparent black and the edge would darken.
|
|
1477
|
+
if (s.a <= 0.0) continue;
|
|
1478
|
+
vec3 c = s.rgb / s.a;
|
|
1479
|
+
float l = dot(c, LUMA);
|
|
1480
|
+
sum += c;
|
|
1481
|
+
sumL += l;
|
|
1482
|
+
sumL2 += l * l;
|
|
1483
|
+
n += 1.0;
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
if (n <= 0.0) continue;
|
|
1488
|
+
float mean = sumL / n;
|
|
1489
|
+
float variance = sumL2 / n - mean * mean;
|
|
1490
|
+
if (variance < bestVar) {
|
|
1491
|
+
bestVar = variance;
|
|
1492
|
+
bestMean = sum / n;
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
return vec4(bestMean * centre.a, centre.a);
|
|
1497
|
+
}
|
|
1498
|
+
`}function Vb(r,e,t,n){let i=Math.round(Math.min(zb,r.radius*n));if(i<1)return null;let s=ne(Nb(i),e);return s?s.makeShaderWithChildren([],[t]):null}var Df={type:"oilPaint",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>Vb(r,e,t,n.scale)};function Of(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=Hb(r,m[g],m[g+1]);y&&(p=Math.max(p,Ya(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=Ya((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 Hb(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 Ya(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 mi(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 Lf(r,e){return e!==void 0&&e>0&&r/e>Math.SQRT2}var Wb=4,Za=new Map,Uf=new WeakMap;function Ja(r,e,t,n,i){let s=n.getImageSize(r),a=n.getImage(r,s&&i?qb(s,e,i):void 0);if(!a)return null;let o=Za.get(r),c=o?.find(h=>h.image===a);if(c)return c.shader;let l=s??{width:a.width(),height:a.height()},u=mi([1,0,0,0,1,0,0,0,1],l.width,l.height,a.width(),a.height()),d=a.makeShaderOptions(t.TileMode.Repeat,t.TileMode.Repeat,t.FilterMode.Linear,t.MipmapMode.None,u);return Uf.set(d,l),o||Za.set(r,o=[]),o.push({image:a,shader:d}),o.length>Wb&&o.shift().shader.delete(),d}function eo(r){return Uf.get(r)}function to(){for(let r of Za.values())for(let{shader:e}of r)e.delete();Za.clear()}function qb(r,e,t){let n=Math.max(e,.01);return Math.max(t.width/(n*r.width),t.height/(n*r.height))*Math.max(r.width,r.height)}var jb=`
|
|
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
|
+
`,Gb={multiply:0,overlay:1,screen:2,"soft-light":3,softLight:3},zf={type:"texture",sampling:{tileMode:"decal",filterMode:"linear"},resources(r,e,t,n){if(!(r.amount>0)||!r.src)return null;let i=Ja(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(jb,e);if(!a)return null;let o=r.angle*Math.PI/180,c=eo(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,Gb[r.blend]??0],[t,s]):null},dispose(){to()}};var Kb=`
|
|
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
|
+
`,$b={rg:0,luminance:1,alpha:2},Nf={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=Ja(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(Kb,e);if(!a)return null;let o=r.angle*Math.PI/180,c=eo(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,$b[r.channel]??0,c.width/2,c.height/2],[t,s]):null},dispose(){to()}};var Xb=`
|
|
1586
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1587
|
+
uniform vec2 u_center; // ripple origin, device px
|
|
1588
|
+
uniform vec2 u_amplitude; // peak displacement per axis, device px
|
|
1589
|
+
uniform float u_wavelength; // distance between crests, device px
|
|
1590
|
+
uniform float u_phase; // radians, pre-wrapped
|
|
1591
|
+
uniform float u_cos; // travel direction, precomputed
|
|
1592
|
+
uniform float u_sin;
|
|
1593
|
+
uniform float u_radial; // 1 = concentric rings, 0 = parallel bands
|
|
1594
|
+
|
|
1595
|
+
vec4 main(vec2 fragCoord) {
|
|
1596
|
+
vec2 d = fragCoord - u_center;
|
|
1597
|
+
// Distance along the travel axis, or from the origin \u2014 the one scalar the
|
|
1598
|
+
// sine is taken of.
|
|
1599
|
+
float t = u_radial > 0.5 ? length(d) : dot(d, vec2(u_cos, u_sin));
|
|
1600
|
+
|
|
1601
|
+
float k = 6.28318530718 / max(u_wavelength, 1.0);
|
|
1602
|
+
float wave = sin(t * k + u_phase);
|
|
1603
|
+
|
|
1604
|
+
return u_content.eval(fragCoord + u_amplitude * wave);
|
|
1605
|
+
}
|
|
1606
|
+
`,Vf={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=ne(Xb,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 Qb=`
|
|
1607
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1608
|
+
uniform vec2 u_center; // vortex centre, device px
|
|
1609
|
+
uniform vec2 u_half; // node half-extent, device px
|
|
1610
|
+
uniform float u_angle; // rotation at the centre, radians
|
|
1611
|
+
uniform float u_radius; // 0\u20131 radius of influence, in normalised units
|
|
1612
|
+
|
|
1613
|
+
vec4 main(vec2 fragCoord) {
|
|
1614
|
+
vec2 half_ = max(u_half, vec2(1.0));
|
|
1615
|
+
vec2 p = (fragCoord - u_center) / half_; // aspect-normalised
|
|
1616
|
+
float r = length(p);
|
|
1617
|
+
if (r >= u_radius) return u_content.eval(fragCoord);
|
|
1618
|
+
|
|
1619
|
+
float falloff = 1.0 - r / max(u_radius, 0.0001);
|
|
1620
|
+
float a = u_angle * falloff * falloff;
|
|
1621
|
+
|
|
1622
|
+
float c = cos(a);
|
|
1623
|
+
float s = sin(a);
|
|
1624
|
+
vec2 rotated = vec2(p.x * c - p.y * s, p.x * s + p.y * c);
|
|
1625
|
+
|
|
1626
|
+
return u_content.eval(u_center + rotated * half_);
|
|
1627
|
+
}
|
|
1628
|
+
`,Hf={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=ne(Qb,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 Yb=32,Zb=2;function Jb(r){return`
|
|
1629
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1630
|
+
uniform vec2 u_center; // ramp origin, device px
|
|
1631
|
+
uniform vec2 u_half; // node half-extent, device px
|
|
1632
|
+
uniform vec2 u_dir; // ramp direction (linear)
|
|
1633
|
+
uniform float u_radius; // blur spread at the far end, device px
|
|
1634
|
+
uniform float u_radius0; // blur spread at the near end, device px
|
|
1635
|
+
uniform float u_start; // 0\u20131 where the blur starts building
|
|
1636
|
+
uniform float u_end; // 0\u20131 where it reaches u_radius
|
|
1637
|
+
uniform float u_radial; // 1 = radial ramp, 0 = linear
|
|
1638
|
+
|
|
1639
|
+
float hash(vec2 p) {
|
|
1640
|
+
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
vec4 main(vec2 fragCoord) {
|
|
1644
|
+
vec2 half_ = max(u_half, vec2(1.0));
|
|
1645
|
+
vec2 p = (fragCoord - u_center) / half_;
|
|
1646
|
+
|
|
1647
|
+
// One scalar drives the ramp, whichever shape it is: distance from the
|
|
1648
|
+
// origin, or distance along the ramp direction remapped to 0\u20131 across the box.
|
|
1649
|
+
float t = u_radial > 0.5 ? length(p) : dot(p, u_dir) * 0.5 + 0.5;
|
|
1650
|
+
|
|
1651
|
+
// Smoothstep rather than a linear remap: a linear ramp leaves a visible line
|
|
1652
|
+
// at u_start where the blur switches on, because the radius' derivative
|
|
1653
|
+
// jumps there. Smoothstep lands both at zero.
|
|
1654
|
+
float ramp = smoothstep(u_start, max(u_end, u_start + 0.0001), clamp(t, 0.0, 1.0));
|
|
1655
|
+
// Between the two ends, not out of sharp: a ramp that starts blurred is a
|
|
1656
|
+
// depth-of-field falloff rather than a fade-to-blur.
|
|
1657
|
+
float radius = mix(u_radius0, u_radius, ramp);
|
|
1658
|
+
|
|
1659
|
+
vec4 sum = u_content.eval(fragCoord);
|
|
1660
|
+
if (radius < 0.5) return sum; // sub-pixel \u2014 nothing to average
|
|
1661
|
+
|
|
1662
|
+
const int N = ${r};
|
|
1663
|
+
float jitter = hash(fragCoord) * 6.28318530718;
|
|
1664
|
+
for (int i = 1; i <= N; i++) {
|
|
1665
|
+
float fi = float(i);
|
|
1666
|
+
float ang = fi * 2.39996323 + jitter; // golden angle, per-pixel rotated
|
|
1667
|
+
float rad = radius * sqrt(fi / float(N));
|
|
1668
|
+
sum += u_content.eval(fragCoord + vec2(cos(ang), sin(ang)) * rad);
|
|
1669
|
+
}
|
|
1670
|
+
return sum / float(N + 1);
|
|
1671
|
+
}
|
|
1672
|
+
`}var Wf={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(Zb,Math.min(Yb,Math.round(r.samples))),a=ne(Jb(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 ek=`
|
|
1673
|
+
uniform shader u_content; // snapshot of the source (premultiplied)
|
|
1674
|
+
uniform vec2 u_center; // fold origin, device px
|
|
1675
|
+
uniform vec2 u_half; // node half-extent, device px
|
|
1676
|
+
uniform float u_wedge; // angular width of one wedge, radians
|
|
1677
|
+
uniform float u_angle; // pattern rotation, radians
|
|
1678
|
+
uniform float u_offset; // radial offset of the sampled wedge, normalised
|
|
1679
|
+
uniform float u_amount; // 0\u20131 blend from the original to the folded pattern
|
|
1680
|
+
|
|
1681
|
+
vec4 main(vec2 fragCoord) {
|
|
1682
|
+
vec2 half_ = max(u_half, vec2(1.0));
|
|
1683
|
+
vec2 p = (fragCoord - u_center) / half_; // aspect-normalised
|
|
1684
|
+
|
|
1685
|
+
float r = length(p);
|
|
1686
|
+
float a = atan(p.y, p.x) - u_angle;
|
|
1687
|
+
|
|
1688
|
+
// Fold into a single mirrored wedge.
|
|
1689
|
+
a = mod(a, u_wedge);
|
|
1690
|
+
a = abs(a - u_wedge * 0.5);
|
|
1691
|
+
a += u_angle;
|
|
1692
|
+
|
|
1693
|
+
vec2 sampled = vec2(cos(a), sin(a)) * max(r + u_offset, 0.0);
|
|
1694
|
+
vec4 folded = u_content.eval(u_center + sampled * half_);
|
|
1695
|
+
|
|
1696
|
+
// Mixing the *sampled colours* rather than the sample positions: blending
|
|
1697
|
+
// the coordinates would slide the fold across the image as it ramps, which
|
|
1698
|
+
// reads as a warp rather than as the pattern appearing.
|
|
1699
|
+
return mix(u_content.eval(fragCoord), folded, u_amount);
|
|
1700
|
+
}
|
|
1701
|
+
`,qf={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=ne(ek,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 tk=16,rk=1;function nk(r,e){let t=i=>{switch(e){case"add":case"plus":return`acc = acc + ${i};`;case"normal":case"source-over":return`acc = acc + ${i} * (1.0 - acc.a);`;default:return`vec4 t = ${i}; acc = acc + t - acc * t;`}},n=Array.from({length:r},(i,s)=>`
|
|
1702
|
+
{
|
|
1703
|
+
float dtn = u_delay * ${(s+1).toFixed(1)};
|
|
1704
|
+
vec2 q = fragCoord + u_velocity * dtn; // undo the translation
|
|
1705
|
+
vec2 d = q - u_center;
|
|
1706
|
+
float a = u_angular * dtn; // undo the rotation
|
|
1707
|
+
float c = cos(a);
|
|
1708
|
+
float s = sin(a);
|
|
1709
|
+
vec2 p = u_center + vec2(d.x * c - d.y * s, d.x * s + d.y * c);
|
|
1710
|
+
${t(`u_content.eval(p) * u_weights[${s}]`)}
|
|
1711
|
+
}`).join("");return`
|
|
1712
|
+
uniform shader u_content; // the node's content this frame
|
|
1713
|
+
uniform vec2 u_center; // node centre, device px
|
|
1714
|
+
uniform vec2 u_velocity; // sampled velocity, device px per second
|
|
1715
|
+
uniform float u_angular; // sampled angular velocity, radians per second
|
|
1716
|
+
uniform float u_delay; // seconds between taps
|
|
1717
|
+
uniform float u_weights[${r}]; // per-tap alpha multiplier, decay^(n+1)
|
|
1718
|
+
|
|
1719
|
+
vec4 main(vec2 fragCoord) {
|
|
1720
|
+
vec4 acc = u_content.eval(fragCoord);
|
|
1721
|
+
${n}
|
|
1722
|
+
return acc;
|
|
1723
|
+
}
|
|
1724
|
+
`}var jf={type:"trails",sampling:{tileMode:"decal",filterMode:"linear"},makeShader(r,e,t,n){let i=Math.max(0,Math.min(tk,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<rk)return null;let d=ne(nk(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 ik=.5,sk=.6,ak=.4,ok=8,ck=48,lk=1.5,Gf=.6,uk=.9;function dk(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;
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
vec4 main(vec2 fragCoord) {
|
|
1741
|
+
float c = coverage(fragCoord);
|
|
1742
|
+
|
|
1743
|
+
// 0 on the outline, 1 once the bevel has bottomed out.
|
|
1744
|
+
float t = clamp((c - 0.5) * 2.0, 0.0, 1.0);
|
|
1745
|
+
float u = 1.0 - t;
|
|
1746
|
+
|
|
1747
|
+
vec2 g = vec2(
|
|
1748
|
+
coverage(fragCoord + vec2(u_step, 0.0)) - coverage(fragCoord - vec2(u_step, 0.0)),
|
|
1749
|
+
coverage(fragCoord + vec2(0.0, u_step)) - coverage(fragCoord - vec2(0.0, u_step))
|
|
1750
|
+
);
|
|
1751
|
+
// The mask grows inward, so its gradient points inward; the outward normal
|
|
1752
|
+
// is its negation. A flat interior has no gradient to normalize.
|
|
1753
|
+
float slope = length(g);
|
|
1754
|
+
vec2 n = slope > 1e-5 ? -g / slope : vec2(0.0);
|
|
1755
|
+
|
|
1756
|
+
vec2 offset = n * (u_refraction * u);
|
|
1757
|
+
vec2 spread = offset * u_dispersion;
|
|
1758
|
+
|
|
1759
|
+
// Red bends least and blue most, as through a prism. The gap between the
|
|
1760
|
+
// three sample positions *is* the dispersion.
|
|
1761
|
+
vec4 r = u_backdrop.eval(fragCoord + offset + spread);
|
|
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);
|
|
1765
|
+
${r?`
|
|
1766
|
+
// Sampled at the *refracted* position too, so a frosted panel still bends
|
|
1767
|
+
// what is behind it rather than flattening to a plain blur.
|
|
1768
|
+
glass = mix(glass, u_soft.eval(fragCoord + offset), u_frost);
|
|
1769
|
+
`:""}
|
|
1770
|
+
vec3 N = vec3(n * u, sqrt(max(0.0, 1.0 - u * u)));
|
|
1771
|
+
// Scaled by the bevel weight as well as by the normal: without it the flat
|
|
1772
|
+
// interior, whose normal points straight out, takes a uniform wash of light.
|
|
1773
|
+
float spec = pow(max(dot(N, u_light), 0.0), u_shininess) * u_gain * u;
|
|
1774
|
+
|
|
1775
|
+
// Source-over of an opaque white highlight, premultiplied \u2014 adding it to the
|
|
1776
|
+
// colour instead would break the premultiplied invariant wherever the
|
|
1777
|
+
// backdrop is transparent.
|
|
1778
|
+
float sa = clamp(spec, 0.0, 1.0);
|
|
1779
|
+
vec4 highlight = vec4(sa);
|
|
1780
|
+
return highlight + glass * (1.0 - sa);
|
|
1781
|
+
}
|
|
1782
|
+
`}var pi=r=>Math.min(1,Math.max(0,r)),hk=(r,e,t)=>r+(e-r)*t;function Kf(r,e){let t=Math.min(e.width,e.height)/2;return pi(r.depth/100)*ik*t}function fk(r,e){return pi(r.frost/100)*ok*e.scale}var $f={type:"glass",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop",renderInputs(r,e,t){let n=Kf(r,t)/2;if(!(n>0))return null;let i=fk(r,t);return i>0?{silhouette:n,blurredSource:i}:{silhouette:n}},makeShader(r,e,t,n,i,s){let a=s?.silhouette;if(!a||n.width<=0||n.height<=0)return null;let o=s?.blurredSource,c=o?pi(r.frost/100):0,l=Kf(r,n),u=pi(r.refraction/100)*sk*l,d=pi(r.dispersion/100)*ak,h=pi(r.splay/100),f=Math.max(0,r.lightIntensity/100)*uk,p=r.lightAngle*Math.PI/180,m=Math.cos(p),g=Math.sin(p),y=Math.hypot(m,g,Gf),b=Math.max(1,l*.125),k=ne(dk(c>0),e);return k?k.makeShaderWithChildren([b,u,d,...c>0?[c]:[],m/y,g/y,Gf/y,hk(ck,lk,h),f],c>0?[t,a,o]:[t,a]):null}};var Xf={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 Qf={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 Yf={type:"colorMatrix",makeImageFilter(r,e){let t=e.ColorFilter.MakeMatrix(r.matrix),n=e.ImageFilter.MakeColorFilter(t,null);return t.delete(),n}};function mk(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 Pn=32;function pk(r){let e=[...r].sort((n,i)=>n[0]-i[0]),t=[];for(let n=0;n<=Pn;n++){let i=mk(e,n/Pn);t.push(Number.isFinite(i)?Math.max(0,Math.min(1,i)):n/Pn)}return t}function gk(r){return r.every((e,t)=>Math.abs(e-t/Pn)<1e-4)}function yk(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 wk(){let r=Array.from({length:Pn},(e,t)=>` y += (u_curve[${t+1}] - u_curve[${t}]) * clamp(t - ${t}.0, 0.0, 1.0);`).join(`
|
|
1783
|
+
`);return`
|
|
1784
|
+
uniform shader u_content;
|
|
1785
|
+
uniform vec4 u_mask; // 1 on the channels this curve drives
|
|
1786
|
+
uniform float u_curve[${Pn+1}]; // the curve, evenly spaced over 0\u20131
|
|
1787
|
+
|
|
1788
|
+
vec4 lookup(vec4 c) {
|
|
1789
|
+
vec4 t = clamp(c, 0.0, 1.0) * ${Pn}.0;
|
|
1790
|
+
vec4 y = vec4(u_curve[0]);
|
|
1791
|
+
${r}
|
|
1792
|
+
return y;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
vec4 main(vec2 p) {
|
|
1796
|
+
vec4 src = u_content.eval(p);
|
|
1797
|
+
// Nothing to grade, and dividing by zero alpha would make a NaN that spreads.
|
|
1798
|
+
if (src.a <= 0.0) return src;
|
|
1799
|
+
|
|
1800
|
+
// A curve is defined on straight colour; the shader is handed (and must
|
|
1801
|
+
// return) premultiplied. The alpha it is remultiplied by is the *curved*
|
|
1802
|
+
// one, so a curve on the alpha channel means what it says.
|
|
1803
|
+
vec4 straight = vec4(src.rgb / src.a, src.a);
|
|
1804
|
+
vec4 curved = mix(straight, lookup(straight), u_mask);
|
|
1805
|
+
return vec4(clamp(curved.rgb, 0.0, 1.0) * curved.a, curved.a);
|
|
1806
|
+
}
|
|
1807
|
+
`}var Zf={type:"curves",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t){let n=pk(r.points??[]);if(gk(n))return null;let i=ne(wk(),e);return i?i.makeShaderWithChildren([...yk(r.channel??"rgb"),...n],[t]):null}};function bk(){return[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]}function kk(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 xk(r){return[1,0,0,0,r,0,1,0,0,r,0,0,1,0,r,0,0,0,1,0]}function Sk(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 Jf(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 Tk(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 vk(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 Ak(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 _k(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 Ck(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 em={type:"colorAdjustment",makeImageFilter(r,e){let t=bk(),n=!1,i=g=>{t=kk(g,t),n=!0},s=r.brightness??0;s!==0&&i(xk(s));let a=r.contrast??1;a!==1&&i(Sk(a));let o=r.saturation??1;o!==1&&i(Jf(o));let c=((r.hue??0)%360+360)%360;c!==0&&i(Tk(c));let l=r.vibrance??0;l!==0&&i(Jf(1+l*.7));let u=r.temperature??0;u!==0&&i(vk(u));let d=r.tint??0;d!==0&&i(Ak(d));let h=r.shadows??0;h!==0&&i(_k(h));let f=r.highlights??0;if(f!==0&&i(Ck(f)),!n)return null;let p=e.ColorFilter.MakeMatrix(t),m=e.ImageFilter.MakeColorFilter(p,null);return p.delete(),m}};var Ek=new Set(["motionBlurResolved"]),Zr=new Map;function Ik(r){if(Ek.has(r.type))return;let e=n=>Pk({type:r.type,mode:n});(e("foreground")==="shader"||e("backdrop")==="shader")&&!r.makeShader&&console.warn(`[motion-script] 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(`[motion-script] Effect handler '${r.type}' has makeShader() but no sampling mode.`)}function Mk(r,e,t){return r==null||e.clip!==!0?r:t.ImageFilter.MakeBlend(t.BlendMode.SrcIn,null,r)??r}var ge={register(r){Ik(r),Zr.set(r.type,r)},alias(r,e){let t=Zr.get(e);if(!t)throw new Error(`Cannot alias "${r}" to unregistered effect "${e}".`);Zr.set(r,t)},get(r){return Zr.get(r)},has(r){return Zr.has(r)},makeImageFilter(r,e,t){let n=Zr.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=Mk(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=Zr.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 Zr.values())r.dispose?.()}};ge.register(Uh);ge.register(zh);ge.register(Nh);ge.register(Vh);ge.register(Hh);ge.register(Wh);ge.register(qh);ge.register(jh);ge.register(Kh);ge.register(Xh);ge.register(tf);ge.register(rf);ge.register(nf);ge.register(sf);ge.register(af);ge.register(of);ge.register(cf);ge.register(lf);ge.register(uf);ge.register(df);ge.register(hf);ge.register(ff);ge.register(pf);ge.register(yf);ge.register(wf);ge.register(bf);ge.register(kf);ge.register(Tf);ge.register(If);ge.register(Mf);ge.register(Rf);ge.register(Bf);ge.register(Df);ge.register(zf);ge.register(Nf);ge.register(Vf);ge.register(Hf);ge.register(Wf);ge.register(qf);ge.register(jf);ge.register($f);ge.register(Jh);ge.alias("sksl","shader");ge.register(ef);ge.register(Xf);ge.register(Qf);ge.register(Yf);ge.register(Zf);ge.register(em);var ro=class extends qe{applyPaint(e,t){if(!e.src)return ja(t);let n=t.getShapeBounds(),i=t.assets.getImageSize(e.src),s=i?Wl(e,i,n,t):void 0,a=t.assets.getCKImage(e.src,s);if(!a)throw new Fk("image",e.src);let o=Ps(a,e,t.canvasKit,n,no(e),{logical:i,footprint:s,mipmaps:!0});return t.transientPaintObjects.push(o),t.paint.setShader(io(e,t,o)),!0}dispose(){Lh()}};function Bk(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 Dk(r,e){let t=e.getDeviceMatrix(),n=t?Ya(t[0],t[1],t[3],t[4]):1;return{...r,width:r.width*n,height:r.height*n,scale:n}}function Wl(r,e,t,n){let i=so(e.width,e.height,r,t);return Of(n.getDeviceMatrix(),i,e.width,e.height,t)}function no(r){for(let e of r.preset?.adjustments??[]){let t=ge.resolveShader(e,"foreground");if(t)return t.sampling?.filterMode}}function io(r,e,t){let n=r.preset?.intensity??1,i=(r.preset?.adjustments??[]).filter(d=>Rk(d.type));if(i.length===0||n<=0)return e.paint.setImageFilter(null),t;let s=Bk(e.getShapeBounds(),e.elapsed),a=[],o=t,c;for(let d of i){let h=ge.resolveShader(d,"foreground");if(!h){a.push(d);continue}let f=e.effectResources();f&&h.resources&&(c??=Dk(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=Ok(t,o,n,e);d&&(e.transientPaintObjects.push(d),o=d)}let l=a.length>0?ge.compose(a,e.canvasKit,s):null;l&&e.transientPaintObjects.push(l);let u=n<1&&l?Uk(l,n,e):l;return u&&u!==l&&e.transientPaintObjects.push(u),e.paint.setImageFilter(u),e.clipFilterToShape=u!=null,o}function Ok(r,e,t,n){let i=ne(Lk,n.canvasKit);return i?i.makeShaderWithChildren([t],[r,e]):null}var Lk=`
|
|
1808
|
+
uniform shader u_dry;
|
|
1809
|
+
uniform shader u_wet;
|
|
1810
|
+
uniform float u_t;
|
|
1811
|
+
|
|
1812
|
+
vec4 main(vec2 p) {
|
|
1813
|
+
return mix(u_dry.eval(p), u_wet.eval(p), u_t);
|
|
1814
|
+
}
|
|
1815
|
+
`;function Uk(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 so(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 Ps(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=mi(so(d,h,e,n),d,h,l,u),p=i!=="nearest"&&s.mipmaps===!0&&Lf(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 Vk(r,e){let t;return zk(r,n=>{if(!Nk(n)||t?.has(n))return;let i=n.static===!0?n.identity:void 0;if(i!==void 0){let a=ql.get(i);if(a){(t??=new Map).set(n,a);return}}let s=e.rasterizeSurface(n.source,n.width,n.height,n.maxPixelRatio??1);s&&((t??=new Map).set(n,s),i!==void 0&&ql.set(i,s))}),t}var ql=new Map;function tm(){ql.clear()}var ao=class extends qe{preflight(e,t){let n=`${t.nodeId}#${t.paintSlot(e)}`,i=oi(t.assets);if(!i){wl(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=Vk(e.scene,t),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=so(n.width(),n.height(),{fit:"stretch"},t.getShapeBounds());return t.paint.setShader(n.makeShaderOptions(i.TileMode.Decal,i.TileMode.Decal,i.FilterMode.Linear,i.MipmapMode.None,s)),!0}};import{requireFontFamily as rm}from"@motionscript/core";function Hk(r,e){switch(e){case"italic":return r.FontSlant.Italic;case"oblique":return r.FontSlant.Oblique;default:return r.FontSlant.Upright}}function Wk(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 im(r,e,t,n){let i=r.FontCollection.Make();i.setDefaultFontManager(e);let s=new r.ParagraphStyle({textStyle:{fontFamilies:[rm(t[0])],fontSize:t[0].fontSize},textAlign:Wk(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:[rm(y)],fontSize:y.fontSize,fontStyle:{weight:{value:y.fontWeight},slant:Hk(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+qk(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=im(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,P)=>{let _=`${M.fontFamily}@${M.fontWeight}@${M.fontStyle}@${M.fontSize}`,F=g.get(_);if(F)return P?.delete(),F;let E=fi(r,P,M.fontSize);return P?.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"),S=o.getShapedLines();for(let M of S){let P=b.length,_=[];for(let F of M.runs){let E=F.glyphs.length;if(E===0)continue;let U=y(t[Gl(u,t,F.offsets[0])],F.typeface),Q=0,xe=Gl(u,t,F.offsets[0]),we=J=>{let Ae=J-Q;if(Ae<=0)return;let Re=new Float32Array(Ae*2);for(let et=0;et<Ae;et++)Re[et*2]=F.positions[(Q+et)*2]+p,Re[et*2+1]=F.positions[(Q+et)*2+1]+m;b.push({segmentIndex:xe,glyphs:F.glyphs.slice(Q,J),positions:Re,font:U}),T&&_.push(F.offsets.slice(Q,J))};for(let J=1;J<E;J++){let Ae=Gl(u,t,F.offsets[J]);Ae!==xe&&(we(J),Q=J,xe=Ae)}we(E)}T&&jk(b,P,_,k,t)}let A=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:A,width:h,height:f,fonts:i}}function oo(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=oo(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=im(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)),S=T>k&&s[T-1]===`
|
|
1816
|
+
`?T-1:T;g=T;let A=b.baseline-b.ascent+f,M=b.baseline+b.descent+f,P=[];for(let _=k;_<S;_++)P.push(nm(o,r,_,!1)+h);P.push(S>k?nm(o,r,S-1,!0)+h:b.left+h),m.push({start:k,end:S,top:A,bottom:M,carets:P})}return o.delete(),c.delete(),l.delete(),m.length===0?null:{lines:m,width:u,height:d}}function nm(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 qk(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 jk(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=Gk(o,l,u.fontSize,u.decoration))}}function Gk(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=jl(i.underlineThickness)??t/14,h=c+(jl(i.underlinePosition)??d);return{left:a,top:h,right:o,bottom:h+d}}let l=jl(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 jl(r){return r!==void 0&&r>0?r:void 0}function Gl(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 Kl(r,e,t){$l(r,e,0,0,t)}function $l(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 sm(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 hm,isStyleOnlySegment as ax,resolveShapePivot as ox}from"@motionscript/core";import{AUTOFIT_PROBE_SIZE as Kk,withTextDescriptor as $k}from"@motionscript/core";function Xl(r){let e=r.fontSize==="autofit"?Kk: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 am(r,e,t){let n=$k(t),i=n.segments??[],s=Xl(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 om(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 Xk,pathOps as Qk}from"@motionscript/core";function Yk(r,e){switch(e){case"italic":return r.FontSlant.Italic;case"oblique":return r.FontSlant.Oblique;default:return r.FontSlant.Upright}}function Zk(r,e,t){switch(r){case"right":case"end":return t-e;case"center":return(t-e)/2;default:return 0}}var Jk=64,Jr=new Map;function ex(r,e){return[r.text,r.fontFamily,e,r.fontWeight,r.fontStyle,r.letterSpacing,r.lineHeight].join("")}function tx(r,e,t,n){let i=ex(t,n),s=Jr.get(i);if(s)return Jr.delete(i),Jr.set(i,s),s.run;let a=rx(r,e,t,n);if(!a)return null;if(Jr.set(i,{run:a.run,fonts:a.fonts}),Jr.size>Jk){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 rx(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:Yk(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=fi(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,A=m.positions[b*2+1]-h.baseline;p.push({glyphId:m.glyphs[b],midX:S,advance:T,perp:A,font:y})}}return c.delete(),o.delete(),s.delete(),{run:{glyphs:p,textWidth:f,fontSize:n},fonts:i}}function nx(r,e,t){let n={glyphs:[],bounds:{left:0,top:0,right:0,bottom:0}},i=Qk.sampler(e);if(i.length<=0)return n;let s=Zk(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 cm(r,e,t){let n=Xk(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=tx(r,e,n,s);return a?nx(a,n.path,n.textAlign):i}function lm(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 ix={width:0,height:0},sx="";function Ql(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(sx)}var co=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 Yl(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 um="center",dm=1;function lo(r,e,t,n,i,s,a,o,c,l){if(i.length===0)return ix;let u={text:i,fontFamily:a,fontSize:s,fontWeight:o,fontStyle:l,letterSpacing:c},d=Ql(Yl(u,um,dm,1/0,0),n),{layout:h}=t.get(d,()=>Tr(r,e,[u],{textAlign:um,lineHeight:dm,maxWidth:1/0,originX:0,originY:0}));return{width:h.width,height:h.height}}function cx(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 fm(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 uo(r,e,t){let n=hm(t);if(n.path!=null)return null;let i=n.segments??[];if(i.length>0){if(!i.every(ax))return null;let o=n.wrap&&n.width>0;return oo(r,e,Xl(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}=fm(r,e,n);return oo(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 mm(r,e,t,n,i,s){let a=hm(n);if(a.path!=null){let F=cm(r,t,n);return{bounds:F.bounds,draw:E=>lm(e,F.glyphs,E)}}let o=a.x,c=a.y,{segment:l,maxWidth:u}=fm(r,t,a),d=Ql(Yl(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=ox(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=a.scale,M=S!==0||A!==1,P=y+f.x*(m/2),_=b-f.y*(g/2);return M&&(T=cx(T,P,_,S,A)),{bounds:T,isText:!0,draw:F=>{M&&e.save();try{M&&(e.translate(P,_),e.rotate(S,0,0),e.scale(A,A),e.translate(-P,-_));for(let E of h.runs)$l(e,E,y,b,F)}finally{M&&e.restore()}}}}import{cornerRadiusOps as Zl,cornerStyleOps as lx,withRectDescriptor as ux}from"@motionscript/core";function En(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=En(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=En(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 pm(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 gi=class extends Tt{resolveState(e){return ux(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=Zl.resolve(e.cornerRadius),l=lx.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=gm(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:Zl.isZero(m),isUniform:Zl.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`:pm(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=gm(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`:pm(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 gm(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 dx}from"@motionscript/core";var en=Math.PI/180,yi=class extends Tt{resolveState(e){return dx(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?ym(e):wm(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?ym(e):wm(e)}buildStrokePath(e){let t=this._outline();if(!t)return;if(!this.needsTrim())return t.copy();let{start:n,end:i}=this.getTrimRange();return En(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):hx(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 Jl(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 hx(r){let{start:e,arc:t}=Jl(r);return`M ${e} ${t}`}function ym(r){let{start:e,arc:t}=Jl(r);return`M ${r.cx} ${r.cy} L ${e} ${t} Z`}function wm(r){let{cx:e,cy:t,halfWidth:n,halfHeight:i,startAngle:s,sweep:a,ratio:o}=r,{start:c,arc:l}=Jl(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 fx}from"@motionscript/core";function mx(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],A=Math.hypot(T,S),M=T/A,P=S/A,_=Math.max(-1,Math.min(1,b*M+k*P)),F=Math.acos(_)/2,E=Math.tan(F),U=Math.min(y,A)/2,Q=s/E;Q>U&&(Q=U);let xe=Q*E,we=f[0]+b*Q,J=f[1]+k*Q;u.push(`${u.length===0?"M":"L"} ${we} ${J}`),u.push(Is(f[0],f[1],b,k,M,P,Q,xe,a))}return u.push("Z"),u.join(" ")}var wi=class extends Tt{resolveState(e){return fx(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 mx(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 px}from"@motionscript/core";function gx(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,A=k/T,M=y[0]-p[0],P=y[1]-p[1],_=Math.hypot(M,P),F=M/_,E=P/_,U=Math.max(-1,Math.min(1,S*F+A*E)),Q=Math.acos(U)/2,xe=Math.tan(Q),we=Math.min(T,_)/2,J=a/xe;J>we&&(J=we);let Ae=J*xe,Re=p[0]+S*J,et=p[1]+A*J;h.push(`${h.length===0?"M":"L"} ${Re} ${et}`),h.push(Is(p[0],p[1],S,A,F,E,J,Ae,o))}return h.push("Z"),h.join(" ")}var bi=class extends Tt{resolveState(e){return px(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 gx(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 yx,withPathDescriptor as wx}from"@motionscript/core";var ki=class extends Tt{resolveState(e){return wx(e)}computeGeometry(){return{svgString:yx(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 En(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 bx}from"@motionscript/core";function kx(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 xi=class extends Tt{resolveState(e){return bx(e)}computeGeometry(){let{points:e,radius:t,closed:n}=this.fullState;return{points:e,radius:t,closed:n}}buildSVGPath(e){return kx(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 bm}from"@motionscript/core";var xx=1,Fs=.001,ho=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=bm.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:bm.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 _=g.getSegment(M,P,!0);_&&(o.addPath(_),_.delete(),u=!0)}else if(i){let[_,F,E,U]=g.getPosTan(M),Q=M>d-Fs?-Fs:Fs;o.moveTo(_,F),o.lineTo(_+E*Q,F+U*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,A=0;for(;A<d-1e-6;){let M=Math.min(T,d-A);S&&y(A,A+M),A+=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),A=(T-b)/(m-f);if(Math.abs(S-1)<1e-4&&Math.abs(A-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-A*l[1];return e.save(),e.concat([S,0,M,0,A,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(xx/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 A of t){let M=this.snapPath(l,S,A.ckPath);this.drawStroke(l,m,A,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 fo=class{canvasKit;getCanvas;pathCollectionStack=[];booleanOpStack=[];constructor(e,t){this.canvasKit=e,this.getCanvas=t}dispose(){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 mo=class{canvasKit;getCanvas;boolean;maskStack=[];constructor(e,t,n){this.canvasKit=e,this.getCanvas=t,this.boolean=n}dispose(){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 po(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(!po(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(!po(r[n],e[n]))return!1;return!0}return!1}function Sx(r){return{left:r[0],top:r[1],right:r[2],bottom:r[3]}}function Tx(r,e){let t=Object.keys(r);if(t.length!==Object.keys(e).length)return!1;for(let n of t)if(!po(r[n],e[n]))return!1;return!0}function vx(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(!po(r[a],e[a]))return!1;return!0}var go=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 fo(e,t),this.mask=new mo(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()}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?Sx(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(Tx(o,c))n=a;else if(a.hasTrim()&&e.hasTrim()&&vx(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 gi(this.canvasKit,this.getCanvas,e))}ellipse(e){this.addShape(new yi(this.canvasKit,this.getCanvas,e))}path(e){this.addShape(new ki(this.canvasKit,this.getCanvas,e))}line(e){this.addShape(new xi(this.canvasKit,this.getCanvas,e))}polygon(e){this.addShape(new wi(this.canvasKit,this.getCanvas,e))}polygram(e){this.addShape(new bi(this.canvasKit,this.getCanvas,e))}text(e){this._boundsDirty=!0;let t=mm(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 Ax,resolveVideoTimestamp as _x}from"@motionscript/core";var yo=class r extends qe{static MAX_ECHOES=32;applyPaint(e,t){if(!e.src)return ja(t);let n=t.assets.getVideoDuration(e.src);if(n===0)throw new Ax("video",e.src);let i=_x(e,t.elapsed,n),s=t.assets.getVideoSize(e.src),a=t.getShapeBounds(),o=s?Wl(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,no(e),{logical:s});return t.transientPaintObjects.push(u),t.paint.setShader(io(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,no(e),{logical:a});t.transientPaintObjects.push(m),c.setShader(io(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 Si(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 km(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 wo=class extends qe{cache=new tn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let s=km(e.start.x,e.start.y,i),a=km(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=Si(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 Cx(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 bo=class extends qe{cache=new tn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let s=Cx(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=Si(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 Px(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 ko=class extends qe{cache=new tn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let[s,a]=Px(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=Si(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 Ex=24,Ti=new Map;function Ix(r,e){for(Ti.set(r,e);Ti.size>Ex;){let t=Ti.keys().next();if(t.done)break;Ti.get(t.value)?.delete?.(),Ti.delete(t.value)}}function Mx(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 xm(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 Fx(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=xm(k,y,p),S=(g*r+b)*4;if(T<f){let A=xm(k,y,p+1);m[S]=Math.round(o*A),m[S+1]=Math.round(c*A),m[S+2]=Math.round(l*A),m[S+3]=u}}}return m}var xo=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=Mx(e,i,s),o=Ti.get(a);if(!o){let d=Fx(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;Ix(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 Rx=8,Bx=`
|
|
1817
|
+
vec2 hash2(vec2 p) {
|
|
1818
|
+
vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
|
|
1819
|
+
p3 += dot(p3, p3.yzx + 33.33);
|
|
1820
|
+
return fract((p3.xx + p3.yz) * p3.zy);
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
float hash1(vec2 p) {
|
|
1824
|
+
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
float valueNoise(vec2 p) {
|
|
1828
|
+
vec2 i = floor(p);
|
|
1829
|
+
vec2 f = fract(p);
|
|
1830
|
+
// Quintic smoothstep: its first *and* second derivatives vanish at the cell
|
|
1831
|
+
// edges, so summed octaves show no grid creases the way cubic ones do.
|
|
1832
|
+
vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
|
|
1833
|
+
float a = hash1(i);
|
|
1834
|
+
float b = hash1(i + vec2(1.0, 0.0));
|
|
1835
|
+
float c = hash1(i + vec2(0.0, 1.0));
|
|
1836
|
+
float d = hash1(i + vec2(1.0, 1.0));
|
|
1837
|
+
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
float simplexNoise(vec2 p) {
|
|
1841
|
+
const float K1 = 0.366025404; // (sqrt(3) - 1) / 2
|
|
1842
|
+
const float K2 = 0.211324865; // (3 - sqrt(3)) / 6
|
|
1843
|
+
|
|
1844
|
+
vec2 i = floor(p + (p.x + p.y) * K1);
|
|
1845
|
+
vec2 a = p - (i - (i.x + i.y) * K2);
|
|
1846
|
+
float m = step(a.y, a.x);
|
|
1847
|
+
vec2 o = vec2(m, 1.0 - m);
|
|
1848
|
+
vec2 b = a - o + K2;
|
|
1849
|
+
vec2 c = a - 1.0 + 2.0 * K2;
|
|
1850
|
+
|
|
1851
|
+
vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);
|
|
1852
|
+
vec3 g = vec3(
|
|
1853
|
+
dot(a, hash2(i) * 2.0 - 1.0),
|
|
1854
|
+
dot(b, hash2(i + o) * 2.0 - 1.0),
|
|
1855
|
+
dot(c, hash2(i + 1.0) * 2.0 - 1.0)
|
|
1856
|
+
);
|
|
1857
|
+
return dot(h * h * h * h * g, vec3(70.0)) * 0.5 + 0.5;
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
float worleyNoise(vec2 p) {
|
|
1861
|
+
vec2 i = floor(p);
|
|
1862
|
+
vec2 f = fract(p);
|
|
1863
|
+
float best = 1.0;
|
|
1864
|
+
for (int y = -1; y <= 1; y++) {
|
|
1865
|
+
for (int x = -1; x <= 1; x++) {
|
|
1866
|
+
vec2 cell = vec2(float(x), float(y));
|
|
1867
|
+
vec2 point = hash2(i + cell);
|
|
1868
|
+
best = min(best, length(cell + point - f));
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
return best;
|
|
1872
|
+
}
|
|
1873
|
+
`;function Dx(r,e,t){let i=r==="ridged"?`
|
|
1874
|
+
float prev = 1.0;
|
|
1875
|
+
for (int o = 0; o < ${e}; o++) {
|
|
1876
|
+
float r = 1.0 - abs(simplexNoise(q) * 2.0 - 1.0);
|
|
1877
|
+
r = r * r * prev;
|
|
1878
|
+
prev = clamp(r, 0.0, 1.0);
|
|
1879
|
+
sum += r * amplitude;
|
|
1880
|
+
total += amplitude;
|
|
1881
|
+
amplitude *= u_gain;
|
|
1882
|
+
q *= u_lacunarity;
|
|
1883
|
+
}`:`
|
|
1884
|
+
for (int o = 0; o < ${e}; o++) {
|
|
1885
|
+
sum += ${r==="value"?"valueNoise(q)":r==="worley"?"worleyNoise(q)":"simplexNoise(q)"} * amplitude;
|
|
1886
|
+
total += amplitude;
|
|
1887
|
+
amplitude *= u_gain;
|
|
1888
|
+
q *= u_lacunarity;
|
|
1889
|
+
}`;return`${Bx}
|
|
1890
|
+
uniform vec2 u_origin; // shape bounds origin, shape-local logical px
|
|
1891
|
+
uniform vec2 u_size; // shape bounds size, shape-local logical px
|
|
1892
|
+
uniform vec2 u_frequency; // cycles of the first octave across the shape
|
|
1893
|
+
uniform vec2 u_offset; // pan through the field, in cycles
|
|
1894
|
+
uniform float u_lacunarity;
|
|
1895
|
+
uniform float u_gain;
|
|
1896
|
+
uniform float u_seed;
|
|
1897
|
+
uniform float u_cos; // field rotation, precomputed
|
|
1898
|
+
uniform float u_sin;
|
|
1899
|
+
uniform float u_contrast;
|
|
1900
|
+
uniform vec4 u_colors[${t}];
|
|
1901
|
+
uniform float u_stops[${t}];
|
|
1902
|
+
|
|
1903
|
+
vec4 main(vec2 fragCoord) {
|
|
1904
|
+
// Normalised to the shape's own box, so the field is pinned to the figure
|
|
1905
|
+
// and u_frequency means "cycles across this shape" at any size.
|
|
1906
|
+
vec2 uv = (fragCoord - u_origin) / max(u_size, vec2(1.0));
|
|
1907
|
+
|
|
1908
|
+
vec2 r = vec2(uv.x * u_cos - uv.y * u_sin, uv.x * u_sin + uv.y * u_cos);
|
|
1909
|
+
vec2 base = r * u_frequency + u_offset + u_seed;
|
|
1910
|
+
|
|
1911
|
+
float sum = 0.0;
|
|
1912
|
+
float amplitude = 1.0;
|
|
1913
|
+
float total = 0.0;
|
|
1914
|
+
vec2 q = base;
|
|
1915
|
+
${i}
|
|
1916
|
+
// Normalising by the summed amplitudes keeps the field in 0\u20131 whatever the
|
|
1917
|
+
// gain, so changing octaves or gain re-textures without also re-exposing.
|
|
1918
|
+
float n = clamp(sum / max(total, 0.0001), 0.0, 1.0);
|
|
1919
|
+
|
|
1920
|
+
// Contrast about the midpoint, so steepening does not also brighten.
|
|
1921
|
+
n = clamp((n - 0.5) * u_contrast + 0.5, 0.0, 1.0);
|
|
1922
|
+
|
|
1923
|
+
vec4 color = u_colors[0];
|
|
1924
|
+
for (int i = 1; i < ${t}; i++) {
|
|
1925
|
+
float t = clamp((n - u_stops[i - 1]) / max(u_stops[i] - u_stops[i - 1], 0.0001), 0.0, 1.0);
|
|
1926
|
+
color = mix(color, u_colors[i], step(u_stops[i - 1], n) * t);
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
// Premultiply: the paint's shader output is composited as premultiplied.
|
|
1930
|
+
// Deliberately *not* multiplied by the fill's opacity or the world alpha \u2014
|
|
1931
|
+
// FillHandler has already put both on the paint via setAlphaf, and Skia
|
|
1932
|
+
// modulates a shader's output by the paint alpha, so folding them in here
|
|
1933
|
+
// would square them.
|
|
1934
|
+
return vec4(color.rgb * color.a, color.a);
|
|
1935
|
+
}
|
|
1936
|
+
`}var So=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(Rx,e.colors.length)),o=ne(Dx(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 Ox,writeUniforms as Lx}from"@motionscript/core";var To=new Map;function Ux(r,e,t){let n=t.canvasKit,i=To.get(r);if(i&&i.image===e)return i.shader;i?.shader.delete();let s=t.assets.getImageSize(r),a=s?mi(Sm,s.width,s.height,e.width(),e.height()):Sm,o=e.makeShaderOptions(n.TileMode.Repeat,n.TileMode.Repeat,n.FilterMode.Linear,n.MipmapMode.None,a);return To.set(r,{image:e,shader:o}),o}var Sm=[1,0,0,0,1,0,0,0,1],vo=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=ne(e.source,t.canvasKit);if(!a)return!1;let o=Cs(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=Lx(o.slots,o.floats,e.uniforms,c,e.source),u=Ox(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&&Yr("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 Yr(`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 Yr(`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(Ux(a.src,o,n))}return i}dispose(){for(let{shader:e}of To.values())e.delete();To.clear()}};var Ao=new Map;function zx(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 Nx(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 Vx(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 _o=class extends qe{applyPaint(e,t){let n=zx(e),i=Ao.get(n);if(!i){let u=Nx(e,t.canvasKit);if(!u)return!1;i=u,Ao.set(n,i)}let s=t.getShapeBounds(),a=s?.left??0,o=s?.top??0,c=e.angle??-45,l=Vx(c,a,o);return t.paint.setShader(i.makeShaderOptions(t.canvasKit.TileMode.Repeat,t.canvasKit.TileMode.Repeat,t.canvasKit.FilterMode.Linear,t.canvasKit.MipmapMode.None,l)),!0}dispose(){for(let e of Ao.values())e.delete();Ao.clear()}};var Hx=`
|
|
1937
|
+
// Declared widest-first \u2014 vec4, then vec2s, then floats.
|
|
1938
|
+
//
|
|
1939
|
+
// Skia lays runtime-effect uniforms out with alignment, so a vec4 declared after
|
|
1940
|
+
// an odd number of floats starts at the next 4-float boundary and the values fed
|
|
1941
|
+
// to makeShader (a flat, padding-free array) land one or two slots off. Every
|
|
1942
|
+
// uniform after the gap then reads garbage, which for a coverage shader means a
|
|
1943
|
+
// solid block rather than an error. Ordering by width leaves no gap to pad, so
|
|
1944
|
+
// the flat array and the layout agree by construction.
|
|
1945
|
+
uniform vec4 u_color;
|
|
1946
|
+
uniform vec2 u_origin; // shape bounds origin, shape-local logical px
|
|
1947
|
+
uniform vec2 u_offset; // lattice shift, logical px
|
|
1948
|
+
uniform float u_spacing; // lattice pitch, logical px
|
|
1949
|
+
uniform float u_radius; // dot radius, logical px
|
|
1950
|
+
uniform float u_feather; // coverage ramp width, logical px
|
|
1951
|
+
|
|
1952
|
+
vec4 main(vec2 fragCoord) {
|
|
1953
|
+
// A radius of zero is a lattice switched off, and has to be answered before
|
|
1954
|
+
// the ramp: the ramp is centred on the dot's edge, so a zero-radius dot still
|
|
1955
|
+
// lands half a pixel of coverage on the pixel it sits in.
|
|
1956
|
+
if (u_radius <= 0.0) return vec4(0.0);
|
|
1957
|
+
|
|
1958
|
+
vec2 p = fragCoord - u_origin - u_offset;
|
|
1959
|
+
// Distance from the centre of the cell this pixel falls in. SkSL's mod is
|
|
1960
|
+
// floor-based, so this holds for negative coordinates too \u2014 which is what a
|
|
1961
|
+
// shape left of the origin, or a negative offset, produces.
|
|
1962
|
+
vec2 d = mod(p, u_spacing) - u_spacing * 0.5;
|
|
1963
|
+
|
|
1964
|
+
float cover = clamp((u_radius - length(d)) / u_feather + 0.5, 0.0, 1.0);
|
|
1965
|
+
float a = u_color.a * cover;
|
|
1966
|
+
return vec4(u_color.rgb * a, a);
|
|
1967
|
+
}
|
|
1968
|
+
`,Co=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=ne(Hx,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
|
+
// Declared widest-first, so the flat array handed to makeShader needs no padding
|
|
1970
|
+
// \u2014 see the note on the dot-grid fill's source for what a gap here costs.
|
|
1971
|
+
uniform vec4 u_color;
|
|
1972
|
+
uniform vec2 u_origin; // shape bounds origin, shape-local logical px
|
|
1973
|
+
uniform vec2 u_size; // shape bounds size, shape-local logical px
|
|
1974
|
+
uniform vec2 u_offset; // ruling shift, logical px
|
|
1975
|
+
uniform float u_divisions; // cells across the shape, per axis
|
|
1976
|
+
uniform float u_subdivisions; // finer cells inside each division
|
|
1977
|
+
uniform float u_halfMajor; // half a division line's thickness, logical px
|
|
1978
|
+
uniform float u_halfMinor; // half a subdivision line's thickness, logical px
|
|
1979
|
+
uniform float u_feather; // coverage ramp width, logical px
|
|
1980
|
+
|
|
1981
|
+
/*
|
|
1982
|
+
* Coverage of the nearest line of a ruling at the given pitch, on either axis.
|
|
1983
|
+
*
|
|
1984
|
+
* SkSL's mod is floor-based, so the distance to the nearest multiple is
|
|
1985
|
+
* min(m, pitch - m) whatever the sign of the coordinate.
|
|
1986
|
+
*/
|
|
1987
|
+
float ruling(vec2 p, vec2 pitch, float halfWidth, float feather) {
|
|
1988
|
+
// A width of zero means the order is switched off, and has to be answered
|
|
1989
|
+
// here rather than left to the ramp: the ramp is centred on the line, so a
|
|
1990
|
+
// zero-width one still lands half a pixel of coverage on the pixels it runs
|
|
1991
|
+
// through \u2014 a ruling you asked not to be drawn, drawn faintly.
|
|
1992
|
+
if (halfWidth <= 0.0) return 0.0;
|
|
1993
|
+
vec2 m = mod(p, pitch);
|
|
1994
|
+
vec2 d = min(m, pitch - m);
|
|
1995
|
+
return clamp((halfWidth - min(d.x, d.y)) / feather + 0.5, 0.0, 1.0);
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
vec4 main(vec2 fragCoord) {
|
|
1999
|
+
vec2 p = fragCoord - u_origin - u_offset;
|
|
2000
|
+
|
|
2001
|
+
// Cells follow the box, so a non-square shape gets non-square cells \u2014 see
|
|
2002
|
+
// GridFillProp. Floored well above zero because a pitch of 0 makes mod
|
|
2003
|
+
// undefined, which paints garbage rather than nothing.
|
|
2004
|
+
vec2 major = max(u_size / max(u_divisions, 0.0001), vec2(0.01));
|
|
2005
|
+
vec2 minor = major / max(u_subdivisions, 1.0);
|
|
2006
|
+
|
|
2007
|
+
float cover = max(
|
|
2008
|
+
ruling(p, major, u_halfMajor, u_feather),
|
|
2009
|
+
ruling(p, minor, u_halfMinor, u_feather)
|
|
2010
|
+
);
|
|
2011
|
+
|
|
2012
|
+
float a = u_color.a * cover;
|
|
2013
|
+
return vec4(u_color.rgb * a, a);
|
|
2014
|
+
}
|
|
2015
|
+
`,Po=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(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 Eo=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 Eo},{name:"linear-gradient",renderer:new wo},{name:"radial-gradient",renderer:new bo},{name:"conic-gradient",renderer:new ko},{name:"image",renderer:new ro},{name:"video",renderer:new yo},{name:"noise",renderer:new xo},{name:"fractalNoise",renderer:new So},{name:"shader",renderer:new vo},{name:"stripe",renderer:new _o},{name:"dotGrid",renderer:new Co},{name:"grid",renderer:new Po},{name:"canvas3D",renderer:new ao}];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 Io=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 Am=r=>-(r??0);function vi(r,e,t){let n=Zx(r,e,t),{x:i,y:s,pivot:a}=Yx(n,e,t);return{...Jx(n),x:i,y:-s,pivot:a}}function eu(r){return vi(r,r.width??0,r.height??0)}function tu(r){let e=vi(r,r.width??0,r.height??0);return r.startAngle!=null&&(e.startAngle=-r.startAngle),r.sweep!=null&&(e.sweep=-r.sweep),e}function ru(r){return vi(r,r.width??0,r.height??0)}function nu(r){return vi(r,r.width??0,r.height??0)}function iu(r){let e=r.points?r.points.map(t=>({x:t.x,y:-t.y})):r.points;return{...r,y:Am(r.y),points:e}}function eS(r){return vi(r,r.width??0,r.height??0)}function tS(r){return vi(r,r.width??0,r.height??0)}function rS(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 su(r){let e={...r,y:Am(r.y)};if(Array.isArray(r.data)&&(e.data=r.data.map(rS)),r.centerBounds){let[t,n,i,s]=r.centerBounds;e.centerBounds=[t,-s,i,-n]}return e}var nS=()=>{};function iS(r,e){return e==="decal"?r.TileMode.Decal:r.TileMode.Clamp}function Tm(r,e){return e==="nearest"?r.FilterMode.Nearest:r.FilterMode.Linear}function au(r,e){return{width:r,height:e,centerX:0,centerY:0,scale:1,time:0,velocity:_m,angularVelocity:0}}var _m={x:0,y:0},vm=4,sS=4;function Cm(r,e){return e>=1?r:r.map(t=>({...t,opacity:(t.opacity??1)*e}))}function aS(r,e){return e>=1?r:r.map(t=>({...t,fill:Cm(t.fill,e)}))}var Mo=class extends jx{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.paint=new this.canvasKit.Paint,this.paint.setAntiAlias(!0),this.layerPaint=new this.canvasKit.Paint,this.buildHandlers()}measureText(e,t,n,i=400,s=0,a="normal"){return lo(this.canvasKit,this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),this.storageAdapter.getFontEpoch(),e,t,n,i,s,a)}layoutTextBlock(e){return uo(this.canvasKit,this.storageAdapter.getFontMgr(),e)}buildHandlers(){let e=()=>this.currentCanvas,t=()=>this.paint;this.shapeHandler=new go(this.canvasKit,e,t,this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),()=>this.storageAdapter.getFontEpoch());let n=()=>this.worldAlpha;this.fillHandler=new Io(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 ho(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;this.currentCanvas=this.surface.getCanvas(),this.activeSurface=this.surface,this.currentCanvas.clear(this.frame?this.canvasKit.TRANSPARENT:this.canvasKit.BLACK),this.currentCanvas.save();let t=this.surface.width()/this.pixelRatio,n=this.surface.height()/this.pixelRatio;if(this.currentCanvas.scale(this.pixelRatio,this.pixelRatio),this.currentCanvas.translate(t/2+this.view.x,n/2+this.view.y),this.view.zoom!==1&&this.currentCanvas.scale(this.view.zoom,this.view.zoom),this.frame){let s=this.canvasKit,a=this.frame.width/2,o=this.frame.height/2,c=s.LTRBRect(-a,-o,a,o),l=this.frameBackground==="black";this.clipToFrame?(this.currentCanvas.clipRect(c,s.ClipOp.Intersect,!0),l&&this.currentCanvas.drawColor(s.BLACK,s.BlendMode.Src)):l&&(this.currentCanvas.save(),this.currentCanvas.clipRect(c,s.ClipOp.Intersect,!0),this.currentCanvas.drawColor(s.BLACK,s.BlendMode.Src),this.currentCanvas.restore())}let i=oi(this.storageAdapter);i?.beginFrame(),this.fillHandler.beginFrame(),this.storageAdapter.beginRenderPass(),this.isRendering=!0;try{e()}finally{this.isRendering=!1,i?.sweep(),this.currentCanvas.restore(),this.surface.flush(),this.storageAdapter.endRenderPass()}}begin(e){if(super.begin(e),this.shapeHandler.beginNode(e.id),this.shapeHandler.reset(),!this.currentCanvas)throw new Error("begin() must be called within the draw() method.");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}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,Wa(),Oh(),tm(),An()?.dispose(),ge.disposeAll(),Gh(),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;if(t){let u=e.groupOpacity();u<1&&(this.worldAlpha*=u)}let i=e.groupTransform(),s=!1;if(i){let u=this.resolveGroupCenter(e,i.center),d=u.x,h=u.y;this.currentCanvas.save(),this.currentCanvas.translate(d,h),this.currentCanvas.rotate(i.rotation,0,0),this.currentCanvas.scale(i.scale,i.scale),this.currentCanvas.translate(-d,-h),s=!0}let a=e.ops(),o=this.buildEffectSegments(e),c=!1,l=null;for(let u=0;u<a.length;u++){let d=o.get(u);d&&(l=d.filter,this.layerPaint.setAlphaf(1),this.layerPaint.setImageFilter(l),this.currentCanvas.saveLayer(this.layerPaint),this.layerPaint.setImageFilter(null),c=!0);let h=a[u];if(h.kind==="effects"){c&&(this.currentCanvas.restore(),l?.delete?.(),l=null,c=!1),this.shapeHandler.reset();continue}this.applyOp(h)}c&&(this.currentCanvas.restore(),l?.delete?.()),s&&this.currentCanvas.restore(),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?ge.compose(l,this.canvasKit,au(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(eu(l.state));break;case"ellipse":this.shapeHandler.ellipse(tu(l.state));break;case"path":this.shapeHandler.path(su(l.state));break;case"line":this.shapeHandler.line(iu(l.state));break;case"polygon":this.shapeHandler.polygon(ru(l.state));break;case"polygram":this.shapeHandler.polygram(nu(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=Qx.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(eu(e.state));break;case"ellipse":this._ellipse(tu(e.state));break;case"path":this._path(su(e.state));break;case"line":this._line(iu(e.state));break;case"polygon":this._polygon(ru(e.state));break;case"polygram":this._polygram(nu(e.state));break;case"text":this._text(eS(e.state));break;case"richText":this._richText(tS(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=ge.compose(g,this.canvasKit,au(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?$h(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=am(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=om(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=>Kl(this.currentCanvas,n,l)},o=i.fill?Cm(i.fill,i.opacity):[];o.length>0&&this.fillHandler.applyFills(o,[a]);let c=i.stroke?aS(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=Gx(e),n=sm(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=>{Kl(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=Kx.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=$x.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=Xx.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 gi(t,n,eu(e.state));case"ellipse":return new yi(t,n,tu(e.state));case"polygon":return new wi(t,n,ru(e.state));case"polygram":return new bi(t,n,nu(e.state));case"path":return new ki(t,n,su(e.state));case"line":return new xi(t,n,iu(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=ge.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=ge.compose(e,i,au(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,Tm(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:nS};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=iS(t,n.sampling.tileMode),h=u.makeShaderOptions(d,d,Tm(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??_m,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=qx(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>=vm)return console.warn(`rasterize() nested more than ${vm} 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,sS)),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))}};var cr=class extends Mo{constructor(e,t){super(e,t)}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 vv}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),at=new TextDecoder,_t=new TextEncoder;var du=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),_r={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},In=du(_r),Cr={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Mn=du(Cr),Pr={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Fn=du(Pr),Pm=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}},Em=/^[0-9a-fA-F]+$/,nn=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),Im=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},hu=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},fu=(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}},Mm=(r,e)=>{let t=r.indexOf(e);t!==-1&&r.splice(t,1)},mu=(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},Fm=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Rm=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}`)},Bs=(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 Ds=(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))},Bm=(r,e,t,n)=>{t=Ze(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),Ds(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},Os=(r,e)=>Math.round(r/e)*e,Rn=(r,e)=>Math.round(r*e)/e,Ro=(r,e)=>Math.floor(r/e)*e,pu=(r,e)=>Math.floor(r*e)/e,Dm=r=>{let e=0;for(;r;)e++,r>>=1;return e},oS=/^[a-z]{3}$/,Pi=r=>oS.test(r),ur=1e6*(1+Number.EPSILON),Om=(r,e)=>{let t={...r,...e};if(r.headers||e.headers){let n=r.headers?Fo(r.headers):{},i=e.headers?Fo(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},Fo=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},Lm=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(ye._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 Vs(1e3*o),i())throw a}},Um=(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)}},ou=null,sn=()=>ou!==null?ou:ou=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),cu=null,Ls=()=>cu!==null?cu:cu=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),lu=null,Us=()=>lu!==null?lu:lu=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),uu=null,zm=()=>{if(uu!==null)return uu;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?uu=Number(r[1]):null},Bn=(r,e)=>r!==-1?r:e,Bo=(r,e,t,n)=>r<=n&&t<=e,zs=function*(r){for(let e in r){let t=r[e];t!==void 0&&(yield{key:e,value:t})}};var Ns=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 Nm=(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("/")},Dn=(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 On=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}},gu=(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 Vs=r=>new Promise(e=>setTimeout(e,r));var yu=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 wu=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 ye=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)}};ye._level=hr.Info;ye._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.")}},Hs=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.")}},Vm=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 Hs)&&!wu(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},Hm=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}},Do=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"],Oo=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Vt=[...Oo,...ht],on=["webvtt"],Ws=[{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}],Wm=[{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}],qm=[{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}],jm=".01.01.01.01.00",Gm=".0.110.01.01.01.0",Km=(r,e,t,n)=>{if(r==="avc"){let s=Math.ceil(e/16)*Math.ceil(t/16),a=Ws.find(d=>s<=d.maxMacroblocks&&n<=d.maxBitrate)??Ne(Ws),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=Wm.find(u=>o<=u.maxPictureSize&&n<=u.maxBitrate)??Ne(Wm);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=qm.find(l=>s<=l.maxPictureSize&&n<=l.maxBitrate)??Ne(qm);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${r}'.`)};var $m=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=hu(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=hu(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(jm)&&(g=g.slice(0,-jm.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(Gm)&&(b=b.slice(0,-Gm.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)},Xm=(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 Ln=48e3,Qm=/^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=Qm.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":Qm.test(r)?r:r==="webvtt"?"webvtt":null,Ym=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},Zm=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},cS=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],lS=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,uS=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,dS=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,hS=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Jm=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(!cS.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(!lS.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(!uS.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(!dS.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")&&!hS.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/.')},fS=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],ep=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(!fS.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(", ")}).`)},tp=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 mS=[44100,48e3,32e3],pS=[-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],Lo=1483304551,Uo=1231971951,gS=(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,rp=(r,e,t,n)=>e===0?0:e===1?144*t/(n<<r):e===2?144*t/n:12*t/n*4,zo=(r,e)=>r===3?e===3?21:36:e===3?13:21,js=(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=pS[a*16*4+l*16+u];if(b===-1)return{header:null,bytesAdvanced:1};let k=b*1e3,T=mS[d]>>a+o,S=gS(a,l,k,T,h);if(e!==null&&e<S)return{header:null,bytesAdvanced:1};let A;return c===3?A=l===3?384:1152:l===3?A=384:l===2?A=1152:A=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:A},bytesAdvanced:1}};var No=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t},qs;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(qs||(qs={}));var cn=r=>r===3?1:2;var Un=[48e3,44100,32e3],bu=[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})},sp=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=Bs(n,t,!1):(w(e===4),i=n.getUint32(t,!1)),t+=e,yield{offset:t,length:i},t+=i}},xu=(r,e)=>{if(e.description){let i=(Ye(e.description)[4]&3)+1;return sp(r,i)}else return Di(r)},Oi=r=>r&31,Vo=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)},ku=new Uint8Array([0,0,0,1]),ap=r=>{let e=r.reduce((i,s)=>i+ku.byteLength+s.byteLength,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(ku,n),n+=ku.byteLength,t.set(i,n),n+=i.byteLength;return t},Ho=(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:Ds(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},op=(r,e)=>{if(e.description){let i=(Ye(e.description)[4]&3)+1;return Ho(r,i)}else return ap(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=Ks(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 ye._error("Error building AVC Decoder Configuration Record:",e),null}},cp=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)},lp=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 ye._error("Error deserializing AVC Decoder Configuration Record:",e),null}},up={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}},Ks=r=>{try{let e=new Ie(Vo(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 U=0;U<(a!==3?8:12);U++)if(e.readBits(1)){let xe=U<6?16:64,we=8,J=8;for(let Ae=0;Ae<xe;Ae++){if(J!==0){let Re=lr(e);J=(we+Re+256)%256}we=J===0?we:J}}}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 U=0;U<E;U++)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),U=Y(e),Q=Y(e),xe=Y(e),we,J;if((l===0?a:0)===0)we=1,J=2-y;else{let Re=a===3?1:2,et=a===1?2:1;we=Re,J=et*(2-y)}m-=we*(E+U),g-=J*(Q+xe)}let k=2,T=2,S=2,A=0,M={num:1,den:1},P=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 Pa=up[et];Pa&&(M=Pa)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),A=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&&np(e);let Ae=e.readBits(1);Ae&&np(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),_=Y(e))}if(P===null){w(_===null);let E=i&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&E)P=0,_=0;else{let U=d+1,Q=h+1,xe=(2-y)*Q,we=Ws.find(Ae=>Ae.level>=s)??Ne(Ws),J=Math.min(Math.floor(we.maxDpbMbs/(U*xe)),16);P=J,_=J}}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:S,transferCharacteristics:T,fullRangeFlag:A,numReorderFrames:P,maxDecFrameBuffering:_}}catch(e){return ye._error("Error parsing AVC SPS:",e),null}},np=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)},yS=(r,e)=>{if(e.description){let i=(Ye(e.description)[21]&3)+1;return Ho(r,i)}else return ap(r)},Gs=(r,e)=>{if(e.description){let i=(Ye(e.description)[21]&3)+1;return sp(r,i)}else return Di(r)},ln=r=>r>>1&63,Su=r=>{try{let e=new Ie(Vo(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}=wS(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 U=Y(e),Q=Y(e),xe=Y(e),we=Y(e),J=1,Ae=1,Re=d===0?u:0;Re===1?(J=2,Ae=2):Re===2&&(J=2,Ae=1),p-=(U+Q)*J,m-=(xe+we)*Ae}let g=Y(e),y=Y(e);Y(e);let k=e.readBits(1)?0:t,T=0;for(let U=k;U<=t;U++)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)&&bS(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(kS(e,S),e.readBits(1)){let U=Y(e);for(let Q=0;Q<U;Q++)Y(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let A=2,M=2,P=2,_=0,F=0,E={num:1,den:1};if(e.readBits(1)){let U=SS(e,t);E=U.pixelAspectRatio,A=U.colourPrimaries,M=U.transferCharacteristics,P=U.matrixCoefficients,_=U.fullRangeFlag,F=U.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:E,colourPrimaries:A,transferCharacteristics:M,matrixCoefficients:P,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 ye._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=Su(t[0]);if(!s)return null;let a=0;if(n.length>0){let l=n[0],u=new Ie(Vo(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 ye._error("Error building HEVC Decoder Configuration Record:",e),null}},wS=(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}},bS=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)}},kS=(r,e)=>{let t=[];for(let n=0;n<e;n++)t[n]=xS(r,n,e,t)},xS=(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},SS=(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=up[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)&&TS(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}},TS=(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&&ip(r,u,s),i&&ip(r,u,s)}},ip=(r,e,t)=>{for(let n=0;n<e;n++)Y(r),Y(r),t&&(Y(r),Y(r)),r.readBits(1)},dp=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 Gs(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 Gs(r,e))t.has(s.offset)||i.push(r.subarray(s.offset,s.offset+s.length));return yS(i,e)},Wo=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 A of Mr)if(y<=A.maxPictureSize){b=A.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}},fp=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 fp(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 A=n.readBits(1);A&&(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 _=n.readBits(5);if(P===0&&(o=_),_>7){let E=n.readBits(1);P===0&&(c=E)}if(A&&n.readBits(1)){let U=l+1;n.skipBits(U),n.skipBits(U),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 A=n.readBits(1),M=0;A?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},jo=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}},vS=[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],mp=r=>{let e=r[0]>>3;return{durationInSamples:vS[e]}},pp=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 xu(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&&(!Us()||zm()>=144)){let a=t.subarray(n.offset,n.offset+n.length),o=Vo(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 Gs(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 fp(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 $s=(r,e)=>{let t=ve(r),n=0,i=t.getUint32(n,!0);n+=4;let s=at.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=at.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=Ns(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=at.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 Xs=[2,1,2,3,3,4,4,5],Go=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}},gp=[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],yp=1536,U2=new Uint8Array([5,4,65,67,45,51]),z2=new Uint8Array([5,4,69,65,67,51]),Tu=[1,2,3,6],Ko=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=Tu[a],d;return i<3?d=Un[i]/1e3:d=bu[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}]}},wp=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}},$o=r=>{let e=r.substreams[0];return w(e),e.fscod<3?Un[e.fscod]:e.fscod2!==null&&e.fscod2<3?bu[e.fscod2]:null},Xo=r=>{let e=r.substreams[0];w(e);let t=Xs[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 ot=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 Qo=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},Yo=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)}},Zo=(r,e)=>r.systemId===e.systemId&&Nm(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,Jo=r=>Dr(r)/1073741824,ec=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),at.decode(ie(r,e))},bp=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 at.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),kp=new Uint32Array(10),xp=!1,AS=()=>{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++)kp[s]=i<<24,i=i<<1^(i&128?283:0);xp=!0},Qs=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),xp||AS();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^kp[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}},Sp=(r,e,t)=>{let n=!1,i=0,s=2**16,a=16,o=new Qs;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 tc=class r extends ot{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 Qo({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 nc(l),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){let l=c;c.trackBacking=new ic(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,A=Ne(a);A&&A.delta===S?A.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)vu(a,u.timestamp);else{let d=_e(c,s.moofOffset-1,h=>h.moofOffset);if(d!==-1){let h=c[d];vu(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 _p(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 nc(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let o=a;a.trackBacking=new ic(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),Jo(e),hn(e),hn(e),Jo(e),hn(e),hn(e),Jo(e)],d=Ai(Os(ES(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?Pp(e):Dr(e),p=hn(e);if(h!==0){if(c){ye._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=h;continue}if(p!==1){ye._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?ye._warn("Unknown encrypted video codec due to missing frma box."):ye._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=sc(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=Ln;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":(ye._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":(ye._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":(ye._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":(ye._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":(ye._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null):k===32?a.info.codec="pcm-f32be":k===64?a.info.codec="pcm-f64be":(ye._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),A=y&4?-1:0;m>0&&m<=64&&(T?m===32&&(a.info.codec=S?"pcm-f32be":"pcm-f32"):A&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&&ye._warn("Unsupported PCM format.")}else b===null?ye._warn("Unknown encrypted audio codec due to missing frma box."):ye._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}:ye._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:In[c],transfer:Mn[l],matrix:Fn[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),ec(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=ec(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":ye._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),f>e.filePos-p){let g=ce(e);w(g===5);let y=ec(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=Ys(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=Un[l]),a.info.numberOfChannels=Xs[u]+d}break;case"dec3":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio");let o=ie(e,n.contentSize),c=wp(o);if(!c){ye._warn("Invalid dec3 box contents, ignoring.");break}let l=$o(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=Xo(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&&(vu(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=Yo(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 A;f?A=K(e):(w(a.currentFragmentState.defaultSampleFlags!==null),A=a.currentFragmentState.defaultSampleFlags),k===0&&y!==null&&(A=y);let M=0;p&&(o===0?M=K(e):M=Dr(e));let P=!(A&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=vp(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&&ye._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=vp(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=at.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=at.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=bp(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}},rc=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=Au(i,n),a=await this.fetchPacketForSampleIndex(s,t);return!Tp(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!Tp(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=PS(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=CS(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 _p(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<u.length&&(s=await Ap(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 Ap(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}},nc=class extends rc{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&&Wo(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: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}},ic=class extends rc{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}},Au=(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 Au(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=Au(r,e),n=_e(r.keySampleIndices,t,i=>i);return r.keySampleIndices[n]??-1}},CS=(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}},PS=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=_e(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},vu=(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},ES=r=>{let[e,t]=r,n=Math.atan2(t,e);return Number.isFinite(n)?n*(180/Math.PI):0},Tp=r=>r.sampleSizes.length===0,vp=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},_p=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},Ap=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++)Zo(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&&Em.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:Im(u)})();r.demuxer.decryptionKeyCache.set(s,c),a=await c}return i.scheme==="cenc"||i.scheme==="cens"?IS(a,i,e,t):MS(a,i,e,t)},IS=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=Cp(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},MS=(r,e,t,n)=>{let i=new Qs;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=Cp(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},Cp=(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 FS=[z.EBML,z.Segment],Wi=[z.SeekHead,z.Info,z.Cluster,z.Tracks,z.Cues,z.Attachments,z.Chapters,z.Tags],Zs=[...FS,...Wi];var _u=8,Et=2,Zt=2*_u,Cu=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},Ep=(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 ac=r=>{let e=Cu(r);return e===null||r.remainingLength<e?null:Ce(r,e)},Pu=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=ac(r);if(e===null)return null;let t=Pu(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 at.decode(t.subarray(0,n))},oc=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Ip(r):sc(r)},cc=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}},Eu=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<_u)break;for(let c=0;c<o.length-_u;c++){o.filePos=a;let l=ac(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 Mp=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 lc;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(lc||(lc={}));var Js;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(Js||(Js={}));var Iu=[{id:z.SeekHead,flag:"seekHeadSeen"},{id:z.Info,flag:"infoSeen"},{id:z.Tracks,flag:"tracksSeen"},{id:z.Cues,flag:"cuesSeen"}],Fp=10*2**20,uc=class extends ot{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 Mp({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 cc(this.reader,a,Zs,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 Eu(this.reader,c,Wi,Math.min(this.currentSegment.elementEndPos??1/0,c+Fp));if(p){n=p;continue}else break}let{id:u,size:d}=l,h=o.filePos,f=Iu.findIndex(p=>p.id===u);if(f!==-1){let p=Iu[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=Iu.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 cc(this.reader,c,Zs,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,Zs);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=oc(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!==lc.Block||o.data.algorithm!==Js.HeaderStripping)&&(ye._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 Mu(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=Ln):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 Fu(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=Fn[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=Mn[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=In[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=-oc(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=oc(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=Ys(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=Ys(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 Hs(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=Ep(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:lc.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:Js.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 Js.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}}},dc=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 Eu(a.reader,b,Wi,Math.min(o.elementEndPos??1/0,b+Fp));if(P){g=P;continue}else break}let T=k.id,S=k.size,A=y.filePos;if(T===z.Cluster){c=await a.readCluster(b,o),S=c.elementEndPos-A;let{blockIndex:P,correctBlockFound:_}=t(c);if(_)return this.fetchPacketInCluster(c,P,s);P!==-1&&(l=c,u=P)}S===void 0&&(w(T!==z.Cluster),S=(await cc(a.reader,A,Zs,o.elementEndPos)).pos-A);let M=A+S;if(o.elementEndPos===null){let P=a.reader.requestSliceRange(M,Et,Zt);if(P instanceof Promise&&(P=await P),!P)break;if(ac(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}},Mu=class extends dc{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?Wo(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}},Fu=class extends dc{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 ea=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=js(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 hc=class extends ot{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 Ru(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 ea(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=zo(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===Lo||o===Uo){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&qs.FrameCount?d.getUint32(4,!1):null,fileSize:h&qs.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>=ta){let i=this.reader.requestSlice(this.reader.fileSize-ta,ta);i instanceof Promise&&(i=await i),w(i),We(i,3)==="TAG"&&Rp(i,this.metadataTags)}return this.metadataTags}finally{e()}}},Ru=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=rp(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 Bu=1399285583,RS=79764919,Bp=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^RS:e<<1;Bp[r]=e>>>0&4294967295}var Dp=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^Bp[n>>>24^s])>>>0}return e.setUint32(22,t,!0),n},Op=(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<<Dm(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=mp(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:i}},Lp=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var pn=27,Nn=282,Up=Nn+65025,Gi=r=>{let e=r.filePos;if(zn(r)!==Bu)return null;r.skip(1);let n=ce(r),i=Np(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}},zp=(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===Bu)return!0;r.skip(1)}}return!1};var fc=class extends ot{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,Nn);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 Du(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:pp(s.data).modeBlockflags},$s(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=jo(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=Ln,t.codecInfo.opusInfo={preSkip:s.preSkip},$s(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,Nn);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,Nn);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 Lp({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Du=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"?Ln: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}=Op(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+Up,a-pn),A=this.demuxer.reader.requestSlice(T,S-T);if(A instanceof Promise&&(A=await A),w(A),!zp(A,S)){a=k+pn;continue e}let P=this.demuxer.reader.requestSliceRange(A.filePos,pn,Nn);P instanceof Promise&&(P=await P),w(P);let _=Gi(P);w(_);let F=!1;if(_.serialNumber===this.bitstream.serialNumber)F=!0;else{let U=this.demuxer.reader.requestSlice(_.headerStartPos,_.totalSize);U instanceof Promise&&(U=await U),w(U);let Q=ie(U,_.totalSize);F=Dp(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,pn,Nn);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=Hp(u,l,d);w(T);let S=Vp(u,T.page,T.segmentIndex);S&&(l=S.page,d=S.segmentIndex)}else for(;;){let T=Hp(u,l,d);if(!T)break;let S=Vp(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 A=this.encodedPacketToMetadata.get(S);if(w(A),!f&&b.endPage.headerStartPos===p.headerStartPos&&b.endSegmentIndex===m?(h=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,S=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h-A.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),w(S),A=this.encodedPacketToMetadata.get(S),w(A)):h+=A.durationInSamples,g=S,y=A,f&&(Math.max(h,0)>n||Math.max(A.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)}},Vp=(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=mu(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}},Hp=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let n=mu(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 mc=class extends ot{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=Lu(g,n);l=Lu(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 Ou(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,Ou=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 Vn=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 ra=1024,pc=class extends ot{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 Uu(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,Vn,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=ra/n,s={timestamp:this.nextTimestampInSamples/n,duration:i,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=ra,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()}}},Uu=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ra}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 Wp=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,qp=(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}},jp=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)},Gp=(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)},Kp=(r,e)=>e==="uncommon-u16"?Ke(r):e==="uncommon-u16-10"?Ke(r)*10:e==="uncommon-u8"?ce(r):typeof e=="number"?e:null,$p=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 gc=class extends ot{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 zu(this);break}case un.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,i);o instanceof Promise&&(o=await o),w(o),$s(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=at.decode(ie(o,l)),d=K(o),h=at.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=Wp(s.readBits(4));if(!o)return null;w(this.audioInfo);let c=qp(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let u=jp(e),d=Gp(e,o),h=Kp(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=$p(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}}},zu=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 Xp=r=>{let e="video/MP2T",t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};var Yp="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.",Qp=new Set,yc=class extends ot{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 A=m.readBits(10),M=m.pos+8*A,P=!1,_=!1;for(;m.pos<M;){let E=m.readBits(8),U=m.readBits(8);E===106?P=!0:(E===122||E===204)&&(_=!0),m.skipBits(8*U)}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}:P&&(F={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:Qp.has(T)||(ye._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),Qp.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 Wn(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=Ks(k);m.info.width=T.displayWidth,m.info.height=T.displayHeight;let S=T.pixelAspectRatio.num,A=T.pixelAspectRatio.den;S>0&&A>0&&(S>A?(m.info.squarePixelWidth=Math.round(m.info.width*S/A),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*A/S))),m.info.colorSpace={primaries:In[T.colourPrimaries],transfer:Mn[T.transferCharacteristics],matrix:Fn[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(A=>A.nalUnitType===it.SPS_NUT).nalUnits[0];w(T);let S=Su(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:In[S.colourPrimaries],transfer:Mn[S.transferCharacteristics],matrix:Fn[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=js(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=Go(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=Xs[b.acmod]+b.lfeon,m.info.sampleRate=Un[b.fscod]}else if(m.info.codec==="eac3"){let b=Ko(y.suppliedPacket.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let k=$o(b);if(k===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Xo(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 Nu(l)):this.trackBackingEntries.push(new Vu(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 Xp(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)}}},Hn=(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(Yp);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},Xi=(r,e)=>{w(r.endPos!==null);let t=Hn(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}},wc=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 Wn(this.elementaryStream,n),s=new na(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 Wn(this.elementaryStream,o);n=new na(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,A)=>{let M=T;for(;M<S;){let P=await s.readPacketHeader(M);if(!P)return null;if(P.pid===c&&P.payloadUnitStartIndicator===1){let _=await s.readSection(M,A);if(!_)return null;let F=Hn(_,!1);if(F&&F.pts!==null)return{pesPacketHeader:F,section:_}}M+=s.packetStride}return null},u=this.elementaryStream.firstSection;w(u);let d=Hn(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 A=0,M=S-1;for(T=A;A<=M;){let P=Math.floor((A+M)/2),_=Ro(P*o,s.packetStride)+d.sectionStartPos,F=_+o,E=await l(_,F,!1);if(!E){M=P-1;continue}E.pesPacketHeader.pts<=i?(T=P,A=P+1):M=P-1}}}h=Ro(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 A=await s.readSection(T,!0);w(A);let M=Xi(A,!0);w(M);let P=new Wn(this.elementaryStream,M),_=new na(this,P);for(;!((Ne(_.presentationOrderPackets)?.pts??-1/0)>=i||!await _.readNextPacket()););let F=Ci(_.presentationOrderPackets,S);if(F===-1)return null;let E=_.presentationOrderPackets[F],U=F===0?0:E.pts-_.presentationOrderPackets[F-1].pts;for(;_.decodeOrderPackets[0]!==E;)_.decodeOrderPackets.shift();_.lastDuration=U;let Q=await _.readNext();w(Q);let xe=this.createEncodedPacket(Q.packet,Q.duration,n);return this.packetBuffers.set(xe,_),this.packetSectionStarts.set(xe,Q.packet.sectionStartPos),xe};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 A=await s.readSection(T,!1);if(A){let M=Hn(A,!1);if(M&&M.pts!==null){if(M.pts>i)break e;y=M,Hu(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 A=await s.readPacketHeader(S);if(!A)break e;if(A.pid===c&&A.payloadUnitStartIndicator===1){let M=await s.readSection(S,!1);if(M){let P=Hn(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,A=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let M=null,P=T<=d.sectionStartPos,_,F=null;if(P)_=d,F=u;else{let Q=await l(T,a.fileSize??1/0,A);_=Q?.pesPacketHeader??null,F=Q?.section??null}let E=!1,U=0;e:for(;_&&!(S!==null&&_.sectionStartPos>=S);){if(_.pts<=i){let xe;if(this.elementaryStream.canBeTrustedWithKeyPackets)xe=_.randomAccessIndicator===1;else{w(F);let we=Xi(F,!0);w(we);let J=new Wn(this.elementaryStream,we);await J.markNextPacket(),xe=J.suppliedPacket?.randomAccessIndicator===1}xe&&(M=_)}if(_.pts>i&&(E=!0),E&&(U++,U>b))break;let Q=_.sectionStartPos+s.packetStride;for(;;){let xe=await s.readPacketHeader(Q);if(!xe)break e;if(xe.pid===c&&xe.payloadUnitStartIndicator===1){let we=await s.readSection(Q,A);if(we){let J=Hn(we,!1);if(J&&J.pts!==null){_=J,F=we,Hu(this.elementaryStream,_);break}}}Q+=s.packetStride}}if(M){let Q=M;if(U===0)e:for(let we=0;we<b;we++){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,A);if(Re){let et=Hn(Re,!1);if(et&&et.pts!==null){Q=et;break}}}J-=s.packetStride}}let xe=await k(Q.sectionStartPos,we=>we.pts<=i&&we.randomAccessIndicator===1);return w(xe),xe}if(P)return null;S=T,T=Math.max(Ro(T-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},Nu=class extends wc{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}},Vu=class extends wc{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}},Hu=(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},Wn=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,A=6;if(S+(t==="avc"?A:1)>d){this.seekTo(p);break}let P=u[T],_,F,E;if(t==="avc")_=Oi(P),F=_===lt.NON_IDR_SLICE||_===lt.SLICE_DPA||_===lt.IDR,E=_===lt.SEI||_===lt.SPS||_===lt.PPS||_===lt.AUD;else{if(_=ln(P),((P&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 U=!1;if(F){let Q;if(t==="avc"){let xe=u.subarray(S,S+A),we=Y(new Ie(xe));Q=!a||we<=o,o=we}else Q=u[S]>>7===1;Q&&(a?U=!0:a=!0)}else E&&a&&(U=!0);if(U){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(ra*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=js(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=gp[3*d+u];w(h!==void 0),this.seekTo(o),c=this.ensureBuffered(h),c instanceof Promise&&(c=await c);let f=Math.round(yp*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=Tu[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(Yp);i=n.pts,Hu(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}},na=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 bc="application/vnd.apple.mpegurl",Wu="#EXT-X-STREAM-INF:",qu="#EXT-X-I-FRAME-STREAM-INF:",ju="#EXT-X-MEDIA:",ia="#EXTINF:",Gu="#EXT-X-MAP:",Ku="#EXT-X-KEY:",$u="#EXT-X-MEDIA-SEQUENCE:",Xu="#EXT-X-BYTERANGE:",Qu="#EXT-X-PROGRAM-DATE-TIME:",Zp="#EXT-X-DISCONTINUITY",Yu="#EXT-X-TARGETDURATION:",Jp="#EXT-X-ENDLIST",Zu="#EXT-X-PLAYLIST-TYPE:",eg="#EXT-X-I-FRAMES-ONLY",kc=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 xc=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=Dn(e,i=>i.getType()==="video")+1;e.push(new Tc(this,t,n))}else if(t.type==="audio"){let n=Dn(e,i=>i.getType()==="audio")+1;e.push(new vc(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=Dn(e,a=>a.getType()==="video")+1;e.push(new Tc(this,{id:e.length+1,type:"video"},s))}else if(i.type==="audio"){let s=Dn(e,a=>a.getType()==="audio")+1;e.push(new vc(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}},Sc=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:Rn(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}},Tc=class extends Sc{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())}},vc=class extends Sc{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 Ju=0,ed=1/0,BS=null;typeof FinalizationRegistry<"u"&&(BS=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,Ju,ed),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 _c(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new qn(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},qn=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 qn))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)}},td=(r,e)=>r.path===e.path,sa=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())}},aa=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(){}},oa=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 Ac({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:rg.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()}},DS=.5*2**20,OS=((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 ye._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)}),tg=new Set,ca=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??OS,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){let a={...Fo(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=US(i);a&&(this._offset=a.offset,this._length=a.length)}let s=2;this._orchestrator=new Ac({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:rg.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 Lm(this._options.fetchFn??fetch,this._url,Om(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"))&&(tg.has(s.origin)||(ye._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.`),tg.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){ye._error("Error while reading response stream. Attempting to resume.",c),await Vs(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()}},LS=/^bytes=(\d+)-(\d*)$/,US=r=>{let e=LS.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 la=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()}},rg={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(Bo(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+DS),{start:r,end:e}}},Ac=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 A=this.cache[S];if(A.start>=o)break;if(A.end<=a)continue;let M=Math.max(a,A.start),P=Math.min(o,A.end);if(w(M<=P),p<M&&m.push({start:p,end:M}),p=P,h){let _=Math.max(e,A.start),F=Math.min(t,A.end);if(_<F){let E=_-e;h.set(A.bytes.subarray(_-A.start,F-A.start),E),E===f&&(f=F-e)}}A.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 A=Math.max(e,S.start),M=Math.min(t,S.end);A===S.start&&M===S.end?k.push(S):A<M&&k.push({start:A,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 A=S.end<o||this.fileSize!==null,M=this.createWorker(S.start,S.end,A);if(M)T&&(M.pendingSlices=[T]),this.runWorker(M);else{let P=_e(this.queuedReads,S.start,F=>F.hole.start),_=P!==-1?this.queuedReads[P]:null;for(_&&S.start<=_.hole.end?(_.hole.end=Math.max(_.hole.end,S.end),_.strictTarget&&=A,T&&_.pendingSlices.push(T)):(P++,_={hole:{start:S.start,end:S.end},strictTarget:A,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(P,0,_));P+1<this.queuedReads.length;){let F=this.queuedReads[P+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(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(Bo(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||Bo(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 _c=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 ng=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},ig=(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}),zS=/^0[xX][0-9a-fA-F]+$/,NS=/^data:.*;base64,/i,ua=class extends xc{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 Vs(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=ng(k,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),A=await new gn(T.source).requestEntireFile();w(A),e=Cc(A,A.length,{ignore:kc}),T.source instanceof Ot&&(this.rootPath=T.source.rootPath)}catch(T){k.error=T,k.hasError=!0}finally{ig(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 A=null;if(T!==-1&&(A=Number(k.slice(T+1)),!Number.isInteger(A)||A<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${k}'.`);return{length:S,offset:A}},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 _=new Uint8Array(Qt),F=ve(_);F.setUint32(8,Math.floor(c/2**32)),F.setUint32(12,c),S={...S,iv:_}}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(ia)){if(g){m=!0;continue}m||(f===null&&c>0&&p!==null&&(i=c*p),m=!0);let S=T.slice(ia.length),A=S.indexOf(","),M=A===-1?S:S.slice(0,A),P=Number(M);if(!Number.isFinite(P)||P<0)throw new Error(`Invalid #EXTINF tag duration '${M}'.`);a=P}else if(T.startsWith(Gu)){let S=new Wr(T.slice(Gu.length)),A=S.get("uri");if(!A)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,A),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(Ku)){let S=new Wr(T.slice(Ku.length)),A=S.get("method");if(A==="NONE")o=null;else if(A==="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,_=S.get("iv");if(_){if(!zS.test(_))throw new Error(`Unsupported IV format '${_}'.`);let E=_.slice(2);E=E.padStart(Qt*2,"0"),P=new Uint8Array(Qt);for(let U=0;U<Qt;U++){let Q=-Qt*2+U;P[U]=parseInt(E.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(A==="SAMPLE-AES"||A==="SAMPLE-AES-CTR"){let M=S.get("uri");if(!M)throw new Error(`Invalid #EXT-X-KEY: ${A} 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 _=null;if(NS.test(M)){let F=M.indexOf(","),E=Ns(M.slice(F+1));if(E.length>=8&&E[4]===112&&E[5]===115&&E[6]===115&&E[7]===104){let U=ve(E).getUint32(0);_=Yo(E.subarray(8,Math.min(U,E.length)))}}o={method:A,psshBox:_}}else throw new Error(`Unsupported encryption method '${A}'. If you think this method should be supported, please raise an issue.`)}else if(T.startsWith($u)){let S=T.slice($u.length),A=Number(S);if(!Number.isInteger(A)||A<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${S}'.`);b(A)}else if(T.startsWith(Xu)){let S=y(T.slice(Xu.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(Qu)){if(g)continue;let S=T.slice(Qu.length),A=Date.parse(S);if(!Number.isFinite(A))continue;let M=A/1e3;if(f===M)continue;if(f===null&&this.segments.length>0){let P=Ne(this.segments),_=P.timestamp+P.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===Zp)l=null;else if(T.startsWith(Yu)){let S=T.slice(Yu.length),A=Number(S);if(!Number.isFinite(A)||A<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${S}'.`);this.refreshInterval=A,p=A}else if(T===Jp){this.streamHasEnded=!0;break}else T.startsWith(Zu)&&T.slice(Zu.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=>Zo(d,u))&&(l=[...l,u]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:l})})}},a=new qr({source:new sa(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=Sp(p,async()=>{let g={stack:[],error:void 0,hasError:!1};try{let y=ng(g,await this.input._getSourceCached({path:h.keyUri,isRoot:!1},sg),!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{ig(g)}},()=>{f.free()});u=new la(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 Ec=class extends ot{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=Cc(e,e.length,{ignore:kc}),{rootPath:n}=this.input._rootSource,i=[],s=[];for(let d=1;d<t.length;d++){let h=t[d];if(h.startsWith(Wu)){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(Wu.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(ju)){let f=new Wr(h.slice(ju.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!==eg){if(h.startsWith(ia)){let f=new ua(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 U=>({track:U,codec:await U.getCodec()})));m=await Promise.all(E.filter(U=>U.codec!==null).map(U=>U.track.getDecoderConfig().then(Q=>Q.codec)))}let g=d.attributes.get("video"),y=d.attributes.get("audio"),b=m.some(_=>gt.includes(Fr(_))),k=m.some(_=>Vt.includes(Fr(_)));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"),U=F.attributes.get("type");return E===g&&U.toLowerCase()==="video"});e:if(_){let F=_.attributes.get("uri");if(F===null)break e;let E=dr(n,F),xe=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(J=>J.getType()==="video");if(!xe||await xe.getCodec()===null)break e;let we=await xe.getDecoderConfig().then(J=>J?.codec??null);w(we!==null),m.push(we)}}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"),U=F.attributes.get("type");return E===y&&U.toLowerCase()==="audio"});e:if(_){let F=_.attributes.get("uri");if(F===null)break e;let E=dr(n,F),xe=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(J=>J.getType()==="audio");if(!xe||await xe.getCodec()===null)break e;let we=await xe.getDecoderConfig().then(J=>J?.codec??null);w(we!==null),m.push(we)}}m=[...new Set(m)];let T=null,S=null,A=d.attributes.getAsNumber("bandwidth");w(A!==null);let M=d.attributes.getAsNumber("average-bandwidth"),P=d.attributes.get("name");for(let _ of m){let F=Fr(_);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 U=d.attributes.get("resolution"),Q=null,xe=null;if(U){let we=U.match(/^(\d+)x(\d+)$/);we&&(Q=Number(we[1]),xe=Number(we[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:A,averageBitrate:M,name:P,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:Q,height:xe}})}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 U of s){let Q=U.attributes.get("group-id"),xe=U.attributes.get("type");if(Q!==E||xe.toLowerCase()!=="video")continue;let we=U.attributes.get("resolution")??d.attributes.get("resolution"),J=null,Ae=null;if(we){let Re=we.match(/^(\d+)x(\d+)$/);Re&&(J=Number(Re[1]),Ae=Number(Re[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:Pc(U.attributes),autoselect:Pc(U.attributes)||ag(U.attributes),languageCode:og(U.attributes.get("language")),lineNumber:U.lineNumber,fullPath:U.fullPath??d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:U.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=_;let E=d.attributes.get("audio");if(E===null){let U=d.attributes.get("channels"),Q=U!==null?Number(U.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:A,averageBitrate:M,name:P,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 U of s){let Q=U.attributes.get("group-id"),xe=U.attributes.get("type");if(Q!==E||xe.toLowerCase()!=="audio")continue;let we=U.attributes.get("channels")??d.attributes.get("channels"),J=we!==null?Number(we.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:Pc(U.attributes),autoselect:Pc(U.attributes)||ag(U.attributes),languageCode:og(U.attributes.get("language")),lineNumber:U.lineNumber,fullPath:U.fullPath??d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:U.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 Mc(d)):this.trackBackings.push(new Fc(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 ua(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return bc}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Ic=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 Mc){for(let s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}else{w(this instanceof Fc);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)}},Mc=class extends Ic{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()}},Fc=class extends Ic{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()}},Pc=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}".`)},ag=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}".`)},og=r=>{if(r===null)return Ge;let e=r.split("-")[0];return e||Ge};var Mt=class{constructor(){this._isIsobmff=!1}},da=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 tc(e)}},Rc=class extends da{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"}},Bc=class extends da{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},ha=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=Cu(n);if(i===null||i<1||i>8||Ce(n,i)!==z.EBML)return!1;let a=Pu(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 uc(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Dc=class extends ha{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Oc=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 ea(e._reader,t,t+4096);if(!n)return!1;let i=n.header,s=zo(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===Lo||o===Uo)return!0;t=n.startPos+n.header.totalSize;let l=await ea(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 hc(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Lc=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 mc(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Uc=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 fc(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},zc=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 gc(e)}},Nc=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,Vn,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,Vn,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 pc(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Vc=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 yc(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 Ec(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return bc}},Hc=new Rc,cg=new Bc,lg=new ha,ug=new Dc,dg=new Oc,hg=new Lc,fg=new Uc,mg=new Nc,pg=new zc,gg=new Vc,yg=new Qi,rd=[yg,Hc,cg,lg,ug,hg,fg,pg,dg,mg,gg];var wg=(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 VS=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},HS=(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 bg=-1/0,kg=-1/0,ya=null;typeof FinalizationRegistry<"u"&&(ya=new FinalizationRegistry(r=>{let e=performance.now();r.type==="video"?(e-bg>=1e3&&(ye._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."),bg=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-kg>=1e3&&(ye._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."),kg=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var jr=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},nd=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],WS=new Set(nd),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||!WS.has(t.format))throw new TypeError("init.format must be one of: "+nd.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&&gu(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??GS(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 ga(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&&gu(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 ga(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:Ls(),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 ga({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&&!nd.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=On({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),ya?.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}):ma(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||(ya?.unregister(this),this._data instanceof jr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ma(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Sg(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 ma(this._data)?this._data.allocationSize(e):Tg(this,e).allocationSize}async copyTo(e,t={}){if(!_i(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Sg(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),ma(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=VS(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{HS(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=Tg(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 ma(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&&wa(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=id(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&&wa(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=id(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=Os(l,e.roundDimensionsTo??1),u=Os(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 qS){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 fa)if(m.canvas.width===d.width&&m.canvas.height===d.height){h=m.canvas,m.age=xg++;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,fa.length>=jS&&fa.splice(Mi(fa,m=>m.age),1),fa.push({canvas:h,age:xg++})}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()}},qS=[];var jS=3,fa=[],xg=0,ga=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}}},ma=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,id=(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}},wa=(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.")},Sg=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.")}},GS=(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)}},Tg=(r,e)=>{let t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},n=e.rect,i=KS(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 XS(i,a,s)},KS=(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(!$S(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},$S=(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},XS=(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}},Wc=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,pa(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(),!Wc.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(!Wc.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}ya?.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&&!Wc.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=Gn(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&&!Wc.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=Gn(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=Ag(c);if(pa(this._data))sn()&&u>2&&c!==o?QS(this._data,y,o,c,u,a,d,h):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:h,format:c});else{let k=vg(o),T=yn(o),S=Gn(o),A;if(this._data instanceof jn){let P=_=>{let F=this._data.getDataPlane(_);if(!(F instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let E=l*T*(S?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(S)if(p)A=P(a),a=0;else{A=new Uint8Array(l*T*u);for(let _=0;_<u;_++){let F=P(_);A.set(F,_*l*T)}}else A=P(0)}else A=this._data;let M=ve(A);for(let P=0;P<h;P++)if(p){let _=P*f,F;S?F=(a*l+(P+d))*T:F=((P+d)*u+a)*T;let E=k(M,F);b(y,_,E)}else for(let _=0;_<u;_++){let E=(P*u+_)*f,U;S?U=(_*l+(P+d))*T:U=((P+d)*u+_)*T;let Q=k(M,U);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(pa(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(Gn(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||(ya?.unregister(this),this._data instanceof jn?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):pa(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():pa(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(Gn(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")}},Gn=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},vg=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)}},Ag=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)}},pa=r=>typeof AudioData<"u"&&r instanceof AudioData,_g=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}},QS=(r,e,t,n,i,s,a,o)=>{let c=vg(t),l=Ag(n),u=yn(t),d=yn(n),h=Gn(t);if(Gn(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)}}},Cg=(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 Pg=new Map;var Eg=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&&wa(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.");Ig(r.codec,r)},Ig=(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.")},sd=r=>{let e=r.bitrate instanceof Lt?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??Km(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,...Ym(r.codec)}},Mg=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.");YS(r.codec,r)},YS=(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}).`)},Fg=r=>{let e=r.bitrate instanceof Lt?r.bitrate._toAudioBitrate(r.codec):r.bitrate;return{codec:r.fullCodecString??Xm(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:e,bitrateMode:r.bitrateMode,...Zm(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}},Rg=new Lt(.3),Bg=new Lt(.6),Dg=new Lt(1),Og=new Lt(2),Lg=new Lt(4);var ad=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.");Ig(r,s);let a=sd({codec:r,width:t,height:n,bitrate:i,framerate:void 0,...s,alpha:"discard"}),o=JSON.stringify(a),c=Pg.get(o);if(c)return c;let l=(async()=>jc.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:Ls()?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 Pg.set(o,l),l};var Gc=[],cd=[],jc=[],od=[];var Ug=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 zg=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 Kn=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.")},ld=(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(Kn(e),this._track.input._disposed)throw new ut;return ld(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Kn(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),Kn(t),this._track.input._disposed)throw new ut;return ld(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(Kn(t),this._track.input._disposed)throw new ut;return ld(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Yi(e),Kn(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(Kn(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(Kn(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}}}},ud=class{constructor(e,t){this.onSample=e,this.onError=t}},Kc=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=Ng(i.length);if(i.length+b.getDecodeQueueSize()>P){({promise:l,resolve:u}=nt()),await l;continue}b.decode(S);let _=await M.next();if(_.done)break;S=_.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){Rm(e);let n=Fm(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 _=0;for(;i.length>0&&P.timestamp-i[0]>-1e-10;)_++,i.shift();if(_>0)for(let F=0;F<_;F++)f(F<_-1?P.clone():P);else P.close()},P=>{h||(h=P,o())}),b=this._createPacketSink(),k=null,T=null,S=-1,A=async()=>{w(T);let P=T;for(y.decode(P);P.sequenceNumber<S;){let _=Ng(s.length);for(;s.length+y.getDecodeQueueSize()>_&&!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 _=await b.getPacket(P,p),F=_&&await b.getKeyPacket(P,p);if(!F){S!==-1&&(await A(),await M()),f(null),k=null;continue}k&&(F.sequenceNumber!==T.sequenceNumber||_.timestamp<k.timestamp)&&(await A(),await M()),i.push(_.timestamp),S=Math.max(_.sequenceNumber,S),k=_,T=F}!d&&!this._track.input._disposed&&(S!==-1&&await A(),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}}}},Ng=r=>r===0?40:8,dd=class extends ud{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=Gc.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&&Us()){let u=lp(Ye(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){let d=Ks(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()||fu(this.inputTimestamps,e.timestamp,t=>t),Us()&&this.currentPacketIndex===0){if(this.codec==="avc"){let t=[];for(let i of xu(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=op(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 $c),!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 Gs(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}fu(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}},Vg=!1,$c=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&&!Vg)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,Vg=!0,ye._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
|
|
2016
|
+
in vec2 a_position;
|
|
2017
|
+
in vec2 a_texCoord;
|
|
2018
|
+
out vec2 v_texCoord;
|
|
2019
|
+
|
|
2020
|
+
void main() {
|
|
2021
|
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
2022
|
+
v_texCoord = a_texCoord;
|
|
2023
|
+
}
|
|
2024
|
+
`),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
2025
|
+
precision highp float;
|
|
2026
|
+
|
|
2027
|
+
uniform sampler2D u_colorTexture;
|
|
2028
|
+
uniform sampler2D u_alphaTexture;
|
|
2029
|
+
in vec2 v_texCoord;
|
|
2030
|
+
out vec4 fragColor;
|
|
2031
|
+
|
|
2032
|
+
void main() {
|
|
2033
|
+
vec3 color = texture(u_colorTexture, v_texCoord).rgb;
|
|
2034
|
+
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
2035
|
+
fragColor = vec4(color, alpha);
|
|
2036
|
+
}
|
|
2037
|
+
`),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([`(${ZS.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()}};$c.forceCpu=!0;var ZS=()=>{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,A=b*m,M=T+2*S+A,P=new Uint8Array(M);await c.copyTo(P);let _=await o(l,u,d,m),F=T+2*S;P.set(_,F);let U={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,U)},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 A={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,A)},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)}},JS=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.")},ba=class extends Kc{constructor(e,t={}){if(!(e instanceof $n))throw new TypeError("videoTrack must be an InputVideoTrack.");JS(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 dd(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 $n}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 Rn(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&&=hd(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&&=hd(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=hd(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},hd=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},$n=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??=On({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=On({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),Gc.some(i=>i.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return ye._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),cd.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return ye._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 fd=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}),Xc=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 eT=1,sg=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 qn))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&&wg(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=eT){let n=this._sourceCache.find(a=>a.cacheGroup===t&&td(a.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let i=this._sourceCachePromises.find(a=>a.cacheGroup===t&&td(a.request,e));if(i)return i.promise.then(a=>a.sourceRef.source.ref());let s=(async()=>{let a=await this._getSourceUncached(e);if(Dn(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(),Mm(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 ka})()}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 ka)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 Xc(n,e)}async getVideoTracks(e){e&&=ts(e);let n=(await this.getTracks()).filter(i=>i.isVideoTrack());return Xc(n,e)}async getAudioTracks(e){e&&=ts(e);let n=(await this.getTracks()).filter(i=>i.isAudioTrack());return Xc(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()),fd(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),fd(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 $n(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()}},ka=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,Ju,ed);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=Bs(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},Ys=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},zn=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},Lu=(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},Pp=r=>{let e=Dr(r),t=K(r);return e*4294967296+t},Np=r=>{let e=zn(r);return tT(r)*4294967296+e},Ip=r=>{Ft(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},sc=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},Cc=(r,e,t)=>at.decode(ie(r,e)).split(`
|
|
2038
|
+
`).map(s=>s.trim()).filter(s=>s.length>0&&!t?.ignore?.(s));var Xn;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Xn||(Xn={}));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 ta=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"],Rp=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=ie(r,ta-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=Bn(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=No(a);return s&Xn.Footer&&(o+=mt),{majorVersion:n,revision:i,flags:s,size:o}},mn=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){ye._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=e.flags&Xn.Footer?e.size-mt:e.size,i=ie(r,n),s=new md(e,i);if(e.flags&Xn.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Xn.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&Xn.Unsynchronisation)),l){ye._warn(`Skipping encrypted ID3v2 frame ${a.id}`),s.pos=c;continue}if(u){ye._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}},md=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?No(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:No(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=Bn(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=Bn(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=Bn(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),at.decode(i.subarray(0,s))}case ns.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),a=Bn(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=Bn(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),at.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var Qc=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 pd=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var Hg=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 Qn=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]]),bd=r=>(qt.setInt16(0,r,!1),[Pe[0],Pe[1]]),jg=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]]),rT=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]]),Gg=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]]),gd=r=>(qt.setInt32(0,2**30*r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),yd=(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},Kg=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]},$g=Kg(0),Xg=r=>[ir(r[0]),ir(r[1]),gd(r[2]),ir(r[3]),ir(r[4]),gd(r[5]),ir(r[6]),ir(r[7]),gd(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),jg(t),n??[]],i),Qg=r=>r.isQuickTime?be("ftyp",[je("qt "),j(512),je("qt ")]):r.fragmented?r.cmaf?be("ftyp",[je("iso5"),j(512),je("iso5"),je("iso6"),je("mp41"),je("cmfc"),je("dash")]):be("ftyp",[je("iso5"),j(512),je("iso5"),je("iso6"),je("mp41")]):be("ftyp",[je("isom"),j(512),je("isom"),r.holdsAvc?je("avc1"):[],je("mp41")]),kd=()=>be("styp",[je("iso5"),j(0),je("iso5"),je("iso6"),je("mp41"),je("cmfc"),je("dash")]),xd=(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)])},xa=r=>({type:"mdat",largeSize:r}),Yg=r=>({type:"free",size:r}),ss=r=>be("moov",void 0,[nT(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>iT(e,r.creationTime)),r.isFragmented?WT(r.trackDatas):null,ZT(r)]),nT=(r,e)=>{let t=Math.max(0,...e.map(a=>$e(Yc(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),Gg(1),Array(10).fill(0),Xg($g),Array(24).fill(0),j(n)])},Yc=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},iT=(r,e)=>{let t=a0(r),n=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return be("trak",void 0,[sT(r,e),n?aT(r,r.startTimestampOffset):null,oT(r,e),t.name!==void 0?be("udta",void 0,[be("name",[..._t.encode(t.name)])]):null])},sT=(r,e)=>{let t=$e(Yc(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=Kg(o??0)}else s=$g;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),Gg(r.type==="audio"?1:0),Se(0),Xg(s),ir(r.type==="video"?r.info.width:0),ir(r.type==="video"?r.info.height:0)])},aT=(r,e)=>{let t=$e(e,Wt),n=$e(Yc(r),Wt),i=!Ar(t)||!Ar(n),s=i?yr:j,a=i?rT:Gr;return be("edts",void 0,[Ve("elst",i?1:0,0,[j(2),s(t),a(-1),ir(1),s(n),a(0),ir(1)])])},oT=(r,e)=>be("mdia",void 0,[cT(r,e),Sd(!0,lT[r.type],uT[r.type]),dT(r)]),cT=(r,e)=>{let t=$e(Yc(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(s0(r.track.metadata.languageCode??Ge)),Se(0)])},lT={video:"vide",audio:"soun",subtitle:"text"},uT={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Sd=(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)]),dT=r=>be("minf",void 0,[pT[r.type](),gT(),bT(r)]),hT=()=>Ve("vmhd",0,1,[Se(0),Se(0),Se(0),Se(0)]),fT=()=>Ve("smhd",0,0,[Se(0),Se(0)]),mT=()=>Ve("nmhd",0,0),pT={video:hT,audio:fT,subtitle:mT},gT=()=>be("dinf",void 0,[yT()]),yT=()=>Ve("dref",0,0,[j(1)],[wT()]),wT=()=>Ve("url ",0,1),bT=r=>{let e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return be("stbl",void 0,[kT(r),OT(r),e?VT(r):null,e?HT(r):null,UT(r),zT(r),NT(r),LT(r)])},kT=r=>{let e;if(r.type==="video")e=xT(rv(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){let t=i0(r.track.source._codec,r.muxer.isQuickTime);w(t),e=CT(t,r)}else r.type==="subtitle"&&(e=BT(sv[r.track.source._codec],r));return w(e),Ve("stsd",0,0,[j(1)],[e])},xT=(r,e)=>be(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),bd(65535)],[nv[e.track.source._codec](e),ST(e),Pm(e.info.decoderConfig.colorSpace)?TT(e):null]),ST=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:be("pasp",[j(r.info.pixelAspectRatio.num),j(r.info.pixelAspectRatio.den)]),TT=r=>be("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)]),vT=r=>r.info.decoderConfig&&be("avcC",[...Ye(r.info.decoderConfig.description)]),AT=r=>r.info.decoderConfig&&be("hvcC",[...Ye(r.info.decoderConfig.description)]),Wg=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=>be("av1C",$m(r.info.decoderConfig.codec)),CT=(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)),bd(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 be(r,n,[iv(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},wd=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),...jg(0),...j(0),...j(0)];if(r.info.decoderConfig.description){let n=Ye(r.info.decoderConfig.description);t=[...t,...Je(5),...yd(n.byteLength),...n]}return t=[...Se(1),...Je(0),...Je(4),...yd(t.length),...t,...Je(6),...Je(1),...Je(2)],t=[...Je(3),...yd(t.length),...t],Ve("esds",0,0,t)},kn=r=>be("wave",void 0,[PT(r),ET(r),be("\0\0\0\0")]),PT=r=>be("frma",[je(i0(r.track.source._codec,r.muxer.isQuickTime))]),ET=r=>{let{littleEndian:e}=Ht(r.track.source._codec);return be("enda",[Se(+e)])},IT=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=jo(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),Se(t),j(n),bd(i),Je(s),...a])},MT=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)])},FT=r=>{let e=Go(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])},RT=r=>{let e=Ko(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])},BT=(r,e)=>be(r,[Array(6).fill(0),Se(1)],[av[e.track.source._codec](e)]),DT=r=>be("vttC",[..._t.encode(r.info.config.description)]);var OT=r=>Ve("stts",0,0,[j(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[j(e.sampleCount),j(e.sampleDelta)])]),LT=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))])},UT=r=>Ve("stsc",0,0,[j(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[j(e.firstChunk),j(e.samplesPerChunk),j(1)])]),zT=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))])},NT=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))]),VT=r=>Ve("ctts",1,0,[j(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[j(e.sampleCount),Gr(e.sampleCompositionTimeOffset)])]),HT=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)])},WT=r=>be("mvex",void 0,r.map(qT)),qT=r=>Ve("trex",0,0,[j(r.track.id),j(1),j(0),j(0),j(0)]),Td=(r,e)=>be("moof",void 0,[jT(r),...e.map(GT)]),jT=r=>Ve("mfhd",0,0,[j(r)]),Zg=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},GT=r=>be("traf",void 0,[KT(r),$T(r),XT(r)]),KT=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:Zg(t)};return Ve("tfhd",0,e,[j(r.track.id),j(n.duration),j(n.size),j(n.flags)])},$T=r=>(w(r.currentChunk),Ve("tfdt",1,0,[yr($e(r.currentChunk.startTimestamp,r.timescale))])),XT=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(Zg),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]):[]])])},Jg=r=>be("mfra",void 0,[...r.map(QT),YT()]),QT=(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)])]),YT=()=>Ve("mfro",0,0,[j(0)]),e0=()=>be("vtte"),t0=(r,e,t,n,i)=>be("vttc",void 0,[i!==null?be("vsid",[Gr(i)]):null,t!==null?be("iden",[..._t.encode(t)]):null,e!==null?be("ctim",[..._t.encode(Hg(e))]):null,n!==null?be("sttg",[..._t.encode(n)]):null,be("payl",[..._t.encode(r)])]),r0=r=>be("vtta",[..._t.encode(r)]),ZT=r=>{let e=[],t=r.format._options.metadataFormat??"auto",n=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){let i=ev(n);i&&e.push(i)}else if(t==="mdta"){let i=tv(n);i&&e.push(i)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&JT(e,r.output._metadataTags);return e.length===0?null:be("udta",void 0,e)},JT=(r,e)=>{for(let{key:t,value:n}of zs(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,[Se(t.length),Se(s0("und")),Array.from(t)])},qg={"image/jpeg":13,"image/png":14,"image/bmp":27},n0=(r,e)=>{let t=[];for(let{key:n,value:i}of zs(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:be("data",[j(qg[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:be("data",[j(0),j(0),Se(0),Se(i),Se(r.tracksTotal??0),Se(0)])});break;case"discNumber":e||t.push({key:"disc",value:be("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:be("data",[j(0),j(0),Array.from(i)])}):i instanceof Kt&&t.push({key:n,value:be("data",[j(qg[i.mimeType]??0),j(0),Array.from(i.data)])}))}return t},ev=r=>{let e=n0(r,!1);return e.length===0?null:Ve("meta",0,0,void 0,[Sd(!1,"mdir","","appl"),be("ilst",void 0,e.map(t=>be(t.key,void 0,[t.value])))])},tv=r=>{let e=n0(r,!0);return e.length===0?null:be("meta",void 0,[Sd(!1,"mdta",""),Ve("keys",0,0,[j(e.length)],e.map(t=>be("mdta",[..._t.encode(t.key)]))),be("ilst",void 0,e.map((t,n)=>{let i=String.fromCharCode(...j(n+1));return be(i,void 0,[t.value])}))])},nr=r=>be("data",[j(1),j(0),..._t.encode(r)]),rv=(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"}},nv={avc:vT,hevc:AT,vp8:Wg,vp9:Wg,av1:_T},i0=(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"}},iv=(r,e)=>{switch(r){case"aac":return wd;case"mp3":return wd;case"opus":return IT;case"vorbis":return wd;case"flac":return MT;case"ac3":return FT;case"eac3":return RT}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},sv={webvtt:"wvtt"},av={webvtt:DT},s0=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 Yn=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 Zc(this,e)}},vd=2**16,Ad=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(vd,{maxByteLength:Ad})}catch{this._buffer=new ArrayBuffer(vd),this._supportsResize=!1}else this._buffer=new ArrayBuffer(vd);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>Ad)throw new Error(`ArrayBuffer exceeded maximum size of ${Ad} 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)}},ov=2**24,cv=2,Sa=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??ov}_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>cv){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 Zc=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)}},Zn=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,lv=2082844800,a0=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},Jc=class extends Qc{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new sr,this.auxWriter=new Yn(this.auxTarget,!1),this.auxBoxWriter=new Qn(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=nt(),this.creationTime=Math.floor(Date.now()/1e3)+lv,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 Qn(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 Yn(n,!0);i.start(),this.initWriter=i,this.initBoxWriter=new Qn(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(Qg({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=xa(!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 Qo({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;Jm(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=cp(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=dp(h),a=!0}let o=Um(1/(e.metadata.frameRate??Wt),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:On({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;ep(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=Do({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;tp(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=Ho(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?Vn: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=e0();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;pd.lastIndex=0;let d=pd.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=r0(u.notes);this.auxBoxWriter.writeBox(m)}let p=t0(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 Qn(this.writer);let m=this.boxWriter.measureBox(kd()),g=this.boxWriter.measureBox(xd(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=Td(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=Td(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=xa(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=xa(!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=xa(!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(kd()),this.boxWriter.writeBox(xd(this,t))}else{let t=this.writer.getPos(),n=Jg(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(Yg(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 el=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})()}},Jn=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}},_d=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Ta=class extends Jn{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(),_d(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},Cd=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=pu(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 tl(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=sd({...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=jc.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.");_d(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})),_d(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=pu(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}},o0=!1,tl=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&&!o0)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,o0=!0,ye._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
|
|
2039
|
+
in vec2 a_position;
|
|
2040
|
+
in vec2 a_texCoord;
|
|
2041
|
+
out vec2 v_texCoord;
|
|
2042
|
+
|
|
2043
|
+
void main() {
|
|
2044
|
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
2045
|
+
v_texCoord = a_texCoord;
|
|
2046
|
+
}
|
|
2047
|
+
`)}createColorProgram(){w(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
2048
|
+
precision highp float;
|
|
2049
|
+
|
|
2050
|
+
uniform sampler2D u_sourceTexture;
|
|
2051
|
+
in vec2 v_texCoord;
|
|
2052
|
+
out vec4 fragColor;
|
|
2053
|
+
|
|
2054
|
+
void main() {
|
|
2055
|
+
vec4 source = texture(u_sourceTexture, v_texCoord);
|
|
2056
|
+
fragColor = vec4(source.rgb, 1.0);
|
|
2057
|
+
}
|
|
2058
|
+
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createAlphaProgram(){w(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
2059
|
+
precision highp float;
|
|
2060
|
+
|
|
2061
|
+
uniform sampler2D u_sourceTexture;
|
|
2062
|
+
uniform vec2 u_resolution; // The width and height of the canvas
|
|
2063
|
+
in vec2 v_texCoord;
|
|
2064
|
+
out vec4 fragColor;
|
|
2065
|
+
|
|
2066
|
+
// This function determines the value for a single byte in the YUV stream
|
|
2067
|
+
float getByteValue(float byteOffset) {
|
|
2068
|
+
float width = u_resolution.x;
|
|
2069
|
+
float height = u_resolution.y;
|
|
2070
|
+
|
|
2071
|
+
float yPlaneSize = width * height;
|
|
2072
|
+
|
|
2073
|
+
if (byteOffset < yPlaneSize) {
|
|
2074
|
+
// This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
|
|
2075
|
+
float y = floor(byteOffset / width);
|
|
2076
|
+
float x = mod(byteOffset, width);
|
|
2077
|
+
|
|
2078
|
+
// Add 0.5 to sample the center of the texel
|
|
2079
|
+
vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
|
|
2080
|
+
|
|
2081
|
+
// The luma value is the alpha from the source texture
|
|
2082
|
+
return texture(u_sourceTexture, sampleCoord).a;
|
|
2083
|
+
} else {
|
|
2084
|
+
// Write a fixed value for chroma and beyond
|
|
2085
|
+
return 128.0 / 255.0;
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
void main() {
|
|
2090
|
+
// Each fragment writes 4 bytes (R, G, B, A)
|
|
2091
|
+
float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
|
|
2092
|
+
float baseByteOffset = pixelIndex * 4.0;
|
|
2093
|
+
|
|
2094
|
+
vec4 result;
|
|
2095
|
+
for (int i = 0; i < 4; i++) {
|
|
2096
|
+
float currentByteOffset = baseByteOffset + float(i);
|
|
2097
|
+
result[i] = getByteValue(currentByteOffset);
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
fragColor = result;
|
|
2101
|
+
}
|
|
2102
|
+
`),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)||ye._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([`(${uv.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()}};tl.forceCpu=!0;var uv=()=>{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",""),A=Math.ceil(a/2),M=Math.ceil(o/2),P=A*M,_=P*h,F=k+2*_,E=new Uint8Array(F),U=T;E.set(s.subarray(U,U+k),0);let Q=k,xe=u?512:d?2048:128;h===1?E.fill(xe,Q):new Uint16Array(E.buffer,Q,2*P).fill(xe);let we=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:we,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[E.buffer]},Re=new VideoFrame(E,Ae);return{colorFrame:J,alphaFrame:Re}}};var va=class extends Jn{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.");Eg(t),super(t.codec),this._encoder=new Cd(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 Pd=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 el({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&&_g(e.format)!==n.transform.sampleFormat){let i=Cg(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=Fg({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(i);let s=od.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=Do({objectType:h,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}let u=Oe.fromEncodedChunk(c);u=u.clone({timestamp:Rn(u.timestamp,i.sampleRate),duration:c.duration!=null?Rn(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,Ug(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{let c=Ze(Math.floor(o*32767),-32768,32767);s.setUint8(a,zg(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)=>Ds(s,a,Ze((o+1)*83886075e-1,0,16777215),i):t==="signed"?this.writeOutputValue=(s,a,o)=>Bm(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 ei=class extends ls{constructor(e){Mg(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Pd(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 Aa=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 Jc(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,...Oo,"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,...Oo,"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 dv=["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=yu(this.metadata.group),n=yu(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}},rl=class extends hs{constructor(e,t,n,i){super(e,t,"video",n,i)}},nl=class extends hs{constructor(e,t,n,i){super(e,t,"audio",n,i)}},il=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)}},Ed=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&&Hm(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.")},ti=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 Zn))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 Zn);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 Zn);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 Yn(t,typeof e=="boolean"?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Jn))throw new TypeError("source must be a VideoSource.");if(Ed(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 rl(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof ls))throw new TypeError("source must be an AudioSource.");Ed(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new nl(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Aa))throw new TypeError("source must be a SubtitleSource.");Ed(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new il(this._tracks.length+1,this,e,n))}setMetadataTags(e){if(Vm(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 dv){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?(ye._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 ye._warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&ye._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?(ye._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 c0=Symbol.for("mediabunny loaded");globalThis[c0]&&ye._error(`[WARNING]
|
|
2103
|
+
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[c0]=!0;var Id=null;function hv(r){Id=r}async function Md(r){if(!Id)return null;try{return await Id(r)}catch{return null}}var fv=(()=>{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 fv){if(i>=n)return e;if(i>=t)return i}return e}function _a(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 mv=512*1024*1024,pv=2e3,Fd=5e3,gv=3e4,yv=6e4,wv=3,bv=2,kv=16*1024*1024,sl=class{_host;_budget;_policy="interactive";_entries=new Map;_pass=0;_inflight=0;constructor(e,t=mv){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"?_a(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??xv(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&&!l0(n)?(t.overSince??=e,e-t.overSince>=Fd&&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*bv,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>=wv)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<pv||s===n&&l0(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<gv||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=_a(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<yv)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 l0(r){return r.width*r.height*4<=kv}function xv(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 Sv=512*1024*1024,u0=96,d0=32;function h0(r){if(!r||!(r.width>0)||!(r.height>0))return{forward:u0,back:d0};let e=Sv/(r.width*r.height*4);return{forward:Math.max(4,Math.min(u0,Math.floor(e*.75))),back:Math.max(1,Math.min(d0,Math.floor(e*.25)))}}var al=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"?_a(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>=Fd&&(this.level=o,this._overSince=null)):this._overSince=null,this.level!==c}};function f0(r){let{data:e}=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Av(r){return/\.svg(?:[?#]|$)/i.test(r)}var _v={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 vv{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 co;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 sl({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||bl()||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(Av(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:f0(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:f0(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 Md(e);return t||(await fetch(e)).blob()}assetUrl(e,t){let n=_v[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 Md(a),c=new qr({formats:rd,source:o?new oa(o):new ca(a)}),l=await c.getPrimaryVideoTrack();if(!l)throw c.dispose(),new Error(`loadVideo(${e}): no video track found`);let u=new ba(l),d=await c.computeDuration(),h=await this.probeFirstFrame(u),f=this.catalogVideoSize(e)??await this.trackDisplaySize(l,h),p=new al(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 kl(),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 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.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(a=>a.src))];return await Promise.all(s.map(async a=>{let o=await(await this.fetchBlob(a)).arrayBuffer();this.fontMgr.registerFont(new Uint8Array(o),t)})),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 Cv from"@motionscript/canvaskit";var Rd=null,ol=null;function Pv(){return new URL("@motionscript/canvaskit/canvaskit.wasm",import.meta.url).href}async function $r(r){if(Rd)return Rd;if(ol)return ol;let e=r??Pv();return ol=Cv({locateFile:()=>e}).then(t=>(Rd=t,t)),ol}import{AssetManager as m0,AudioSink as Ev,ClipStore as Iv,placeTracks as Mv,AssetTimeline as Fv,renderSettled as Rv,SETTLE_PASSES as Bv,spansCovering as p0,StateEvaluator as Dv,yieldToScheduler as Ov}from"@motionscript/core";var cl=class extends Ev{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 g0({renderContext:r,storageAdapter:e},t,n){await Rv(()=>r.execute(t),e,()=>!0)==="exhausted"&&console.warn(`[export] frame ${n} still had pending decodes after ${Bv} renders; it may not be exact.`)}function y0(r){let e=r.getDecodePolicy();return r.setDecodePolicy("exact"),()=>r.setDecodePolicy(e)}function Lv(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 w0(r){let{project:e,registry:t,assetCatalog:n,renderContext:i}=r,{fps:s,viewport:a}=Lv(e),o=i,c={registry:t,viewport:a,fps:s,assets:n,measurer:o},l={},u=new Iv(e,c,{isReady:f=>l.manager?.isReady(f)??!1}),d=new Fv(e,c,{store:u}),h=new Dv(e,c,u);return{store:u,precomper:d,stateEvaluator:h,measurer:o,fps:s,viewport:a,loads:l}}async function b0(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 Bd(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 k0(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}=w0(r),y=y0(l);try{let b=d.run(),{totalFrames:k,totalDuration:T}=b,S=g.manager=new m0(b,l,new cl);await b0(u,S,r.project.tracks.map(E=>E.id));let A=Bd(b),M=a&&A.length>0&&n!==void 0;await t.start({width:m.width*e,height:m.height*e,fps:p,totalFrames:k,hasAudio:M});let P=1/p,_=0;l.setPlaying(!0);try{for(let E=0;E<k;E++)s?.throwIfAborted(),await S.loadAt(E),h.stateAt(E),h.layout(f),await g0(o,()=>h.render(c),E),await t.addFrame(_,P),_+=P,i?.((E+1)/k*(M?.85:1)),(E+1)%4===0&&await Ov()}finally{l.setPlaying(!1)}if(M){let E=await n.mix(A,T);E!==null&&t.addAudio&&await t.addAudio(E),i?.(.97)}let F=await t.finalize();return i?.(1),F}finally{y(),h.dispose(),u.dispose()}}async function x0(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}=w0(r),h=y0(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);Uv(n,g,m);let y=d.manager=new m0(g,a,new cl);return await b0(o,y,p0(o.spans,m).map(b=>b.id)),await y.loadAt(m),l.stateAt(m),l.layout(u),await g0(i,()=>l.render(s),m),{frame:m,totalFrames:f}}finally{h(),l.dispose(),o.dispose()}}function Uv(r,e,t){if(e.buildErrors.length===0)return;let n=new Map(e.buildErrors.map(a=>[a.trackId,a])),i=p0(Mv(r.tracks,e.fps),t);if(i.length===0||!i.every(a=>n.has(a.id)))return;let s=i.map(a=>` ${a.id}: ${n.get(a.id).message}`).join(`
|
|
2104
|
+
`);throw new Error(`Frame ${t} has nothing to draw \u2014 every track on it failed to build:
|
|
2105
|
+
${s}`)}import{ManifestAssetCatalog as zv,Registry as Nv,resolveProjectDocument as Vv}from"@motionscript/core";var Xr={viewport:{width:1920,height:1080},fps:60};var Hv=.2,Wv=2e6,qv=1e8;function S0(r,e,t){let n=r*e*t*Hv;return Math.round(Math.min(qv,Math.max(Wv,n)))}var jv=192e3,Gv=1,Kv=2,$v={image:{},video:{},audio:{},font:{}},Dd=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 va(e,{codec:a,bitrate:i.bitrate??S0(n.width,n.height,t),hardwareAcceleration:i.hardwareAcceleration??"no-preference",keyFrameInterval:i.keyFrameInterval??Gv,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 ti({format:new xn,target:this.target})}async start(e){this.output.addVideoTrack(this.video,{frameRate:e.fps}),e.hasAudio&&(this.audio=new ei({codec:"aac",bitrate:this.audioOptions.bitrate??jv}),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 ll(r){let e=Math.round(r);return e%2===0?e:e+1}var Xv=8192;function Qv(r,e){let t=Math.max(e.width,e.height),n=Math.max(1,Math.round(r));for(;n>1&&t*n>Xv;)n--;return n}async function Yv(r,e,t){if(!r||r==="avc")return"avc";try{if(await ad(r,{width:e.width,height:e.height,bitrate:S0(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 Od(r){let{document:e,registry:t=new Nv,scale:n=1,filename:i="export.mp4",manifest:s=$v,includeAudio:a=!0,video:o,audio:c={},onProgress:l,signal:u,wasmUrl:d,supersample:h=Kv,returnBytes:f=!1}=r,p=Vv(e,r,Xr);if(p.tracks.length===0)return;u?.throwIfAborted();let m=p.viewport,g=p.fps,y={width:ll(m.width*n),height:ll(m.height*n)},b=Qv(h,y),k=n*b,T=document.createElement("canvas");T.width=ll(m.width*k),T.height=ll(m.height*k),T.style.display="none",document.body.appendChild(T);let S=await $r(d),A=new zv(s),M=new jt(S,A,m,g),P=new cr(S,M);P.mount(T);let _=await Yv(o?.codec,y,g),F;try{F=await k0({project:p,registry:t,scale:k,includeAudio:a,renderContext:P,storageAdapter:M,assetCatalog:A,sink:new Dd(T,g,y,o,c,_),mixer:new Xd(c.sampleRate,A),onProgress:l,signal:u})}finally{P.dispose(),document.body.removeChild(T)}if(!F)return;if(f)return F;let E=new Blob([F.buffer],{type:"video/mp4"}),U=URL.createObjectURL(E),Q=document.createElement("a");Q.href=U,Q.download=i,document.body.appendChild(Q),Q.click(),document.body.removeChild(Q),URL.revokeObjectURL(U)}import{resolveProjectDocument as nA}from"@motionscript/core";import{ManifestAssetCatalog as T0,Registry as Zv,resolveProjectDocument as Jv,setTheme as eA}from"@motionscript/core";var tA={image:{},video:{},audio:{},font:{}};function rA(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 v0(r){return r==="jpeg"?"image/jpeg":"image/png"}var ys=class{canvas;renderContext;storageAdapter;catalog;canvasKit;ownsCanvas;viewportValue;fpsValue;scaleValue;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.manifest=t.manifest??tA,this.theme=t.theme,this.registry=t.registry??new Zv,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 T0(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.scaleValue&&(this.scaleValue=n,this.remount());let i=Jv(e,{viewport:this.viewportValue},{viewport:this.viewportValue,fps:this.fpsValue});return eA(i.theme??this.theme),x0({project:i,registry:this.registry,scale:n,renderContext:this.renderContext,storageAdapter:this.storageAdapter,assetCatalog:this.catalog,frame:rA(t,i.fps)})}setTheme(e){this.theme=e}setManifest(e){this.assertLive(),this.manifest=e,this.catalog=new T0(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())}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.")),v0(n),i)})}toDataURL(e){let{format:t="png",quality:n=.92}=e??{};return this.snapshotToCanvas().toDataURL(v0(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.scaleValue,this.canvas.height=this.viewportValue.height*this.scaleValue}remount(){this.sizeCanvas(),this.renderContext.mount(this.canvas)}assertLive(){if(this.disposed)throw new Error("This StillRenderer has been disposed.")}};async function Ld(r={}){let e=await $r(r.wasmUrl);return new ys(e,r)}async function iA(r){let{registry:e,scale:t,manifest:n,theme:i,wasmUrl:s,frame:a,format:o="png",quality:c=.92}=r,l=nA(r.document,r,Xr);if(l.tracks.length===0)throw new Error("The project has no tracks to screenshot.");let u=await Ld({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 sA(r,e){if(r.codec!==e.codec||r.codedWidth!==e.codedWidth||r.codedHeight!==e.codedHeight)return!1;let t=A0(r.description),n=A0(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 A0(r){return r?ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r):null}var aA=192e3;async function oA(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 aa(r[l]),formats:[Hc]}).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&&!sA(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 Sa(e.stream):new sr,i=new ti({format:new xn,target:n}),s=new Ta(t[0].track.codec);i.addVideoTrack(s);let a=e.audio?new ei({codec:"aac",bitrate:e.audioBitrate??aA}):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 cA,AssetTimeline as lA,Registry as uA,resolveProjectDocument as dA}from"@motionscript/core";var ul=class{storageAdapter;constructor(e){this.storageAdapter=e}measureText(e,t,n,i=400,s=0,a="normal"){return lo(this.storageAdapter.getCanvasKit(),this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),this.storageAdapter.getFontEpoch(),e,t,n,i,s,a)}layoutTextBlock(e){return uo(this.storageAdapter.getCanvasKit(),this.storageAdapter.getFontMgr(),e)}};var ri=class extends ul{};var hA={image:{},video:{},audio:{},font:{}};async function fA(r){let{registry:e=new uA,manifest:t=hA,sampleRate:n,wasmUrl:i}=r,s=dA(r.document,r,Xr);if(s.tracks.length===0)return null;let a=s.viewport,o=s.fps,c=await $r(i),l=new cA(t),u=new jt(c,l,a,o),d=new ri(u),h=new lA(s,{registry:e,viewport:a,fps:o,assets:l,measurer:d},{assets:!1});try{let f=h.run(),p=Bd(f);return p.length===0?null:await ml(p,f.totalDuration,{sampleRate:n,catalog:l})}finally{h.dispose(),u.dispose()}}import{Ticker as mA}from"@motionscript/core";var Ca=class extends mA{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 kA}from"@motionscript/core";var dl=iy(_0(),1);import*as pA from"@motionscript/core/sdk";import*as gA from"@motionscript/core/jsx/jsx-runtime";function yA(){return new URL("esbuild-wasm/esbuild.wasm",import.meta.url).href}var wA;function bA(r){return wA??=(async()=>(await dl.initialize({wasmURL:r??yA()}),async e=>{let{code:t}=await dl.transform(e,{loader:"tsx",format:"cjs",target:"es2020",tsconfigRaw:{compilerOptions:{experimentalDecorators:!0}}});return t}))()}function C0(r,e){return{sdk:r?.sdk??pA,jsxRuntime:r?.jsxRuntime??gA,modules:r?.modules,compile:r?.compile??(async t=>(await bA(e))(t))}}var zd=class{canvasKit;defaults;wasmUrl;still=null;stillRegistry=null;constructor(e,t,n){this.canvasKit=e,this.defaults=t,this.wasmUrl=n}async exportVideo(e){let t=e.encode??{};return Od({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})}async exportStill(e){let t=this.renderer(e),n=await t.render(e.project,{scale:e.scale,...xA(e.frame)});return{bytes:await t.toBytes({format:e.format,quality:e.quality}),frame:n.frame,totalFrames:n.totalFrames}}dispose(){this.still?.dispose(),this.still=null}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 xA(r){return r.kind==="frame"?{frame:r.frame}:{frame:r.kind}}async function SA(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=C0(r.dynamicNodes,r.compilerWasmUrl),s=await $r(r.wasmUrl),a=new zd(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 ri(l)},createAudioSink(){return new pl},createTicker(l,u){return new Ca({context:u.getContext(),fps:l})},createExporter(){return a},dispose(){a.dispose()}},c=new kA(o,{...r,nodes:t,dynamicNodes:i});for(let l of n)await c.registerNode(l);return c}var ct=null,P0=!0,bs=new Map,hl=64,fl=4096;function TA(r,e){let t=new r.WebGLRenderer({antialias:e,alpha:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!0});return t.setClearColor(0,0),t.setPixelRatio(1),fl=t.capabilities.maxTextureSize??fl,t}function vA(r,e){return ct&&P0!==e&&(ct.dispose(),ct.forceContextLoss(),ct=null),ct||(ct=TA(r,e),P0=e,bs.clear()),ct}function AA(r,e,t){let n={width:Math.min(fl,Math.max(1,Math.ceil(e/hl)*hl)),height:Math.min(fl,Math.max(1,Math.ceil(t/hl)*hl))},i=bs.get(r);if(!i)return bs.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)&&bs.set(r,s),s}function _A(r,e,t,n,i,s,a={}){let o=vA(r,a.antialias!==!1),c=AA(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 CA(r,e){ct&&(ct.shadowMap.enabled!==e.shadowsEnabled&&(ct.shadowMap.enabled=e.shadowsEnabled,ct.shadowMap.needsUpdate=!0),ct.shadowMap.type!==e.shadowType&&(ct.shadowMap.type=e.shadowType,ct.shadowMap.needsUpdate=!0),ct.toneMapping=e.toneMapping,ct.toneMappingExposure=e.toneMappingExposure)}function PA(){return ct}function EA(){ct?.dispose(),ct?.forceContextLoss(),ct=null,bs.clear()}function IA(r){bs.delete(r)}var E0={render:_A,applySettings:CA,active:PA,forgetBuffer:IA,dispose:EA};xl();Sl(E0);export{As as Canvas3DBackend,ws as ConcatMismatchError,ge as EffectRegistry,Og as QUALITY_HIGH,Bg as QUALITY_LOW,Dg as QUALITY_MEDIUM,Lg as QUALITY_VERY_HIGH,Rg as QUALITY_VERY_LOW,ys as StillRenderer,pl as WebAudioPlayer,ri as WebMeasureContext,cr as WebRenderContext,jt as WebStorageAdapter,Ca as WebTicker,oi as canvas3DBackend,oA as concatVideoSegments,SA as createBrowserEngine,Ld as createStillRenderer,Wa as disposeCanvas3DBackend,sy as encodeWav,iA as exportScreenshot,Od as exportVideo,$r as getCanvasKit,vs as loadCanvas3D,ml as mixAudio,fA as mixTimelineAudio,hv as setAssetByteSource};
|
|
2106
|
+
/*! Bundled license information:
|
|
2107
|
+
|
|
2108
|
+
mediabunny/dist/modules/src/misc.js:
|
|
2109
|
+
mediabunny/dist/modules/src/logging.js:
|
|
2110
|
+
mediabunny/dist/modules/src/metadata.js:
|
|
2111
|
+
mediabunny/dist/modules/shared/bitstream.js:
|
|
2112
|
+
mediabunny/dist/modules/shared/aac-misc.js:
|
|
2113
|
+
mediabunny/dist/modules/src/codec.js:
|
|
2114
|
+
mediabunny/dist/modules/shared/mp3-misc.js:
|
|
2115
|
+
mediabunny/dist/modules/shared/ac3-misc.js:
|
|
2116
|
+
mediabunny/dist/modules/src/codec-data.js:
|
|
2117
|
+
mediabunny/dist/modules/src/demuxer.js:
|
|
2118
|
+
mediabunny/dist/modules/src/packet.js:
|
|
2119
|
+
mediabunny/dist/modules/src/isobmff/isobmff-misc.js:
|
|
2120
|
+
mediabunny/dist/modules/src/isobmff/isobmff-reader.js:
|
|
2121
|
+
mediabunny/dist/modules/src/aes.js:
|
|
2122
|
+
mediabunny/dist/modules/src/isobmff/isobmff-demuxer.js:
|
|
2123
|
+
mediabunny/dist/modules/src/matroska/ebml.js:
|
|
2124
|
+
mediabunny/dist/modules/src/matroska/matroska-misc.js:
|
|
2125
|
+
mediabunny/dist/modules/src/matroska/matroska-demuxer.js:
|
|
2126
|
+
mediabunny/dist/modules/src/mp3/mp3-reader.js:
|
|
2127
|
+
mediabunny/dist/modules/src/mp3/mp3-demuxer.js:
|
|
2128
|
+
mediabunny/dist/modules/src/ogg/ogg-misc.js:
|
|
2129
|
+
mediabunny/dist/modules/src/ogg/ogg-reader.js:
|
|
2130
|
+
mediabunny/dist/modules/src/ogg/ogg-demuxer.js:
|
|
2131
|
+
mediabunny/dist/modules/src/wave/wave-demuxer.js:
|
|
2132
|
+
mediabunny/dist/modules/src/adts/adts-reader.js:
|
|
2133
|
+
mediabunny/dist/modules/src/adts/adts-demuxer.js:
|
|
2134
|
+
mediabunny/dist/modules/src/flac/flac-misc.js:
|
|
2135
|
+
mediabunny/dist/modules/src/flac/flac-demuxer.js:
|
|
2136
|
+
mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-misc.js:
|
|
2137
|
+
mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-demuxer.js:
|
|
2138
|
+
mediabunny/dist/modules/src/hls/hls-misc.js:
|
|
2139
|
+
mediabunny/dist/modules/src/segmented-input.js:
|
|
2140
|
+
mediabunny/dist/modules/src/source.js:
|
|
2141
|
+
mediabunny/dist/modules/src/hls/hls-segmented-input.js:
|
|
2142
|
+
mediabunny/dist/modules/src/hls/hls-demuxer.js:
|
|
2143
|
+
mediabunny/dist/modules/src/input-format.js:
|
|
2144
|
+
mediabunny/dist/modules/src/sample.js:
|
|
2145
|
+
mediabunny/dist/modules/src/encode.js:
|
|
2146
|
+
mediabunny/dist/modules/src/custom-coder.js:
|
|
2147
|
+
mediabunny/dist/modules/src/pcm.js:
|
|
2148
|
+
mediabunny/dist/modules/src/media-sink.js:
|
|
2149
|
+
mediabunny/dist/modules/src/input-track.js:
|
|
2150
|
+
mediabunny/dist/modules/src/input.js:
|
|
2151
|
+
mediabunny/dist/modules/src/reader.js:
|
|
2152
|
+
mediabunny/dist/modules/src/id3.js:
|
|
2153
|
+
mediabunny/dist/modules/src/muxer.js:
|
|
2154
|
+
mediabunny/dist/modules/src/subtitles.js:
|
|
2155
|
+
mediabunny/dist/modules/src/isobmff/isobmff-boxes.js:
|
|
2156
|
+
mediabunny/dist/modules/src/writer.js:
|
|
2157
|
+
mediabunny/dist/modules/src/target.js:
|
|
2158
|
+
mediabunny/dist/modules/src/isobmff/isobmff-muxer.js:
|
|
2159
|
+
mediabunny/dist/modules/src/resample.js:
|
|
2160
|
+
mediabunny/dist/modules/src/media-source.js:
|
|
2161
|
+
mediabunny/dist/modules/src/output-format.js:
|
|
2162
|
+
mediabunny/dist/modules/src/output.js:
|
|
2163
|
+
mediabunny/dist/modules/src/index.js:
|
|
2164
|
+
(*!
|
|
2165
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
2166
|
+
*
|
|
2167
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
2168
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
2169
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
2170
|
+
*)
|
|
2171
|
+
*/
|
|
2172
|
+
//# sourceMappingURL=index.js.map
|