@motionscript/browser 0.1.0-alpha.7 → 0.1.0-alpha.8

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.
Files changed (148) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/NOTICE +15 -14
  3. package/README.md +66 -43
  4. package/dist/asset-bytes.d.ts +7 -4
  5. package/dist/asset-bytes.d.ts.map +1 -1
  6. package/dist/asset-bytes.js +9 -4
  7. package/dist/asset-bytes.js.map +1 -1
  8. package/dist/audio/bus-graph.d.ts.map +1 -1
  9. package/dist/audio/bus-graph.js +15 -6
  10. package/dist/audio/bus-graph.js.map +1 -1
  11. package/dist/audio/effect-graph.d.ts +62 -0
  12. package/dist/audio/effect-graph.d.ts.map +1 -0
  13. package/dist/audio/effect-graph.js +234 -0
  14. package/dist/audio/effect-graph.js.map +1 -0
  15. package/dist/audio/index.d.ts.map +1 -1
  16. package/dist/audio/index.js +2 -3
  17. package/dist/audio/index.js.map +1 -1
  18. package/dist/audio/mixer.d.ts +4 -4
  19. package/dist/audio/mixer.d.ts.map +1 -1
  20. package/dist/audio/mixer.js +18 -38
  21. package/dist/audio/mixer.js.map +1 -1
  22. package/dist/audio/player.d.ts +12 -6
  23. package/dist/audio/player.d.ts.map +1 -1
  24. package/dist/audio/player.js +49 -62
  25. package/dist/audio/player.js.map +1 -1
  26. package/dist/browser/THIRD_PARTY_LICENSES.txt +379 -27
  27. package/dist/browser/audio.js +1 -1
  28. package/dist/browser/chunks/chunk-IILVN4SK.js +2 -0
  29. package/dist/browser/chunks/chunk-IILVN4SK.js.map +7 -0
  30. package/dist/browser/chunks/chunk-KLXMRKTL.js +2 -0
  31. package/dist/browser/chunks/chunk-L5UFQACH.js +163 -0
  32. package/dist/browser/chunks/chunk-L5UFQACH.js.map +7 -0
  33. package/dist/browser/chunks/mediabunny-mp3-encoder-ZCIHVVTJ.js +14 -0
  34. package/dist/browser/chunks/mediabunny-mp3-encoder-ZCIHVVTJ.js.map +7 -0
  35. package/dist/browser/index.js +51 -1343
  36. package/dist/browser/index.js.map +4 -4
  37. package/dist/browser/manifest.json +8 -8
  38. package/dist/browser/ms_renderer_bg.wasm +0 -0
  39. package/dist/canvaskit-renderer.d.ts +8 -0
  40. package/dist/canvaskit-renderer.d.ts.map +1 -0
  41. package/dist/canvaskit-renderer.js +23 -0
  42. package/dist/canvaskit-renderer.js.map +1 -0
  43. package/dist/concat.d.ts +33 -7
  44. package/dist/concat.d.ts.map +1 -1
  45. package/dist/concat.js +117 -72
  46. package/dist/concat.js.map +1 -1
  47. package/dist/deliver.d.ts +10 -0
  48. package/dist/deliver.d.ts.map +1 -0
  49. package/dist/deliver.js +22 -0
  50. package/dist/deliver.js.map +1 -0
  51. package/dist/dynamic-nodes.d.ts.map +1 -1
  52. package/dist/dynamic-nodes.js +2 -3
  53. package/dist/dynamic-nodes.js.map +1 -1
  54. package/dist/engine.d.ts +37 -9
  55. package/dist/engine.d.ts.map +1 -1
  56. package/dist/engine.js +41 -32
  57. package/dist/engine.js.map +1 -1
  58. package/dist/export-audio.d.ts +36 -0
  59. package/dist/export-audio.d.ts.map +1 -0
  60. package/dist/export-audio.js +56 -0
  61. package/dist/export-audio.js.map +1 -0
  62. package/dist/exporter.d.ts +125 -14
  63. package/dist/exporter.d.ts.map +1 -1
  64. package/dist/exporter.js +133 -89
  65. package/dist/exporter.js.map +1 -1
  66. package/dist/formats.d.ts +36 -0
  67. package/dist/formats.d.ts.map +1 -0
  68. package/dist/formats.js +83 -0
  69. package/dist/formats.js.map +1 -0
  70. package/dist/frame-loop.d.ts +190 -0
  71. package/dist/frame-loop.d.ts.map +1 -0
  72. package/dist/frame-loop.js +304 -0
  73. package/dist/frame-loop.js.map +1 -0
  74. package/dist/getter.d.ts +4 -1
  75. package/dist/getter.d.ts.map +1 -1
  76. package/dist/getter.js +7 -6
  77. package/dist/getter.js.map +1 -1
  78. package/dist/index.d.ts +12 -11
  79. package/dist/index.d.ts.map +1 -1
  80. package/dist/index.js +17 -21
  81. package/dist/index.js.map +1 -1
  82. package/dist/mix-timeline-audio.d.ts +5 -5
  83. package/dist/mix-timeline-audio.d.ts.map +1 -1
  84. package/dist/mix-timeline-audio.js +10 -12
  85. package/dist/mix-timeline-audio.js.map +1 -1
  86. package/dist/parallel/export-parallel.d.ts +32 -0
  87. package/dist/parallel/export-parallel.d.ts.map +1 -0
  88. package/dist/parallel/export-parallel.js +114 -0
  89. package/dist/parallel/export-parallel.js.map +1 -0
  90. package/dist/parallel/governor.d.ts +57 -0
  91. package/dist/parallel/governor.d.ts.map +1 -0
  92. package/dist/parallel/governor.js +79 -0
  93. package/dist/parallel/governor.js.map +1 -0
  94. package/dist/parallel/lane.d.ts +45 -0
  95. package/dist/parallel/lane.d.ts.map +1 -0
  96. package/dist/parallel/lane.js +2 -0
  97. package/dist/parallel/lane.js.map +1 -0
  98. package/dist/parallel/lanes.d.ts +20 -0
  99. package/dist/parallel/lanes.d.ts.map +1 -0
  100. package/dist/parallel/lanes.js +152 -0
  101. package/dist/parallel/lanes.js.map +1 -0
  102. package/dist/parallel/plan.d.ts +23 -0
  103. package/dist/parallel/plan.d.ts.map +1 -0
  104. package/dist/parallel/plan.js +30 -0
  105. package/dist/parallel/plan.js.map +1 -0
  106. package/dist/parallel/run-lanes.d.ts +38 -0
  107. package/dist/parallel/run-lanes.d.ts.map +1 -0
  108. package/dist/parallel/run-lanes.js +164 -0
  109. package/dist/parallel/run-lanes.js.map +1 -0
  110. package/dist/parallel/session.d.ts +9 -0
  111. package/dist/parallel/session.d.ts.map +1 -0
  112. package/dist/parallel/session.js +79 -0
  113. package/dist/parallel/session.js.map +1 -0
  114. package/dist/render-context.d.ts +2 -0
  115. package/dist/render-context.d.ts.map +1 -1
  116. package/dist/render-context.js +8 -4
  117. package/dist/render-context.js.map +1 -1
  118. package/dist/renderer.d.ts +22 -0
  119. package/dist/renderer.d.ts.map +1 -0
  120. package/dist/renderer.js +23 -0
  121. package/dist/renderer.js.map +1 -0
  122. package/dist/screenshot.d.ts +4 -4
  123. package/dist/screenshot.d.ts.map +1 -1
  124. package/dist/screenshot.js +3 -3
  125. package/dist/screenshot.js.map +1 -1
  126. package/dist/still.d.ts +17 -19
  127. package/dist/still.d.ts.map +1 -1
  128. package/dist/still.js +27 -34
  129. package/dist/still.js.map +1 -1
  130. package/dist/ticker.d.ts +22 -8
  131. package/dist/ticker.d.ts.map +1 -1
  132. package/dist/ticker.js +55 -20
  133. package/dist/ticker.js.map +1 -1
  134. package/package.json +9 -10
  135. package/dist/browser/chunks/GLTFLoader-PGXD4V5B.js +0 -2
  136. package/dist/browser/chunks/GLTFLoader-PGXD4V5B.js.map +0 -7
  137. package/dist/browser/chunks/SkeletonUtils-XYDMTGTM.js +0 -2
  138. package/dist/browser/chunks/chunk-2MAFJWBZ.js +0 -2
  139. package/dist/browser/chunks/chunk-2MAFJWBZ.js.map +0 -7
  140. package/dist/browser/chunks/chunk-CTLBXZSU.js +0 -4119
  141. package/dist/browser/chunks/chunk-CTLBXZSU.js.map +0 -7
  142. package/dist/browser/chunks/chunk-FQ32PDIU.js +0 -2
  143. package/dist/browser/chunks/chunk-FQ32PDIU.js.map +0 -7
  144. package/dist/browser/chunks/chunk-FY3BTKY4.js +0 -2
  145. package/dist/browser/chunks/chunk-FY3BTKY4.js.map +0 -7
  146. package/dist/browser/chunks/three.module-Z4EOVUWF.js +0 -2
  147. package/dist/browser/chunks/three.module-Z4EOVUWF.js.map +0 -7
  148. /package/dist/browser/chunks/{SkeletonUtils-XYDMTGTM.js.map → chunk-KLXMRKTL.js.map} +0 -0
@@ -1,17 +1,17 @@
1
- import{a as Cy,b as gl,c as th,f as yl,g as rh,h as Py,i as wl}from"./chunks/chunk-2MAFJWBZ.js";import{a as vy,b as _y}from"./chunks/chunk-FY3BTKY4.js";var Q0=vy((i4,qd)=>{(r=>{"use strict";var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,s=(S,A)=>{for(var I in A)e(S,I,{get:A[I],enumerable:!0})},a=(S,A,I,U)=>{if(A&&typeof A=="object"||typeof A=="function")for(let K of n(A))!i.call(S,K)&&K!==I&&e(S,K,{get:()=>A[K],enumerable:!(U=t(A,K))||U.enumerable});return S},o=S=>a(e({},"__esModule",{value:!0}),S),c=(S,A,I)=>new Promise((U,K)=>{var $=B=>{try{se(I.next(B))}catch(re){K(re)}},H=B=>{try{se(I.throw(B))}catch(re){K(re)}},se=B=>B.done?U(B.value):Promise.resolve(B.value).then($,H);se((I=I.apply(S,A)).next())}),l={};s(l,{analyzeMetafile:()=>my,analyzeMetafileSync:()=>wy,build:()=>uy,buildSync:()=>py,context:()=>dy,default:()=>xy,formatMessages:()=>fy,formatMessagesSync:()=>yy,initialize:()=>ky,stop:()=>by,transform:()=>hy,transformSync:()=>gy,version:()=>ly}),r.exports=o(l);function u(S){let A=U=>{if(U===null)I.write8(0);else if(typeof U=="boolean")I.write8(1),I.write8(+U);else if(typeof U=="number")I.write8(2),I.write32(U|0);else if(typeof U=="string")I.write8(3),I.write(f(U));else if(U instanceof Uint8Array)I.write8(4),I.write(U);else if(U instanceof Array){I.write8(5),I.write32(U.length);for(let K of U)A(K)}else{let K=Object.keys(U);I.write8(6),I.write32(K.length);for(let $ of K)I.write(f($)),A(U[$])}},I=new h;return I.write32(0),I.write32(S.id<<1|+!S.isRequest),A(S.value),y(I.buf,I.len-4,0),I.buf.subarray(0,I.len)}function d(S){let A=()=>{switch(I.read8()){case 0:return null;case 1:return!!I.read8();case 2:return I.read32();case 3:return p(I.read());case 4:return I.read();case 5:{let H=I.read32(),se=[];for(let B=0;B<H;B++)se.push(A());return se}case 6:{let H=I.read32(),se={};for(let B=0;B<H;B++)se[p(I.read())]=A();return se}default:throw new Error("Invalid packet")}},I=new h(S),U=I.read32(),K=(U&1)===0;U>>>=1;let $=A();if(I.ptr!==S.length)throw new Error("Invalid packet");return{id:U,isRequest:K,value:$}}var h=class{constructor(S=new Uint8Array(1024)){this.buf=S,this.len=0,this.ptr=0}_write(S){if(this.len+S>this.buf.length){let A=new Uint8Array((this.len+S)*2);A.set(this.buf),this.buf=A}return this.len+=S,this.len-S}write8(S){let A=this._write(1);this.buf[A]=S}write32(S){let A=this._write(4);y(this.buf,S,A)}write(S){let A=this._write(4+S.length);y(this.buf,S.length,A),this.buf.set(S,A+4)}_read(S){if(this.ptr+S>this.buf.length)throw new Error("Invalid packet");return this.ptr+=S,this.ptr-S}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let S=this.read32(),A=new Uint8Array(S),I=this._read(A.length);return A.set(this.buf.subarray(I,I+S)),A}},f,p,m;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let S=new TextEncoder,A=new TextDecoder;f=I=>S.encode(I),p=I=>A.decode(I),m='new TextEncoder().encode("")'}else if(typeof Buffer<"u")f=S=>Buffer.from(S),p=S=>{let{buffer:A,byteOffset:I,byteLength:U}=S;return Buffer.from(A,I,U).toString()},m='Buffer.from("")';else throw new Error("No UTF-8 codec found");if(!(f("")instanceof Uint8Array))throw new Error(`Invariant violation: "${m} instanceof Uint8Array" is incorrectly false
1
+ import{a as Xa,b as qn,e as Zn,f as vs,g as ro,h as Qn}from"./chunks/chunk-IILVN4SK.js";import{A as ws,B as ys,C as Tt,c as os,d as ls,e as cs,f as Jn,g as us,h as Za,i as Qa,j as eo,k as to,l as no,m as fs,n as Yn,q as ds,r as hs,s as xn,t as Et,u as _s,v as ps,w as ms,x as gs,y as Xn,z as bs}from"./chunks/chunk-L5UFQACH.js";import{b as Ja,c as Ya}from"./chunks/chunk-KLXMRKTL.js";var xa=Ja((mp,es)=>{(e=>{"use strict";var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,i=(h,m)=>{for(var b in m)t(h,b,{get:m[b],enumerable:!0})},a=(h,m,b,S)=>{if(m&&typeof m=="object"||typeof m=="function")for(let O of r(m))!s.call(h,O)&&O!==b&&t(h,O,{get:()=>m[O],enumerable:!(S=n(m,O))||S.enumerable});return h},o=h=>a(t({},"__esModule",{value:!0}),h),l=(h,m,b)=>new Promise((S,O)=>{var $=x=>{try{V(b.next(x))}catch(N){O(N)}},P=x=>{try{V(b.throw(x))}catch(N){O(N)}},V=x=>x.done?S(x.value):Promise.resolve(x.value).then($,P);V((b=b.apply(h,m)).next())}),c={};i(c,{analyzeMetafile:()=>Ba,analyzeMetafileSync:()=>Wa,build:()=>$a,buildSync:()=>Ua,context:()=>Da,default:()=>Ha,formatMessages:()=>Fa,formatMessagesSync:()=>Na,initialize:()=>Ga,stop:()=>Va,transform:()=>La,transformSync:()=>ja,version:()=>Oa}),e.exports=o(c);function u(h){let m=S=>{if(S===null)b.write8(0);else if(typeof S=="boolean")b.write8(1),b.write8(+S);else if(typeof S=="number")b.write8(2),b.write32(S|0);else if(typeof S=="string")b.write8(3),b.write(_(S));else if(S instanceof Uint8Array)b.write8(4),b.write(S);else if(S instanceof Array){b.write8(5),b.write32(S.length);for(let O of S)m(O)}else{let O=Object.keys(S);b.write8(6),b.write32(O.length);for(let $ of O)b.write(_($)),m(S[$])}},b=new d;return b.write32(0),b.write32(h.id<<1|+!h.isRequest),m(h.value),L(b.buf,b.len-4,0),b.buf.subarray(0,b.len)}function f(h){let m=()=>{switch(b.read8()){case 0:return null;case 1:return!!b.read8();case 2:return b.read32();case 3:return p(b.read());case 4:return b.read();case 5:{let P=b.read32(),V=[];for(let x=0;x<P;x++)V.push(m());return V}case 6:{let P=b.read32(),V={};for(let x=0;x<P;x++)V[p(b.read())]=m();return V}default:throw new Error("Invalid packet")}},b=new d(h),S=b.read32(),O=(S&1)===0;S>>>=1;let $=m();if(b.ptr!==h.length)throw new Error("Invalid packet");return{id:S,isRequest:O,value:$}}var d=class{constructor(h=new Uint8Array(1024)){this.buf=h,this.len=0,this.ptr=0}_write(h){if(this.len+h>this.buf.length){let m=new Uint8Array((this.len+h)*2);m.set(this.buf),this.buf=m}return this.len+=h,this.len-h}write8(h){let m=this._write(1);this.buf[m]=h}write32(h){let m=this._write(4);L(this.buf,h,m)}write(h){let m=this._write(4+h.length);L(this.buf,h.length,m),this.buf.set(h,m+4)}_read(h){if(this.ptr+h>this.buf.length)throw new Error("Invalid packet");return this.ptr+=h,this.ptr-h}read8(){return this.buf[this._read(1)]}read32(){return R(this.buf,this._read(4))}read(){let h=this.read32(),m=new Uint8Array(h),b=this._read(m.length);return m.set(this.buf.subarray(b,b+h)),m}},_,p,w;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let h=new TextEncoder,m=new TextDecoder;_=b=>h.encode(b),p=b=>m.decode(b),w='new TextEncoder().encode("")'}else if(typeof Buffer<"u")_=h=>Buffer.from(h),p=h=>{let{buffer:m,byteOffset:b,byteLength:S}=h;return Buffer.from(m,b,S).toString()},w='Buffer.from("")';else throw new Error("No UTF-8 codec found");if(!(_("")instanceof Uint8Array))throw new Error(`Invariant violation: "${w} instanceof Uint8Array" is incorrectly false
2
2
 
3
3
  This indicates that your JavaScript environment is broken. You cannot use
4
4
  esbuild in this environment because esbuild relies on this invariant. This
5
5
  is not a problem with esbuild. You need to fix your environment instead.
6
- `);function g(S,A){return(S[A++]|S[A++]<<8|S[A++]<<16|S[A++]<<24)>>>0}function y(S,A,I){S[I++]=A,S[I++]=A>>8,S[I++]=A>>16,S[I++]=A>>24}var b=String.fromCharCode;function k(S,A,I){let U=S[A],K=1,$=0;for(let H=0;H<A;H++)S[H]===10?(K++,$=0):$++;throw new SyntaxError(I||(A===S.length?"Unexpected end of input while parsing JSON":U>=32&&U<=126?`Unexpected character ${b(U)} in JSON at position ${A} (line ${K}, column ${$})`:`Unexpected byte 0x${U.toString(16)} in JSON at position ${A} (line ${K}, column ${$})`))}function T(S){if(!(S instanceof Uint8Array))throw new Error("JSON input must be a Uint8Array");let A=[],I=[],U=[],K=S.length,$=null,H=0,se,B=0;for(;B<K;){let re=S[B++];if(re<=32)continue;let ae;switch(H===2&&$===null&&re!==34&&re!==125&&k(S,--B),re){case 116:{(S[B++]!==114||S[B++]!==117||S[B++]!==101)&&k(S,--B),ae=!0;break}case 102:{(S[B++]!==97||S[B++]!==108||S[B++]!==115||S[B++]!==101)&&k(S,--B),ae=!1;break}case 110:{(S[B++]!==117||S[B++]!==108||S[B++]!==108)&&k(S,--B),ae=null;break}case 45:case 46:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:{let he=B;for(ae=b(re),re=S[B];;){switch(re){case 43:case 45:case 46:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 101:case 69:{ae+=b(re),re=S[++B];continue}}break}ae=+ae,isNaN(ae)&&k(S,--he,"Invalid number");break}case 34:{for(ae="";B>=K&&k(S,K),re=S[B++],re!==34;)if(re===92)switch(S[B++]){case 34:ae+='"';break;case 47:ae+="/";break;case 92:ae+="\\";break;case 98:ae+="\b";break;case 102:ae+="\f";break;case 110:ae+=`
7
- `;break;case 114:ae+="\r";break;case 116:ae+=" ";break;case 117:{let he=0;for(let Be=0;Be<4;Be++)re=S[B++],he<<=4,re>=48&&re<=57?he|=re-48:re>=97&&re<=102?he|=re+-87:re>=65&&re<=70?he|=re+-55:k(S,--B);ae+=b(he);break}default:k(S,--B);break}else if(re<=127)ae+=b(re);else if((re&224)===192)ae+=b((re&31)<<6|S[B++]&63);else if((re&240)===224)ae+=b((re&15)<<12|(S[B++]&63)<<6|S[B++]&63);else if((re&248)==240){let he=(re&7)<<18|(S[B++]&63)<<12|(S[B++]&63)<<6|S[B++]&63;he>65535&&(he-=65536,ae+=b(he>>10&1023|55296),he=56320|he&1023),ae+=b(he)}ae[0];break}case 91:{ae=[],A.push($),I.push(se),U.push(H),$=null,se=ae,H=1;continue}case 123:{ae={},A.push($),I.push(se),U.push(H),$=null,se=ae,H=2;continue}case 93:{H!==1&&k(S,--B),ae=se,$=A.pop(),se=I.pop(),H=U.pop();break}case 125:{H!==2&&k(S,--B),ae=se,$=A.pop(),se=I.pop(),H=U.pop();break}default:k(S,--B)}for(re=S[B];re<=32;)re=S[++B];switch(H){case 0:{if(B===K)return ae;break}case 1:{if(se.push(ae),re===44){B++;continue}if(re===93)continue;break}case 2:{if($===null){if($=ae,re===58){B++;continue}}else{if(se[$]=ae,$=null,re===44){B++;continue}if(re===125)continue}break}}break}k(S,B)}var x=JSON.stringify,v="warning",M="silent";function C(S,A){let I=[];for(let U of S){if(bt(U,A),U.indexOf(",")>=0)throw new Error(`Invalid ${A}: ${U}`);I.push(U)}return I.join(",")}var _=()=>null,F=S=>typeof S=="boolean"?null:"a boolean",E=S=>typeof S=="string"?null:"a string",O=S=>S instanceof RegExp?null:"a RegExp object",Q=S=>typeof S=="number"&&S===(S|0)?null:"an integer",ye=S=>typeof S=="number"&&S===(S|0)&&S>=0&&S<=65535?null:"a valid port number",Z=S=>typeof S=="function"?null:"a function",ee=S=>Array.isArray(S)?null:"an array",ve=S=>Array.isArray(S)&&S.every(A=>typeof A=="string")?null:"an array of strings",Re=S=>typeof S=="object"&&S!==null&&!Array.isArray(S)?null:"an object",et=S=>typeof S=="object"&&S!==null?null:"an array or an object",Ra=S=>S instanceof WebAssembly.Module?null:"a WebAssembly.Module",Kd=S=>typeof S=="object"&&!Array.isArray(S)?null:"an object or null",jd=S=>typeof S=="string"||typeof S=="boolean"?null:"a string or a boolean",Z0=S=>typeof S=="string"||typeof S=="object"&&S!==null&&!Array.isArray(S)?null:"a string or an object",$d=S=>typeof S=="string"||Array.isArray(S)&&S.every(A=>typeof A=="string")?null:"a string or an array of strings",Xd=S=>typeof S=="string"||S instanceof Uint8Array?null:"a string or a Uint8Array",J0=S=>typeof S=="string"||S instanceof URL?null:"a string or a URL";function R(S,A,I,U){let K=S[I];if(A[I+""]=!0,K===void 0)return;let $=U(K);if($!==null)throw new Error(`${x(I)} must be ${$}`);return K}function tt(S,A,I){for(let U in S)if(!(U in A))throw new Error(`Invalid option ${I}: ${x(U)}`)}function ey(S){let A=Object.create(null),I=R(S,A,"wasmURL",J0),U=R(S,A,"wasmModule",Ra),K=R(S,A,"worker",F);return tt(S,A,"in initialize() call"),{wasmURL:I,wasmModule:U,worker:K}}function Qd(S){let A;if(S!==void 0){A=Object.create(null);for(let I in S){let U=S[I];if(typeof U=="string"||U===!1)A[I]=U;else throw new Error(`Expected ${x(I)} in mangle cache to map to either a string or false`)}}return A}function Ba(S,A,I,U,K){let $=R(A,I,"color",F),H=R(A,I,"logLevel",E),se=R(A,I,"logLimit",Q),B=R(A,I,"logStyle",E);$!==void 0?S.push(`--color=${$}`):U&&S.push("--color=true"),S.push(`--log-level=${H||K}`),S.push(`--log-limit=${se||0}`),B&&S.push(`--log-style=${B}`)}function bt(S,A,I){if(typeof S!="string")throw new Error(`Expected value for ${A}${I!==void 0?" "+x(I):""} to be a string, got ${typeof S} instead`);return S}function Yd(S,A,I){let U=R(A,I,"legalComments",E),K=R(A,I,"sourceRoot",E),$=R(A,I,"sourcesContent",F),H=R(A,I,"target",$d),se=R(A,I,"format",E),B=R(A,I,"globalName",E),re=R(A,I,"mangleProps",O),ae=R(A,I,"reserveProps",O),he=R(A,I,"mangleQuoted",F),Be=R(A,I,"minify",F),Ee=R(A,I,"minifySyntax",F),Le=R(A,I,"minifyWhitespace",F),Ue=R(A,I,"minifyIdentifiers",F),ge=R(A,I,"lineLimit",Q),Qe=R(A,I,"drop",ve),pe=R(A,I,"dropLabels",ve),me=R(A,I,"charset",E),J=R(A,I,"treeShaking",F),q=R(A,I,"ignoreAnnotations",F),D=R(A,I,"jsx",E),V=R(A,I,"jsxFactory",E),W=R(A,I,"jsxFragment",E),te=R(A,I,"jsxImportSource",E),le=R(A,I,"jsxDev",F),z=R(A,I,"jsxSideEffects",F),X=R(A,I,"define",Re),oe=R(A,I,"logOverride",Re),Te=R(A,I,"supported",Re),P=R(A,I,"pure",ve),L=R(A,I,"keepNames",F),ne=R(A,I,"platform",E),fe=R(A,I,"tsconfigRaw",Z0),Me=R(A,I,"absPaths",ve);if(U&&S.push(`--legal-comments=${U}`),K!==void 0&&S.push(`--source-root=${K}`),$!==void 0&&S.push(`--sources-content=${$}`),H&&S.push(`--target=${C(Array.isArray(H)?H:[H],"target")}`),se&&S.push(`--format=${se}`),B&&S.push(`--global-name=${B}`),ne&&S.push(`--platform=${ne}`),fe&&S.push(`--tsconfig-raw=${typeof fe=="string"?fe:JSON.stringify(fe)}`),Be&&S.push("--minify"),Ee&&S.push("--minify-syntax"),Le&&S.push("--minify-whitespace"),Ue&&S.push("--minify-identifiers"),ge&&S.push(`--line-limit=${ge}`),me&&S.push(`--charset=${me}`),J!==void 0&&S.push(`--tree-shaking=${J}`),q&&S.push("--ignore-annotations"),Qe)for(let de of Qe)S.push(`--drop:${bt(de,"drop")}`);if(pe&&S.push(`--drop-labels=${C(pe,"drop label")}`),Me&&S.push(`--abs-paths=${C(Me,"abs paths")}`),re&&S.push(`--mangle-props=${La(re)}`),ae&&S.push(`--reserve-props=${La(ae)}`),he!==void 0&&S.push(`--mangle-quoted=${he}`),D&&S.push(`--jsx=${D}`),V&&S.push(`--jsx-factory=${V}`),W&&S.push(`--jsx-fragment=${W}`),te&&S.push(`--jsx-import-source=${te}`),le&&S.push("--jsx-dev"),z&&S.push("--jsx-side-effects"),X)for(let de in X){if(de.indexOf("=")>=0)throw new Error(`Invalid define: ${de}`);S.push(`--define:${de}=${bt(X[de],"define",de)}`)}if(oe)for(let de in oe){if(de.indexOf("=")>=0)throw new Error(`Invalid log override: ${de}`);S.push(`--log-override:${de}=${bt(oe[de],"log override",de)}`)}if(Te)for(let de in Te){if(de.indexOf("=")>=0)throw new Error(`Invalid supported: ${de}`);let Ne=Te[de];if(typeof Ne!="boolean")throw new Error(`Expected value for supported ${x(de)} to be a boolean, got ${typeof Ne} instead`);S.push(`--supported:${de}=${Ne}`)}if(P)for(let de of P)S.push(`--pure:${bt(de,"pure")}`);L&&S.push("--keep-names")}function ty(S,A,I,U,K){var $;let H=[],se=[],B=Object.create(null),re=null,ae=null;Ba(H,A,B,I,U),Yd(H,A,B);let he=R(A,B,"sourcemap",jd),Be=R(A,B,"bundle",F),Ee=R(A,B,"splitting",F),Le=R(A,B,"preserveSymlinks",F),Ue=R(A,B,"metafile",F),ge=R(A,B,"outfile",E),Qe=R(A,B,"outdir",E),pe=R(A,B,"outbase",E),me=R(A,B,"tsconfig",E),J=R(A,B,"resolveExtensions",ve),q=R(A,B,"nodePaths",ve),D=R(A,B,"mainFields",ve),V=R(A,B,"conditions",ve),W=R(A,B,"external",ve),te=R(A,B,"packages",E),le=R(A,B,"alias",Re),z=R(A,B,"loader",Re),X=R(A,B,"outExtension",Re),oe=R(A,B,"publicPath",E),Te=R(A,B,"entryNames",E),P=R(A,B,"chunkNames",E),L=R(A,B,"assetNames",E),ne=R(A,B,"inject",ve),fe=R(A,B,"banner",Re),Me=R(A,B,"footer",Re),de=R(A,B,"entryPoints",et),Ne=R(A,B,"absWorkingDir",E),De=R(A,B,"stdin",Re),Fe=($=R(A,B,"write",F))!=null?$:K,kt=R(A,B,"allowOverwrite",F),rt=R(A,B,"mangleCache",Re);if(B.plugins=!0,tt(A,B,`in ${S}() call`),he&&H.push(`--sourcemap${he===!0?"":`=${he}`}`),Be&&H.push("--bundle"),kt&&H.push("--allow-overwrite"),Ee&&H.push("--splitting"),Le&&H.push("--preserve-symlinks"),Ue&&H.push("--metafile"),ge&&H.push(`--outfile=${ge}`),Qe&&H.push(`--outdir=${Qe}`),pe&&H.push(`--outbase=${pe}`),me&&H.push(`--tsconfig=${me}`),te&&H.push(`--packages=${te}`),J&&H.push(`--resolve-extensions=${C(J,"resolve extension")}`),oe&&H.push(`--public-path=${oe}`),Te&&H.push(`--entry-names=${Te}`),P&&H.push(`--chunk-names=${P}`),L&&H.push(`--asset-names=${L}`),D&&H.push(`--main-fields=${C(D,"main field")}`),V&&H.push(`--conditions=${C(V,"condition")}`),W)for(let ke of W)H.push(`--external:${bt(ke,"external")}`);if(le)for(let ke in le){if(ke.indexOf("=")>=0)throw new Error(`Invalid package name in alias: ${ke}`);H.push(`--alias:${ke}=${bt(le[ke],"alias",ke)}`)}if(fe)for(let ke in fe){if(ke.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${ke}`);H.push(`--banner:${ke}=${bt(fe[ke],"banner",ke)}`)}if(Me)for(let ke in Me){if(ke.indexOf("=")>=0)throw new Error(`Invalid footer file type: ${ke}`);H.push(`--footer:${ke}=${bt(Me[ke],"footer",ke)}`)}if(ne)for(let ke of ne)H.push(`--inject:${bt(ke,"inject")}`);if(z)for(let ke in z){if(ke.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${ke}`);H.push(`--loader:${ke}=${bt(z[ke],"loader",ke)}`)}if(X)for(let ke in X){if(ke.indexOf("=")>=0)throw new Error(`Invalid out extension: ${ke}`);H.push(`--out-extension:${ke}=${bt(X[ke],"out extension",ke)}`)}if(de)if(Array.isArray(de))for(let ke=0,kr=de.length;ke<kr;ke++){let Ut=de[ke];if(typeof Ut=="object"&&Ut!==null){let or=Object.create(null),Sr=R(Ut,or,"in",E),Nt=R(Ut,or,"out",E);if(tt(Ut,or,"in entry point at index "+ke),Sr===void 0)throw new Error('Missing property "in" for entry point at index '+ke);if(Nt===void 0)throw new Error('Missing property "out" for entry point at index '+ke);se.push([Nt,Sr])}else se.push(["",bt(Ut,"entry point at index "+ke)])}else for(let ke in de)se.push([ke,bt(de[ke],"entry point",ke)]);if(De){let ke=Object.create(null),kr=R(De,ke,"contents",Xd),Ut=R(De,ke,"resolveDir",E),or=R(De,ke,"sourcefile",E),Sr=R(De,ke,"loader",E);tt(De,ke,'in "stdin" object'),or&&H.push(`--sourcefile=${or}`),Sr&&H.push(`--loader=${Sr}`),Ut&&(ae=Ut),typeof kr=="string"?re=f(kr):kr instanceof Uint8Array&&(re=kr)}let br=[];if(q)for(let ke of q)ke+="",br.push(ke);return{entries:se,flags:H,write:Fe,stdinContents:re,stdinResolveDir:ae,absWorkingDir:Ne,nodePaths:br,mangleCache:Qd(rt)}}function ry(S,A,I,U){let K=[],$=Object.create(null);Ba(K,A,$,I,U),Yd(K,A,$);let H=R(A,$,"sourcemap",jd),se=R(A,$,"sourcefile",E),B=R(A,$,"loader",E),re=R(A,$,"banner",E),ae=R(A,$,"footer",E),he=R(A,$,"mangleCache",Re);return tt(A,$,`in ${S}() call`),H&&K.push(`--sourcemap=${H===!0?"external":H}`),se&&K.push(`--sourcefile=${se}`),B&&K.push(`--loader=${B}`),re&&K.push(`--banner=${re}`),ae&&K.push(`--footer=${ae}`),{flags:K,mangleCache:Qd(he)}}function ny(S){let A={},I={didClose:!1,reason:""},U={},K=0,$=0,H=new Uint8Array(16*1024),se=0,B=me=>{let J=se+me.length;if(J>H.length){let D=new Uint8Array(J*2);D.set(H),H=D}H.set(me,se),se+=me.length;let q=0;for(;q+4<=se;){let D=g(H,q);if(q+4+D>se)break;q+=4,Le(H.subarray(q,q+D)),q+=D}q>0&&(H.copyWithin(0,q,se),se-=q)},re=me=>{I.didClose=!0,me&&(I.reason=": "+(me.message||me));let J="The service was stopped"+I.reason;for(let q in U)U[q](J,null);U={}},ae=(me,J,q)=>{if(I.didClose)return q("The service is no longer running"+I.reason,null);let D=K++;U[D]=(V,W)=>{try{q(V,W)}finally{me&&me.unref()}},me&&me.ref(),S.writeToStdin(u({id:D,isRequest:!0,value:J}))},he=(me,J)=>{if(I.didClose)throw new Error("The service is no longer running"+I.reason);S.writeToStdin(u({id:me,isRequest:!1,value:J}))},Be=(me,J)=>c(null,null,function*(){try{if(J.command==="ping"){he(me,{});return}if(typeof J.key=="number"){let q=A[J.key];if(!q)return;let D=q[J.command];if(D){yield D(me,J);return}}throw new Error("Invalid command: "+J.command)}catch(q){let D=[Tn(q,S,null,void 0,"")];try{he(me,{errors:D})}catch{}}}),Ee=!0,Le=me=>{if(Ee){Ee=!1;let q=String.fromCharCode(...me);if(q!=="0.28.2")throw new Error(`Cannot start service: Host version "0.28.2" does not match binary version ${x(q)}`);return}let J=d(me);if(J.isRequest)Be(J.id,J.value);else{let q=U[J.id];delete U[J.id],J.value.error?q(J.value.error,{}):q(null,J.value)}};return{readFromStdout:B,afterClose:re,service:{buildOrContext:({callName:me,refs:J,options:q,isTTY:D,defaultWD:V,callback:W})=>{let te=0,le=$++,z={},X={ref(){++te===1&&J&&J.ref()},unref(){--te===0&&(delete A[le],J&&J.unref())}};A[le]=z,X.ref(),iy(me,le,ae,he,X,S,z,q,D,V,(oe,Te)=>{try{W(oe,Te)}finally{X.unref()}})},transform:({callName:me,refs:J,input:q,options:D,isTTY:V,fs:W,callback:te})=>{let le=Zd(),z=X=>{try{if(typeof q!="string"&&!(q instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:oe,mangleCache:Te}=ry(me,D,V,M),P={command:"transform",flags:oe,inputFS:X!==null,input:X!==null?f(X):typeof q=="string"?f(q):q};Te&&(P.mangleCache=Te),ae(J,P,(L,ne)=>{if(L)return te(new Error(L),null);let fe=ii(ne.errors,le),Me=ii(ne.warnings,le),de=1,Ne=()=>{if(--de===0){let De={warnings:Me,code:ne.code,map:ne.map,mangleCache:void 0,legalComments:void 0};"legalComments"in ne&&(De.legalComments=ne?.legalComments),ne.mangleCache&&(De.mangleCache=ne?.mangleCache),te(null,De)}};if(fe.length>0)return te(ks("Transform failed",fe,Me),null);ne.codeFS&&(de++,W.readFile(ne.code,(De,Fe)=>{De!==null?te(De,null):(ne.code=Fe,Ne())})),ne.mapFS&&(de++,W.readFile(ne.map,(De,Fe)=>{De!==null?te(De,null):(ne.map=Fe,Ne())})),Ne()})}catch(oe){let Te=[];try{Ba(Te,D,{},V,M)}catch{}let P=Tn(oe,S,le,void 0,"");ae(J,{command:"error",flags:Te,error:P},()=>{P.detail=le.load(P.detail),te(ks("Transform failed",[P],[]),null)})}};if((typeof q=="string"||q instanceof Uint8Array)&&q.length>1024*1024){let X=z;z=()=>W.writeFile(q,X)}z(null)},formatMessages:({callName:me,refs:J,messages:q,options:D,callback:V})=>{if(!D)throw new Error(`Missing second argument in ${me}() call`);let W={},te=R(D,W,"kind",E),le=R(D,W,"color",F),z=R(D,W,"terminalWidth",Q),X=R(D,W,"logStyle",E);if(tt(D,W,`in ${me}() call`),te===void 0)throw new Error(`Missing "kind" in ${me}() call`);if(te!=="error"&&te!=="warning")throw new Error(`Expected "kind" to be "error" or "warning" in ${me}() call`);let oe={command:"format-msgs",messages:wr(q,"messages",null,"",z),isWarning:te==="warning"};le!==void 0&&(oe.color=le),z!==void 0&&(oe.terminalWidth=z),X!==void 0&&(oe.logStyle=X),ae(J,oe,(Te,P)=>{if(Te)return V(new Error(Te),null);V(null,P.messages)})},analyzeMetafile:({callName:me,refs:J,metafile:q,options:D,callback:V})=>{D===void 0&&(D={});let W={},te=R(D,W,"color",F),le=R(D,W,"verbose",F);tt(D,W,`in ${me}() call`);let z={command:"analyze-metafile",metafile:q};te!==void 0&&(z.color=te),le!==void 0&&(z.verbose=le),ae(J,z,(X,oe)=>{if(X)return V(new Error(X),null);V(null,oe.result)})}}}}function iy(S,A,I,U,K,$,H,se,B,re,ae){let he=Zd(),Be=S==="context",Ee=(ge,Qe)=>{let pe=[];try{Ba(pe,se,{},B,v)}catch{}let me=Tn(ge,$,he,void 0,Qe);I(K,{command:"error",flags:pe,error:me},()=>{me.detail=he.load(me.detail),ae(ks(Be?"Context failed":"Build failed",[me],[]),null)})},Le;if(typeof se=="object"){let ge=se.plugins;if(ge!==void 0){if(!Array.isArray(ge))return Ee(new Error('"plugins" must be an array'),"");Le=ge}}if(Le&&Le.length>0){if($.isSync)return Ee(new Error("Cannot use plugins in synchronous API calls"),"");sy(A,I,U,K,$,H,se,Le,he).then(ge=>{if(!ge.ok)return Ee(ge.error,ge.pluginName);try{Ue(ge.requestPlugins,ge.runOnEndCallbacks,ge.scheduleOnDisposeCallbacks)}catch(Qe){Ee(Qe,"")}},ge=>Ee(ge,""));return}try{Ue(null,(ge,Qe)=>Qe([],[]),()=>{})}catch(ge){Ee(ge,"")}function Ue(ge,Qe,pe){let me=$.hasFS,{entries:J,flags:q,write:D,stdinContents:V,stdinResolveDir:W,absWorkingDir:te,nodePaths:le,mangleCache:z}=ty(S,se,B,v,me);if(D&&!$.hasFS)throw new Error('The "write" option is unavailable in this environment');let X={command:"build",key:A,entries:J,flags:q,write:D,stdinContents:V,stdinResolveDir:W,absWorkingDir:te||re,nodePaths:le,context:Be};ge&&(X.plugins=ge),z&&(X.mangleCache=z);let oe=(L,ne)=>{let fe={errors:ii(L.errors,he),warnings:ii(L.warnings,he),outputFiles:void 0,metafile:void 0,mangleCache:void 0},Me=fe.errors.slice(),de=fe.warnings.slice();L.outputFiles&&(fe.outputFiles=L.outputFiles.map(oy)),L.metafile&&L.metafile.length&&(fe.metafile=cy(L.metafile)),L.mangleCache&&(fe.mangleCache=L.mangleCache),L.writeToStdout!==void 0&&console.log(p(L.writeToStdout).replace(/\n$/,"")),Qe(fe,(Ne,De)=>{if(Me.length>0||Ne.length>0){let Fe=ks("Build failed",Me.concat(Ne),de.concat(De));return ne(Fe,null,Ne,De)}ne(null,fe,Ne,De)})},Te,P;Be&&(H["on-end"]=(L,ne)=>new Promise(fe=>{oe(ne,(Me,de,Ne,De)=>{let Fe={errors:Ne,warnings:De};P&&P(Me,de),Te=void 0,P=void 0,U(L,Fe),fe()})})),I(K,X,(L,ne)=>{if(L)return ae(new Error(L),null);if(!Be)return oe(ne,(de,Ne)=>(pe(),ae(de,Ne)));if(ne.errors.length>0)return ae(ks("Context failed",ne.errors,ne.warnings),null);let fe=!1,Me={rebuild:()=>(Te||(Te=new Promise((de,Ne)=>{let De;P=(kt,rt)=>{De||(De=()=>kt?Ne(kt):de(rt))};let Fe=()=>{I(K,{command:"rebuild",key:A},(rt,br)=>{rt?Ne(new Error(rt)):De?De():Fe()})};Fe()})),Te),watch:(de={})=>new Promise((Ne,De)=>{if(!$.hasFS)throw new Error('Cannot use the "watch" API in this environment');let Fe={},kt=R(de,Fe,"delay",Q);tt(de,Fe,"in watch() call");let rt={command:"watch",key:A};kt&&(rt.delay=kt),I(K,rt,br=>{br?De(new Error(br)):Ne(void 0)})}),serve:(de={})=>new Promise((Ne,De)=>{if(!$.hasFS)throw new Error('Cannot use the "serve" API in this environment');let Fe={},kt=R(de,Fe,"port",ye),rt=R(de,Fe,"host",E),br=R(de,Fe,"servedir",E),ke=R(de,Fe,"keyfile",E),kr=R(de,Fe,"certfile",E),Ut=R(de,Fe,"fallback",E),or=R(de,Fe,"cors",Re),Sr=R(de,Fe,"onRequest",Z);tt(de,Fe,"in serve() call");let Nt={command:"serve",key:A,onRequest:!!Sr};if(kt!==void 0&&(Nt.port=kt),rt!==void 0&&(Nt.host=rt),br!==void 0&&(Nt.servedir=br),ke!==void 0&&(Nt.keyfile=ke),kr!==void 0&&(Nt.certfile=kr),Ut!==void 0&&(Nt.fallback=Ut),or){let xs={},si=R(or,xs,"origin",$d);tt(or,xs,'on "cors" object'),Array.isArray(si)?Nt.corsOrigin=si:si!==void 0&&(Nt.corsOrigin=[si])}I(K,Nt,(xs,si)=>{if(xs)return De(new Error(xs));Sr&&(H["serve-request"]=(Ty,Ay)=>{Sr(Ay.args),U(Ty,{})}),Ne(si)})}),cancel:()=>new Promise(de=>{if(fe)return de();I(K,{command:"cancel",key:A},()=>{de()})}),dispose:()=>new Promise(de=>{if(fe)return de();fe=!0,I(K,{command:"dispose",key:A},()=>{de(),pe(),K.unref()})})};K.ref(),ae(null,Me)})}}var sy=(S,A,I,U,K,$,H,se,B)=>c(null,null,function*(){let re=[],ae=[],he={},Be={},Ee=[],Le=0,Ue=0,ge=[],Qe=!1;se=[...se];for(let J of se){let q={};if(typeof J!="object")throw new Error(`Plugin at index ${Ue} must be an object`);let D=R(J,q,"name",E);if(typeof D!="string"||D==="")throw new Error(`Plugin at index ${Ue} is missing a name`);try{let V=R(J,q,"setup",Z);if(typeof V!="function")throw new Error("Plugin is missing a setup function");tt(J,q,`on plugin ${x(D)}`);let W={name:D,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};Ue++;let le=V({initialOptions:H,resolve:(z,X={})=>{if(!Qe)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof z!="string")throw new Error("The path to resolve must be a string");let oe=Object.create(null),Te=R(X,oe,"pluginName",E),P=R(X,oe,"importer",E),L=R(X,oe,"namespace",E),ne=R(X,oe,"resolveDir",E),fe=R(X,oe,"kind",E),Me=R(X,oe,"pluginData",_),de=R(X,oe,"with",Re);return tt(X,oe,"in resolve() call"),new Promise((Ne,De)=>{let Fe={command:"resolve",path:z,key:S,pluginName:D};if(Te!=null&&(Fe.pluginName=Te),P!=null&&(Fe.importer=P),L!=null&&(Fe.namespace=L),ne!=null&&(Fe.resolveDir=ne),fe!=null)Fe.kind=fe;else throw new Error('Must specify "kind" when calling "resolve"');Me!=null&&(Fe.pluginData=B.store(Me)),de!=null&&(Fe.with=ay(de,"with")),A(U,Fe,(kt,rt)=>{kt!==null?De(new Error(kt)):Ne({errors:ii(rt.errors,B),warnings:ii(rt.warnings,B),path:rt.path,external:rt.external,sideEffects:rt.sideEffects,namespace:rt.namespace,suffix:rt.suffix,pluginData:B.load(rt.pluginData)})})})},onStart(z){let X='This error came from the "onStart" callback registered here:',oe=Da(new Error(X),K,"onStart");re.push({name:D,callback:z,note:oe}),W.onStart=!0},onEnd(z){let X='This error came from the "onEnd" callback registered here:',oe=Da(new Error(X),K,"onEnd");ae.push({name:D,callback:z,note:oe}),W.onEnd=!0},onResolve(z,X){let oe='This error came from the "onResolve" callback registered here:',Te=Da(new Error(oe),K,"onResolve"),P={},L=R(z,P,"filter",O),ne=R(z,P,"namespace",E);if(tt(z,P,`in onResolve() call for plugin ${x(D)}`),L==null)throw new Error("onResolve() call is missing a filter");let fe=Le++;he[fe]={name:D,callback:X,note:Te},W.onResolve.push({id:fe,filter:La(L),namespace:ne||""})},onLoad(z,X){let oe='This error came from the "onLoad" callback registered here:',Te=Da(new Error(oe),K,"onLoad"),P={},L=R(z,P,"filter",O),ne=R(z,P,"namespace",E);if(tt(z,P,`in onLoad() call for plugin ${x(D)}`),L==null)throw new Error("onLoad() call is missing a filter");let fe=Le++;Be[fe]={name:D,callback:X,note:Te},W.onLoad.push({id:fe,filter:La(L),namespace:ne||""})},onDispose(z){Ee.push(z)},esbuild:K.esbuild});le&&(yield le),ge.push(W)}catch(V){return{ok:!1,error:V,pluginName:D}}}$["on-start"]=(J,q)=>c(null,null,function*(){B.clear();let D={errors:[],warnings:[]};yield Promise.all(re.map(V=>c(null,[V],function*({name:W,callback:te,note:le}){try{let z=yield te();if(z!=null){if(typeof z!="object")throw new Error(`Expected onStart() callback in plugin ${x(W)} to return an object`);let X={},oe=R(z,X,"errors",ee),Te=R(z,X,"warnings",ee);tt(z,X,`from onStart() callback in plugin ${x(W)}`),oe!=null&&D.errors.push(...wr(oe,"errors",B,W,void 0)),Te!=null&&D.warnings.push(...wr(Te,"warnings",B,W,void 0))}}catch(z){D.errors.push(Tn(z,K,B,le&&le(),W))}}))),I(J,D)}),$["on-resolve"]=(J,q)=>c(null,null,function*(){let D={},V="",W,te;for(let le of q.ids)try{({name:V,callback:W,note:te}=he[le]);let z=yield W({path:q.path,importer:q.importer,namespace:q.namespace,resolveDir:q.resolveDir,kind:q.kind,pluginData:B.load(q.pluginData),with:q.with});if(z!=null){if(typeof z!="object")throw new Error(`Expected onResolve() callback in plugin ${x(V)} to return an object`);let X={},oe=R(z,X,"pluginName",E),Te=R(z,X,"path",E),P=R(z,X,"namespace",E),L=R(z,X,"suffix",E),ne=R(z,X,"external",F),fe=R(z,X,"sideEffects",F),Me=R(z,X,"pluginData",_),de=R(z,X,"errors",ee),Ne=R(z,X,"warnings",ee),De=R(z,X,"watchFiles",ve),Fe=R(z,X,"watchDirs",ve);tt(z,X,`from onResolve() callback in plugin ${x(V)}`),D.id=le,oe!=null&&(D.pluginName=oe),Te!=null&&(D.path=Te),P!=null&&(D.namespace=P),L!=null&&(D.suffix=L),ne!=null&&(D.external=ne),fe!=null&&(D.sideEffects=fe),Me!=null&&(D.pluginData=B.store(Me)),de!=null&&(D.errors=wr(de,"errors",B,V,void 0)),Ne!=null&&(D.warnings=wr(Ne,"warnings",B,V,void 0)),De!=null&&(D.watchFiles=Oa(De,"watchFiles")),Fe!=null&&(D.watchDirs=Oa(Fe,"watchDirs"));break}}catch(z){D={id:le,errors:[Tn(z,K,B,te&&te(),V)]};break}I(J,D)}),$["on-load"]=(J,q)=>c(null,null,function*(){let D={},V="",W,te;for(let le of q.ids)try{({name:V,callback:W,note:te}=Be[le]);let z=yield W({path:q.path,namespace:q.namespace,suffix:q.suffix,pluginData:B.load(q.pluginData),with:q.with});if(z!=null){if(typeof z!="object")throw new Error(`Expected onLoad() callback in plugin ${x(V)} to return an object`);let X={},oe=R(z,X,"pluginName",E),Te=R(z,X,"contents",Xd),P=R(z,X,"resolveDir",E),L=R(z,X,"pluginData",_),ne=R(z,X,"loader",E),fe=R(z,X,"errors",ee),Me=R(z,X,"warnings",ee),de=R(z,X,"watchFiles",ve),Ne=R(z,X,"watchDirs",ve);tt(z,X,`from onLoad() callback in plugin ${x(V)}`),D.id=le,oe!=null&&(D.pluginName=oe),Te instanceof Uint8Array?D.contents=Te:Te!=null&&(D.contents=f(Te)),P!=null&&(D.resolveDir=P),L!=null&&(D.pluginData=B.store(L)),ne!=null&&(D.loader=ne),fe!=null&&(D.errors=wr(fe,"errors",B,V,void 0)),Me!=null&&(D.warnings=wr(Me,"warnings",B,V,void 0)),de!=null&&(D.watchFiles=Oa(de,"watchFiles")),Ne!=null&&(D.watchDirs=Oa(Ne,"watchDirs"));break}}catch(z){D={id:le,errors:[Tn(z,K,B,te&&te(),V)]};break}I(J,D)});let pe=(J,q)=>q([],[]);ae.length>0&&(pe=(J,q)=>{c(null,null,function*(){let D=[],V=[];for(let{name:W,callback:te,note:le}of ae){let z,X;try{let oe=yield te(J);if(oe!=null){if(typeof oe!="object")throw new Error(`Expected onEnd() callback in plugin ${x(W)} to return an object`);let Te={},P=R(oe,Te,"errors",ee),L=R(oe,Te,"warnings",ee);tt(oe,Te,`from onEnd() callback in plugin ${x(W)}`),P!=null&&(z=wr(P,"errors",B,W,void 0)),L!=null&&(X=wr(L,"warnings",B,W,void 0))}}catch(oe){z=[Tn(oe,K,B,le&&le(),W)]}if(z){D.push(...z);try{J.errors.push(...z)}catch{}}if(X){V.push(...X);try{J.warnings.push(...X)}catch{}}}q(D,V)})});let me=()=>{for(let J of Ee)setTimeout(()=>J(),0)};return Qe=!0,{ok:!0,requestPlugins:ge,runOnEndCallbacks:pe,scheduleOnDisposeCallbacks:me}});function Zd(){let S=new Map,A=0;return{clear(){S.clear()},load(I){return S.get(I)},store(I){if(I===void 0)return-1;let U=A++;return S.set(U,I),U}}}function Da(S,A,I){let U,K=!1;return()=>{if(K)return U;K=!0;try{let $=(S.stack+"").split(`
8
- `);$.splice(1,1);let H=Jd(A,$,I);if(H)return U={text:S.message,location:H},U}catch{}}}function Tn(S,A,I,U,K){let $="Internal error",H=null;try{$=(S&&S.message||S)+""}catch{}try{H=Jd(A,(S.stack+"").split(`
9
- `),"")}catch{}return{id:"",pluginName:K,text:$,location:H,notes:U?[U]:[],detail:I?I.store(S):-1}}function Jd(S,A,I){let U=" at ";if(S.readFileSync&&!A[0].startsWith(U)&&A[1].startsWith(U))for(let K=1;K<A.length;K++){let $=A[K];if($.startsWith(U))for($=$.slice(U.length);;){let H=/^(?:new |async )?\S+ \((.*)\)$/.exec($);if(H){$=H[1];continue}if(H=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec($),H){$=H[1];continue}if(H=/^(\S+):(\d+):(\d+)$/.exec($),H){let se;try{se=S.readFileSync(H[1],"utf8")}catch{break}let B=se.split(/\r\n|\r|\n|\u2028|\u2029/)[+H[2]-1]||"",re=+H[3]-1,ae=B.slice(re,re+I.length)===I?I.length:0;return{file:H[1],namespace:"file",line:+H[2],column:f(B.slice(0,re)).length,length:f(B.slice(re,re+ae)).length,lineText:B+`
10
- `+A.slice(1).join(`
11
- `),suggestion:""}}break}}return null}function ks(S,A,I){let U=5;S+=A.length<1?"":` with ${A.length} error${A.length<2?"":"s"}:`+A.slice(0,U+1).map(($,H)=>{if(H===U)return`
6
+ `);function R(h,m){return(h[m++]|h[m++]<<8|h[m++]<<16|h[m++]<<24)>>>0}function L(h,m,b){h[b++]=m,h[b++]=m>>8,h[b++]=m>>16,h[b++]=m>>24}var F=String.fromCharCode;function H(h,m,b){let S=h[m],O=1,$=0;for(let P=0;P<m;P++)h[P]===10?(O++,$=0):$++;throw new SyntaxError(b||(m===h.length?"Unexpected end of input while parsing JSON":S>=32&&S<=126?`Unexpected character ${F(S)} in JSON at position ${m} (line ${O}, column ${$})`:`Unexpected byte 0x${S.toString(16)} in JSON at position ${m} (line ${O}, column ${$})`))}function se(h){if(!(h instanceof Uint8Array))throw new Error("JSON input must be a Uint8Array");let m=[],b=[],S=[],O=h.length,$=null,P=0,V,x=0;for(;x<O;){let N=h[x++];if(N<=32)continue;let G;switch(P===2&&$===null&&N!==34&&N!==125&&H(h,--x),N){case 116:{(h[x++]!==114||h[x++]!==117||h[x++]!==101)&&H(h,--x),G=!0;break}case 102:{(h[x++]!==97||h[x++]!==108||h[x++]!==115||h[x++]!==101)&&H(h,--x),G=!1;break}case 110:{(h[x++]!==117||h[x++]!==108||h[x++]!==108)&&H(h,--x),G=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 Z=x;for(G=F(N),N=h[x];;){switch(N){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:{G+=F(N),N=h[++x];continue}}break}G=+G,isNaN(G)&&H(h,--Z,"Invalid number");break}case 34:{for(G="";x>=O&&H(h,O),N=h[x++],N!==34;)if(N===92)switch(h[x++]){case 34:G+='"';break;case 47:G+="/";break;case 92:G+="\\";break;case 98:G+="\b";break;case 102:G+="\f";break;case 110:G+=`
7
+ `;break;case 114:G+="\r";break;case 116:G+=" ";break;case 117:{let Z=0;for(let he=0;he<4;he++)N=h[x++],Z<<=4,N>=48&&N<=57?Z|=N-48:N>=97&&N<=102?Z|=N+-87:N>=65&&N<=70?Z|=N+-55:H(h,--x);G+=F(Z);break}default:H(h,--x);break}else if(N<=127)G+=F(N);else if((N&224)===192)G+=F((N&31)<<6|h[x++]&63);else if((N&240)===224)G+=F((N&15)<<12|(h[x++]&63)<<6|h[x++]&63);else if((N&248)==240){let Z=(N&7)<<18|(h[x++]&63)<<12|(h[x++]&63)<<6|h[x++]&63;Z>65535&&(Z-=65536,G+=F(Z>>10&1023|55296),Z=56320|Z&1023),G+=F(Z)}G[0];break}case 91:{G=[],m.push($),b.push(V),S.push(P),$=null,V=G,P=1;continue}case 123:{G={},m.push($),b.push(V),S.push(P),$=null,V=G,P=2;continue}case 93:{P!==1&&H(h,--x),G=V,$=m.pop(),V=b.pop(),P=S.pop();break}case 125:{P!==2&&H(h,--x),G=V,$=m.pop(),V=b.pop(),P=S.pop();break}default:H(h,--x)}for(N=h[x];N<=32;)N=h[++x];switch(P){case 0:{if(x===O)return G;break}case 1:{if(V.push(G),N===44){x++;continue}if(N===93)continue;break}case 2:{if($===null){if($=G,N===58){x++;continue}}else{if(V[$]=G,$=null,N===44){x++;continue}if(N===125)continue}break}}break}H(h,x)}var X=JSON.stringify,ye="warning",ve="silent";function q(h,m){let b=[];for(let S of h){if(Le(S,m),S.indexOf(",")>=0)throw new Error(`Invalid ${m}: ${S}`);b.push(S)}return b.join(",")}var oe=()=>null,K=h=>typeof h=="boolean"?null:"a boolean",B=h=>typeof h=="string"?null:"a string",xe=h=>h instanceof RegExp?null:"a RegExp object",we=h=>typeof h=="number"&&h===(h|0)?null:"an integer",Te=h=>typeof h=="number"&&h===(h|0)&&h>=0&&h<=65535?null:"a valid port number",Ue=h=>typeof h=="function"?null:"a function",ae=h=>Array.isArray(h)?null:"an array",Ae=h=>Array.isArray(h)&&h.every(m=>typeof m=="string")?null:"an array of strings",$e=h=>typeof h=="object"&&h!==null&&!Array.isArray(h)?null:"an object",Mt=h=>typeof h=="object"&&h!==null?null:"an array or an object",zn=h=>h instanceof WebAssembly.Module?null:"a WebAssembly.Module",Nt=h=>typeof h=="object"&&!Array.isArray(h)?null:"an object or null",Wt=h=>typeof h=="string"||typeof h=="boolean"?null:"a string or a boolean",Hn=h=>typeof h=="string"||typeof h=="object"&&h!==null&&!Array.isArray(h)?null:"a string or an object",_n=h=>typeof h=="string"||Array.isArray(h)&&h.every(m=>typeof m=="string")?null:"a string or an array of strings",pn=h=>typeof h=="string"||h instanceof Uint8Array?null:"a string or a Uint8Array",Kn=h=>typeof h=="string"||h instanceof URL?null:"a string or a URL";function v(h,m,b,S){let O=h[b];if(m[b+""]=!0,O===void 0)return;let $=S(O);if($!==null)throw new Error(`${X(b)} must be ${$}`);return O}function Pe(h,m,b){for(let S in h)if(!(S in m))throw new Error(`Invalid option ${b}: ${X(S)}`)}function Ma(h){let m=Object.create(null),b=v(h,m,"wasmURL",Kn),S=v(h,m,"wasmModule",zn),O=v(h,m,"worker",K);return Pe(h,m,"in initialize() call"),{wasmURL:b,wasmModule:S,worker:O}}function ns(h){let m;if(h!==void 0){m=Object.create(null);for(let b in h){let S=h[b];if(typeof S=="string"||S===!1)m[b]=S;else throw new Error(`Expected ${X(b)} in mangle cache to map to either a string or false`)}}return m}function mn(h,m,b,S,O){let $=v(m,b,"color",K),P=v(m,b,"logLevel",B),V=v(m,b,"logLimit",we),x=v(m,b,"logStyle",B);$!==void 0?h.push(`--color=${$}`):S&&h.push("--color=true"),h.push(`--log-level=${P||O}`),h.push(`--log-limit=${V||0}`),x&&h.push(`--log-style=${x}`)}function Le(h,m,b){if(typeof h!="string")throw new Error(`Expected value for ${m}${b!==void 0?" "+X(b):""} to be a string, got ${typeof h} instead`);return h}function rs(h,m,b){let S=v(m,b,"legalComments",B),O=v(m,b,"sourceRoot",B),$=v(m,b,"sourcesContent",K),P=v(m,b,"target",_n),V=v(m,b,"format",B),x=v(m,b,"globalName",B),N=v(m,b,"mangleProps",xe),G=v(m,b,"reserveProps",xe),Z=v(m,b,"mangleQuoted",K),he=v(m,b,"minify",K),ue=v(m,b,"minifySyntax",K),pe=v(m,b,"minifyWhitespace",K),me=v(m,b,"minifyIdentifiers",K),ne=v(m,b,"lineLimit",we),Ee=v(m,b,"drop",Ae),te=v(m,b,"dropLabels",Ae),ee=v(m,b,"charset",B),U=v(m,b,"treeShaking",K),C=v(m,b,"ignoreAnnotations",K),k=v(m,b,"jsx",B),T=v(m,b,"jsxFactory",B),I=v(m,b,"jsxFragment",B),j=v(m,b,"jsxImportSource",B),J=v(m,b,"jsxDev",K),E=v(m,b,"jsxSideEffects",K),D=v(m,b,"define",$e),z=v(m,b,"logOverride",$e),ie=v(m,b,"supported",$e),g=v(m,b,"pure",Ae),M=v(m,b,"keepNames",K),W=v(m,b,"platform",B),Q=v(m,b,"tsconfigRaw",Hn),fe=v(m,b,"absPaths",Ae);if(S&&h.push(`--legal-comments=${S}`),O!==void 0&&h.push(`--source-root=${O}`),$!==void 0&&h.push(`--sources-content=${$}`),P&&h.push(`--target=${q(Array.isArray(P)?P:[P],"target")}`),V&&h.push(`--format=${V}`),x&&h.push(`--global-name=${x}`),W&&h.push(`--platform=${W}`),Q&&h.push(`--tsconfig-raw=${typeof Q=="string"?Q:JSON.stringify(Q)}`),he&&h.push("--minify"),ue&&h.push("--minify-syntax"),pe&&h.push("--minify-whitespace"),me&&h.push("--minify-identifiers"),ne&&h.push(`--line-limit=${ne}`),ee&&h.push(`--charset=${ee}`),U!==void 0&&h.push(`--tree-shaking=${U}`),C&&h.push("--ignore-annotations"),Ee)for(let Y of Ee)h.push(`--drop:${Le(Y,"drop")}`);if(te&&h.push(`--drop-labels=${q(te,"drop label")}`),fe&&h.push(`--abs-paths=${q(fe,"abs paths")}`),N&&h.push(`--mangle-props=${wn(N)}`),G&&h.push(`--reserve-props=${wn(G)}`),Z!==void 0&&h.push(`--mangle-quoted=${Z}`),k&&h.push(`--jsx=${k}`),T&&h.push(`--jsx-factory=${T}`),I&&h.push(`--jsx-fragment=${I}`),j&&h.push(`--jsx-import-source=${j}`),J&&h.push("--jsx-dev"),E&&h.push("--jsx-side-effects"),D)for(let Y in D){if(Y.indexOf("=")>=0)throw new Error(`Invalid define: ${Y}`);h.push(`--define:${Y}=${Le(D[Y],"define",Y)}`)}if(z)for(let Y in z){if(Y.indexOf("=")>=0)throw new Error(`Invalid log override: ${Y}`);h.push(`--log-override:${Y}=${Le(z[Y],"log override",Y)}`)}if(ie)for(let Y in ie){if(Y.indexOf("=")>=0)throw new Error(`Invalid supported: ${Y}`);let ge=ie[Y];if(typeof ge!="boolean")throw new Error(`Expected value for supported ${X(Y)} to be a boolean, got ${typeof ge} instead`);h.push(`--supported:${Y}=${ge}`)}if(g)for(let Y of g)h.push(`--pure:${Le(Y,"pure")}`);M&&h.push("--keep-names")}function Sa(h,m,b,S,O){var $;let P=[],V=[],x=Object.create(null),N=null,G=null;mn(P,m,x,b,S),rs(P,m,x);let Z=v(m,x,"sourcemap",Wt),he=v(m,x,"bundle",K),ue=v(m,x,"splitting",K),pe=v(m,x,"preserveSymlinks",K),me=v(m,x,"metafile",K),ne=v(m,x,"outfile",B),Ee=v(m,x,"outdir",B),te=v(m,x,"outbase",B),ee=v(m,x,"tsconfig",B),U=v(m,x,"resolveExtensions",Ae),C=v(m,x,"nodePaths",Ae),k=v(m,x,"mainFields",Ae),T=v(m,x,"conditions",Ae),I=v(m,x,"external",Ae),j=v(m,x,"packages",B),J=v(m,x,"alias",$e),E=v(m,x,"loader",$e),D=v(m,x,"outExtension",$e),z=v(m,x,"publicPath",B),ie=v(m,x,"entryNames",B),g=v(m,x,"chunkNames",B),M=v(m,x,"assetNames",B),W=v(m,x,"inject",Ae),Q=v(m,x,"banner",$e),fe=v(m,x,"footer",$e),Y=v(m,x,"entryPoints",Mt),ge=v(m,x,"absWorkingDir",B),_e=v(m,x,"stdin",$e),de=($=v(m,x,"write",K))!=null?$:O,Fe=v(m,x,"allowOverwrite",K),Ie=v(m,x,"mangleCache",$e);if(x.plugins=!0,Pe(m,x,`in ${h}() call`),Z&&P.push(`--sourcemap${Z===!0?"":`=${Z}`}`),he&&P.push("--bundle"),Fe&&P.push("--allow-overwrite"),ue&&P.push("--splitting"),pe&&P.push("--preserve-symlinks"),me&&P.push("--metafile"),ne&&P.push(`--outfile=${ne}`),Ee&&P.push(`--outdir=${Ee}`),te&&P.push(`--outbase=${te}`),ee&&P.push(`--tsconfig=${ee}`),j&&P.push(`--packages=${j}`),U&&P.push(`--resolve-extensions=${q(U,"resolve extension")}`),z&&P.push(`--public-path=${z}`),ie&&P.push(`--entry-names=${ie}`),g&&P.push(`--chunk-names=${g}`),M&&P.push(`--asset-names=${M}`),k&&P.push(`--main-fields=${q(k,"main field")}`),T&&P.push(`--conditions=${q(T,"condition")}`),I)for(let re of I)P.push(`--external:${Le(re,"external")}`);if(J)for(let re in J){if(re.indexOf("=")>=0)throw new Error(`Invalid package name in alias: ${re}`);P.push(`--alias:${re}=${Le(J[re],"alias",re)}`)}if(Q)for(let re in Q){if(re.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${re}`);P.push(`--banner:${re}=${Le(Q[re],"banner",re)}`)}if(fe)for(let re in fe){if(re.indexOf("=")>=0)throw new Error(`Invalid footer file type: ${re}`);P.push(`--footer:${re}=${Le(fe[re],"footer",re)}`)}if(W)for(let re of W)P.push(`--inject:${Le(re,"inject")}`);if(E)for(let re in E){if(re.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${re}`);P.push(`--loader:${re}=${Le(E[re],"loader",re)}`)}if(D)for(let re in D){if(re.indexOf("=")>=0)throw new Error(`Invalid out extension: ${re}`);P.push(`--out-extension:${re}=${Le(D[re],"out extension",re)}`)}if(Y)if(Array.isArray(Y))for(let re=0,Je=Y.length;re<Je;re++){let je=Y[re];if(typeof je=="object"&&je!==null){let Ge=Object.create(null),Ye=v(je,Ge,"in",B),Ne=v(je,Ge,"out",B);if(Pe(je,Ge,"in entry point at index "+re),Ye===void 0)throw new Error('Missing property "in" for entry point at index '+re);if(Ne===void 0)throw new Error('Missing property "out" for entry point at index '+re);V.push([Ne,Ye])}else V.push(["",Le(je,"entry point at index "+re)])}else for(let re in Y)V.push([re,Le(Y[re],"entry point",re)]);if(_e){let re=Object.create(null),Je=v(_e,re,"contents",pn),je=v(_e,re,"resolveDir",B),Ge=v(_e,re,"sourcefile",B),Ye=v(_e,re,"loader",B);Pe(_e,re,'in "stdin" object'),Ge&&P.push(`--sourcefile=${Ge}`),Ye&&P.push(`--loader=${Ye}`),je&&(G=je),typeof Je=="string"?N=_(Je):Je instanceof Uint8Array&&(N=Je)}let qe=[];if(C)for(let re of C)re+="",qe.push(re);return{entries:V,flags:P,write:de,stdinContents:N,stdinResolveDir:G,absWorkingDir:ge,nodePaths:qe,mangleCache:ns(Ie)}}function Aa(h,m,b,S){let O=[],$=Object.create(null);mn(O,m,$,b,S),rs(O,m,$);let P=v(m,$,"sourcemap",Wt),V=v(m,$,"sourcefile",B),x=v(m,$,"loader",B),N=v(m,$,"banner",B),G=v(m,$,"footer",B),Z=v(m,$,"mangleCache",$e);return Pe(m,$,`in ${h}() call`),P&&O.push(`--sourcemap=${P===!0?"external":P}`),V&&O.push(`--sourcefile=${V}`),x&&O.push(`--loader=${x}`),N&&O.push(`--banner=${N}`),G&&O.push(`--footer=${G}`),{flags:O,mangleCache:ns(Z)}}function Ea(h){let m={},b={didClose:!1,reason:""},S={},O=0,$=0,P=new Uint8Array(16*1024),V=0,x=ee=>{let U=V+ee.length;if(U>P.length){let k=new Uint8Array(U*2);k.set(P),P=k}P.set(ee,V),V+=ee.length;let C=0;for(;C+4<=V;){let k=R(P,C);if(C+4+k>V)break;C+=4,pe(P.subarray(C,C+k)),C+=k}C>0&&(P.copyWithin(0,C,V),V-=C)},N=ee=>{b.didClose=!0,ee&&(b.reason=": "+(ee.message||ee));let U="The service was stopped"+b.reason;for(let C in S)S[C](U,null);S={}},G=(ee,U,C)=>{if(b.didClose)return C("The service is no longer running"+b.reason,null);let k=O++;S[k]=(T,I)=>{try{C(T,I)}finally{ee&&ee.unref()}},ee&&ee.ref(),h.writeToStdin(u({id:k,isRequest:!0,value:U}))},Z=(ee,U)=>{if(b.didClose)throw new Error("The service is no longer running"+b.reason);h.writeToStdin(u({id:ee,isRequest:!1,value:U}))},he=(ee,U)=>l(null,null,function*(){try{if(U.command==="ping"){Z(ee,{});return}if(typeof U.key=="number"){let C=m[U.key];if(!C)return;let k=C[U.command];if(k){yield k(ee,U);return}}throw new Error("Invalid command: "+U.command)}catch(C){let k=[lt(C,h,null,void 0,"")];try{Z(ee,{errors:k})}catch{}}}),ue=!0,pe=ee=>{if(ue){ue=!1;let C=String.fromCharCode(...ee);if(C!=="0.28.2")throw new Error(`Cannot start service: Host version "0.28.2" does not match binary version ${X(C)}`);return}let U=f(ee);if(U.isRequest)he(U.id,U.value);else{let C=S[U.id];delete S[U.id],U.value.error?C(U.value.error,{}):C(null,U.value)}};return{readFromStdout:x,afterClose:N,service:{buildOrContext:({callName:ee,refs:U,options:C,isTTY:k,defaultWD:T,callback:I})=>{let j=0,J=$++,E={},D={ref(){++j===1&&U&&U.ref()},unref(){--j===0&&(delete m[J],U&&U.unref())}};m[J]=E,D.ref(),Ta(ee,J,G,Z,D,h,E,C,k,T,(z,ie)=>{try{I(z,ie)}finally{D.unref()}})},transform:({callName:ee,refs:U,input:C,options:k,isTTY:T,fs:I,callback:j})=>{let J=ss(),E=D=>{try{if(typeof C!="string"&&!(C instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:z,mangleCache:ie}=Aa(ee,k,T,ve),g={command:"transform",flags:z,inputFS:D!==null,input:D!==null?_(D):typeof C=="string"?_(C):C};ie&&(g.mangleCache=ie),G(U,g,(M,W)=>{if(M)return j(new Error(M),null);let Q=St(W.errors,J),fe=St(W.warnings,J),Y=1,ge=()=>{if(--Y===0){let _e={warnings:fe,code:W.code,map:W.map,mangleCache:void 0,legalComments:void 0};"legalComments"in W&&(_e.legalComments=W?.legalComments),W.mangleCache&&(_e.mangleCache=W?.mangleCache),j(null,_e)}};if(Q.length>0)return j(Vt("Transform failed",Q,fe),null);W.codeFS&&(Y++,I.readFile(W.code,(_e,de)=>{_e!==null?j(_e,null):(W.code=de,ge())})),W.mapFS&&(Y++,I.readFile(W.map,(_e,de)=>{_e!==null?j(_e,null):(W.map=de,ge())})),ge()})}catch(z){let ie=[];try{mn(ie,k,{},T,ve)}catch{}let g=lt(z,h,J,void 0,"");G(U,{command:"error",flags:ie,error:g},()=>{g.detail=J.load(g.detail),j(Vt("Transform failed",[g],[]),null)})}};if((typeof C=="string"||C instanceof Uint8Array)&&C.length>1024*1024){let D=E;E=()=>I.writeFile(C,D)}E(null)},formatMessages:({callName:ee,refs:U,messages:C,options:k,callback:T})=>{if(!k)throw new Error(`Missing second argument in ${ee}() call`);let I={},j=v(k,I,"kind",B),J=v(k,I,"color",K),E=v(k,I,"terminalWidth",we),D=v(k,I,"logStyle",B);if(Pe(k,I,`in ${ee}() call`),j===void 0)throw new Error(`Missing "kind" in ${ee}() call`);if(j!=="error"&&j!=="warning")throw new Error(`Expected "kind" to be "error" or "warning" in ${ee}() call`);let z={command:"format-msgs",messages:Ke(C,"messages",null,"",E),isWarning:j==="warning"};J!==void 0&&(z.color=J),E!==void 0&&(z.terminalWidth=E),D!==void 0&&(z.logStyle=D),G(U,z,(ie,g)=>{if(ie)return T(new Error(ie),null);T(null,g.messages)})},analyzeMetafile:({callName:ee,refs:U,metafile:C,options:k,callback:T})=>{k===void 0&&(k={});let I={},j=v(k,I,"color",K),J=v(k,I,"verbose",K);Pe(k,I,`in ${ee}() call`);let E={command:"analyze-metafile",metafile:C};j!==void 0&&(E.color=j),J!==void 0&&(E.verbose=J),G(U,E,(D,z)=>{if(D)return T(new Error(D),null);T(null,z.result)})}}}}function Ta(h,m,b,S,O,$,P,V,x,N,G){let Z=ss(),he=h==="context",ue=(ne,Ee)=>{let te=[];try{mn(te,V,{},x,ye)}catch{}let ee=lt(ne,$,Z,void 0,Ee);b(O,{command:"error",flags:te,error:ee},()=>{ee.detail=Z.load(ee.detail),G(Vt(he?"Context failed":"Build failed",[ee],[]),null)})},pe;if(typeof V=="object"){let ne=V.plugins;if(ne!==void 0){if(!Array.isArray(ne))return ue(new Error('"plugins" must be an array'),"");pe=ne}}if(pe&&pe.length>0){if($.isSync)return ue(new Error("Cannot use plugins in synchronous API calls"),"");Pa(m,b,S,O,$,P,V,pe,Z).then(ne=>{if(!ne.ok)return ue(ne.error,ne.pluginName);try{me(ne.requestPlugins,ne.runOnEndCallbacks,ne.scheduleOnDisposeCallbacks)}catch(Ee){ue(Ee,"")}},ne=>ue(ne,""));return}try{me(null,(ne,Ee)=>Ee([],[]),()=>{})}catch(ne){ue(ne,"")}function me(ne,Ee,te){let ee=$.hasFS,{entries:U,flags:C,write:k,stdinContents:T,stdinResolveDir:I,absWorkingDir:j,nodePaths:J,mangleCache:E}=Sa(h,V,x,ye,ee);if(k&&!$.hasFS)throw new Error('The "write" option is unavailable in this environment');let D={command:"build",key:m,entries:U,flags:C,write:k,stdinContents:T,stdinResolveDir:I,absWorkingDir:j||N,nodePaths:J,context:he};ne&&(D.plugins=ne),E&&(D.mangleCache=E);let z=(M,W)=>{let Q={errors:St(M.errors,Z),warnings:St(M.warnings,Z),outputFiles:void 0,metafile:void 0,mangleCache:void 0},fe=Q.errors.slice(),Y=Q.warnings.slice();M.outputFiles&&(Q.outputFiles=M.outputFiles.map(Ra)),M.metafile&&M.metafile.length&&(Q.metafile=Ca(M.metafile)),M.mangleCache&&(Q.mangleCache=M.mangleCache),M.writeToStdout!==void 0&&console.log(p(M.writeToStdout).replace(/\n$/,"")),Ee(Q,(ge,_e)=>{if(fe.length>0||ge.length>0){let de=Vt("Build failed",fe.concat(ge),Y.concat(_e));return W(de,null,ge,_e)}W(null,Q,ge,_e)})},ie,g;he&&(P["on-end"]=(M,W)=>new Promise(Q=>{z(W,(fe,Y,ge,_e)=>{let de={errors:ge,warnings:_e};g&&g(fe,Y),ie=void 0,g=void 0,S(M,de),Q()})})),b(O,D,(M,W)=>{if(M)return G(new Error(M),null);if(!he)return z(W,(Y,ge)=>(te(),G(Y,ge)));if(W.errors.length>0)return G(Vt("Context failed",W.errors,W.warnings),null);let Q=!1,fe={rebuild:()=>(ie||(ie=new Promise((Y,ge)=>{let _e;g=(Fe,Ie)=>{_e||(_e=()=>Fe?ge(Fe):Y(Ie))};let de=()=>{b(O,{command:"rebuild",key:m},(Ie,qe)=>{Ie?ge(new Error(Ie)):_e?_e():de()})};de()})),ie),watch:(Y={})=>new Promise((ge,_e)=>{if(!$.hasFS)throw new Error('Cannot use the "watch" API in this environment');let de={},Fe=v(Y,de,"delay",we);Pe(Y,de,"in watch() call");let Ie={command:"watch",key:m};Fe&&(Ie.delay=Fe),b(O,Ie,qe=>{qe?_e(new Error(qe)):ge(void 0)})}),serve:(Y={})=>new Promise((ge,_e)=>{if(!$.hasFS)throw new Error('Cannot use the "serve" API in this environment');let de={},Fe=v(Y,de,"port",Te),Ie=v(Y,de,"host",B),qe=v(Y,de,"servedir",B),re=v(Y,de,"keyfile",B),Je=v(Y,de,"certfile",B),je=v(Y,de,"fallback",B),Ge=v(Y,de,"cors",$e),Ye=v(Y,de,"onRequest",Ue);Pe(Y,de,"in serve() call");let Ne={command:"serve",key:m,onRequest:!!Ye};if(Fe!==void 0&&(Ne.port=Fe),Ie!==void 0&&(Ne.host=Ie),qe!==void 0&&(Ne.servedir=qe),re!==void 0&&(Ne.keyfile=re),Je!==void 0&&(Ne.certfile=Je),je!==void 0&&(Ne.fallback=je),Ge){let zt={},At=v(Ge,zt,"origin",_n);Pe(Ge,zt,'on "cors" object'),Array.isArray(At)?Ne.corsOrigin=At:At!==void 0&&(Ne.corsOrigin=[At])}b(O,Ne,(zt,At)=>{if(zt)return _e(new Error(zt));Ye&&(P["serve-request"]=(Ka,qa)=>{Ye(qa.args),S(Ka,{})}),ge(At)})}),cancel:()=>new Promise(Y=>{if(Q)return Y();b(O,{command:"cancel",key:m},()=>{Y()})}),dispose:()=>new Promise(Y=>{if(Q)return Y();Q=!0,b(O,{command:"dispose",key:m},()=>{Y(),te(),O.unref()})})};O.ref(),G(null,fe)})}}var Pa=(h,m,b,S,O,$,P,V,x)=>l(null,null,function*(){let N=[],G=[],Z={},he={},ue=[],pe=0,me=0,ne=[],Ee=!1;V=[...V];for(let U of V){let C={};if(typeof U!="object")throw new Error(`Plugin at index ${me} must be an object`);let k=v(U,C,"name",B);if(typeof k!="string"||k==="")throw new Error(`Plugin at index ${me} is missing a name`);try{let T=v(U,C,"setup",Ue);if(typeof T!="function")throw new Error("Plugin is missing a setup function");Pe(U,C,`on plugin ${X(k)}`);let I={name:k,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};me++;let J=T({initialOptions:P,resolve:(E,D={})=>{if(!Ee)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof E!="string")throw new Error("The path to resolve must be a string");let z=Object.create(null),ie=v(D,z,"pluginName",B),g=v(D,z,"importer",B),M=v(D,z,"namespace",B),W=v(D,z,"resolveDir",B),Q=v(D,z,"kind",B),fe=v(D,z,"pluginData",oe),Y=v(D,z,"with",$e);return Pe(D,z,"in resolve() call"),new Promise((ge,_e)=>{let de={command:"resolve",path:E,key:h,pluginName:k};if(ie!=null&&(de.pluginName=ie),g!=null&&(de.importer=g),M!=null&&(de.namespace=M),W!=null&&(de.resolveDir=W),Q!=null)de.kind=Q;else throw new Error('Must specify "kind" when calling "resolve"');fe!=null&&(de.pluginData=x.store(fe)),Y!=null&&(de.with=Ia(Y,"with")),m(S,de,(Fe,Ie)=>{Fe!==null?_e(new Error(Fe)):ge({errors:St(Ie.errors,x),warnings:St(Ie.warnings,x),path:Ie.path,external:Ie.external,sideEffects:Ie.sideEffects,namespace:Ie.namespace,suffix:Ie.suffix,pluginData:x.load(Ie.pluginData)})})})},onStart(E){let D='This error came from the "onStart" callback registered here:',z=gn(new Error(D),O,"onStart");N.push({name:k,callback:E,note:z}),I.onStart=!0},onEnd(E){let D='This error came from the "onEnd" callback registered here:',z=gn(new Error(D),O,"onEnd");G.push({name:k,callback:E,note:z}),I.onEnd=!0},onResolve(E,D){let z='This error came from the "onResolve" callback registered here:',ie=gn(new Error(z),O,"onResolve"),g={},M=v(E,g,"filter",xe),W=v(E,g,"namespace",B);if(Pe(E,g,`in onResolve() call for plugin ${X(k)}`),M==null)throw new Error("onResolve() call is missing a filter");let Q=pe++;Z[Q]={name:k,callback:D,note:ie},I.onResolve.push({id:Q,filter:wn(M),namespace:W||""})},onLoad(E,D){let z='This error came from the "onLoad" callback registered here:',ie=gn(new Error(z),O,"onLoad"),g={},M=v(E,g,"filter",xe),W=v(E,g,"namespace",B);if(Pe(E,g,`in onLoad() call for plugin ${X(k)}`),M==null)throw new Error("onLoad() call is missing a filter");let Q=pe++;he[Q]={name:k,callback:D,note:ie},I.onLoad.push({id:Q,filter:wn(M),namespace:W||""})},onDispose(E){ue.push(E)},esbuild:O.esbuild});J&&(yield J),ne.push(I)}catch(T){return{ok:!1,error:T,pluginName:k}}}$["on-start"]=(U,C)=>l(null,null,function*(){x.clear();let k={errors:[],warnings:[]};yield Promise.all(N.map(T=>l(null,[T],function*({name:I,callback:j,note:J}){try{let E=yield j();if(E!=null){if(typeof E!="object")throw new Error(`Expected onStart() callback in plugin ${X(I)} to return an object`);let D={},z=v(E,D,"errors",ae),ie=v(E,D,"warnings",ae);Pe(E,D,`from onStart() callback in plugin ${X(I)}`),z!=null&&k.errors.push(...Ke(z,"errors",x,I,void 0)),ie!=null&&k.warnings.push(...Ke(ie,"warnings",x,I,void 0))}}catch(E){k.errors.push(lt(E,O,x,J&&J(),I))}}))),b(U,k)}),$["on-resolve"]=(U,C)=>l(null,null,function*(){let k={},T="",I,j;for(let J of C.ids)try{({name:T,callback:I,note:j}=Z[J]);let E=yield I({path:C.path,importer:C.importer,namespace:C.namespace,resolveDir:C.resolveDir,kind:C.kind,pluginData:x.load(C.pluginData),with:C.with});if(E!=null){if(typeof E!="object")throw new Error(`Expected onResolve() callback in plugin ${X(T)} to return an object`);let D={},z=v(E,D,"pluginName",B),ie=v(E,D,"path",B),g=v(E,D,"namespace",B),M=v(E,D,"suffix",B),W=v(E,D,"external",K),Q=v(E,D,"sideEffects",K),fe=v(E,D,"pluginData",oe),Y=v(E,D,"errors",ae),ge=v(E,D,"warnings",ae),_e=v(E,D,"watchFiles",Ae),de=v(E,D,"watchDirs",Ae);Pe(E,D,`from onResolve() callback in plugin ${X(T)}`),k.id=J,z!=null&&(k.pluginName=z),ie!=null&&(k.path=ie),g!=null&&(k.namespace=g),M!=null&&(k.suffix=M),W!=null&&(k.external=W),Q!=null&&(k.sideEffects=Q),fe!=null&&(k.pluginData=x.store(fe)),Y!=null&&(k.errors=Ke(Y,"errors",x,T,void 0)),ge!=null&&(k.warnings=Ke(ge,"warnings",x,T,void 0)),_e!=null&&(k.watchFiles=bn(_e,"watchFiles")),de!=null&&(k.watchDirs=bn(de,"watchDirs"));break}}catch(E){k={id:J,errors:[lt(E,O,x,j&&j(),T)]};break}b(U,k)}),$["on-load"]=(U,C)=>l(null,null,function*(){let k={},T="",I,j;for(let J of C.ids)try{({name:T,callback:I,note:j}=he[J]);let E=yield I({path:C.path,namespace:C.namespace,suffix:C.suffix,pluginData:x.load(C.pluginData),with:C.with});if(E!=null){if(typeof E!="object")throw new Error(`Expected onLoad() callback in plugin ${X(T)} to return an object`);let D={},z=v(E,D,"pluginName",B),ie=v(E,D,"contents",pn),g=v(E,D,"resolveDir",B),M=v(E,D,"pluginData",oe),W=v(E,D,"loader",B),Q=v(E,D,"errors",ae),fe=v(E,D,"warnings",ae),Y=v(E,D,"watchFiles",Ae),ge=v(E,D,"watchDirs",Ae);Pe(E,D,`from onLoad() callback in plugin ${X(T)}`),k.id=J,z!=null&&(k.pluginName=z),ie instanceof Uint8Array?k.contents=ie:ie!=null&&(k.contents=_(ie)),g!=null&&(k.resolveDir=g),M!=null&&(k.pluginData=x.store(M)),W!=null&&(k.loader=W),Q!=null&&(k.errors=Ke(Q,"errors",x,T,void 0)),fe!=null&&(k.warnings=Ke(fe,"warnings",x,T,void 0)),Y!=null&&(k.watchFiles=bn(Y,"watchFiles")),ge!=null&&(k.watchDirs=bn(ge,"watchDirs"));break}}catch(E){k={id:J,errors:[lt(E,O,x,j&&j(),T)]};break}b(U,k)});let te=(U,C)=>C([],[]);G.length>0&&(te=(U,C)=>{l(null,null,function*(){let k=[],T=[];for(let{name:I,callback:j,note:J}of G){let E,D;try{let z=yield j(U);if(z!=null){if(typeof z!="object")throw new Error(`Expected onEnd() callback in plugin ${X(I)} to return an object`);let ie={},g=v(z,ie,"errors",ae),M=v(z,ie,"warnings",ae);Pe(z,ie,`from onEnd() callback in plugin ${X(I)}`),g!=null&&(E=Ke(g,"errors",x,I,void 0)),M!=null&&(D=Ke(M,"warnings",x,I,void 0))}}catch(z){E=[lt(z,O,x,J&&J(),I)]}if(E){k.push(...E);try{U.errors.push(...E)}catch{}}if(D){T.push(...D);try{U.warnings.push(...D)}catch{}}}C(k,T)})});let ee=()=>{for(let U of ue)setTimeout(()=>U(),0)};return Ee=!0,{ok:!0,requestPlugins:ne,runOnEndCallbacks:te,scheduleOnDisposeCallbacks:ee}});function ss(){let h=new Map,m=0;return{clear(){h.clear()},load(b){return h.get(b)},store(b){if(b===void 0)return-1;let S=m++;return h.set(S,b),S}}}function gn(h,m,b){let S,O=!1;return()=>{if(O)return S;O=!0;try{let $=(h.stack+"").split(`
8
+ `);$.splice(1,1);let P=is(m,$,b);if(P)return S={text:h.message,location:P},S}catch{}}}function lt(h,m,b,S,O){let $="Internal error",P=null;try{$=(h&&h.message||h)+""}catch{}try{P=is(m,(h.stack+"").split(`
9
+ `),"")}catch{}return{id:"",pluginName:O,text:$,location:P,notes:S?[S]:[],detail:b?b.store(h):-1}}function is(h,m,b){let S=" at ";if(h.readFileSync&&!m[0].startsWith(S)&&m[1].startsWith(S))for(let O=1;O<m.length;O++){let $=m[O];if($.startsWith(S))for($=$.slice(S.length);;){let P=/^(?:new |async )?\S+ \((.*)\)$/.exec($);if(P){$=P[1];continue}if(P=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec($),P){$=P[1];continue}if(P=/^(\S+):(\d+):(\d+)$/.exec($),P){let V;try{V=h.readFileSync(P[1],"utf8")}catch{break}let x=V.split(/\r\n|\r|\n|\u2028|\u2029/)[+P[2]-1]||"",N=+P[3]-1,G=x.slice(N,N+b.length)===b?b.length:0;return{file:P[1],namespace:"file",line:+P[2],column:_(x.slice(0,N)).length,length:_(x.slice(N,N+G)).length,lineText:x+`
10
+ `+m.slice(1).join(`
11
+ `),suggestion:""}}break}}return null}function Vt(h,m,b){let S=5;h+=m.length<1?"":` with ${m.length} error${m.length<2?"":"s"}:`+m.slice(0,S+1).map(($,P)=>{if(P===S)return`
12
12
  ...`;if(!$.location)return`
13
- error: ${$.text}`;let{file:se,line:B,column:re}=$.location,ae=$.pluginName?`[plugin: ${$.pluginName}] `:"";return`
14
- ${se}:${B}:${re}: ERROR: ${ae}${$.text}`}).join("");let K=new Error(S);for(let[$,H]of[["errors",A],["warnings",I]])Object.defineProperty(K,$,{configurable:!0,enumerable:!0,get:()=>H,set:se=>Object.defineProperty(K,$,{configurable:!0,enumerable:!0,value:se})});return K}function ii(S,A){for(let I of S)I.detail=A.load(I.detail);return S}function eh(S,A,I){if(S==null)return null;let U={},K=R(S,U,"file",E),$=R(S,U,"namespace",E),H=R(S,U,"line",Q),se=R(S,U,"column",Q),B=R(S,U,"length",Q),re=R(S,U,"lineText",E),ae=R(S,U,"suggestion",E);if(tt(S,U,A),re){let he=re.slice(0,(se&&se>0?se:0)+(B&&B>0?B:0)+(I&&I>0?I:80));!/[\x7F-\uFFFF]/.test(he)&&!/\n/.test(re)&&(re=he)}return{file:K||"",namespace:$||"",line:H||0,column:se||0,length:B||0,lineText:re||"",suggestion:ae||""}}function wr(S,A,I,U,K){let $=[],H=0;for(let se of S){let B={},re=R(se,B,"id",E),ae=R(se,B,"pluginName",E),he=R(se,B,"text",E),Be=R(se,B,"location",Kd),Ee=R(se,B,"notes",ee),Le=R(se,B,"detail",_),Ue=`in element ${H} of "${A}"`;tt(se,B,Ue);let ge=[];if(Ee)for(let Qe of Ee){let pe={},me=R(Qe,pe,"text",E),J=R(Qe,pe,"location",Kd);tt(Qe,pe,Ue),ge.push({text:me||"",location:eh(J,Ue,K)})}$.push({id:re||"",pluginName:ae||U,text:he||"",location:eh(Be,Ue,K),notes:ge,detail:I?I.store(Le):-1}),H++}return $}function Oa(S,A){let I=[];for(let U of S){if(typeof U!="string")throw new Error(`${x(A)} must be an array of strings`);I.push(U)}return I}function ay(S,A){let I=Object.create(null);for(let U in S){let K=S[U];if(typeof K!="string")throw new Error(`key ${x(U)} in object ${x(A)} must be a string`);I[U]=K}return I}function oy({path:S,contents:A,hash:I}){let U=null;return{path:S,contents:A,hash:I,get text(){let K=this.contents;return(U===null||K!==A)&&(A=K,U=p(K)),U}}}function La(S){let A=S.source;return S.flags&&(A=`(?${S.flags})${A}`),A}function cy(S){let A;try{A=p(S)}catch{return T(S)}return JSON.parse(A)}var ly="0.28.2",uy=S=>Ss().build(S),dy=S=>Ss().context(S),hy=(S,A)=>Ss().transform(S,A),fy=(S,A)=>Ss().formatMessages(S,A),my=(S,A)=>Ss().analyzeMetafile(S,A),py=()=>{throw new Error('The "buildSync" API only works in node')},gy=()=>{throw new Error('The "transformSync" API only works in node')},yy=()=>{throw new Error('The "formatMessagesSync" API only works in node')},wy=()=>{throw new Error('The "analyzeMetafileSync" API only works in node')},by=()=>(Ua&&Ua(),Promise.resolve()),An,Ua,Na,Ss=()=>{if(Na)return Na;throw An?new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this'):new Error('You need to call "initialize" before calling this')},ky=S=>{S=ey(S||{});let A=S.wasmURL,I=S.wasmModule,U=S.worker!==!1;if(!A&&!I)throw new Error('Must provide either the "wasmURL" option or the "wasmModule" option');if(An)throw new Error('Cannot call "initialize" more than once');return An=Sy(A||"",I,U),An.catch(()=>{An=void 0}),An},Sy=(S,A,I)=>c(null,null,function*(){let U,K,$=new Promise(he=>K=he);if(I){let he=new Blob([`onmessage=((postMessage) => {
13
+ error: ${$.text}`;let{file:V,line:x,column:N}=$.location,G=$.pluginName?`[plugin: ${$.pluginName}] `:"";return`
14
+ ${V}:${x}:${N}: ERROR: ${G}${$.text}`}).join("");let O=new Error(h);for(let[$,P]of[["errors",m],["warnings",b]])Object.defineProperty(O,$,{configurable:!0,enumerable:!0,get:()=>P,set:V=>Object.defineProperty(O,$,{configurable:!0,enumerable:!0,value:V})});return O}function St(h,m){for(let b of h)b.detail=m.load(b.detail);return h}function as(h,m,b){if(h==null)return null;let S={},O=v(h,S,"file",B),$=v(h,S,"namespace",B),P=v(h,S,"line",we),V=v(h,S,"column",we),x=v(h,S,"length",we),N=v(h,S,"lineText",B),G=v(h,S,"suggestion",B);if(Pe(h,S,m),N){let Z=N.slice(0,(V&&V>0?V:0)+(x&&x>0?x:0)+(b&&b>0?b:80));!/[\x7F-\uFFFF]/.test(Z)&&!/\n/.test(N)&&(N=Z)}return{file:O||"",namespace:$||"",line:P||0,column:V||0,length:x||0,lineText:N||"",suggestion:G||""}}function Ke(h,m,b,S,O){let $=[],P=0;for(let V of h){let x={},N=v(V,x,"id",B),G=v(V,x,"pluginName",B),Z=v(V,x,"text",B),he=v(V,x,"location",Nt),ue=v(V,x,"notes",ae),pe=v(V,x,"detail",oe),me=`in element ${P} of "${m}"`;Pe(V,x,me);let ne=[];if(ue)for(let Ee of ue){let te={},ee=v(Ee,te,"text",B),U=v(Ee,te,"location",Nt);Pe(Ee,te,me),ne.push({text:ee||"",location:as(U,me,O)})}$.push({id:N||"",pluginName:G||S,text:Z||"",location:as(he,me,O),notes:ne,detail:b?b.store(pe):-1}),P++}return $}function bn(h,m){let b=[];for(let S of h){if(typeof S!="string")throw new Error(`${X(m)} must be an array of strings`);b.push(S)}return b}function Ia(h,m){let b=Object.create(null);for(let S in h){let O=h[S];if(typeof O!="string")throw new Error(`key ${X(S)} in object ${X(m)} must be a string`);b[S]=O}return b}function Ra({path:h,contents:m,hash:b}){let S=null;return{path:h,contents:m,hash:b,get text(){let O=this.contents;return(S===null||O!==m)&&(m=O,S=p(O)),S}}}function wn(h){let m=h.source;return h.flags&&(m=`(?${h.flags})${m}`),m}function Ca(h){let m;try{m=p(h)}catch{return se(h)}return JSON.parse(m)}var Oa="0.28.2",$a=h=>Gt().build(h),Da=h=>Gt().context(h),La=(h,m)=>Gt().transform(h,m),Fa=(h,m)=>Gt().formatMessages(h,m),Ba=(h,m)=>Gt().analyzeMetafile(h,m),Ua=()=>{throw new Error('The "buildSync" API only works in node')},ja=()=>{throw new Error('The "transformSync" API only works in node')},Na=()=>{throw new Error('The "formatMessagesSync" API only works in node')},Wa=()=>{throw new Error('The "analyzeMetafileSync" API only works in node')},Va=()=>(yn&&yn(),Promise.resolve()),ct,yn,vn,Gt=()=>{if(vn)return vn;throw ct?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')},Ga=h=>{h=Ma(h||{});let m=h.wasmURL,b=h.wasmModule,S=h.worker!==!1;if(!m&&!b)throw new Error('Must provide either the "wasmURL" option or the "wasmModule" option');if(ct)throw new Error('Cannot call "initialize" more than once');return ct=za(m||"",b,S),ct.catch(()=>{ct=void 0}),ct},za=(h,m,b)=>l(null,null,function*(){let S,O,$=new Promise(Z=>O=Z);if(b){let Z=new Blob([`onmessage=((postMessage) => {
15
15
  // Copyright 2018 The Go Authors. All rights reserved.
16
16
  // Use of this source code is governed by a BSD-style
17
17
  // license that can be found in the LICENSE file.
@@ -689,1338 +689,46 @@ ${se}:${B}:${re}: ERROR: ${ae}${$.text}`}).join("");let K=new Error(S);for(let[$
689
689
  });
690
690
  }
691
691
  return (m) => onmessage(m);
692
- })(postMessage)`],{type:"text/javascript"});U=new Worker(URL.createObjectURL(he))}else{let he=(Ee=>{var Le=(pe,me,J)=>new Promise((q,D)=>{var V=le=>{try{te(J.next(le))}catch(z){D(z)}},W=le=>{try{te(J.throw(le))}catch(z){D(z)}},te=le=>le.done?q(le.value):Promise.resolve(le.value).then(V,W);te((J=J.apply(pe,me)).next())});let Ue,ge={};for(let pe=self;pe;pe=Object.getPrototypeOf(pe))for(let me of Object.getOwnPropertyNames(pe))me in ge||Object.defineProperty(ge,me,{get:()=>self[me]});(()=>{let pe=()=>{let q=new Error("not implemented");return q.code="ENOSYS",q};if(!ge.fs){let q="";ge.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1,O_DIRECTORY:-1},writeSync(D,V){q+=J.decode(V);let W=q.lastIndexOf(`
693
- `);return W!=-1&&(console.log(q.substring(0,W)),q=q.substring(W+1)),V.length},write(D,V,W,te,le,z){if(W!==0||te!==V.length||le!==null){z(pe());return}let X=this.writeSync(D,V);z(null,X)},chmod(D,V,W){W(pe())},chown(D,V,W,te){te(pe())},close(D,V){V(pe())},fchmod(D,V,W){W(pe())},fchown(D,V,W,te){te(pe())},fstat(D,V){V(pe())},fsync(D,V){V(null)},ftruncate(D,V,W){W(pe())},lchown(D,V,W,te){te(pe())},link(D,V,W){W(pe())},lstat(D,V){V(pe())},mkdir(D,V,W){W(pe())},open(D,V,W,te){te(pe())},read(D,V,W,te,le,z){z(pe())},readdir(D,V){V(pe())},readlink(D,V){V(pe())},rename(D,V,W){W(pe())},rmdir(D,V){V(pe())},stat(D,V){V(pe())},symlink(D,V,W){W(pe())},truncate(D,V,W){W(pe())},unlink(D,V){V(pe())},utimes(D,V,W,te){te(pe())}}}if(ge.process||(ge.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw pe()},pid:-1,ppid:-1,umask(){throw pe()},cwd(){throw pe()},chdir(){throw pe()}}),ge.path||(ge.path={resolve(...q){return q.join("/")}}),!ge.crypto)throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");if(!ge.performance)throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");if(!ge.TextEncoder)throw new Error("globalThis.TextEncoder is not available, polyfill required");if(!ge.TextDecoder)throw new Error("globalThis.TextDecoder is not available, polyfill required");let me=new TextEncoder("utf-8"),J=new TextDecoder("utf-8");ge.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=P=>{P!==0&&console.warn("exit code:",P)},this._exitPromise=new Promise(P=>{this._resolveExitPromise=P}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let q=(P,L)=>{this.mem.setUint32(P+0,L,!0),this.mem.setUint32(P+4,Math.floor(L/4294967296),!0)},D=(P,L)=>{this.mem.setUint32(P+0,L,!0)},V=P=>{let L=this.mem.getUint32(P+0,!0),ne=this.mem.getInt32(P+4,!0);return L+ne*4294967296},W=P=>{let L=this.mem.getFloat64(P,!0);if(L===0)return;if(!isNaN(L))return L;let ne=this.mem.getUint32(P,!0);return this._values[ne]},te=(P,L)=>{if(typeof L=="number"&&L!==0){if(isNaN(L)){this.mem.setUint32(P+4,2146959360,!0),this.mem.setUint32(P,0,!0);return}this.mem.setFloat64(P,L,!0);return}if(L===void 0){this.mem.setFloat64(P,0,!0);return}let fe=this._ids.get(L);fe===void 0&&(fe=this._idPool.pop(),fe===void 0&&(fe=this._values.length),this._values[fe]=L,this._goRefCounts[fe]=0,this._ids.set(L,fe)),this._goRefCounts[fe]++;let Me=0;switch(typeof L){case"object":L!==null&&(Me=1);break;case"string":Me=2;break;case"symbol":Me=3;break;case"function":Me=4;break}this.mem.setUint32(P+4,2146959360|Me,!0),this.mem.setUint32(P,fe,!0)},le=P=>{let L=V(P+0),ne=V(P+8);return new Uint8Array(this._inst.exports.mem.buffer,L,ne)},z=P=>{let L=V(P+0),ne=V(P+8),fe=new Array(ne);for(let Me=0;Me<ne;Me++)fe[Me]=W(L+Me*8);return fe},X=P=>{let L=V(P+0),ne=V(P+8);return J.decode(new DataView(this._inst.exports.mem.buffer,L,ne))},oe=(P,L)=>(this._inst.exports.testExport0(),this._inst.exports.testExport(P,L)),Te=Date.now()-performance.now();this.importObject={_gotest:{add:(P,L)=>P+L,callExport:oe},gojs:{"runtime.wasmExit":P=>{P>>>=0;let L=this.mem.getInt32(P+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(L)},"runtime.wasmWrite":P=>{P>>>=0;let L=V(P+8),ne=V(P+16),fe=this.mem.getInt32(P+24,!0);ge.fs.writeSync(L,new Uint8Array(this._inst.exports.mem.buffer,ne,fe))},"runtime.resetMemoryDataView":P=>{P>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":P=>{P>>>=0,q(P+8,(Te+performance.now())*1e6)},"runtime.walltime":P=>{P>>>=0;let L=new Date().getTime();q(P+8,L/1e3),this.mem.setInt32(P+16,L%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":P=>{P>>>=0;let L=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(L,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(L);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},V(P+8))),this.mem.setInt32(P+16,L,!0)},"runtime.clearTimeoutEvent":P=>{P>>>=0;let L=this.mem.getInt32(P+8,!0);clearTimeout(this._scheduledTimeouts.get(L)),this._scheduledTimeouts.delete(L)},"runtime.getRandomData":P=>{P>>>=0,crypto.getRandomValues(le(P+8))},"syscall/js.finalizeRef":P=>{P>>>=0;let L=this.mem.getUint32(P+8,!0);if(this._goRefCounts[L]--,this._goRefCounts[L]===0){let ne=this._values[L];this._values[L]=null,this._ids.delete(ne),this._idPool.push(L)}},"syscall/js.stringVal":P=>{P>>>=0,te(P+24,X(P+8))},"syscall/js.valueGet":P=>{P>>>=0;let L=Reflect.get(W(P+8),X(P+16));P=this._inst.exports.getsp()>>>0,te(P+32,L)},"syscall/js.valueSet":P=>{P>>>=0,Reflect.set(W(P+8),X(P+16),W(P+32))},"syscall/js.valueDelete":P=>{P>>>=0,Reflect.deleteProperty(W(P+8),X(P+16))},"syscall/js.valueIndex":P=>{P>>>=0,te(P+24,Reflect.get(W(P+8),V(P+16)))},"syscall/js.valueSetIndex":P=>{P>>>=0,Reflect.set(W(P+8),V(P+16),W(P+24))},"syscall/js.valueCall":P=>{P>>>=0;try{let L=W(P+8),ne=Reflect.get(L,X(P+16)),fe=z(P+32),Me=Reflect.apply(ne,L,fe);P=this._inst.exports.getsp()>>>0,te(P+56,Me),this.mem.setUint8(P+64,1)}catch(L){P=this._inst.exports.getsp()>>>0,te(P+56,L),this.mem.setUint8(P+64,0)}},"syscall/js.valueInvoke":P=>{P>>>=0;try{let L=W(P+8),ne=z(P+16),fe=Reflect.apply(L,void 0,ne);P=this._inst.exports.getsp()>>>0,te(P+40,fe),this.mem.setUint8(P+48,1)}catch(L){P=this._inst.exports.getsp()>>>0,te(P+40,L),this.mem.setUint8(P+48,0)}},"syscall/js.valueNew":P=>{P>>>=0;try{let L=W(P+8),ne=z(P+16),fe=Reflect.construct(L,ne);P=this._inst.exports.getsp()>>>0,te(P+40,fe),this.mem.setUint8(P+48,1)}catch(L){P=this._inst.exports.getsp()>>>0,te(P+40,L),this.mem.setUint8(P+48,0)}},"syscall/js.valueLength":P=>{P>>>=0,q(P+16,parseInt(W(P+8).length))},"syscall/js.valuePrepareString":P=>{P>>>=0;let L=me.encode(String(W(P+8)));te(P+16,L),q(P+24,L.length)},"syscall/js.valueLoadString":P=>{P>>>=0;let L=W(P+8);le(P+16).set(L)},"syscall/js.valueInstanceOf":P=>{P>>>=0,this.mem.setUint8(P+24,W(P+8)instanceof W(P+16)?1:0)},"syscall/js.copyBytesToGo":P=>{P>>>=0;let L=le(P+8),ne=W(P+32);if(!(ne instanceof Uint8Array||ne instanceof Uint8ClampedArray)){this.mem.setUint8(P+48,0);return}let fe=ne.subarray(0,L.length);L.set(fe),q(P+40,fe.length),this.mem.setUint8(P+48,1)},"syscall/js.copyBytesToJS":P=>{P>>>=0;let L=W(P+8),ne=le(P+16);if(!(L instanceof Uint8Array||L instanceof Uint8ClampedArray)){this.mem.setUint8(P+48,0);return}let fe=ne.subarray(0,L.length);L.set(fe),q(P+40,fe.length),this.mem.setUint8(P+48,1)},debug:P=>{console.log(P)}}}}run(q){return Le(this,null,function*(){if(!(q instanceof WebAssembly.Instance))throw new Error("Go.run: WebAssembly.Instance expected");this._inst=q,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,ge,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[ge,5],[this,6]]),this._idPool=[],this.exited=!1;let D=4096,V=oe=>{let Te=D,P=me.encode(oe+"\0");return new Uint8Array(this.mem.buffer,D,P.length).set(P),D+=P.length,D%8!==0&&(D+=8-D%8),Te},W=this.argv.length,te=[];this.argv.forEach(oe=>{te.push(V(oe))}),te.push(0),Object.keys(this.env).sort().forEach(oe=>{te.push(V(`${oe}=${this.env[oe]}`))}),te.push(0);let z=D;if(te.forEach(oe=>{this.mem.setUint32(D,oe,!0),this.mem.setUint32(D+4,0,!0),D+=8}),D>=12288)throw new Error("total length of command line and environment variables exceeds limit");this._inst.exports.run(W,z),this.exited&&this._resolveExitPromise(),yield this._exitPromise})}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(q){let D=this;return function(){let V={id:q,this:this,args:arguments};return D._pendingEvent=V,D._resume(),V.result}}}})(),Ue=({data:pe})=>{let me=new TextDecoder,J=ge.fs,q="";J.writeSync=(le,z)=>{if(le===1)Ee(z);else if(le===2){q+=me.decode(z);let X=q.split(`
694
- `);X.length>1&&console.log(X.slice(0,-1).join(`
695
- `)),q=X[X.length-1]}else throw new Error("Bad write");return z.length};let D=[],V,W=0;Ue=({data:le})=>(le.length>0&&(D.push(le),V&&V()),te),J.read=(le,z,X,oe,Te,P)=>{if(le!==0||X!==0||oe!==z.length||Te!==null)throw new Error("Bad read");if(D.length===0){V=()=>J.read(le,z,X,oe,Te,P);return}let L=D[0],ne=Math.max(0,Math.min(oe,L.length-W));z.set(L.subarray(W,W+ne),X),W+=ne,W===L.length&&(D.shift(),W=0),P(null,ne)};let te=new ge.Go;return te.argv=["","--service=0.28.2"],Qe(pe,te).then(le=>{Ee(null),te.run(le)},le=>{Ee(le)}),te};function Qe(pe,me){return Le(this,null,function*(){if(pe instanceof WebAssembly.Module)return WebAssembly.instantiate(pe,me.importObject);let J=yield fetch(pe);if(!J.ok)throw new Error(`Failed to download ${JSON.stringify(pe)}`);if("instantiateStreaming"in WebAssembly&&/^application\/wasm($|;)/i.test(J.headers.get("Content-Type")||""))return(yield WebAssembly.instantiateStreaming(J,me.importObject)).instance;let q=yield J.arrayBuffer();return(yield WebAssembly.instantiate(q,me.importObject)).instance})}return pe=>Ue(pe)})(Ee=>U.onmessage({data:Ee})),Be;U={onmessage:null,postMessage:Ee=>setTimeout(()=>{try{Be=he({data:Ee})}catch(Le){K(Le)}}),terminate(){if(Be)for(let Ee of Be._scheduledTimeouts.values())clearTimeout(Ee)}}}let H,se,B=new Promise((he,Be)=>{H=he,se=Be});U.onmessage=({data:he})=>{U.onmessage=({data:Be})=>re(Be),he?se(he):H()},U.postMessage(A||new URL(S,location.href).toString());let{readFromStdout:re,service:ae}=ny({writeToStdin(he){U.postMessage(he)},isSync:!1,hasFS:!1,esbuild:l});yield B,Ua=()=>{U.terminate(),An=void 0,Ua=void 0,Na=void 0},Na={build:he=>new Promise((Be,Ee)=>{$.then(Ee),ae.buildOrContext({callName:"build",refs:null,options:he,isTTY:!1,defaultWD:"/",callback:(Le,Ue)=>Le?Ee(Le):Be(Ue)})}),context:he=>new Promise((Be,Ee)=>{$.then(Ee),ae.buildOrContext({callName:"context",refs:null,options:he,isTTY:!1,defaultWD:"/",callback:(Le,Ue)=>Le?Ee(Le):Be(Ue)})}),transform:(he,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.transform({callName:"transform",refs:null,input:he,options:Be||{},isTTY:!1,fs:{readFile(Ue,ge){ge(new Error("Internal error"),null)},writeFile(Ue,ge){ge(null)}},callback:(Ue,ge)=>Ue?Le(Ue):Ee(ge)})}),formatMessages:(he,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.formatMessages({callName:"formatMessages",refs:null,messages:he,options:Be,callback:(Ue,ge)=>Ue?Le(Ue):Ee(ge)})}),analyzeMetafile:(he,Be)=>new Promise((Ee,Le)=>{$.then(Le),ae.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof he=="string"?he:JSON.stringify(he),options:Be,callback:(Ue,ge)=>Ue?Le(Ue):Ee(ge)})})}}),xy=l})(typeof qd=="object"?qd:{set exports(r){(typeof self<"u"?self:this).esbuild=r}})});import{resolveSurfaceSource as bx,CanvasRenderContext2D as kx,withRichTextDescriptor as Sx,fillOps as xx,strokeOps as Tx,shadowOps as Ax,alignmentOps as vx,resolveShapeAlignment as _x,resolvePivotPosition as Cx,stripShapeAlignmentKeys as Px}from"@motionscript/core";import{canvas3DResourceKey as sh,parseCanvas3DResourceKey as Ey,registerCanvas3DResourceLoader as Iy,registerCanvas3DWarmup as My}from"@motionscript/core";var bl=null,nh=null,za=new Set,Ts=new Map;function kl(){return bl}function As(){return bl?Promise.resolve():(nh??=import("./chunks/three.module-Z4EOVUWF.js").then(r=>(bl=r,r)),nh.then(()=>{}))}function Sl(r){za.add(r)}function xl(){return za.size>0||Ts.size>0}function ah(r,e){Ts.set(r,e)}async function Tl(){let r=!1;for(let e=0;e<4&&!(za.size===0&&Ts.size===0);e++){za.clear();let t=[...Ts];Ts.clear(),await As(),t.length>0&&await Promise.all(t.map(([n])=>oh(n))),r=!0}return r}var Va=new Map;async function oh(r){let e=Ey(r);if(e?.kind!=="gltf")return;let t=await Fy(e.src);t&&Va.set(r,t)}function vn(r){return Va.get(sh("gltf",r))??null}async function Fy(r){try{let[,e,t]=await Promise.all([As(),import("./chunks/GLTFLoader-PGXD4V5B.js"),import("./chunks/SkeletonUtils-XYDMTGTM.js")]),n=await new e.GLTFLoader().loadAsync(r);return{scene:n.scene,animations:n.animations,clone:()=>t.clone(n.scene)}}catch(e){return ih.has(r)||(ih.add(r),console.warn(`[motionscript] Could not load the model "${r}" (only glTF/GLB files load): ${e instanceof Error?e.message:String(e)}`)),null}}var ih=new Set;function Ry(r){r.scene.traverse(e=>{let t=e;t.geometry?.dispose?.();let n=Array.isArray(t.material)?t.material:[t.material];for(let i of n)if(i){for(let s of Object.values(i)){let a=s;a?.isTexture&&a.dispose()}i.dispose()}})}function Al(){My(As),Iy(async(r,e)=>{let t=sh(r,e);await oh(t);let n=Va.get(t);return n?()=>{Va.delete(t),Ry(n)}:()=>{}})}import{canvas3DResourceKey as fw}from"@motionscript/core";import{parseColor as ch}from"@motionscript/core";function He(r){return r*(Math.PI/180)}function lh(r,e){switch(e){case"back":return r.BackSide;case"both":return r.DoubleSide;default:return r.FrontSide}}function uh(r,e){switch(e){case"additive":return r.AdditiveBlending;case"subtractive":return r.SubtractiveBlending;case"multiply":return r.MultiplyBlending;case"none":return r.NoBlending;default:return r.NormalBlending}}function vl(r,e){switch(e){case"repeat":return r.RepeatWrapping;case"mirror":return r.MirroredRepeatWrapping;default:return r.ClampToEdgeWrapping}}function dh(r,e){return e==="nearest"?r.NearestFilter:r.LinearFilter}function hh(r,e){return e==="nearest"?r.NearestFilter:r.LinearMipmapLinearFilter}function fh(r,e){return e==="linear"?r.LinearSRGBColorSpace:r.SRGBColorSpace}function mh(r,e){switch(e){case"low":return{type:r.PCFShadowMap,mapSize:512};case"high":return{type:r.PCFSoftShadowMap,mapSize:4096};default:return{type:r.PCFSoftShadowMap,mapSize:2048}}}function ph(r,e){switch(e){case"none":return r.NoToneMapping;case"linear":return r.LinearToneMapping;case"reinhard":return r.ReinhardToneMapping;case"cineon":return r.CineonToneMapping;case"agx":return r.AgXToneMapping;case"neutral":return r.NeutralToneMapping;default:return r.ACESFilmicToneMapping}}function St(r,e,t){let[n,i,s,a]=typeof t=="string"?ch(t):t;return e.setRGB(n,i,s,r.SRGBColorSpace),a}function _l(r,e){let t=new r.Color;return St(r,t,e),t}function Cl(r){let[,,,e]=typeof r=="string"?ch(r):r;return e}import{cylinderRadii as By,evaluateParametric as gh,evaluateRoundedBox as Dy,resolveBevel3D as Oy,resolveVector3 as yh,segmentsOf as xt,toPathString as Ly}from"@motionscript/core";function Qr(r,e){switch(e.type){case"box":{let[t,n,i]=xt(e.segments,[1,1,1]),s=e.width??1,a=e.height??1,o=e.depth??1;return(e.cornerRadius??0)>0?Pl(r,Dy({width:s,height:a,depth:o,radius:e.cornerRadius,segments:[t,n,i]})):new r.BoxGeometry(s,a,o,t,n,i)}case"sphere":{let[t,n]=xt(e.segments,[32,16]);return new r.SphereGeometry(e.radius??1,t,n,He(e.startAngle??0),He(e.sweep??360),He(e.startLatitude??0),He(e.latitudeSweep??180))}case"plane":{let[t,n]=xt(e.segments,[1,1]);return new r.PlaneGeometry(e.width??1,e.height??1,t,n)}case"cylinder":{let[t,n]=By(e.radius),[i,s]=xt(e.segments,[32,1]);return new r.CylinderGeometry(t,n,e.height??1,i,s,!(e.capped??!0),He(e.startAngle??0),He(e.sweep??360))}case"cone":{let[t,n]=xt(e.segments,[32,1]);return new r.ConeGeometry(e.radius??1,e.height??1,t,n,!(e.capped??!0),He(e.startAngle??0),He(e.sweep??360))}case"torus":{let[t,n]=xt(e.segments,[16,48]),i=new r.TorusGeometry(e.radius??1,e.thickness??.4,t,n,He(e.sweep??360));return e.startAngle&&i.rotateZ(He(e.startAngle)),i}case"torusKnot":{let[t,n]=xt(e.segments,[64,8]),[i,s]=e.windings??[2,3];return new r.TorusKnotGeometry(e.radius??1,e.thickness??.4,t,n,i,s)}case"circle":{let[t]=xt(e.segments,[32]);return new r.CircleGeometry(e.radius??1,t,He(e.startAngle??0),He(e.sweep??360))}case"ring":{let[t,n]=xt(e.segments,[32,1]);return new r.RingGeometry(e.innerRadius??.5,e.radius??1,t,n,He(e.startAngle??0),He(e.sweep??360))}case"capsule":{let[t,n]=xt(e.segments,[16,8]);return new r.CapsuleGeometry(e.radius??.5,e.height??1,n,t)}case"polyhedron":{let[t]=xt(e.segments,[1]);return Ny(r,e.shape,e.radius??1,e.segments===void 0?0:t)}case"extrude":return zy(r,e);case"lathe":{let[t]=xt(e.segments,[12]);return new r.LatheGeometry(e.points.map(n=>Gy(r,n)),t,He(e.startAngle??0),He(e.sweep??360))}case"tube":{let[t,n]=xt(e.segments,[64,8]);return new r.TubeGeometry(new r.CatmullRomCurve3(e.points.map(i=>qy(r,i)),e.closed??!1),t,e.radius??1,n,e.closed??!1)}case"buffer":return Pl(r,e);case"parametric":return Pl(r,gh(e));case"edges":{let t=Qr(r,e.source),n=new r.EdgesGeometry(t,e.thresholdAngle??1);return t.dispose(),n}case"wireframe":{let t=Qr(r,e.source),n=new r.WireframeGeometry(t);return t.dispose(),n}case"modelGeometry":return Uy(vn(e.src)?.scene,e.node)?.geometry.clone()??new r.BufferGeometry;default:return new r.BufferGeometry}}function Uy(r,e){if(!r)return null;if(e!==void 0){let n=r.getObjectByName(e);return n?.isMesh?n:null}let t=null;return r.traverse(n=>{let i=n;t===null&&i.isMesh&&(t=i)}),t}function Ny(r,e,t,n){switch(e){case"tetrahedron":return new r.TetrahedronGeometry(t,n);case"octahedron":return new r.OctahedronGeometry(t,n);case"dodecahedron":return new r.DodecahedronGeometry(t,n);default:return new r.IcosahedronGeometry(t,n)}}function zy(r,e){let t=e.path,n=typeof t=="object"&&"toPathState"in t?t.toPathState().data:t,i=Vy(r,Ly(n));if(i.length===0)return new r.BufferGeometry;let[s]=xt(e.segments,[12]),a=Oy(e.bevel);return new r.ExtrudeGeometry(i,{depth:e.depth??1,curveSegments:s,bevelEnabled:a!==null,bevelThickness:a?.thickness??.2,bevelSize:a?.size??.1,bevelOffset:a?.offset??0,bevelSegments:a?.segments??3})}function Vy(r,e){let t=[],n=null,i=0,s=0,a=e.match(/[MLCQZmlcqz][^MLCQZmlcqz]*/g)??[];for(let o of a){let c=o[0],l=(o.slice(1).match(/-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]).map(Number);switch(c){case"M":case"m":{n&&t.push(n),n=new r.Shape,i=l[0]??0,s=l[1]??0,n.moveTo(i,s);break}case"L":case"l":{if(!n)break;for(let u=0;u+1<l.length;u+=2)i=l[u],s=l[u+1],n.lineTo(i,s);break}case"C":case"c":{if(!n)break;for(let u=0;u+5<l.length;u+=6)n.bezierCurveTo(l[u],l[u+1],l[u+2],l[u+3],l[u+4],l[u+5]),i=l[u+4],s=l[u+5];break}case"Q":case"q":{if(!n)break;for(let u=0;u+3<l.length;u+=4)n.quadraticCurveTo(l[u],l[u+1],l[u+2],l[u+3]),i=l[u+2],s=l[u+3];break}case"Z":case"z":{n?.closePath();break}}}return n&&t.push(n),t}function Pl(r,e){let t=new r.BufferGeometry;return t.setAttribute("position",new r.BufferAttribute(Wa(e.position),3)),e.normal&&t.setAttribute("normal",new r.BufferAttribute(Wa(e.normal),3)),e.uv&&t.setAttribute("uv",new r.BufferAttribute(Wa(e.uv),2)),e.color&&t.setAttribute("color",new r.BufferAttribute(Wa(e.color),3)),e.index&&t.setIndex(new r.BufferAttribute(Wy(e.index),1)),wh(e)&&bh(t),t}var El="derivedNormals";function wh(r){return r.computeNormals===!0&&!r.normal}function bh(r){r.computeVertexNormals(),r.userData[El]=!0}function kh(r,e){if(!Ha(r,"position",e.position,3))return!1;let t=wh(e);if(!(t&&r.userData[El]===!0)&&!Ha(r,"normal",e.normal,3)||!Ha(r,"uv",e.uv,2)||!Ha(r,"color",e.color,3))return!1;if(e.index){let i=r.getIndex();if(!i||i.array.length!==e.index.length)return!1;i.array.set(e.index),i.needsUpdate=!0}return t?bh(r):r.userData[El]=!1,r.computeBoundingSphere(),!0}function Ha(r,e,t,n){let i=r.getAttribute(e);return t?!i||i.array.length!==t.length||i.itemSize!==n?!1:(i.array.set(t),i.needsUpdate=!0,!0):i===void 0}function _n(r){let e=[r.type];r.type==="modelGeometry"&&e.push(`loaded=${vn(r.src)?"1":"0"}`);let t=r;for(let n of Object.keys(t).sort()){if(n==="type"||n==="revision"||n==="staticData")continue;let i=t[n];if(i!==void 0)if(n==="source")e.push(`source=${_n(i)}`);else{if(typeof i=="function")continue;Hy(i)?e.push(`${n}#${i.length}`):Array.isArray(i)?e.push(`${n}=${JSON.stringify(i)}`):typeof i=="object"?e.push(`${n}=${JSON.stringify(i)}`):e.push(`${n}=${String(i)}`)}}return e.join("|")}function Sh(r){return r.type==="parametric"?!0:r.type!=="buffer"?!1:r.staticData!==!0}function xh(r){return r.type==="parametric"?gh(r):r}function Hy(r){return ArrayBuffer.isView(r)?!0:Array.isArray(r)&&r.length>4}function Wa(r){return r instanceof Float32Array?r:new Float32Array(Array.from(r))}function Wy(r){return r instanceof Uint32Array?r:new Uint32Array(Array.from(r))}function qy(r,e){let t=yh(e);return new r.Vector3(t.x,t.y,t.z)}function Gy(r,e){let t=yh(e);return new r.Vector2(t.x,t.y)}import{STRUCTURAL_MATERIAL_KEYS as vh}from"@motionscript/core";var Ml=["map","alphaMap","aoMap","normalMap","displacementMap","envMap","lightMap","emissionMap","roughnessMap","metalnessMap","specularMap","gradientMap","matcap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap"],Il={emission:"emissive",emissionStrength:"emissiveIntensity",emissionMap:"emissiveMap"},Ky=new Set(["normalMap","roughnessMap","metalnessMap","aoMap","displacementMap","alphaMap","clearcoatRoughnessMap","clearcoatNormalMap","transmissionMap","thicknessMap"]),Th=["color","emission","specular","sheenColor","specularColor","attenuationColor"];function jy(r){let e=r;return e.transparent===!0||typeof e.opacity=="number"&&e.opacity<1||e.alphaMap!==void 0||typeof e.transmission=="number"&&e.transmission>0||e.color!==void 0&&Cl(e.color)<1}function $y(r,e){switch(e.type){case"basic":return new r.MeshBasicMaterial;case"standard":return new r.MeshStandardMaterial;case"physical":return new r.MeshPhysicalMaterial;case"phong":return new r.MeshPhongMaterial;case"lambert":return new r.MeshLambertMaterial;case"toon":return new r.MeshToonMaterial;case"normal":return new r.MeshNormalMaterial;case"depth":return new r.MeshDepthMaterial;case"matcap":return new r.MeshMatcapMaterial;case"points":return new r.PointsMaterial;case"lineBasic":return new r.LineBasicMaterial;case"lineDashed":return new r.LineDashedMaterial;case"sprite":return new r.SpriteMaterial;case"shadow":return new r.ShadowMaterial;case"shader":return Xy(r,e);default:return new r.MeshStandardMaterial}}function Xy(r,e){let t=e.raw?r.RawShaderMaterial:r.ShaderMaterial;return new t({vertexShader:e.vertex,fragmentShader:e.fragment,defines:e.defines,uniforms:{}})}function xr(r,e,t){let n=$y(r,e);return Yr(r,n,e,t,!0),n}function Yr(r,e,t,n,i=!1){let s=t,a=e,o;for(let l of Th){let u=s[l];if(u===void 0)continue;let d=Il[l]??l,h=a[d];if(h&&typeof h=="object"&&"setRGB"in h?St(r,h,u):a[d]=_l(r,u),l==="color"){let f=Cl(u);f<1&&(o=f)}}for(let l of Object.keys(s)){if(l==="type"||l==="params"||Th.includes(l)||Ml.includes(l)||l==="uniforms"||l==="vertex"||l==="fragment"||l==="defines"||l==="raw"||l==="extends"||!i&&vh.includes(l)||l==="transparent")continue;let u=s[l];if(u!==void 0)switch(l){case"faces":e.side=lh(r,u);break;case"shading":a.flatShading=u==="flat";break;case"blend":e.blending=uh(r,u);break;case"normalScale":Qy(r,a,u);break;case"rotation":a.rotation=He(u);break;case"iridescenceThicknessRange":a.iridescenceThicknessRange=[...u];break;case"width":a.linewidth=u;break;case"anisotropyRotation":a.anisotropyRotation=He(u);break;default:a[Il[l]??l]=u;break}}o!==void 0&&s.opacity===void 0&&(e.opacity=o);let c=jy(t);!e.transparent&&c&&(e.transparent=!0,e.needsUpdate=!0),s.depthWrite===void 0&&(e.depthWrite=!c);for(let l of Ml){let u=s[l];u!==void 0&&(a[Il[l]??l]=n.resolve(u,Ky.has(l)?"linear":"srgb"))}if(t.type==="shader"&&Yy(r,e,t.uniforms,n),t.params)for(let l of Object.keys(t.params))a[l]=t.params[l];i&&(e.needsUpdate=!0)}function Qy(r,e,t){let n=e.normalScale,i=typeof t=="number"?t:t.x,s=typeof t=="number"?t:t.y;n&&"set"in n?n.set(i,s):e.normalScale=new r.Vector2(i,s)}function Yy(r,e,t,n){if(t)for(let i of Object.keys(t)){let s=Zy(r,t[i],n),a=e.uniforms[i];a?a.value=s:e.uniforms[i]={value:s}}}function Zy(r,e,t){if(typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return Jy(e)?t.resolve(e,"srgb"):_l(r,e);if(Array.isArray(e)){let n=e;switch(n.length){case 2:return new r.Vector2(n[0],n[1]);case 3:return new r.Vector3(n[0],n[1],n[2]);case 4:return new r.Vector4(n[0],n[1],n[2],n[3]);default:return[...n]}}if(typeof e=="object"&&e!==null){let n=e;if("src"in n||"data"in n)return t.resolve(e,"srgb");if("w"in n)return new r.Vector4(n.x,n.y,n.z,n.w);if("z"in n)return new r.Vector3(n.x,n.y,n.z);if("y"in n)return new r.Vector2(n.x,n.y)}return e}function Jy(r){return r.startsWith("/")||r.startsWith(".")||/\.(png|jpe?g|webp|avif|svg|ktx2?|hdr|exr)$/i.test(r)}function Cn(r){let e=r,t=[r.type];for(let n of vh){let i=e[n];i!==void 0&&t.push(`${n}=${JSON.stringify(i)}`)}for(let n of Ml)e[n]!==void 0&&t.push(`+${n}`);return r.type==="shader"&&(t.push(`v=${Ah(r.vertex)}`,`f=${Ah(r.fragment)}`),r.uniforms&&t.push(`u=${Object.keys(r.uniforms).sort().join(",")}`)),r.params&&t.push(`params=${JSON.stringify(r.params)}`),t.join("|")}function Ah(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}import{resolveShadowOptions3D as _h,resolveVector3 as ew}from"@motionscript/core";var tw=4*Math.PI;function Ch(r,e){switch(e.type){case"ambient":return new r.AmbientLight;case"hemisphere":return new r.HemisphereLight;case"directional":return new r.DirectionalLight;case"point":return new r.PointLight;case"spot":return new r.SpotLight;case"area":return new r.RectAreaLight;default:return new r.AmbientLight}}function Ph(r,e,t){let n=t;if(t.type==="hemisphere"){let s=e;t.sky!==void 0&&St(r,s.color,t.sky),t.ground!==void 0&&St(r,s.groundColor,t.ground)}else n.color!==void 0&&St(r,e.color,n.color);if(n.intensity!==void 0){let s=t.type==="point"||t.type==="spot"?tw:1;e.intensity=n.intensity*s}let i=e;if(n.distance!==void 0&&(i.distance=n.distance),n.decay!==void 0&&(i.decay=n.decay),n.penumbra!==void 0&&(i.penumbra=n.penumbra),n.angle!==void 0&&(i.angle=He(n.angle)),n.width!==void 0&&(i.width=n.width),n.height!==void 0&&(i.height=n.height),t.params)for(let s of Object.keys(t.params))i[s]=t.params[s]}function Eh(r,e,t){let n=t;if(!("target"in e))return;let i=e.target;if(n.target===void 0){i.parent===e&&(e.remove(i),i.position.set(0,0,0),i.updateMatrixWorld());return}let s=ew(n.target);i.parent||e.add(i),e.updateWorldMatrix(!0,!1),i.position.copy(e.worldToLocal(new r.Vector3(s.x,s.y,s.z))),i.updateMatrixWorld()}function Ih(r,e,t){if(!("shadow"in r)||!r.shadow)return;let n=e.shadow,i=n===void 0?null:_h(n);if(r.castShadow=i!==null,!i)return;let s=r.shadow,a=s.camera;s.radius=1+(i.softness??.5)*8;let o=i.extent??rw(t),c=!1;e.type==="directional"&&a.left!==-o&&(a.left=-o,a.right=o,a.top=o,a.bottom=-o,c=!0);let l=Math.max(.05,o*.05),u=Math.max(l+1,o*8);a.near!==l&&(a.near=l,c=!0),a.far!==u&&(a.far=u,c=!0),c&&a.updateProjectionMatrix();let d=s.mapSize.x||2048;if(s.bias=-(u-l)/(d*512),s.normalBias=o*.01,i.params){let h=s;for(let f of Object.keys(i.params))h[f]=i.params[f]}}function rw(r){if(!r)return 10;let e=Math.max(r.max.x-r.min.x,r.max.y-r.min.y,r.max.z-r.min.z);return Math.max(1,e*.75)}function Mh(r){let e=r.shadow,t=e!==void 0&&_h(e)!==null,n=[r.type];return t&&n.push("shadow"),r.params&&n.push(`params=${JSON.stringify(r.params)}`),n.join("|")}import{resolveCameraPlacement as aw}from"@motionscript/core";import{resolveVector3 as qa,shadowCasts as nw,shadowReceives as iw}from"@motionscript/core";function ai(r,e){if(!e){r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),r.visible=!0,Fh(r,void 0);return}if(e.position!==void 0){let t=qa(e.position);r.position.set(t.x,t.y,t.z)}else r.position.set(0,0,0);if(e.scale!==void 0){let t=qa(e.scale);r.scale.set(t.x,t.y,t.z)}else r.scale.set(1,1,1);if(e.lookAt!==void 0){let t=qa(e.lookAt);r.lookAt(t.x,t.y,t.z)}else if(e.quaternion!==void 0){let t=e.quaternion;r.quaternion.set(t.x,t.y,t.z,t.w)}else e.rotation!==void 0?sw(r,e.rotation):r.rotation.set(0,0,0);r.visible=e.visible!==!1,Fh(r,e.shadow),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder)}function Fh(r,e){r.isLight||(r.castShadow=nw(e),r.receiveShadow=iw(e))}function sw(r,e){let t=qa(e),n=e?.order;r.rotation.set(He(t.x),He(t.y),He(t.z),n??"XYZ")}function Rh(r,e,t){return t.type==="perspective"?e instanceof r.PerspectiveCamera:e instanceof r.OrthographicCamera}function Fl(r,e){return e?.type==="orthographic"?new r.OrthographicCamera:new r.PerspectiveCamera}function Bh(r,e,t,n,i,s){let a=i>0?n/i:1;if(!t){let u=e;u.fov=50,u.near=.1,u.far=1e3,u.aspect!==a&&(u.aspect=a),u.position.set(0,0,5),u.lookAt(0,0,0),u.updateProjectionMatrix();return}let o=ow(t,s),c=!1;if(t.type==="perspective"){let u=e,d=t.fov??50,h=t.zoom??1;u.fov!==d&&(u.fov=d,c=!0),u.near!==o.near&&(u.near=o.near,c=!0),u.far!==o.far&&(u.far=o.far,c=!0),u.aspect!==a&&(u.aspect=a,c=!0),u.zoom!==h&&(u.zoom=h,c=!0)}else{let u=e,d=t.zoom??1,h=(t.frustumHeight??10)/2,f=-h*a,p=h*a;u.left!==f&&(u.left=f,c=!0),u.right!==p&&(u.right=p,c=!0),u.top!==h&&(u.top=h,c=!0),u.bottom!==-h&&(u.bottom=-h,c=!0),u.near!==o.near&&(u.near=o.near,c=!0),u.far!==o.far&&(u.far=o.far,c=!0),u.zoom!==d&&(u.zoom=d,c=!0)}let l=aw(t);if(ai(e,{...t,position:l.position,lookAt:l.lookAt}),t.params){let u=e;for(let d of Object.keys(t.params))u[d]=t.params[d];c=!0}c&&e.updateProjectionMatrix()}function ow(r,e){if(r.near!==void 0&&r.far!==void 0)return{near:r.near,far:r.far};let t=e?Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z):10,n=r.distance??Math.max(t,1)*2,i=Math.max(t,n,1);return{near:r.near??Math.max(.01,i/1e3),far:r.far??i*10}}import{resolveVector3 as cw}from"@motionscript/core";function Dh(r,e,t){if(!t){e.fog=null;return}if(t.density!==void 0){let s=t.density;if(e.fog instanceof r.FogExp2){t.color!==void 0&&St(r,e.fog.color,t.color),e.fog.density=s;return}e.fog=new r.FogExp2(0,s),t.color!==void 0&&St(r,e.fog.color,t.color);return}let n=t.near??1,i=t.far??1e3;if(e.fog instanceof r.Fog){t.color!==void 0&&St(r,e.fog.color,t.color),e.fog.near=n,e.fog.far=i;return}e.fog=new r.Fog(0,n,i),t.color!==void 0&&St(r,e.fog.color,t.color)}function Oh(r,e,t,n){if(!t){Ga(e),e.environment=null,e.background=null;return}let i=lw(r,e,t,n);if(!i){e.background=null;return}if(e.environment=i,e.environmentIntensity=t.intensity??1,t.rotation!==void 0&&"environmentRotation"in e){let{x:s,y:a,z:o}=cw(t.rotation);e.environmentRotation.set(He(s),He(a),He(o))}t.background?(e.background=i,e.backgroundBlurriness=t.blur??0,e.backgroundIntensity=t.intensity??1):e.background=null}function Ga(r){r.userData.__roomEnvironment?.texture.dispose(),r.userData.__roomEnvironment=void 0}function lw(r,e,t,n){if(t.preset===void 0||!n)return null;let i=e.userData.__roomEnvironment;if(i?.renderer===n)return i.texture;Ga(e);let s=new r.PMREMGenerator(n),a=new r.Scene;a.background=new r.Color(12303291);let o=s.fromScene(a,.04);return s.dispose(),e.userData.__roomEnvironment={renderer:n,texture:o.texture},o.texture}function Uh(r){return vn(r)?.clone()??null}function Nh(r){return vn(r)!==null}function zh(r,e,t,n,i){let s=vn(t)?.animations??[];if(s.length===0)return i;if(!n||n.length===0){if(i)for(let o of i.actions.values())o.enabled=!1;return i}let a=i??{mixer:new r.AnimationMixer(e),actions:new Map};for(let o of a.actions.values())o.enabled=!1;for(let o of n){let c=dw(s,o.clip);if(!c)continue;let l=a.actions.get(c.name);l||(l=a.mixer.clipAction(c),a.actions.set(c.name,l)),l.enabled=!0,l.setEffectiveWeight(o.weight??1),l.play(),l.paused=!0,l.time=hw(o.time,c.duration)}return a.mixer.update(0),a}var Lh=new WeakMap;function Vh(r,e,t,n){t&&e.traverse(i=>{let s=i;if(!s.isMesh)return;let a=Array.isArray(s.material)?s.material:[s.material],o=!1,c=a.map(l=>{let u=l?Lh.get(l):void 0;if(u!==void 0&&t[u]!==void 0)return Yr(r,l,t[u],n),l;let d=uw(t,s.name,l?.name);if(d===null)return l;let h=xr(r,t[d],n);return Lh.set(h,d),o=!0,h});o&&(s.material=Array.isArray(s.material)?c:c[0])})}function Hh(r){return r?Object.keys(r).sort().map(e=>`${e}=${JSON.stringify(r[e])}`).join("&"):""}function uw(r,e,t){return r[e]!==void 0?e:t!==void 0&&r[t]!==void 0?t:null}function dw(r,e){return e===void 0?r[0]:typeof e=="number"?r[e]:r.find(t=>t.name===e)}function hw(r,e){if(!Number.isFinite(r)||e<=0)return 0;let t=r%e;return t<0?t+e:t}var Ka=class{three;scene;camera;cache=new Map;frame=0;constructor(e){this.three=e,this.scene=new e.Scene,this.camera=Fl(e,null)}sync(e,t,n,i,s=null){this.frame++;let a=this.three,o=[-1],c=[this.scene],l=[""],u=new Map,d=[],h=null,f=!1;for(let b of e.ops()){if(b.kind==="pop"){c.length>1&&(c.pop(),o.pop(),l.pop());continue}o[o.length-1]++;let k=l[l.length-1],T=c[c.length-1];if(b.kind==="push"){let M=k?`${k}.${o[o.length-1]}`:String(o[o.length-1]),C=this.resolveGroup(M,b.transform,T);c.push(C),o.push(-1),l.push(b.transform?.key?`@${b.transform.key}`:M);continue}if(b.kind==="camera"){h={descriptor:b.camera,parent:T},f=!0;continue}let x=pw(b),v=this.resolveDrawable(b,mw(k,b,x,u),T,i,x);v&&b.kind==="light"&&d.push({light:v.object,descriptor:b.light})}this.sweep();let p=this.sceneBounds();for(let{light:b,descriptor:k}of d)Eh(a,b,k),Ih(b,k,p);h&&this.resolveCamera(h.descriptor,t,n,h.parent,p),Dh(a,this.scene,e.fogDescriptor()),Oh(a,this.scene,e.environmentDescriptor(),s?.active()??null);let m=e.shadowSettings(),g=e.toneSettings(),y=mh(a,m?.quality);s?.applySettings(a,{shadowsEnabled:m?.enabled===!0,shadowType:y.type,toneMapping:ph(a,g?.mapping),toneMappingExposure:g?.exposure??1});for(let{light:b}of d){let k=b.shadow;k&&k.mapSize.x!==y.mapSize&&(k.mapSize.set(y.mapSize,y.mapSize),k.map?.dispose(),k.map=null)}return f||this.resolveCamera(null,t,n,this.scene,p),{scene:this.scene,camera:this.camera}}sceneBounds(){this.scene.updateMatrixWorld(!0);let e=new this.three.Box3().setFromObject(this.scene);return e.isEmpty()?null:{min:{x:e.min.x,y:e.min.y,z:e.min.z},max:{x:e.max.x,y:e.max.y,z:e.max.z}}}resolveGroup(e,t,n){let i=t?.key?`@${t.key}|push`:`${e}|push`,s=this.cache.get(i);return(!s||s.kind!=="push")&&(this.discard(s),s={object:new this.three.Group,kind:"push",seen:this.frame},this.cache.set(i,s)),s.seen=this.frame,ai(s.object,t),s.object.parent!==n&&n.add(s.object),s.object}resolveDrawable(e,t,n,i,s){let a=this.cache.get(t);if(a&&a.kind!==e.kind&&(this.discard(a),a=void 0),a=this.ensure(a,t,e,i,s),!!a)return a.seen=this.frame,this.mutate(a,e,i),a.object.parent!==n&&n.add(a.object),a}ensure(e,t,n,i,s){if(e&&yw(e,s))return e;this.discard(e);let a=this.build(n,i);if(!a)return;let o={object:a,kind:n.kind,seen:this.frame,...s},c=n.geometry;return c?.type==="parametric"&&(o.parametricRevision=c.revision),this.cache.set(t,o),o}build(e,t){let n=this.three;switch(e.kind){case"mesh":{let i=Qr(n,e.geometry),s=this.buildMaterials(e.material,t);return new n.Mesh(i,s)}case"light":return Ch(n,e.light);case"instances":{let i=Qr(n,e.geometry),s=xr(n,e.material,t),a=new n.InstancedMesh(i,s,Math.max(1,e.instances.length));return a.instanceMatrix.setUsage(n.DynamicDrawUsage),a}case"points":{let i=Qr(n,e.geometry),s=xr(n,e.material,t);return new n.Points(i,s)}case"line":{let i=Qr(n,e.geometry),s=xr(n,e.material,t),a=e.mode==="segments"?new n.LineSegments(i,s):e.mode==="loop"?new n.LineLoop(i,s):new n.Line(i,s);return e.material.type==="lineDashed"&&a.computeLineDistances(),a}case"sprite":{let i=xr(n,e.material,t);return new n.Sprite(i)}case"model":{let i=Uh(e.src);return i||ah(fw("gltf",e.src),"gltf"),i}default:return null}}buildMaterials(e,t){return Array.isArray(e)?e.map(n=>xr(this.three,n,t)):xr(this.three,e,t)}mutate(e,t,n){let i=this.three;switch(ai(e.object,t.transform),t.kind){case"mesh":case"points":case"line":{let s=e.object;this.refreshDynamicGeometry(s,t.geometry,e),this.applyMaterials(s.material,(t.kind==="mesh",t.material),n);break}case"instances":{let s=e.object;this.refreshDynamicGeometry(s,t.geometry,e),Yr(i,s.material,t.material,n),this.writeInstances(s,t.instances,t.colors);break}case"sprite":Yr(i,e.object.material,t.material,n);break;case"light":Ph(i,e.object,t.light);break;case"model":e.modelPlayback=zh(i,e.object,t.src,t.animation,e.modelPlayback),Vh(i,e.object,t.override,n);break}}applyMaterials(e,t,n){if(Array.isArray(e)&&Array.isArray(t)){let i=Math.min(e.length,t.length);for(let s=0;s<i;s++)Yr(this.three,e[s],t[s],n);return}!Array.isArray(e)&&!Array.isArray(t)&&Yr(this.three,e,t,n)}refreshDynamicGeometry(e,t,n){if(!Sh(t))return;if(t.type==="parametric"&&t.revision!==void 0){if(n.parametricRevision===t.revision)return;n.parametricRevision=t.revision}let i=xh(t);kh(e.geometry,i)||(e.geometry.dispose(),e.geometry=Qr(this.three,i),n.geometrySig=_n(t),e.computeLineDistances&&e.isLine&&e.computeLineDistances())}writeInstances(e,t,n){let i=this.three,s=e.userData.__scratch??(e.userData.__scratch=new i.Object3D),a=Math.min(t.length,e.count);for(let o=0;o<a;o++)ai(s,t[o]),s.updateMatrix(),e.setMatrixAt(o,s.matrix);if(e.instanceMatrix.needsUpdate=!0,a<e.count){s.position.set(0,0,0),s.rotation.set(0,0,0),s.scale.set(0,0,0),s.updateMatrix();for(let o=a;o<e.count;o++)e.setMatrixAt(o,s.matrix)}if(n){let o=new i.Color;for(let c=0;c<Math.min(n.length,e.count);c++)St(i,o,n[c]),e.setColorAt(c,o);e.instanceColor&&(e.instanceColor.needsUpdate=!0)}}resolveCamera(e,t,n,i,s){let a=this.three;e&&!Rh(a,this.camera,e)&&(this.camera=Fl(a,e)),Bh(a,this.camera,e,t,n,s),i!==this.scene?this.camera.parent!==i&&i.add(this.camera):this.camera.parent&&this.camera.removeFromParent()}sweep(){for(let[e,t]of this.cache)t.seen!==this.frame&&(this.discard(t),this.cache.delete(e))}discard(e){e&&(e.object.removeFromParent(),Wh(e.object))}dispose(){for(let e of this.cache.values())this.discard(e);this.cache.clear(),Ga(this.scene),this.scene.environment=null,this.scene.clear()}};function mw(r,e,t,n){let i=`${r}|${e.kind}|${t.geometrySig??""}|${t.materialSig??""}|${t.lightSig??""}|${t.count??""}`,s=n.get(i)??0;return n.set(i,s+1),`${i}#${s}`}function pw(r){switch(r.kind){case"mesh":return{geometrySig:_n(r.geometry),materialSig:gw(r.material)};case"points":return{geometrySig:_n(r.geometry),materialSig:Cn(r.material)};case"line":return{geometrySig:_n(r.geometry),materialSig:`${r.mode}|${Cn(r.material)}`};case"instances":return{geometrySig:_n(r.geometry),materialSig:Cn(r.material),count:r.instances.length};case"sprite":return{materialSig:Cn(r.material)};case"light":return{lightSig:Mh(r.light)};case"model":return{geometrySig:`${r.src}|${Nh(r.src)?"1":"0"}`,materialSig:Hh(r.override)};default:return{}}}function gw(r){return Array.isArray(r)?r.map(Cn).join("&"):Cn(r)}function yw(r,e){return r.geometrySig===e.geometrySig&&r.materialSig===e.materialSig&&r.lightSig===e.lightSig&&r.count===e.count}function Wh(r){let e=r;e.geometry?.dispose?.();let t=e.material;if(Array.isArray(t))for(let n of t)n.dispose();else t?.dispose?.();for(let n of[...r.children])Wh(n)}var qh=null;function Rl(r){qh=r}function vs(){return qh}import{isDataTexture3D as $h,isSurfaceTexture3D as Xh,resolveTexture3D as ww}from"@motionscript/core";var zt=new Map,Dl=new Map,Pn=0,oi=new Map,ja=class{three;assets;surfaceOwner="";rasters;constructor(e,t){this.three=e,this.assets=t}beginFrame(){Pn++}setRasters(e,t){this.surfaceOwner=e,this.rasters=t}resolve(e,t){let n=ww(e),i=bw(e,t,this.surfaceOwner);if(Xh(n)){let o=this.rasters?.get(n);if(!o)return null;let c=zt.get(i);if(c?.resolved)return c.raster!==o&&(this.uploadRaster(c.texture,o),c.raster=o),oi.set(i,Pn),c.texture;let l=this.createRasterTexture(o);return this.applySampler(l,e,t),zt.set(i,{texture:l,resolved:!0,raster:o}),this.touchData(i),l}if(!$h(n))return this.resolveImage(n.src,e,t,i);let s=zt.get(i);if(s?.resolved)return s.revision!==n.revision&&(this.uploadData(s.texture,n),s.revision=n.revision),oi.set(i,Pn),s.texture;let a=this.createDataTexture(n);return this.applySampler(a,e,t),zt.set(i,{texture:a,revision:n.revision,resolved:!0}),this.touchData(i),a}touchData(e){oi.set(e,Pn);for(let[t,n]of oi)n>=Pn-1||(zt.get(t)?.texture.dispose(),zt.delete(t),oi.delete(t))}resolveImage(e,t,n,i){let s=this.assets.getImagePixels(e);if(!s)return null;let a=`${i}|px=${s.width}x${s.height}`,o=zt.get(a);if(o?.resolved){if(o.pixels!==s){let c=o.texture.image;c.data=s.pixels,o.texture.needsUpdate=!0,o.pixels=s}}else{let c=this.createImageTexture(s);this.applySampler(c,t,n),o={texture:c,resolved:!0,pixels:s},zt.set(a,o)}return this.touchLevel(i,a),o.texture}touchLevel(e,t){let n=Dl.get(e);n||Dl.set(e,n=new Map),n.set(t,Pn);for(let[i,s]of n)s>=Pn-1||(zt.get(i)?.texture.dispose(),zt.delete(i),n.delete(i))}createImageTexture(e){let t=new this.three.DataTexture(e.pixels,e.width,e.height,this.three.RGBAFormat,this.three.UnsignedByteType);return t.flipY=!0,t.needsUpdate=!0,t}createRasterTexture(e){let t=new this.three.DataTexture(e.pixels,e.width,e.height,this.three.RGBAFormat,this.three.UnsignedByteType);return t.flipY=!0,t.needsUpdate=!0,t}uploadRaster(e,t){let n=e.image;n.width===t.width&&n.height===t.height?n.data.set(t.pixels):(n.data=t.pixels,n.width=t.width,n.height=t.height),e.needsUpdate=!0}createDataTexture(e){let t=new this.three.DataTexture(jh(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=jh(t.data);n.data.length===i.length?n.data.set(i):n.data=i,e.needsUpdate=!0}applySampler(e,t,n){let i=this.three,s=typeof t=="string"?{}:t;if(e.wrapS=vl(i,s.wrapS),e.wrapT=vl(i,s.wrapT),e.magFilter=dh(i,s.magFilter),e.minFilter=hh(i,s.minFilter),e.colorSpace=fh(i,s.colorSpace??n),s.repeat){let[a,o]=Bl(s.repeat);e.repeat.set(a,o)}if(s.offset){let[a,o]=Bl(s.offset);e.offset.set(a,o)}if(s.center){let[a,o]=Bl(s.center);e.center.set(a,o)}s.rotation!==void 0&&(e.rotation=He(s.rotation)),s.anisotropy!==void 0&&(e.anisotropy=s.anisotropy),s.flipY!==void 0&&(e.flipY=s.flipY),e.generateMipmaps=e.minFilter!==i.NearestFilter&&e.minFilter!==i.LinearFilter}};function bw(r,e,t){if(typeof r=="string")return`${r}|${e}`;let n=r,i=[];for(let s of Object.keys(n).sort())s==="data"||s==="revision"||s!=="source"&&i.push(`${s}=${JSON.stringify(n[s])}`);return $h(r)&&i.push(`data=${r.width}x${r.height}#${xw(r.data)}`),Xh(r)&&i.push(`owner=${t}`,`sfc=${Tw(r)}`),i.push(`cs=${e}`),i.join("|")}var Gh=new WeakMap,kw=0,Kh=new WeakMap,Sw=0;function xw(r){let e=Kh.get(r);return e===void 0&&(e=`d${Sw++}`,Kh.set(r,e)),e}function Tw(r){if(r.identity!==void 0)return r.identity;let e=r.source,t=Gh.get(e);return t===void 0&&(t=`s${kw++}`,Gh.set(e,t)),t}function Bl(r){return Array.isArray(r)?[r[0],r[1]]:[r.x,r.y]}function jh(r){return r instanceof Uint8Array?r:new Uint8Array(Array.from(r))}function Qh(){for(let r of zt.values())r.texture.dispose();zt.clear(),Dl.clear(),oi.clear()}var _s=class{three;assets;host;graphs=new Map;textures;frame=0;touched=new Set;constructor(e,t,n){this.three=e,this.assets=t,this.host=n,this.textures=new ja(e,t)}get frameIndex(){return this.frame}render(e,t,n,i,s={}){let a=this.graphs.get(e);a||(a=new Ka(this.three),this.graphs.set(e,a)),this.touched.add(e),this.textures.setRasters(e,s.rasters),this.host.prepare(this.three,s);let{scene:o,camera:c}=a.sync(t,n,i,this.textures,this.host);return this.host.render(this.three,e,o,c,n,i,s)}beginFrame(){this.frame++,this.touched.clear(),this.textures.beginFrame()}sweep(){for(let[e,t]of this.graphs)this.touched.has(e)||(this.release(e,t),this.graphs.delete(e))}dispose(){for(let[e,t]of this.graphs)this.release(e,t);this.graphs.clear(),this.touched.clear()}release(e,t){t.dispose(),this.host.forgetBuffer(e),this.assets.release3DTexture(e)}get module(){return this.three}},$a=null;function ci(r){let e=kl();if(!e)return null;let t=vs();return t?($a??=new _s(e,r,t),$a):null}function Xa(){$a?.dispose(),$a=null}import{forEachTexture3D as eS,isSurfaceTexture3D as tS}from"@motionscript/core";function Qa(r){return 1/Math.max(r.getDeviceScale(),1e-4)}function Ya(r,e){return e.opacityRealised?1:r.opacity??1}var qe=class{dispose(){}};import{AssetNotLoadedError as jk,isPixelFilter as $k}from"@motionscript/core";var Aw=[224,224,224],vw=[200,200,200],Cs=null;function _w(r){let t=new Uint8Array(4096);for(let n=0;n<32;n++)for(let i=0;i<32;i++){let s=i<16==n<16,[a,o,c]=s?Aw:vw,l=(n*32+i)*4;t[l]=a,t[l+1]=o,t[l+2]=c,t[l+3]=255}return r.MakeImage({width:32,height:32,alphaType:r.AlphaType.Unpremul,colorType:r.ColorType.RGBA_8888,colorSpace:r.ColorSpace.SRGB},t,128)}function Za(r){let e=r.canvasKit;if(Cs??=_w(e),!Cs)return!1;let t=r.getShapeBounds(),n=t?.left??0,i=t?.top??0,s=Cs.makeShaderOptions(e.TileMode.Repeat,e.TileMode.Repeat,e.FilterMode.Nearest,e.MipmapMode.None,[1,0,n,0,1,i,0,0,1]);return r.paint.setShader(s),r.transientPaintObjects.push(s),!0}function Yh(){Cs?.delete(),Cs=null}import{effectSurface as Hk}from"@motionscript/core";var Zh={type:"blur",makeImageFilter(r,e){let t=r.radius/2;return e.ImageFilter.MakeBlur(t,t,e.TileMode.Decal,null)}};var Jh={type:"directionalBlur",makeImageFilter(r,e){if(r.radius<=0)return null;let t=r.radius/2,n=r.angle*Math.PI/180,i=Math.cos(n),s=Math.sin(n),a={filter:e.FilterMode.Linear},o=e.ImageFilter.MakeMatrixTransform([i,s,0,-s,i,0,0,0,1],a,null),c=e.ImageFilter.MakeBlur(t,0,e.TileMode.Decal,o);o.delete();let l=e.ImageFilter.MakeMatrixTransform([i,-s,0,s,i,0,0,0,1],a,c);return c.delete(),l}};var ef={type:"grayscale",makeImageFilter(r,e){let t=Math.max(0,Math.min(1,r.amount)),n=[1-t+t*.2126,t*.7152,t*.0722,0,0,t*.2126,1-t+t*.7152,t*.0722,0,0,t*.2126,t*.7152,1-t+t*.0722,0,0,0,0,0,1,0],i=e.ColorFilter.MakeMatrix(n),s=e.ImageFilter.MakeColorFilter(i,null);return i.delete(),s}};var tf={type:"pixelate",makeImageFilter(r,e,{width:t,height:n}){let i=Math.max(1,Math.min(t,r.blocks.x)),s=Math.max(1,Math.min(n,r.blocks.y)),a=t/i,o=n/s,c={filter:e.FilterMode.Nearest},l=r.sharpColors?{filter:e.FilterMode.Nearest}:{filter:e.FilterMode.Linear},u=-t/2,d=-n/2,h=e.ImageFilter.MakeMatrixTransform([1/a,0,-u/a,0,1/o,-d/o,0,0,1],c,null),f=e.ImageFilter.MakeMatrixTransform([a,0,u,0,o,d,0,0,1],l,h);return h.delete(),f}};var rf={type:"bloom",makeImageFilter(r,e){if(r.radius<=0||r.intensity<=0)return null;let t=Math.max(0,Math.min(1,r.threshold)),n=r.radius/2,i=t<1?1/(1-t):1,s=-t*i,a=[i,0,0,0,s,0,i,0,0,s,0,0,i,0,s,0,0,0,1,0],o=e.ColorFilter.MakeMatrix(a),c=e.ImageFilter.MakeColorFilter(o,null);o.delete();let l=e.ImageFilter.MakeBlur(n,n,e.TileMode.Decal,c);c.delete();let u=l;if(r.intensity!==1){let h=r.intensity,f=[h,0,0,0,0,0,h,0,0,0,0,0,h,0,0,0,0,0,1,0],p=e.ColorFilter.MakeMatrix(f);u=e.ImageFilter.MakeColorFilter(p,l),p.delete(),l.delete()}let d=e.ImageFilter.MakeBlend(e.BlendMode.Screen,null,u);return u.delete(),d}};var nf={type:"vintage",makeImageFilter(r,e){if(r.amount<=0&&r.warmth===0)return null;let t=Math.max(0,Math.min(1,r.amount)),n=Math.max(-1,Math.min(1,r.warmth)),i=(m,g)=>m+(g-m)*t,s=[.393,.769,.189],a=[.349,.686,.168],o=[.272,.534,.131],c=n>0?n*.15:0,l=n<0?-n*.15:0,u=n<0?-n*.05:0,d=n>0?n*.05:0,h=[i(1,s[0]),i(0,s[1]),i(0,s[2]),0,c-u,i(0,a[0]),i(1,a[1]),i(0,a[2]),0,0,i(0,o[0]),i(0,o[1]),i(1,o[2]),0,-l+d,0,0,0,1,0],f=e.ColorFilter.MakeMatrix(h),p=e.ImageFilter.MakeColorFilter(f,null);return f.delete(),p}};var sf={type:"chromaticAberration",makeImageFilter(r,e){if(r.amount<=0)return null;let t=r.angle*Math.PI/180,n=Math.cos(t)*r.amount,i=Math.sin(t)*r.amount,s=[1.4,-.2,-.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],a=e.ColorFilter.MakeMatrix(s),o=e.ImageFilter.MakeOffset(n,i,null),c=e.ImageFilter.MakeColorFilter(a,o);a.delete(),o.delete();let l=[0,0,0,0,0,0,0,0,0,0,-.2,-.2,1.4,0,0,0,0,0,1,0],u=e.ColorFilter.MakeMatrix(l),d=e.ImageFilter.MakeOffset(-n,-i,null),h=e.ImageFilter.MakeColorFilter(u,d);u.delete(),d.delete();let f=e.ImageFilter.MakeBlend(e.BlendMode.Screen,null,c);c.delete();let p=e.ImageFilter.MakeBlend(e.BlendMode.Screen,f,h);return f.delete(),h.delete(),p}};var Cw=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],li=.2126,ui=.7152,di=.0722;function Pw(r){switch(r){case"red":return[-1,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];case"green":return[1,0,0,0,0,0,-1,0,0,1,0,0,1,0,0,0,0,0,1,0];case"blue":return[1,0,0,0,0,0,1,0,0,0,0,0,-1,0,1,0,0,0,1,0];case"alpha":return[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,-1,1];case"hue":return[2*li-1,2*ui,2*di,0,0,2*li,2*ui-1,2*di,0,0,2*li,2*ui,2*di-1,0,0,0,0,0,1,0];case"luminance":return[1-2*li,-2*ui,-2*di,0,1,-2*li,1-2*ui,-2*di,0,1,-2*li,-2*ui,1-2*di,0,1,0,0,0,1,0];default:return[-1,0,0,0,1,0,-1,0,0,1,0,0,-1,0,1,0,0,0,1,0]}}var af={type:"invert",makeImageFilter(r,e){let t=Math.max(0,Math.min(1,r.strength));if(t===0)return null;let n=Pw(r.channel),i=Cw.map((o,c)=>o+(n[c]-o)*t),s=e.ColorFilter.MakeMatrix(i),a=e.ImageFilter.MakeColorFilter(s,null);return s.delete(),a}};var hi=new Map,Ew=64,Ol=!1;function ue(r,e){let t=hi.get(r);if(t)return t;let n=e.RuntimeEffect.Make(r,i=>{console.warn("[SkSL] Compilation error:",i)});return n&&hi.set(r,n),hi.size>Ew&&!Ol&&(Ol=!0,console.warn(`[SkSL] ${hi.size} distinct shader sources have been compiled. If a shader's source is built per frame (e.g. a value interpolated into a template literal), keep the source constant and move what changes into a uniform \u2014 uniform values are an in-place write, a new source is a new program.`)),n??null}function of(){for(let r of hi.values())r.delete();hi.clear(),Ol=!1}import{resolveEffectAxis as Iw}from"@motionscript/core";function fi(r,e){return r.mode==="backdrop"?[0,0]:[e.centerX-e.width/2,e.centerY-e.height/2]}var Mw=`
696
- 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 Fw(r,e,t,n,i=[0,0]){if(!(r.strength>0))return null;let s=ue(Mw,e);if(!s)return null;let a=Iw(r.axis),o=r.strength*n;return s.makeShaderWithChildren([i[0],i[1],o*a.x,o*a.y],[t])}var cf={type:"scatter",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Fw(r,e,t,n.scale,fi(r,n))};import{resolveEffectAxis as Rw,resolveMotionBlurAlignment as Bw}from"@motionscript/core";var Dw=32,Ow=64;function lf(r,e,t){if(t<=0||r.strength<=0||r.length<=0)return null;let n=Rw(r.axis),i=r.length/100,s=e.x*t*n.x*i*r.strength,a=e.y*t*n.y*i*r.strength,o=Math.hypot(s,a);return o<.01?null:{type:"motionBlurResolved",angle:Math.atan2(a,s)*180/Math.PI,radius:o,phase:Bw(r.alignment),samples:r.samples}}var uf={type:"motionBlurResolved",makeImageFilter(r,e){if(r.radius<=0)return null;let t=r.angle*Math.PI/180,n=Math.cos(t),i=Math.sin(t),s=r.phase*r.radius/2,a=n*s,o=i*s,c=Math.min(Math.round(r.samples),Ow);return c>Dw?Uw(r,e,n,i,a,o,c):Lw(r,e,n,i,a,o)}};function Lw(r,e,t,n,i,s){let a=r.radius/2,o={filter:e.FilterMode.Linear},c=i!==0||s!==0?e.ImageFilter.MakeOffset(i,s,null):null,l=e.ImageFilter.MakeMatrixTransform([t,n,0,-n,t,0,0,0,1],o,c);c?.delete();let u=e.ImageFilter.MakeBlur(a,0,e.TileMode.Decal,l);l.delete();let d=e.ImageFilter.MakeMatrixTransform([t,-n,0,n,t,0,0,0,1],o,u);return u.delete(),d}function Uw(r,e,t,n,i,s,a){let o=r.radius/2,c=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1/a,0],l=e.ColorFilter.MakeMatrix(c),u=null;for(let d=0;d<a;d++){let h=a===1?0:d/(a-1)*2-1,f=t*o*h+i,p=n*o*h+s,m=e.ImageFilter.MakeOffset(f,p,null),g=e.ImageFilter.MakeColorFilter(l,m);if(m.delete(),u===null)u=g;else{let y=e.ImageFilter.MakeBlend(e.BlendMode.Plus,u,g);u.delete(),g.delete(),u=y}}return l.delete(),u}import{normalizeUniforms as Vw,writeUniforms as Hw}from"@motionscript/core";function jt(r,e){switch(e){case"multiply":return r.BlendMode.Multiply;case"screen":return r.BlendMode.Screen;case"overlay":return r.BlendMode.Overlay;case"darken":return r.BlendMode.Darken;case"lighten":return r.BlendMode.Lighten;case"color-dodge":return r.BlendMode.ColorDodge;case"color-burn":return r.BlendMode.ColorBurn;case"hard-light":return r.BlendMode.HardLight;case"soft-light":return r.BlendMode.SoftLight;case"difference":return r.BlendMode.Difference;case"exclusion":return r.BlendMode.Exclusion;case"hue":return r.BlendMode.Hue;case"saturation":return r.BlendMode.Saturation;case"color":return r.BlendMode.Color;case"luminosity":return r.BlendMode.Luminosity;default:return r.BlendMode.SrcOver}}import{describeUniforms as Nw,parseShaderChildren as zw}from"@motionscript/core";var df=new WeakMap;function Ps(r,e){let t=df.get(r);if(t)return t;let n={slots:Nw(r),floats:r.getUniformFloatCount(),children:zw(e)};return df.set(r,n),n}var Ja=new Set;function Zr(r){Ja.has(r)||(Ja.size>512&&Ja.clear(),Ja.add(r),console.warn(`[SkSL] ${r}`))}var hf="u_backdrop";function Ww(r){let{width:e,height:t,centerX:n,centerY:i}=r;return{u_size:[e,t],u_resolution:[e,t],u_half:[e/2,t/2],u_center:[n,i],u_origin:[n-e/2,i-t/2],u_aspect:t===0?0:e/t,u_time:r.time,u_scale:r.scale}}var qw={};function ff(r,e,t){return Hw(r.slots,r.floats,Vw(e.uniforms),t,e.source)}function Gw(r,e){let t=[];for(let n of r.children){if(n.name===hf&&n.kind==="shader"){t.push(e);continue}return Zr(`a backdrop shader effect declares "${n.name}", which nothing supplies \u2014 an effect can only sample "${hf}".`),null}return t}var mf={type:"shader",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop"&&r.mode==="backdrop",makeShader(r,e,t,n){let i=ue(r.source,e);if(!i)return null;let s=Ps(i,r.source),a=ff(s,r,Ww(n)),o=Gw(s,t);if(!o)return null;let c=i.makeShaderWithChildren(a,o);return c||(Zr(`a backdrop shader effect's uniform buffer was rejected (${s.floats} floats, ${s.slots.length} uniform(s)).`),null)},makeImageFilter(r,e){if(r.mode==="backdrop")return null;let t=ue(r.source,e);if(!t)return null;let n=Ps(t,r.source);if(n.children.length>0)return Zr(`a foreground shader effect declares "${n.children[0].name}", but only a backdrop shader is given a child to sample \u2014 set mode: 'backdrop'.`),null;let i=t.makeShader(ff(n,r,qw));if(!i)return null;let s=e.ImageFilter.MakeShader(i);i.delete();let a=jt(e,r.blendMode??"screen"),o=e.ImageFilter.MakeBlend(a,null,s);return s.delete(),o}};var Ul=new WeakMap,Nl=new Set;function Kw(r,e){let t=Ul.get(r.table);if(t)return t.shader;let n=r.size;if(!Number.isInteger(n)||n<2)return null;let i=n*n,s=n,a=new Uint8Array(i*s*4);for(let u=0;u<n;u++)for(let d=0;d<n;d++)for(let h=0;h<n;h++){let f=((u*n+d)*n+h)*3;if(f+2>=r.table.length)continue;let p=(d*i+(u*n+h))*4;a[p]=Ll(r.table[f]),a[p+1]=Ll(r.table[f+1]),a[p+2]=Ll(r.table[f+2]),a[p+3]=255}let o=e.MakeImage({width:i,height:s,alphaType:e.AlphaType.Unpremul,colorType:e.ColorType.RGBA_8888,colorSpace:e.ColorSpace.SRGB},a,i*4);if(!o)return null;let c=o.makeShaderOptions(e.TileMode.Clamp,e.TileMode.Clamp,e.FilterMode.Linear,e.MipmapMode.None),l={image:o,shader:c};return Ul.set(r.table,l),Nl.add(l),c}function Ll(r){return Number.isFinite(r)?Math.max(0,Math.min(255,Math.round(r*255))):0}var jw=`
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
- `,pf={type:"lut",sampling:{tileMode:"clamp",filterMode:"linear"},resources(r,e){let t=Kw(r,e);return t?[t]:null},makeShader(r,e,t,n,i){if(r.amount<=0)return null;let s=i?.[0];if(!s)return null;let a=ue(jw,e);return a?a.makeShaderWithChildren([r.size,r.amount],[t,s]):null},dispose(){for(let{image:r,shader:e}of Nl)e.delete(),r.delete();Nl.clear(),Ul=new WeakMap}};var $w=`
747
- 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 Xw(r,e,t,n,i,s,a){let o=r.strength;if(o===0||s<=0||a<=0)return null;let c=s/2,l=a/2,u=ue($w,e);if(!u)return null;let d=n+(r.center.x-.5)*s,h=i+(r.center.y-.5)*a;return u.makeShaderWithChildren([d,h,c,l,o],[t])}var gf={type:"bulge",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Xw(r,e,t,n.centerX,n.centerY,n.width,n.height)};var Qw=`
762
- 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 Yw(r,e,t,n,i,s,a){let o=r.scale;if(o===1||o<=0||s<=0||a<=0)return null;let c=n+(r.center.x-.5)*s,l=i+(r.center.y-.5)*a,u=ue(Qw,e);return u?u.makeShaderWithChildren([c,l,o],[t]):null}var yf={type:"magnify",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop",makeShader:(r,e,t,n)=>Yw(r,e,t,n.centerX,n.centerY,n.width,n.height)};var Zw=`
771
- 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 Jw(r,e,t){if(r.levels<2)return null;let n=ue(Zw,e);return n?n.makeShaderWithChildren([r.levels],[t]):null}var wf={type:"posterize",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>Jw(r,e,t)};import{resolveEffectColor as eb}from"@motionscript/core";var zl=[12,16,24,32,40],tb=3;function rb(r){let e=2*Math.PI*r/tb;return zl.find(t=>t>=e)??zl[zl.length-1]}function nb(r,e){let t=r!=="inside",n=r!=="outside",i=r!=="outside",s=(2*Math.PI/e).toFixed(8);return`
786
- 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 ib(r,e){switch(r){case"inside":return{out:0,in:e};case"center":return{out:e/2,in:e/2};default:return{out:e,in:0}}}function sb(r,e,t,n){let i=r.width*n,s=eb(r.color);if(!(i>0)||s[3]<=0)return null;let a=ib(r.position,i),o=nb(r.position,rb(Math.max(a.out,a.in))),c=ue(o,e);if(!c)return null;let l=r.position==="inside"?[a.in]:r.position==="center"?[a.out,a.in]:[a.out];return c.makeShaderWithChildren([...l,...s],[t])}var bf={type:"outline",sampling:{tileMode:"decal",filterMode:"linear"},handles:(r,e)=>e==="foreground",makeShader:(r,e,t,n)=>sb(r,e,t,n.scale)};import{resolveEffectColor as ab}from"@motionscript/core";var Vl=[2,3,4,6],Hl=12,ob=4;function cb(r){let e=r/ob;return Vl.find(t=>t>=e)??Vl[Vl.length-1]}function lb(r,e){let t=(2*Math.PI/Hl).toFixed(8),n=e?`
816
- float silhouette(vec2 p) {
817
- float a = u_content.eval(p).a;
818
- for (int i = 0; i < ${Hl}; 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 < ${Hl}; 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 ub(r,e,t,n){let i=ab(r.color);if(i[3]<=0)return null;let s=r.offsetX*n,a=-r.offsetY*n,o=Math.max(0,r.blur*n)/2,c=Math.max(0,r.spread*n);if(s===0&&a===0&&o===0&&c===0)return null;let l=lb(cb(o),c>0),u=ue(l,e);if(!u)return null;let d=[s,a,o,...i];return c>0&&d.push(c),u.makeShaderWithChildren(d,[t])}var kf={type:"dropShadow",sampling:{tileMode:"decal",filterMode:"linear"},handles:(r,e)=>e==="foreground",makeShader:(r,e,t,n)=>ub(r,e,t,n.scale)};import{resolveEffectColor as db}from"@motionscript/core";var hb=`
867
- 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 fb(r,e,t,n){let i=db(r.color);if(r.amount<=0||i[3]<=0||n.width<=0||n.height<=0)return null;let s=ue(hb,e);return s?s.makeShaderWithChildren([n.centerX,n.centerY,n.width/2,n.height/2,i[0],i[1],i[2],i[3],r.amount,r.radius,r.softness],[t]):null}var Sf={type:"vignette",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>fb(r,e,t,n)};var mb=`
891
- 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 pb(r,e,t,n,i,s=[0,0]){if(!(r.amount>0))return null;let a=ue(mb,e);if(!a)return null;let o=r.animated?r.seed+Math.floor(i*1e3):r.seed;return a.makeShaderWithChildren([s[0],s[1],r.amount,Math.max(r.size*n,1),o,r.colored?1:0],[t])}var xf={type:"grain",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>pb(r,e,t,n.scale,n.time,fi(r,n))};var gb=`
922
- 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 yb(r,e,t,n){if(r.amount===0)return null;let i=ue(gb,e);return i?i.makeShaderWithChildren([r.amount,Math.max(r.radius,0)*n],[t]):null}var Tf={type:"sharpen",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>yb(r,e,t,n.scale)};var wb={sobel:0,prewitt:1,laplacian:2},bb=`
948
- 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 kb(r,e,t,n){if(!(r.strength>0))return null;let i=ue(bb,e);return i?i.makeShaderWithChildren([r.strength,wb[r.kernel]??0,r.colored?1:0,n],[t]):null}var Af={type:"edges",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>kb(r,e,t,n.scale)};var Sb=`
984
- 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 xb(r,e,t){let n=ue(Sb,e);return n?n.makeShaderWithChildren([r.level,r.smoothness],[t]):null}var vf={type:"threshold",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>xb(r,e,t)};var Tb=2,Ab=32;function vb(r){return`
1005
- 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 _b(r,e,t,n){if(!(r.amount>0)||n.width<=0||n.height<=0)return null;let i=Math.round(Math.max(Tb,Math.min(Ab,r.samples))),s=ue(vb(i),e);if(!s)return null;let a=n.centerX+(r.center.x-.5)*n.width,o=n.centerY+(r.center.y-.5)*n.height;return s.makeShaderWithChildren([a,o,r.amount,r.style==="spin"?1:0],[t])}var _f={type:"radialBlur",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>_b(r,e,t,n)};var Cb={dot:0,line:1,cross:2},Pb={mono:0,rgb:1,cmyk:2},Eb=`
1032
- 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 Ib(r,e,t,n){let i=r.size*n.scale;if(!(i>=1))return null;let s=ue(Eb,e);return s?s.makeShaderWithChildren([n.centerX,n.centerY,i,r.angle*Math.PI/180,Cb[r.shape]??0,Pb[r.separation]??0],[t]):null}var Cf={type:"halftone",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Ib(r,e,t,n)};var Mb="e8yOVglJi3jaB+U3jl3KakXertJzm985bcTcngPJTPc8ddJT6mIl7ztdoQdH8wxyKr6F1wCTXqg8aZ50OCCKRakgO9+09jbERrJS0AzsM7J9JxY+6i5arBCOK3w3qXHAXOWPG4DYqhCT3HXpkSay25w//61F4y53670E4MOiZtlQ/51iK5hqGewpmmeAvRmQ516kirgCftDuUbn5YOcTLZ0ORqXDOHhRshw0VcBmglDGCV0he6MZyUyQLFmCDewWwG4DzYQO0qVdhv4gQqRT0gfB/2xP8p8+HWmaC0SRuOCAyP0rWwj4yGrxz6oV+jcc72+Wu9RU74cQ27LyR886kieB5Eu58D962ACryeNs+Dx0Sy8SyiRfvIvmJ8XXax1UOGKvct+YgyhCiQB7RZbVrYtG3jUMaz63cDplGZxxsGDuP6cadVkgvTBNcjgRliaEtZvggJfcdArTS3WrNIP4n9ADjBm5RugUuqBh58tuDl3nJaSB+MifJf+ojcgp+QrUFI/EL96wjPmZ4cCMYNnDC/EfWr40Ra/7MKQQ8VEItSl47lDWNWWn0Vj8Oh6jLbw+ewPATReSWwPUUg/mXYVMnm1T+mWbEEdsDFoe964yVaZHz24F9IkaWH7LXojamGPiP74jmfQFdC2TC8SGUduK9KnQYuZ3N+2+fzZ2rD3cvzC00waFO8nqKdGmekUFf+1rjzHonLZk4JlC6xe6I0PIFo9srVp/weNNfddoru8FZhlSMZcfttdrK5rqvSCVAnbnQ3wovORffbSJOee33Jkhyw6sfBZPKsgAsyyea/57qlb3Cc84Fa8hnfUYSSV4QcaR2XD3QaJTFbBKDF76zVaoG5r1qEwdoQJQ8hVfJ21Psz71Vtw90oZz6GGGTs43AtUtoEnhiP9FbMk5tJjou5v9LbQPhsgHfPvMhNxxRIIv8WEKN2rZj/42w26dzY7EFuVjhyi6ZvumHzy+9RSrjeZph8B2KKNh1I0LXd1wCTNaG35I6idh4pUjYjuiKK8TwI3P4onID1p0qyHgPwf/NXybAceiGJEJwkufDGrdJlW2Qx/yElXDAjGo8CiJTsuE3ahkzZirTbk02qwD9Y7T625MJndEsCvnQNORXLaFU6nZRflxN+x6MV7wgteWQHf2D57eXrGV6XffSnDDrhz4QsEU5zUBbvYSdUmIwk8XXTkForsY8GKfvxiACfYrb+kRZyu0WNhKzJjesSpZHLHKiWTBNIDWLUQetJYPPeRhoCZqk0+1hNg7ksrzGm7lfcWqh/xamdUFek7yY8RMotMjwIPOG44LsGsaRAFuwvlPBTHtF5NIBm31gstf+4GZA3q38Al1+x1YsSVioC+wPZwn30fOMbM+j+Eyl6053g6QPp5N6KV38yaf/X7Okjh6mtmndFLN+6nBmlIVNNIkVMjgTjKlz0HDnOt9C+JZ1Qj0ZRlyDIL3HVa8EdEfiWu7VnbxBGE2wkVivzJYqeAR6idgQOG5JXlcGznjr45xte07II/WXIkrbA9J1L1DkHa+UoW17MNj0HuoaP51VOku+hrXtiiL1RCW3QmM6hdLZ72LshyGDqE96YjVZALxRBOfZK9zDuwYqvKOMmmlJ/EWmCvYPJ0kSQI27CZGk8IBqXuYOGmo/nBP7Xk80G8oxqE9B/zQaOxW0gq8KH6gxVveegn3x0i4ft1QzLD9BoRjzkf9qhRWi67jlcaDDLU01V5Fyw/kQxm5LK0cpE23kPd/3Fd4Rp41iq9smFH/PR6HLr6TVTSfImY7AHUeV5njNa5xAWF9yfNxYBtQ26DlbIoi7LSMVn2Z0FuE2mXzBThdEi/Kqya+BPcgQusUs3DXqu1G1Bziif3Kmr2K5zDWScEg5oy74DIPQKC+dDpdGUv1owhtLdPsATzwDcAjmXjSnuJvkBnogVvXdsVfzTOUVAdlI3KtXXYNUyvzQWC4chSBWqE5Th2Us9so8Aez+Y3IL37fTZ8eumGxdJQ0WN9DuiFJtPBSask9lCykC4XkGfbDm4X6AM8wqNl/FqXODJKs9NIN7sxt+lh7SIrWLnqqDGS3OcL0c0SIJNZL+KyBFGr9hwA6nw2o5RK5+k1qrUd9Mdw8tk2N70G3W+RuJvpRLmpClSqBpjoG0BlqnFYe6kjZjxZdkg3L/aQQwm0Ey+szplzZxIX6Jk9nfzuZ3ie/Y6oMXMsXom0fkwfCSZ14vOEbs3TDVRfWjqzE/j250W+aJv130SmuVzdo5iqQP6BUjb8beSxIb7iQ0eofywKJ8RXnknTyLV/gx3r3MoveAj2CzFn+Aea3aelcgQ7aiAM1xlgJoT3vg+Eam4JXutkicQviTvWx1BXiNwdXrndfQJ9PzSRGp4G4DFE8q2kesFvupBCMNZxIhh1BLLVSJaRg9oKt42i9TQJrv9Q9+RZ68KzRKJppCY5bpHzElzP1vdotbYS14RnUN/6e2BXsxTfTbSlO161wJtyj9pVr7nfkQ7QZRy5/F9qUpyhTCK1jmks2ZoQ/6Kc08iFH/WwYS40OqfQGOmWWVG6MJWKBl1F8Epi/82Uc68ZUdQTIGjeXwRNy35HJ87BgM+564pHNLOgBvv2xD8hQfsxlsxHUouMlfblZksf5EMLsAK/HPgjgqPxHhwa1PYMQtDTZSuCxB0/SM6JiBlAjh8xIFbJpQ4DGX5EYVdtvJLoC3pAvf1rDZ+041CBKc6YoRnjkU/S2LGYgyTZ44pxM9JFgp4hYfPNmjf8dvOhxof4IvFv3Id4OqTHge6EzivqXPnVS6aw8AZZHEnib2jODt9KTNRuLdddMkuerXCXOayvWDP8izj+lKbh4Vz+IMNRAZ55/NoqeT/hxRCLrwkoVYOykDcci+XLepcH9XrME8VoRZtupWxCdwABsGPWMC7ehfENyuwrlGNdGAsfdpg26fRzsxA/Wb70alNa0Zgec17Ah0DeVVobNKVWIMBrib5Q96aAnvv5A4zB/01G8P91XG8foLZltkVp/oPCUJ2brWZfcK1OqQfEuXMUMiFL0ey5yU4T1br4RQrEK6mxAn0zEIbt5SIAYb69e+JoteaZp+TuMXa9MxST7uzNeFn21OxXJRXWSz2UCrX7jPKYnuUDlxQS1SBfcnfBmkdW2gM4N+4hYBvDHltEKjUQRx+gFJoK+CNIY9IKrQwtz58xL+4tw8aUJ+COF6ZdGIPxw2oQaomGT2CqqYTF8wiNNFvMqrmQ13aNoIjdW7ijbpWRLktirUO12njkDZsrdjK8rowXFJFUyv188uhjLZLOPVwDHS/sUOu10kP9RBN86pGKXVHrllhvOQa7jgbVrv30h+7U1bh2UKmHW7ZYuWB1Fbt1anOa2h+Kb23hSMeEL0C/vZ6+JcMtMCbshyY2ub+rJBtg7EcFRg/d2AqE/F1LkOogTWfHPROO8TyJ15qPB8ROHN3lGDWkfTAWx+qCIdEqlkzof2iydsFvZhELoVRKDMriK+KJvK7oTWccq/s+bBKvNc7+bBLJ7EqdCug06Y5XPsfUX06f6fNCQKmAWO/HCEuR2u1TqEHz2M2kXnSu9/ElxImBH0+iVOuCYaU6McPBiQ+EsTYZoMfWLZ/6I1nsCTi5nwJJZL7k77nLK3rdoKIVZ0weXZcVDHZK48HnYYJUY4bDMAIQfZbJ/HNS3EzK9JJYNqPcf38FWz6AXUKsl+KR/4SQ/6wqfXhKmQo8DU63/HadH9jCL4abVSgypPgDMplSRNO+nPvkKTO03efVI24DrVXjRkECYByneM8Bf3D+8Ww6vhG/LiOXEUyN37ZnZcDLBfRa1cQRfK3TIV/aHazjzDna+TnDLmsFipwaTsFwWrMkyZRFcruuDs3jpCXGOFdSX/1DaHUosef+y0S9BFU2O212f0E/9v4btH5kvu+Igg8ZfJI7dGTOHIdhVzCJzkUEA76C7/DVsSA6UQ57JMO9IczQEs2ScuAWVGGOJus2k6gQ87h80nRQ9sWLedxJSrkHaoOkIq1zjbP9BgeY4xv+5bIlLKXvIHtL0ZSP5Ua1qHsyj54s59tVAa+FK9Ah8YSZ4uZBjhNpX5Y8GR6vWj/9rF1E5wX5CsgSduhJpowlYLd8czuMGj6JUMbjXfQ+K37eBYCnGeg9bjMGpKp5V5zis+UwT4sRzqCNq+sgiYTUFmLaF92gq74rQWC6V8ErZeZlHp3RZr0DmdYkDoT7GLFgIQPMWVOCtIu02C3bKHJPXDWfOoUMqAUnTtjiAou19w+QvzQ6U1hNOIuh3wx6GsRTK7wrCM/JoEcRO6Vtw45n8qNWPv5w0a89/U9f7X7dGgMSYJXv2s5TueBOaVAvSQlcdYHZGtFefx22qQNxhMfZlJYFflx6K2CeqNs4hshI5dB9mL3MB/EahEbiUPoct7BhZPOYJVW01ylct88BtJ7KDnfOq4CH8fzXyFIkAodFEkbw41PpDu1F+/mSWgfZPwIfKSO6xWsONKvJkHq4C251x/b2IptjBEYKj24VF3ZD7D9E2AYo8agi2lFm8/E5/Ct+jUxGtdgHPmxSvCkKi2mEF5KER2IIc3XbJSeVzxmhPrA8sYz8dl0r8IGMEqBk4ZE25clS/06TlSiThNmqwKcVvHuqNZealOW7gx+95LxuTtzFYkic/qFUKOaeGMfgbNs1+3bL0eeNnszrOvHLtxqXhIpTuFnkqXsNzzoMb645c9EJ7zDAgWvYaSyRcuMxw8EV++2/I6Wn3vZPcDVubvY3yRJkBVirLCIvoUZYlWXsGhkTXY5xC848arAWdQdMPty6pBbhL25PAd4w/lAHmU6kMxRqxTgaXMHlQJLnrQ3UIYCNs0Ye6Rp8uehf4QtWeL/WtCy7NtgrYRftj51amck3Wkl7+noAIL6za/qZsOyGD2mScNonftR3T72Z+qyXK5KO/6zKlE/ld0appsoITu09oxXb6UoVno3cwix7CLPqDGOdzORXJaulRFH0p1bSb+EEl0/MTXn5IpAQ9zRBXlTJOEnxJ4WaBG+RIAN408m7mEDyRpho47CTLtEzba5IDxkCzIr9U8T6b0GPFS+5bE262jlVyujvK/W3EnOWL/GjUg/i2HJbFO7WRJ8aaTY8mqYXOI1/ZwJdXB/KaDrg+32edWYzZfKkghg2yH4wHgMIz6gOsH+mbCi2NGl4sSh67A6oob9VWBu5xUvx6XdELwlrdSvG0AXNE4oJiNnT3V6ww6g/1MwZnvE73OuKj0UWW1lB8z0SHZN2xU+u3c9yjeT7lX5w16IsppRG5Ohyl5HUyF6B5No38FafDGrDQIoATkM9xRKLK5jDVlXJSaDD5HGcpofsuxhVJetI5hBLFMfSQUMwKrne7QdJi24bvaEGK/LhoDuVQr2ctQN+KSaLpx0wmhbpYjhSAXgOu7hC8d6fkvhRclXCr9iOgAPmVUGMNviCG/kkbXPKCI5gIsCm9A5pHzYW/JNV+ypha7xBkMm22+AvYIf1Ks/LHLA==";var Fb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eo=null;function Pf(){if(eo)return eo;let r=Mb.replace(/[^A-Za-z0-9+/]/g,""),e=new Uint8Array(r.length*3>>2),t=0,n=0,i=0;for(let s=0;s<r.length;s++)t=t<<6|Fb.indexOf(r[s]),n+=6,n>=8&&(n-=8,e[i++]=t>>n&255);return eo=e.subarray(0,i),eo}function Rb(r,e){let t=r==="blue",n=t?`u_noise.eval(mod(cell, ${64}.0) + 0.5).r`:e===2?"bayer2(cell)":e===4?"bayer2(cell * 0.5) * 0.25 + bayer2(cell)":"(bayer2(cell * 0.25) * 0.25 + bayer2(cell * 0.5)) * 0.25 + bayer2(cell)";return`
1188
- 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 ro=new WeakMap,Wl=new Set;function Bb(r){let e=ro.get(r);if(e!==void 0)return e?.shader??null;let t=Pf(),n=new Uint8Array(t.length*4);for(let o=0;o<t.length;o++){let c=t[o];n[o*4]=c,n[o*4+1]=c,n[o*4+2]=c,n[o*4+3]=255}let i=r.MakeImage({width:64,height:64,alphaType:r.AlphaType.Unpremul,colorType:r.ColorType.RGBA_8888,colorSpace:r.ColorSpace.SRGB},n,256);if(!i)return ro.set(r,null),null;let s=i.makeShaderOptions(r.TileMode.Repeat,r.TileMode.Repeat,r.FilterMode.Nearest,r.MipmapMode.None),a={image:i,shader:s};return ro.set(r,a),Wl.add(a),s}function Db(r,e,t,n,i=[0,0]){if(r.levels>=256)return null;let s=r.noise==="blue"?Bb(e):null,a=r.noise==="blue"&&s?"blue":"bayer",o=ue(Rb(a,r.matrix),e);if(!o)return null;let c=a==="blue"?[t,s]:[t];return o.makeShaderWithChildren([i[0],i[1],r.levels,Math.max(r.scale*n,1),r.monochrome?1:0],c)}var Ef={type:"dither",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>Db(r,e,t,n.scale,fi(r,n)),dispose(){for(let{image:r,shader:e}of Wl)e.delete(),r.delete();Wl.clear(),ro=new WeakMap}};import{resolveEffectColor as If}from"@motionscript/core";var Ob=.2126,Lb=.7152,Ub=.0722;function Nb(r,e,t){let n=Math.max(0,Math.min(1,r)),i=c=>{let l=(t[c]-e[c])*n;return[l*Ob,l*Lb,l*Ub,0,e[c]*n]},[s,a,o]=[i(0),i(1),i(2)];return s[0]+=1-n,a[1]+=1-n,o[2]+=1-n,[...s,...a,...o,0,0,0,1,0]}var Mf={type:"duotone",makeImageFilter(r,e){if(r.amount<=0)return null;let t=Nb(r.amount,If(r.shadows),If(r.highlights)),n=e.ColorFilter.MakeMatrix(t),i=e.ImageFilter.MakeColorFilter(n,null);return n.delete(),i}};var zb=`
1218
- 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 Vb(r,e,t,n){let{red:i,green:s,blue:a}=r;if(i.x===0&&i.y===0&&s.x===0&&s.y===0&&a.x===0&&a.y===0)return null;let c=ue(zb,e);return c?c.makeShaderWithChildren([i.x*n,i.y*n,s.x*n,s.y*n,a.x*n,a.y*n],[t]):null}var Ff={type:"rgbShift",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Vb(r,e,t,n.scale)};var Hb=`
1241
- 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=ue(Hb,e);if(!s)return null;let a=r.angle*Math.PI/180;return s.makeShaderWithChildren([n.centerX,n.centerY,i,r.thickness,r.darkness,r.offset*n.scale,Math.cos(a),Math.sin(a)],[t])}var Rf={type:"scanlines",sampling:{tileMode:"decal",filterMode:"linear"},makeShader:(r,e,t,n)=>Wb(r,e,t,n)};import{resolveEffectAxis as qb}from"@motionscript/core";var Gb=`
1271
- 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 Kb(r,e,t,n){if(!(r.amount>0)||!(r.density>0))return null;let i=ue(Gb,e);if(!i)return null;let s=qb(r.axis);return s.x===0&&s.y===0?null:i.makeShaderWithChildren([n.centerX,n.centerY,r.amount*n.scale,Math.max(r.size*n.scale,1),r.density,r.seed,s.x,s.y],[t])}var Bf={type:"blockDisplace",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>Kb(r,e,t,n)};var Df={gameboy:["#0f380f","#306230","#8bac0f","#9bbc0f"],cga:["#000000","#55ffff","#ff55ff","#ffffff"],nes:["#000000","#fcfcfc","#bcbcbc","#7c7c7c","#0000fc","#0078f8","#3cbcfc","#a4e4fc","#b8f818","#00b800","#005800","#f83800","#e40058","#f878f8","#f8b800","#503000"]};function Of(r){let e=parseInt(r.slice(1),16),t=n=>((e>>n&255)/255).toFixed(4);return`vec3(${t(16)}, ${t(8)}, ${t(0)})`}function jb(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 = ${Of(Df[r][0])};
1311
- float bestDist = dot(base - crushed, base - crushed);
1312
- ${Df[r].slice(1).map(t=>` { vec3 p = ${Of(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 $b(r,e,t){if(!(r.amount>0)||r.palette==="none"&&r.bits>=8)return null;let n=ue(jb(r.palette),e);return n?n.makeShaderWithChildren([r.bits,r.amount],[t]):null}var Lf={type:"bitCrush",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t)=>$b(r,e,t)};import{resolveAsciiCharset as zf,resolveEffectColor as Vf}from"@motionscript/core";function Xb(r,e,t=!1){return{weight:{value:Math.max(1,Math.min(1e3,Math.round(e)))},slant:t?r.FontSlant.Italic:r.FontSlant.Upright,width:r.FontWidth.Normal}}function ql(r,e,t,n,i=!1){return e.matchFamilyStyle(t,Xb(r,n,i))}function mi(r,e,t){let n=new r.Font(e,t);return n.setSubpixel(!0),n.setHinting(r.FontHinting.None),n.setLinearMetrics(!0),n}var Qb=64,Uf=256,Gl=r=>Math.max(4,Math.min(Qb,Math.round(r))),Nf=r=>Math.min([...r].length,Uf),Yb=(r,e)=>`${e}|${r.cell}|${r.fontFamily}|${r.fontWeight}|${r.charset}`,no=class{entries=new Map;get(e,t,n){let i=Yb(e,n.fontEpoch),s=this.entries.get(i);if(s!==void 0)return s;let a=Jb(e,t,n);return this.entries.set(i,a),a}dispose(){for(let e of this.entries.values())e?.dispose();this.entries.clear()}};function Zb(r,e,t){let n=ql(e,t.fontMgr,r.fontFamily,r.fontWeight);if(n)return n;if(t.fontMgr.countFamilies()>0){let i=t.fontMgr.getFamilyName(0),s=ql(e,t.fontMgr,i,r.fontWeight);if(s)return s}return null}function Jb(r,e,t){let n=[...r.charset].slice(0,Uf);if(n.length===0)return null;let i=Gl(r.cell),s=t.makeSurface(i*n.length,i);if(!s)return null;let a=mi(e,Zb(r,e,t),i*.8),o=s.getCanvas();o.clear(e.BLACK);let c=new e.Paint;c.setColor(e.WHITE),c.setAntiAlias(!0);let l=0;if(n.forEach((h,f)=>{let p=a.getGlyphIDs(h);if(p.length===0||p[0]===0){l++;return}let g=a.getGlyphWidths(p)[0]??i,y=f*i+(i-g)/2,b=i*.78;o.drawGlyphs(p,[y,b],0,0,a,c)}),l>0&&console.warn(`[motionscript] ascii: ${l}/${n.length} glyphs are missing from '${r.fontFamily}'. Register a font covering those characters, or use the 'standard' charset, which is plain ASCII.`),l===n.length)return c.delete(),a.delete(),s.delete(),null;c.delete(),a.delete(),s.flush();let u=s.makeImageSnapshot(),d=u.makeShaderOptions(e.TileMode.Clamp,e.TileMode.Clamp,e.FilterMode.Linear,e.MipmapMode.None);return{shader:d,count:n.length,cell:i,dispose(){d.delete(),u.delete(),s.delete()}}}var ek=2,Hf=r=>Gl(Math.max(8,r*ek)),tk=`
1320
- 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
- `,qf={type:"ascii",sampling:{tileMode:"decal",filterMode:"nearest"},resources(r,e,t){let n=zf(r.charset);if(n.length===0)return null;let i=Wf.get({charset:n,fontFamily:r.fontFamily,fontWeight:400,cell:Hf(r.size)},e,t);return i?[i.shader]:null},makeShader(r,e,t,n,i){let s=i?.[0];if(!s)return null;let a=r.size*n.scale;if(!(a>=2))return null;let o=ue(tk,e);if(!o)return null;let c=Vf(r.ink),l=Vf(r.background);return o.makeShaderWithChildren([n.centerX,n.centerY,a,Nf(zf(r.charset)),Hf(r.size),...c,...l,r.colored?1:0],[t,s])},dispose(){Wf.dispose()}},Wf=new no;var Gf={type:"streak",makeImageFilter(r,e){if(r.intensity<=0||r.length<=0)return null;let t=Math.max(0,Math.min(1,r.threshold)),n=t<1?1/(1-t):1,i=-t*n,s=[n,0,0,0,i,0,n,0,0,i,0,0,n,0,i,0,0,0,1,0],a=e.ColorFilter.MakeMatrix(s),o=e.ImageFilter.MakeColorFilter(a,null);a.delete();let c=r.angle*Math.PI/180,l={filter:e.FilterMode.Linear,mipmap:e.MipmapMode.None};if(c!==0){let h=e.ImageFilter.MakeMatrixTransform(e.Matrix.rotated(-c),l,o);o.delete(),o=h}let u=e.ImageFilter.MakeBlur(r.length/2,.01,e.TileMode.Decal,o);if(o.delete(),o=u,c!==0){let h=e.ImageFilter.MakeMatrixTransform(e.Matrix.rotated(c),l,o);o.delete(),o=h}if(r.intensity!==1){let h=r.intensity,f=[h,0,0,0,0,0,h,0,0,0,0,0,h,0,0,0,0,0,1,0],p=e.ColorFilter.MakeMatrix(f),m=e.ImageFilter.MakeColorFilter(p,o);p.delete(),o.delete(),o=m}let d=e.ImageFilter.MakeBlend(e.BlendMode.Screen,null,o);return o.delete(),d}};import{resolveEffectAxis as rk,resolveEffectColor as Kf}from"@motionscript/core";var nk="vec3(0.2126, 0.7152, 0.0722)";function ik(r,e,t){let n=r==="ramp",i=n?`uniform vec4 u_colors[${t}]; // ramp colours, straight RGBA
1366
- 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, ${nk}) * 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 sk(r,e,t){let n=r.channel==="alpha",i=n?0:Math.max(0,Math.min(1,r.threshold)),s=i<1?1/(1-i):1,a=-i*s,o=n?[0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0]:[s,0,0,0,a,0,s,0,0,a,0,0,s,0,a,0,0,0,1,0],c=e.ColorFilter.MakeMatrix(o),l=e.ImageFilter.MakeColorFilter(c,null);c.delete();let u=Math.max(0,r.spread)*t;if(u<=0)return l;let d=e.ImageFilter.MakeDilate(u,u,l);return l.delete(),d}var jf={type:"glow",sampling:{tileMode:"decal",filterMode:"linear"},renderInputs(r,e,t){if(r.radius<=0&&r.spread<=0||r.intensity<=0)return null;let n=Math.max(0,r.radius)*t.scale/2,i=rk(r.axis);return{blurredSource:{sigmaX:n*i.x,sigmaY:n*i.y,prefilter:sk(r,e,t.scale)}}},makeShader(r,e,t,n,i,s){let a=s?.blurredSource;if(!a)return null;let o=r.colors.length,c=ik(r.tint,r.loopStyle==="mirror",o),l=ue(c,e);if(!l)return null;let u=[r.intensity];if(r.tint==="solid"&&u.push(...Kf(r.color)),r.tint==="ramp"){for(let g of r.colors)u.push(...Kf(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=jt(e,r.blend),f=e.Shader.MakeBlend(h,t,d);if(d.delete(),r.original==="behind")return f;let p=e.Shader.MakeBlend(e.BlendMode.SrcOver,f,t);return f.delete(),p}};var ak=6;function ok(r){return`
1395
- uniform shader u_content; // snapshot of the source (premultiplied)
1396
-
1397
- const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
1398
-
1399
- vec4 main(vec2 fragCoord) {
1400
- vec4 centre = u_content.eval(fragCoord);
1401
- if (centre.a <= 0.0) return centre;
1402
-
1403
- vec3 bestMean = centre.rgb / centre.a;
1404
- float bestVar = 1e9;
1405
-
1406
- // Four quadrants: (-r..0,-r..0), (0..r,-r..0), (-r..0,0..r), (0..r,0..r).
1407
- for (int q = 0; q < 4; q++) {
1408
- float sx = (q == 1 || q == 3) ? 1.0 : -1.0;
1409
- float sy = (q == 2 || q == 3) ? 1.0 : -1.0;
1410
-
1411
- vec3 sum = vec3(0.0);
1412
- float sumL = 0.0;
1413
- float sumL2 = 0.0;
1414
- float n = 0.0;
1415
-
1416
- for (int y = 0; y <= ${r}; y++) {
1417
- for (int x = 0; x <= ${r}; x++) {
1418
- vec4 s = u_content.eval(fragCoord + vec2(float(x) * sx, float(y) * sy));
1419
- // Skip anything outside the silhouette, or the window would be
1420
- // pulled toward transparent black and the edge would darken.
1421
- if (s.a <= 0.0) continue;
1422
- vec3 c = s.rgb / s.a;
1423
- float l = dot(c, LUMA);
1424
- sum += c;
1425
- sumL += l;
1426
- sumL2 += l * l;
1427
- n += 1.0;
1428
- }
1429
- }
1430
-
1431
- if (n <= 0.0) continue;
1432
- float mean = sumL / n;
1433
- float variance = sumL2 / n - mean * mean;
1434
- if (variance < bestVar) {
1435
- bestVar = variance;
1436
- bestMean = sum / n;
1437
- }
1438
- }
1439
-
1440
- return vec4(bestMean * centre.a, centre.a);
1441
- }
1442
- `}function ck(r,e,t,n){let i=Math.round(Math.min(ak,r.radius*n));if(i<1)return null;let s=ue(ok(i),e);return s?s.makeShaderWithChildren([],[t]):null}var $f={type:"oilPaint",sampling:{tileMode:"decal",filterMode:"nearest"},makeShader:(r,e,t,n)=>ck(r,e,t,n.scale)};var lk=`
1443
- uniform shader u_content; // snapshot of the source (premultiplied)
1444
- uniform vec2 u_center; // ripple origin, device px
1445
- uniform vec2 u_amplitude; // peak displacement per axis, device px
1446
- uniform float u_wavelength; // distance between crests, device px
1447
- uniform float u_phase; // radians, pre-wrapped
1448
- uniform float u_cos; // travel direction, precomputed
1449
- uniform float u_sin;
1450
- uniform float u_radial; // 1 = concentric rings, 0 = parallel bands
1451
-
1452
- vec4 main(vec2 fragCoord) {
1453
- vec2 d = fragCoord - u_center;
1454
- // Distance along the travel axis, or from the origin \u2014 the one scalar the
1455
- // sine is taken of.
1456
- float t = u_radial > 0.5 ? length(d) : dot(d, vec2(u_cos, u_sin));
1457
-
1458
- float k = 6.28318530718 / max(u_wavelength, 1.0);
1459
- float wave = sin(t * k + u_phase);
1460
-
1461
- return u_content.eval(fragCoord + u_amplitude * wave);
1462
- }
1463
- `,Xf={type:"wave",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t,n){let{x:i,y:s}=r.amplitude;if(i===0&&s===0||n.width<=0||n.height<=0)return null;let a=ue(lk,e);if(!a)return null;let o=r.angle*Math.PI/180,c=(r.phase%360+360)%360*Math.PI/180,l=n.centerX+(r.center.x-.5)*n.width,u=n.centerY+(r.center.y-.5)*n.height;return a.makeShaderWithChildren([l,u,i*n.scale,s*n.scale,Math.max(r.wavelength,.01)*n.scale,c,Math.cos(o),Math.sin(o),r.shape==="radial"?1:0],[t])}};var uk=`
1464
- uniform shader u_content; // snapshot of the source (premultiplied)
1465
- uniform vec2 u_center; // vortex centre, device px
1466
- uniform vec2 u_half; // node half-extent, device px
1467
- uniform float u_angle; // rotation at the centre, radians
1468
- uniform float u_radius; // 0\u20131 radius of influence, in normalised units
1469
-
1470
- vec4 main(vec2 fragCoord) {
1471
- vec2 half_ = max(u_half, vec2(1.0));
1472
- vec2 p = (fragCoord - u_center) / half_; // aspect-normalised
1473
- float r = length(p);
1474
- if (r >= u_radius) return u_content.eval(fragCoord);
1475
-
1476
- float falloff = 1.0 - r / max(u_radius, 0.0001);
1477
- float a = u_angle * falloff * falloff;
1478
-
1479
- float c = cos(a);
1480
- float s = sin(a);
1481
- vec2 rotated = vec2(p.x * c - p.y * s, p.x * s + p.y * c);
1482
-
1483
- return u_content.eval(u_center + rotated * half_);
1484
- }
1485
- `,Qf={type:"twirl",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t,n){if(r.angle===0||r.radius<=0||n.width<=0||n.height<=0)return null;let i=ue(uk,e);if(!i)return null;let s=n.centerX+(r.center.x-.5)*n.width,a=n.centerY+(r.center.y-.5)*n.height;return i.makeShaderWithChildren([s,a,n.width/2,n.height/2,r.angle*Math.PI/180,r.radius],[t])}};var dk=32,hk=2;function fk(r){return`
1486
- uniform shader u_content; // snapshot of the source (premultiplied)
1487
- uniform vec2 u_center; // ramp origin, device px
1488
- uniform vec2 u_half; // node half-extent, device px
1489
- uniform vec2 u_dir; // ramp direction (linear)
1490
- uniform float u_radius; // blur spread at the far end, device px
1491
- uniform float u_radius0; // blur spread at the near end, device px
1492
- uniform float u_start; // 0\u20131 where the blur starts building
1493
- uniform float u_end; // 0\u20131 where it reaches u_radius
1494
- uniform float u_radial; // 1 = radial ramp, 0 = linear
1495
-
1496
- float hash(vec2 p) {
1497
- return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
1498
- }
1499
-
1500
- vec4 main(vec2 fragCoord) {
1501
- vec2 half_ = max(u_half, vec2(1.0));
1502
- vec2 p = (fragCoord - u_center) / half_;
1503
-
1504
- // One scalar drives the ramp, whichever shape it is: distance from the
1505
- // origin, or distance along the ramp direction remapped to 0\u20131 across the box.
1506
- float t = u_radial > 0.5 ? length(p) : dot(p, u_dir) * 0.5 + 0.5;
1507
-
1508
- // Smoothstep rather than a linear remap: a linear ramp leaves a visible line
1509
- // at u_start where the blur switches on, because the radius' derivative
1510
- // jumps there. Smoothstep lands both at zero.
1511
- float ramp = smoothstep(u_start, max(u_end, u_start + 0.0001), clamp(t, 0.0, 1.0));
1512
- // Between the two ends, not out of sharp: a ramp that starts blurred is a
1513
- // depth-of-field falloff rather than a fade-to-blur.
1514
- float radius = mix(u_radius0, u_radius, ramp);
1515
-
1516
- vec4 sum = u_content.eval(fragCoord);
1517
- if (radius < 0.5) return sum; // sub-pixel \u2014 nothing to average
1518
-
1519
- const int N = ${r};
1520
- float jitter = hash(fragCoord) * 6.28318530718;
1521
- for (int i = 1; i <= N; i++) {
1522
- float fi = float(i);
1523
- float ang = fi * 2.39996323 + jitter; // golden angle, per-pixel rotated
1524
- float rad = radius * sqrt(fi / float(N));
1525
- sum += u_content.eval(fragCoord + vec2(cos(ang), sin(ang)) * rad);
1526
- }
1527
- return sum / float(N + 1);
1528
- }
1529
- `}var Yf={type:"progressiveBlur",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t,n){let i=r.startRadius??0;if(r.radius<=0&&i<=0||n.width<=0||n.height<=0)return null;let s=Math.max(hk,Math.min(dk,Math.round(r.samples))),a=ue(fk(s),e);if(!a)return null;let o=r.angle*Math.PI/180,c=n.centerX+(r.center.x-.5)*n.width,l=n.centerY+(r.center.y-.5)*n.height;return a.makeShaderWithChildren([c,l,n.width/2,n.height/2,Math.cos(o),Math.sin(o),r.radius*n.scale,i*n.scale,r.start,r.end,r.shape==="radial"?1:0],[t])}};var mk=`
1530
- uniform shader u_content; // snapshot of the source (premultiplied)
1531
- uniform vec2 u_center; // fold origin, device px
1532
- uniform vec2 u_half; // node half-extent, device px
1533
- uniform float u_wedge; // angular width of one wedge, radians
1534
- uniform float u_angle; // pattern rotation, radians
1535
- uniform float u_offset; // radial offset of the sampled wedge, normalised
1536
- uniform float u_amount; // 0\u20131 blend from the original to the folded pattern
1537
-
1538
- vec4 main(vec2 fragCoord) {
1539
- vec2 half_ = max(u_half, vec2(1.0));
1540
- vec2 p = (fragCoord - u_center) / half_; // aspect-normalised
1541
-
1542
- float r = length(p);
1543
- float a = atan(p.y, p.x) - u_angle;
1544
-
1545
- // Fold into a single mirrored wedge.
1546
- a = mod(a, u_wedge);
1547
- a = abs(a - u_wedge * 0.5);
1548
- a += u_angle;
1549
-
1550
- vec2 sampled = vec2(cos(a), sin(a)) * max(r + u_offset, 0.0);
1551
- vec4 folded = u_content.eval(u_center + sampled * half_);
1552
-
1553
- // Mixing the *sampled colours* rather than the sample positions: blending
1554
- // the coordinates would slide the fold across the image as it ramps, which
1555
- // reads as a warp rather than as the pattern appearing.
1556
- return mix(u_content.eval(fragCoord), folded, u_amount);
1557
- }
1558
- `,Zf={type:"kaleidoscope",sampling:{tileMode:"decal",filterMode:"linear"},makeShader(r,e,t,n){let i=Math.round(r.segments);if(i<2||r.amount<=0||n.width<=0||n.height<=0)return null;let s=ue(mk,e);if(!s)return null;let a=n.centerX+(r.center.x-.5)*n.width,o=n.centerY+(r.center.y-.5)*n.height;return s.makeShaderWithChildren([a,o,n.width/2,n.height/2,2*Math.PI/i,r.angle*Math.PI/180,r.offset,Math.max(0,Math.min(1,r.amount))],[t])}};var pk=1.5,gk=.5,yk=.35,wk=1.4,bk=1,kk=.75,Sk=1.2,xk=.1,Tk=.06,Ak=.7,vk=.3,Jf=.25,Kl=7;function _k(r){return`
1559
- uniform shader u_backdrop; // beneath the node, frosted when asked
1560
- uniform shader u_field; // alpha: distance inside the outline over u_deepest
1561
- uniform float u_deepest; // device px a field alpha of 1 stands for
1562
- uniform float u_bevel; // bevel width, device px
1563
- uniform float u_base; // glass under the bevel, device px
1564
- uniform float u_eta; // 1 / refractive index
1565
- uniform float u_amount; // 0-1 scale on the pull
1566
- uniform float u_spread; // spectrum spread, share of the pull
1567
- uniform vec2 u_light; // unit vector toward the light, y-down
1568
- uniform float u_rim; // rim falloff width, device px
1569
- uniform float u_lobe; // rim falloff exponent around the outline
1570
- uniform float u_gain; // rim alpha facing the light
1571
- uniform float u_far; // rim facing away, share of u_gain
1572
- uniform float u_shade; // projected-light shading facing the light
1573
- uniform float u_glow; // and facing away
1574
- uniform float u_reach; // share of the bevel the shading fades out across
1575
-
1576
- float dist(vec2 p) {
1577
- return u_field.eval(p).a * u_deepest;
1578
- }
1579
-
1580
- vec4 main(vec2 p) {
1581
- float d = dist(p);
1582
- vec2 g = vec2(dist(p + vec2(1.0, 0.0)) - dist(p - vec2(1.0, 0.0)),
1583
- dist(p + vec2(0.0, 1.0)) - dist(p - vec2(0.0, 1.0)));
1584
- float gl = length(g);
1585
- // Distance grows inward, so the outward normal is its negated gradient.
1586
- vec2 n = gl > 1e-4 ? -g / gl : vec2(0.0);
1587
-
1588
- // Squircle bevel: height h and its slope over the bevel, which is as tall as it is wide.
1589
- float x = clamp(d / u_bevel, 0.001, 1.0);
1590
- float y = 1.0 - x;
1591
- float y4 = y * y * y * y;
1592
- float h = pow(1.0 - y4, 0.25);
1593
- float slope = y * y * y * pow(max(1.0 - y4, 1e-6), -0.75);
1594
-
1595
- // Refract a straight-down ray through the surface normal (n\xB7slope, 1).
1596
- float cosi = inversesqrt(1.0 + slope * slope);
1597
- float k = 1.0 - u_eta * u_eta * (1.0 - cosi * cosi);
1598
- float a = u_eta * cosi - sqrt(max(k, 0.0));
1599
- float lateral = a * slope * cosi; // along n; negative, so inward
1600
- float down = a * cosi - u_eta; // negative
1601
- vec2 pull = n * (lateral / -down) * (u_bevel * h + u_base) * u_amount;
1602
- ${r?`
1603
- // Red bends least and blue most; integrating over the taps with a weight
1604
- // per channel turns the split into a spectrum rather than three ghosts.
1605
- vec3 sum = vec3(0.0);
1606
- vec3 weight = vec3(0.0);
1607
- float alpha = 0.0;
1608
- for (int i = 0; i < ${Kl}; i++) {
1609
- float t = float(i) / ${Kl-1}.0;
1610
- vec4 s = u_backdrop.eval(p + pull * (1.0 + u_spread * (t * 2.0 - 1.0)));
1611
- vec3 w = exp(-pow((vec3(t) - vec3(0.0, 0.5, 1.0)) / 0.3, vec3(2.0)));
1612
- sum += s.rgb * w;
1613
- weight += w;
1614
- alpha += s.a;
1615
- }
1616
- vec4 glass = vec4(sum / weight, alpha / ${Kl}.0);
1617
- glass.rgb = min(glass.rgb, vec3(glass.a));
1618
- `:`
1619
- vec4 glass = u_backdrop.eval(p + pull);
1620
- `}
1621
- float facing = dot(n, u_light);
1622
- float near = pow(max(facing, 0.0), u_lobe);
1623
- float far = u_far * pow(max(-facing, 0.0), u_lobe);
1624
-
1625
- // Light projected through the bevel: it leaves the side facing it a shade
1626
- // darker and lands on the opposite side, fading out across the bevel.
1627
- float across = 1.0 - smoothstep(0.0, u_reach, x);
1628
- glass.rgb *= 1.0 - u_shade * near * across;
1629
- glass.rgb += (vec3(glass.a) - glass.rgb) * (u_glow * far / u_far * across);
1630
-
1631
- // A thin rim on the outline, brightest facing the light and again, a little
1632
- // dimmer, on the side opposite it. White source-over, premultiplied.
1633
- float spec = clamp(u_gain * (near + far) * (1.0 - smoothstep(0.0, u_rim, d)), 0.0, 1.0);
1634
- return vec4(spec) + glass * (1.0 - spec);
1635
- }
1636
- `}var em=r=>Math.min(1,Math.max(0,r));function Ck(r,e){return Math.max(0,r.frost)*.5*e.scale}var tm={type:"glass",sampling:{tileMode:"clamp",filterMode:"linear"},handles:(r,e)=>e==="backdrop",renderInputs(r,e,t){if(!(r.depth>0))return null;let n=Ck(r,t);return n>.25?{distanceField:!0,blurredSource:n}:{distanceField:!0}},makeShader(r,e,t,n,i,s){let a=s?.distanceField;if(!a)return null;let o=Math.min(Math.max(0,r.depth)*n.scale,a.maxDistance);if(!(o>0))return null;let c=em(r.dispersion/100)*yk,l=em(r.splay/100),u=r.lightAngle*Math.PI/180,d=Math.max(0,r.lightIntensity/100),h=ue(_k(c>0),e);return h?h.makeShaderWithChildren([a.maxDistance,o,gk*o,1/pk,Math.max(0,r.refraction/100),c,Math.sin(u),-Math.cos(u),wk*n.scale,Sk,d*bk,kk,d*xk*(1-Jf*l),d*Tk*(1-Jf*l),Ak+vk*l],[s?.blurredSource??t,a.shader]):null}};var rm={type:"exposure",makeImageFilter(r,e){let t=r.amount,n=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0],i=e.ColorFilter.MakeMatrix(n),s=e.ImageFilter.MakeColorFilter(i,null);return i.delete(),s}};var nm={type:"alpha",makeImageFilter(r,e){let n=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,Math.max(0,Math.min(1,r.amount)),0],i=e.ColorFilter.MakeMatrix(n),s=e.ImageFilter.MakeColorFilter(i,null);return i.delete(),s}};var im={type:"colorMatrix",makeImageFilter(r,e){let t=e.ColorFilter.MakeMatrix(r.matrix),n=e.ImageFilter.MakeColorFilter(t,null);return t.delete(),n}};function Pk(r,e){if(r.length===0)return e;if(e<=r[0][0])return r[0][1];let t=r[r.length-1];if(e>=t[0])return t[1];for(let n=0;n<r.length-1;n++){let[i,s]=r[n],[a,o]=r[n+1];if(e>=i&&e<=a){let c=a===i?0:(e-i)/(a-i);return s+(o-s)*c}}return e}var En=32;function Ek(r){let e=[...r].sort((n,i)=>n[0]-i[0]),t=[];for(let n=0;n<=En;n++){let i=Pk(e,n/En);t.push(Number.isFinite(i)?Math.max(0,Math.min(1,i)):n/En)}return t}function Ik(r){return r.every((e,t)=>Math.abs(e-t/En)<1e-4)}function Mk(r){switch(r){case"r":return[1,0,0,0];case"g":return[0,1,0,0];case"b":return[0,0,1,0];case"a":return[0,0,0,1];default:return[1,1,1,0]}}function Fk(){let r=Array.from({length:En},(e,t)=>` y += (u_curve[${t+1}] - u_curve[${t}]) * clamp(t - ${t}.0, 0.0, 1.0);`).join(`
1637
- `);return`
1638
- uniform shader u_content;
1639
- uniform vec4 u_mask; // 1 on the channels this curve drives
1640
- uniform float u_curve[${En+1}]; // the curve, evenly spaced over 0\u20131
1641
-
1642
- vec4 lookup(vec4 c) {
1643
- vec4 t = clamp(c, 0.0, 1.0) * ${En}.0;
1644
- vec4 y = vec4(u_curve[0]);
1645
- ${r}
1646
- return y;
1647
- }
1648
-
1649
- vec4 main(vec2 p) {
1650
- vec4 src = u_content.eval(p);
1651
- // Nothing to grade, and dividing by zero alpha would make a NaN that spreads.
1652
- if (src.a <= 0.0) return src;
1653
-
1654
- // A curve is defined on straight colour; the shader is handed (and must
1655
- // return) premultiplied. The alpha it is remultiplied by is the *curved*
1656
- // one, so a curve on the alpha channel means what it says.
1657
- vec4 straight = vec4(src.rgb / src.a, src.a);
1658
- vec4 curved = mix(straight, lookup(straight), u_mask);
1659
- return vec4(clamp(curved.rgb, 0.0, 1.0) * curved.a, curved.a);
1660
- }
1661
- `}var sm={type:"curves",sampling:{tileMode:"clamp",filterMode:"linear"},makeShader(r,e,t){let n=Ek(r.points??[]);if(Ik(n))return null;let i=ue(Fk(),e);return i?i.makeShaderWithChildren([...Mk(r.channel??"rgb"),...n],[t]):null}};function Rk(){return[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]}function Bk(r,e){let t=new Array(20).fill(0);for(let n=0;n<4;n++)for(let i=0;i<5;i++){let s=0;for(let a=0;a<4;a++)s+=r[n*5+a]*e[a*5+i];i===4&&(s+=r[n*5+4]),t[n*5+i]=s}return t}function Dk(r){return[1,0,0,0,r,0,1,0,0,r,0,0,1,0,r,0,0,0,1,0]}function Ok(r){let e=.5*(1-r);return[r,0,0,0,e,0,r,0,0,e,0,0,r,0,e,0,0,0,1,0]}function am(r){let e=1-r;return[r+e*.2126,e*.7152,e*.0722,0,0,e*.2126,r+e*.7152,e*.0722,0,0,e*.2126,e*.7152,r+e*.0722,0,0,0,0,0,1,0]}function Lk(r){let e=r*Math.PI/180,t=Math.cos(e),n=Math.sin(e);return[.2126+t*(1-.2126)+n*-.2126,.7152+t*-.7152+n*-.7152,.0722+t*-.0722+n*(1-.0722),0,0,.2126+t*-.2126+n*.143,.7152+t*(1-.7152)+n*.14,.0722+t*-.0722+n*-.283,0,0,.2126+t*-.2126+n*-(1-.2126),.7152+t*-.7152+n*.7152,.0722+t*(1-.0722)+n*.0722,0,0,0,0,0,1,0]}function Uk(r){return[1,0,0,0,r*.1,0,1,0,0,0,0,0,1,0,-r*.1,0,0,0,1,0]}function Nk(r){return[1,0,0,0,r*.05,0,1,0,0,-r*.1,0,0,1,0,r*.05,0,0,0,1,0]}function zk(r){let e=1-.2*r,t=.2*r;return[e,0,0,0,t,0,e,0,0,t,0,0,e,0,t,0,0,0,1,0]}function Vk(r){let e=1+.2*r,t=-.1*r;return[e,0,0,0,t,0,e,0,0,t,0,0,e,0,t,0,0,0,1,0]}var om={type:"colorAdjustment",makeImageFilter(r,e){let t=Rk(),n=!1,i=g=>{t=Bk(g,t),n=!0},s=r.brightness??0;s!==0&&i(Dk(s));let a=r.contrast??1;a!==1&&i(Ok(a));let o=r.saturation??1;o!==1&&i(am(o));let c=((r.hue??0)%360+360)%360;c!==0&&i(Lk(c));let l=r.vibrance??0;l!==0&&i(am(1+l*.7));let u=r.temperature??0;u!==0&&i(Uk(u));let d=r.tint??0;d!==0&&i(Nk(d));let h=r.shadows??0;h!==0&&i(zk(h));let f=r.highlights??0;if(f!==0&&i(Vk(f)),!n)return null;let p=e.ColorFilter.MakeMatrix(t),m=e.ImageFilter.MakeColorFilter(p,null);return p.delete(),m}};var Wk=new Set(["motionBlurResolved"]),Jr=new Map;function qk(r){if(Wk.has(r.type))return;let e=n=>Hk({type:r.type,mode:n});(e("foreground")==="shader"||e("backdrop")==="shader")&&!r.makeShader&&console.warn(`[motionscript] Effect '${r.type}' declares surface 'shader' in core but its renderer handler has no makeShader() \u2014 it will never render.`),r.makeShader&&!r.sampling&&console.warn(`[motionscript] Effect handler '${r.type}' has makeShader() but no sampling mode.`)}function Gk(r,e,t){return r==null||e.clip!==!0?r:t.ImageFilter.MakeBlend(t.BlendMode.SrcIn,null,r)??r}var Se={register(r){qk(r),Jr.set(r.type,r)},alias(r,e){let t=Jr.get(e);if(!t)throw new Error(`Cannot alias "${r}" to unregistered effect "${e}".`);Jr.set(r,t)},get(r){return Jr.get(r)},has(r){return Jr.has(r)},makeImageFilter(r,e,t){let n=Jr.get(r.type);return n?.makeImageFilter?n.makeImageFilter(r,e,t):null},compose(r,e,t){let n=null;for(let i of r){let s=Gk(this.makeImageFilter(i,e,t),i,e);s!=null&&(n=n===null?s:e.ImageFilter.MakeCompose(s,n))}return n},resolveShader(r,e){let t=Jr.get(r.type);if(t?.makeShader&&!(t.handles&&!t.handles(r,e)))return t},isShaderEffect(r,e){return this.resolveShader(r,e)!==void 0},disposeAll(){for(let r of Jr.values())r.dispose?.()}};Se.register(Zh);Se.register(Jh);Se.register(ef);Se.register(tf);Se.register(rf);Se.register(nf);Se.register(sf);Se.register(af);Se.register(cf);Se.register(uf);Se.register(gf);Se.register(yf);Se.register(wf);Se.register(bf);Se.register(kf);Se.register(Sf);Se.register(xf);Se.register(Tf);Se.register(Af);Se.register(vf);Se.register(_f);Se.register(Cf);Se.register(Ef);Se.register(Mf);Se.register(Ff);Se.register(Rf);Se.register(Bf);Se.register(Lf);Se.register(qf);Se.register(Gf);Se.register(jf);Se.register($f);Se.register(Xf);Se.register(Qf);Se.register(Yf);Se.register(Zf);Se.register(tm);Se.register(mf);Se.alias("sksl","shader");Se.register(pf);Se.register(rm);Se.register(nm);Se.register(im);Se.register(sm);Se.register(om);function cm(r,e,t,n,i){if(!r||!(t>0)||!(n>0))return;let s=Math.max(t,n),a=e[0],o=e[1],c=e[3],l=e[4],u=r[6]??0,d=r[7]??0,h=r[8]??1,f=u!==0||d!==0||h!==1,p=0;if(f&&i){let m=[i.left,i.top,i.right,i.top,i.left,i.bottom,i.right,i.bottom];for(let g=0;g<8;g+=2){let y=Kk(r,m[g],m[g+1]);y&&(p=Math.max(p,io(y[0]*a+y[1]*c,y[0]*o+y[1]*l,y[2]*a+y[3]*c,y[2]*o+y[3]*l)))}}if(p===0){let m=r[0],g=r[1],y=r[3],b=r[4],k=f&&h!==0?Math.abs(h):1;p=io((m*a+g*c)/k,(m*o+g*l)/k,(y*a+b*c)/k,(y*o+b*l)/k)}if(!(!Number.isFinite(p)||p<=0))return p*s}function Kk(r,e,t){let n=r[6]*e+r[7]*t+r[8];if(!(n>1e-9))return null;let i=(r[0]*e+r[1]*t+r[2])/n,s=(r[3]*e+r[4]*t+r[5])/n;return[(r[0]-i*r[6])/n,(r[1]-i*r[7])/n,(r[3]-s*r[6])/n,(r[4]-s*r[7])/n]}function io(r,e,t,n){let i=r*r+e*e+t*t+n*n,s=r*n-e*t,a=Math.sqrt(Math.max(0,i*i-4*s*s));return Math.sqrt((i+a)/2)}function so(r,e,t,n,i){let s=n>0?e/n:1,a=i>0?t/i:1;return s===1&&a===1?r:[r[0]*s,r[1]*a,r[2],r[3]*s,r[4]*a,r[5],r[6]*s,r[7]*a,r[8]]}function lm(r,e){return e!==void 0&&e>0&&r/e>Math.SQRT2}var ao=class extends qe{applyPaint(e,t){if(!e.src)return Za(t);let n=t.getShapeBounds(),i=t.assets.getImageSize(e.src),s=i?jl(e,i,n,t):void 0,a=t.assets.getCKImage(e.src,s);if(!a)throw new jk("image",e.src);let o=Es(a,e,t.canvasKit,n,oo(e),{logical:i,footprint:s,mipmaps:!0});return t.transientPaintObjects.push(o),t.paint.setShader(co(e,t,o)),!0}dispose(){Yh()}};function Xk(r,e){return{centerX:r?(r.left+r.right)/2:0,centerY:r?(r.top+r.bottom)/2:0,width:r?r.right-r.left:0,height:r?r.bottom-r.top:0,scale:1,time:e,velocity:{x:0,y:0},angularVelocity:0}}function Qk(r,e){let t=e.getDeviceMatrix(),n=t?io(t[0],t[1],t[3],t[4]):1;return{...r,width:r.width*n,height:r.height*n,scale:n}}function jl(r,e,t,n){let i=lo(e.width,e.height,r,t);return cm(n.getDeviceMatrix(),i,e.width,e.height,t)}function oo(r){for(let e of r.preset?.adjustments??[]){let t=Se.resolveShader(e,"foreground");if(t)return t.sampling?.filterMode}}function co(r,e,t){let n=r.preset?.intensity??1,i=(r.preset?.adjustments??[]).filter(d=>$k(d.type));if(i.length===0||n<=0)return e.paint.setImageFilter(null),t;let s=Xk(e.getShapeBounds(),e.elapsed),a=[],o=t,c;for(let d of i){let h=Se.resolveShader(d,"foreground");if(!h){a.push(d);continue}let f=e.effectResources();f&&h.resources&&(c??=Qk(s,e));let p=(f&&h.resources?.(d,e.canvasKit,f,c))??[],m=h.makeShader(d,e.canvasKit,o,s,p);m&&(e.transientPaintObjects.push(m),o=m)}if(n<1&&o!==t){let d=Yk(t,o,n,e);d&&(e.transientPaintObjects.push(d),o=d)}let l=a.length>0?Se.compose(a,e.canvasKit,s):null;l&&e.transientPaintObjects.push(l);let u=n<1&&l?Jk(l,n,e):l;return u&&u!==l&&e.transientPaintObjects.push(u),e.paint.setImageFilter(u),e.clipFilterToShape=u!=null,o}function Yk(r,e,t,n){let i=ue(Zk,n.canvasKit);return i?i.makeShaderWithChildren([t],[r,e]):null}var Zk=`
1662
- uniform shader u_dry;
1663
- uniform shader u_wet;
1664
- uniform float u_t;
1665
-
1666
- vec4 main(vec2 p) {
1667
- return mix(u_dry.eval(p), u_wet.eval(p), u_t);
1668
- }
1669
- `;function Jk(r,e,t){let n=t.canvasKit,i=n.ColorFilter.MakeMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,e,0]),s=n.ImageFilter.MakeColorFilter(i,r);i.delete();let a=n.ImageFilter.MakeBlend(n.BlendMode.SrcOver,null,s);return s.delete(),a}function lo(r,e,t,n){if(t.matrix)return t.matrix instanceof Float32Array?Array.from(t.matrix):t.matrix.flat();let i=t.zoom??1;if(!n)return[i,0,0,0,i,0,0,0,1];let s=t.fit??"fill",a=n.right-n.left,o=n.bottom-n.top,c=s==="tile"?void 0:t.crop,l=c?c.left*r:0,u=c?c.top*e:0,d=c?r*(1-c.left-c.right):r,h=c?e*(1-c.top-c.bottom):e;if(d<=0||h<=0)return[i,0,n.left,0,i,n.top,0,0,1];let f,p;if(s==="fit"?f=p=Math.min(a/d,o/h):s==="stretch"?(f=a/d,p=o/h):s==="tile"?f=p=1:f=p=Math.max(a/d,o/h),f*=i,p*=i,s==="tile")return[f,0,n.left,0,p,n.top,0,0,1];let m=t.anchor??{x:0,y:0},g=(m.x+1)/2,y=(1-m.y)/2,b=n.left+g*(a-d*f)-l*f,k=n.top+y*(o-h*p)-u*p;return[f,0,b,0,p,k,0,0,1]}function Es(r,e,t,n,i="linear",s={}){let a=e.fit??"fill",o=a!=="fit"&&(e.zoom??1)>=1,c=a==="tile"?t.TileMode.Repeat:o?t.TileMode.Clamp:t.TileMode.Decal,l=r.width(),u=r.height(),d=s.logical?.width||l,h=s.logical?.height||u,f=so(lo(d,h,e,n),d,h,l,u),p=i!=="nearest"&&s.mipmaps===!0&&lm(Math.max(l,u),s.footprint);return r.makeShaderOptions(c,c,i==="nearest"?t.FilterMode.Nearest:t.FilterMode.Linear,p?t.MipmapMode.Linear:t.MipmapMode.None,f)}function rS(r,e,t){let n;return eS(r,i=>{if(!tS(i)||n?.has(i))return;let s=i.static===!0?i.identity:void 0;if(s!==void 0){let o=Is.get(s);if(o){o.used=t,(n??=new Map).set(i,o.raster);return}}let a=e.rasterizeSurface(i.source,i.width,i.height,i.maxPixelRatio??1);a&&((n??=new Map).set(i,a),s!==void 0&&(nS(t),Is.set(s,{raster:a,used:t})))}),n}var Is=new Map;function nS(r){for(let[e,t]of Is)t.used<r-1&&Is.delete(e)}function um(){Is.clear()}var uo=class extends qe{preflight(e,t){let n=`${t.nodeId}#${t.paintSlot(e)}`,i=ci(t.assets);if(!i){Sl(n);return}let s=t.getShapeBounds();if(!s)return;let a=s.right-s.left,o=s.bottom-s.top;if(!(a>0)||!(o>0))return;let c=rS(e.scene,t,i.frameIndex),l=Math.min(e.maxPixelRatio??2,Math.max(t.getDeviceScale(),1)),u=i.render(n,e.scene,Math.max(1,Math.ceil(a*l)),Math.max(1,Math.ceil(o*l)),{antialias:e.antialias!==!1,rasters:c}),d=t.assets.upload3DFrame(n,u.source,u.width,u.height);d&&t.preflighted.set(e,d)}applyPaint(e,t){let n=t.preflighted.get(e);if(!n)return!1;let i=t.canvasKit,s=lo(n.width(),n.height(),{fit:"stretch"},t.getShapeBounds()),a=n.makeShaderOptions(i.TileMode.Decal,i.TileMode.Decal,i.FilterMode.Linear,i.MipmapMode.None,s);return t.paint.setShader(a),t.transientPaintObjects.push(a),!0}};import{requireFontFamily as dm}from"@motionscript/core";function iS(r,e){switch(e){case"italic":return r.FontSlant.Italic;case"oblique":return r.FontSlant.Oblique;default:return r.FontSlant.Upright}}function sS(r,e){switch(e){case"left":return r.TextAlign.Left;case"right":return r.TextAlign.Right;case"justify":return r.TextAlign.Justify;case"start":return r.TextAlign.Start;case"end":return r.TextAlign.End;default:return r.TextAlign.Center}}function fm(r,e,t,n){let i=r.FontCollection.Make();i.setDefaultFontManager(e);let s=new r.ParagraphStyle({textStyle:{fontFamilies:[dm(t[0])],fontSize:t[0].fontSize},textAlign:sS(r,n.textAlign)}),a=r.ParagraphBuilder.MakeFromFontCollection(s,i),o=[],c=0;for(let y of t)o.push(c),a.pushStyle(new r.TextStyle({fontFamilies:[dm(y)],fontSize:y.fontSize,fontStyle:{weight:{value:y.fontWeight},slant:iS(r,y.fontStyle)},fontVariations:[{axis:"wght",value:y.fontWeight}],letterSpacing:y.letterSpacing,heightMultiplier:n.lineHeight})),a.addText(y.text),a.pop(),c+=y.text.length;let l=a.build(),u=isFinite(n.maxWidth)&&n.maxWidth>0;l.layout(u?n.maxWidth:1e7);let d=Math.ceil(l.getMaxIntrinsicWidth())+1,h=u?n.maxWidth:Math.max(d,n.boxWidth??0);l.layout(h);let f=l.getLongestLine(),p=l.getHeight(),m=n.originX-h/2,g=n.originY-p/2+aS(p,n);return{paragraph:l,builder:a,fontCollection:i,segmentStartChar:o,layoutWidth:h,blockWidth:f,blockHeight:p,shiftX:m,shiftY:g}}function Tr(r,e,t,n){let i=[],s=t.every(M=>M.text.length===0);if(t.length===0||s)return{runs:[],bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0,fonts:i};let a=fm(r,e,t,n),{paragraph:o,builder:c,fontCollection:l,segmentStartChar:u,layoutWidth:d,blockWidth:h,blockHeight:f,shiftX:p,shiftY:m}=a,g=new Map,y=(M,C)=>{let _=`${M.fontFamily}@${M.fontWeight}@${M.fontStyle}@${M.fontSize}`,F=g.get(_);if(F)return C?.delete(),F;let E=mi(r,C,M.fontSize);return C?.delete(),g.set(_,E),i.push(E),E},b=[],k=t.map(M=>M.text).join(""),T=t.some(M=>M.decoration!==void 0&&M.decoration!=="none"),x=o.getShapedLines();for(let M of x){let C=b.length,_=[];for(let F of M.runs){let E=F.glyphs.length;if(E===0)continue;let O=y(t[Xl(u,t,F.offsets[0])],F.typeface),Q=0,ye=Xl(u,t,F.offsets[0]),Z=ee=>{let ve=ee-Q;if(ve<=0)return;let Re=new Float32Array(ve*2);for(let et=0;et<ve;et++)Re[et*2]=F.positions[(Q+et)*2]+p,Re[et*2+1]=F.positions[(Q+et)*2+1]+m;b.push({segmentIndex:ye,glyphs:F.glyphs.slice(Q,ee),positions:Re,font:O}),T&&_.push(F.offsets.slice(Q,ee))};for(let ee=1;ee<E;ee++){let ve=Xl(u,t,F.offsets[ee]);ve!==ye&&(Z(ee),Q=ee,ye=ve)}Z(E)}T&&oS(b,C,_,k,t)}let v=h>0&&f>0?{left:p,top:m,right:p+d,bottom:m+f}:{left:0,top:0,right:0,bottom:0};return o.delete(),c.delete(),l.delete(),{runs:b,bounds:v,width:h,height:f,fonts:i}}function ho(r,e,t,n){let i=Array.isArray(t)?t:[t],s=i.map(y=>y.text).join("");if(i.length===0||s.length===0){let y=i[0];if(!y)return null;let b=ho(r,e,{...y,text:"M"},n);if(!b)return null;let k=b.lines[0];return{lines:[{start:0,end:0,top:k.top,bottom:k.bottom,carets:[0]}],width:0,height:b.height}}let a=fm(r,e,i,n),{paragraph:o,builder:c,fontCollection:l,blockWidth:u,blockHeight:d,shiftX:h,shiftY:f}=a,p=o.getLineMetrics(),m=[],g=0;for(let y=0;y<p.length;y++){let b=p[y],k=g,T=y===p.length-1?s.length:Math.min(s.length,Math.max(k,b.endIncludingNewline,b.endIndex,b.endExcludingWhitespaces)),x=T>k&&s[T-1]===`
1670
- `?T-1:T;g=T;let v=b.baseline-b.ascent+f,M=b.baseline+b.descent+f,C=[];for(let _=k;_<x;_++)C.push(hm(o,r,_,!1)+h);C.push(x>k?hm(o,r,x-1,!0)+h:b.left+h),m.push({start:k,end:x,top:v,bottom:M,carets:C})}return o.delete(),c.delete(),l.delete(),m.length===0?null:{lines:m,width:u,height:d}}function hm(r,e,t,n){let s=r.getRectsForRange(t,t+1,e.RectHeightStyle.Max,e.RectWidthStyle.Tight)[0]?.rect;return s?n?s[2]:s[0]:0}function aS(r,e){let t=e.boxHeight??0;if(t<=0)return 0;switch(e.verticalAlign){case"top":return(r-t)/2;case"bottom":return(t-r)/2;default:return 0}}function oS(r,e,t,n,i){let s=!0;for(let a=r.length-1;a>=e;a--){let o=r[a],c=t[a-e],l=o.glyphs.length;if(s){for(;l>0&&/\s/.test(n[c[l-1]]??"");)l--;l>0&&(s=!1)}let u=i[o.segmentIndex];l===0||u.decoration===void 0||u.decoration==="none"||(o.decoration=cS(o,l,u.fontSize,u.decoration))}}function cS(r,e,t,n){let i=r.font.getMetrics(),s=r.font.getGlyphWidths(r.glyphs.subarray(0,e)),a=r.positions[0],o=r.positions[(e-1)*2]+s[e-1],c=r.positions[1];if(n==="underline"){let d=$l(i.underlineThickness)??t/14,h=c+($l(i.underlinePosition)??d);return{left:a,top:h,right:o,bottom:h+d}}let l=$l(i.strikeoutThickness)??t/14,u=c+(i.strikeoutPosition!==void 0&&i.strikeoutPosition<0?i.strikeoutPosition:-t*.26);return{left:a,top:u-l/2,right:o,bottom:u+l/2}}function $l(r){return r!==void 0&&r>0?r:void 0}function Xl(r,e,t){for(let n=0;n<e.length;n++){let i=e[n].text.length;if(i>0&&t>=r[n]&&t<r[n]+i)return n}for(let n=e.length-1;n>=0;n--)if(e[n].text.length>0)return n;return 0}function Ql(r,e,t){Yl(r,e,0,0,t)}function Yl(r,e,t,n,i){r.drawGlyphs(e.glyphs,e.positions,t,n,e.font,i);let s=e.decoration;s&&r.drawRect(Float32Array.of(s.left+t,s.top+n,s.right+t,s.bottom+n),i)}function mm(r,e,t){let{spans:n,lineHeight:i,textAlign:s,width:a}=t,o=n.map(u=>({text:u.text,fontFamily:u.fontFamily,fontSize:u.fontSize,fontWeight:u.fontWeight,fontStyle:u.fontStyle,letterSpacing:u.letterSpacing})),c=Tr(r,e,o,{textAlign:s,lineHeight:i,maxWidth:a>0?a:1/0,boxWidth:a,originX:0,originY:0});return{runs:c.runs.map(u=>({...u,span:n[u.segmentIndex]})),bounds:c.bounds,fonts:c.fonts}}import{withTextDescriptor as Sm,isStyleOnlySegment as TS,resolveShapePivot as AS}from"@motionscript/core";import{AUTOFIT_PROBE_SIZE as lS,withTextDescriptor as uS}from"@motionscript/core";function Zl(r){let e=r.fontSize==="autofit"?lS:r.fontSize;return(r.segments??[]).map(t=>({text:t.text,fontFamily:t.fontFamily??r.fontFamily,fontSize:t.fontSize??e,fontWeight:t.fontWeight,fontStyle:t.fontStyle??r.fontStyle,letterSpacing:t.letterSpacing,decoration:t.textDecoration??r.textDecoration}))}function pm(r,e,t){let n=uS(t),i=n.segments??[],s=Zl(n),a=n.wrap&&n.width>0,o=Tr(r,e,s,{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:a?n.width:1/0,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:n.x,originY:n.y});return{runs:o.runs.map(l=>({...l,segment:i[l.segmentIndex]})),bounds:o.bounds,fonts:o.fonts}}function gm(r){let e=r.positions;if(e.length===0)return{x:0,y:0};let t=1/0,n=-1/0,i=1/0,s=-1/0;for(let a=0;a<e.length;a+=2){let o=e[a],c=e[a+1];o<t&&(t=o),o>n&&(n=o),c<i&&(i=c),c>s&&(s=c)}return{x:(t+n)/2,y:(i+s)/2}}import{withTextDescriptor as dS,pathOps as hS}from"@motionscript/core";function fS(r,e){switch(e){case"italic":return r.FontSlant.Italic;case"oblique":return r.FontSlant.Oblique;default:return r.FontSlant.Upright}}function mS(r,e,t){switch(r){case"right":case"end":return t-e;case"center":return(t-e)/2;default:return 0}}var pS=64,en=new Map,gS="";function yS(r,e,t){return[r.text,r.fontFamily,e,r.fontWeight,r.fontStyle,r.letterSpacing,r.lineHeight,t].join(gS)}function wS(r,e,t,n,i){let s=yS(t,n,i),a=en.get(s);if(a)return en.delete(s),en.set(s,a),a.run;let o=bS(r,e,t,n);if(!o)return null;if(en.set(s,{run:o.run,fonts:o.fonts}),en.size>pS){let c=en.keys().next().value;if(c!==void 0){let l=en.get(c);if(en.delete(c),l)for(let u of l.fonts)u.delete()}}return o.run}function bS(r,e,t,n){let i=[],s=r.FontCollection.Make();s.setDefaultFontManager(e);let a=new r.ParagraphStyle({textStyle:{fontFamilies:[t.fontFamily],fontSize:n},textAlign:r.TextAlign.Left}),o=r.ParagraphBuilder.MakeFromFontCollection(a,s);o.pushStyle(new r.TextStyle({fontFamilies:[t.fontFamily],fontSize:n,fontStyle:{weight:{value:t.fontWeight},slant:fS(r,t.fontStyle)},fontVariations:[{axis:"wght",value:t.fontWeight}],letterSpacing:t.letterSpacing,heightMultiplier:t.lineHeight})),o.addText(t.text.replace(/\s*\n\s*/g," ")),o.pop();let c=o.build();c.layout(1e7);let l=new Map,u=m=>{let g=`${t.fontFamily}@${t.fontWeight}@${t.fontStyle}@${n}`,y=l.get(g);if(y)return m?.delete(),y;let b=mi(r,m,n);return m?.delete(),l.set(g,b),i.push(b),b},h=c.getShapedLines()[0];if(!h){c.delete(),o.delete(),s.delete();for(let m of i)m.delete();return null}let f=0;for(let m of h.runs){let g=m.glyphs.length;g>0&&(f=Math.max(f,m.positions[g*2]))}let p=[];for(let m of h.runs){let g=m.glyphs.length;if(g===0)continue;let y=u(m.typeface);for(let b=0;b<g;b++){let k=m.positions[b*2],T=m.positions[(b+1)*2]-k,x=k+T/2,v=m.positions[b*2+1]-h.baseline;p.push({glyphId:m.glyphs[b],midX:x,advance:T,perp:v,font:y})}}return c.delete(),o.delete(),s.delete(),{run:{glyphs:p,textWidth:f,fontSize:n},fonts:i}}function kS(r,e,t){let n={glyphs:[],bounds:{left:0,top:0,right:0,bottom:0}},i=hS.sampler(e);if(i.length<=0)return n;let s=mS(t,r.textWidth,i.length),a=[],o=1/0,c=1/0,l=-1/0,u=-1/0,d=(p,m)=>{p<o&&(o=p),p>l&&(l=p),m<c&&(c=m),m>u&&(u=m)};for(let p of r.glyphs){let m=p.midX+s;if(m<0||m>i.length)continue;let g=i.frameAt(m);if(!g)continue;let y=g.x+p.perp*-g.ty,b=g.y+p.perp*g.tx,k=Math.atan2(g.ty,g.tx)*180/Math.PI;a.push({glyphId:p.glyphId,x:y,y:b,angle:k,halfAdvance:p.advance/2,font:p.font}),d(y,b)}let h=r.fontSize,f=a.length>0?{left:o-h,top:c-h,right:l+h,bottom:u+h}:{left:0,top:0,right:0,bottom:0};return{glyphs:a,bounds:f}}function ym(r,e,t,n){let i=dS(t),s={glyphs:[],bounds:{left:0,top:0,right:0,bottom:0}};if(i.text.length===0||i.path==null)return s;let a=i.fontSize==="autofit"?100:i.fontSize,o=wS(r,e,i,a,n);return o?kS(o,i.path,i.textAlign):s}function wm(r,e,t){for(let n of e)r.save(),r.translate(n.x,n.y),n.angle!==0&&r.rotate(n.angle,0,0),r.drawGlyphs([n.glyphId],new Float32Array([-n.halfAdvance,0]),0,0,n.font,t),r.restore()}var SS={width:0,height:0},xS="";function Jl(r,e){return[r.text,r.fontFamily,r.fontSize,r.fontWeight,r.fontStyle,r.letterSpacing,r.decoration,r.lineHeight,r.textAlign,r.verticalAlign,r.maxWidth,r.boxWidth,r.boxHeight,e].join(xS)}var fo=class{limit;ceiling;map=new Map;pass=0;constructor(e=256,t=16384){this.limit=e,this.ceiling=t}get(e,t){let n=this.map.get(e);if(n)return this.map.delete(e),this.map.set(e,n),n.pass=this.pass,n;let i={layout:t(),pass:this.pass};return this.map.set(e,i),this._evict(),i}endPass(){this.pass++,this._evict()}dispose(){for(let e of this.map.values())for(let t of e.layout.fonts)t.delete();this.map.clear()}_evict(){for(;this.map.size>this.limit;){let[e,t]=this.map.entries().next().value;if(t.pass>=this.pass-1&&this.map.size<=this.ceiling)return;this.map.delete(e);for(let n of t.layout.fonts)n.delete()}}};function eu(r,e,t,n,i,s=0,a="center"){return{text:r.text,fontFamily:r.fontFamily,fontSize:r.fontSize,fontWeight:r.fontWeight,fontStyle:r.fontStyle,letterSpacing:r.letterSpacing,decoration:r.decoration??"none",lineHeight:t,textAlign:e,verticalAlign:a,maxWidth:n,boxWidth:i,boxHeight:a==="center"?0:s}}var bm="center",km=1;function mo(r,e,t,n,i,s,a,o,c,l){if(i.length===0)return SS;let u={text:i,fontFamily:a,fontSize:s,fontWeight:o,fontStyle:l,letterSpacing:c},d=Jl(eu(u,bm,km,1/0,0),n),{layout:h}=t.get(d,()=>Tr(r,e,[u],{textAlign:bm,lineHeight:km,maxWidth:1/0,originX:0,originY:0}));return{width:h.width,height:h.height}}function vS(r,e,t,n,i){let s=n*Math.PI/180,a=Math.cos(s),o=Math.sin(s),c=[{x:r.left,y:r.top},{x:r.right,y:r.top},{x:r.right,y:r.bottom},{x:r.left,y:r.bottom}],l=1/0,u=1/0,d=-1/0,h=-1/0;for(let f of c){let p=(f.x-e)*i,m=(f.y-t)*i,g=e+p*a-m*o,y=t+p*o+m*a;g<l&&(l=g),g>d&&(d=g),y<u&&(u=y),y>h&&(h=y)}return{left:l,top:u,right:d,bottom:h}}function xm(r,e,t){let n=t.fontSize==="autofit",i=n?100:t.fontSize,s=t.wrap&&t.width>0,a=o=>({text:t.text,fontFamily:t.fontFamily,fontSize:o,fontWeight:t.fontWeight,fontStyle:t.fontStyle,letterSpacing:t.letterSpacing,decoration:t.textDecoration});if(n&&t.width>0&&t.height>0){let o=Tr(r,e,[a(i)],{textAlign:t.textAlign,lineHeight:t.lineHeight,maxWidth:1/0,originX:t.x,originY:t.y}),c=o.width>0?t.width/o.width:1,l=o.height>0?t.height/o.height:1,u=i*Math.min(c,l);for(let d of o.fonts)d.delete();s&&u<t.minFontSize?i=t.minFontSize:(i=u,s=!1)}return{segment:a(i),maxWidth:s?t.width:1/0}}function po(r,e,t){let n=Sm(t);if(n.path!=null)return null;let i=n.segments??[];if(i.length>0){if(!i.every(TS))return null;let o=n.wrap&&n.width>0;return ho(r,e,Zl(n),{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:o?n.width:1/0,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:0,originY:0})}let{segment:s,maxWidth:a}=xm(r,e,n);return ho(r,e,s,{textAlign:n.textAlign,lineHeight:n.lineHeight,maxWidth:a,boxWidth:n.width,boxHeight:n.height,verticalAlign:n.verticalAlign,originX:0,originY:0})}function Tm(r,e,t,n,i,s){let a=Sm(n);if(a.path!=null){let F=ym(r,t,n,s);return{bounds:F.bounds,draw:E=>wm(e,F.glyphs,E)}}let o=a.x,c=a.y,{segment:l,maxWidth:u}=xm(r,t,a),d=Jl(eu(l,a.textAlign,a.lineHeight,u,a.width,a.height,a.verticalAlign),s),{layout:h}=i.get(d,()=>Tr(r,t,[l],{textAlign:a.textAlign,lineHeight:a.lineHeight,maxWidth:u,boxWidth:a.width,boxHeight:a.height,verticalAlign:a.verticalAlign,originX:0,originY:0})),f=AS(a.pivot),p=a.width>0&&a.height>0,m=p?a.width:h.width,g=p?a.height:h.height,y=!p&&f.x!==0?o-f.x*(h.width/2):o,b=!p&&f.y!==0?c+f.y*(h.height/2):c,k=h.bounds,T={left:k.left+y,top:k.top+b,right:k.right+y,bottom:k.bottom+b},x=a.rotation,v=a.scale,M=x!==0||v!==1,C=y+f.x*(m/2),_=b-f.y*(g/2);return M&&(T=vS(T,C,_,x,v)),{bounds:T,isText:!0,draw:F=>{M&&e.save();try{M&&(e.translate(C,_),e.rotate(x,0,0),e.scale(v,v),e.translate(-C,-_));for(let E of h.runs)Yl(e,E,y,b,F)}finally{M&&e.restore()}}}}import{cornerRadiusOps as tu,cornerStyleOps as _S,withRectDescriptor as CS}from"@motionscript/core";function In(r,e,t,n){let i=0,s=new r.ContourMeasureIter(e,!1,1),a=s.next();for(;a;)i+=a.length(),a.delete(),a=s.next();if(s.delete(),i<=0)return e.copy();let o=t*i,c=n*i,l=[];s=new r.ContourMeasureIter(e,!1,1);let u=0;for(a=s.next();a;){let h=a.length(),f=u,p=u+h;if(p>o&&f<c){let m=Math.max(0,o-f),g=Math.min(h,c-f);l.push(a.getSegment(m,g,!0))}u=p,a.delete(),a=s.next()}if(s.delete(),l.length===0)return r.Path.MakeFromSVGString("M 0 0")??e.copy();if(l.length===1)return l[0];let d=l.map(h=>h.toSVGString());return l.forEach(h=>h.delete()),r.Path.MakeFromSVGString(d.join(" "))??e.copy()}var Tt=class{canvasKit;fullState;inputState;ckPath;_basePath;_geo;getCanvas;get canvas(){return this.getCanvas()}constructor(e,t,n){this.canvasKit=e,this.getCanvas=t,this.inputState=n,this.fullState=this.resolveState(n)}buildSVGAlignInterior(e){return null}_alignInterior;_alignInteriorBuilt=!1;strokeAlignInterior(){if(!this._alignInteriorBuilt){this._alignInteriorBuilt=!0;let e=this.buildSVGAlignInterior(this.geometry);if(e!=null){let t=this.canvasKit.Path.MakeFromSVGString(e);this._alignInterior=t?this.applyShapeTransform(t):void 0}}return this._alignInterior??(this.needsTrim()?this._basePath:void 0)}buildSpreadSVGPath(e,t){return null}hasTrim(){return this.needsTrim()}trimRange(){return this.getTrimRange()}hasShapeTransform(){let e=this.fullState;return(e.rotation??0)!==0||(e.scale??1)!==1}get geometry(){return this._geo??=this.computeGeometry()}ensurePath(){if(this.ckPath)return;let e=this.buildSVGPath(this.geometry),t=this.canvasKit.Path.MakeFromSVGString(e);if(!t){console.warn(`${this.constructor.name}: failed to create path`);return}let n=this.applyShapeTransform(t);if(this.needsTrim()){this._basePath=n;let{start:i,end:s}=this.getTrimRange();this.ckPath=In(this.canvasKit,n,i,s)}else this.ckPath=n}applyShapeTransform(e,t){let n=this.fullState,i=n.rotation??0,s=n.scale??1;if(i===0&&s===1)return e;let a=t?t.x:n.x??0,o=t?t.y:n.y??0,c=n.pivot??{x:0,y:0},l=a+c.x*((n.width??0)/2),u=o-c.y*((n.height??0)/2),d=i*Math.PI/180,h=Math.cos(d),f=Math.sin(d),p=h*s,m=-f*s,g=f*s,y=h*s,b=l-p*l-m*u,k=u-g*l-y*u,T=new this.canvasKit.PathBuilder(e);T.transform(p,m,b,g,y,k,0,0,1);let x=T.detachAndDelete();return e.delete(),x}spreadPath(e){let t=this.buildSpreadSVGPath(this.geometry,e);if(t==null)return null;let n=this.canvasKit.Path.MakeFromSVGString(t);return n?this.applyShapeTransform(n):null}_setBasePath(e){this._basePath=e}paintBounds(){if(!this._basePath)return;let e=this._basePath.getBounds();return{left:e[0],top:e[1],right:e[2],bottom:e[3]}}retrim(e,t){let n=this._basePath;if(!n)return;let i=this.fullState;i.start=e,i.end=t,this.ckPath?.delete(),this.ckPath=In(this.canvasKit,n,e,t),this._strokePath?.delete(),this._strokePath=void 0,this._strokePathBuilt=!1}_strokePath;_strokePathBuilt=!1;strokePath(){return this._strokePathBuilt||(this._strokePathBuilt=!0,this.ensurePath(),this._strokePath=this.ckPath?this.buildStrokePath(this.ckPath):void 0),this._strokePath}buildStrokePath(e){}deletePaths(){this.ckPath?.delete(),this.ckPath=void 0,this._basePath?.delete(),this._basePath=void 0,this._alignInterior?.delete(),this._alignInterior=void 0,this._alignInteriorBuilt=!1,this._strokePath?.delete(),this._strokePath=void 0,this._strokePathBuilt=!1}draw(e,t){this.ensurePath(),this.ckPath&&this.canvas.drawPath(this.ckPath,e)}strokeDraw(e){let t=this.strokePath()??this.ckPath;t&&this.canvas.drawPath(t,e)}clip(e){this.ensurePath(),this.ckPath&&this.canvas.clipPath(this.ckPath,this.canvasKit.ClipOp.Intersect,!0)}supportsSpread(){return!1}toCurrentShape(e){let t=this;return{draw:n=>t.draw(n,e),strokeDraw:n=>t.strokeDraw(n),get ckPath(){return t.ckPath},get strokePath(){return t.strokePath()},get alignInterior(){return t.strokeAlignInterior()},get paintBounds(){return t.paintBounds()},trimmed:this.needsTrim(),bounds:this.computeBounds(this.geometry),spreadPath:this.supportsSpread()?n=>t.spreadPath(n):void 0}}computeBounds(e){}};function Ar(r){return r.radius>0?r.radius:0}function Ms(r,e,t,n,i,s,a){return a.radius<=0?"":Fs(r,e,t,n,i,s,a.radius,a.radius,a.style)}function Fs(r,e,t,n,i,s,a,o,c){let l=r+i*a,u=e+s*a;if(c==="angled")return`L ${l} ${u}`;let h=t*s-n*i<0?1:0;return`A ${o} ${o} 0 0 ${h} ${l} ${u}`}function Am(r,e,t,n,i,s,a,o){let c=Ar(i),l=Ar(s),u=Ar(a),d=Ar(o);return[`M ${r+c} ${e}`,`L ${t-l} ${e}`,Ms(t,e,-1,0,0,1,s),`L ${t} ${n-u}`,Ms(t,n,0,-1,-1,0,a),`L ${r+d} ${n}`,Ms(r,n,1,0,0,-1,o),`L ${r} ${e+c}`,Ms(r,e,0,1,1,0,i),"Z"].filter(Boolean).join(" ")}var pi=class extends Tt{resolveState(e){return CS(e)}computeGeometry(){let e=this.fullState,t=e.width/2,n=e.height/2,i=e.x-t,s=e.y-n,a=e.x+t,o=e.y+n,c=tu.resolve(e.cornerRadius),l=_S.resolve(e.cornerStyle),u={radius:Math.max(0,c.topLeft),style:l.topLeft},d={radius:Math.max(0,c.topRight),style:l.topRight},h={radius:Math.max(0,c.bottomRight),style:l.bottomRight},f={radius:Math.max(0,c.bottomLeft),style:l.bottomLeft},p=vm(e.width,e.height,u,d,h,f);u.radius*=p,d.radius*=p,h.radius*=p,f.radius*=p;let m={topLeft:u.radius,topRight:d.radius,bottomRight:h.radius,bottomLeft:f.radius},g=l.topLeft==="rounded"&&l.topRight==="rounded"&&l.bottomRight==="rounded"&&l.bottomLeft==="rounded";return{left:i,top:s,right:a,bottom:o,tl:u,tr:d,br:h,bl:f,isZero:tu.isZero(m),isUniform:tu.isUniform(m),isPlainRounded:g}}buildSVGPath(e){let{left:t,top:n,right:i,bottom:s,tl:a,tr:o,br:c,bl:l,isZero:u}=e;return u?`M ${t} ${n} L ${i} ${n} L ${i} ${s} L ${t} ${s} Z`:Am(t,n,i,s,a,o,c,l)}hasCornerRadius(){return!this.geometry.isZero}supportsSpread(){return!0}buildSpreadSVGPath(e,t){let n=e.left-t,i=e.top-t,s=e.right+t,a=e.bottom+t,o=s-n,c=a-i;if(o<=0||c<=0)return null;let l={...e.tl,radius:Math.max(0,e.tl.radius+t)},u={...e.tr,radius:Math.max(0,e.tr.radius+t)},d={...e.br,radius:Math.max(0,e.br.radius+t)},h={...e.bl,radius:Math.max(0,e.bl.radius+t)},f=vm(o,c,l,u,d,h);return l.radius*=f,u.radius*=f,d.radius*=f,h.radius*=f,l.radius===0&&u.radius===0&&d.radius===0&&h.radius===0?`M ${n} ${i} L ${s} ${i} L ${s} ${a} L ${n} ${a} Z`:Am(n,i,s,a,l,u,d,h)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}draw(e,t){let n=this.geometry;if(t&&!this.needsTrim()&&!this.hasShapeTransform()){let i=this.canvasKit,s=i.LTRBRect(n.left,n.top,n.right,n.bottom);if(n.isZero){this.canvas.drawRect(s,e);return}if(n.isUniform&&n.isPlainRounded){this.canvas.drawRRect(i.RRectXY(s,n.tl.radius,n.tl.radius),e);return}}super.draw(e,t)}clip(e){let t=this.geometry,n=this.canvasKit;if(e&&!this.needsTrim()&&!this.hasShapeTransform()){let i=n.LTRBRect(t.left,t.top,t.right,t.bottom);if(t.isZero){this.canvas.clipRect(i,n.ClipOp.Intersect,!0);return}if(t.isUniform&&t.isPlainRounded){this.canvas.clipRRect(n.RRectXY(i,t.tl.radius,t.tl.radius),n.ClipOp.Intersect,!0);return}}super.clip(e)}};function vm(r,e,t,n,i,s){let a=Ar(t),o=Ar(n),c=Ar(i),l=Ar(s),u=a+o>0?Math.min(1,r/(a+o)):1,d=l+c>0?Math.min(1,r/(l+c)):1,h=a+l>0?Math.min(1,e/(a+l)):1,f=o+c>0?Math.min(1,e/(o+c)):1;return Math.min(u,d,h,f)}import{withEllipseDescriptor as PS}from"@motionscript/core";var tn=Math.PI/180,gi=class extends Tt{resolveState(e){return PS(e)}computeGeometry(){let e=this.fullState,t=e.sweep??360;return{cx:e.x,cy:e.y,halfWidth:e.width/2,halfHeight:e.height/2,sweep:t,isFullShape:Math.abs(t)>=360,startAngle:e.startAngle??0,ratio:Math.max(0,Math.min(1,e.ratio??0))}}buildSVGPath(e){let{cx:t,cy:n,halfWidth:i,halfHeight:s,ratio:a}=e;if(a>=1)return"";if(!e.isFullShape)return a<=0?_m(e):Cm(e);let o=Rs(t,n,i,s,0);return a<=0?o:`${o} ${Rs(t,n,i*a,s*a,1)}`}buildSVGAlignInterior(e){return e.isFullShape?e.ratio>=1?Rs(e.cx,e.cy,e.halfWidth,e.halfHeight,0):null:e.ratio>=1||e.ratio<=0?_m(e):Cm(e)}buildStrokePath(e){let t=this._outline();if(!t)return;if(!this.needsTrim())return t.copy();let{start:n,end:i}=this.getTrimRange();return In(this.canvasKit,t,n,i)}paintBounds(){let e=this._outline();if(!e)return super.paintBounds();let[t,n,i,s]=e.getBounds();return{left:t,top:n,right:i,bottom:s}}deletePaths(){super.deletePaths(),this._outlinePath?.delete(),this._outlinePath=void 0,this._outlineBuilt=!1}supportsSpread(){return!0}buildSpreadSVGPath(e,t){if(!e.isFullShape||e.ratio>=1)return null;let n=e.halfWidth+t,i=e.halfHeight+t;return n<=0||i<=0?null:Rs(e.cx,e.cy,n,i,0)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){let{cx:t,cy:n,halfWidth:i,halfHeight:s}=e;return{left:t-i,top:n-s,right:t+i,bottom:n+s}}_outlinePath;_outlineBuilt=!1;_outline(){if(!this._outlineBuilt){this._outlineBuilt=!0;let e=this.geometry;if(e.ratio>=1){let t=e.isFullShape?Rs(e.cx,e.cy,e.halfWidth,e.halfHeight,0):ES(e),n=this.canvasKit.Path.MakeFromSVGString(t);this._outlinePath=n?this.applyShapeTransform(n):void 0}}return this._outlinePath}};function Rs(r,e,t,n,i){let s=r-t,a=r+t;return`M ${s} ${e} A ${t} ${n} 0 1 ${i} ${a} ${e} A ${t} ${n} 0 1 ${i} ${s} ${e} Z`}function ru(r){let{cx:e,cy:t,halfWidth:n,halfHeight:i,startAngle:s,sweep:a}=r,o=s+a,c=Math.abs(a)>180?1:0,l=a>0?1:0,u=e+n*Math.cos(s*tn),d=t+i*Math.sin(s*tn),h=e+n*Math.cos(o*tn),f=t+i*Math.sin(o*tn);return{start:`${u} ${d}`,arc:`A ${n} ${i} 0 ${c} ${l} ${h} ${f}`}}function ES(r){let{start:e,arc:t}=ru(r);return`M ${e} ${t}`}function _m(r){let{start:e,arc:t}=ru(r);return`M ${r.cx} ${r.cy} L ${e} ${t} Z`}function Cm(r){let{cx:e,cy:t,halfWidth:n,halfHeight:i,startAngle:s,sweep:a,ratio:o}=r,{start:c,arc:l}=ru(r),u=s+a,d=n*o,h=i*o,f=e+d*Math.cos(s*tn),p=t+h*Math.sin(s*tn),m=e+d*Math.cos(u*tn),g=t+h*Math.sin(u*tn),y=Math.abs(a)>180?1:0,b=a>0?0:1;return`M ${c} ${l} L ${m} ${g} A ${d} ${h} 0 ${y} ${b} ${f} ${p} Z`}import{withPolygonDescriptor as IS}from"@motionscript/core";function MS(r,e,t,n,i,s,a){let o=2*Math.PI/i,c=-Math.PI/2,l=[];for(let d=0;d<i;d++){let h=c+d*o;l.push([r+t*Math.cos(h),e+n*Math.sin(h)])}if(s<=0){let d=l.map(([h,f],p)=>`${p===0?"M":"L"} ${h} ${f}`);return d.push("Z"),d.join(" ")}let u=[];for(let d=0;d<i;d++){let h=l[(d-1+i)%i],f=l[d],p=l[(d+1)%i],m=h[0]-f[0],g=h[1]-f[1],y=Math.hypot(m,g),b=m/y,k=g/y,T=p[0]-f[0],x=p[1]-f[1],v=Math.hypot(T,x),M=T/v,C=x/v,_=Math.max(-1,Math.min(1,b*M+k*C)),F=Math.acos(_)/2,E=Math.tan(F),O=Math.min(y,v)/2,Q=s/E;Q>O&&(Q=O);let ye=Q*E,Z=f[0]+b*Q,ee=f[1]+k*Q;u.push(`${u.length===0?"M":"L"} ${Z} ${ee}`),u.push(Fs(f[0],f[1],b,k,M,C,Q,ye,a))}return u.push("Z"),u.join(" ")}var yi=class extends Tt{resolveState(e){return IS(e)}computeGeometry(){let e=this.fullState;return{cx:e.x,cy:e.y,rx:e.width/2,ry:e.height/2,sides:Math.max(3,Math.round(e.sides)),cornerRadius:e.cornerRadius,cornerStyle:e.cornerStyle}}buildSVGPath(e){return MS(e.cx,e.cy,e.rx,e.ry,e.sides,e.cornerRadius,e.cornerStyle)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.cx-e.rx,top:e.cy-e.ry,right:e.cx+e.rx,bottom:e.cy+e.ry}}};import{withPolygramDescriptor as FS}from"@motionscript/core";function RS(r,e,t,n,i,s,a,o){let c=i*2,l=Math.PI/i,u=-Math.PI/2,d=[];for(let f=0;f<c;f++){let p=u+f*l,g=f%2===0?1:s;d.push([r+t*g*Math.cos(p),e+n*g*Math.sin(p)])}if(a<=0){let f=d.map(([p,m],g)=>`${g===0?"M":"L"} ${p} ${m}`);return f.push("Z"),f.join(" ")}let h=[];for(let f=0;f<c;f++){let p=d[f];if(!(f%2===0)){h.push(`${h.length===0?"M":"L"} ${p[0]} ${p[1]}`);continue}let g=d[(f-1+c)%c],y=d[(f+1)%c],b=g[0]-p[0],k=g[1]-p[1],T=Math.hypot(b,k),x=b/T,v=k/T,M=y[0]-p[0],C=y[1]-p[1],_=Math.hypot(M,C),F=M/_,E=C/_,O=Math.max(-1,Math.min(1,x*F+v*E)),Q=Math.acos(O)/2,ye=Math.tan(Q),Z=Math.min(T,_)/2,ee=a/ye;ee>Z&&(ee=Z);let ve=ee*ye,Re=p[0]+x*ee,et=p[1]+v*ee;h.push(`${h.length===0?"M":"L"} ${Re} ${et}`),h.push(Fs(p[0],p[1],x,v,F,E,ee,ve,o))}return h.push("Z"),h.join(" ")}var wi=class extends Tt{resolveState(e){return FS(e)}computeGeometry(){let e=this.fullState;return{cx:e.x,cy:e.y,rx:e.width/2,ry:e.height/2,sides:Math.max(3,Math.round(e.sides)),ratio:Math.max(0,Math.min(1,e.ratio)),cornerRadius:e.cornerRadius,cornerStyle:e.cornerStyle}}buildSVGPath(e){return RS(e.cx,e.cy,e.rx,e.ry,e.sides,e.ratio,e.cornerRadius,e.cornerStyle)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}computeBounds(e){return{left:e.cx-e.rx,top:e.cy-e.ry,right:e.cx+e.rx,bottom:e.cy+e.ry}}};import{toPathString as BS,withPathDescriptor as DS}from"@motionscript/core";var bi=class extends Tt{resolveState(e){return DS(e)}computeGeometry(){return{svgString:BS(this.fullState.data),offsetX:0,offsetY:0}}buildSVGPath(e){return e.svgString}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}buildCenteredTransformedTrimmed(e,t,n){let i=this.canvasKit.Path.MakeFromSVGString(e);if(!i){console.warn("PathShape: failed to parse SVG path string:",e);return}let s=new this.canvasKit.PathBuilder(i);s.offset(t,n);let a=s.detachAndDelete();i.delete();let o=this.applyShapeTransform(a,{x:0,y:0});if(this.needsTrim()){this._setBasePath(o);let{start:c,end:l}=this.getTrimRange();return In(this.canvasKit,o,c,l)}return o}ensurePath(){if(this.ckPath)return;let e=this.geometry,t=this.canvasKit.Path.MakeFromSVGString(e.svgString);if(!t){console.warn("PathShape: failed to parse SVG path string:",e.svgString);return}let n=this.fullState.centerBounds,[i,s,a,o]=n??t.getBounds();e.offsetX=-(i+(a-i)/2),e.offsetY=-(s+(o-s)/2),t.delete(),this.ckPath=this.buildCenteredTransformedTrimmed(e.svgString,e.offsetX,e.offsetY)}draw(e,t){this.ensurePath(),this.ckPath&&this.canvas.drawPath(this.ckPath,e)}clip(e){this.ensurePath(),this.ckPath&&this.canvas.clipPath(this.ckPath,this.canvasKit.ClipOp.Intersect,!0)}};import{withLineDescriptor as OS}from"@motionscript/core";function LS(r,e,t){if(r.length===0)return"M 0 0";if(r.length===1)return`M ${r[0].x} ${r[0].y}`;let n=Math.max(0,e),i=[],s=r.length,a=(o,c)=>{let l=c.x-o.x,u=c.y-o.y,d=Math.sqrt(l*l+u*u);return d>0?{dx:l/d,dy:u/d,len:d}:{dx:0,dy:0,len:0}};if(n===0){i.push(`M ${r[0].x} ${r[0].y}`);for(let o=1;o<s;o++)i.push(`L ${r[o].x} ${r[o].y}`)}else{let o=t?s:s-1;for(let c=0;c<=o;c++){let l=r[(c-1+s)%s],u=r[c%s],d=r[(c+1)%s];if(!t&&c===0){i.push(`M ${u.x} ${u.y}`);continue}if(!t&&c===s-1){i.push(`L ${u.x} ${u.y}`);continue}let h=a(l,u),f=a(u,d),p=Math.min(n,h.len/2),m=Math.min(n,f.len/2),g=u.x-h.dx*p,y=u.y-h.dy*p,b=u.x+f.dx*m,k=u.y+f.dy*m;c===0&&t?i.push(`M ${g} ${y}`):i.push(`L ${g} ${y}`),i.push(`Q ${u.x} ${u.y} ${b} ${k}`)}}return t&&i.push("Z"),i.join(" ")}var ki=class extends Tt{resolveState(e){return OS(e)}computeGeometry(){let{points:e,radius:t,closed:n}=this.fullState;return{points:e,radius:t,closed:n}}buildSVGPath(e){return LS(e.points,e.radius,e.closed)}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}ensurePath(){this.fullState.points.length!==0&&super.ensurePath()}};var vr=new Map;function Fm(r,e,t){let n=[t[0],t[1],0,t[3],t[4],0,0,0,1],i=`${n.slice(0,5).map(o=>o.toFixed(5)).join(",")}|${e.toSVGString()}`,s=vr.get(i);if(s)return vr.delete(i),vr.set(i,s),s;let a=US(r,e,n);if(!a)return null;if(vr.set(i,a),vr.size>16){let[o,c]=vr.entries().next().value;vr.delete(o),c.image.delete()}return a}function Rm(){for(let r of vr.values())r.image.delete();vr.clear()}function US(r,e,t){let[n,i,s,a]=e.getBounds(),o=[n,s,n,s].map((E,O)=>t[0]*E+t[1]*(O<2?i:a)),c=[n,s,n,s].map((E,O)=>t[3]*E+t[4]*(O<2?i:a)),l=2,u=Math.floor(Math.min(...o))-l,d=Math.floor(Math.min(...c))-l,h=Math.ceil(Math.max(...o))+l-u,f=Math.ceil(Math.max(...c))+l-d;if(!(h>l*2)||!(f>l*2))return null;let p=h*f,m=p>15e5?Math.sqrt(15e5/p):1,g=p*m*m<=4e5?2:1,y=Math.max(1,Math.ceil(h*m)),b=Math.max(1,Math.ceil(f*m)),k=y*g,T=b*g,x=m*g,v=NS(r,e,t,k,T,x,u,d);if(!v)return null;let M=g===2?Im(Pm(v,k,T),k,T):Pm(v,k,T),C=0;for(let E=0;E<M.length;E++)M[E]/=x,M[E]>C&&(C=M[E]);if(!(C>0))return null;let _=Float32Array.from(v,E=>E/255);VS(M,g===2?Im(_,k,T):_,y,b,m),WS(M,y,b,C,m);let F=qS(r,M,y,b,C);return F?{image:F,originX:u,originY:d,texel:1/m,maxDistance:C}:null}function NS(r,e,t,n,i,s,a,o){let c=r.MakeSurface(n,i);if(!c)return null;let l=c.getCanvas();l.clear(r.TRANSPARENT),l.scale(s,s),l.translate(-a,-o),l.concat(t);let u=new r.Paint;u.setAntiAlias(!0),u.setColor(r.WHITE),l.drawPath(e,u),u.delete();let d=c.makeImageSnapshot(),h=d.readPixels(0,0,{width:n,height:i,colorType:r.ColorType.RGBA_8888,alphaType:r.AlphaType.Unpremul,colorSpace:r.ColorSpace.SRGB});if(d.delete(),c.delete(),!h)return null;let f=new Uint8Array(n*i);for(let p=0;p<f.length;p++)f[p]=h[p*4+3];return f}var zS=1e20;function Pm(r,e,t){let n=Math.max(e,t),i=new Float64Array(n),s=new Float64Array(n),a=new Int32Array(n),o=new Float64Array(n+1),c=new Float64Array(e*t);for(let u=0;u<e*t;u++)c[u]=r[u]>=128?zS:0;for(let u=0;u<e;u++){for(let d=0;d<t;d++)i[d]=c[d*e+u];Em(i,t,s,a,o);for(let d=0;d<t;d++)c[d*e+u]=s[d]}let l=new Float32Array(e*t);for(let u=0;u<t;u++){for(let d=0;d<e;d++)i[d]=c[u*e+d];Em(i,e,s,a,o);for(let d=0;d<e;d++)l[u*e+d]=s[d]>0?Math.max(0,Math.sqrt(s[d])-.5):0}return l}function Em(r,e,t,n,i){let s=0;n[0]=0,i[0]=-1/0,i[1]=1/0;for(let a=1;a<e;a++){let o=(r[a]+a*a-(r[n[s]]+n[s]*n[s]))/(2*a-2*n[s]);for(;o<=i[s];)s--,o=(r[a]+a*a-(r[n[s]]+n[s]*n[s]))/(2*a-2*n[s]);s++,n[s]=a,i[s]=o,i[s+1]=1/0}s=0;for(let a=0;a<e;a++){for(;i[s+1]<a;)s++;t[a]=(a-n[s])*(a-n[s])+r[n[s]]}}function Im(r,e,t){let n=e/2,i=t/2,s=new Float32Array(n*i);for(let a=0;a<i;a++)for(let o=0;o<n;o++){let c=2*a*e+2*o;s[a*n+o]=(r[c]+r[c+1]+r[c+e]+r[c+e+1])/4}return s}var Bs=2;function VS(r,e,t,n,i){let s=iu(e,t,n,Bs),a=iu(r,t,n,Bs),o=Math.sqrt(Bs*Bs+Bs)/i,c=1.5*o,l=2.5*o;for(let u=0;u<r.length;u++){let d=r[u];if(d<=0)continue;if(d>=l){r[u]=a[u];continue}let h=s[u],f=h>.5?o*HS(Math.min(h,.9999)):0,p=d<=c?0:(d-c)/(l-c);r[u]=f+(a[u]-f)*p*p*(3-2*p)}}function HS(r){let e=Math.sqrt(-2*Math.log(1-r));return e-(2.515517+.802853*e+.010328*e*e)/(1+1.432788*e+.189269*e*e+.001308*e*e*e)}function WS(r,e,t,n,i){let s=Math.max(1,Math.round(n*.08*i)),a=iu(r,e,t,s),o=n*.15,c=n*.6;for(let l=0;l<r.length;l++){let u=r[l];if(u<=o)continue;let d=Math.min(1,(u-o)/(c-o)),h=d*d*(3-2*d);r[l]=u+(a[l]-u)*h}}function iu(r,e,t,n){let i=Float32Array.from(r),s=new Float32Array(r.length);for(let a=0;a<3;a++)Mm(i,s,e,t,n,1,e),Mm(s,i,t,e,n,e,1);return i}function Mm(r,e,t,n,i,s,a){let o=2*i+1;for(let c=0;c<n;c++){let l=c*a,u=0;for(let d=-i;d<=i;d++)u+=r[l+nu(d,t)*s];for(let d=0;d<t;d++)e[l+d*s]=u/o,u+=r[l+nu(d+i+1,t)*s]-r[l+nu(d-i,t)*s]}}var nu=(r,e)=>r<0?0:r>=e?e-1:r;function qS(r,e,t,n,i){let s=new Uint16Array(t*n*4);for(let c=0;c<t*n;c++)s[c*4+3]=KS(Math.min(1,e[c]/i));let a=r.MakeImage({width:t,height:n,colorType:r.ColorType.RGBA_F16,alphaType:r.AlphaType.Premul,colorSpace:r.ColorSpace.SRGB},new Uint8Array(s.buffer),t*8);if(a)return a;let o=new Uint8Array(t*n*4);for(let c=0;c<t*n;c++)o[c*4+3]=Math.round(Math.min(1,e[c]/i)*255);return r.MakeImage({width:t,height:n,colorType:r.ColorType.RGBA_8888,alphaType:r.AlphaType.Premul,colorSpace:r.ColorSpace.SRGB},o,t*4)}var Bm=new Float32Array(1),GS=new Uint32Array(Bm.buffer);function KS(r){Bm[0]=r;let e=GS[0],t=(e>>>23&255)-112,n=e&8388607;return t<=0?t<-10?0:((n|8388608)>>13-t)+1>>1:(t<<10)+(n+4096>>13)}import{isStrokeMarker as Si,pathOps as Nm}from"@motionscript/core";var Om=Math.hypot(1,.5),Dm=.5/Om,jS=1/Om,$S=.35;function su(r){return r==="arrow"||r==="triangle"||r==="stealth"}function Lm(r,e,t){return su(r)?Math.min(e,t/(2*.5)):0}function Um(r,e,t){let n=e/2;switch(r){case"dot":return null;case"triangle":return[0,0,-e,e*.5,-e,-e*.5];case"stealth":return[0,0,-e,e*.5,-e*(1-$S),0,-e,-e*.5];case"arrow":return XS(e,t);case"box":return[-n,-n,n,-n,n,n,-n,n];case"diamond":return[n,0,0,n,-n,0,0,-n];case"bar":return[-t/2,-n,t/2,-n,t/2,n,-t/2,n]}}function XS(r,e){let t=r*.5,n=-r-e*Dm,i=t-e*jS;if(i<=0)return[0,0,-r,t,-r,-t];let s=-e/Dm;return[0,0,-r,t,n,i,s,0,n,-i,-r,-t]}var QS=1,Ds=.001,go=class{canvasKit;getCanvas;getPaint;fills;constructor(e,t,n,i){this.canvasKit=e,this.getCanvas=t,this.getPaint=n,this.fills=i}makeUniformDashEffect(e,t,n=0,i){let s=i??this.measureDashFit(e,t);return s?this.canvasKit.PathEffect.MakeDash(s.scaledDash,n*s.scale):null}measureDashFit(e,t){let n=0,i=!1,s=new this.canvasKit.ContourMeasureIter(e,!1,1),a=s.next();for(;a;)n+=a.length(),a.isClosed()||(i=!0),a.delete(),a=s.next();s.delete();let o=Nm.dashScale(t,{length:n,closed:!0},n);return o===null?null:{scaledDash:t.map(c=>c*o),scale:o,total:n,open:i}}buildDashedPath(e,t,n,i,s){let a=s??this.measureDashFit(e,t);if(!a)return null;let o=new this.canvasKit.PathBuilder,c=new this.canvasKit.ContourMeasureIter(e,!1,1),l=c.next(),u=!1;for(;l;){let d=l.length(),h=l.isClosed()?a.scale:Nm.dashScale(t,{length:d,closed:!1},a.total)??a.scale,f=t.map(M=>M*h),p=f.reduce((M,C)=>M+C,0),m=(n*h%p+p)%p,g=l,y=(M,C)=>{if(C-M>Ds){let _=g.getSegment(M,C,!0);_&&(o.addPath(_),_.delete(),u=!0)}else if(i){let[_,F,E,O]=g.getPosTan(M),Q=M>d-Ds?-Ds:Ds;o.moveTo(_,F),o.lineTo(_+E*Q,F+O*Q),u=!0}},b=0,k=0;for(;k+f[b]<=m&&b<f.length&&!(f[b]<=Ds&&Math.abs(m-k)<1e-6||(k+=f[b],b=(b+1)%f.length,b===0)););let T=f[b]-(m-k),x=b%2===0,v=0;for(;v<d-1e-6;){let M=Math.min(T,d-v);x&&y(v,v+M),v+=M,T-=M,T<=1e-6&&(b=(b+1)%f.length,T=f[b],x=!x)}x&&T<=1e-6&&!l.isClosed()&&y(d,d),l.delete(),l=c.next()}return c.delete(),u?o.detachAndDelete():(o.delete(),null)}ckCap(e){switch(e){case"round":return this.canvasKit.StrokeCap.Round;case"square":return this.canvasKit.StrokeCap.Square;default:return this.canvasKit.StrokeCap.Butt}}ckJoin(e){switch(e){case"round":return this.canvasKit.StrokeJoin.Round;case"bevel":return this.canvasKit.StrokeJoin.Bevel;default:return this.canvasKit.StrokeJoin.Miter}}applyCapJoin(e,t,n){e.setStrokeCap(this.ckCap(n)),e.setStrokeJoin(this.ckJoin(t.join)),e.setStrokeMiter(t.miterLimit)}strokeOpts(e,t,n){return{width:t,cap:this.ckCap(n),join:this.ckJoin(e.join),miter_limit:e.miterLimit}}capPlan(e,t,n,i){let s=e.startCap??e.cap,a=e.endCap??e.cap,o=n?e.cap:Si(a)?"butt":a,c=[];if(!t||s===o&&a===o)return{cap:o,ends:c};let l=(Si(s)?1:0)+(Si(a)?1:0),u=new this.canvasKit.ContourMeasureIter(t,!1,1);for(let d=u.next();d;d=u.next()){let h=d.length();if(!d.isClosed()&&h>0){let f=Math.min(e.capScale*i,h/Math.max(1,l)),p=m=>d.getPosTan(m);s!==o&&this.pushEnd(c,p(0),p(f),-1,s,f,i),a!==o&&this.pushEnd(c,p(h),p(h-f),1,a,f,i)}d.delete()}return u.delete(),{cap:o,ends:c}}pushEnd(e,[t,n,i,s],a,o,c,l,u){let d=o*i,h=o*s;Si(c)&&su(c)&&Math.hypot(t-a[0],n-a[1])>1e-6&&(d=t-a[0],h=n-a[1]);let f=Math.hypot(d,h);f<1e-9||e.push({x:t,y:n,dx:d/f,dy:h/f,cap:c,size:l,weight:u})}strokeBand(e,t,n,i){let s=e.makeStroked(this.strokeOpts(n,t,i.cap));if(!s||i.ends.length===0)return s;let a=t/2,o=Math.min(a,1)/2,c=i.ends.map(d=>s.contains(d.x-d.dx*o,d.y-d.dy*o)),l=a*1.01+.5,u=s;return i.ends.forEach((d,h)=>{if(Si(d.cap)){u=this.addMarker(u,d,d.cap,l,i.cap!=="butt");return}if(i.cap!=="butt"&&(u=this.combine(u,this.endBox(d,l,l),this.canvasKit.PathOp.Difference)),c[h]&&d.cap!=="butt"){let f=d.cap==="round"?this.endDisc(d,a):this.endBox(d,a,a);u=this.combine(u,f,this.canvasKit.PathOp.Union)}}),u}addMarker(e,t,n,i,s){let{x:a,y:o,dx:c,dy:l,size:u,weight:d}=t,h=Lm(n,u,d),f=e;if(h>0||s){let g={...t,x:a-c*h,y:o-l*h};f=this.combine(f,this.endBox(g,h+i,i),this.canvasKit.PathOp.Difference)}let p=Um(n,u,d),m=new this.canvasKit.PathBuilder;if(p){let g=new Array(p.length);for(let y=0;y<p.length;y+=2)g[y]=a+p[y]*c-p[y+1]*l,g[y+1]=o+p[y]*l+p[y+1]*c;m.addPolygon(g,!0)}else m.addCircle(a,o,u/2);return this.combine(f,m.detachAndDelete(),this.canvasKit.PathOp.Union)}endBox({x:e,y:t,dx:n,dy:i},s,a){let o=-i*a,c=n*a,l=n*s,u=i*s,d=new this.canvasKit.PathBuilder;return d.addPolygon([e+o,t+c,e+o+l,t+c+u,e-o+l,t-c+u,e-o,t-c],!0),d.detachAndDelete()}endDisc({x:e,y:t,dx:n,dy:i},s){let a=Math.atan2(n,-i)*180/Math.PI,o=new this.canvasKit.PathBuilder;return o.addArc([e-s,t-s,e+s,t+s],a,-180),o.close(),o.detachAndDelete()}combine(e,t,n){let i=this.canvasKit.Path.MakeFromOp(e,t,n);return t.delete(),i?(e.delete(),i):e}deviceMetrics(e){let t=e.getTotalMatrix(),n=Math.hypot(t[0],t[3]),i=Math.hypot(t[1],t[4]),s=Math.sqrt(Math.abs(t[0]*t[4]-t[1]*t[3])),a=Math.abs(t[1])>1e-6||Math.abs(t[3])>1e-6;return{sx:n,sy:i,scale:s,rotated:a,tx:t[2],ty:t[5]}}resolveStrokeWidth(e,t,n){if(e<=0||t<=0)return{logical:0,intDeviceWidth:-1};if(n)return{logical:e,intDeviceWidth:-1};let i=e*t;if(i>=2.5)return{logical:e,intDeviceWidth:-1};let s=Math.max(1,Math.round(i));return{logical:s/t,intDeviceWidth:s}}snapPath(e,t,n){if(t<=0||!n)return!1;let i=e.getTotalMatrix();if(Math.abs(i[1])>1e-6||Math.abs(i[3])>1e-6)return!1;let s=i[0],a=i[4],o=i[2],c=i[5];if(s===0||a===0)return!1;let l=n.getBounds(),u=l[2]-l[0],d=l[3]-l[1];if(u<=0||d<=0)return!1;let h=o+s*l[0],f=c+a*l[1],p=o+s*l[2],m=c+a*l[3],g=t%2===0?0:.5,y=Math.round(h-g)+g,b=Math.round(f-g)+g,k=Math.round(p-g)+g,T=Math.round(m-g)+g;if(k-y<1||T-b<1)return!1;let x=(k-y)/(p-h),v=(T-b)/(m-f);if(Math.abs(x-1)<1e-4&&Math.abs(v-1)<1e-4&&Math.abs(y-h)<1e-4&&Math.abs(b-f)<1e-4)return!1;let M=(y-o)/s-x*l[0],C=(b-c)/a-v*l[1];return e.save(),e.concat([x,0,M,0,v,C,0,0,1]),!0}applyStrokes(e,t,n){if(e.length===0)return!1;let i=this.getCanvas(),s=this.getPaint(),a=this.fills.openPass(e.flatMap(c=>c.fill),s,()=>{});s.setStyle(this.canvasKit.PaintStyle.Stroke);let o=this.fills.worldAlpha();for(let c of e){let l=c.weight??1,{scale:u,rotated:d}=this.deviceMetrics(i),{logical:h,intDeviceWidth:f}=this.resolveStrokeWidth(l,u,d);s.setStrokeWidth(h);for(let p of c.fill){let m=(p.opacity??1)*o;for(let g of t){n&&n(p,g);let y=b=>this.drawStrokeBand(i,b,g,c,h,f,u,a.clipFilterToShape);a.drawShape=y,this.fills.applyFill(a,p,m)&&!a.skipDefaultDraw&&y(s),this.fills.endFill(a)}}}return this.fills.closePass(a),s.setStyle(this.canvasKit.PaintStyle.Stroke),s.setStrokeCap(this.canvasKit.StrokeCap.Butt),s.setStrokeJoin(this.canvasKit.StrokeJoin.Miter),s.setStrokeMiter(4),!0}drawStrokeBand(e,t,n,i,s,a,o,c){let l=this.snapPath(e,a,n.ckPath),u=c?this.strokeOutline(n,i,s):null;u&&(e.save(),e.clipPath(u,this.canvasKit.ClipOp.Intersect,!0)),this.drawStroke(e,t,n,i,s,a,o),u&&(e.restore(),u.delete()),l&&e.restore()}strokeOutline(e,t,n){if(e.isText)return null;let i=e.strokePath??e.ckPath;if(!i)return null;let s=t.dash&&t.dash.length>0?this.buildDashedPath(i,t.dash,t.dashOffset??0,t.cap!=="butt"):null,a=this.alignedStrokeBand(s??i,n,t.align??0,e.alignInterior??e.ckPath,t,this.capPlan(t,i,!!s,n));return s?.delete(),a}drawStroke(e,t,n,i,s,a,o){let c=n.isText?void 0:n.strokePath??n.ckPath,l=n.strokeDraw??n.draw,u=!!(i.dash&&i.dash.length>0),d=this.capPlan(i,c,u,s);if(this.applyCapJoin(t,i,d.cap),n.isText){this.drawTextUnionStroke(e,t,n,i,s,o);return}let h=u&&c?this.measureDashFit(c,i.dash):null,f=i.align??0,p=n.alignInterior??n.ckPath;if((a>0||d.ends.length>0||h?.open)&&c){let m=u?this.buildDashedPath(c,i.dash,i.dashOffset??0,i.cap!=="butt",h??void 0):c;if(m){let g=this.alignedStrokeBand(m,s,f,p,i,d);if(m!==c&&m.delete(),g){t.setStyle(this.canvasKit.PaintStyle.Fill),e.drawPath(g,t),t.setStyle(this.canvasKit.PaintStyle.Stroke),g.delete();return}}}if(f!==0&&!u&&c){let m=this.alignedStrokeBand(c,s,f,p,i,d);if(m){t.setStyle(this.canvasKit.PaintStyle.Fill),e.drawPath(m,t),t.setStyle(this.canvasKit.PaintStyle.Stroke),m.delete();return}}if(u&&c){let m=this.makeUniformDashEffect(c,i.dash,i.dashOffset??0,h??void 0);if(m){t.setPathEffect(m),f!==0&&a<=0&&p&&this.isClosedPath(p)?this.drawAlignedDashedStroke(e,t,c,p,f):e.drawPath(c,t),t.setPathEffect(null),m.delete();return}}l(t)}alignedStrokeBand(e,t,n,i,s,a){if(n===0||!i||!this.isClosedPath(i)||a.ends.some(p=>Si(p.cap)))return this.strokeBand(e,t,s,a);let o=Math.max(-1,Math.min(1,n)),c=(1+o)*t,l=(1-o)*t,u=(p,m)=>{if(p<=0)return null;let g=this.strokeBand(e,p,s,a);if(!g)return null;let y=this.canvasKit.Path.MakeFromOp(g,i,m);return g.delete(),y},d=u(c,this.canvasKit.PathOp.Difference),h=u(l,this.canvasKit.PathOp.Intersect);if(!d||!h)return d??h;let f=this.canvasKit.Path.MakeFromOp(d,h,this.canvasKit.PathOp.Union);return d.delete(),h.delete(),f}isClosedPath(e){let t=new this.canvasKit.ContourMeasureIter(e,!1,1),n=t.next();if(!n)return t.delete(),!1;let i=!0;for(;n;)n.isClosed()||(i=!1),n.delete(),n=t.next();return t.delete(),i}drawAlignedDashedStroke(e,t,n,i,s){let a=t.getStrokeWidth(),o=Math.max(-1,Math.min(1,s)),c=[[(1+o)*a,this.canvasKit.ClipOp.Difference],[(1-o)*a,this.canvasKit.ClipOp.Intersect]];for(let[l,u]of c)l<=0||(e.save(),t.setStrokeWidth(l),e.clipPath(i,u,!0),e.drawPath(n,t),e.restore());t.setStrokeWidth(a)}drawTextUnionStroke(e,t,n,i,s,a){let o=!!(i.dash&&i.dash.length>0),c=null;o&&(c=this.canvasKit.PathEffect.MakeDash(i.dash,i.dashOffset??0),t.setPathEffect(c));let l=i.align??0;l===0?(t.setStrokeWidth(s),n.draw(t)):Math.abs(l)<1?(this.drawTextPartiallyAlignedStroke(e,t,n,i,s,l),t.setStrokeWidth(s)):(e.saveLayer(),t.setStrokeWidth(s*2),n.draw(t),this.applyTextAlignMask(e,n,l,s,a),e.restore(),t.setStrokeWidth(s)),c&&(t.setPathEffect(null),c.delete())}drawTextPartiallyAlignedStroke(e,t,n,i,s,a){let o=(1+a)*s/2,c=(1-a)*s/2;e.saveLayer(),t.setStrokeWidth(2*Math.max(o,c)),n.draw(t);let l=a>0,u=new this.canvasKit.Paint;u.setBlendMode(this.canvasKit.BlendMode.DstOut),e.saveLayer(u);let d=new this.canvasKit.Paint;d.setAntiAlias(!0),d.setColor(this.canvasKit.WHITE),d.setStyle(this.canvasKit.PaintStyle.Fill),l||(e.drawPaint(d),d.setBlendMode(this.canvasKit.BlendMode.Clear)),n.draw(d),d.setBlendMode(this.canvasKit.BlendMode.Clear),d.setStyle(this.canvasKit.PaintStyle.Stroke),d.setStrokeWidth(2*(l?c:o)),d.setStrokeJoin(this.ckJoin(i.join)),d.setStrokeMiter(i.miterLimit),n.draw(d),d.delete(),e.restore(),u.delete(),e.restore()}applyTextAlignMask(e,t,n,i,s){let a=n>0,o=new this.canvasKit.Paint;o.setBlendMode(a?this.canvasKit.BlendMode.DstOut:this.canvasKit.BlendMode.DstIn),e.saveLayer(o);let c=new this.canvasKit.Paint;c.setAntiAlias(!0),c.setColor(this.canvasKit.WHITE),c.setStyle(this.canvasKit.PaintStyle.Fill);let l=s>0?Math.min(QS/s,i):0,u=l>0?a?this.canvasKit.ImageFilter.MakeErode(l,l,null):this.canvasKit.ImageFilter.MakeDilate(l,l,null):null;u&&c.setImageFilter(u),t.draw(c),u&&(c.setImageFilter(null),u.delete()),c.delete(),e.restore(),o.delete()}applyShadows(e,t,n,i,s){if(e.length===0)return;let a=this.getPaint(),o=n.length>0&&n.some(d=>(d.opacity??1)>0),c=i.length>0,l=this.fills.worldAlpha(),u=this.fills.openShadowPass(e.flatMap(d=>d.fill),a);for(let d of e)d.inner||this.applyDropShadow(d,t,o,c,i,l,u,s);this.fills.closePass(u),a.setStyle(this.canvasKit.PaintStyle.Fill),a.setPathEffect(null),a.setStrokeCap(this.canvasKit.StrokeCap.Butt),a.setStrokeJoin(this.canvasKit.StrokeJoin.Miter),a.setStrokeMiter(4)}applyInnerShadows(e,t,n,i){if(e.length===0)return;let s=this.getPaint(),a=n.length>0&&n.some(l=>(l.opacity??1)>0),o=this.fills.worldAlpha(),c=this.fills.openShadowPass(e.flatMap(l=>l.fill),s);for(let l of e)l.inner&&this.applyInnerShadow(l,t,a,o,c,i);this.fills.closePass(c),s.setStyle(this.canvasKit.PaintStyle.Fill),s.setPathEffect(null)}applyDropShadow(e,t,n,i,s,a,o,c){let l=this.getCanvas(),u=o.paint,d=e.offset?.x??0,h=e.offset?.y??0,f=e.spread!==0&&n?t.map(m=>m.spreadPath?.(e.spread)??null):null,p=m=>{if(n){m.setStyle(this.canvasKit.PaintStyle.Fill),m.setPathEffect(null);for(let g=0;g<t.length;g++){let y=f?.[g];y?l.drawPath(y,m):t[g].draw(m)}}if(i){m.setStyle(this.canvasKit.PaintStyle.Stroke);for(let g of s){let y=g.weight??1,{scale:b,rotated:k}=this.deviceMetrics(l),{logical:T,intDeviceWidth:x}=this.resolveStrokeWidth(y,b,k);m.setStrokeWidth(T),m.setPathEffect(null);for(let v of t){let M=this.snapPath(l,x,v.ckPath);this.drawStroke(l,m,v,g,T,x,b),M&&l.restore()}}}};o.drawShape=p;for(let m of e.fill){let g=(m.opacity??1)*a,y=new this.canvasKit.Paint;if(y.setAlphaf(g),e.blur>0){let b=e.blur/2,k=this.canvasKit.ImageFilter.MakeBlur(b,b,this.canvasKit.TileMode.Decal,null);y.setImageFilter(k)}l.save(),l.translate(d,-h),l.saveLayer(y),c&&c(m,null),this.fills.applyFill(o,m,1,!1)&&!o.skipDefaultDraw&&p(u),this.fills.endFill(o),l.restore(),l.restore(),y.delete()}if(f)for(let m of f)m?.delete()}applyInnerShadow(e,t,n,i,s,a){if(!n)return;let o=this.getCanvas(),c=s.paint,l=e.offset?.x??0,u=-(e.offset?.y??0);for(let d of t){if(!d.ckPath)continue;let h=e.spread!==0&&!!d.spreadPath,f=h?d.spreadPath(-e.spread):null,p=f??(h?null:d.ckPath),m=this.buildInnerShadowRegion(p,d.ckPath,l,u,e.blur);if(!m){f?.delete();continue}let g=y=>{y.setStyle(this.canvasKit.PaintStyle.Fill),y.setPathEffect(null),o.drawPath(m,y)};s.drawShape=g;for(let y of e.fill){let b=(y.opacity??1)*i,k=new this.canvasKit.Paint;if(k.setAlphaf(b),e.blur>0){let T=e.blur/2,x=this.canvasKit.ImageFilter.MakeBlur(T,T,this.canvasKit.TileMode.Decal,null);k.setImageFilter(x)}o.save(),o.clipPath(d.ckPath,this.canvasKit.ClipOp.Intersect,!0),o.saveLayer(k),a&&a(y,null),this.fills.applyFill(s,y,1,!1)&&!s.skipDefaultDraw&&g(c),this.fills.endFill(s),o.restore(),o.restore(),k.delete()}m.delete(),f?.delete()}}buildInnerShadowRegion(e,t,n,i,s){let a=t.getBounds(),o=s*2+Math.abs(n)+Math.abs(i)+1,c=new this.canvasKit.PathBuilder;c.addRect([a[0]-o,a[1]-o,a[2]+o,a[3]+o]);let l=c.detachAndDelete();if(!e)return l;let u=new this.canvasKit.PathBuilder(e);u.offset(n,i);let d=u.detachAndDelete(),h=this.canvasKit.Path.MakeFromOp(l,d,this.canvasKit.PathOp.Difference);return l.delete(),d.delete(),h}};var yo=class{canvasKit;getCanvas;pathCollectionStack=[];booleanOpStack=[];constructor(e,t){this.canvasKit=e,this.getCanvas=t}dispose(){this.pathCollectionStack=[],this.booleanOpStack=[]}resetPass(){for(let e of this.pathCollectionStack)for(let t of e.paths)t.delete();this.pathCollectionStack=[],this.booleanOpStack=[]}isCollecting(){return this.pathCollectionStack.length>0}contributeToPathCollection(e){if(this.pathCollectionStack.length===0)return;let t=this.pathCollectionStack[this.pathCollectionStack.length-1],n=this.getCanvas().getTotalMatrix(),i=this.canvasKit.Matrix.multiply(t.invBaseMatrix,n),s=new this.canvasKit.PathBuilder;s.addPath(e,i),t.paths.push(s.detachAndDelete())}pushFrame(){let e=Array.from(this.getCanvas().getTotalMatrix()),t=this.canvasKit.Matrix.invert(e)??this.canvasKit.Matrix.identity();this.pathCollectionStack.push({paths:[],invBaseMatrix:t})}popFrame(){let e=this.pathCollectionStack.pop();return e?e.paths:[]}toCanvasKitPathOp(e){switch(e){case"subtract":return this.canvasKit.PathOp.Difference;case"intersect":return this.canvasKit.PathOp.Intersect;case"exclude":return this.canvasKit.PathOp.XOR;default:return this.canvasKit.PathOp.Union}}combinePaths(e,t){if(e.length===0)return null;let n=this.toCanvasKitPathOp(t),i=e[0];for(let s=1;s<e.length;s++){let a=this.canvasKit.Path.MakeFromOp(i,e[s],n);if(i.delete(),e[s].delete(),!a){for(let o=s+1;o<e.length;o++)e[o].delete();return null}i=a}return i}beginBoolean(e){this.pushFrame(),this.booleanOpStack.push(e)}endBoolean(e){let t=this.booleanOpStack.pop()??"union",n=this.popFrame(),i=this.combinePaths(n,t);if(!i)return null;this.contributeToPathCollection(i);let s=e();return{draw:o=>{s.drawPath(i,o)},ckPath:i}}};var wo=class{canvasKit;getCanvas;boolean;maskStack=[];constructor(e,t,n){this.canvasKit=e,this.getCanvas=t,this.boolean=n}dispose(){this.maskStack=[]}resetPass(){this.maskStack=[]}beginMask(e){let t=this.getCanvas(),n=e?.mode??"alpha",i=e?.inverted??!1,s=e?.apply,a=s!=null?new Set(Array.isArray(s)?s:[s]):null;if(n==="vector"){t.save(),this.boolean.pushFrame(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:1});return}if(n==="luminance"){t.saveLayer();let o=new this.canvasKit.Paint,c=this.canvasKit.ColorFilter.MakeMatrix([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,.2126,.7152,.0722,0,0]);o.setColorFilter(c),t.saveLayer(o),o.delete(),c.delete(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:2});return}t.saveLayer(),this.maskStack.push({mode:n,inverted:i,apply:a,restores:2})}getApply(){return this.maskStack[this.maskStack.length-1]?.apply??null}applyMask(e){let t=this.getCanvas(),n=this.maskStack[this.maskStack.length-1];if(!n){console.warn("applyMask() called outside of a mask scope.");return}if(n.mode==="vector"){let s=this.boolean.popFrame(),a=this.boolean.combinePaths(s,"union");if(e(),a){let o=n.inverted?this.canvasKit.ClipOp.Difference:this.canvasKit.ClipOp.Intersect;t.clipPath(a,o,!0),a.delete()}return}n.mode==="luminance"&&t.restore();let i=new this.canvasKit.Paint;i.setBlendMode(n.inverted?this.canvasKit.BlendMode.SrcOut:this.canvasKit.BlendMode.SrcIn),t.saveLayer(i),i.delete(),e()}endMask(){let e=this.maskStack.pop();if(!e)return;let t=this.getCanvas();for(let n=0;n<e.restores;n++)t.restore()}};function bo(r,e){if(r===e)return!0;if(typeof r!="object"||typeof e!="object"||r===null||e===null)return!1;if("x"in r&&"y"in r&&"x"in e&&"y"in e){let n=r,i=e;return n.x===i.x&&n.y===i.y}if(Array.isArray(r)&&Array.isArray(e)){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!bo(r[n],e[n]))return!1;return!0}let t=["topLeft","topRight","bottomRight","bottomLeft"];if(t.every(n=>n in r)&&t.every(n=>n in e)){for(let n of t)if(!bo(r[n],e[n]))return!1;return!0}return!1}function YS(r){return{left:r[0],top:r[1],right:r[2],bottom:r[3]}}function ZS(r,e){let t=Object.keys(r);if(t.length!==Object.keys(e).length)return!1;for(let n of t)if(!bo(r[n],e[n]))return!1;return!0}function JS(r,e,...t){let n=new Set(t),i=Object.keys(r).filter(a=>!n.has(a)),s=Object.keys(e).filter(a=>!n.has(a));if(i.length!==s.length)return!1;for(let a of i)if(!bo(r[a],e[a]))return!1;return!0}var ko=class{canvasKit;getCanvas;getPaint;fontMgr;paragraphCache;getFontEpoch;shapes=[];paintApplied=!1;pendingShadows=null;boolean;mask;boundsOverride=[];shapeCache=new Map;currentNodeId="";shapeIndex=0;_cachedBounds=null;_boundsDirty=!0;transientPaths=new Set;_measuring=!1;_measureShapes=[];_savedNodeId="";_savedShapeIndex=0;constructor(e,t,n,i,s,a){this.canvasKit=e,this.getCanvas=t,this.getPaint=n,this.fontMgr=i,this.paragraphCache=s,this.getFontEpoch=a,this.boolean=new yo(e,t),this.mask=new wo(e,t,this.boolean)}beginNode(e){this.currentNodeId=e,this.shapeIndex=0}reset(){for(let e of this.transientPaths)e.delete();this.transientPaths.clear(),this.shapes=[],this.paintApplied=!1,this.pendingShadows=null,this._boundsDirty=!0,this._cachedBounds=null}storePendingShadows(e){this.pendingShadows=e.length>0?e:null}takePendingShadows(){let e=this.pendingShadows;return this.pendingShadows=null,e}dispose(){this.shapes=[];for(let e of this.transientPaths)e.delete();this.transientPaths.clear();for(let e of this.shapeCache.values())e.shape.deletePaths();this.shapeCache.clear(),this.boolean.dispose(),this.mask.dispose()}resetPass(){this._measuring&&this.endMeasure(),this.reset(),this.boundsOverride.length=0,this.boolean.resetPass(),this.mask.resetPass(),this.currentNodeId="",this.shapeIndex=0}isCollectingPaths(){return this.boolean.isCollecting()}pushBounds(e){this.boundsOverride.push(e)}popBounds(){this.boundsOverride.pop()}getShapeBounds(){if(this.boundsOverride.length>0)return this.boundsOverride[this.boundsOverride.length-1];if(!this._boundsDirty&&this._cachedBounds!==null)return this._cachedBounds;let e=1/0,t=1/0,n=-1/0,i=-1/0;for(let s of this.shapes){let a=s.paintBounds??(s.ckPath?YS(s.ckPath.getBounds()):s.bounds);a&&(a.left<e&&(e=a.left),a.top<t&&(t=a.top),a.right>n&&(n=a.right),a.bottom>i&&(i=a.bottom))}return this._boundsDirty=!1,this._cachedBounds=isFinite(e)?{left:e,top:t,right:n,bottom:i}:null,this._cachedBounds}addShape(e){this._boundsDirty=!0;let t=!this.boolean.isCollecting(),n=e;if(this.currentNodeId){let i=`${this.currentNodeId}:${this.shapeIndex++}`,s=this.shapeCache.get(i);if(s){let a=s.shape,o=e.inputState,c=a.inputState;if(ZS(o,c))n=a;else if(a.hasTrim()&&e.hasTrim()&&JS(o,c,"start","end")){let{start:l,end:u}=e.trimRange();(s.trimStart!==l||s.trimEnd!==u)&&(a.retrim(l,u),s.trimStart=l,s.trimEnd=u),a.inputState=e.inputState,n=a}else{a.deletePaths();let l=e.hasTrim()?e.trimRange():{start:0,end:1};this.shapeCache.set(i,{shape:e,trimStart:l.start,trimEnd:l.end}),n=e}}else{let a=e.hasTrim()?e.trimRange():{start:0,end:1};this.shapeCache.set(i,{shape:e,trimStart:a.start,trimEnd:a.end})}}n.ensurePath(),this._measuring&&this._measureShapes.push(n),!t&&n.ckPath&&this.boolean.contributeToPathCollection(n.ckPath),this.shapes.push(n.toCurrentShape(t))}rect(e){this.addShape(new pi(this.canvasKit,this.getCanvas,e))}ellipse(e){this.addShape(new gi(this.canvasKit,this.getCanvas,e))}path(e){this.addShape(new bi(this.canvasKit,this.getCanvas,e))}line(e){this.addShape(new ki(this.canvasKit,this.getCanvas,e))}polygon(e){this.addShape(new yi(this.canvasKit,this.getCanvas,e))}polygram(e){this.addShape(new wi(this.canvasKit,this.getCanvas,e))}text(e){this._boundsDirty=!0;let t=Tm(this.canvasKit,this.getCanvas(),this.fontMgr,e,this.paragraphCache,this.getFontEpoch());this.shapes.push(t)}cut(){let e=this.shapes.filter(a=>a.ckPath);if(e.length===0)return;let t=e[e.length-1].ckPath.copy(),n=e.slice(0,-1),i;if(n.length===0)t.delete(),i=e[0].ckPath.copy();else{let a=this.boolean.combinePaths(n.map(o=>o.ckPath.copy()),"union");a?i=this.boolean.combinePaths([a,t],"subtract"):(t.delete(),i=null)}for(let a of this.shapes)a.ckPath&&this.transientPaths.has(a.ckPath)&&(a.ckPath.delete(),this.transientPaths.delete(a.ckPath));if(this.shapes=[],this.paintApplied=!1,!i)return;this.transientPaths.add(i);let s=this.getCanvas();this.shapes.push({draw:a=>{s.drawPath(i,a)},ckPath:i})}beginMeasure(){this._savedNodeId=this.currentNodeId,this._savedShapeIndex=this.shapeIndex,this.currentNodeId="",this._measuring=!0,this._measureShapes=[],this.shapes=[]}endMeasure(){for(let e of this._measureShapes)e.deletePaths();this._measureShapes=[],this._measuring=!1,this.currentNodeId=this._savedNodeId,this.shapeIndex=this._savedShapeIndex,this.shapes=[],this._boundsDirty=!0,this._cachedBounds=null}beginNested(){let e={nodeId:this.currentNodeId,shapeIndex:this.shapeIndex,shapes:this.shapes,paintApplied:this.paintApplied,pendingShadows:this.pendingShadows,transientPaths:this.transientPaths};return this.shapes=[],this.paintApplied=!1,this.pendingShadows=null,this.transientPaths=new Set,this._boundsDirty=!0,this._cachedBounds=null,e}endNested(e){for(let t of this.transientPaths)t.delete();this.currentNodeId=e.nodeId,this.shapeIndex=e.shapeIndex,this.shapes=e.shapes,this.paintApplied=e.paintApplied,this.pendingShadows=e.pendingShadows,this.transientPaths=e.transientPaths,this._boundsDirty=!0,this._cachedBounds=null}measureUnionBounds(){let e=1/0,t=1/0,n=-1/0,i=-1/0;for(let s of this.shapes)if(s.ckPath&&!s.ckPath.isEmpty()){let a=s.ckPath.getBounds();a[0]<e&&(e=a[0]),a[1]<t&&(t=a[1]),a[2]>n&&(n=a[2]),a[3]>i&&(i=a[3])}else s.bounds&&(s.bounds.left<e&&(e=s.bounds.left),s.bounds.top<t&&(t=s.bounds.top),s.bounds.right>n&&(n=s.bounds.right),s.bounds.bottom>i&&(i=s.bounds.bottom));return isFinite(e)?{left:e,top:t,right:n,bottom:i}:null}unionStrokeShape(){if(this.shapes.some(a=>a.isText))return null;let e=this.shapes.filter(a=>a.ckPath);if(e.length<2)return null;let t=this.boolean.combinePaths(e.map(a=>a.ckPath.copy()),"union");if(!t)return null;let n=e.some(a=>a.strokePath&&a.strokePath!==a.ckPath||a.trimmed||this.hasOpenContour(a.ckPath)),i;if(n){let a=new this.canvasKit.PathBuilder;for(let o of e)a.addPath(o.strokePath??o.ckPath);i=a.detachAndDelete()}let s=this.getCanvas();return{draw:a=>{s.drawPath(t,a)},strokeDraw:a=>{s.drawPath(i??t,a)},ckPath:t,strokePath:i}}hasOpenContour(e){let t=new this.canvasKit.ContourMeasureIter(e,!1,1),n=!1;for(let i=t.next();i&&(i.isClosed()||(n=!0),i.delete(),!n);i=t.next());return t.delete(),n}beginBoolean(e){this.boolean.beginBoolean(e)}endBoolean(){let e=this.boolean.endBoolean(this.getCanvas);this.shapes=[],this.paintApplied=!1,e&&this.shapes.push(e)}beginMask(e){this.mask.beginMask(e)}applyMask(){this.mask.applyMask(()=>{this.shapes=[],this.paintApplied=!1})}endMask(){this.mask.endMask()}getMaskApply(){return this.mask.getApply()}};import{AssetNotLoadedError as ex,resolveVideoTimestamp as tx}from"@motionscript/core";var So=class r extends qe{static MAX_ECHOES=32;applyPaint(e,t){if(!e.src)return Za(t);let n=t.assets.getVideoDuration(e.src);if(n===0)throw new ex("video",e.src);let i=tx(e,t.elapsed,n),s=t.assets.getVideoSize(e.src),a=t.getShapeBounds(),o=s?jl(e,s,a,t):void 0,c=t.assets.claimVideoFrame(e.src,i,o);if(!c)return!1;let l=e.preset?.adjustments.find(d=>d.type==="echo");if(l&&l.echoes>0&&l.delay>0)return this.drawEchoStack(e,t,l,c,i,s,o),t.skipDefaultDraw=!0,!0;let u=Es(c,e,t.canvasKit,a,oo(e),{logical:s});return t.transientPaintObjects.push(u),t.paint.setShader(co(e,t,u)),!0}drawEchoStack(e,t,n,i,s,a,o){let{paint:c,canvasKit:l}=t,u=n.decay??.5,d=jt(l,n.blend??"screen"),h=Math.min(Math.max(0,Math.floor(n.echoes)),r.MAX_ECHOES),f=Ya(e,t)*t.worldAlpha,p=t.getShapeBounds();for(let g=h;g>=1;g--){let y=s-g*n.delay;if(y<0)continue;let b=t.assets.getVideoFrameImage(e.src,y,o);if(!b)continue;t.transientImages.push(b);let k=Es(b,e,l,p,"linear",{logical:a});t.transientPaintObjects.push(k),c.setShader(k),c.setImageFilter(null),c.setAlphaf(f*Math.pow(u,g)),c.setBlendMode(d),t.drawShape(c)}let m=Es(i,e,l,p,oo(e),{logical:a});t.transientPaintObjects.push(m),c.setShader(co(e,t,m)),c.setAlphaf(f),c.setBlendMode(d),t.drawShape(c),c.setShader(null),c.setImageFilter(null),c.setAlphaf(f),c.setBlendMode(e.blend?jt(l,e.blend):l.BlendMode.SrcOver)}};var rn=class{limit;map=new Map;constructor(e=256){this.limit=e}get(e,t){let n=this.map.get(e);if(n)return this.map.delete(e),this.map.set(e,n),n;let i=t();if(this.map.set(e,i),this.map.size>this.limit){let s=this.map.keys().next().value;s!==void 0&&(this.map.get(s)?.delete(),this.map.delete(s))}return i}dispose(){for(let e of this.map.values())e.delete();this.map.clear()}};function xi(r,e){return e.map(t=>r.Color4f(t[0],t[1],t[2],t[3]))}function At(r,e){for(let t=0;t<e.length;t++)r.push(e[t].toFixed(4))}function zm(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var xo=class extends qe{cache=new rn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let s=zm(e.start.x,e.start.y,i),a=zm(e.end.x,e.end.y,i),o=["L"];At(o,s),At(o,a);for(let u of e.colors)At(o,u);o.push("|"),At(o,e.stops);let c=o.join(","),l=this.cache.get(c,()=>{let u=xi(n,e.colors),d=e.stops.length===u.length?e.stops:u.map((h,f)=>f/(u.length-1));return n.Shader.MakeLinearGradient(s,a,u,d,n.TileMode.Clamp)});return t.paint.setShader(l),!0}dispose(){this.cache.dispose()}};function rx(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var To=class extends qe{cache=new rn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let s=rx(e.center.x,e.center.y,i),a=["R"];At(a,s),At(a,[e.radius]);for(let l of e.colors)At(a,l);a.push("|"),At(a,e.stops);let o=a.join(","),c=this.cache.get(o,()=>{let l=xi(n,e.colors),u=e.stops.length===l.length?e.stops:l.map((d,h)=>h/(l.length-1));return n.Shader.MakeRadialGradient(s,e.radius,l,u,n.TileMode.Clamp)});return t.paint.setShader(c),!0}dispose(){this.cache.dispose()}};function nx(r,e,t){let n=(t.left+t.right)/2,i=(t.top+t.bottom)/2,s=(t.right-t.left)/2,a=(t.bottom-t.top)/2;return[n+r*s,i-e*a]}var Ao=class extends qe{cache=new rn;applyPaint(e,t){let n=t.canvasKit,i=t.getShapeBounds();if(!i)return!1;let[s,a]=nx(e.center.x,e.center.y,i),o=e.startAngle??0,c=["C"];At(c,[s,a,o]);for(let d of e.colors)At(c,d);c.push("|"),At(c,e.stops);let l=c.join(","),u=this.cache.get(l,()=>{let d=xi(n,e.colors),h=e.stops.length===d.length?e.stops:d.map((f,p)=>p/(d.length-1));return n.Shader.MakeSweepGradient(s,a,d,h,n.TileMode.Clamp,null,0,o,o+360)});return t.paint.setShader(u),!0}dispose(){this.cache.dispose()}};var ix=24,Ti=new Map;function sx(r,e){for(Ti.set(r,e);Ti.size>ix;){let t=Ti.keys().next();if(t.done)break;Ti.get(t.value)?.delete?.(),Ti.delete(t.value)}}function ax(r,e,t){let[n,i,s,a]=r.color;return`${e}x${t}|${r.size.x},${r.size.y}|${r.density}|${r.seed}|${n},${i},${s},${a}`}function Vm(r,e,t){let n=(r*1664525+1013904223^e*1664525*1664525+1013904223)+t>>>0;return n^=n>>>17,n=Math.imul(n,2654435769)>>>0,n^=n>>>13,n=Math.imul(n,1818371886)>>>0,n^=n>>>16,(n>>>0)/4294967296}function ox(r,e,t){let[n,i,s,a]=t.color,o=Math.round(n*255),c=Math.round(i*255),l=Math.round(s*255),u=Math.round(a*255),d=Math.max(1,Math.round(t.size.x)),h=Math.max(1,Math.round(t.size.y)),f=Math.min(1,Math.max(0,t.density)),p=Math.round(t.seed),m=new Uint8Array(r*e*4);for(let g=0;g<e;g++){let y=Math.floor(g/h);for(let b=0;b<r;b++){let k=Math.floor(b/d),T=Vm(k,y,p),x=(g*r+b)*4;if(T<f){let v=Vm(k,y,p+1);m[x]=Math.round(o*v),m[x+1]=Math.round(c*v),m[x+2]=Math.round(l*v),m[x+3]=u}}}return m}var vo=class extends qe{applyPaint(e,t){let n=t.getShapeBounds(),i=n?Math.ceil(n.right-n.left):256,s=n?Math.ceil(n.bottom-n.top):256;if(i<=0||s<=0)return!1;let a=ax(e,i,s),o=Ti.get(a);if(!o){let h=ox(i,s,e);if(o=t.canvasKit.MakeImage({width:i,height:s,alphaType:t.canvasKit.AlphaType.Unpremul,colorType:t.canvasKit.ColorType.RGBA_8888,colorSpace:t.canvasKit.ColorSpace.SRGB},h,4*i),!o)return!1;sx(a,o)}let c=n?.left??0,l=n?.top??0,u=[1,0,c,0,1,l,0,0,1],d=o.makeShaderOptions(t.canvasKit.TileMode.Repeat,t.canvasKit.TileMode.Repeat,t.canvasKit.FilterMode.Nearest,t.canvasKit.MipmapMode.None,u);return t.paint.setShader(d),t.transientPaintObjects.push(d),!0}};var cx=8,lx=`
1671
- vec2 hash2(vec2 p) {
1672
- vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
1673
- p3 += dot(p3, p3.yzx + 33.33);
1674
- return fract((p3.xx + p3.yz) * p3.zy);
1675
- }
1676
-
1677
- float hash1(vec2 p) {
1678
- return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
1679
- }
1680
-
1681
- float valueNoise(vec2 p) {
1682
- vec2 i = floor(p);
1683
- vec2 f = fract(p);
1684
- // Quintic smoothstep: its first *and* second derivatives vanish at the cell
1685
- // edges, so summed octaves show no grid creases the way cubic ones do.
1686
- vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
1687
- float a = hash1(i);
1688
- float b = hash1(i + vec2(1.0, 0.0));
1689
- float c = hash1(i + vec2(0.0, 1.0));
1690
- float d = hash1(i + vec2(1.0, 1.0));
1691
- return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
1692
- }
1693
-
1694
- float simplexNoise(vec2 p) {
1695
- const float K1 = 0.366025404; // (sqrt(3) - 1) / 2
1696
- const float K2 = 0.211324865; // (3 - sqrt(3)) / 6
1697
-
1698
- vec2 i = floor(p + (p.x + p.y) * K1);
1699
- vec2 a = p - (i - (i.x + i.y) * K2);
1700
- float m = step(a.y, a.x);
1701
- vec2 o = vec2(m, 1.0 - m);
1702
- vec2 b = a - o + K2;
1703
- vec2 c = a - 1.0 + 2.0 * K2;
1704
-
1705
- vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);
1706
- vec3 g = vec3(
1707
- dot(a, hash2(i) * 2.0 - 1.0),
1708
- dot(b, hash2(i + o) * 2.0 - 1.0),
1709
- dot(c, hash2(i + 1.0) * 2.0 - 1.0)
1710
- );
1711
- return dot(h * h * h * h * g, vec3(70.0)) * 0.5 + 0.5;
1712
- }
1713
-
1714
- float worleyNoise(vec2 p) {
1715
- vec2 i = floor(p);
1716
- vec2 f = fract(p);
1717
- float best = 1.0;
1718
- for (int y = -1; y <= 1; y++) {
1719
- for (int x = -1; x <= 1; x++) {
1720
- vec2 cell = vec2(float(x), float(y));
1721
- vec2 point = hash2(i + cell);
1722
- best = min(best, length(cell + point - f));
1723
- }
1724
- }
1725
- return best;
1726
- }
1727
- `;function ux(r,e,t){let i=r==="ridged"?`
1728
- float prev = 1.0;
1729
- for (int o = 0; o < ${e}; o++) {
1730
- float r = 1.0 - abs(simplexNoise(q) * 2.0 - 1.0);
1731
- r = r * r * prev;
1732
- prev = clamp(r, 0.0, 1.0);
1733
- sum += r * amplitude;
1734
- total += amplitude;
1735
- amplitude *= u_gain;
1736
- q *= u_lacunarity;
1737
- }`:`
1738
- for (int o = 0; o < ${e}; o++) {
1739
- sum += ${r==="value"?"valueNoise(q)":r==="worley"?"worleyNoise(q)":"simplexNoise(q)"} * amplitude;
1740
- total += amplitude;
1741
- amplitude *= u_gain;
1742
- q *= u_lacunarity;
1743
- }`;return`${lx}
1744
- uniform vec2 u_origin; // shape bounds origin, shape-local logical px
1745
- uniform vec2 u_size; // shape bounds size, shape-local logical px
1746
- uniform vec2 u_frequency; // cycles of the first octave across the shape
1747
- uniform vec2 u_offset; // pan through the field, in cycles
1748
- uniform float u_lacunarity;
1749
- uniform float u_gain;
1750
- uniform float u_seed;
1751
- uniform float u_cos; // field rotation, precomputed
1752
- uniform float u_sin;
1753
- uniform float u_contrast;
1754
- uniform vec4 u_colors[${t}];
1755
- uniform float u_stops[${t}];
1756
-
1757
- vec4 main(vec2 fragCoord) {
1758
- // Normalised to the shape's own box, so the field is pinned to the figure
1759
- // and u_frequency means "cycles across this shape" at any size.
1760
- vec2 uv = (fragCoord - u_origin) / max(u_size, vec2(1.0));
1761
-
1762
- vec2 r = vec2(uv.x * u_cos - uv.y * u_sin, uv.x * u_sin + uv.y * u_cos);
1763
- vec2 base = r * u_frequency + u_offset + u_seed;
1764
-
1765
- float sum = 0.0;
1766
- float amplitude = 1.0;
1767
- float total = 0.0;
1768
- vec2 q = base;
1769
- ${i}
1770
- // Normalising by the summed amplitudes keeps the field in 0\u20131 whatever the
1771
- // gain, so changing octaves or gain re-textures without also re-exposing.
1772
- float n = clamp(sum / max(total, 0.0001), 0.0, 1.0);
1773
-
1774
- // Contrast about the midpoint, so steepening does not also brighten.
1775
- n = clamp((n - 0.5) * u_contrast + 0.5, 0.0, 1.0);
1776
-
1777
- vec4 color = u_colors[0];
1778
- for (int i = 1; i < ${t}; i++) {
1779
- float t = clamp((n - u_stops[i - 1]) / max(u_stops[i] - u_stops[i - 1], 0.0001), 0.0, 1.0);
1780
- color = mix(color, u_colors[i], step(u_stops[i - 1], n) * t);
1781
- }
1782
-
1783
- // Premultiply: the paint's shader output is composited as premultiplied.
1784
- // Deliberately *not* multiplied by the fill's opacity or the world alpha \u2014
1785
- // FillHandler has already put both on the paint via setAlphaf, and Skia
1786
- // modulates a shader's output by the paint alpha, so folding them in here
1787
- // would square them.
1788
- return vec4(color.rgb * color.a, color.a);
1789
- }
1790
- `}var _o=class extends qe{live=null;replaceLive(e){this.live?.delete(),this.live=e}applyPaint(e,t){let n=t.getShapeBounds();if(!n)return!1;let i=n.right-n.left,s=n.bottom-n.top;if(i<=0||s<=0)return!1;let a=Math.max(2,Math.min(cx,e.colors.length)),o=ue(ux(e.basis,e.octaves,a),t.canvasKit);if(!o)return!1;let c=e.angle*Math.PI/180,l=[],u=[];for(let h=0;h<a;h++){let f=e.colors[Math.min(h,e.colors.length-1)];l.push(f[0],f[1],f[2],f[3]),u.push(e.stops[Math.min(h,e.stops.length-1)]??h/(a-1))}let d=o.makeShader([n.left,n.top,i,s,e.frequency.x,e.frequency.y,e.offset.x,e.offset.y,e.lacunarity,e.gain,e.seed,Math.cos(c),Math.sin(c),e.contrast,...l,...u]);return d?(this.replaceLive(d),t.paint.setShader(d),!0):!1}dispose(){this.replaceLive(null)}};import{coordsMatrix as dx,writeUniforms as hx}from"@motionscript/core";var Co=new Map;function fx(r,e,t){let n=t.canvasKit,i=Co.get(r);if(i&&i.image===e)return i.shader;i?.shader.delete();let s=t.assets.getImageSize(r),a=s?so(Hm,s.width,s.height,e.width(),e.height()):Hm,o=e.makeShaderOptions(n.TileMode.Repeat,n.TileMode.Repeat,n.FilterMode.Linear,n.MipmapMode.None,a);return Co.set(r,{image:e,shader:o}),o}var Hm=[1,0,0,0,1,0,0,0,1],Po=class extends qe{applyPaint(e,t){if(!e.source)return!1;let n=t.getShapeBounds();if(!n)return!1;let i=n.right-n.left,s=n.bottom-n.top;if(i<=0||s<=0)return!1;let a=ue(e.source,t.canvasKit);if(!a)return!1;let o=Ps(a,e.source),c={u_size:[i,s],u_resolution:[i,s],u_origin:[n.left,n.top],u_aspect:i/s,u_time:t.elapsed,get u_scale(){return t.getDeviceScale()}},l=hx(o.slots,o.floats,e.uniforms,c,e.source),u=dx(e.coords,n),d;if(o.children.length>0){let h=this.bindChildren(o.children,e,t);if(!h)return!1;d=a.makeShaderWithChildren(l,h,u)}else e.textures?.length&&Zr("a shader fill supplies textures but its source declares no `uniform shader`."),d=a.makeShader(l,u);return d?(t.transientPaintObjects.push(d),t.paint.setShader(d),!0):!1}bindChildren(e,t,n){let i=[];for(let s of e){if(s.kind!=="shader")return Zr(`a shader fill declares \`uniform ${s.kind} ${s.name}\`, which it cannot bind. Only \`uniform shader\` is supported.`),null;let a=t.textures?.find(c=>c.name===s.name);if(!a)return Zr(`a shader fill declares \`uniform shader ${s.name}\` but no texture of that name was supplied.`),null;let o=n.assets.getCKImage(a.src);if(!o)return null;i.push(fx(a.src,o,n))}return i}dispose(){for(let{shader:e}of Co.values())e.delete();Co.clear()}};var Eo=new Map;function mx(r){let e=r.gap??8,t=r.strokeWidth??1,[n,i,s,a]=r.color??[0,0,0,1];return`${e}|${t}|${n},${i},${s},${a}`}function px(r,e){let t=Math.max(1,Math.round(r.gap??8)),n=r.strokeWidth??1,[i,s,a,o]=r.color??[0,0,0,1],c=e.MakeSurface(t,t);if(!c)return null;let l=new e.Paint;try{let u=c.getCanvas();u.clear(e.TRANSPARENT),l.setAntiAlias(!0),l.setStyle(e.PaintStyle.Stroke),l.setStrokeWidth(n),l.setColor(e.Color(Math.round(i*255),Math.round(s*255),Math.round(a*255),o));let d=n/2;u.drawLine(d,0,d,t,l),c.flush();let h=c.makeImageSnapshot(),f=h?.readPixels(0,0,{width:t,height:t,alphaType:e.AlphaType.Unpremul,colorType:e.ColorType.RGBA_8888,colorSpace:e.ColorSpace.SRGB});return h?.delete(),f?e.MakeImage({width:t,height:t,alphaType:e.AlphaType.Unpremul,colorType:e.ColorType.RGBA_8888,colorSpace:e.ColorSpace.SRGB},new Uint8Array(f),4*t):null}finally{l.delete(),c.delete()}}function gx(r,e,t){let n=r*Math.PI/180,i=Math.cos(n),s=Math.sin(n);return[i,-s,e-i*e+s*t,s,i,t-s*e-i*t,0,0,1]}var Io=class extends qe{applyPaint(e,t){let n=mx(e),i=Eo.get(n);if(!i){let d=px(e,t.canvasKit);if(!d)return!1;i=d,Eo.set(n,i)}let s=t.getShapeBounds(),a=s?.left??0,o=s?.top??0,c=e.angle??-45,l=gx(c,a,o),u=i.makeShaderOptions(t.canvasKit.TileMode.Repeat,t.canvasKit.TileMode.Repeat,t.canvasKit.FilterMode.Linear,t.canvasKit.MipmapMode.None,l);return t.paint.setShader(u),t.transientPaintObjects.push(u),!0}dispose(){for(let e of Eo.values())e.delete();Eo.clear()}};var yx=`
1791
- // Declared widest-first \u2014 vec4, then vec2s, then floats.
1792
- //
1793
- // Skia lays runtime-effect uniforms out with alignment, so a vec4 declared after
1794
- // an odd number of floats starts at the next 4-float boundary and the values fed
1795
- // to makeShader (a flat, padding-free array) land one or two slots off. Every
1796
- // uniform after the gap then reads garbage, which for a coverage shader means a
1797
- // solid block rather than an error. Ordering by width leaves no gap to pad, so
1798
- // the flat array and the layout agree by construction.
1799
- uniform vec4 u_color;
1800
- uniform vec2 u_origin; // shape bounds origin, shape-local logical px
1801
- uniform vec2 u_offset; // lattice shift, logical px
1802
- uniform float u_spacing; // lattice pitch, logical px
1803
- uniform float u_radius; // dot radius, logical px
1804
- uniform float u_feather; // coverage ramp width, logical px
1805
-
1806
- vec4 main(vec2 fragCoord) {
1807
- // A radius of zero is a lattice switched off, and has to be answered before
1808
- // the ramp: the ramp is centred on the dot's edge, so a zero-radius dot still
1809
- // lands half a pixel of coverage on the pixel it sits in.
1810
- if (u_radius <= 0.0) return vec4(0.0);
1811
-
1812
- vec2 p = fragCoord - u_origin - u_offset;
1813
- // Distance from the centre of the cell this pixel falls in. SkSL's mod is
1814
- // floor-based, so this holds for negative coordinates too \u2014 which is what a
1815
- // shape left of the origin, or a negative offset, produces.
1816
- vec2 d = mod(p, u_spacing) - u_spacing * 0.5;
1817
-
1818
- float cover = clamp((u_radius - length(d)) / u_feather + 0.5, 0.0, 1.0);
1819
- float a = u_color.a * cover;
1820
- return vec4(u_color.rgb * a, a);
1821
- }
1822
- `,Mo=class extends qe{live=null;replaceLive(e){this.live?.delete(),this.live=e}applyPaint(e,t){let n=t.getShapeBounds();if(!n)return!1;let i=ue(yx,t.canvasKit);if(!i)return!1;let s=Math.max(.01,e.spacing),a=i.makeShader([e.color[0],e.color[1],e.color[2],e.color[3],n.left,n.top,e.offset.x,e.offset.y,s,Math.max(0,e.radius),Qa(t)]);return a?(this.replaceLive(a),t.paint.setShader(a),!0):!1}dispose(){this.replaceLive(null)}};var wx=`
1823
- // Declared widest-first, so the flat array handed to makeShader needs no padding
1824
- // \u2014 see the note on the dot-grid fill's source for what a gap here costs.
1825
- uniform vec4 u_color;
1826
- uniform vec2 u_origin; // shape bounds origin, shape-local logical px
1827
- uniform vec2 u_size; // shape bounds size, shape-local logical px
1828
- uniform vec2 u_offset; // ruling shift, logical px
1829
- uniform float u_divisions; // cells across the shape, per axis
1830
- uniform float u_subdivisions; // finer cells inside each division
1831
- uniform float u_halfMajor; // half a division line's thickness, logical px
1832
- uniform float u_halfMinor; // half a subdivision line's thickness, logical px
1833
- uniform float u_feather; // coverage ramp width, logical px
1834
-
1835
- /*
1836
- * Coverage of the nearest line of a ruling at the given pitch, on either axis.
1837
- *
1838
- * SkSL's mod is floor-based, so the distance to the nearest multiple is
1839
- * min(m, pitch - m) whatever the sign of the coordinate.
1840
- */
1841
- float ruling(vec2 p, vec2 pitch, float halfWidth, float feather) {
1842
- // A width of zero means the order is switched off, and has to be answered
1843
- // here rather than left to the ramp: the ramp is centred on the line, so a
1844
- // zero-width one still lands half a pixel of coverage on the pixels it runs
1845
- // through \u2014 a ruling you asked not to be drawn, drawn faintly.
1846
- if (halfWidth <= 0.0) return 0.0;
1847
- vec2 m = mod(p, pitch);
1848
- vec2 d = min(m, pitch - m);
1849
- return clamp((halfWidth - min(d.x, d.y)) / feather + 0.5, 0.0, 1.0);
1850
- }
1851
-
1852
- vec4 main(vec2 fragCoord) {
1853
- vec2 p = fragCoord - u_origin - u_offset;
1854
-
1855
- // Cells follow the box, so a non-square shape gets non-square cells \u2014 see
1856
- // GridFillProp. Floored well above zero because a pitch of 0 makes mod
1857
- // undefined, which paints garbage rather than nothing.
1858
- vec2 major = max(u_size / max(u_divisions, 0.0001), vec2(0.01));
1859
- vec2 minor = major / max(u_subdivisions, 1.0);
1860
-
1861
- float cover = max(
1862
- ruling(p, major, u_halfMajor, u_feather),
1863
- ruling(p, minor, u_halfMinor, u_feather)
1864
- );
1865
-
1866
- float a = u_color.a * cover;
1867
- return vec4(u_color.rgb * a, a);
1868
- }
1869
- `,Fo=class extends qe{live=null;replaceLive(e){this.live?.delete(),this.live=e}applyPaint(e,t){let n=t.getShapeBounds();if(!n)return!1;let i=n.right-n.left,s=n.bottom-n.top;if(i<=0||s<=0)return!1;let a=ue(wx,t.canvasKit);if(!a)return!1;let o=Math.max(1,Math.round(e.subdivisions)),c=a.makeShader([e.color[0],e.color[1],e.color[2],e.color[3],n.left,n.top,i,s,e.offset.x,e.offset.y,Math.max(1e-4,e.divisions),o,Math.max(0,e.strokeWidth)*.5,Math.max(0,e.subdivisionWidth)*.5,Qa(t)]);return c?(this.replaceLive(c),t.paint.setShader(c),!0):!1}dispose(){this.replaceLive(null)}};var Ro=class extends qe{applyPaint(e,t){return t.paint.setColorComponents(e.color[0],e.color[1],e.color[2],e.color[3]*Ya(e,t)*t.worldAlpha),t.paint.setShader(null),!0}};var Os=class{static list=[{name:"solid",renderer:new Ro},{name:"linear-gradient",renderer:new xo},{name:"radial-gradient",renderer:new To},{name:"conic-gradient",renderer:new Ao},{name:"image",renderer:new ao},{name:"video",renderer:new So},{name:"noise",renderer:new vo},{name:"fractalNoise",renderer:new _o},{name:"shader",renderer:new Po},{name:"stripe",renderer:new Io},{name:"dotGrid",renderer:new Mo},{name:"grid",renderer:new Fo},{name:"canvas3D",renderer:new uo}];static get(e){return this.list.find(t=>t.name===e)?.renderer}static applyPaint(e,t){let n=this.get(e.type);return n?n.applyPaint(e,t):!1}static preflight(e,t){this.get(e.type)?.preflight?.(e,t)}static disposeRenderers(){for(let{renderer:e}of this.list)e?.dispose()}};var Bo=class{canvasKit;getPaint;getCanvas;getUnionBounds;getSpaceRect;assets;getWorldAlpha;getNodeId;getElapsed;getDeviceScale;rasterizeSurface;effectResources;getDeviceMatrix;slots=new Map;currentBounds=null;constructor(e,t,n,i,s,a,o=()=>1,c=()=>"",l=()=>0,u=()=>1,d=()=>null,h=()=>null,f=()=>null){this.canvasKit=e,this.getPaint=t,this.getCanvas=n,this.getUnionBounds=i,this.getSpaceRect=s,this.assets=a,this.getWorldAlpha=o,this.getNodeId=c,this.getElapsed=l,this.getDeviceScale=u,this.rasterizeSurface=d,this.effectResources=h,this.getDeviceMatrix=f,this.currentBounds=null}worldAlpha(){return this.getWorldAlpha()}beginFrame(){this.slots.clear(),this.preflighted.clear()}paintSlot(e){let t=this.getNodeId(),n=this.slots.get(t);n||(n=new Map,this.slots.set(t,n));let i=n.get(e);if(i!==void 0)return i;let s=n.size;return n.set(e,s),s}unionPath(e){if(e.length<2||e.some(n=>!n.ckPath))return null;let t=e[0].ckPath.copy();for(let n=1;n<e.length;n++){let i=this.canvasKit.Path.MakeFromOp(t,e[n].ckPath,this.canvasKit.PathOp.Union);if(t.delete(),!i)return null;t=i}return t}setCurrentBounds(e){this.currentBounds=e}boundsForSpace(e,t){switch(e){case"parent":case"global":return this.getSpaceRect(e)??this.getUnionBounds();default:return this.getUnionBounds()}}dispose(){}getCanvasKitBlendMode(e){return jt(this.canvasKit,e)}buildRendererCtx(e,t=this.getWorldAlpha()){let n;return{canvasKit:this.canvasKit,paint:e,assets:this.assets,worldAlpha:t,opacityRealised:!1,getShapeBounds:()=>this.currentBounds,nodeId:this.getNodeId(),elapsed:this.getElapsed(),getDeviceScale:this.getDeviceScale,getDeviceMatrix:()=>n===void 0?n=this.getDeviceMatrix():n,paintSlot:i=>this.paintSlot(i),rasterizeSurface:this.rasterizeSurface,effectResources:this.effectResources,preflighted:new Map,transientImages:[],transientPaintObjects:[],clipFilterToShape:!1,drawShape:()=>{},skipDefaultDraw:!1}}preflighted=new Map;preflight(e,t){let n=this.buildRendererCtx(t);n.preflighted=this.preflighted;for(let i of e)this.preflighted.has(i)||(this.currentBounds=this.boundsForSpace(i.space??"local",null),Os.preflight(i,n));this.currentBounds=null}openPass(e,t,n,i=this.getWorldAlpha()){this.preflight(e,t);let s=this.buildRendererCtx(t,i);return s.preflighted=this.preflighted,s.drawShape=n,s}openShadowPass(e,t){let n=this.openPass(e,t,()=>{},1);return n.opacityRealised=!0,n}applyFill(e,t,n,i=!0){let s=e.paint;return s.setAlphaf(n),s.setBlendMode(i&&t.blend?this.getCanvasKitBlendMode(t.blend):this.canvasKit.BlendMode.SrcOver),s.setImageFilter(null),e.skipDefaultDraw=!1,e.clipFilterToShape=!1,Os.applyPaint(t,e)}endFill(e){let t=e.paint;t.setShader(null),t.setImageFilter(null);for(let n of e.transientImages)n.delete();e.transientImages.length=0;for(let n of e.transientPaintObjects)n.delete();e.transientPaintObjects.length=0}closePass(e){let t=e.paint;this.currentBounds=null,t.setBlendMode(this.canvasKit.BlendMode.SrcOver),t.setAlphaf(1),t.setShader(null),t.setImageFilter(null)}drawShapes(e,t,n=!1){let i=this.unionPath(t),s=()=>{if(i)this.getCanvas().drawPath(i,e);else for(let o of t)o.draw(e)},a=n?i??(t.length===1?t[0].ckPath:null):null;if(a){let o=this.getCanvas();o.save(),o.clipPath(a,this.canvasKit.ClipOp.Intersect,!0),s(),o.restore()}else s();i?.delete()}applyFills(e,t){if(e.length===0)return!1;let n=this.getPaint(),i=this.openPass(e,n,a=>this.drawShapes(a,t,i.clipFilterToShape));n.setStyle(this.canvasKit.PaintStyle.Fill);let s=this.getWorldAlpha();for(let a of e)this.currentBounds=this.boundsForSpace(a.space??"local",null),this.applyFill(i,a,(a.opacity??1)*s)&&!i.skipDefaultDraw&&this.drawShapes(n,t,i.clipFilterToShape),this.endFill(i);return this.closePass(i),!0}};var Gm=r=>-(r??0);function Ai(r,e,t){let n=Cx(r,e,t),{x:i,y:s,pivot:a}=_x(n,e,t);return{...Px(n),x:i,y:-s,pivot:a}}function au(r){return Ai(r,r.width??0,r.height??0)}function ou(r){let e=Ai(r,r.width??0,r.height??0);return r.startAngle!=null&&(e.startAngle=-r.startAngle),r.sweep!=null&&(e.sweep=-r.sweep),e}function cu(r){return Ai(r,r.width??0,r.height??0)}function lu(r){return Ai(r,r.width??0,r.height??0)}function uu(r){let e=r.points?r.points.map(t=>({x:t.x,y:-t.y})):r.points;return{...r,y:Gm(r.y),points:e}}function Ex(r){return Ai(r,r.width??0,r.height??0)}function Ix(r){return Ai(r,r.width??0,r.height??0)}function Mx(r){switch(r.type){case"M":case"m":case"L":case"l":case"T":case"t":return{...r,y:-r.y};case"V":case"v":return{...r,y:-r.y};case"H":case"h":return r;case"C":case"c":return{...r,y1:-r.y1,y2:-r.y2,y:-r.y};case"S":case"s":return{...r,y2:-r.y2,y:-r.y};case"Q":case"q":return{...r,y1:-r.y1,y:-r.y};case"A":case"a":return{...r,y:-r.y,sweep:r.sweep===1?0:1};case"Z":case"z":return r}}function du(r){let e={...r,y:Gm(r.y)};if(Array.isArray(r.data)&&(e.data=r.data.map(Mx),r.centerBounds)){let[t,n,i,s]=r.centerBounds;e.centerBounds=[t,-s,i,-n]}return e}var Fx=()=>{};function Rx(r,e){return e==="decal"?r.TileMode.Decal:r.TileMode.Clamp}function Wm(r,e){return e==="nearest"?r.FilterMode.Nearest:r.FilterMode.Linear}function hu(r,e){return{width:r,height:e,centerX:0,centerY:0,scale:1,time:0,velocity:Km,angularVelocity:0}}var Km={x:0,y:0},qm=4,Bx=4;function jm(r,e){return e>=1?r:r.map(t=>({...t,opacity:(t.opacity??1)*e}))}function Dx(r,e){return e>=1?r:r.map(t=>({...t,fill:jm(t.fill,e)}))}var Do=class extends kx{currentCanvas;canvasKit;surface;activeSurface;rasterDepth=0;warnedInertShapeProps=new Set;paint;layerPaint;mounted=!1;isRendering=!1;effectLayerStack=[];worldAlpha=1;worldAlphaStack=[];clipRestoreStack=[];clipShapeStack=[];fillHandler;strokeHandler;shapeHandler;deferredPaintsStack=[];storageAdapter;constructor(e,t){super(),this.canvasKit=e,this.storageAdapter=t,this._makePaints(),this.buildHandlers()}measureText(e,t,n,i=400,s=0,a="normal"){return mo(this.canvasKit,this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),this.storageAdapter.getFontEpoch(),e,t,n,i,s,a)}layoutTextBlock(e){return po(this.canvasKit,this.storageAdapter.getFontMgr(),e)}buildHandlers(){let e=()=>this.currentCanvas,t=()=>this.paint;this.shapeHandler=new ko(this.canvasKit,e,t,this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),()=>this.storageAdapter.getFontEpoch());let n=()=>this.worldAlpha;this.fillHandler=new Bo(this.canvasKit,t,e,()=>this.shapeHandler.getShapeBounds(),i=>this.spaceRect(i),this.storageAdapter,n,()=>this.currentNodeStack.length>0?this.currentNodeId():"",()=>this.currentRenderState()?.elapsed??0,()=>{let i=this.currentCanvas.getTotalMatrix();return Math.max(Math.hypot(i[0],i[3]),Math.hypot(i[1],i[4]),1)},(i,s,a,o)=>this.rasterizeSurfaceSource(i,s,a,o),()=>this.effectResources(),()=>this.currentCanvas?.getTotalMatrix()??null),this.strokeHandler=new go(this.canvasKit,e,t,this.fillHandler)}pixelRatio=1;view={zoom:1,x:0,y:0};frame=null;clipToFrame=!0;frameBackground="black";executePass(e){if(!this.mounted||!this.surface)return;let t=this.surface.getCanvas();this.currentCanvas=t,this.activeSurface=this.surface,this.currentCanvas.clear(this.frame?this.canvasKit.TRANSPARENT:this.canvasKit.BLACK);let n=t.getSaveCount();this.currentCanvas.save();let i=this.surface.width()/this.pixelRatio,s=this.surface.height()/this.pixelRatio;if(this.currentCanvas.scale(this.pixelRatio,this.pixelRatio),this.currentCanvas.translate(i/2+this.view.x,s/2+this.view.y),this.view.zoom!==1&&this.currentCanvas.scale(this.view.zoom,this.view.zoom),this.frame){let c=this.canvasKit,l=this.frame.width/2,u=this.frame.height/2,d=c.LTRBRect(-l,-u,l,u),h=this.frameBackground==="black";this.clipToFrame?(this.currentCanvas.clipRect(d,c.ClipOp.Intersect,!0),h&&this.currentCanvas.drawColor(c.BLACK,c.BlendMode.Src)):h&&(this.currentCanvas.save(),this.currentCanvas.clipRect(d,c.ClipOp.Intersect,!0),this.currentCanvas.drawColor(c.BLACK,c.BlendMode.Src),this.currentCanvas.restore())}let a=ci(this.storageAdapter);a?.beginFrame(),this.fillHandler.beginFrame(),this.storageAdapter.beginRenderPass(),this.isRendering=!0;let o=!0;try{e(),o=!1}finally{this.isRendering=!1,this._resetPass(t,n,o),a?.sweep(),this.surface.flush(),this.storageAdapter.endRenderPass(),this.storageAdapter.getParagraphCache().endPass()}}begin(e){if(!this.currentCanvas)throw new Error("begin() must be called within the draw() method.");super.begin(e),this.shapeHandler.beginNode(e.id),this.shapeHandler.reset(),this.effectLayerStack.push(0),this.worldAlphaStack.push(this.worldAlpha),this.currentCanvas.save()}end(){if(!this.currentCanvas)throw new Error("end() must be called within the draw() method.");let e=this.effectLayerStack.pop()??0;for(let t=0;t<e;t++)this.currentCanvas.restore();this.worldAlpha=this.worldAlphaStack.pop()??1,this.currentCanvas.restore(),super.end()}currentWorldAlpha(){return this.worldAlpha}_resetPass(e,t,n){for(let i of this.effectScopeStack)for(let s of i.captures)s.offscreen.delete();this.effectScopeStack.length=0,this.currentCanvas=e,this.activeSurface=this.surface,e.restoreToCount(t),this.effectLayerStack.length=0,this.worldAlphaStack.length=0,this.worldAlpha=1,this.clipRestoreStack.length=0,this.clipShapeStack.length=0,this.cameraRestoreStack.length=0,this.deferredPaintsStack.length=0,this.rasterDepth=0,this.shapeHandler.resetPass(),this._resetScopes(),n&&(this.paint.delete(),this.layerPaint.delete(),this._makePaints())}_makePaints(){this.paint=new this.canvasKit.Paint,this.paint.setAntiAlias(!0),this.layerPaint=new this.canvasKit.Paint}dispose(){this.fillHandler?.dispose(),this.shapeHandler?.dispose(),this.storageAdapter.dispose(),this.surface&&this.surface.dispose(),this.mounted=!1,this.canvasKit=void 0,this.paint?.delete(),this.paint=void 0,this.layerPaint?.delete(),this.layerPaint=void 0,this.currentCanvas=void 0,this.effectLayerStack.length=0,this.clipRestoreStack.length=0,this.clipShapeStack.length=0,this.deferredPaintsStack.length=0,this.effectScopeStack.length=0,Xa(),Qh(),um(),vs()?.dispose(),Se.disposeAll(),of(),Rm(),super.dispose()}execute(e){this.executePass(e)}attach(e){this.mounted&&this.detach(),this.surface=e,this.mounted=!0,this.storageAdapter.setSurface(e)}detach(){this.mounted&&(this.storageAdapter.setSurface(null),this.surface.dispose(),this.mounted=!1)}snapshotPixels(){if(!this.mounted){console.warn("snapshotPixels() must be called after attach().");return}this.surface.flush();let e=this.surface.makeImageSnapshot();if(!e)return;let t=this.canvasKit,n=this.frameDeviceRect(),i=n?Math.max(0,Math.round(n.left)):0,s=n?Math.max(0,Math.round(n.top)):0,a=n?Math.max(1,Math.min(e.width()-i,Math.round(n.right-n.left))):e.width(),o=n?Math.max(1,Math.min(e.height()-s,Math.round(n.bottom-n.top))):e.height(),c=e.readPixels(i,s,{width:a,height:o,colorType:t.ColorType.RGBA_8888,alphaType:t.AlphaType.Unpremul,colorSpace:t.ColorSpace.SRGB});if(e.delete(),!!c)return{pixels:new Uint8Array(c),width:a,height:o}}drawGraphics(e){if(!this.isRendering){console.warn("draw() must be called within the draw() method.");return}let t=e.needsGroupLayer(),n=this.worldAlpha,i=this.currentCanvas,s=i.getSaveCount(),a=null,o=null;try{if(t){let d=e.groupOpacity();d<1&&(this.worldAlpha*=d)}let c=e.groupTransform();if(c){let d=this.resolveGroupCenter(e,c.center),h=d.x,f=d.y;i.save(),i.translate(h,f),i.rotate(c.rotation,0,0),i.scale(c.scale,c.scale),i.translate(-h,-f)}let l=e.ops();o=this.buildEffectSegments(e);let u=!1;for(let d=0;d<l.length;d++){let h=o.get(d);h&&(o.delete(d),a=h.filter,this.layerPaint.setAlphaf(1),this.layerPaint.setImageFilter(a),i.saveLayer(this.layerPaint),this.layerPaint.setImageFilter(null),u=!0);let f=l[d];if(f.kind==="effects"){u&&(i.restore(),a?.delete?.(),a=null,u=!1),this.shapeHandler.reset();continue}this.applyOp(f)}}finally{if(i.restoreToCount(s),a?.delete?.(),o)for(let c of o.values())c.filter.delete?.();this.worldAlpha=n}}buildEffectSegments(e){let t=e.ops(),n=new Map,i=0,s=!1,a=o=>o==="rect"||o==="ellipse"||o==="path"||o==="line"||o==="polygon"||o==="polygram"||o==="text"||o==="richText";for(let o=0;o<t.length;o++){let c=t[o];if(a(c.kind)){s&&(i=o,s=!1);continue}if(c.kind==="fill"||c.kind==="stroke"||c.kind==="shadow"){s=!0;continue}if(c.kind==="effects"){let l=this.resolveMotionBlurEffects(c.effects.filter(d=>d.mode!=="backdrop")),u=l.length>0?Se.compose(l,this.canvasKit,hu(this.activeSurface.width(),this.activeSurface.height())):null;u!=null&&n.set(i,{filter:u}),i=o+1,s=!1;continue}}return n}resolveGroupCenter(e,t){if(t!==void 0&&typeof t!="string")return{x:t.x,y:t.y};this.shapeHandler.beginMeasure();for(let l of e.ops())switch(l.kind){case"rect":this.shapeHandler.rect(au(l.state));break;case"ellipse":this.shapeHandler.ellipse(ou(l.state));break;case"path":this.shapeHandler.path(du(l.state));break;case"line":this.shapeHandler.line(uu(l.state));break;case"polygon":this.shapeHandler.polygon(cu(l.state));break;case"polygram":this.shapeHandler.polygram(lu(l.state));break}let n=this.shapeHandler.measureUnionBounds();if(this.shapeHandler.endMeasure(),!n)return{x:0,y:0};let i=(n.left+n.right)/2,s=(n.top+n.bottom)/2;if(t===void 0)return{x:i,y:s};let a=vx.resolve(t),o=(n.right-n.left)/2,c=(n.bottom-n.top)/2;return{x:i+a.x*o,y:s-a.y*c}}warnInertShapeProps(e,t){let n={opacity:t.opacity!==void 0&&t.opacity!==1,blend:t.blend!==void 0&&t.blend!=="pass-through"};for(let i of["opacity","blend"])!n[i]||this.warnedInertShapeProps.has(i)||(this.warnedInertShapeProps.add(i),console.warn(`Graphics2D .${e}() was given \`${i}\`, which a shape does not draw. Use Graphics2D.opacity() for the whole group, or the node's own opacity and blend.`))}applyOp(e){switch(e.kind){case"rect":case"ellipse":case"path":case"line":case"polygon":case"polygram":case"text":case"richText":this.warnInertShapeProps(e.kind,e.state)}switch(e.kind){case"rect":this._rect(au(e.state));break;case"ellipse":this._ellipse(ou(e.state));break;case"path":this._path(du(e.state));break;case"line":this._line(uu(e.state));break;case"polygon":this._polygon(cu(e.state));break;case"polygram":this._polygram(lu(e.state));break;case"text":this._text(Ex(e.state));break;case"richText":this._richText(Ix(e.state));break;case"fill":this._fill(e.fills);break;case"stroke":this._stroke(e.strokes);break;case"shadow":this._shadow(e.shadows);break;case"cut":this._cut();break;case"mask":this._maskOp(e.options);break;case"applyMask":this._applyMask();break;case"endMask":this._endMaskOp();break;case"effects":break}}transform(e){if(!this.isRendering)return console.warn("transform() must be called within the draw() method."),this;let t=e.x??0,n=e.y??0,i=e.width??0,s=e.height??0,a=e.opacity??1,o=e.blend??"pass-through",c=e.rotation??0,l=e.scale??1,u=e.effects??[],d=e.pivot??{x:0,y:0},h=e.matrix;if(h)this.currentCanvas.concat([h.a,h.c,h.e,h.b,h.d,h.f,h.g??0,h.h??0,h.i??1]);else{let g=d.x*(i/2),y=-d.y*(s/2);this.currentCanvas.translate(t+g,n+y),this.currentCanvas.rotate(c,0,0),this.currentCanvas.scale(l,l),this.currentCanvas.translate(-g,-y)}let f=u.filter(g=>g.mode!=="backdrop"),p=null;if(f.length>0){let g=this.resolveMotionBlurEffects(f);p=Se.compose(g,this.canvasKit,hu(i,s))}if(o!=="pass-through")this.layerPaint.setAlphaf(this.worldAlpha*(a<1?a:1)),this.layerPaint.setBlendMode(jt(this.canvasKit,o)),this.layerPaint.setImageFilter(p??null),this.currentCanvas.saveLayer(this.layerPaint),this.layerPaint.setAlphaf(1),this.layerPaint.setBlendMode(this.canvasKit.BlendMode.SrcOver),this.layerPaint.setImageFilter(null),this.effectLayerStack[this.effectLayerStack.length-1]++,this.worldAlpha=1;else{if(p!=null){this.layerPaint.setAlphaf(1),this.layerPaint.setImageFilter(p);let g=this.canvasKit.LTRBRect(-i/2,-s/2,i/2,s/2);this.currentCanvas.saveLayer(this.layerPaint,g),this.layerPaint.setImageFilter(null),this.effectLayerStack[this.effectLayerStack.length-1]++}a<1&&(this.worldAlpha*=a)}return this}resolveMotionBlurEffects(e){let t=!1;for(let s of e)if(s.type==="motionBlur"){t=!0;break}if(!t)return e;let n=this.currentRenderState(),i=[];for(let s of e){if(s.type!=="motionBlur"){i.push(s);continue}let a=n?lf(s,n.velocity,n.dt):null;a&&i.push(a)}return i}frameDeviceRect(){if(!this.frame||!this.surface)return null;let e=this.pixelRatio,t=this.surface.width()/e/2+this.view.x,n=this.surface.height()/e/2+this.view.y,i=this.frame.width/2*this.view.zoom,s=this.frame.height/2*this.view.zoom;return{left:(t-i)*e,top:(n-s)*e,right:(t+i)*e,bottom:(n+s)*e}}spaceRect(e){if(e==="parent")return this.currentSpaceRects().parent??null;if(e==="global"){let t=this.currentCanvas?.getTotalMatrix();if(!t)return null;let n=this.canvasKit.Matrix.invert(t);if(!n)return null;let i=this.frame&&this.activeSurface===this.surface?this.frameDeviceRect():null;if(i){let l=this.canvasKit.Matrix.mapPoints(n,[i.left,i.top]),u=this.canvasKit.Matrix.mapPoints(n,[i.right,i.bottom]);return{left:Math.min(l[0],u[0]),top:Math.min(l[1],u[1]),right:Math.max(l[0],u[0]),bottom:Math.max(l[1],u[1])}}let s=this.activeSurface.width(),a=this.activeSurface.height(),o=this.canvasKit.Matrix.mapPoints(n,[0,0]),c=this.canvasKit.Matrix.mapPoints(n,[s,a]);return{left:Math.min(o[0],c[0]),top:Math.min(o[1],c[1]),right:Math.max(o[0],c[0]),bottom:Math.max(o[1],c[1])}}return null}_rect(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.rect(e),this.shapeHandler.paintApplied&&this.shapeHandler.reset()}_ellipse(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.ellipse(e)}_path(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.path(e)}_line(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.line(e)}_polygon(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.polygon(e)}_polygram(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset(),this.shapeHandler.polygram(e)}_text(e){if(this.shapeHandler.paintApplied&&this.shapeHandler.reset(),e.segments&&e.segments.length>0){this._segmentedText(e);return}this.shapeHandler.text(e)}_segmentedText(e){let t=pm(this.canvasKit,this.storageAdapter.getFontMgr(),e);this.shapeHandler.pushBounds(t.bounds);try{for(let n of t.runs){if(n.glyphs.length===0||!n.segment)continue;let i=n.segment,s=i.x!==0||i.y!==0||i.scale!==1||i.rotation!==0;if(s){let l=gm(n);this.currentCanvas.save(),this.currentCanvas.translate(i.x,i.y),i.rotation!==0&&this.currentCanvas.rotate(i.rotation,l.x,l.y),i.scale!==1&&(this.currentCanvas.translate(l.x,l.y),this.currentCanvas.scale(i.scale,i.scale),this.currentCanvas.translate(-l.x,-l.y))}let a={isText:!0,draw:l=>Ql(this.currentCanvas,n,l)},o=i.fill?jm(i.fill,i.opacity):[];o.length>0&&this.fillHandler.applyFills(o,[a]);let c=i.stroke?Dx(i.stroke,i.opacity):[];c.length>0&&this.strokeHandler.applyStrokes(c,[a]),s&&this.currentCanvas.restore()}}finally{this.shapeHandler.popBounds();for(let n of t.fonts)n.delete()}}_richText(e){this.shapeHandler.paintApplied&&this.shapeHandler.reset();let t=Sx(e),n=mm(this.canvasKit,this.storageAdapter.getFontMgr(),t);this.shapeHandler.pushBounds(n.bounds);try{for(let i of n.runs){if(i.glyphs.length===0)continue;let s={isText:!0,draw:a=>{Ql(this.currentCanvas,i,a)}};i.span.fill.length>0&&this.fillHandler.applyFills(i.span.fill,[s]),i.span.stroke.length>0&&this.strokeHandler.applyStrokes(i.span.stroke,[s])}}finally{this.shapeHandler.popBounds();for(let i of n.fonts)i.delete()}}_fill(e){let t=xx.resolve(e);if(t.length===0){this.shapeHandler.paintApplied=!0;return}if(this.shapeHandler.isCollectingPaths()){this.shapeHandler.paintApplied=!0;return}let n=this.shapeHandler.getMaskApply();if(n!==null&&!n.has("fill")){let s=this.deferredPaintsStack[this.deferredPaintsStack.length-1];if(s){s.push({kind:"fill",shapes:[...this.shapeHandler.shapes],fills:t,shadows:this.shapeHandler.takePendingShadows()}),this.shapeHandler.paintApplied=!0;return}}let i=this.shapeHandler.takePendingShadows();if(i){let s=i[0].fill[0]?.space??"local",{shapes:a,dispose:o}=this.strokeShapesForSpace(s);this.strokeHandler.applyShadows(i,a,t,[],this.applyFillSpaceBounds),this.fillHandler.applyFills(t,this.shapeHandler.shapes),this.strokeHandler.applyInnerShadows(i,a,t,this.applyFillSpaceBounds),o()}else this.fillHandler.applyFills(t,this.shapeHandler.shapes);this.shapeHandler.paintApplied=!0}applyFillSpaceBounds=(e,t)=>{this.fillHandler.setCurrentBounds(this.fillHandler.boundsForSpace(e.space??"local",t))};strokeShapesForSpace(e){let t=this.shapeHandler.unionStrokeShape();return t?{shapes:[t],dispose:()=>{t.ckPath?.delete(),t.strokePath&&t.strokePath!==t.ckPath&&t.strokePath.delete()}}:{shapes:this.shapeHandler.shapes,dispose:()=>{}}}_stroke(e){let t=Tx.resolve(e);if(t.length===0)return;if(this.shapeHandler.isCollectingPaths()){this.shapeHandler.paintApplied=!0;return}let n=this.shapeHandler.getMaskApply();if(n!==null&&!n.has("stroke")){let c=this.deferredPaintsStack[this.deferredPaintsStack.length-1];if(c){c.push({kind:"stroke",shapes:[...this.shapeHandler.shapes],strokes:t,shadows:this.shapeHandler.takePendingShadows()}),this.shapeHandler.paintApplied=!0;return}}let i=this.shapeHandler.takePendingShadows();if(i){let c=i[0].fill[0]?.space??"local",{shapes:l,dispose:u}=this.strokeShapesForSpace(c);this.strokeHandler.applyShadows(i,l,[],t,this.applyFillSpaceBounds),u()}let s=t[0].fill[0]?.space??"local",{shapes:a,dispose:o}=this.strokeShapesForSpace(s);this.strokeHandler.applyStrokes(t,a,this.applyFillSpaceBounds),o(),this.shapeHandler.paintApplied=!0}_shadow(e){let t=Ax.resolve(e);t.length!==0&&(this.shapeHandler.isCollectingPaths()||this.shapeHandler.storePendingShadows(t))}_cut(){this.shapeHandler.cut()}cameraRestoreStack=[];beginCamera(e,t,n,i){if(!this.isRendering){console.warn("beginCamera() must be called within the draw() method.");return}let s=this.currentCanvas,a=this.canvasKit;if(s.save(),this.clipsCameraViewport(e)){let o=e.x-e.width/2,c=e.y-e.height/2,l=e.x+e.width/2,u=e.y+e.height/2;s.clipRect(a.LTRBRect(o,c,l,u),a.ClipOp.Intersect,!0)}s.save(),s.translate(e.x,e.y),s.rotate(-i,0,0),s.scale(n,n),s.translate(-t.x,t.y),this.cameraRestoreStack.push(2)}clipsCameraViewport(e){let t=this.frame;return this.clipToFrame||!t?!0:!(e.x===0&&e.y===0&&e.width===t.width&&e.height===t.height)}endCamera(){if(!this.isRendering){console.warn("endCamera() must be called within the draw() method.");return}let e=this.cameraRestoreStack.pop()??0;for(let t=0;t<e;t++)this.currentCanvas.restore()}beginClip(e){if(!this.isRendering){console.warn("beginClip() must be called within the draw() method.");return}let t=this.currentCanvas;t.save(),this.clipRestoreStack.push(1),this.clipShapeStack.push(e);let n=e.ops();if(n.length===1&&n[0].kind!=="cut"){let s=this.buildClipShapeOp(n[0]);s&&(s.clip(!0),s.deletePaths());return}let i=this.combineClipPath(e);i&&(t.clipPath(i,this.canvasKit.ClipOp.Intersect,!0),i.delete())}endClip(){if(!this.isRendering){console.warn("endClip() must be called within the draw() method.");return}let e=this.clipRestoreStack.pop()??0;this.clipShapeStack.pop();for(let t=0;t<e;t++)this.currentCanvas.restore()}buildClipShapeOp(e){let t=this.canvasKit,n=()=>this.currentCanvas;switch(e.kind){case"rect":return new pi(t,n,au(e.state));case"ellipse":return new gi(t,n,ou(e.state));case"polygon":return new yi(t,n,cu(e.state));case"polygram":return new wi(t,n,lu(e.state));case"path":return new bi(t,n,du(e.state));case"line":return new ki(t,n,uu(e.state));case"cut":return null}}combineClipPath(e){let t=this.canvasKit,n=[];for(let i of e.ops()){if(i.kind==="cut"){let a=n.pop();if(!a)continue;let o=this.unionPaths(n.splice(0,n.length));if(!o){a.delete();continue}let c=t.Path.MakeFromOp(o,a,t.PathOp.Difference);o.delete(),a.delete(),c&&n.push(c);continue}let s=this.buildClipShapeOp(i);s&&(s.ensurePath(),s.ckPath&&n.push(s.ckPath.copy()),s.deletePaths())}return this.unionPaths(n)}unionPaths(e){let t=this.canvasKit;if(e.length===0)return null;let n=e[0];for(let i=1;i<e.length;i++){let s=t.Path.MakeFromOp(n,e[i],t.PathOp.Union);if(n.delete(),e[i].delete(),!s){for(let a=i+1;a<e.length;a++)e[a].delete();return null}n=s}return n}effectScopeStack=[];beginEffects(e,t,n,i){if(!this.isRendering){console.warn("beginEffects() must be called within the draw() method.");return}let s={canvasRestores:0,captures:[]},a=[],o=[];for(let c of e){let l=Se.resolveShader(c,t);l?o.push({handler:l,effect:c}):a.push(c)}if(t==="backdrop"&&a.length>0&&this.openBackdropFilterLayer(a,n,i)&&s.canvasRestores++,t==="backdrop")for(let{handler:c,effect:l}of o)this.paintBackdropShaderEffect(c,l,n,i);else for(let c=o.length-1;c>=0;c--){let{handler:l,effect:u}=o[c],d=this.openForegroundCapture(l,u,n,i);d&&s.captures.push(d)}this.effectScopeStack.push(s)}endEffects(){if(!this.isRendering){console.warn("endEffects() must be called within the draw() method.");return}let e=this.effectScopeStack.pop();if(e){for(let t=e.captures.length-1;t>=0;t--)this.resolveForegroundCapture(e.captures[t]);for(let t=0;t<e.canvasRestores;t++)this.currentCanvas.restore()}}openBackdropFilterLayer(e,t,n){let i=this.canvasKit,s=Se.compose(e,i,hu(t,n));if(s==null)return!1;let a=this.pixelRatio,o={filter:i.FilterMode.Linear,mipmap:i.MipmapMode.None},c=i.ImageFilter.MakeMatrixTransform(i.Matrix.scaled(1/a,1/a),o,null),l=i.ImageFilter.MakeCompose(s,c),u=i.ImageFilter.MakeMatrixTransform(i.Matrix.scaled(a,a),o,l);return this.currentCanvas.saveLayer(void 0,null,u,void 0,i.TileMode.Clamp),u.delete(),l.delete(),c.delete(),s.delete(),!0}paintBackdropShaderEffect(e,t,n,i){let s=this.canvasKit;if(n<=0||i<=0)return;let a=this.currentCanvas.getTotalMatrix(),o=this.activeSurface.makeImageSnapshot(),c=o.makeShaderOptions(s.TileMode.Clamp,s.TileMode.Clamp,Wm(s,e.sampling.filterMode),s.MipmapMode.None),l=this.shaderGeometry(a,n,i),u=e.resources?.(t,s,this.effectResources(),l)??[],d=this.buildRenderInputs(e,t,l,o,a),h=e.makeShader(t,s,c,l,u,d.shaders);h!=null&&(this.paintShaderInDeviceSpace(h,a),h.delete()),d.dispose(),c.delete(),o.delete()}buildRenderInputs(e,t,n,i,s){let a=e.renderInputs?.(t,this.canvasKit,n);if(!a)return{shaders:{},dispose:Fx};let o={},c=[];if(a.distanceField){let l=this.outlineDistanceField(s);l&&(o.distanceField={shader:l.shader,maxDistance:l.maxDistance},c.push(l.dispose))}if(a.blurredSource!==void 0){let l=this.blurredCopy(i,a.blurredSource);typeof a.blurredSource!="number"&&a.blurredSource.prefilter?.delete(),l&&(o.blurredSource=l.shader,c.push(l.dispose))}return{shaders:o,dispose:()=>{for(let l of c)l()}}}outlineDistanceField(e){let t=this.clipShapeStack[this.clipShapeStack.length-1];if(!t||t.isEmpty())return null;let n=this.canvasKit,i=this.combineClipPath(t);if(!i)return null;let s=Fm(n,i,e);if(i.delete(),!s)return null;let a=n.Matrix.multiply(n.Matrix.translated(e[2]+s.originX,e[5]+s.originY),n.Matrix.scaled(s.texel,s.texel)),o=s.image.makeShaderOptions(n.TileMode.Decal,n.TileMode.Decal,n.FilterMode.Linear,n.MipmapMode.None,a);return{shader:o,maxDistance:s.maxDistance,dispose:()=>o.delete()}}blurredCopy(e,t){let n=this.canvasKit,i=this.activeSurface.makeSurface(this.activeSurface.imageInfo());if(!i)return null;let s=typeof t=="number"?t:t.sigmaX,a=typeof t=="number"?t:t.sigmaY,o=typeof t=="number"?void 0:t.prefilter,c=i.getCanvas();c.clear(n.TRANSPARENT);let l=new n.Paint,u=s>0||a>0?n.ImageFilter.MakeBlur(s,a,n.TileMode.Clamp,null):null,d=u&&o?n.ImageFilter.MakeCompose(u,o):null,h=d??u??o??null;return h&&l.setImageFilter(h),c.drawImage(e,0,0,l),d?.delete(),u?.delete(),l.delete(),this.wrapOffscreen(i,n.TileMode.Clamp)}wrapOffscreen(e,t){let n=this.canvasKit,i=e.makeImageSnapshot(),s=i.makeShaderOptions(t,t,n.FilterMode.Linear,n.MipmapMode.None);return{shader:s,dispose:()=>{s.delete(),i.delete(),e.delete()}}}openForegroundCapture(e,t,n,i){let s=this.canvasKit;if(n<=0||i<=0)return null;let a=this.activeSurface.makeSurface(this.activeSurface.imageInfo());if(!a)return null;let o=this.currentCanvas.getTotalMatrix(),c=a.getCanvas();c.save(),c.clear(s.TRANSPARENT),c.concat(o);let l=this.currentCanvas;return this.currentCanvas=c,{handler:e,effect:t,width:n,height:i,savedCanvas:l,offscreen:a,matrix:o}}resolveForegroundCapture(e){let t=this.canvasKit,{handler:n,effect:i,width:s,height:a,savedCanvas:o,offscreen:c,matrix:l}=e;this.currentCanvas.restore(),this.currentCanvas=o;let u=c.makeImageSnapshot(),d=Rx(t,n.sampling.tileMode),h=u.makeShaderOptions(d,d,Wm(t,n.sampling.filterMode),t.MipmapMode.None),f=this.shaderGeometry(l,s,a),p=n.resources?.(i,t,this.effectResources(),f)??[],m=this.buildRenderInputs(n,i,f,u,l),g=n.makeShader(i,t,h,f,p,m.shaders),y=g!=null&&i.clip===!0?t.Shader.MakeBlend(t.BlendMode.SrcIn,h,g):null;this.paintShaderInDeviceSpace(y??g??h,l),y?.delete(),g?.delete(),m.dispose(),h.delete(),u.delete(),c.delete()}effectResources(){return{fontMgr:this.storageAdapter.getFontMgr(),fontEpoch:this.storageAdapter.getFontEpoch(),makeSurface:(e,t)=>!(e>0)||!(t>0)?null:this.activeSurface.makeSurface({...this.activeSurface.imageInfo(),width:Math.ceil(e),height:Math.ceil(t)}),getImage:(e,t)=>this.storageAdapter.getCKImage(e,t),getImageSize:e=>this.storageAdapter.getImageSize(e)}}shaderGeometry(e,t,n){let i=Math.hypot(e[0],e[3]),s=Math.hypot(e[1],e[4]),a=this.currentRenderState();return{centerX:e[2],centerY:e[5],width:t*i,height:n*s,scale:i,time:a?.elapsed??0,velocity:a?.velocity??Km,angularVelocity:a?.angularVelocity??0}}paintShaderInDeviceSpace(e,t){let n=this.canvasKit;this.currentCanvas.save();let i=n.Matrix.invert(t);i&&this.currentCanvas.concat(i);let s=new n.Paint;s.setShader(e),s.setAntiAlias(!0),this.currentCanvas.drawRect(n.LTRBRect(0,0,this.activeSurface.width(),this.activeSurface.height()),s),s.delete(),this.currentCanvas.restore()}rasterizeSurfaceSource(e,t,n,i){let s=bx(e);if(s.kind==="graphics")return this.rasterize(t,n,()=>this.draw(s.graphics),i);let a=s.node;return this.rasterize(t,n,()=>{a.layout({x:0,y:0,width:t,height:n},this),a.render(this)},i)}rasterize(e,t,n,i=1){if(!this.isRendering||!this.surface||!(e>0)||!(t>0))return null;if(this.rasterDepth>=qm)return console.warn(`rasterize() nested more than ${qm} deep \u2014 skipping. A Surface2D is most likely nested inside itself via a Canvas3D.`),null;let s=this.canvasKit,a=Math.max(1,Math.min(i,Bx)),o=Math.max(1,Math.ceil(e*a)),c=Math.max(1,Math.ceil(t*a)),l=this.activeSurface.makeSurface({...this.activeSurface.imageInfo(),width:o,height:c});if(!l)return null;let u=this.currentCanvas,d=this.activeSurface,h=this.worldAlpha,f=this.shapeHandler.beginNested(),p=l.getCanvas();p.save(),p.clear(s.TRANSPARENT),p.scale(a,a),p.translate(e/2,t/2),this.currentCanvas=p,this.activeSurface=l,this.worldAlpha=1,this.rasterDepth++;try{n()}finally{p.restore(),this.rasterDepth--,this.currentCanvas=u,this.activeSurface=d,this.worldAlpha=h,this.shapeHandler.endNested(f)}l.flush();let m=l.makeImageSnapshot(),g=m?.readPixels(0,0,{width:o,height:c,colorType:s.ColorType.RGBA_8888,alphaType:s.AlphaType.Unpremul,colorSpace:s.ColorSpace.SRGB});return m?.delete(),l.delete(),g?{pixels:new Uint8Array(g),width:o,height:c}:null}beginBoolean(e){if(!this.isRendering){console.warn("beginBoolean() must be called within the draw() method.");return}this.shapeHandler.beginBoolean(e)}endBoolean(){if(!this.isRendering){console.warn("endBoolean() must be called within the draw() method.");return}this.shapeHandler.endBoolean()}beginMask(e){if(!this.isRendering){console.warn("beginMask() must be called within the draw() method.");return}this.shapeHandler.beginMask(e),this.deferredPaintsStack.push([])}applyMask(){if(!this.isRendering){console.warn("applyMask() must be called within the draw() method.");return}this.shapeHandler.applyMask()}endMask(){if(!this.isRendering){console.warn("endMask() must be called within the draw() method.");return}this.shapeHandler.endMask();let e=this.deferredPaintsStack.pop()??[];this.flushDeferredPaints(e)}_maskOp(e){this.beginMask(e)}_applyMask(){this.applyMask()}_endMaskOp(){this.endMask()}flushDeferredPaints(e){for(let t of e)t.kind==="stroke"?(t.shadows&&this.strokeHandler.applyShadows(t.shadows,t.shapes,[],t.strokes,this.applyFillSpaceBounds),this.strokeHandler.applyStrokes(t.strokes,t.shapes,this.applyFillSpaceBounds)):(t.shadows&&this.strokeHandler.applyShadows(t.shadows,t.shapes,t.fills,[],this.applyFillSpaceBounds),this.fillHandler.applyFills(t.fills,t.shapes),t.shadows&&this.strokeHandler.applyInnerShadows(t.shadows,t.shapes,t.fills,this.applyFillSpaceBounds))}};import{AssetManager as $m,AudioSink as Ox,ClipStore as Lx,AssetTimeline as Ux,renderSettled as Nx,SETTLE_PASSES as zx,setTheme as Vx,spansCovering as Xm,StateEvaluator as Hx,yieldToScheduler as Wx}from"@motionscript/core";var Ls=class extends Ox{get schedulesAudio(){return!1}has(e){return!0}async append(e,t){}retain(e){}schedule(e){}syncTo(e){}play(e,t,n){}stop(){}};async function Qm({renderContext:r,storageAdapter:e},t,n){await Nx(()=>r.execute(t),e,()=>!0)==="exhausted"&&console.warn(`[export] frame ${n} still had pending decodes after ${zx} renders; it may not be exact.`)}function Ym(r){let e=r.getDecodePolicy();return r.setDecodePolicy("exact"),()=>r.setDecodePolicy(e)}function qx(r){let{fps:e,viewport:t}=r;if(e===void 0||t===void 0)throw new Error("Rendering takes a project whose fps and viewport are resolved \u2014 see Session.");return{fps:e,viewport:t}}function Gx(r,e){if(!r)return{start:0,end:e};let{start:t,end:n}=r;if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<=t||n>e)throw new RangeError(`Frames ${t} to ${n} are not a range inside this timeline's ${e} frames.`);return{start:t,end:n}}function Zm(r){let{project:e,registry:t,assetCatalog:n,renderContext:i}=r,{fps:s,viewport:a}=qx(e),o=()=>Vx(e.theme??r.theme);o();let c=i,l={registry:t,viewport:a,fps:s,assets:n,measurer:c},u={},d=new Lx(e,l,{isReady:p=>u.manager?.isReady(p)??!1}),h=new Ux(e,l,{store:d}),f=new Hx(e,l,d);return{store:d,precomper:h,stateEvaluator:f,measurer:c,fps:s,viewport:a,loads:u,applyTheme:o}}async function Jm(r,e,t){let n=t.flatMap(i=>r.layoutGates(i).filter(s=>!e.isReady(s.src)));n.length>0&&await e.loadRecords(n),r.settleGates(t)}function fu(r){let e=[];for(let t of r.tracks){let n=t.startFrame/r.fps;for(let i of t.audioRequests)e.push({request:i,globalOffset:n})}return e}async function mu(r){let{scale:e=1,sink:t,mixer:n,onProgress:i,signal:s,includeAudio:a=!0}=r,o=r,{renderContext:c,storageAdapter:l}=o;if(r.project.tracks.length===0)return;s?.throwIfAborted(),c.pixelRatio=e;let{store:u,precomper:d,stateEvaluator:h,measurer:f,fps:p,viewport:m,loads:g,applyTheme:y}=Zm(r),b=Ym(l);try{let{start:k,end:T}=Gx(r.frames,d.result().totalFrames),x=r.frames?u.spans.filter(Z=>Z.startFrame<T&&Z.endFrame>=k).map(Z=>Z.id):r.project.tracks.map(Z=>Z.id);if(r.frames)for(let Z of x)u.discover(Z);let v=r.frames?d.result():d.run(),{totalDuration:M}=v,C=T-k;ep(u,v,k,T-1);let _=g.manager=new $m(v,l,new Ls);await Jm(u,_,x);let F=fu(v),E=a&&!r.frames&&F.length>0&&n!==void 0;await t.start({width:m.width*e,height:m.height*e,fps:p,totalFrames:C,hasAudio:E});let O=1/p,Q=0;l.setPlaying(!0);try{for(let Z=k;Z<T;Z++){s?.throwIfAborted(),await _.loadAt(Z),y(),h.stateAt(Z),h.layout(f),await Qm(o,()=>h.render(c),Z),await t.addFrame(Q,O),Q+=O;let ee=Z-k+1;i?.(ee/C*(E?.85:1)),(Z+1)%4===0&&await Wx()}}finally{l.setPlaying(!1)}if(E){let Z=await n.mix(F,M);Z!==null&&t.addAudio&&await t.addAudio(Z),i?.(.97)}let ye=await t.finalize();return i?.(1),ye}finally{b(),h.dispose(),u.dispose()}}var Us=class extends Error{frame;failures;name="NothingToDrawError";constructor(e,t){let n=t.map(i=>` ${i.trackId}: ${i.message}`).join(`
1870
- `);super(`Frame ${e} has nothing to draw \u2014 every track on it failed to build:
1871
- ${n}`),this.frame=e,this.failures=t}};async function pu(r){let{scale:e=1,frame:t,project:n}=r,i=r,{renderContext:s,storageAdapter:a}=i;if(n.tracks.length===0)throw new Error("The project has no tracks to render.");s.pixelRatio=e;let{store:o,precomper:c,stateEvaluator:l,measurer:u,loads:d}=Zm(r),h=Ym(a);try{let{totalFrames:f}=c.result(),p=t.kind==="first"?0:t.kind==="last"?f-1:t.frame,m=Math.max(0,Math.min(f-1,Math.floor(p))),g=c.ensureCovering(m);ep(o,g,m);let y=d.manager=new $m(g,a,new Ls);return await Jm(o,y,Xm(o.spans,m).map(b=>b.id)),await y.loadAt(m),l.stateAt(m),l.layout(u),await Qm(i,()=>l.render(s),m),{frame:m,totalFrames:f}}finally{h(),l.dispose(),o.dispose()}}function ep(r,e,t,n=t){let i=new Map(e.buildErrors.filter(s=>r.failed(s.trackId)).map(s=>[s.trackId,s]));if(i.size!==0)for(let s=t;s<=n;s++){let a=Xm(r.spans,s);if(a.length>0&&a.every(o=>i.has(o.id)))throw new Us(s,a.map(o=>i.get(o.id)))}}var at=null,tp=!0,vi=new Map,Oo=64,Lo=4096;function Kx(r,e){let t=new r.WebGLRenderer({antialias:e,alpha:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!0});return t.setClearColor(0,0),t.setPixelRatio(1),Lo=t.capabilities.maxTextureSize??Lo,t}function rp(r,e){return at&&tp!==e&&(at.dispose(),at.forceContextLoss(),at=null),at||(at=Kx(r,e),tp=e,vi.clear()),at}function jx(r,e,t){let n={width:Math.min(Lo,Math.max(1,Math.ceil(e/Oo)*Oo)),height:Math.min(Lo,Math.max(1,Math.ceil(t/Oo)*Oo))},i=vi.get(r);if(!i)return vi.set(r,n),n;let s={width:Math.max(i.width,n.width),height:Math.max(i.height,n.height)};return(s.width!==i.width||s.height!==i.height)&&vi.set(r,s),s}function $x(r,e,t,n,i,s,a={}){let o=rp(r,a.antialias!==!1),c=jx(e,i,s),l=o.getSize(new r.Vector2);return(l.x!==c.width||l.y!==c.height)&&o.setSize(c.width,c.height,!1),o.render(t,n),{source:o.domElement,width:c.width,height:c.height}}function Xx(r,e){at&&(at.shadowMap.enabled!==e.shadowsEnabled&&(at.shadowMap.enabled=e.shadowsEnabled,at.shadowMap.needsUpdate=!0),at.shadowMap.type!==e.shadowType&&(at.shadowMap.type=e.shadowType,at.shadowMap.needsUpdate=!0),at.toneMapping=e.toneMapping,at.toneMappingExposure=e.toneMappingExposure)}function Qx(){return at}function Yx(){at?.dispose(),at?.forceContextLoss(),at=null,vi.clear()}function Zx(r){vi.delete(r)}var Jx={prepare:(r,e)=>{rp(r,e.antialias!==!1)},render:$x,applySettings:Xx,active:Qx,forgetBuffer:Zx,dispose:Yx};function np(){Al(),Rl(Jx)}var cr=class extends Do{constructor(e,t){super(e,t),np()}mount(e){let t=this.canvasKit.MakeWebGLCanvasSurface(e);if(!t)throw new Error("Failed to create CanvasKit surface");this.attach(t)}unmount(){this.detach()}screenshot(e="image/png",t){let n=this.snapshotPixels();if(!n)return;let{pixels:i,width:s,height:a}=n,o=document.createElement("canvas");o.width=s,o.height=a;let c=o.getContext("2d");if(c)return c.putImageData(new ImageData(new Uint8ClampedArray(i),s,a),0,0),o.toDataURL(e,t)}};import{StorageAdapter as gv}from"@motionscript/core";function w(r){if(!r)throw new Error("Assertion failed.")}var _i=r=>{let e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},ze=r=>r&&r[r.length-1],_r=r=>r>=0&&r<2**32,Y=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},lr=r=>{let e=Y(r);return(e&1)===0?-(e>>1):e+1>>1};var Ye=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),Ae=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),ot=new TextDecoder,_t=new TextEncoder;var ku=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Cr={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Mn=ku(Cr),Pr={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Fn=ku(Pr),Er={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Rn=ku(Er),ip=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,Ci=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r),vt=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(i=>{let s=!1;e=()=>{s||(i(),this.pending--,s=!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},sp=/^[0-9a-fA-F]+$/,sn=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),ap=r=>{w(r.length%2===0);let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},Su=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Ir=(r,e,t)=>{let n=0,i=r.length-1,s=-1;for(;n<=i;){let a=n+i>>1,o=t(r[a]);o===e?(s=a,i=a-1):o<e?n=a+1:i=a-1}return s},_e=(r,e,t)=>{let n=0,i=r.length-1,s=-1;for(;n<=i;){let a=n+(i-n+1)/2|0;t(r[a])<=e?(s=a,n=a+1):i=a-1}return s},xu=(r,e,t)=>{let n=_e(r,t(e),t);r.splice(n+1,0,e)},nt=()=>{let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}},op=(r,e)=>{let t=r.indexOf(e);t!==-1&&r.splice(t,1)},Tu=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Pi=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},cp=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},lp=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},Ct=r=>{throw new Error(`Unexpected value: ${r}`)},Ns=(r,e,t)=>{let n=r.getUint8(e),i=r.getUint8(e+1),s=r.getUint8(e+2);return t?n|i<<8|s<<16:n<<16|i<<8|s};var zs=(r,e,t,n)=>{t=t>>>0,t=t&16777215,n?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},up=(r,e,t,n)=>{t=Ze(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),zs(r,e,t,n)};var Ze=(r,e,t)=>Math.max(e,Math.min(t,r)),Ke="und",Mr=r=>{let e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Vs=(r,e)=>Math.round(r/e)*e,Bn=(r,e)=>Math.round(r*e)/e,No=(r,e)=>Math.floor(r/e)*e,Au=(r,e)=>Math.floor(r*e)/e,dp=r=>{let e=0;for(;r;)e++,r>>=1;return e},eT=/^[a-z]{3}$/,Ei=r=>eT.test(r),ur=1e6*(1+Number.EPSILON),hp=(r,e)=>{let t={...r,...e};if(r.headers||e.headers){let n=r.headers?Uo(r.headers):{},i=e.headers?Uo(e.headers):{},s={...n};Object.entries(i).forEach(([a,o])=>{let c=Object.keys(s).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),t.headers=s}return t},Uo=r=>{if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}if(Array.isArray(r)){let e={};return r.forEach(([t,n])=>{e[t]=n}),e}return r},fp=async(r,e,t,n,i)=>{let s=0;for(;;)try{return await r(e,t)}catch(a){if(i())throw a;s++;let o=n(s,a,e);if(o===null)throw a;if(we._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await Ks(1e3*o),i())throw a}},mp=(r,e)=>{let t=r<0?-1:1;r=Math.abs(r);let n=0,i=1,s=1,a=0,o=r;for(;;){let c=Math.floor(o),l=c*s+n,u=c*a+i;if(u>e)return{num:t*s,den:a};if(n=s,i=a,s=l,a=u,o=1/(o-c),!isFinite(o))break}return{num:t*s,den:a}},nn=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},gu=null,an=()=>gu!==null?gu:gu=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),yu=null,Hs=()=>yu!==null?yu:yu=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),wu=null,Ws=()=>wu!==null?wu:wu=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),bu=null,pp=()=>{if(bu!==null)return bu;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?bu=Number(r[1]):null},Dn=(r,e)=>r!==-1?r:e,zo=(r,e,t,n)=>r<=n&&t<=e,qs=function*(r){for(let e in r){let t=r[e];t!==void 0&&(yield{key:e,value:t})}};var Gs=r=>{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t};var gp=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},Ii=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Mi=r=>typeof r=="number"&&!Number.isNaN(r),dr=(r,e)=>{if(e.includes("://"))return e;if(r.includes("://")){let o=r.indexOf("?");o!==-1&&(r=r.slice(0,o))}let t;if(e.startsWith("/")){let o=r.indexOf("://");if(o===-1)t=e;else{let c=r.indexOf("/",o+3);c===-1?t=r+e:t=r.slice(0,c)+e}}else{let o=r.lastIndexOf("/");o===-1?t=e:t=r.slice(0,o+1)+e}let n="",i=t.indexOf("://");if(i!==-1){let o=t.indexOf("/",i+3);o!==-1&&(n=t.slice(0,o),t=t.slice(o))}let s=t.split("/"),a=[];for(let o of s)o===".."?a.pop():o!=="."&&a.push(o);return n+a.join("/")},On=(r,e)=>{let t=0;for(let n=0;n<r.length;n++)e(r[n])&&t++;return t},Fi=(r,e)=>{let t=-1,n=1/0;for(let i=0;i<r.length;i++){let s=e(r[i]);s<n&&(n=s,t=i)}return t};var Ln=r=>{w(Number.isInteger(r.num)),w(Number.isInteger(r.den)),w(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){let i=e%t;e=t,t=i}let n=e||1;return{num:r.num/n,den:r.den/n}},vu=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};var Ks=r=>new Promise(e=>setTimeout(e,r));var _u=r=>Array.isArray(r)?r:[r],Vt=class{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);let i={fn:t,once:n?.once??!1};return this._listeners.get(e).add(i),()=>{this._listeners.get(e)?.delete(i)}}_emit(...e){let[t,n]=e,i=this._listeners.get(t);if(i)for(let s of i){try{s.fn(n)}catch(a){console.error(a)}s.once&&i.delete(s)}}};var Cu=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");var hr;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(hr||(hr={}));var we=class r{constructor(){}static get level(){return r._level}static set level(e){if(e!==hr.Silent&&e!==hr.Errors&&e!==hr.Warnings&&e!==hr.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");r._level=e}static get _emitter(){return r._emitterInstance??=new Vt}static on(e,t,n){return r._emitter.on(e,t,n)}static _error(...e){r._emitter._emit("error",e),r._level>=hr.Errors&&console.error(...e)}static _warn(...e){r._emitter._emit("warn",e),r._level>=hr.Warnings&&console.warn(...e)}static _info(...e){r._emitter._emit("info",e),r._level>=hr.Info&&console.info(...e)}};we._level=hr.Info;we._emitterInstance=null;var $t=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}},js=class{constructor(e,t,n,i){if(this.data=e,this.mimeType=t,this.name=n,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("description, when provided, must be a string.")}},yp=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof $t)&&!(e instanceof js)&&!Cu(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}};var dt={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},wp=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var Ie=class r{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),i=(t&1<<n)>>n;return this.pos++,i}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let i=this.pos;i<n;i++){let s=Math.floor(i/8),a=this.bytes[s],o=7-(i&7);a&=~(1<<o),a|=(t&1<<n-i-1)>>n-i-1<<o,this.bytes[s]=a}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new r(this.bytes);return e.pos=this.pos,e}};var fr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],on=[-1,1,2,3,4,5,6,8],Ri=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new Ie(r),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let n=e.readBits(4),i=null;n===15?i=e.readBits(24):n<fr.length&&(i=fr[n]);let s=e.readBits(4),a=null;return s>=1&&s<=7&&(a=on[s]),{objectType:t,frequencyIndex:n,sampleRate:i,channelConfiguration:s,numberOfChannels:a}},Vo=r=>{let e=fr.indexOf(r.sampleRate),t=null;e===-1&&(e=15,t=r.sampleRate);let n=on.indexOf(r.numberOfChannels);if(n===-1)throw new TypeError(`Unsupported number of channels: ${r.numberOfChannels}`);let i=13;r.objectType>=32&&(i+=6),e===15&&(i+=24);let s=Math.ceil(i/8),a=new Uint8Array(s),o=new Ie(a);return r.objectType<32?o.writeBits(5,r.objectType):(o.writeBits(5,31),o.writeBits(6,r.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,t),o.writeBits(4,n),a};var gt=["avc","hevc","vp9","av1","vp8"],ht=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Ho=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Ht=[...Ho,...ht],cn=["webvtt"],$s=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],bp=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Fr=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],kp=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Sp=".01.01.01.01.00",xp=".0.110.01.01.01.0",Tp=(r,e,t,n)=>{if(r==="avc"){let s=Math.ceil(e/16)*Math.ceil(t/16),a=$s.find(d=>s<=d.maxMacroblocks&&n<=d.maxBitrate)??ze($s),o=a?a.level:0,c="64".padStart(2,"0"),l="00",u=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(r==="hevc"){let o=e*t,c=bp.find(u=>o<=u.maxPictureSize&&n<=u.maxBitrate)??ze(bp);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){let s=e*t;return`vp09.00.${(Fr.find(c=>s<=c.maxPictureSize&&n<=c.maxBitrate)??ze(Fr)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){let s=e*t,a=kp.find(l=>s<=l.maxPictureSize&&n<=l.maxBitrate)??ze(kp);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${r}'.`)};var Ap=r=>{let e=r.split("."),i=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(s<<5)+o,l=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,h=0,f=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,g=e[5]?Number(e[5][2]):0,y=(l<<7)+(d<<6)+(h<<5)+(f<<4)+(p<<3)+(m<<2)+g;return[i,c,y,0]},Bi=r=>{let{codec:e,codecDescription:t,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o}=r;if(e==="avc"){if(w(r.avcType!==null),i){let c=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${r.avcType}.${sn(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${sn(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,h,f;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,u=Su(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,h=s.generalLevelIdc,f=[...s.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let m=Ae(t),g=m.getUint8(1);c=g>>6&3,l=g&31,u=Su(m.getUint32(2)),d=g>>5&1,h=m.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(m.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=u.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=h;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(m=>m.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let y=r.width*r.height,b=ze(Fr).level;for(let k of Fr)if(y<=k.maxPictureSize){b=k.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}let c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),u=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),f=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),m=a.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${l}.${u}.${d}`;return g+=`.${h}.${f}.${p}.${m}`,g.endsWith(Sp)&&(g=g.slice(0,-Sp.length)),g}else if(e==="av1"){if(!o){let k=r.width*r.height,T=ze(Fr).level;for(let x of Fr)if(k<=x.maxPictureSize){T=x.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=o.profile,l=o.level.toString().padStart(2,"0"),u=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",f=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),p=n?.primaries?Cr[n.primaries]:1,m=n?.transfer?Pr[n.transfer]:1,g=n?.matrix?Er[n.matrix]:1,y=n?.fullRange?1:0,b=`av01.${c}.${l}${u}.${d}`;return b+=`.${h}.${f.toString().padStart(3,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${m.toString().padStart(2,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(xp)&&(b=b.slice(0,-xp.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)},vp=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(ht.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},Di=r=>{let{codec:e,codecDescription:t,aacCodecInfo:n}=r;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");if(n.isMpeg2)return"mp4a.67";{let i;return n.objectType!==null?i=n.objectType:i=Ri(t).objectType,`mp4a.40.${i}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&ht.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)};var Un=48e3,_p=/^pcm-([usf])(\d+)(be)?$/,Wt=r=>{if(w(ht.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=_p.exec(r);w(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let n=Number(e[2])/8,i=e[3]!=="be",s=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:n,littleEndian:i,silentValue:s}},Rr=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":r==="ulaw"?"ulaw":r==="alaw"?"alaw":_p.test(r)?r:r==="webvtt"?"webvtt":null,Cp=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},Pp=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},tT=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],rT=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,nT=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,iT=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,sT=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Ep=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!tT.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!Ci(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=r.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let t=Object.keys(Cr);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);let n=Object.keys(Pr);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let i=Object.keys(Er);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!rT.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!nT.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!iT.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")&&!sT.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},aT=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],Ip=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!aT.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!Ci(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!ht.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ht.join(", ")}).`)},Mp=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var oT=[44100,48e3,32e3],cT=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Wo=1483304551,qo=1231971951,lT=(r,e,t,n,i)=>e===0?0:e===1?Math.floor(144*t/(n<<r))+i:e===2?Math.floor(144*t/n)+i:(Math.floor(12*t/n)+i)*4,Fp=(r,e,t,n)=>e===0?0:e===1?144*t/(n<<r):e===2?144*t/n:12*t/n*4,Go=(r,e)=>r===3?e===3?21:36:e===3?13:21,Qs=(r,e)=>{let t=r>>>24,n=r>>>16&255,i=r>>>8&255,s=r&255;if(t!==255&&n!==255&&i!==255&&s!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;n&16?a=n&8?0:1:(a=1,o=1);let c=n>>3&3,l=n>>1&3,u=i>>4&15,d=(i>>2&3)%3,h=i>>1&1,f=s>>6&3,p=s>>4&3,m=s>>3&1,g=s>>2&1,y=s&3,b=cT[a*16*4+l*16+u];if(b===-1)return{header:null,bytesAdvanced:1};let k=b*1e3,T=oT[d]>>a+o,x=lT(a,l,k,T,h);if(e!==null&&e<x)return{header:null,bytesAdvanced:1};let v;return c===3?v=l===3?384:1152:l===3?v=384:l===2?v=1152:v=576,{header:{totalSize:x,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:k,frequencyIndex:d,sampleRate:T,channel:f,modeExtension:p,copyright:m,original:g,emphasis:y,audioSamplesInFrame:v},bytesAdvanced:1}};var Ko=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t},Xs;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(Xs||(Xs={}));var ln=r=>r===3?1:2;var Nn=[48e3,44100,32e3],Pu=[24e3,22050,16e3];var lt;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(lt||(lt={}));var it;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(it||(it={}));var Oi=function*(r){let e=0,t=-1;for(;e<r.length-2;){let n=r.indexOf(0,e);if(n===-1||n>=r.length-2)break;e=n;let i=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?i=4:r[e+1]===0&&r[e+2]===1&&(i=3),i===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+i,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},Dp=function*(r,e){let t=0,n=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let i;e===1?i=n.getUint8(t):e===2?i=n.getUint16(t,!1):e===3?i=Ns(n,t,!1):(w(e===4),i=n.getUint32(t,!1)),t+=e,yield{offset:t,length:i},t+=i}},Iu=(r,e)=>{if(e.description){let i=(Ye(e.description)[4]&3)+1;return Dp(r,i)}else return Oi(r)},Li=r=>r&31,jo=r=>{let e=[],t=r.length;for(let n=0;n<t;n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e.push(0,0),n+=2):e.push(r[n]);return new Uint8Array(e)},Eu=new Uint8Array([0,0,0,1]),Op=r=>{let e=r.reduce((i,s)=>i+Eu.byteLength+s.byteLength,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(Eu,n),n+=Eu.byteLength,t.set(i,n),n+=i.byteLength;return t},$o=(r,e)=>{let t=r.reduce((s,a)=>s+e+a.byteLength,0),n=new Uint8Array(t),i=0;for(let s of r){let a=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:a.setUint8(i,s.byteLength);break;case 2:a.setUint16(i,s.byteLength,!1);break;case 3:zs(a,i,s.byteLength,!1);break;case 4:a.setUint32(i,s.byteLength,!1);break}i+=e,n.set(s,i),i+=s.byteLength}return n},Lp=(r,e)=>{if(e.description){let i=(Ye(e.description)[4]&3)+1;return $o(r,i)}else return Op(r)},Ui=r=>{try{let e=[],t=[],n=[];for(let o of Oi(r)){let c=r.subarray(o.offset,o.offset+o.length),l=Li(c[0]);l===lt.SPS?e.push(c):l===lt.PPS?t.push(c):l===lt.SPS_EXT&&n.push(c)}if(e.length===0||t.length===0)return null;let i=e[0],s=Zs(i);w(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(e){return we._error("Error building AVC Decoder Configuration Record:",e),null}},Up=r=>{let e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(let t of r.sequenceParameterSets){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}e.push(r.pictureParameterSets.length);for(let t of r.pictureParameterSets){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}if(r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144){w(r.chromaFormat!==null),w(r.bitDepthLumaMinus8!==null),w(r.bitDepthChromaMinus8!==null),w(r.sequenceParameterSetExt!==null),e.push(252|r.chromaFormat&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.sequenceParameterSetExt.length);for(let t of r.sequenceParameterSetExt){let n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}}return new Uint8Array(e)},Np=r=>{try{let e=Ae(r),t=0,n=e.getUint8(t++),i=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let f=0;f<c;f++){let p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}let u=e.getUint8(t++),d=[];for(let f=0;f<u;f++){let p=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+p)),t+=p}let h={configurationVersion:n,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&t+4<=r.length){let f=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,g=e.getUint8(t++);h.chromaFormat=f,h.bitDepthLumaMinus8=p,h.bitDepthChromaMinus8=m;let y=[];for(let b=0;b<g;b++){let k=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+k)),t+=k}h.sequenceParameterSetExt=y}return h}catch(e){return we._error("Error deserializing AVC Decoder Configuration Record:",e),null}},zp={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Zs=r=>{try{let e=new Ie(jo(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();Y(e);let a=1,o=0,c=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=Y(e),a===3&&(l=e.readBits(1)),o=Y(e),c=Y(e),e.skipBits(1),e.readBits(1))){for(let O=0;O<(a!==3?8:12);O++)if(e.readBits(1)){let ye=O<6?16:64,Z=8,ee=8;for(let ve=0;ve<ye;ve++){if(ee!==0){let Re=lr(e);ee=(Z+Re+256)%256}Z=ee===0?Z:ee}}}Y(e);let u=Y(e);if(u===0)Y(e);else if(u===1){e.skipBits(1),lr(e),lr(e);let E=Y(e);for(let O=0;O<E;O++)lr(e)}Y(e),e.skipBits(1);let d=Y(e),h=Y(e),f=16*(d+1),p=16*(h+1),m=f,g=p,y=e.readBits(1);if(y||e.skipBits(1),e.skipBits(1),e.readBits(1)){let E=Y(e),O=Y(e),Q=Y(e),ye=Y(e),Z,ee;if((l===0?a:0)===0)Z=1,ee=2-y;else{let Re=a===3?1:2,et=a===1?2:1;Z=Re,ee=et*(2-y)}m-=Z*(E+O),g-=ee*(Q+ye)}let k=2,T=2,x=2,v=0,M={num:1,den:1},C=null,_=null;if(e.readBits(1)){if(e.readBits(1)){let et=e.readBits(8);if(et===255)M={num:e.readBits(16),den:e.readBits(16)};else{let Ra=zp[et];Ra&&(M=Ra)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),v=e.readBits(1),e.readBits(1)&&(k=e.readBits(8),T=e.readBits(8),x=e.readBits(8))),e.readBits(1)&&(Y(e),Y(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let ee=e.readBits(1);ee&&Rp(e);let ve=e.readBits(1);ve&&Rp(e),(ee||ve)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),Y(e),Y(e),Y(e),Y(e),C=Y(e),_=Y(e))}if(C===null){w(_===null);let E=i&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&E)C=0,_=0;else{let O=d+1,Q=h+1,ye=(2-y)*Q,Z=$s.find(ve=>ve.level>=s)??ze($s),ee=Math.min(Math.floor(Z.maxDpbMbs/(O*ye)),16);C=ee,_=ee}}return w(_!==null),{profileIdc:n,constraintFlags:i,levelIdc:s,frameMbsOnlyFlag:y,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:g,pixelAspectRatio:M,colourPrimaries:k,matrixCoefficients:x,transferCharacteristics:T,fullRangeFlag:v,numReorderFrames:C,maxDecFrameBuffering:_}}catch(e){return we._error("Error parsing AVC SPS:",e),null}},Rp=r=>{let e=Y(r);r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)Y(r),Y(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},uT=(r,e)=>{if(e.description){let i=(Ye(e.description)[21]&3)+1;return $o(r,i)}else return Op(r)},Ys=(r,e)=>{if(e.description){let i=(Ye(e.description)[21]&3)+1;return Dp(r,i)}else return Oi(r)},un=r=>r>>1&63,Mu=r=>{try{let e=new Ie(jo(r));e.skipBits(16),e.readBits(4);let t=e.readBits(3),n=e.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=dT(e,t);Y(e);let u=Y(e),d=0;u===3&&(d=e.readBits(1));let h=Y(e),f=Y(e),p=h,m=f;if(e.readBits(1)){let O=Y(e),Q=Y(e),ye=Y(e),Z=Y(e),ee=1,ve=1,Re=d===0?u:0;Re===1?(ee=2,ve=2):Re===2&&(ee=2,ve=1),p-=(O+Q)*ee,m-=(ye+Z)*ve}let g=Y(e),y=Y(e);Y(e);let k=e.readBits(1)?0:t,T=0;for(let O=k;O<=t;O++)Y(e),T=Y(e),Y(e);Y(e),Y(e),Y(e),Y(e),Y(e),Y(e),e.readBits(1)&&e.readBits(1)&&hT(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),Y(e),Y(e),e.skipBits(1));let x=Y(e);if(fT(e,x),e.readBits(1)){let O=Y(e);for(let Q=0;Q<O;Q++)Y(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let v=2,M=2,C=2,_=0,F=0,E={num:1,den:1};if(e.readBits(1)){let O=pT(e,t);E=O.pixelAspectRatio,v=O.colourPrimaries,M=O.transferCharacteristics,C=O.matrixCoefficients,_=O.fullRangeFlag,F=O.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:E,colourPrimaries:v,transferCharacteristics:M,matrixCoefficients:C,fullRangeFlag:_,maxDecFrameBuffering:T+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:F}}catch(e){return we._error("Error parsing HEVC SPS:",e),null}},Ni=r=>{try{let e=[],t=[],n=[],i=[];for(let l of Oi(r)){let u=r.subarray(l.offset,l.offset+l.length),d=un(u[0]);d===it.VPS_NUT?e.push(u):d===it.SPS_NUT?t.push(u):d===it.PPS_NUT?n.push(u):(d===it.PREFIX_SEI_NUT||d===it.SUFFIX_SEI_NUT)&&i.push(u)}if(t.length===0||n.length===0)return null;let s=Mu(t[0]);if(!s)return null;let a=0;if(n.length>0){let l=n[0],u=new Ie(jo(l));u.skipBits(16),Y(u),Y(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),Y(u),Y(u),lr(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&Y(u),lr(u),lr(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);let d=u.readBits(1),h=u.readBits(1);!d&&!h?a=0:d&&!h?a=2:!d&&h?a=3:a=0}let o=[...e.length?[{arrayCompleteness:1,nalUnitType:it.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:it.SPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:it.PPS_NUT,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:un(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return we._error("Error building HEVC Decoder Configuration Record:",e),null}},dT=(r,e)=>{let t=r.readBits(2),n=r.readBits(1),i=r.readBits(5),s=0;for(let u=0;u<32;u++)s=s<<1|r.readBits(1);let a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);let o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},hT=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))Y(r);else{let i=Math.min(64,1<<4+(e<<1));e>1&&lr(r);for(let s=0;s<i;s++)lr(r)}},fT=(r,e)=>{let t=[];for(let n=0;n<e;n++)t[n]=mT(r,n,e,t)},mT=(r,e,t,n)=>{let i=0,s=0,a=0;if(e!==0&&(s=r.readBits(1)),s){if(e===t){let c=Y(r);a=e-(c+1)}else a=e-1;r.readBits(1),Y(r);let o=n[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);i=n[a]}else{let o=Y(r),c=Y(r);for(let l=0;l<o;l++)Y(r),r.readBits(1);for(let l=0;l<c;l++)Y(r),r.readBits(1);i=o+c}return i},pT=(r,e)=>{let t=2,n=2,i=2,s=0,a=0,o={num:1,den:1};if(r.readBits(1)){let c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{let l=zp[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),s=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),n=r.readBits(8),i=r.readBits(8))),r.readBits(1)&&(Y(r),Y(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(Y(r),Y(r),Y(r),Y(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&Y(r),r.readBits(1)&&gT(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=Y(r),Y(r),Y(r),Y(r),Y(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},gT=(r,e,t)=>{let n=!1,i=!1,s=!1;e&&(n=r.readBits(1)===1,i=r.readBits(1)===1,(n||i)&&(s=r.readBits(1)===1,s&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),s&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let a=0;a<=t;a++){let o=r.readBits(1)===1,c=!0;o||(c=r.readBits(1)===1);let l=!1;c?Y(r):l=r.readBits(1)===1;let u=1;l||(u=Y(r)+1),n&&Bp(r,u,s),i&&Bp(r,u,s)}},Bp=(r,e,t)=>{for(let n=0;n<e;n++)Y(r),Y(r),t&&(Y(r),Y(r)),r.readBits(1)},Vp=r=>{let e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(let t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(let n of t.nalUnits){e.push(n.length>>8&255),e.push(n.length&255);for(let i=0;i<n.length;i++)e.push(n[i])}}return new Uint8Array(e)};var pt;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(pt||(pt={}));var Hp=(r,e)=>{let t=new Set,n=pt.audAllowed;for(let s of Ys(r,e)){if(n===pt.noMoreDataAllowed){t.add(s.offset);continue}let a=un(r[s.offset]);if(n===pt.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?n>pt.audAllowed?o=!0:n=pt.beforeFirstVcl:a<=31?n>pt.afterFirstVcl?o=!0:n=pt.afterFirstVcl:a===36?n!==pt.afterFirstVcl?o=!0:n=pt.eoBitstreamAllowed:a===37?n<pt.afterFirstVcl?o=!0:n=pt.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?n>pt.beforeFirstVcl?o=!0:n=pt.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&n<pt.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;let i=[];for(let s of Ys(r,e))t.has(s.offset)||i.push(r.subarray(s.offset,s.offset+s.length));return uT(i,e)},Xo=r=>{let e=new Ie(r);if(e.readBits(2)!==2)return null;let n=e.readBits(1),s=(e.readBits(1)<<1)+n;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=e.readBits(1)?12:10);let u=e.readBits(3),d=0,h=0;if(u!==7)if(h=e.readBits(1),s===1||s===3){let M=e.readBits(1),C=e.readBits(1);d=!M&&!C?3:M&&!C?2:1,e.skipBits(1)}else d=1;else d=3,h=1;let f=e.readBits(16),p=e.readBits(16),m=f+1,g=p+1,y=m*g,b=ze(Fr).level;for(let v of Fr)if(y<=v.maxPictureSize){b=v.level;break}return{profile:s,level:b,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Wp=function*(r){let e=new Ie(r),t=()=>{let n=0;for(let i=0;i<8;i++){let s=e.readAlignedByte();if(n|=(s&127)<<i*7,!(s&128))break;if(i===7&&s&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),i=e.readBits(1),s=e.readBits(1);e.skipBits(1),i&&e.skipBits(8);let a;if(s){let o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);w(e.pos%8===0),yield{type:n,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Qo=r=>{for(let{type:e,data:t}of Wp(r)){if(e!==1)continue;let n=new Ie(t),i=n.readBits(3),s=n.readBits(1),a=n.readBits(1),o=0,c=0,l=0;if(a)o=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let v=n.readBits(1);v&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let M=n.readBits(5);for(let C=0;C<=M;C++){n.skipBits(12);let _=n.readBits(5);if(C===0&&(o=_),_>7){let E=n.readBits(1);C===0&&(c=E)}if(v&&n.readBits(1)){let O=l+1;n.skipBits(O),n.skipBits(O),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let u=n.readBits(4),d=n.readBits(4),h=u+1;n.skipBits(h);let f=d+1;n.skipBits(f);let p=0;if(a?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!a){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let x=n.readBits(1);x&&(n.skipBits(1),n.skipBits(1));let v=n.readBits(1),M=0;v?M=2:M=n.readBits(1),M>0&&(n.readBits(1)||n.skipBits(1)),x&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let m=n.readBits(1),g=8;i===2&&m?g=n.readBits(1)?12:10:i<=2&&(g=m?10:8);let y=0;i!==1&&(y=n.readBits(1));let b=1,k=1,T=0;return y||(i===0?(b=1,k=1):i===1?(b=0,k=0):g===12&&(b=n.readBits(1),b&&(k=n.readBits(1))),b&&k&&(T=n.readBits(2))),{profile:i,level:o,tier:c,bitDepth:g,monochrome:y,chromaSubsamplingX:b,chromaSubsamplingY:k,chromaSamplePosition:T}}return null},Yo=r=>{let e=Ae(r),t=e.getUint8(9),n=e.getUint16(10,!0),i=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18),o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:n,inputSampleRate:i,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},yT=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],qp=r=>{let e=r[0]>>3;return{durationInSamples:yT[e]}},Gp=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=r.length,n=new Uint8Array(t);for(let d=0;d<t;d++)n[d]=r[t-1-d];let i=new Ie(n),s=0;for(;i.getBitsLeft()>97;)if(i.readBits(1)===1){s=i.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;i.getBitsLeft()>=97;){let d=i.pos,h=i.readBits(8),f=i.readBits(16),p=i.readBits(16);if(h>63||f!==0||p!==0){i.pos=d;break}if(i.skipBits(1),a++,a>64)break;i.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;i.pos=0,i.skipBits(s);let u=Array(l).fill(0);for(let d=l-1;d>=0;d--)i.skipBits(40),u[d]=i.readBits(1);return{modeBlockflags:u}},hn=(r,e,t)=>{switch(r){case"avc":{for(let n of Iu(t,e)){let i=t[n.offset],s=Li(i);if(s>=lt.NON_IDR_SLICE&&s<=lt.SLICE_DPC)return"delta";if(s===lt.IDR)return"key";if(s===lt.SEI&&(!Ws()||pp()>=144)){let a=t.subarray(n.offset,n.offset+n.length),o=jo(a),c=1;do{let l=0;for(;;){let h=o[c++];if(h===void 0||(l+=h,h<255))break}let u=0;for(;;){let h=o[c++];if(h===void 0||(u+=h,h<255))break}if(l===6){let h=new Ie(o);h.pos=8*c;let f=Y(h),p=h.readBits(1);if(f===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(let n of Ys(t,e)){let i=un(t[n.offset]);if(i<it.BLA_W_LP)return"delta";if(i<=it.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let n=new Ie(t);if(n.readBits(2)!==2)return null;let i=n.readBits(1);return(n.readBits(1)<<1)+i===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:i,data:s}of Wp(t))if(i===1){let a=new Ie(s);a.skipBits(4),n=!!a.readBits(1)}else if(i===3||i===6||i===7){if(n)return"key";let a=new Ie(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:Ct(r),w(!1)}},dn;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(dn||(dn={}));var Js=(r,e)=>{let t=Ae(r),n=0,i=t.getUint32(n,!0);n+=4;let s=ot.decode(r.subarray(n,n+i));n+=i,i>0&&(e.raw??={},e.raw.vendor??=s);let a=t.getUint32(n,!0);n+=4;for(let o=0;o<a;o++){let c=t.getUint32(n,!0);n+=4;let l=ot.decode(r.subarray(n,n+c));n+=c;let u=l.indexOf("=");if(u===-1)continue;let d=l.slice(0,u).toUpperCase(),h=l.slice(u+1);switch(e.raw??={},e.raw[d]??=h,d){case"TITLE":e.title??=h;break;case"DESCRIPTION":e.description??=h;break;case"ARTIST":e.artist??=h;break;case"ALBUM":e.album??=h;break;case"ALBUMARTIST":e.albumArtist??=h;break;case"COMMENT":e.comment??=h;break;case"LYRICS":e.lyrics??=h;break;case"TRACKNUMBER":{let f=h.split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"TRACKTOTAL":{let f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{let f=h.split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DISCTOTAL":{let f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{let f=new Date(h);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=h;break;case"METADATA_BLOCK_PICTURE":{let f=Gs(h),p=Ae(f),m=p.getUint32(0,!1),g=p.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+g)),b=p.getUint32(8+g,!1),k=ot.decode(f.subarray(12+g,12+g+b)),T=p.getUint32(g+b+28),x=f.subarray(g+b+32,g+b+32+T);e.images??=[],e.images.push({data:x,mimeType:y,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:k||void 0})}break}}};var ea=[2,1,2,3,3,4,4,5],Zo=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;let e=new Ie(r);e.skipBits(16),e.skipBits(16);let t=e.readBits(2);if(t===3)return null;let n=e.readBits(6),i=e.readBits(5);if(i>8)return null;let s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);let o=e.readBits(1),c=Math.floor(n/2);return{fscod:t,bsid:i,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},Kp=[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],jp=1536,gM=new Uint8Array([5,4,65,67,45,51]),yM=new Uint8Array([5,4,69,65,67,51]),Fu=[1,2,3,6],Jo=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;let e=new Ie(r);e.skipBits(16);let t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;let n=e.readBits(11),i=e.readBits(2),s=0,a;i===3?(s=e.readBits(2),a=3):a=e.readBits(2);let o=e.readBits(3),c=e.readBits(1),l=e.readBits(5);if(l<11||l>16)return null;let u=Fu[a],d;return i<3?d=Nn[i]/1e3:d=Pu[s]/1e3,{dataRate:Math.round((n+1)*d/(u*16)),substreams:[{fscod:i,fscod2:s,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},$p=r=>{if(r.length<2)return null;let e=new Ie(r),t=e.readBits(13),n=e.readBits(3),i=[];for(let s=0;s<=n&&!(Math.ceil(e.pos/8)+3>r.length);s++){let a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);let c=e.readBits(3),l=e.readBits(3),u=e.readBits(1);e.skipBits(3);let d=e.readBits(4),h=0;d>0?h=e.readBits(9):e.skipBits(1),i.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:h})}return i.length===0?null:{dataRate:t,substreams:i}},ec=r=>{let e=r.substreams[0];return w(e),e.fscod<3?Nn[e.fscod]:e.fscod2!==null&&e.fscod2<3?Pu[e.fscod2]:null},tc=r=>{let e=r.substreams[0];w(e);let t=ea[e.acmod]+e.lfeon;if(e.numDepSub>0){let n=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)e.chanLoc&1<<8-i&&(t+=n[i])}return t};var ct=class{constructor(e){this.input=e}dispose(){}};var st=new Uint8Array(0),Oe=class r{constructor(e,t,n,i,s=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=i,this.sequenceNumber=s,e===st&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===st}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new r(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new r(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}};var rc=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings)];t+=`; codecs="${n.join(", ")}"`}return t},nc=r=>{let e=Ae(r),t=0,n=e.getUint8(t);t+=1,t+=3;let i=sn(r.subarray(t,t+16));t+=16;let s=null;if(n>0){let o=e.getUint32(t);if(t+=4,o>0){s=[];for(let c=0;c<o;c++)s.push(sn(r.subarray(t,t+16))),t+=16}}let a=e.getUint32(t);return t+=4,{systemId:i,keyIds:s,data:r.slice(t,t+a)}},ic=(r,e)=>r.systemId===e.systemId&&gp(r.data,e.data);var Xt=8,Br=16,Dr=r=>{let e=j(r),t=We(r,4),n=8;e===1&&(e=Pt(r),n=16);let s=e-n;return s<0?null:{name:t,totalSize:e,headerSize:n,contentSize:s}},fn=r=>Or(r)/65536,sc=r=>Or(r)/1073741824,ac=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;let n=ce(r);if(e|=n&127,(n&128)===0)break}return e},Qt=r=>{let e=je(r);return r.skip(2),e=Math.min(e,r.remainingLength),ot.decode(ie(r,e))},Xp=r=>{let e=Dr(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;let t=j(r);r.skip(4);let n=ie(r,e.contentSize-8);switch(t){case 1:return ot.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new $t(n,"image/jpeg");case 14:return new $t(n,"image/png");case 27:return new $t(n,"image/bmp");default:return n}};var Yt=16,Lr=new Uint32Array(256),zi=new Uint32Array(256),Vi=new Uint32Array(256),Hi=new Uint32Array(256),Wi=new Uint32Array(256),ft=new Uint32Array(256),Qp=new Uint32Array(10),Yp=!1,wT=()=>{let r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let s=0,a=1;s<256;s++)t[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);let n=(s,a)=>s&&a?t[(e[s]+e[a])%255]:0;r[0]=99;for(let s=1;s<256;s++){let a=t[255-e[s]],o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[s]=o}for(let s=0;s<256;s++){let a=r[s],o=r.indexOf(s);Lr[s]=a<<24|a<<16|a<<8|a,ft[s]=o<<24|o<<16|o<<8|o;let c=n(o,14),l=n(o,9),u=n(o,13),d=n(o,11),h=c<<24|l<<16|u<<8|d;zi[s]=h,Vi[s]=h>>>8|h<<24,Hi[s]=h>>>16|h<<16,Wi[s]=h>>>24|h<<8}let i=1;for(let s=0;s<10;s++)Qp[s]=i<<24,i=i<<1^(i&128?283:0);Yp=!0},ta=class{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Yt/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Yt),this.out=new Uint8Array(Yt),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){w(e.byteLength===16),w(t.byteLength===16),Yp||wT();let n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let s=4;s<44;s+=4){let a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^Lr[a>>>16&255]&4278190080^Lr[a>>>8&255]&16711680^Lr[a>>>0&255]&65280^Lr[a>>>24&255]&255^Qp[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){let c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){let o=this.roundkey[s+a];this.roundkey[s+a]=zi[Lr[o>>>24&255]&255]^Vi[Lr[o>>>16&255]&255]^Hi[Lr[o>>>8&255]&255]^Wi[Lr[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],i=this.inView.getUint32(12,!1)^this.roundkey[3],s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1),l,u,d,h;for(let y=1;y<10;y++){let b=y*4;l=zi[e>>>24]^Vi[i>>>16&255]^Hi[n>>>8&255]^Wi[t&255]^this.roundkey[b],u=zi[t>>>24]^Vi[e>>>16&255]^Hi[i>>>8&255]^Wi[n&255]^this.roundkey[b+1],d=zi[n>>>24]^Vi[t>>>16&255]^Hi[e>>>8&255]^Wi[i&255]^this.roundkey[b+2],h=zi[i>>>24]^Vi[n>>>16&255]^Hi[t>>>8&255]^Wi[e&255]^this.roundkey[b+3],e=l,t=u,n=d,i=h}let f=ft[e>>>24&255]&4278190080^ft[i>>>16&255]&16711680^ft[n>>>8&255]&65280^ft[t>>>0&255]&255^this.roundkey[40],p=ft[t>>>24&255]&4278190080^ft[e>>>16&255]&16711680^ft[i>>>8&255]&65280^ft[n>>>0&255]&255^this.roundkey[41],m=ft[n>>>24&255]&4278190080^ft[t>>>16&255]&16711680^ft[e>>>8&255]&65280^ft[i>>>0&255]&255^this.roundkey[42],g=ft[i>>>24&255]&4278190080^ft[n>>>16&255]&16711680^ft[t>>>8&255]&65280^ft[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,g^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}},Zp=(r,e,t)=>{let n=!1,i=0,s=2**16,a=16,o=new ta;return new ReadableStream({pull:async c=>{n||(o.init(await e()),n=!0);let l=s+a,u=r.requestSliceRange(i,0,l);if(u instanceof Promise&&(u=await u),!u||u.length===0)throw new Error("Invalid ciphertext.");let d=u.length;if(d%16!==0)throw new Error("Invalid ciphertext.");let h=d===l?d-a:d,f=ie(u,h),p=new Uint8Array(h);for(let m=0;m<h;m+=16)o.in.set(f.subarray(m,m+16)),o.decrypt(),p.set(o.out,m);if(h<d)c.enqueue(p),i+=h;else{let m=p[h-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let g=p.subarray(0,h-m);c.enqueue(g),c.close(),t()}},cancel:()=>{t()}})};var oc=class r extends ct{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(n=>n.getDecoderConfig().then(i=>i?.codec??null)));return rc({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(n=>n.info?.type==="video"),hasAudio:this.tracks.some(n=>n.info?.type==="audio"),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1;for(;;){let n=this.reader.requestSliceRange(e,Xt,Br);if(n instanceof Promise&&(n=await n),!n)break;let i=e,s=Dr(n);if(!s)break;if(s.name==="ftyp"||s.name==="styp"){let a=We(n,4);this.isQuickTime=a==="qt "}else if(s.name==="moov"){let a=this.reader.requestSlice(n.filePos,s.contentSize);if(a instanceof Promise&&(a=await a),!a)break;this.moovSlice=a,this.readContiguousBoxes(this.moovSlice);for(let o of this.tracks){let c=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(c*o.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+s.totalSize;break}else if(s.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');let a=await this.input._initInput._getDemuxer();if(a.constructor!==r)throw new Error("Init input must match the input's format.");await a.readMetadata(),this.movieTimescale=a.movieTimescale,this.movieDurationInTimescale=a.movieDurationInTimescale,this.metadataTags=a.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=a.fragmentTrackDefaults,this.psshBoxes=a.psshBoxes;for(let o of a.tracks){let c={id:o.id,demuxer:this,trackBacking:null,disposition:o.disposition,timescale:o.timescale,durationInMediaTimescale:o.durationInMediaTimescale,durationInMovieTimescale:o.durationInMovieTimescale,rotation:o.rotation,internalCodecId:o.internalCodecId,name:o.name,languageCode:o.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:o.editListPreviousSegmentDurations,editListOffset:o.editListOffset,encryptionInfo:o.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:o.info};if(o.trackBacking){if(w(c.info),c.info.type==="video"&&c.info.width!==-1){let l=c;c.trackBacking=new lc(l),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){let l=c;c.trackBacking=new uc(l),this.tracks.push(c)}}}t=!1;break}e=i+s.totalSize}if(t){w(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);n instanceof Promise&&(n=await n),w(n);let i=j(n),s=this.reader.fileSize-i;if(s>=0&&s<=this.reader.fileSize-Br){let a=this.reader.requestSliceRange(s,Xt,Br);if(a instanceof Promise&&(a=await a),a){let o=Dr(a);if(o&&o.name==="mfra"){let c=this.reader.requestSlice(a.filePos,o.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;w(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ht.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){w(e.info?.type==="audio");let s=Wt(e.info.codec),a=[],o=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],d=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let h=0;h<d;h++){let f=l.startSampleIndex+h*l.samplesPerChunk,p=f+l.samplesPerChunk,m=_e(t.sampleTimingEntries,f,C=>C.startIndex),g=t.sampleTimingEntries[m],y=_e(t.sampleTimingEntries,p,C=>C.startIndex),b=t.sampleTimingEntries[y],k=g.startDecodeTimestamp+(f-g.startIndex)*g.delta,x=b.startDecodeTimestamp+(p-b.startIndex)*b.delta-k,v=ze(a);v&&v.delta===x?v.count++:a.push({startIndex:l.startChunkIndex+h,startDecodeTimestamp:k,count:1,delta:x});let M=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(M)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let s of t.sampleTimingEntries)for(let a=0;a<s.count;a++)t.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(let s of t.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){let o=s.startIndex+a,c=t.presentationTimestamps[o];c&&(c.presentationTimestamp+=s.offset)}t.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let s=0;s<t.presentationTimestamps.length;s++)t.presentationTimestampIndexMap[t.presentationTimestamps[s].sampleIndex]=s}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,Xt,Br);t instanceof Promise&&(t=await t),w(t);let n=Dr(t);w(n?.name==="moof");let i=this.reader.requestSlice(e,n.totalSize);i instanceof Promise&&(i=await i),w(i),this.traverseBox(i);let s=this.lastReadFragment;w(s&&s.moofOffset===e);for(let[,a]of s.trackData){let o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){let u=o.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(u)Ru(a,u.timestamp);else{let d=_e(c,s.moofOffset-1,h=>h.moofOffset);if(d!==-1){let h=c[d];Ru(a,h.endTimestamp)}}a.startTimestampIsFinal=!0}let l=_e(c,a.startTimestamp,u=>u.startTimestamp);if((l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){let u=await rg(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let d=0;d<Math.min(a.samples.length,u.length);d++){let h=u[d];a.samples[d].encryption=h}}}return s}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Xt&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Xt;){let n=e.filePos,i=Dr(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=n+i.totalSize}}traverseBox(e){let t=e.filePos,n=Dr(e);if(!n)return!1;let i=e.filePos,s=t+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mvhd":{let a=ce(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=j(e),this.movieDurationInTimescale=Pt(e)):(e.skip(8),this.movieTimescale=j(e),this.movieDurationInTimescale=j(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:Ke,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(i,n.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){let o=a;a.trackBacking=new lc(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let o=a;a.trackBacking=new uc(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{let a=this.currentTrack;if(!a)break;let o=ce(e),l=!!(Zt(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=j(e),e.skip(4),a.durationInMovieTimescale=j(e);else if(o===1)e.skip(16),a.id=j(e),e.skip(4),a.durationInMovieTimescale=Pt(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);let u=[fn(e),fn(e),sc(e),fn(e),fn(e),sc(e),fn(e),fn(e),sc(e)],d=_i(Vs(xT(u),90));w(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{let a=this.currentTrack;if(!a)break;let o=ce(e);e.skip(3);let c=!1,l=0,u=j(e);for(let d=0;d<u;d++){let h=o===1?Pt(e):j(e),f=o===1?ig(e):Or(e),p=fn(e);if(h!==0){if(c){we._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=h;continue}if(p!==1){we._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=l,a.editListOffset=f,c=!0}}}break;case"mdhd":{let a=this.currentTrack;if(!a)break;let o=ce(e);e.skip(3),o===0?(e.skip(8),a.timescale=j(e),a.durationInMediaTimescale=j(e)):o===1&&(e.skip(16),a.timescale=j(e),a.durationInMediaTimescale=Pt(e));let c=je(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;Ei(a.languageCode)||(a.languageCode=Ke)}}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=j(e);for(let l=0;l<c;l++){let u=e.filePos,d=Dr(e);if(!d)break;a.internalCodecId=d.name;let h=d.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=je(e),a.info.height=je(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));let f=h==="encv"?a.frmaCodecString:h;a.frmaCodecString=null,f==="avc1"||f==="avc3"?(a.info.codec="avc",a.info.avcType=f==="avc1"?1:3):f==="hvc1"||f==="hev1"?a.info.codec="hevc":f==="vp08"?a.info.codec="vp8":f==="vp09"?a.info.codec="vp9":f==="av01"?a.info.codec="av1":f===null?we._warn("Unknown encrypted video codec due to missing frma box."):we._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{e.skip(8);let f=je(e);e.skip(6);let p=je(e),m=je(e);e.skip(4);let g=j(e)/65536,y=null;o===0&&f>0&&(f===1?(e.skip(4),m=8*j(e),e.skip(8)):f===2&&(e.skip(4),g=dc(e),p=j(e),e.skip(4),m=j(e),y=j(e),e.skip(8))),a.info.numberOfChannels=p,a.info.sampleRate=g,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));let b=h==="enca"?a.frmaCodecString:h;if(a.frmaCodecString=null,b!=="mp4a")if(b==="opus")a.info.codec="opus",a.info.sampleRate=Un;else if(b==="flac")a.info.codec="flac";else if(b==="ulaw")a.info.codec="ulaw";else if(b==="alaw")a.info.codec="alaw";else if(b==="ac-3")a.info.codec="ac3";else if(b==="ec-3")a.info.codec="eac3";else if(b==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(we._warn(`Unsupported sample size ${m} for codec 'twos'.`),a.info.codec=null);else if(b==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(we._warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(b==="raw ")a.info.codec="pcm-u8";else if(b==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(b==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(b==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(b==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(b==="ipcm"){let k=a.info.pcmSampleSize;a.info.pcmLittleEndian?k===16?a.info.codec="pcm-s16":k===24?a.info.codec="pcm-s24":k===32?a.info.codec="pcm-s32":(we._warn(`Invalid ipcm sample size ${k}.`),a.info.codec=null):k===16?a.info.codec="pcm-s16be":k===24?a.info.codec="pcm-s24be":k===32?a.info.codec="pcm-s32be":(we._warn(`Invalid ipcm sample size ${k}.`),a.info.codec=null)}else if(b==="fpcm"){let k=a.info.pcmSampleSize;a.info.pcmLittleEndian?k===32?a.info.codec="pcm-f32":k===64?a.info.codec="pcm-f64":(we._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null):k===32?a.info.codec="pcm-f32be":k===64?a.info.codec="pcm-f64be":(we._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null)}else if(b==="lpcm"&&y!==null){let k=m+7>>3,T=!!(y&1),x=!!(y&2),v=y&4?-1:0;m>0&&m<=64&&(T?m===32&&(a.info.codec=x?"pcm-f32be":"pcm-f32"):v&1<<k-1?k===1?a.info.codec="pcm-s8":k===2?a.info.codec=x?"pcm-s16be":"pcm-s16":k===3?a.info.codec=x?"pcm-s24be":"pcm-s24":k===4&&(a.info.codec=x?"pcm-s32be":"pcm-s32"):k===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&we._warn("Unsupported PCM format.")}else b===null?we._warn("Unknown encrypted audio codec due to missing frma box."):we._warn(`Unsupported audio codec (sample entry type '${d.name}').`)}e.filePos=u+d.totalSize}}break;case"frma":{let a=this.currentTrack;if(!a)break;let c=We(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{let a=this.currentTrack;if(!a)break;e.skip(4);let o=We(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:we._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;let o=ce(e);e.skip(3),e.skip(1);let c=ce(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=ce(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=ce(e),a.encryptionInfo.defaultKid=sn(ie(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){let l=ce(e),u=new Uint8Array(16);u.set(ie(e,l),0),a.encryptionInfo.defaultConstantIv=u}}break;case"avcC":{let a=this.currentTrack;if(!a)break;w(a.info),a.info.codecDescription=ie(e,n.contentSize)}break;case"hvcC":{let a=this.currentTrack;if(!a)break;w(a.info),a.info.codecDescription=ie(e,n.contentSize)}break;case"vpcC":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video"),e.skip(4);let o=ce(e),c=ce(e),l=ce(e),u=l>>4,d=l>>1&7,h=l&1,f=ce(e),p=ce(e),m=ce(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:m}}break;case"av1C":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video"),e.skip(1);let o=ce(e),c=o>>5,l=o&31,u=ce(e),d=u>>7,h=u>>6&1,f=u>>5&1,p=u>>4&1,m=u>>3&1,g=u>>2&1,y=u&3,b=c===2&&h?f?12:10:h?10:8;a.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:b,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:g,chromaSamplePosition:y}}break;case"colr":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video");let o=We(e,4);if(o!=="nclx"&&o!=="nclc")break;let c=je(e),l=je(e),u=je(e),d;o==="nclx"&&(d=!!(ce(e)&128)),a.info.colorSpace={primaries:Mn[c],transfer:Fn[l],matrix:Rn[u],fullRange:d}}break;case"pasp":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="video");let o=j(e),c=j(e);o>0&&c>0&&(o>c?a.info.squarePixelWidth=Math.round(a.info.width*o/c):a.info.squarePixelHeight=Math.round(a.info.height*c/o))}break;case"wave":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"esds":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(4);let o=ce(e);w(o===3),ac(e),e.skip(2);let c=ce(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){let g=ce(e);e.skip(g)}d&&e.skip(2);let h=ce(e);w(h===4);let f=ac(e),p=e.filePos,m=ce(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":we._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),f>e.filePos-p){let g=ce(e);w(g===5);let y=ac(e);if(a.info.codecDescription=ie(e,y),a.info.codec==="aac"){let b=Ri(a.info.codecDescription);b.numberOfChannels!==null&&(a.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(a.info.sampleRate=b.sampleRate)}}}break;case"enda":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(je(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=je(e),l=j(e),u=ra(e),d=ce(e),h;d!==0?h=ie(e,2+o):h=new Uint8Array(0);let f=new Uint8Array(19+h.byteLength),p=new DataView(f.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,u,!0),p.setUint8(18,d),f.set(h,19),a.info.codecDescription=f,a.info.numberOfChannels=o}break;case"dfLa":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio"),e.skip(4);let o=127,c=128,l=e.filePos;for(;e.filePos<s;){let p=ce(e),m=Zt(e);if((p&o)===dn.STREAMINFO){e.skip(10);let y=j(e),b=y>>>12,k=(y>>9&7)+1;a.info.sampleRate=b,a.info.numberOfChannels=k,e.skip(20)}else e.skip(m);if(p&c)break}let u=e.filePos;e.filePos=l;let d=ie(e,u-l),h=new Uint8Array(4+d.byteLength);new DataView(h.buffer).setUint32(0,1716281667,!1),h.set(d,4),a.info.codecDescription=h}break;case"dac3":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio");let o=ie(e,3),c=new Ie(o),l=c.readBits(2);c.skipBits(8);let u=c.readBits(3),d=c.readBits(1);l<3&&(a.info.sampleRate=Nn[l]),a.info.numberOfChannels=ea[u]+d}break;case"dec3":{let a=this.currentTrack;if(!a)break;w(a.info?.type==="audio");let o=ie(e,n.contentSize),c=$p(o);if(!c){we._warn("Invalid dec3 box contents, ignoring.");break}let l=ec(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=tc(c)}break;case"stts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=j(e),c=0,l=0;for(let u=0;u<o;u++){let d=j(e),h=j(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=j(e),c=0;for(let l=0;l<o;l++){let u=j(e),d=Or(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=j(e),c=j(e);if(o===0)for(let l=0;l<c;l++){let u=j(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=j(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=j(e);for(let c=0;c<o;c++){let l=j(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=j(e);for(let l=0;l<o;l++){let u=j(e)-1,d=j(e),h=j(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=j(e);for(let c=0;c<o;c++){let l=j(e);a.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=j(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):j(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);let a=j(e),o=j(e),c=j(e),l=j(e),u=j(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=j(e),c=this.tracks.find(b=>b.id===o);if(!c)break;let l=j(e),u=(l&48)>>4,d=(l&12)>>2,h=l&3,f=[ce,je,Zt,j],p=f[u],m=f[d],g=f[h],y=j(e);for(let b=0;b<y;b++){let k=a===1?Pt(e):j(e),T=a===1?Pt(e):j(e);p(e),m(e),g(e),c.fragmentLookupTable.push({timestamp:k,moofOffset:T})}c.fragmentLookupTable.sort((b,k)=>b.timestamp-k.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){let k=c.fragmentLookupTable[b],T=c.fragmentLookupTable[b+1];k.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(i,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(w(this.currentFragment),this.readContiguousBoxes(e.slice(i,n.contentSize)),this.currentTrack){let a=this.currentFragment.trackData.get(this.currentTrack.id);e:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}a.presentationTimestamps=a.samples.map((u,d)=>({presentationTimestamp:u.presentationTimestamp,sampleIndex:d})).sort((u,d)=>u.presentationTimestamp-d.presentationTimestamp);for(let u=0;u<a.presentationTimestamps.length;u++){let d=a.presentationTimestamps[u],h=a.samples[d.sampleIndex];if(a.firstKeyFrameTimestamp===null&&h.isKeyFrame&&(a.firstKeyFrameTimestamp=h.presentationTimestamp),u<a.presentationTimestamps.length-1){let p=a.presentationTimestamps[u+1].presentationTimestamp-d.presentationTimestamp;h.duration=p}}let o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[ze(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;let{currentFragmentState:l}=this.currentTrack;w(l),l.startTimestamp!==null&&(Ru(a,l.startTimestamp),a.startTimestampIsFinal=!0),l.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=l.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let a=nc(ie(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{w(this.currentFragment),e.skip(1);let a=Zt(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),u=!!(a&16),d=!!(a&32),h=!!(a&65536),f=!!(a&131072),p=j(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=j(e)),l&&(m.currentFragmentState.defaultSampleDuration=j(e)),u&&(m.currentFragmentState.defaultSampleSize=j(e)),d&&(m.currentFragmentState.defaultSampleFlags=j(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?j(e):Pt(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{let a=this.currentTrack;if(!a)break;w(this.currentFragment),w(a.currentFragmentState);let o=ce(e),c=Zt(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),h=!!(c&512),f=!!(c&1024),p=!!(c&2048),m=j(e),g=null;l&&(g=Or(e));let y=null;u&&(y=j(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=j(e):(w(a.currentFragmentState.defaultSampleDuration!==null),T=a.currentFragmentState.defaultSampleDuration);let x;h?x=j(e):(w(a.currentFragmentState.defaultSampleSize!==null),x=a.currentFragmentState.defaultSampleSize);let v;f?v=j(e):(w(a.currentFragmentState.defaultSampleFlags!==null),v=a.currentFragmentState.defaultSampleFlags),k===0&&y!==null&&(v=y);let M=0;p&&(o===0?M=j(e):M=Or(e));let C=!(v&65536);b.samples.push({presentationTimestamp:b.currentTimestamp+M,duration:T,byteOffset:b.currentOffset,byteSize:x,isKeyFrame:C,encryption:null}),b.currentOffset+=x,b.currentTimestamp+=T}this.currentFragment.implicitBaseDataOffset=b.currentOffset}break;case"saiz":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),Zt(e)&1){let h=We(e,4),f=j(e);if(h!==a.encryptionInfo.scheme||f!==0)break}let c=ce(e),l=j(e),u=null;c===0&&l>0&&(u=ie(e,l));let d=eg(a);d.defaultSampleInfoSize=c,d.sampleSizes=u,d.sampleCount=l}break;case"saio":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;let o=ce(e);if(Zt(e)&1){let h=We(e,4),f=j(e);if(h!==a.encryptionInfo.scheme||f!==0)break}let l=j(e);if(l===0)break;l>1&&we._warn("Multiple saio entries are not supported; using the first offset only.");let u=o===0?j(e):Number(Pt(e));this.currentFragment&&(u+=this.currentFragment.moofOffset);let d=eg(a);d.offset=u}break;case"senc":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;w(this.currentFragment);let o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);let l=!!(Zt(e)&2),u=j(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=je(e);p=[];for(let y=0;y<g;y++){let b=je(e),k=j(e);p.push({clearLen:b,protectedLen:k})}}let m=o.samples[h];m.encryption={iv:f,subsamples:p}}}break;case"udta":{let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},o.name[0]==="\xA9"?this.metadataTags.raw[o.name]??=Qt(c):this.metadataTags.raw[o.name]??=ie(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=ot.decode(ie(c,o.contentSize)):this.metadataTags.title??=Qt(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Qt(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Qt(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Qt(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Qt(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Qt(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(Qt(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Qt(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Qt(c));break}}}break;case"meta":{if(this.currentTrack)break;let o=j(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=j(e);for(let o=0;o<a;o++){let c=j(e);e.skip(4);let l=ot.decode(ie(e,c-8));this.currentMetadataKeys.set(o+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let a=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(let{boxInfo:o,slice:c}of a){let l=o.name,u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));let d=Xp(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=d,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof $t?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let h=d.split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let h=Ae(d),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let h=Ae(d),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}},cc=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let i of e.tracks)if(i.trackBacking.getType()===t&&n++,i===this.internalTrack)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(w(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Mr(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Bu(i,n),a=await this.fetchPacketForSampleIndex(s,t);return!Jp(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=_e(c.presentationTimestamps,n,h=>h.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let a=s.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<a.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=bT(i,n),a=await this.fetchPacketForSampleIndex(s,t);return!Jp(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=Pi(c.presentationTimestamps,h=>c.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=n),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ST(s,n);return this.fetchPacketForSampleIndex(a,t)}let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){let o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>i.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{let a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let o=a.samples.findIndex(c=>c.isKeyFrame);return w(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=kT(n,e);if(!i)return null;let s;if(t.metadataOnly)s=st;else{let l=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(l instanceof Promise&&(l=await l),!l)return null;if(s=ie(l,i.sampleSize),this.internalTrack.encryptionAuxInfo){w(this.internalTrack.encryptionInfo);let u=await rg(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<u.length&&(s=await tg(this.internalTrack,u[e],s,null))}}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,c=new Oe(s,i.isKeyFrame?"key":"delta",a,o,e,i.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[t];w(s);let a;if(n.metadataOnly)a=st;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(u instanceof Promise&&(u=await u),!u)return null;a=ie(u,s.byteSize),s.encryption&&(a=await tg(this.internalTrack,s.encryption,a,e))}let o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new Oe(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,n,i,s){let a=this.internalTrack.demuxer,o=null,c=null,l=-1;if(e){let{sampleIndex:g,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,g,s);g!==-1&&(c=e,l=g)}let u=_e(this.internalTrack.fragmentLookupTable,n,g=>g.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,h=_e(this.internalTrack.fragmentPositionCache,n,g=>g.startTimestamp),f=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,p=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let k=o.trackData.get(this.internalTrack.id);if(k&&k.startTimestamp>i)break}let g=a.reader.requestSliceRange(m,Xt,Br);if(g instanceof Promise&&(g=await g),!g)break;let y=m,b=Dr(g);if(!b)break;if(b.name==="moof"){o=await a.readFragment(y);let{sampleIndex:k,correctSampleFound:T}=t(o);if(T)return this.fetchPacketInFragment(o,k,s);k!==-1&&(c=o,l=k)}m=y+b.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let g=this.internalTrack.fragmentLookupTable[u-1];w(!g||g.timestamp<d.timestamp);let y=g?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,i,s)}return c?this.fetchPacketInFragment(c,l,s):null}},lc=class extends cc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&Xo(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Qo(t.data)}let e={codec:Bi(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},uc=class extends cc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Di(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Bu=(r,e)=>{if(r.presentationTimestamps){let t=_e(r.presentationTimestamps,e,n=>n.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{let t=_e(r.sampleTimingEntries,e,i=>i.startDecodeTimestamp);if(t===-1)return-1;let n=r.sampleTimingEntries[t];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},bT=(r,e)=>{if(!r.keySampleIndices)return Bu(r,e);if(r.presentationTimestamps){let t=_e(r.presentationTimestamps,e,n=>n.presentationTimestamp);if(t===-1)return-1;for(let n=t;n>=0;n--){let i=r.presentationTimestamps[n].sampleIndex;if(Ir(r.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{let t=Bu(r,e),n=_e(r.keySampleIndices,t,i=>i);return r.keySampleIndices[n]??-1}},kT=(r,e)=>{let t=_e(r.sampleTimingEntries,e,y=>y.startIndex),n=r.sampleTimingEntries[t];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,a=_e(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);let c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=_e(r.sampleToChunk,e,y=>y.startSampleIndex),u=r.sampleToChunk[l];w(u);let d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),h=r.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,p=0,m=h;if(r.sampleSizes.length===1)m+=c*(e-f),p+=c*u.samplesPerChunk;else for(let y=f;y<f+u.samplesPerChunk;y++){let b=r.sampleSizes[y];y<e&&(m+=b),p+=b}let g=n.delta;if(r.presentationTimestamps){let y=r.presentationTimestampIndexMap[e];w(y!==void 0),y<r.presentationTimestamps.length-1&&(g=r.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:m,sampleSize:c,chunkOffset:h,chunkSize:p,isKeyFrame:r.keySampleIndices?Ir(r.keySampleIndices,e,y=>y)!==-1:!0}},ST=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=_e(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},Ru=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(let t of r.samples)t.presentationTimestamp+=e;for(let t of r.presentationTimestamps)t.presentationTimestamp+=e},xT=r=>{let[e,t]=r,n=Math.atan2(t,e);return Number.isFinite(n)?n*(180/Math.PI):0},Jp=r=>r.sampleSizes.length===0,eg=r=>r.currentFragmentState?r.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:r.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},rg=async(r,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let n=0;if(t.defaultSampleInfoSize>0)n=t.defaultSampleInfoSize*t.sampleCount;else{w(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)n+=t.sampleSizes[o]}let i=r.requestSlice(t.offset,n);if(i instanceof Promise&&(i=await i),!i)throw new Error("Failed to read auxiliary encryption info.");let s=e.defaultPerSampleIvSize;w(s!==null);let a=[];for(let o=0;o<t.sampleCount;o++){let c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],l=new Uint8Array(16);s>0?l.set(ie(i,s),0):l.set(e.defaultConstantIv,0);let u=null;if(c>s){let d=je(i);u=[];for(let h=0;h<d;h++){let f=je(i),p=j(i);u.push({clearLen:f,protectedLen:p})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},tg=async(r,e,t,n)=>{w(r.encryptionInfo);let i=r.encryptionInfo;w(i.defaultKid!==null);let s=i.defaultKid,a,o=r.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!r.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let c=(async()=>{let l=r.demuxer.psshBoxes;if(n){l=[...l,...n.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(s));for(let d=0;d<l.length-1;d++)for(let h=d+1;h<l.length;h++)ic(l[d],l[h])&&(l.splice(h,1),h--)}let u=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:l});if(!(typeof u=="string"&&u.length===32&&sp.test(u)||u instanceof Uint8Array&&u.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return u instanceof Uint8Array?u:ap(u)})();r.demuxer.decryptionKeyCache.set(s,c),a=await c}return i.scheme==="cenc"||i.scheme==="cens"?TT(a,i,e,t):AT(a,i,e,t)},TT=async(r,e,t,n)=>{let i=new Uint8Array(16);i.set(t.iv,0);let s=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{let m=await crypto.subtle.decrypt({name:"AES-CTR",counter:i,length:64},s,p);return new Uint8Array(m)};if(!t.subsamples)return a(n);w(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);let o=ng(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock),c=0;for(let p of o)for(let m of p.perSubsample)c+=m.length;let l=new Uint8Array(c),u=0;for(let p of o)for(let m of p.perSubsample)l.set(n.subarray(m.offset,m.offset+m.length),u),u+=m.length;let d=await a(l),h=new Uint8Array(n),f=0;for(let p of o)for(let m of p.perSubsample)h.set(d.subarray(f,f+m.length),m.offset),f+=m.length;return h},AT=(r,e,t,n)=>{let i=new ta;i.init({key:r,iv:t.iv});let s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(w(s!==null&&a!==null),!t.subsamples){let u=new Uint8Array(n),d=Math.floor(n.length/16);for(let h=0;h<d;h++){let f=h*16;i.in.set(n.subarray(f,f+16)),i.decrypt(),u.set(i.out,f)}return u}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");let o=new Uint8Array(n),c=ng(t.subsamples,s,a),l=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(let u of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(let d of u.perSubsample){let h=d.length/16;for(let f=0;f<h;f++){let p=d.offset+f*16;i.in.set(n.subarray(p,p+16)),i.decrypt(),o.set(i.out,p)}}}return o},ng=(r,e,t)=>{let n=[],i=e!==0||t!==0,s=0;for(let a of r){s+=a.clearLen;let o=[];if(!i)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let c=a.protectedLen,l=s;for(;c>0&&!(c<16*e);){let u=16*e;o.push({offset:l,length:u}),l+=u,c-=u;let d=Math.min(16*t,c);l+=d,c-=d}s+=a.protectedLen}n.push({perSubsample:o})}return n};var N;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(N||(N={}));var vT=[N.EBML,N.Segment],qi=[N.SeekHead,N.Info,N.Cluster,N.Tracks,N.Cues,N.Attachments,N.Chapters,N.Tags],na=[...vT,...qi];var Du=8,Et=2,Jt=2*Du,Ou=r=>{if(r.remainingLength<1)return null;let e=ce(r);if(r.skip(-1),e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;return r.remainingLength<t?null:t},Gi=r=>{if(r.remainingLength<1)return null;let e=ce(r);if(e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;if(r.remainingLength<t-1)return null;let i=e&n-1;for(let s=1;s<t;s++)i*=256,i+=ce(r);return i},Ce=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let n=0;n<e;n++)t*=256,t+=ce(r);return t},sg=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let n=0;n<e;n++)t<<=8n,t+=BigInt(ce(r));return t};var hc=r=>{let e=Ou(r);return e===null||r.remainingLength<e?null:Ce(r,e)},Lu=r=>{if(r.remainingLength<1)return null;if(ce(r)===255)return;r.skip(-1);let t=Gi(r);if(t===null)return null;if(t!==72057594037927940)return t},er=r=>{w(r.remainingLength>=Et);let e=hc(r);if(e===null)return null;let t=Lu(r);return t===null?null:{id:e,size:t}},mn=(r,e)=>{let t=ie(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return String.fromCharCode(...t.subarray(0,n))},Ki=(r,e)=>{let t=ie(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return ot.decode(t.subarray(0,n))},fc=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?ag(r):dc(r)},mc=async(r,e,t,n)=>{let i=new Set(t),s=e;for(;n===null||s<n;){let a=r.requestSliceRange(s,Et,Jt);if(a instanceof Promise&&(a=await a),!a)break;let o=er(a);if(!o)break;if(i.has(o.id))return{pos:s,found:!0};Ur(o.size),s=a.filePos+o.size}return{pos:n!==null&&n>s?n:s,found:!1}},Uu=async(r,e,t,n)=>{let s=new Set(t),a=e;for(;a<n;){let o=r.requestSliceRange(a,0,Math.min(65536,n-a));if(o instanceof Promise&&(o=await o),!o||o.length<Du)break;for(let c=0;c<o.length-Du;c++){o.filePos=a;let l=hc(o);if(l!==null&&s.has(l))return a;a++}}return null},Bt={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function Ur(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var og=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(", ")}"`}return t};var Nr;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Nr||(Nr={}));var pc;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(pc||(pc={}));var ia;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(ia||(ia={}));var Nu=[{id:N.SeekHead,flag:"seekHeadSeen"},{id:N.Info,flag:"infoSeen"},{id:N.Tracks,flag:"tracksSeen"},{id:N.Cues,flag:"cuesSeen"}],cg=10*2**20,gc=class extends ct{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(n=>n.getDecoderConfig().then(i=>i?.codec??null)));return og({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(i=>i.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Et,Jt);if(t instanceof Promise&&(t=await t),!t)break;let n=er(t);if(!n)break;let i=n.id,s=n.size,a=t.filePos;if(i===N.EBML){Ur(s);let o=this.reader.requestSlice(a,s);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(i===N.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(i===N.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await mc(this.reader,a,na,this.reader.fileSize)).pos-a);let o=ze(this.segments);o&&(o.elementEndPos=a+s)}Ur(s),e=a+s}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(n,Et,Jt);if(o instanceof Promise&&(o=await o),!o)break;let c=n,l=er(o);if(!l||!qi.includes(l.id)&&l.id!==N.Void){let p=await Uu(this.reader,c,qi,Math.min(this.currentSegment.elementEndPos??1/0,c+cg));if(p){n=p;continue}else break}let{id:u,size:d}=l,h=o.filePos,f=Nu.findIndex(p=>p.id===u);if(f!==-1){let p=Nu[f].flag;this.currentSegment[p]=!0,Ur(d);let m=this.reader.requestSlice(h,d);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}else if(u===N.Tags||u===N.Attachments){u===N.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ur(d);let p=this.reader.requestSlice(h,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===N.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;n=h+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let o of this.currentSegment.seekEntries){let c=Nu.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,Et,Jt);if(l instanceof Promise&&(l=await l),!l)continue;let u=er(l);if(!u)continue;let{id:d,size:h}=u;if(d!==c.id)continue;Ur(h),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,h);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);let i=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(let o of this.currentSegment.cuePoints){let c=i.get(o.trackId);c&&c.cuePoints.push(o)}for(let o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){let l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,a=-1/0;for(let o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(let o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,Et,Jt);n instanceof Promise&&(n=await n),w(n);let i=e,s=er(n);w(s);let a=s.id;w(a===N.Cluster);let o=s.size,c=n.filePos;o===void 0&&(o=(await mc(this.reader,c,na,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);let u={segment:t,elementStartPos:i,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){let d=this.readContiguousElements(l,na);u.elementEndPos=d}for(let[,d]of u.trackData){let h=d.track;w(d.blocks.length>0);let f=!1;for(let y=0;y<d.blocks.length;y++){let b=d.blocks[y];b.timestamp+=u.timestamp,f||=b.lacing!==Nr.None}d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){let b=d.presentationTimestamps[y],k=d.blocks[b.blockIndex];if(d.firstKeyFrameTimestamp===null&&k.isKeyFrame&&(d.firstKeyFrameTimestamp=k.timestamp),y<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[y+1];k.duration=T.timestamp-k.timestamp}else k.duration===0&&h.defaultDuration!=null&&k.lacing===Nr.None&&(k.duration=h.defaultDuration)}f&&(this.expandLacedBlocks(d.blocks,h),d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));let p=d.blocks[d.presentationTimestamps[0].blockIndex],m=d.blocks[ze(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=m.timestamp+m.duration;let g=_e(h.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(g===-1||h.clusterPositionCache[g].elementStartPos!==i)&&h.clusterPositionCache.splice(g+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let i=e.segment.tracks.find(s=>s.id===t);if(!i)return null;n={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let i=e[n];if(i.lacing===Nr.None)continue;i.decoded||(i.data=this.decodeBlockData(t,i.data),i.decoded=!0);let s=yt.tempFromBytes(i.data),a=[],o=ce(s)+1;switch(i.lacing){case Nr.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){let h=ce(s);if(d+=h,h<255){a.push(d),l+=d;break}}}a.push(s.length-(s.bufferPos+l))}break;case Nr.FixedSize:{let l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case Nr.Ebml:{let l=Gi(s);w(l!==null);let u=l;a.push(u);let d=u;for(let h=1;h<o-1;h++){let f=s.bufferPos,p=Gi(s);w(p!==null);let m=p,y=(1<<(s.bufferPos-f)*7-1)-1,b=m-y;u+=b,a.push(u),d+=u}a.push(s.length-(s.bufferPos+d))}break;default:w(!1)}w(a.length===o),e.splice(n,1);let c=i.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){let u=a[l],d=ie(s,u),h=i.timestamp+c*l/o,f=c/o;e.splice(n+l,0,{timestamp:h,duration:f,isKeyFrame:i.isKeyFrame,data:d,lacing:Nr.None,decoded:!0,mainAdditional:i.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===N.Tags&&!e.tagsSeen)){if(!(t.id===N.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Et,Jt);if(n instanceof Promise&&(n=await n),!n)continue;let i=er(n);if(!i||i.id!==t.id)continue;let{size:s}=i;Ur(s),w(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,s);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===N.Tags?e.tagsSeen=!0:t.id===N.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Et;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let n=er(e);if(!n||t&&t.includes(n.id))return!1;let{id:i,size:s}=n,a=e.filePos;switch(Ur(s),i){case N.DocType:this.isWebM=mn(e,s)==="webm";break;case N.Seek:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,s)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case N.SeekID:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=Ce(e,s)}break;case N.SeekPosition:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=Ce(e,s)}break;case N.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Ce(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case N.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=fc(e,s)}break;case N.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...dt,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==pc.Block||o.data.algorithm!==ia.HeaderStripping)&&(we._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let u=this.currentTrack.info.displayWidth*this.currentTrack.info.height,d=this.currentTrack.info.displayHeight*this.currentTrack.info.width;u>0&&d>0&&(u>d?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*u/d):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*d/u))}this.currentTrack.codecId===Bt.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Bt.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.vp8?this.currentTrack.info.codec="vp8":c===Bt.vp9?this.currentTrack.info.codec="vp9":c===Bt.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack;this.currentTrack.trackBacking=new zu(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===Bt.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Bt.mp3?this.currentTrack.info.codec="mp3":c===Bt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Un):c===Bt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Bt.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack;this.currentTrack.trackBacking=new Vu(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case N.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=Ce(e,s)}break;case N.TrackType:{if(!this.currentTrack)break;let o=Ce(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case N.FlagEnabled:{if(!this.currentTrack)break;Ce(e,s)||(this.currentTrack=null)}break;case N.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Ce(e,s)}break;case N.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Ce(e,s)}break;case N.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Ce(e,s)}break;case N.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Ce(e,s)}break;case N.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Ce(e,s)}break;case N.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Ce(e,s)}break;case N.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=mn(e,s)}break;case N.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=ie(e,s)}break;case N.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Ce(e,s)}break;case N.Name:{if(!this.currentTrack)break;this.currentTrack.name=Ki(e,s)}break;case N.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=mn(e,s),Ei(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Ke)}break;case N.LanguageBCP47:{if(!this.currentTrack)break;let c=mn(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Ke,this.currentTrack.hasLanguageBcp47=!0}break;case N.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case N.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=Ce(e,s)}break;case N.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=Ce(e,s)}break;case N.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=Ce(e,s)}break;case N.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=Ce(e,s)}break;case N.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=Ce(e,s)}break;case N.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=Ce(e,s)===1}break;case N.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,s))}break;case N.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=Rn[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case N.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=Ce(e,s)===2}break;case N.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=Fn[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case N.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=Ce(e,s),c=Mn[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case N.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case N.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-fc(e,s);try{this.currentTrack.info.rotation=_i(c)}catch{}}break;case N.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case N.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=fc(e,s)}break;case N.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=Ce(e,s)}break;case N.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=Ce(e,s)}break;case N.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case N.CueTime:this.currentCueTime=Ce(e,s);break;case N.CueTrackPositions:{if(this.currentCueTime===null)break;w(this.currentSegment);let o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,s)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case N.CueTrack:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=Ce(e,s)}break;case N.CueClusterPosition:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;w(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+Ce(e,s)}break;case N.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Ce(e,s)}break;case N.SimpleBlock:{if(!this.currentCluster)break;let o=Gi(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=ra(e),u=ce(e),d=u>>1&3,h=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(h=!0);let f=ie(e,s-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:h,data:f,lacing:d,decoded:!p,mainAdditional:null})}break;case N.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case N.Block:{if(!this.currentCluster)break;let o=Gi(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=ra(e),d=ce(e)>>1&3,h=ie(e,s-(e.filePos-a)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:h,lacing:d,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case N.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case N.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case N.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=ie(e,s)}break;case N.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Ce(e,s)}break;case N.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Ce(e,s)}break;case N.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case N.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case N.Targets:this.readContiguousElements(e.slice(a,s));break;case N.TargetTypeValue:Ce(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case N.TagTrackUID:case N.TagEditionUID:case N.TagChapterUID:case N.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case N.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case N.TagName:this.currentSimpleTagName=Ki(e,s);break;case N.TagString:{if(!this.currentSimpleTagName)break;let o=Ki(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case N.TagBinary:{if(!this.currentSimpleTagName)break;let o=ie(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case N.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));let o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new js(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case N.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=sg(e,s)}break;case N.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Ki(e,s)}break;case N.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=mn(e,s)}break;case N.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=ie(e,s)}break;case N.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Ki(e,s)}break;case N.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case N.ContentEncoding:this.currentDecodingInstruction={order:0,scope:pc.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case N.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Ce(e,s)}break;case N.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Ce(e,s)}break;case N.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:ia.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case N.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Ce(e,s)}break;case N.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=ie(e,s)}break;case N.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,t){w(e.decodingInstructions.length>0);let n=t;for(let i of e.decodingInstructions)switch(w(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case ia.HeaderStripping:if(i.data.settings&&i.data.settings.length>0){let s=i.data.settings,a=new Uint8Array(s.length+n.length);a.set(s,0),a.set(n,s.length),n=a}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":n.title??=t;break;case"description":n.description??=t;break;case"artist":n.artist??=t;break;case"album":n.album??=t;break;case"album_artist":n.albumArtist??=t;break;case"genre":n.genre??=t;break;case"comment":n.comment??=t;break;case"lyrics":n.lyrics??=t;break;case"date":{let i=new Date(t);Number.isNaN(i.getTime())||(n.date??=i)}break;case"track_number":case"part_number":{let i=t.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.tracksTotal??=a)}break;case"disc_number":case"disc":{let i=t.split("/"),s=Number.parseInt(i[0],10),a=i[1]&&Number.parseInt(i[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),a&&Number.isInteger(a)&&a>0&&(n.discsTotal??=a)}break}}},yc=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let i of e.segments)for(let s of i.tracks)if(s.trackBacking.getType()===t&&n++,s===this.internalTrack)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor,n=await this.getFirstPacket({metadataOnly:!0});return t+=n?.timestamp??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Mr(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=_e(s.presentationTimestamps,n,l=>l.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let s=i.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{let s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let a=Pi(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){let a=i.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>n.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.blocks.findIndex(o=>o.isKeyFrame);return w(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[t];w(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let a=n.metadataOnly?st:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,l={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?st:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);let u=new Oe(a,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,s.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,n,i,s){let{demuxer:a,segment:o}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:y,correctBlockFound:b}=t(e);if(b)return this.fetchPacketInCluster(e,y,s);y!==-1&&(l=e,u=y)}let d=_e(this.internalTrack.cuePoints,n,y=>y.time),h=d!==-1?this.internalTrack.cuePoints[d]:null,f=_e(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,m=Math.max(h?.clusterPosition??0,p?.elementStartPos??0)||null,g;for(e?m===null||e.elementStartPos>=m?(g=e.elementEndPos,c=e):g=m:g=m??o.clusterSeekStartPos;o.elementEndPos===null||g<=o.elementEndPos-Et;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>i)break}let y=a.reader.requestSliceRange(g,Et,Jt);if(y instanceof Promise&&(y=await y),!y)break;let b=g,k=er(y);if(!k||!qi.includes(k.id)&&k.id!==N.Void){let C=await Uu(a.reader,b,qi,Math.min(o.elementEndPos??1/0,b+cg));if(C){g=C;continue}else break}let T=k.id,x=k.size,v=y.filePos;if(T===N.Cluster){c=await a.readCluster(b,o),x=c.elementEndPos-v;let{blockIndex:C,correctBlockFound:_}=t(c);if(_)return this.fetchPacketInCluster(c,C,s);C!==-1&&(l=c,u=C)}x===void 0&&(w(T!==N.Cluster),x=(await mc(a.reader,v,na,o.elementEndPos)).pos-v);let M=v+x;if(o.elementEndPos===null){let C=a.reader.requestSliceRange(M,Et,Jt);if(C instanceof Promise&&(C=await C),!C)break;if(hc(C)===N.Segment){o.elementEndPos=M;break}}g=M}if(h&&(!l||l.elementStartPos<h.clusterPosition)){let y=this.internalTrack.cuePoints[d-1];w(!y||y.time<h.time);let b=y?.time??-1/0;return this.performClusterLookup(null,t,b,i,s)}return l?this.fetchPacketInCluster(l,u,s):null}},zu=class extends yc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let n={codec:Bi({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Ui(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Ni(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Xo(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Qo(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}},Vu=class extends yc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Di({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};var sa=async(r,e,t,n=null)=>{let s=e;for(;t===null||s<t;){let a=t!==null?Math.min(65536,t-s):65536,o=r.requestSliceRange(s,4,a);if(o instanceof Promise&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let c=o.filePos,l=j(o),u=r.fileSize!==null?r.fileSize-s:null,d=Qs(l,u);if(d.header&&(!n||d.header.sampleRate===n.sampleRate&&d.header.mpegVersionId===n.mpegVersionId&&d.header.layer===n.layer&&ln(d.header.channel)===ln(n.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};var wc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new vt,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Hu(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,mt);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}let c=It(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}let e=await sa(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Go(t.mpegVersionId,t.channel),i=this.reader.requestSlice(e.startPos+n,4);if(i instanceof Promise&&(i=await i),i){let o=j(i);if(o===Wo||o===qo){if(!this.xingData){let l=this.reader.requestSlice(e.startPos+n+4,12);if(l instanceof Promise&&(l=await l),l){let u=ie(l,12),d=Ae(u),h=d.getUint32(0,!1);this.xingData={frameCount:h&Xs.FrameCount?d.getUint32(4,!1):null,fileSize:h&Xs.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,n=!1;for(;;){let i=this.reader.requestSlice(t,mt);if(i instanceof Promise&&(i=await i),!i)break;let s=It(i);if(!s)break;n=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(a instanceof Promise&&(a=await a),!a)break;pn(a,s,this.metadataTags),t=i.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=aa){let i=this.reader.requestSlice(this.reader.fileSize-aa,aa);i instanceof Promise&&(i=await i),w(i),We(i,3)==="TAG"&&lg(i,this.metadataTags)}return this.metadataTags}finally{e()}}},Hu=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(w(e.firstFrameHeader!==null),w(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){let t=Fp(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Ke}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return w(this.demuxer.firstFrameHeader),ln(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:ln(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=ie(s,n.dataSize)}return new Oe(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=Ir(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Wu=1399285583,_T=79764919,ug=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^_T:e<<1;ug[r]=e>>>0&4294967295}var dg=r=>{let e=Ae(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let i=0;i<r.length;i++){let s=r[i];n=(n<<8^ug[n>>>24^s])>>>0}return e.setUint32(22,t,!0),n},hg=(r,e,t)=>{let n=0,i=null;if(r.length>0)if(e.codec==="vorbis"){w(e.vorbisInfo);let s=e.vorbisInfo.modeBlockflags.length,o=(1<<dp(s-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,u=e.vorbisInfo.modeBlockflags[c];if(i=e.vorbisInfo.blocksizes[u],u===1){let d=(o|1)+1,h=r[0]&d?1:0;l=e.vorbisInfo.blocksizes[h]}n=l!==null?l+i>>2:0}else e.codec==="opus"&&(n=qp(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:i}},fg=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var gn=27,Vn=282,mg=Vn+65025,ji=r=>{let e=r.filePos;if(zn(r)!==Wu)return null;r.skip(1);let n=ce(r),i=gg(r),s=zn(r),a=zn(r),o=zn(r),c=ce(r),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=ce(r);let u=27+c,d=l.reduce((f,p)=>f+p,0),h=u+d;return{headerStartPos:e,totalSize:h,dataStartPos:e+u,dataSize:d,headerType:n,granulePosition:i,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:l}},pg=(r,e)=>{for(;r.filePos<e-3;){let t=zn(r),n=t&255,i=t>>>8&255,s=t>>>16&255,a=t>>>24&255,o=79;if(!(n!==o&&i!==o&&s!==o&&a!==o)){if(r.skip(-4),t===Wu)return!0;r.skip(1)}}return!1};var bc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,gn,Vn);if(t instanceof Promise&&(t=await t),!t)break;let n=ji(t);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let t of this.bitstreams){let n=await this.readPacket(t.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,t):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,t),t.codecInfo.codec!==null&&this.trackBackings.push(new qu(t,this)))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||(n=await this.findNextPacketStart(i),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||i.data[0]!==3||s.data[0]!==5)return;let a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(i.data.length);let c=new Uint8Array(1+a.length+e.data.length+i.data.length+s.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(i.data,1+a.length+e.data.length),c.set(s.data,1+a.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=s;let l=Ae(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Gp(s.data).modeBlockflags},Js(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;let s=Yo(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=Un,t.codecInfo.opusInfo={preSkip:s.preSkip},Js(i.data.subarray(8),this.metadataTags)}async readPacket(e,t){w(t<e.lacingValues.length);let n=0;for(let d=0;d<t;d++)n+=e.lacingValues[d];let i=e,s=n,a=t,o=[];e:for(;;){let d=this.reader.requestSlice(i.dataStartPos,i.dataSize);d instanceof Promise&&(d=await d),w(d);let h=ie(d,i.dataSize);for(;;){if(a===i.lacingValues.length){o.push(h.subarray(n,s));break}let p=i.lacingValues[a];if(s+=p,p<255){o.push(h.subarray(n,s));break e}a++}let f=i.headerStartPos+i.totalSize;for(;;){let p=this.reader.requestSliceRange(f,gn,Vn);if(p instanceof Promise&&(p=await p),!p)return null;let m=ji(p);if(!m)return null;if(i=m,i.serialNumber===e.serialNumber)break;f=i.headerStartPos+i.totalSize}n=0,s=0,a=0}let c=o.reduce((d,h)=>d+h.length,0);if(c===0)return null;let l=new Uint8Array(c),u=0;for(let d=0;d<o.length;d++){let h=o[d];l.set(h,u),u+=h.length}return{data:l,endPage:i,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let i=this.reader.requestSliceRange(n,gn,Vn);if(i instanceof Promise&&(i=await i),!i)return null;let s=ji(i);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};n=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(n=>n?.codec??null)));return fg({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},qu=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new vt,this.internalSampleRate=e.codecInfo.codec==="opus"?Un:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return w(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return w(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Ke}getDisposition(){return{...dt,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(w(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:i,vorbisBlockSize:s}=hg(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new Oe(n.metadataOnly?st:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){w(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(w(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let i=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let i=await this.demuxer.findNextPacketStart(n.packet);if(!i)return null;let s=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=Mr(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;w(this.bitstream.lastMetadataPacket);let i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let s=i.startPage,a=this.demuxer.reader.fileSize,o=[s];e:for(;s.headerStartPos+s.totalSize<a;){let b=s.headerStartPos,k=Math.floor((b+a)/2),T=k;for(;;){let x=Math.min(T+mg,a-gn),v=this.demuxer.reader.requestSlice(T,x-T);if(v instanceof Promise&&(v=await v),w(v),!pg(v,x)){a=k+gn;continue e}let C=this.demuxer.reader.requestSliceRange(v.filePos,gn,Vn);C instanceof Promise&&(C=await C),w(C);let _=ji(C);w(_);let F=!1;if(_.serialNumber===this.bitstream.serialNumber)F=!0;else{let O=this.demuxer.reader.requestSlice(_.headerStartPos,_.totalSize);O instanceof Promise&&(O=await O),w(O);let Q=ie(O,_.totalSize);F=dg(Q)===_.checksum}if(!F){T=_.headerStartPos+4;continue}if(F&&_.serialNumber!==this.bitstream.serialNumber){T=_.headerStartPos+_.totalSize;continue}if(_.granulePosition===-1){T=_.headerStartPos+_.totalSize;continue}this.granulePositionToTimestampInSamples(_.granulePosition)>n?a=_.headerStartPos:(s=_,o.push(_));continue e}}let c=i.startPage;for(let b of o){if(b.granulePosition===s.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){let b=l.headerStartPos+l.totalSize,k=this.demuxer.reader.requestSliceRange(b,gn,Vn);k instanceof Promise&&(k=await k),w(k);let T=ji(k);w(T),l=T,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}w(l.granulePosition!==-1);let d=null,h,f,p=l,m=0;if(l.headerStartPos===i.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,d=0;else{h=0,f=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;let b={data:st,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(b)){let T=wg(u,l,d);w(T);let x=yg(u,T.page,T.segmentIndex);x&&(l=x.page,d=x.segmentIndex)}else for(;;){let T=wg(u,l,d);if(!T)break;let x=yg(u,T.page,T.segmentIndex);if(!x)break;if(l=x.page,d=x.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,m=T.segmentIndex;break}}}let g=null,y=null;for(;l!==null;){w(d!==null);let b=await this.demuxer.readPacket(l,d);if(!b)break;if(!(l.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let x=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);w(x);let v=this.encodedPacketToMetadata.get(x);if(w(v),!f&&b.endPage.headerStartPos===p.headerStartPos&&b.endSegmentIndex===m?(h=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,x=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h-v.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),w(x),v=this.encodedPacketToMetadata.get(x),w(v)):h+=v.durationInSamples,g=x,y=v,f&&(Math.max(h,0)>n||Math.max(v.timestampInSamples,0)===n))break}let T=await this.demuxer.findNextPacketStart(b);if(!T)break;l=T.startPage,d=T.startSegmentIndex}return g}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let i=Mr(e*this.internalSampleRate);e=i/this.internalSampleRate;let s=_e(this.sequentialScanCache,i,c=>c.timestampInSamples),a;if(s!==-1){let c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){let c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;let l=this.encodedPacketToMetadata.get(a);w(l),this.sequentialScanCache.length>0&&w(ze(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},yg=(r,e,t)=>{let n=e,i=t;e:for(;;){for(i--,i;i>=0;i--)if(n.lacingValues[i]<255){i++;break e}if(w(i===-1),!(n.headerType&1)){i=0;break}let a=Tu(r,o=>o.headerStartPos<n.headerStartPos);if(!a)return null;n=a,i=n.lacingValues.length}if(w(i!==-1),i===n.lacingValues.length){let s=r[r.indexOf(n)+1];w(s),n=s,i=0}return{page:n,segmentIndex:i}},wg=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let n=Tu(r,i=>i.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var Vr;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Vr||(Vr={}));var kc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),w(e);let t=We(e,4),n=t!=="RIFX",i=t==="RF64",s=Hr(e,n),a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(We(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;a===null||u<a;){let h=this.reader.requestSlice(u,8);if(h instanceof Promise&&(h=await h),!h)break;let f=We(h,4),p=Hr(h,n),m=h.filePos;if(i&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(m,p,n);else if(f==="data"){if(l??=p,this.dataStart=h.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let g=this.reader.requestSlice(m,p);if(g instanceof Promise&&(g=await g),!g)break;let y=Ku(g,n);l=Ku(g,n),a=Math.min(y+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(m,p,n):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(m,p);u=m+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new Gu(this))})()}async parseFmtChunk(e,t,n){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let s=Xi(i,n),a=Xi(i,n),o=Hr(i,n);i.skip(4);let c=Xi(i,n),l;if(t===14?l=8:l=Xi(i,n),t>=18&&s!==357){let u=Xi(i,n),d=t-18;if(Math.min(d,u)>=22&&s===Vr.EXTENSIBLE){i.skip(6);let f=ie(i,16);s=f[0]|f[1]<<8}}(s===Vr.MULAW||s===Vr.ALAW)&&(l=8),this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,n){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let s=We(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+t-8;){i.filePos=a;let o=We(i,4),c=Hr(i,n),l=ie(i,c),u=0;for(let h=0;h<l.length&&l[h]!==0;h++)u++;let d=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=d,o){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let h=d.split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"YEAR":{let h=Number.parseInt(d,10);Number.isInteger(h)&&h>0&&(this.metadataTags.date??=new Date(h,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+c+(c&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let i=It(n);if(i){let s=t-mt;if(i.size=Math.min(i.size,s),i.size>0){let a=n.slice(e+mt,i.size);pn(a,i,this.metadataTags)}}}getCodec(){if(w(this.audioInfo),this.audioInfo.format===Vr.MULAW)return"ulaw";if(this.audioInfo.format===Vr.ALAW)return"alaw";if(this.audioInfo.format===Vr.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===Vr.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},$i=2048,Gu=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(w(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return w(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Ke}getDisposition(){return{...dt}}async getPacketAtIndex(e,t){w(e>=0),w(this.demuxer.audioInfo);let n=e*$i*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let i=Math.min($i*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);if(c instanceof Promise&&(c=await c),!c)return null}let s;if(t.metadataOnly)s=st;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);c instanceof Promise&&(c=await c),w(c),s=ie(c,i)}let a=e*$i/this.demuxer.audioInfo.sampleRate,o=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Oe(s,"key",a,o,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){w(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/$i,(this.demuxer.dataSize-1)/($i*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let i=await this.getPacketAtIndex(n,t);if(i)return i;if(n===0)return null;w(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){let a=await this.getNextPacket(s,t);if(!a)break;s=a}return s}getNextPacket(e,t){w(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/$i);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Hn=7,tr=9,rr=r=>{let e=r.filePos,t=ie(r,9),n=new Ie(t);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let a=n.readBits(1),o=n.readBits(2)+1,c=n.readBits(4);if(c===15)return null;n.skipBits(1);let l=n.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let u=n.readBits(13);n.skipBits(11);let d=n.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?r.filePos-=2:h=n.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:h,startPos:e}};var oa=1024,Sc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new vt,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();w(this.firstFrameHeader),this.trackBackings=[new ju(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,mt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let o=It(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Hn,tr);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=rr(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=fr[t.samplingFrequencyIndex];w(n!==void 0);let i=oa/n,s={timestamp:this.nextTimestampInSamples/n,duration:i,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=oa,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let n=this.reader.requestSlice(t,mt);if(n instanceof Promise&&(n=await n),!n)break;let i=It(n);if(!i)break;let s=this.reader.requestSlice(n.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;pn(s,i,this.metadataTags),t=n.filePos+i.size}return this.metadataTags}finally{e()}}},ju=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/oa}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Ke}getCodec(){return"aac"}getInternalCodecId(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){w(this.demuxer.firstFrameHeader);let e=on[this.demuxer.firstFrameHeader.channelConfiguration];return w(e!==void 0),e}getSampleRate(){w(this.demuxer.firstFrameHeader);let e=fr[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return w(e!==void 0),e}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=ie(s,n.dataSize)}return new Oe(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=Ir(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");let s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var bg=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,kg=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Sg=r=>{let e=0,t=new Ie(ie(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let n=[],i=e-1,s=new Ie(ie(r,i)),a=8-e-1;for(let c=0;c<a;c++)n.unshift(t.readBits(1));for(let c=0;c<i;c++)for(let l=0;l<8;l++){let u=s.readBits(1);l<2||n.unshift(u)}return n.reduce((c,l,u)=>c|l<<u,0)},xg=(r,e)=>{if(e==="uncommon-u16")return je(r)+1;if(e==="uncommon-u8")return ce(r)+1;if(typeof e=="number")return e;Ct(e),w(!1)},Tg=(r,e)=>e==="uncommon-u16"?je(r):e==="uncommon-u16-10"?je(r)*10:e==="uncommon-u8"?ce(r):typeof e=="number"?e:null,Ag=r=>{let t=0;for(let n of r){t^=n;for(let i=0;i<8;i++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var xc=class extends ct{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new vt,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),w(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,mt);if(t instanceof Promise&&(t=await t),!t){this.lastSampleLoaded=!0;return}let n=It(t);if(!n)break;let i=this.reader.requestSlice(t.filePos,n.size);i instanceof Promise&&(i=await i),w(i),pn(i,n,this.metadataTags),e=t.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);w(t);let n=ce(t),i=Zt(t),s=(n&128)!==0;switch(n&127){case dn.STREAMINFO:{let o=this.reader.requestSlice(e,i);if(o instanceof Promise&&(o=await o),w(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=ie(o,34),l=new Ie(c),u=l.readBits(16),d=l.readBits(16),h=l.readBits(24),f=l.readBits(24),p=l.readBits(20),m=l.readBits(3)+1;l.readBits(5);let g=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:p,totalSamples:g,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:h,maximumFrameSize:f,description:y},this.trackBacking=new $u(this);break}case dn.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,i);o instanceof Promise&&(o=await o),w(o),Js(ie(o,i),this.metadataTags);break}case dn.PICTURE:{let o=this.reader.requestSlice(e,i);o instanceof Promise&&(o=await o),w(o);let c=j(o),l=j(o),u=ot.decode(ie(o,l)),d=j(o),h=ot.decode(ie(o,d));o.skip(16);let f=j(o),p=ie(o,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:u,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:h});break}default:break}if(e+=i,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){w(this.audioInfo);let n=6,i=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,o=this.audioInfo.minimumFrameSize||s,l=(this.audioInfo.maximumFrameSize||a)+i,u=await this.reader.requestSliceRange(e,i,l);if(!u)return null;let d=this.readFlacFrameHeader({slice:u,isFirstPacket:t});if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-n)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(ce(u)===255){let f=u.filePos,p=ce(u),m=this.blockingBit===1?249:248;if(p!==m){u.filePos=f;continue}u.skip(-2);let g=u.filePos-e,y=this.readFlacFrameHeader({slice:u,isFirstPacket:!1});if(!y){u.filePos=f;continue}if(this.blockingBit===0){if(y.num-d.num!==1){u.filePos=f;continue}}else if(y.num-d.num!==d.blockSize){u.filePos=f;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:g,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,i=ie(e,4),s=new Ie(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){w(t);let g=s.readBits(1);this.blockingBit=g}else if(this.blockingBit===1){if(w(!t),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(w(!t),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let o=bg(s.readBits(4));if(!o)return null;w(this.audioInfo);let c=kg(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let u=Sg(e),d=xg(e,o),h=Tg(e,c);if(h===null||h!==this.audioInfo.sampleRate)return null;let f=e.filePos-n,p=ce(e);e.skip(-f),e.skip(-1);let m=Ag(ie(e,f));return p!==m?null:{num:u,blockSize:d,sampleRate:h}}async advanceReader(){await this.readMetadata(),w(this.lastLoadedPos!==null),w(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(s),t.isLastFrame){this.lastSampleLoaded=!0;return}}},$u=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Ke}getTimeResolution(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...dt}}async getDecoderConfig(){return w(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(w(this.demuxer.audioInfo),e<0)return null;let n=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_e(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(i===-1){await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[i],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(i,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=st;else{let o=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;i=ie(o,n.byteSize)}w(this.demuxer.audioInfo);let s=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new Oe(i,"key",s,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var vg=r=>{let e="video/MP2T",t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};var Cg="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",_g=new Set,Tc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=205,t=this.reader.requestSlice(0,e);t instanceof Promise&&(t=await t),w(t);let n=ie(t,e);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let i=256;this.minReferencePointByteDistance=i*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){let l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===l.pid)){s+=this.packetStride;continue}let u=await this.readSection(s,!0,!c);if(!u)break;let d=3,h=32,f=!1;if(!c&&u.pid!==0&&!(u.payload[0]===0&&u.payload[1]===0&&u.payload[2]===1)){let g=new Ie(u.payload),y=g.readAlignedByte();g.skipBits(8*y),f=g.readBits(8)===2}if(u.pid===0&&!o){let m=new Ie(u.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(14);let y=m.readBits(10);for(m.skipBits(40);8*(y+d)-m.pos>h;){let b=m.readBits(16);m.skipBits(3);let k=m.readBits(13);if(b!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=k}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((u.pid===a||f)&&!c){let m=new Ie(u.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(12);let y=m.readBits(12);m.skipBits(43);let b=m.readBits(13);m.skipBits(6);let k=m.readBits(10);for(m.skipBits(8*k);8*(y+d)-m.pos>h;){let T=m.readBits(8);m.skipBits(3);let x=m.readBits(13);m.skipBits(6);let v=m.readBits(10),M=m.pos+8*v,C=!1,_=!1;for(;m.pos<M;){let E=m.readBits(8),O=m.readBits(8);E===106?C=!0:(E===122||E===204)&&(_=!0),m.skipBits(8*O)}let F=null;switch(T){case 27:case 36:F={type:"video",codec:T===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let E;if(T===3||T===4)E="mp3";else if(T===15)E="aac";else if(T===129)E="ac3";else if(T===135)E="eac3";else throw new Error("Unreachable.");F={type:"audio",codec:E,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:_?F={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:C&&(F={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:_g.has(T)||(we._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),_g.add(T))}F&&this.elementaryStreams.push({demuxer:this,pid:x,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:F,referencePesPackets:[]})}c=!0}else{let m=this.elementaryStreams.find(g=>g.pid===u.pid);e:if(m&&!m.initialized){let g=Qi(u,!0);if(!g)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=u,m.canBeTrustedWithKeyPackets=u.randomAccessIndicator===1,this.input._initInput){let k=(await this.input._initInput._getDemuxer()).elementaryStreams.find(T=>T.pid===u.pid&&T.info.codec===m.info.codec);if(k){m.info=k.info,m.initialized=!0;break e}}let y=new qn(m,g);if(m.info.type==="video"){for(;;){let b=y;if(b.suppliedPacket=null,await y.markNextPacket(),m.info.codec==="avc"){if(!y.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=Ui(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;let k=m.info.avcCodecInfo.sequenceParameterSets[0];w(k);let T=Zs(k);m.info.width=T.displayWidth,m.info.height=T.displayHeight;let x=T.pixelAspectRatio.num,v=T.pixelAspectRatio.den;x>0&&v>0&&(x>v?(m.info.squarePixelWidth=Math.round(m.info.width*x/v),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*v/x))),m.info.colorSpace={primaries:Mn[T.colourPrimaries],transfer:Fn[T.transferCharacteristics],matrix:Rn[T.matrixCoefficients],fullRange:!!T.fullRangeFlag},m.info.reorderSize=T.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!y.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=Ni(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;let T=m.info.hevcCodecInfo.arrays.find(v=>v.nalUnitType===it.SPS_NUT).nalUnits[0];w(T);let x=Mu(T);m.info.width=x.displayWidth,m.info.height=x.displayHeight,x.pixelAspectRatio.num>x.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*x.pixelAspectRatio.num/x.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*x.pixelAspectRatio.den/x.pixelAspectRatio.num)),m.info.colorSpace={primaries:Mn[x.colourPrimaries],transfer:Fn[x.transferCharacteristics],matrix:Rn[x.matrixCoefficients],fullRange:!!x.fullRangeFlag},m.info.reorderSize=x.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Bi({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await y.markNextPacket(),!y.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){let b=yt.tempFromBytes(y.suppliedPacket.data),k=rr(b);if(!k)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:k.objectType},m.info.numberOfChannels=on[k.channelConfiguration],m.info.sampleRate=fr[k.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){let b=j(yt.tempFromBytes(y.suppliedPacket.data)),k=Qs(b,y.suppliedPacket.data.byteLength);if(!k.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=ln(k.header.channel),m.info.sampleRate=k.header.sampleRate}else if(m.info.codec==="ac3"){let b=Zo(y.suppliedPacket.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=ea[b.acmod]+b.lfeon,m.info.sampleRate=Nn[b.fscod]}else if(m.info.codec==="eac3"){let b=Jo(y.suppliedPacket.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let k=ec(b);if(k===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=tc(b),m.info.sampleRate=k}else throw new Error("Unhandled.");m.info.decoderConfig={codec:Di({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let l of this.elementaryStreams)l.info.type==="video"?this.trackBackingEntries.push(new Xu(l)):this.trackBackingEntries.push(new Qu(l))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(n=>n?.codec??null)));return vg(e)}async readSection(e,t,n=!1){let i=e,s=e,a=[],o=0,c=null,l=!0,u=0;for(;;){let h=await this.readPacket(s);if(s+=this.packetStride,!h)break;if(c){if(h.pid!==c.pid){if(n)break;continue}if(h.payloadUnitStartIndicator===1)break}else{if(h.payloadUnitStartIndicator===0)break;c=h}let f=!!(h.adaptationFieldControl&2),p=!!(h.adaptationFieldControl&1),m=0;if(f&&(m=1+h.body[0],h===c&&m>1&&(u=h.body[1]>>6&1)),p&&(m===0?(a.push(h.body),o+=h.body.byteLength):(a.push(h.body.subarray(m)),o+=h.body.byteLength-m)),i=s,!t&&o>=64){l=!1;break}if(Ir(this.sectionEndPositions,i,y=>y)!==-1){l=!1;break}}if(l){let h=_e(this.sectionEndPositions,i,f=>f);this.sectionEndPositions.splice(h+1,0,i)}if(!c)return null;let d;if(a.length===1)d=a[0];else{let h=a.reduce((p,m)=>p+m.length,0);d=new Uint8Array(h);let f=0;for(let p of a)d.set(p,f),f+=p.length}return{startPos:e,endPos:t?i:null,pid:c.pid,payload:d,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(ce(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let i=je(t),s=i>>15,a=i>>14&1,o=i>>13&1,c=i&8191,l=ce(t),u=l>>6,d=l>>4&3,h=l&15;return{payloadUnitStartIndicator:a,pid:c,adaptationFieldControl:d}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=ie(t,188);if(n[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let s=(n[1]<<8)+n[2],a=s>>15,o=s>>14&1,c=s>>13&1,l=s&8191,u=n[3],d=u>>6,h=u>>4&3,f=u&15;return{payloadUnitStartIndicator:o,pid:l,adaptationFieldControl:h,body:n.subarray(4)}}},Wn=(r,e)=>{if(r.payload.byteLength<3)return null;let t=new Ie(r.payload);if(t.readBits(24)!==1)return null;let i=t.readBits(8);if(t.skipBits(16),i===188||i===190||i===191||i===240||i===241||i===255||i===242||i===248)return null;t.skipBits(8);let s=t.readBits(2);t.skipBits(14);let a=null;if(s===2||s===3)a=0,t.skipBits(4),a+=t.readBits(3)*(1<<30),t.skipBits(1),a+=t.readBits(15)*32768,t.skipBits(1),a+=t.readBits(15);else if(e)throw new Error(Cg);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},Qi=(r,e)=>{w(r.endPos!==null);let t=Wn(r,e);if(!t)return null;let n=new Ie(r.payload);n.skipBits(32);let i=n.readBits(16),s=6;n.skipBits(16);let a=n.readBits(8),o=n.pos+8*a;n.pos=o;let c=o/8;w(Number.isInteger(c));let l=r.payload.subarray(c,i>0?s+i:r.payload.byteLength);return{...t,data:l}},Ac=class r{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type,n=0;for(let i of e.trackBackingEntries)if(i.getType()===t&&n++,w(i instanceof r),i.elementaryStream===this.elementaryStream)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Ke}getDisposition(){return{...dt,primary:!1}}getTimeResolution(){return 9e4}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,n){let i;return this.allPacketsAreKeyPackets()?i="key":i=e.randomAccessIndicator===1?"key":"delta",new Oe(n.metadataOnly?st:e.data,i,e.pts/9e4,Math.max(t/9e4,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;w(t);let n=Qi(t,!0);w(n);let i=new qn(this.elementaryStream,n),s=new ca(this,i),a=await s.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){let u=await n.readNext();if(!u)return null;this.packetBuffers.delete(e);let d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}let i=this.packetSectionStarts.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");let a=await this.elementaryStream.demuxer.readSection(i,!0);w(a);let o=Qi(a,!0);w(o);let c=new qn(this.elementaryStream,o);n=new ca(this,c);let l=e.sequenceNumber;for(;;){let u=await n.readNext();if(!u)return null;if(u.packet.sequenceNumber>l){let d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type==="key")return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){let i=Mr(e*9e4),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,l=async(T,x,v)=>{let M=T;for(;M<x;){let C=await s.readPacketHeader(M);if(!C)return null;if(C.pid===c&&C.payloadUnitStartIndicator===1){let _=await s.readSection(M,v);if(!_)return null;let F=Wn(_,!1);if(F&&F.pts!==null)return{pesPacketHeader:F,section:_}}M+=s.packetStride}return null},u=this.elementaryStream.firstSection;w(u);let d=Wn(u,!0);if(w(d),i<d.pts)return null;let h,f=this.elementaryStream.referencePesPackets,p=_e(f,i,T=>T.pts),m=p!==-1?f[p]:null;if(m&&i-m.pts<9e4/2)h=m.sectionStartPos;else{let T=0;if(a.fileSize!==null){let x=Math.ceil(a.fileSize/o);if(x>1){let v=0,M=x-1;for(T=v;v<=M;){let C=Math.floor((v+M)/2),_=No(C*o,s.packetStride)+d.sectionStartPos,F=_+o,E=await l(_,F,!1);if(!E){M=C-1;continue}E.pesPacketHeader.pts<=i?(T=C,v=C+1):M=C-1}}}h=No(T*o,s.packetStride)+d.sectionStartPos}let y=(await l(h,a.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);let b=this.getReorderSize(),k=async(T,x)=>{let v=await s.readSection(T,!0);w(v);let M=Qi(v,!0);w(M);let C=new qn(this.elementaryStream,M),_=new ca(this,C);for(;!((ze(_.presentationOrderPackets)?.pts??-1/0)>=i||!await _.readNextPacket()););let F=Pi(_.presentationOrderPackets,x);if(F===-1)return null;let E=_.presentationOrderPackets[F],O=F===0?0:E.pts-_.presentationOrderPackets[F-1].pts;for(;_.decodeOrderPackets[0]!==E;)_.decodeOrderPackets.shift();_.lastDuration=O;let Q=await _.readNext();w(Q);let ye=this.createEncodedPacket(Q.packet,Q.duration,n);return this.packetBuffers.set(ye,_),this.packetSectionStarts.set(ye,Q.packet.sectionStartPos),ye};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let T=y.sectionStartPos+s.packetStride;for(;;){let x=await s.readPacketHeader(T);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){let v=await s.readSection(T,!1);if(v){let M=Wn(v,!1);if(M&&M.pts!==null){if(M.pts>i)break e;y=M,Yu(this.elementaryStream,y);break}}}T+=s.packetStride}}e:for(let T=0;T<b+1;T++){let x=y.sectionStartPos-s.packetStride;for(;x>=s.packetOffset;){let v=await s.readPacketHeader(x);if(!v)break e;if(v.pid===c&&v.payloadUnitStartIndicator===1){let M=await s.readSection(x,!1);if(M){let C=Wn(M,!1);if(C&&C.pts!==null){y=C;break}}}x-=s.packetStride}}return k(y.sectionStartPos,T=>T.pts<=i)}else{let T=h,x=null,v=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let M=null,C=T<=d.sectionStartPos,_,F=null;if(C)_=d,F=u;else{let Q=await l(T,a.fileSize??1/0,v);_=Q?.pesPacketHeader??null,F=Q?.section??null}let E=!1,O=0;e:for(;_&&!(x!==null&&_.sectionStartPos>=x);){if(_.pts<=i){let ye;if(this.elementaryStream.canBeTrustedWithKeyPackets)ye=_.randomAccessIndicator===1;else{w(F);let Z=Qi(F,!0);w(Z);let ee=new qn(this.elementaryStream,Z);await ee.markNextPacket(),ye=ee.suppliedPacket?.randomAccessIndicator===1}ye&&(M=_)}if(_.pts>i&&(E=!0),E&&(O++,O>b))break;let Q=_.sectionStartPos+s.packetStride;for(;;){let ye=await s.readPacketHeader(Q);if(!ye)break e;if(ye.pid===c&&ye.payloadUnitStartIndicator===1){let Z=await s.readSection(Q,v);if(Z){let ee=Wn(Z,!1);if(ee&&ee.pts!==null){_=ee,F=Z,Yu(this.elementaryStream,_);break}}}Q+=s.packetStride}}if(M){let Q=M;if(O===0)e:for(let Z=0;Z<b;Z++){let ee=Q.sectionStartPos-s.packetStride;for(;ee>=s.packetOffset;){let ve=await s.readPacketHeader(ee);if(!ve)break e;if(ve.pid===c&&ve.payloadUnitStartIndicator===1){let Re=await s.readSection(ee,v);if(Re){let et=Wn(Re,!1);if(et&&et.pts!==null){Q=et;break}}}ee-=s.packetStride}}let ye=await k(Q.sectionStartPos,Z=>Z.pts<=i&&Z.randomAccessIndicator===1);return w(ye),ye}if(C)return null;x=T,T=Math.max(No(T-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},Xu=class extends Ac{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return w(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Qu=class extends Ac{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return w(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},Yu=(r,e)=>{let t=r.referencePesPackets,n=_e(t,e.sectionStartPos,i=>i.sectionStartPos);if(n>=0){let i=t[n];if(e.pts<=i.pts)return!1;let s=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-i.sectionStartPos<s)return!1;if(n<t.length-1){let a=t[n+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return t.splice(n+1,0,e),!0},qn=class{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return w(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let n;if(this.pesPackets.length===0)n=this.startingPesPacket;else{let i=ze(this.pesPackets).sectionEndPos;for(w(i!==null);;){let s=await this.demuxer.readPacketHeader(i);if(!s)return;if(s.pid===this.pid){let a=await this.demuxer.readSection(i,!0);if(!a)return;let o=Qi(a,!1);if(o){n=o;break}}i+=this.demuxer.packetStride}}this.pesPackets.push(n),this.endPos+=n.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,i=n+e;if(this.currentPos+=e,i<=t.data.byteLength)return t.data.subarray(n,i);let s=new Uint8Array(e);s.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){let t=this.getCurrentPesPacket(),n=this.currentPesPacketPos+t.data.byteLength;if(e<n)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){w(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type==="video"){let t=e.info.codec,n=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");let i=t==="avc"?1:2,s=null,a=!1,o=0;for(;;){let c=this.ensureBuffered(n);if(c instanceof Promise&&(c=await c),c===0)break;let l=this.currentPos,u=this.readBytes(c),d=u.byteLength,h=0;for(;h<d;){let f=u.indexOf(0,h);if(f===-1||f>=d)break;h=f;let p=l+h;if(h+3>=d){this.seekTo(p);break}let m=u[h+1],g=u[h+2],y=u[h+3],b=0;if(m===0&&g===0&&y===1?b=4:m===0&&g===1&&(b=3),b===0){h++;continue}let k=p;s??=k;let T=h+b,x=T+i,v=6;if(x+(t==="avc"?v:1)>d){this.seekTo(p);break}let C=u[T],_,F,E;if(t==="avc")_=Li(C),F=_===lt.NON_IDR_SLICE||_===lt.SLICE_DPA||_===lt.IDR,E=_===lt.SEI||_===lt.SPS||_===lt.PPS||_===lt.AUD;else{if(_=un(C),((C&1)<<5|u[T+1]>>3)>0){h+=b;continue}F=_<=it.RASL_R||_>=it.BLA_W_LP&&_<=21,E=_>=it.VPS_NUT&&_<=37||_===it.PREFIX_SEI_NUT||_>=41&&_<=44||_>=48&&_<=55}let O=!1;if(F){let Q;if(t==="avc"){let ye=u.subarray(x,x+v),Z=Y(new Ie(ye));Q=!a||Z<=o,o=Z}else Q=u[x]>>7===1;Q&&(a?O=!0:a=!0)}else E&&a&&(O=!0);if(O){let Q=k-s;return this.seekTo(s),this.supplyPacket(Q,0)}h+=b}if(c<n)break}if(s!==null&&this.endPos>s){let c=this.endPos-s;return this.seekTo(s),this.supplyPacket(c,0)}}else{let t=e.info.codec,n=128;for(;;){let i=this.ensureBuffered(n);i instanceof Promise&&(i=await i);let s=this.currentPos;for(;this.currentPos-s<i;){let a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(tr);if(c instanceof Promise&&(c=await c),c<tr)return;let l=this.readBytes(tr),u=rr(yt.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return d instanceof Promise&&(d=await d),this.supplyPacket(d,Math.round(oa*9e4/e.info.sampleRate))}else this.seekTo(o+1)}else if(t==="mp3"){if(a!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(4);if(c instanceof Promise&&(c=await c),c<4)return;let l=this.readBytes(4),u=Ae(l).getUint32(0),d=Qs(u,null);if(d.header){this.seekTo(o);let h=this.ensureBuffered(d.header.totalSize);h instanceof Promise&&(h=await h);let f=d.header.audioSamplesInFrame*9e4/e.info.sampleRate;return this.supplyPacket(h,Math.round(f))}else this.seekTo(o+1)}else if(t==="ac3"){if(a!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}let h=Kp[3*d+u];w(h!==void 0),this.seekTo(o),c=this.ensureBuffered(h),c instanceof Promise&&(c=await c);let f=Math.round(jp*9e4/e.info.sampleRate);return this.supplyPacket(c,f)}else if(t==="eac3"){if(a!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let d=(((l[2]&7)<<8|l[3])+1)*2,f=l[4]>>6===3?3:l[4]>>4&3,p=Fu[f];this.seekTo(o),c=this.ensureBuffered(d),c instanceof Promise&&(c=await c);let m=p*256,g=Math.round(m*9e4/e.info.sampleRate);return this.supplyPacket(c,g)}else throw new Error("Unhandled.")}if(i<n)break}}}supplyPacket(e,t){let n=this.getCurrentPesPacket(),i;if(this.lastSuppliedPesPacket===n)w(this.nextPts!==null),i=this.nextPts;else{if(n.pts===null)throw new Error(Cg);i=n.pts,Yu(this.elementaryStream,n)}this.lastSuppliedPesPacket=n,this.nextPts=i+t;let s=n.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),c=n.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){let l=hn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(l)}}this.suppliedPacket={pts:i,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},ca=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),w(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);w(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let i=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(i))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(w(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let t=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[t].pts&&(t=i);let n=this.reorderBuffer[t];this.presentationOrderPackets.push(n),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};var vc="application/vnd.apple.mpegurl",Zu="#EXT-X-STREAM-INF:",Ju="#EXT-X-I-FRAME-STREAM-INF:",ed="#EXT-X-MEDIA:",la="#EXTINF:",td="#EXT-X-MAP:",rd="#EXT-X-KEY:",nd="#EXT-X-MEDIA-SEQUENCE:",id="#EXT-X-BYTERANGE:",sd="#EXT-X-PROGRAM-DATE-TIME:",Pg="#EXT-X-DISCONTINUITY",ad="#EXT-X-TARGETDURATION:",Eg="#EXT-X-ENDLIST",od="#EXT-X-PLAYLIST-TYPE:",Ig="#EXT-X-I-FRAMES-ONLY",_c=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT"),qr=class{constructor(e){this._attributes={};let t="",n="",i=!1,s=!1;for(let a=0;a<e.length;a++){let o=e[a];o==='"'?s=!s:o==="="&&!i&&!s?i=!0:o===","&&!s?(t&&(this._attributes[t.trim().toLowerCase()]=n),t="",n="",i=!1):i?n+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=n)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}};var Cc=class{constructor(e,t,n){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=n}async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(t??=await this.getFirstSegment({}),!t||t.unixEpochTimestamp===null)return null;let n=e-t.timestamp;return t.unixEpochTimestamp+n}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type==="video"){let n=On(e,i=>i.getType()==="video")+1;e.push(new Ec(this,t,n))}else if(t.type==="audio"){let n=On(e,i=>i.getType()==="audio")+1;e.push(new Ic(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let n=await this.getInputForSegment(this.firstSegment).getTracks();for(let i of n)if(i.type==="video"){let s=On(e,a=>a.getType()==="video")+1;e.push(new Ec(this,{id:e.length+1,type:"video"},s))}else if(i.type==="audio"){let s=On(e,a=>a.getType()==="audio")+1;e.push(new Ic(this,{id:e.length+1,type:"audio"},s))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(t!==void 0)return t;let n=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,n),n}async getMediaOffset(e,t){let n=e.firstSegment??e,i;if(this.firstSegmentFirstTimestamps.has(n))i=this.firstSegmentFirstTimestamps.get(n);else{let l=this.getInputForSegment(n);i=await this.getFirstTimestampForInput(l),this.firstSegmentFirstTimestamps.set(n,i)}if(n===e)return n.timestamp-i;let s=await this.getFirstTimestampForInput(t),a=e.timestamp-n.timestamp,c=s-i-a;return Math.abs(c)<=Math.min(.25,a)?n.timestamp-i:e.timestamp-s}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}},Pc=class{constructor(e,t,n){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let n=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(i=>i.type===this.decl.type&&i.number===this.number);if(!n)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=n})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),w(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,n){w(e.sequenceNumber>=0),w(this.segmentedInput.firstSegment);let i=await this.segmentedInput.getMediaOffset(t,n.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:Bn(e.timestamp+i,await n.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:n,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),w(this.segmentedInput.firstSegment),w(this.firstInputTrack);let t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,n){let i=this.packetInfos.get(e);if(!i)throw new Error("Packet was not created from this track.");let s=n?await i.track._backing.getNextKeyPacket(i.sourcePacket,t):await i.track._backing.getNextPacket(i.sourcePacket,t);if(s)return this.createAdjustedPacket(s,i.segment,i.track);let a=i.segment;for(;;){let o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;let u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(h=>h.type===i.track.type&&h.number===i.track.number);if(!u){a=o;continue}let d=await u._backing.getFirstPacket(t);return d?this.createAdjustedPacket(d,o,u):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,n){let i=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!i)return null;for(await this.hydrate();i;){let s=this.segmentedInput.getInputForSegment(i),o=(await s.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(i,s),l=e-c,u=n?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!u){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(u,i,o)}return null}},Ec=class extends Pc{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},Ic=class extends Pc{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}};Ii();var cd=0,ld=1/0,CT=null;typeof FinalizationRegistry<"u"&&(CT=new FinalizationRegistry(r=>{r()}));var wt=class extends Vt{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new ut;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,cd,ld),e=this._getFileSize(),w(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ut;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Fc(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Gn(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Gn=class{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");let e=this.source;w(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Ot=class extends wt{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=i=>{if(!(i instanceof wt||i instanceof Gn))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let s=i instanceof wt?i.ref():i;return s.source._usedForHls||=this._usedForHls,s};return t instanceof Promise?t.then(n):n(t)}},ud=(r,e)=>r.path===e.path,ua=class extends Ot{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,n,i){if(!this._root){if(!this._rootRequest){let s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{let c=o instanceof wt?o.ref():o;return this._root=c,this._rootRequest=null,c};s instanceof Promise?this._rootRequest=s.then(a):(a(s),w(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,t,n,i))}return this._root.source._read(e,t,n,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},da=class extends wt{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=Ye(e),this._view=Ae(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},ha=class extends wt{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Mi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Mc({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Fg.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,n,i){return this._orchestrator.read(e,t,n,i)}async _runWorker(e){w(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!an()&&this._options.useStreamReader!==!1?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:i}=await t.read();if(n)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},PT=.5*2**20,ET=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let i=null;try{typeof window<"u"&&typeof window.location<"u"&&(i=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&i!==null&&i!==window.location.origin)return we._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),Mg=new Set,fa=class r extends Ot{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Mi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");let n=e instanceof Request?e.url:e instanceof URL?e.href:e;super(n,a=>new r(a.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??ET,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){let a={...Uo(t.requestInit.headers)},o=Object.keys(a).find(c=>c.toLowerCase()==="range");o!==void 0&&(i=a[o],delete a[o],this._requestInit.headers=a)}if(e instanceof Request){let a=e.headers.get("Range");if(a!==null){i??=a;let o=new Request(e);o.headers.delete("Range"),this._url=o}}if(i!==null){let a=MT(i);a&&(this._offset=a.offset,this._length=a.length)}let s=2;this._orchestrator=new Mc({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:Fg.network})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;let e=this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:Ze(e-this._offset,0,this._length??1/0)}_read(e,t,n,i){if(this._length!==null&&t>this._length)return null;let s=this._offset,a=this._orchestrator.read(s+e,s+t,Math.max(s+n,s),s+Math.min(i,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return a instanceof Promise?a.then(o):o(a)}async _runWorker(e){for(;;){let t=new AbortController,n=await fp(this._options.fetchFn??fetch,this._url,hp(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(this._orchestrator.fileSize===null){let s=n.headers.get("Content-Range");if(s){let o=/\/(\d+)/.exec(s);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}let a=n.headers.get("Content-Length");a&&this._orchestrator.supplyFileSize(e.currentPos+Number(a))}if(this._fileSizeDetermined=!0,n.status!==206){if(!this._usedForHls){let s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(Mg.has(s.origin)||(we._warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),Mg.add(s.origin)))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize!==null?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await i.read()}catch(c){if(this._disposed)throw c;let l=this._getRetryDelay(1,c,this._url);if(l!==null){we._error("Error while reading response stream. Attempting to resume.",c),await Ks(1e3*l);break}else throw c}if(e.aborted)continue;let{done:a,value:o}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_dispose(){this._orchestrator.dispose()}},IT=/^bytes=(\d+)-(\d*)$/,MT=r=>{let e=IT.exec(r.trim());if(!e)return null;let t=Number(e[1]),n=e[2]===""?null:Number(e[2]);return n!==null&&n<t?null:{offset:t,length:n!==null?n-t+1:null}};var ma=class extends wt{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Mi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let n=_e(this._cache,e,u=>u.start),i=n!==-1?this._cache[n]:null;if(i&&i.start<=e&&t<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let s=e,a=new Uint8Array(t-e);if(n!==-1)for(let u=n;u<this._cache.length;u++){let d=this._cache[u];if(d.start>=t)break;let h=Math.max(e,d.start);h>s&&this._throwDueToCacheMiss();let f=Math.min(t,d.end);h<f&&(a.set(d.bytes.subarray(h-d.start,f-d.start),h-e),s=f)}if(s===t)return{bytes:a,view:Ae(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:o,resolve:c,reject:l}=nt();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else throw u})),o}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,i=this._currentIndex+t.byteLength;this._dispatchRead(n,i);for(let s=0;s<this._pendingSlices.length;s++){let a=this._pendingSlices[s],o=Math.max(n,a.start),c=Math.min(i,a.end);o<c&&(a.bytes.set(t.subarray(o-n,c-n),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:Ae(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:n,end:i,bytes:t,view:Ae(t),age:0});this._cache.length>0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},Fg={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(let i of t){let a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-8388608);if(zo(r,e,a,i.targetPos)){let o=i.targetPos-i.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,i.startPos+u)}}return e=Math.max(e,r+PT),{start:r,end:e}}},Mc=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,n,i){w(!this.disposed);let s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,n),o=Math.min(s.end,this.fileSize??1/0,i);w(a<=e&&t<=o);let c=null,l=_e(this.cache,e,x=>x.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});let d=_e(this.cache,a,x=>x.start),h=c?null:new Uint8Array(t-e),f=0,p=a,m=[];if(d!==-1){for(let x=d;x<this.cache.length;x++){let v=this.cache[x];if(v.start>=o)break;if(v.end<=a)continue;let M=Math.max(a,v.start),C=Math.min(o,v.end);if(w(M<=C),p<M&&m.push({start:p,end:M}),p=C,h){let _=Math.max(e,v.start),F=Math.min(t,v.end);if(_<F){let E=_-e;h.set(v.bytes.subarray(_-v.start,F-v.start),E),E===f&&(f=F-e)}}v.age=this.nextAge++}p<o&&m.push({start:p,end:o})}else m.push({start:a,end:o});if(h&&f>=h.length&&(c={bytes:h,view:Ae(h),offset:e}),m.length===0)return w(c),c;let{promise:g,resolve:y,reject:b}=nt(),k=[];for(let x of m){let v=Math.max(e,x.start),M=Math.min(t,x.end);v===x.start&&M===x.end?k.push(x):v<M&&k.push({start:v,end:M})}let T=h&&{start:e,bytes:h,holes:k,resolve:y,reject:b};e:for(let x of m){for(let C of this.workers)if(this.checkHoleAgainstWorker(C,x,T?[T]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}let v=x.end<o||this.fileSize!==null,M=this.createWorker(x.start,x.end,v);if(M)T&&(M.pendingSlices=[T]),this.runWorker(M);else{let C=_e(this.queuedReads,x.start,F=>F.hole.start),_=C!==-1?this.queuedReads[C]:null;for(_&&x.start<=_.hole.end?(_.hole.end=Math.max(_.hole.end,x.end),_.strictTarget&&=v,T&&_.pendingSlices.push(T)):(C++,_={hole:{start:x.start,end:x.end},strictTarget:v,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(C,0,_));C+1<this.queuedReads.length;){let F=this.queuedReads[C+1];if(F.hole.start>_.hole.end)break;_.hole.end=Math.max(_.hole.end,F.hole.end),_.pendingSlices.push(...F.pendingSlices),_.strictTarget&&=F.strictTarget,_.age=Math.min(_.age,F.age),this.queuedReads.splice(C+1,1)}}}return c?g.catch(x=>{if(!this.disposed)throw x}):(w(h),c=g.then(x=>x&&{bytes:x,view:Ae(x),offset:e})),c}checkHoleAgainstWorker(e,t,n){if(zo(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let s=0;s<n.length;s++){let a=n[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let n=0;n<this.queuedReads.length;n++){let i=this.queuedReads[n];if(this.checkHoleAgainstWorker(e,i.hole,i.pendingSlices))this.queuedReads.splice(n,1),n--,t=!0;else if(t)break}}createWorker(e,t,n){if(this.workers.length>=this.options.maxWorkerCount){let s=null,a=null;for(let o=0;o<this.workers.length;o++){let c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!s||c.age<s.age)&&(a=o,s=c)}if(s)w(a!==null),w(s.pendingSlices.length===0),this.workers.splice(a,1);else return null}let i={startPos:e,currentPos:e,targetPos:t,strictTarget:n,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){w(!e.running),w(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)throw t}).finally(()=>{if(!(e.running||this.workers.length>=this.options.maxWorkerCount)&&this.queuedReads.length>0){let t=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[t].age&&(t=s);let n=this.queuedReads[t];this.queuedReads.splice(t,1);let i=this.createWorker(n.hole.start,n.hole.end,n.strictTarget);w(i),i.pendingSlices=n.pendingSlices,this.runWorker(i)}})}consolidateEverythingIntoOneWorker(e){let t=new Set(e.pendingSlices);for(let n=0;n<this.workers.length;n++){let i=this.workers[n];if(i!==e){for(let s of i.pendingSlices)t.add(s);i.aborted=!0,i.pendingSlices.length=0,this.workers.splice(n,1),n--}}for(let n=0;n<this.queuedReads.length;n++){let i=this.queuedReads[n];for(let s of i.pendingSlices)t.add(s)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){w(!e.aborted);let n=e.currentPos,i=n+t.length;this.insertIntoCache({start:n,end:i,bytes:t,view:Ae(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let s=0;s<e.pendingSlices.length;s++){let a=e.pendingSlices[s],o=Math.max(n,a.start),c=Math.min(i,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-n,c-n),o-a.start);for(let l=0;l<a.holes.length;l++){let u=a.holes[l];n<=u.start&&i>u.start&&(u.start=i),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let a=this.workers[s];e===a||a.running||zo(n,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),s--)}}supplyFileSize(e){w(this.fileSize===null),this.fileSize=e;for(let t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let n=0;n<t.pendingSlices.length;n++){let i=t.pendingSlices[n];for(let s of i.holes)if(s.end>e){i.resolve(null),t.pendingSlices.splice(n,1),n--;break}}}for(let t=0;t<this.queuedReads.length;t++){let n=this.queuedReads[t];if(n.hole.start>=e){for(let i of n.pendingSlices)i.resolve(null);this.queuedReads.splice(t,1),t--}else if(n.hole.end>e){n.hole.end=e,n.strictTarget=!0;for(let i=0;i<n.pendingSlices.length;i++){let s=n.pendingSlices[i];s.start>=e&&(s.resolve(null),n.pendingSlices.splice(i,1),i--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){let t=this.workers.indexOf(e);w(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(let n of e.pendingSlices)n.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=_e(this.cache,e.start,n=>n.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let i=new Uint8Array(e.end-n.start);i.set(n.bytes,0),i.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=i,n.view=Ae(i),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let i=this.cache[n];if(e.end<=i.start)break;if(e.end>=i.end){this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length,n--;continue}let s=new Uint8Array(i.end-e.start);s.set(e.bytes,0),s.set(i.bytes,i.start-e.start),this.currentCacheSize-=e.end-i.start,e.bytes=s,e.view=Ae(s),e.end=i.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,i=this.cache[0];for(let s=1;s<this.cache.length;s++){let a=this.cache[s];a.age<i.age&&(n=s,i=a)}if(this.currentCacheSize-i.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};var Fc=class extends wt{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:Ze(e-this._offset,0,this._length??1/0)}_read(e,t,n,i){if(this._length!==null&&t>this._length)return null;let s=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+i),a=o=>o?(o.offset-=this._offset,o):null;return s instanceof Promise?s.then(a):a(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}};var Rg=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},Bg=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n}),FT=/^0[xX][0-9a-fA-F]+$/,RT=/^data:.*;base64,/i,pa=class extends Cc{constructor(e,t,n,i){super(e.input,t,n),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=i}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await Ks(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){let k={stack:[],error:void 0,hasError:!1};try{let T=Rg(k,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),v=await new yn(T.source).requestEntireFile();w(v),e=Rc(v,v.length,{ignore:_c}),T.source instanceof Ot&&(this.rootPath=T.source.rootPath)}catch(T){k.error=T,k.hasError=!0}finally{Bg(k)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=!1,i=0,s=null,a=null,o=null,c=0,l=null,u=null,d=null,h=null,f=null,p=null,m=!1,g=ze(this.segments)??null,y=k=>{let T=k.indexOf("@"),x=Number(T===-1?k:k.slice(0,T));if(!Number.isInteger(x)||x<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${k}'.`);let v=null;if(T!==-1&&(v=Number(k.slice(T+1)),!Number.isInteger(v)||v<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${k}'.`);return{length:x,offset:v}},b=k=>{c=k,g&&(w(g.sequenceNumber!==null),g.sequenceNumber<k&&(i=g.timestamp+g.duration,l=g.firstSegment,u=g.initSegment,f=g.lastProgramDateTimeSeconds,s=g.unixEpochTimestamp!==null?g.unixEpochTimestamp+g.duration:null,g=null))};for(let k=0;k<e.length;k++){let T=e[k];if(!n){if(T!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");n=!0;continue}if(!T.startsWith("#")){if(!g){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let x=o;if(x&&x.method==="AES-128"&&!x.iv){let _=new Uint8Array(Yt),F=Ae(_);F.setUint32(8,Math.floor(c/2**32)),F.setUint32(12,c),x={...x,iv:_}}let M={path:dr(this.rootPath,T),offset:h?.offset??0,length:h?.length??null},C={timestamp:i,unixEpochTimestamp:s,firstSegment:l,sequenceNumber:c,location:M,duration:a,encryption:x,initSegment:u,lastProgramDateTimeSeconds:f};l??=C,i+=a,s!==null&&(s+=a),this.segments.push(C)}a=null,h===null?d=null:h=null,b(c+1)}if(T.startsWith(la)){if(g){m=!0;continue}m||(f===null&&c>0&&p!==null&&(i=c*p),m=!0);let x=T.slice(la.length),v=x.indexOf(","),M=v===-1?x:x.slice(0,v),C=Number(M);if(!Number.isFinite(C)||C<0)throw new Error(`Invalid #EXTINF tag duration '${M}'.`);a=C}else if(T.startsWith(td)){let x=new qr(T.slice(td.length)),v=x.get("uri");if(!v)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let M=x.get("byterange"),C=null;if(M!==null&&(C=y(M)),C&&C.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){let F={path:dr(this.rootPath,v),offset:C?.offset??0,length:C?.length??null};if(o?.method==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");u={timestamp:i,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:F,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:f}}a=null,h===null?d=null:h=null}else if(T.startsWith(rd)){let x=new qr(T.slice(rd.length)),v=x.get("method");if(v==="NONE")o=null;else if(v==="AES-128"){let M=x.get("uri");if(!M)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let C=null,_=x.get("iv");if(_){if(!FT.test(_))throw new Error(`Unsupported IV format '${_}'.`);let E=_.slice(2);E=E.padStart(Yt*2,"0"),C=new Uint8Array(Yt);for(let O=0;O<Yt;O++){let Q=-Yt*2+O;C[O]=parseInt(E.slice(Q,Q+2),16)}}let F=x.get("keyformat")??"identity";if(F!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");o={method:"AES-128",keyUri:dr(this.rootPath,M),iv:C,keyFormat:F}}else if(v==="SAMPLE-AES"||v==="SAMPLE-AES-CTR"){let M=x.get("uri");if(!M)throw new Error(`Invalid #EXT-X-KEY: ${v} requires a URI attribute.`);if((x.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let _=null;if(RT.test(M)){let F=M.indexOf(","),E=Gs(M.slice(F+1));if(E.length>=8&&E[4]===112&&E[5]===115&&E[6]===115&&E[7]===104){let O=Ae(E).getUint32(0);_=nc(E.subarray(8,Math.min(O,E.length)))}}o={method:v,psshBox:_}}else throw new Error(`Unsupported encryption method '${v}'. If you think this method should be supported, please raise an issue.`)}else if(T.startsWith(nd)){let x=T.slice(nd.length),v=Number(x);if(!Number.isInteger(v)||v<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${x}'.`);b(v)}else if(T.startsWith(id)){let x=y(T.slice(id.length));if(x.offset===null){if(d===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");x.offset=d}h=x,d=x.offset+x.length}else if(T.startsWith(sd)){if(g)continue;let x=T.slice(sd.length),v=Date.parse(x);if(!Number.isFinite(v))continue;let M=v/1e3;if(f===M)continue;if(f===null&&this.segments.length>0){let C=ze(this.segments),_=C.timestamp+C.duration,F=M-_;for(let E of this.segments)E.unixEpochTimestamp=E.timestamp+F,t&&(E.timestamp=E.unixEpochTimestamp)}f=M,s=M,t&&(i=M)}else if(T===Pg)l=null;else if(T.startsWith(ad)){let x=T.slice(ad.length),v=Number(x);if(!Number.isFinite(v)||v<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${x}'.`);this.refreshInterval=v,p=v}else if(T===Eg){this.streamHasEnded=!0;break}else T.startsWith(od)&&T.slice(od.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!n)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let i=_e(this.segments,e,a=>a.timestamp);if(i===-1)return null;if(i<this.segments.length-1||this.streamHasEnded||n)return this.segments[i];let s=this.segments[i];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,t){let n=this.segments.indexOf(e);w(n!==-1);let i=n+1,s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return w(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,n=this.inputCache.find(c=>c.segment===t);if(n)return n.age=this.nextInputCacheAge++,n.input;let i=null;(t.initSegment||t.firstSegment)&&(i=this.getInputForSegment(t.initSegment??t.firstSegment));let s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(c=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(c);let l=c.psshBoxes,{psshBox:u}=t.encryption;return(u.keyIds===null||u.keyIds.includes(c.keyId))&&!l.some(d=>ic(d,u))&&(l=[...l,u]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:l})})}},a=new Gr({source:new ua(t.location.path,async c=>{w(c.isRoot);let l={...c,isRoot:!1},u,d=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(u=await this.input._getSourceCached(l),d){let f=u.source.slice(t.location.offset,t.location.length??void 0).ref();u.free(),u=f}}else if(t.encryption.method==="AES-128"){let h=t.encryption;w(h.iv);let f=await this.input._getSourceCached(l);if(d){let y=f.source.slice(t.location.offset,t.location.length??void 0).ref();f.free(),f=y}let p=new yn(f.source),m=Zp(p,async()=>{let g={stack:[],error:void 0,hasError:!1};try{let y=Rg(g,await this.input._getSourceCached({path:h.keyUri,isRoot:!1},Dg),!1),k=await new yn(y.source).requestSlice(0,Yt);if(!k)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:ie(k,Yt),iv:h.iv}}catch(y){g.error=y,g.hasError=!0}finally{Bg(g)}},()=>{f.free()});u=new ma(m).ref()}else w(!1);return u}),formats:this.input._formats.filter(c=>!(c instanceof Yi)),initInput:i??void 0,formatOptions:s});if(a._onFormatDetermined=c=>{if((t.encryption?.method==="SAMPLE-AES"||t.encryption?.method==="SAMPLE-AES-CTR")&&!c._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){let c=Fi(this.inputCache,l=>l.age);w(c!==-1),this.inputCache.splice(c,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}};var Dc=class extends ct{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{w(this.input._rootSource instanceof Ot);let e=await this.input._reader.requestEntireFile();w(e);let t=Rc(e,e.length,{ignore:_c}),{rootPath:n}=this.input._rootSource,i=[],s=[];for(let d=1;d<t.length;d++){let h=t[d];if(h.startsWith(Zu)){let f=d,p=t[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");let m=dr(n,p),g=new qr(h.slice(Zu.length));if(g.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");i.push({fullPath:m,attributes:g,lineNumber:f,hasOnlyKeyPackets:!1})}else if(h.startsWith(Ju)){let f=new qr(h.slice(Ju.length)),p=f.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(f.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let g=dr(n,p);i.push({fullPath:g,attributes:f,lineNumber:d,hasOnlyKeyPackets:!0})}else if(h.startsWith(ed)){let f=new qr(h.slice(ed.length));if(f.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(f.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let g=null,y=f.get("uri");y!==null&&(g=dr(n,y)),s.push({fullPath:g,attributes:f,lineNumber:d})}else if(h!==Ig){if(h.startsWith(la)){let f=new pa(this,n,null,t);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}}let a=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(i.map(async(d,h)=>{let f=[],p=d.attributes.get("codecs"),m;if(p)m=p.split(",").map(_=>_.trim());else{let F=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),E=await Promise.all(F.map(async O=>({track:O,codec:await O.getCodec()})));m=await Promise.all(E.filter(O=>O.codec!==null).map(O=>O.track.getDecoderConfig().then(Q=>Q.codec)))}let g=d.attributes.get("video"),y=d.attributes.get("audio"),b=m.some(_=>gt.includes(Rr(_))),k=m.some(_=>Ht.includes(Rr(_)));if(g!==null&&!b){if(!a.includes(g))throw new Error(`Invalid M3U8 file; variant stream references video group "${g}" which is not defined in any #EXT-X-MEDIA tags.`);let _=s.find(F=>{let E=F.attributes.get("group-id"),O=F.attributes.get("type");return E===g&&O.toLowerCase()==="video"});e:if(_){let F=_.attributes.get("uri");if(F===null)break e;let E=dr(n,F),ye=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(ee=>ee.getType()==="video");if(!ye||await ye.getCodec()===null)break e;let Z=await ye.getDecoderConfig().then(ee=>ee?.codec??null);w(Z!==null),m.push(Z)}}if(y!==null&&!k){if(!o.includes(y))throw new Error(`Invalid M3U8 file; variant stream references audio group "${y}" which is not defined in any #EXT-X-MEDIA tags.`);let _=s.find(F=>{let E=F.attributes.get("group-id"),O=F.attributes.get("type");return E===y&&O.toLowerCase()==="audio"});e:if(_){let F=_.attributes.get("uri");if(F===null)break e;let E=dr(n,F),ye=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(ee=>ee.getType()==="audio");if(!ye||await ye.getCodec()===null)break e;let Z=await ye.getDecoderConfig().then(ee=>ee?.codec??null);w(Z!==null),m.push(Z)}}m=[...new Set(m)];let T=null,x=null,v=d.attributes.getAsNumber("bandwidth");w(v!==null);let M=d.attributes.getAsNumber("average-bandwidth"),C=d.attributes.get("name");for(let _ of m){let F=Rr(_);if(F!==null){if(gt.includes(F)){if(T!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");T=_;let E=d.attributes.get("video");if(E===null){let O=d.attributes.get("resolution"),Q=null,ye=null;if(O){let Z=O.match(/^(\d+)x(\d+)$/);Z&&(Q=Number(Z[1]),ye=Number(Z[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Ke,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(h),peakBitrate:v,averageBitrate:M,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:Q,height:ye}})}else{if(!a.includes(E))throw new Error(`Invalid M3U8 file; variant stream references video group "${E}" which is not defined in any #EXT-X-MEDIA tags.`);for(let O of s){let Q=O.attributes.get("group-id"),ye=O.attributes.get("type");if(Q!==E||ye.toLowerCase()!=="video")continue;let Z=O.attributes.get("resolution")??d.attributes.get("resolution"),ee=null,ve=null;if(Z){let Re=Z.match(/^(\d+)x(\d+)$/);Re&&(ee=Number(Re[1]),ve=Number(Re[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:Bc(O.attributes),autoselect:Bc(O.attributes)||Og(O.attributes),languageCode:Lg(O.attributes.get("language")),lineNumber:O.lineNumber,fullPath:O.fullPath??d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:O.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:ee,height:ve}})}}}else if(Ht.includes(F)){if(x!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");x=_;let E=d.attributes.get("audio");if(E===null){let O=d.attributes.get("channels"),Q=O!==null?Number(O.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Ke,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:x,pairingMask:1n<<BigInt(h),peakBitrate:v,averageBitrate:M,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:Q!==null&&Number.isInteger(Q)&&Q>0?Q:null}})}else{if(!o.includes(E))throw new Error(`Invalid M3U8 file; variant stream references audio group "${E}" which is not defined in any #EXT-X-MEDIA tags.`);for(let O of s){let Q=O.attributes.get("group-id"),ye=O.attributes.get("type");if(Q!==E||ye.toLowerCase()!=="audio")continue;let Z=O.attributes.get("channels")??d.attributes.get("channels"),ee=Z!==null?Number(Z.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:Bc(O.attributes),autoselect:Bc(O.attributes)||Og(O.attributes),languageCode:Lg(O.attributes.get("language")),lineNumber:O.lineNumber,fullPath:O.fullPath??d.fullPath,fullCodecString:x,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:O.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:ee!==null&&Number.isInteger(ee)&&ee>0?ee:null}})}}}}}return f})),l=[],u=d=>{let h=l.find(f=>f.fullPath===d.fullPath&&f.info.type===d.info.type);h?(h.pairingMask|=d.pairingMask,h.default||=d.default,h.autoselect||=d.autoselect,h.lineNumber=Math.min(h.lineNumber,d.lineNumber),d.peakBitrate!==null&&(h.peakBitrate=Math.max(h.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(h.averageBitrate=Math.max(h.averageBitrate??-1/0,d.averageBitrate)),h.languageCode===Ke&&(h.languageCode=d.languageCode)):(d.id=l.length+1,l.push(d))};for(let d of c)for(let h of d)u(h);l.sort((d,h)=>d.lineNumber-h.lineNumber),this.trackBackings=[];for(let d of l)d.info.type==="video"?this.trackBackings.push(new Lc(d)):this.trackBackings.push(new Uc(d));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),w(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(i=>i.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),t=new pa(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return vc}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Oc=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,i=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(i.length===1)t=i[0];else if(this instanceof Lc){for(let s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}else{w(this instanceof Uc);for(let s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...dt,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){w(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},Lc=class extends Oc{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Rr(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},Uc=class extends Oc{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Rr(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},Bc=r=>{let e=r.get("default");if(e===null)return!1;let t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},Og=r=>{let e=r.get("autoselect");if(e===null)return!1;let t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},Lg=r=>{if(r===null)return Ke;let e=r.split("-")[0];return e||Ke};var Mt=class{constructor(){this._isIsobmff=!1}},ga=class extends Mt{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);let n=We(t,4);return n!=="ftyp"&&n!=="styp"?null:We(t,4)}_createDemuxer(e){return new oc(e)}},Nc=class extends ga{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!=="qt ";let n=e._reader.requestSlice(4,4);if(n instanceof Promise&&(n=await n),!n)return!1;let i=We(n,4);return i==="moof"||i==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}},zc=class extends ga{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},ya=class extends Mt{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,Jt);if(n instanceof Promise&&(n=await n),!n)return!1;let i=Ou(n);if(i===null||i<1||i>8||Ce(n,i)!==N.EBML)return!1;let a=Lu(n);if(typeof a!="number")return!1;let o=e._reader.requestSlice(n.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;let c=n.filePos;for(;o.filePos<=c+a-Et;){let l=er(o);if(!l)break;let{id:u,size:d}=l,h=o.filePos;if(d===void 0)return!1;switch(u){case N.EBMLVersion:if(Ce(o,d)!==1)return!1;break;case N.EBMLReadVersion:if(Ce(o,d)!==1)return!1;break;case N.DocType:if(mn(o,d)!==t)return!1;break;case N.DocTypeVersion:if(Ce(o,d)>4)return!1;break}o.filePos=h+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new gc(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Vc=class extends ya{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Hc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,mt);if(d instanceof Promise&&(d=await d),!d)break;let h=It(d);if(!h)break;t=d.filePos+h.size}let n=await sa(e._reader,t,t+4096);if(!n)return!1;let i=n.header,s=Go(i.mpegVersionId,i.channel),a=e._reader.requestSlice(n.startPos+s,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=j(a);if(o===Wo||o===qo)return!0;t=n.startPos+n.header.totalSize;let l=await sa(e._reader,t,t+4);if(!l)return!1;let u=l.header;return!(i.channel!==u.channel||i.sampleRate!==u.sampleRate)}_createDemuxer(e){return new wc(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Wc=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=We(t,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(t.skip(4),We(t,4)==="WAVE")}_createDemuxer(e){return new kc(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},qc=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?We(t,4)==="OggS":!1}_createDemuxer(e){return new bc(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Gc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,mt);if(i instanceof Promise&&(i=await i),!i)break;let s=It(i);if(!s)break;t=i.filePos+s.size}let n=e._reader.requestSlice(t,4);return n instanceof Promise&&(n=await n),n?We(n,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new xc(e)}},Kc=class extends Mt{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,mt);if(a instanceof Promise&&(a=await a),!a)break;let o=It(a);if(!o)break;t=a.filePos+o.size}let n=e._reader.requestSliceRange(t,Hn,tr);if(n instanceof Promise&&(n=await n),!n)return!1;let i=rr(n);if(!i||(t+=i.frameLength,n=e._reader.requestSliceRange(t,Hn,tr),n instanceof Promise&&(n=await n),!n))return!1;let s=rr(n);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new Sc(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},jc=class extends Mt{async _canReadInput(e){let t=205,n=e._reader.requestSlice(0,t);if(n instanceof Promise&&(n=await n),!n)return!1;let i=ie(n,t);return i[0]===71&&i[188]===71||i[0]===71&&i[204]===71?!0:i[4]===71&&i[196]===71}_createDemuxer(e){return new Tc(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},Yi=class extends Mt{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||!(We(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof Ot))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new Dc(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return vc}},$c=new Nc,Ug=new zc,Ng=new ya,zg=new Vc,Vg=new Hc,Hg=new Wc,Wg=new qc,qg=new Kc,Gg=new Gc,Kg=new jc,jg=new Yi,dd=[jg,$c,Ug,Ng,zg,Hg,Wg,Gg,Vg,qg,Kg];var $g=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(r.hls!==void 0){if(!r.hls||typeof r.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(r.hls.offsetTimestampsByDateTime!==void 0&&typeof r.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var BT=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},DT=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});Ii();var Xg=-1/0,Qg=-1/0,xa=null;typeof FinalizationRegistry<"u"&&(xa=new FinalizationRegistry(r=>{let e=performance.now();r.type==="video"?(e-Xg>=1e3&&(we._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Xg=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-Qg>=1e3&&(we._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Qg=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var Kr=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},hd=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],OT=new Set(hd),nr=class r{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!OT.has(t.format))throw new TypeError("init.format must be one of: "+hd.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let i of t.layout){if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(i.offset)||i.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(i.stride)||i.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&vu(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=t._doNotCopy?Ye(e):Ye(e).slice(),this._layout=t.layout??NT(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;let n=t.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new Sa(n),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");t?.visibleRect!==void 0&&vu(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Sa(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new r(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*ur),duration:Math.trunc((t.duration??0)*ur)||void 0}),t);let n=0,i=0;if("naturalWidth"in e?(n=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,i=e.videoHeight):"width"in e&&(n=Number(e.width),i=Number(e.height)),!n||!i)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(n,i),a=s.getContext("2d",{alpha:Hs(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n,height:i},this.squarePixelWidth=n,this.squarePixelHeight=i,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Sa({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Kr){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!hd.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=Ln({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),xa?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return w(this._data!==null),this._data instanceof Kr?new r(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):ba(this._data)?new r(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(w(this._layout),new r(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(xa?.unregister(this),this._data instanceof Kr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ba(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Zg(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return ba(this._data)?this._data.allocationSize(e):Jg(this,e).allocationSize}async copyTo(e,t={}){if(!Ci(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Zg(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(w(this._data!==null),ba(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof Kr){let l={stack:[],error:void 0,hasError:!1};try{let u=BT(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof r))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(u.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${u.format}' instead.`);return await u.copyTo(e,t)}catch(u){l.error=u,l.hasError=!0}finally{DT(l)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let l=this.toVideoFrame(),u=await l.copyTo(e,t);return l.close(),u}let n=Jg(this,t);w(this.format);let i=Ye(e);if(i.byteLength<n.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${n.allocationSize}, Available: ${i.byteLength}`);let s=Qc(this.format),a;if(this._data instanceof Kr){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 Kr){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let e=this._data.getDataPlanes();if(e instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let t=e.reduce((a,o)=>a+o.data.byteLength,0),n=new Uint8Array(t),i=0,s=[];for(let a of e)n.set(a.data,i),s.push(i),i+=a.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ba(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,i,s,a,o,c,l){let u=0,d=0,h=this.displayWidth,f=this.displayHeight,p=0,m=0,g=this.displayWidth,y=this.displayHeight;if(a!==void 0?(u=t,d=n,h=i,f=s,p=a,m=o,c!==void 0?(g=c,y=l):(g=h,y=f)):(p=t,m=n,i!==void 0&&(g=i,y=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:h,sHeight:f}=this._rotateSourceRegion(u,d,h,f,this.rotation));let b=this.toCanvasImageSource();e.save();let k=p+g/2,T=m+y/2;e.translate(k,T),e.rotate(this.rotation*Math.PI/180);let x=this.rotation%180===0?1:g/y;e.scale(1/x,x),e.drawImage(b,u,d,h,f,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Ta(t.crop,"options.");let n=e.canvas.width,i=e.canvas.height,s=t.rotation??this.rotation,[a,o]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=t.crop;c&&(c=fd(c,a,o));let l,u,d,h,{sx:f,sy:p,sWidth:m,sHeight:g}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,s);if(t.fit==="fill")l=0,u=0,d=n,h=i;else{let[b,k]=t.crop?[t.crop.width,t.crop.height]:[a,o],T=t.fit==="contain"?Math.min(n/b,i/k):Math.max(n/b,i/k);d=b*T,h=k*T,l=(n-d)/2,u=(i-h)/2}e.save();let y=s%180===0?1:d/h;e.translate(n/2,i/2),e.rotate(s*Math.PI/180),e.scale(1/y,y),e.translate(-n/2,-i/2),e.drawImage(this.toCanvasImageSource(),f,p,m,g,l,u,d,h),e.restore()}_rotateSourceRegion(e,t,n,i,s){return s===90?[e,t,n,i]=[t,this.squarePixelHeight-e-n,i,n]:s===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-i]:s===270&&([e,t,n,i]=[this.squarePixelWidth-t-i,e,i,n]),{sx:e,sy:t,sWidth:n,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(w(this._data!==null),this._data instanceof Kr||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&Ta(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let t=_i(this.rotation+(e.rotate??0)),[n,i]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=e.crop;s&&(s=fd(s,n,i));let a=s?s.width:n,o=s?s.height:i,c=a/o,l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=o),l=Vs(l,e.roundDimensionsTo??1),u=Vs(u,e.roundDimensionsTo??1);let d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:s??{left:0,top:0,width:n,height:i},alpha:e.alpha??"keep"};for(let m of LT){let g=m(this,d);if(g instanceof Promise&&(g=await g),g!==null)return g}let h=null,f=!1;for(let m of wa)if(m.canvas.width===d.width&&m.canvas.height===d.height){h=m.canvas,m.age=Yg++;break}if(h===null){if(typeof OffscreenCanvas<"u")h=new OffscreenCanvas(d.width,d.height);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");h=document.createElement("canvas"),h.width=d.width,h.height=d.height}f=!0,wa.length>=UT&&wa.splice(Fi(wa,m=>m.age),1),wa.push({canvas:h,age:Yg++})}let p=h.getContext("2d",{alpha:!0});if(!p)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return d.alpha==="discard"?(p.fillStyle="black",p.fillRect(0,0,d.width,d.height)):f||p.clearRect(0,0,d.width,d.height),this.drawWithFit(p,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new r(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}},LT=[];var UT=3,wa=[],Yg=0,Sa=class{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let t=Object.keys(Cr);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);let n=Object.keys(Pr);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(", ")}.`);let i=Object.keys(Er);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},ba=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,fd=(r,e,t)=>{let n=Math.min(r.left,e),i=Math.min(r.top,t),s=Math.min(r.width,e-n),a=Math.min(r.height,t-i);return w(s>=0),w(a>=0),{left:n,top:i,width:s,height:a}},Ta=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Zg=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},NT=(r,e,t)=>{let n=Qc(r),i=[],s=0;for(let a of n){let o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),l=o*a.sampleBytes,u=l*c;i.push({offset:s,stride:l}),s+=u}return i},Qc=r=>{let e=(t,n,i,s,a)=>{let o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:i,heightDivisor:s},{sampleBytes:n,widthDivisor:i,heightDivisor:s}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ct(r),w(!1)}},Jg=(r,e)=>{let t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},n=e.rect,i=zT(t,n,r.codedWidth,r.codedHeight,r.format),s=e.layout,a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return HT(i,a,s)},zT=(r,e,t,n,i)=>{let s={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>n)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!VT(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},VT=(r,e)=>{if(r===null)return!0;let t=Qc(r);for(let n=0;n<t.length;n++){let i=t[n],s=i.widthDivisor,a=i.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},HT=(r,e,t)=>{let n=Qc(e),i=n.length;if(t!==void 0&&t.length!==i)throw new TypeError(`Layout must have ${i} planes.`);let s=0,a=[],o=[];for(let c=0;c<i;c++){let l=n[c],u=l.sampleBytes,d=l.widthDivisor,h=l.heightDivisor,f={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(f.sourceTop=Math.ceil(Math.trunc(r.y||0)/h),f.sourceHeight=Math.ceil(Math.trunc(r.height||0)/h),f.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*u,f.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*u,t!==void 0){let g=t[c];if(g.stride<f.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);f.destinationOffset=g.offset,f.destinationStride=g.stride}else f.destinationOffset=s,f.destinationStride=f.sourceWidthBytes;let m=f.destinationStride*f.sourceHeight+f.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),s=Math.max(s,m);for(let g=0;g<c;g++){let y=a[g];if(!(o[c]<=y.destinationOffset||o[g]<=f.destinationOffset))throw new TypeError("Planes overlap.")}a.push(f)}return{allocationSize:s,computedLayouts:a}},Xc=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Kn=class{constructor(){this._referenceCount=0}},mr=class r{get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}constructor(e){if(this._closed=!1,ka(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof Kn){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Xc.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Xc.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let t=e.data.byteLength/(wn(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let i=this.numberOfFrames*this.numberOfChannels*wn(this.format);if(n.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}xa?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Xc.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let i=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(i>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let s=wn(t),a=jn(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?i:i*this.numberOfChannels)*s}copyTo(e,t){if(!Ci(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Xc.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{format:n,frameCount:i,frameOffset:s}=t,{planeIndex:a}=t,o=this.format,c=n??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");let h=i!==void 0?i:l-d;if(h>l-d)throw new RangeError("frameCount out of range");let f=wn(c),p=jn(c);if(p&&a>=u)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");let g=(p?h:h*u)*f;if(e.byteLength<g)throw new RangeError("Destination buffer is too small");let y=Ae(e),b=t0(c);if(ka(this._data))an()&&u>2&&c!==o?WT(this._data,y,o,c,u,a,d,h):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:h,format:c});else{let k=e0(o),T=wn(o),x=jn(o),v;if(this._data instanceof Kn){let C=_=>{let F=this._data.getDataPlane(_);if(!(F instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let E=l*T*(x?1:u);if(F.byteLength!==E)throw new TypeError(`Data plane ${_} has invalid size. Expected exactly ${E} bytes, got ${F.byteLength} bytes.`);return F};if(x)if(p)v=C(a),a=0;else{v=new Uint8Array(l*T*u);for(let _=0;_<u;_++){let F=C(_);v.set(F,_*l*T)}}else v=C(0)}else v=this._data;let M=Ae(v);for(let C=0;C<h;C++)if(p){let _=C*f,F;x?F=(a*l+(C+d))*T:F=((C+d)*u+a)*T;let E=k(M,F);b(y,_,E)}else for(let _=0;_<u;_++){let E=(C*u+_)*f,O;x?O=(_*l+(C+d))*T:O=((C+d)*u+_)*T;let Q=k(M,O);b(y,E,Q)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Kn){let e=new r(this._data);return e.setTimestamp(this.timestamp),e}else if(ka(this._data)){let e=new r(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endSample must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startSample out of range.");if(t>this.numberOfFrames)throw new RangeError("endSample out of range.");if(t<e)throw new RangeError("endSample must not be less than startSample.");if(this._closed)throw new Error("AudioSample is closed.");let n=t-e,i=wn(this.format),s;if(jn(this.format)){let a=n*i;if(s=new Uint8Array(a*this.numberOfChannels),n>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(s.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:n})}else s=new Uint8Array(n*this.numberOfChannels*i),n>0&&this.copyTo(s,{planeIndex:0,format:this.format,frameOffset:e,frameCount:n});return new r({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(xa?.unregister(this),this._data instanceof Kn?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ka(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof Kn?this._createAudioDataFromData():ka(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(jn(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(n/i),c=0,l=a;for(;l>0;){let u=Math.min(o,l),d=new Float32Array(i*u);for(let h=0;h<i;h++)e.copyFromChannel(d.subarray(h*u,(h+1)*u),h,c);yield new r({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:i,timestamp:t+c/s,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(n/i),c=0,l=a,u=[];for(;l>0;){let d=Math.min(o,l),h=new Float32Array(i*d);for(let p=0;p<i;p++)e.copyFromChannel(h.subarray(p*d,(p+1)*d),p,c);let f=new r({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:i,timestamp:t+c/s,data:h});u.push(f),c+=d,l-=d}return u}},wn=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},jn=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},e0=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},t0=r=>{switch(r){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,Ze((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,Ze(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,Ze(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},ka=r=>typeof AudioData<"u"&&r instanceof AudioData,r0=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},WT=(r,e,t,n,i,s,a,o)=>{let c=e0(t),l=t0(n),u=wn(t),d=wn(n),h=jn(t);if(jn(n))if(h){let p=new ArrayBuffer(o*u),m=Ae(p);r.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++){let y=g*u,b=g*d,k=c(m,y);l(e,b,k)}}else{let p=new ArrayBuffer(o*i*u),m=Ae(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++){let y=(g*i+s)*u,b=g*d,k=c(m,y);l(e,b,k)}}else if(h){let p=o*u,m=new ArrayBuffer(p),g=Ae(m);for(let y=0;y<i;y++){r.copyTo(m,{planeIndex:y,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){let k=b*u,T=(b*i+y)*d,x=c(g,k);l(e,T,x)}}}else{let p=new ArrayBuffer(o*i*u),m=Ae(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++)for(let y=0;y<i;y++){let b=g*i+y,k=b*u,T=b*d,x=c(m,k);l(e,T,x)}}},n0=(r,e)=>{let t=r.allocationSize({format:e,planeIndex:0}),n=new ArrayBuffer(t);return r.copyTo(n,{format:e,planeIndex:0}),new mr({data:n,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};var i0=new Map;var s0=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!gt.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${gt.join(", ")}.`);if(!(r.bitrate instanceof Lt)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.crop!==void 0&&Ta(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");a0(r.codec,r)},a0=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Rr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},md=r=>{let e=r.bitrate instanceof Lt?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??Tp(r.codec,r.width,r.height,e),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:e,bitrateMode:r.bitrateMode,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...Cp(r.codec)}},o0=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Ht.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${Ht.join(", ")}.`);if(r.bitrate===void 0&&!(ht.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(r.bitrate!==void 0&&!(r.bitrate instanceof Lt)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");qT(r.codec,r)},qT=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Rr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},c0=r=>{let e=r.bitrate instanceof Lt?r.bitrate._toAudioBitrate(r.codec):r.bitrate;return{codec:r.fullCodecString??vp(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:e,bitrateMode:r.bitrateMode,...Pp(r.codec)}},Lt=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,n){let i=t*n,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,c=Math.pow(i/a,.95),d=o*c*s[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(ht.includes(e)||e==="flac")return;let n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let i=n*this._factor;return e==="aac"?i=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-i)<Math.abs(a-i)?o:a):e==="opus"||e==="vorbis"?i=Math.max(6e3,i):e==="mp3"&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-i)<Math.abs(a-i)?o:a)),Math.round(i/1e3)*1e3}},l0=new Lt(.3),u0=new Lt(.6),d0=new Lt(1),h0=new Lt(2),f0=new Lt(4);var pd=async(r,e={})=>{let{width:t=1280,height:n=720,bitrate:i=1e6,...s}=e;if(!gt.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(n)||n<=0)throw new TypeError("height must be a positive integer.");if(!(i instanceof Lt)&&(!Number.isInteger(i)||i<=0))throw new TypeError("bitrate must be a positive integer or a quality.");a0(r,s);let a=md({codec:r,width:t,height:n,bitrate:i,framerate:void 0,...s,alpha:"discard"}),o=JSON.stringify(a),c=i0.get(o);if(c)return c;let l=(async()=>Yc.some(h=>h.supports(r,a))?!0:typeof VideoEncoder>"u"||(t%2===1||n%2===1)&&(r==="avc"||r==="hevc")||!(await VideoEncoder.isConfigSupported(a)).supported?!1:Hs()?new Promise(async h=>{try{let f=new VideoEncoder({output:()=>{},error:()=>h(!1)});f.configure(a);let p=new Uint8Array(t*n*4),m=new VideoFrame(p,{format:"RGBA",codedWidth:t,codedHeight:n,timestamp:0});f.encode(m),m.close(),await f.flush(),h(!0)}catch{h(!1)}}):!0)();return i0.set(o,l),l};var Zc=[],yd=[],Yc=[],gd=[];var m0=r=>{let n=r,i=4096,s=0,a=12,o=0;for(n<0&&(n=-n,s=128),n+=33,n>8191&&(n=8191);(n&i)!==i&&a>=5;)i>>=1,a--;return o=n>>a-4&15,~(s|a-5<<4|o)&255};var p0=r=>{let t=2048,n=0,i=11,s=0,a=r;for(a<0&&(a=-a,n=128),a>4095&&(a=4095);(a&t)!==t&&i>=5;)t>>=1,i--;return s=a>>(i===4?1:i-4)&15,(n|i-4<<4|s)^85};var $n=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},Zi=r=>{if(!Mi(r))throw new TypeError("timestamp must be a number.")},wd=(r,e,t)=>t.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let i=await r.determinePacketType(n);return i&&(n.type=i),n}):e,bn=class{constructor(e){if(!(e instanceof Ji))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if($n(e),this._track.input._disposed)throw new ut;return wd(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){$n(e);let t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Zi(e),$n(t),this._track.input._disposed)throw new ut;return wd(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if($n(t),this._track.input._disposed)throw new ut;return wd(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Zi(e),$n(t),this._track.input._disposed)throw new ut;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(w(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if($n(t),this._track.input._disposed)throw new ut;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(w(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof Oe))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof Oe))throw new TypeError("endPacket must be an EncodedPacket.");if($n(n),this._track.input._disposed)throw new ut;let i=[],{promise:s,resolve:a}=nt(),{promise:o,resolve:c}=nt(),l=!1,u=!1,d=null,h=[],f=()=>Math.max(2,h.length);(async()=>{let m=e??await this.getFirstPacket(n);for(;m&&!u&&!this._track.input._disposed&&!(t&&m.sequenceNumber>=t?.sequenceNumber);){if(i.length>f()){({promise:o,resolve:c}=nt()),await o;continue}i.push(m),a(),{promise:s,resolve:a}=nt(),m=await this.getNextPacket(m,n)}l=!0,a()})().catch(m=>{d||(d=m,a())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new ut;if(u)return{value:void 0,done:!0};if(d)throw d;if(i.length>0){let m=i.shift(),g=performance.now();for(h.push(g);h.length>0&&g-h[0]>=1e3;)h.shift();return c(),{value:m,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}},bd=class{constructor(e,t){this.onSample=e,this.onError=t}},Jc=class{mediaSamplesInRange(e=-1/0,t=1/0,n){Zi(e),Zi(t);let i=[],s=!1,a=null,{promise:o,resolve:c}=nt(),{promise:l,resolve:u}=nt(),d=!1,h=!1,f=!1,p=null,m={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let b=await this._createDecoder(C=>{if(u(),C.timestamp>=t&&(h=!0),h){C.close();return}a&&(C.timestamp>e?(i.push(a),s=!0):a.close()),C.timestamp>=e&&(i.push(C),s=!0),a=s?null:C,i.length>0&&(c(),{promise:o,resolve:c}=nt())},C=>{p||(p=C,c())}),k=this._createPacketSink(),T=await k.getKeyPacket(e,m)??await k.getFirstKeyPacket(m),x=T,M=k.packets(T??void 0,void 0,m);for(await M.next();x&&!h&&!this._track.input._disposed;){let C=g0(i.length);if(i.length+b.getDecodeQueueSize()>C){({promise:l,resolve:u}=nt()),await l;continue}b.decode(x);let _=await M.next();if(_.done)break;x=_.value}await M.return(),!f&&!this._track.input._disposed&&await b.flush(),b.close(),!s&&a&&i.push(a),d=!0,c()})().catch(b=>{p||(p=b,c())});let g=this._track,y=()=>{a?.close();for(let b of i)b.close()};return{async next(){for(;;){if(g.input._disposed)throw y(),new ut;if(f)return{value:void 0,done:!0};if(p)throw y(),p;if(i.length>0){let b=i.shift();return u(),{value:b,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,h=!0,u(),c(),y(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){lp(e);let n=cp(e),i=[],s=[],{promise:a,resolve:o}=nt(),{promise:c,resolve:l}=nt(),u=!1,d=!1,h=null,f=y=>{s.push(y),o(),{promise:a,resolve:o}=nt()},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let y=await this._createDecoder(C=>{if(l(),d){C.close();return}let _=0;for(;i.length>0&&C.timestamp-i[0]>-1e-10;)_++,i.shift();if(_>0)for(let F=0;F<_;F++)f(F<_-1?C.clone():C);else C.close()},C=>{h||(h=C,o())}),b=this._createPacketSink(),k=null,T=null,x=-1,v=async()=>{w(T);let C=T;for(y.decode(C);C.sequenceNumber<x;){let _=g0(s.length);for(;s.length+y.getDecodeQueueSize()>_&&!d;)({promise:c,resolve:l}=nt()),await c;if(d)break;let F=await b.getNextPacket(C,p);w(F),y.decode(F),C=F}x=-1},M=async()=>{await y.flush();for(let C=0;C<i.length;C++)f(null);i.length=0};for await(let C of n){if(Zi(C),d||this._track.input._disposed)break;let _=await b.getPacket(C,p),F=_&&await b.getKeyPacket(C,p);if(!F){x!==-1&&(await v(),await M()),f(null),k=null;continue}k&&(F.sequenceNumber!==T.sequenceNumber||_.timestamp<k.timestamp)&&(await v(),await M()),i.push(_.timestamp),x=Math.max(_.sequenceNumber,x),k=_,T=F}!d&&!this._track.input._disposed&&(x!==-1&&await v(),await M()),y.close(),u=!0,o()})().catch(y=>{h||(h=y,o())});let m=this._track,g=()=>{for(let y of s)y?.close()};return{async next(){for(;;){if(m.input._disposed)throw g(),new ut;if(d)return{value:void 0,done:!0};if(h)throw g(),h;if(s.length>0){let y=s.shift();return w(y!==void 0),l(),{value:y,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),g(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}},g0=r=>r===0?40:8,kd=class extends bd{constructor(e,t,n,i,s,a){super(e,t),this.codec=n,this.decoderConfig=i,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new nn,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.frameHandlerSerializer=new nn;let o=Zc.find(c=>c.supports(n,i));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof nr))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=u=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();w(d!==void 0),await this.mergeAlpha(u,d)}else this.colorQueue.push(u)}).catch(d=>this.onError(d))};if(n==="avc"&&this.decoderConfig.description&&Ws()){let u=Np(Ye(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){let d=Zs(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(w(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(w(this.decoder),an()||xu(this.inputTimestamps,e.timestamp,t=>t),Ws()&&this.currentPacketIndex===0){if(this.codec==="avc"){let t=[];for(let i of Iu(e.data,this.decoderConfig)){let s=Li(e.data[i.offset]);s===lt.AUD&&(t.length=0),s>=20&&s<=31||t.push(e.data.subarray(i.offset,i.offset+i.length))}let n=Lp(t,this.decoderConfig);e=new Oe(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){let t=Hp(e.data,this.decoderConfig);t&&(e=new Oe(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new el),!this.alphaDecoder){let n=s=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){let a=this.colorQueue.shift();w(a!==void 0),await this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let a=this.colorQueue.shift();w(a!==void 0),await this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(a=>this.onError(a))},i=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(s)}catch(a){this.onError(a)}},error:s=>{s.stack=i,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=hn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of Ys(e,this.decoderConfig)){let n=un(e[t.offset]);if(n===it.RASL_N||n===it.RASL_R)return!0}return!1}sampleHandler(e){if(an()){if(this.sampleQueue.length>0&&e.timestamp>=ze(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}xu(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();w(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){if(!t){let s=new nr(e);this.sampleHandler(s);return}w(this.merger);let n=await this.merger.update(e,t),i=new nr(n);this.sampleHandler(i)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(w(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await this.frameHandlerSerializer.currentPromise,this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),an()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(w(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},y0=!1,el=class r{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let e=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!r.forceCpu&&e&&!y0)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let t=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!t)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=t,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}catch(t){this.gl=null,this.canvas=null,y0=!0,we._warn("Falling back to CPU for color/alpha merging.",t)}}async update(e,t){return this.gl?this.updateGpu(e,t):this.updateCpu(e,t)}createProgram(){w(this.gl);let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
1872
- in vec2 a_position;
1873
- in vec2 a_texCoord;
1874
- out vec2 v_texCoord;
1875
-
1876
- void main() {
1877
- gl_Position = vec4(a_position, 0.0, 1.0);
1878
- v_texCoord = a_texCoord;
1879
- }
1880
- `),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
1881
- precision highp float;
1882
-
1883
- uniform sampler2D u_colorTexture;
1884
- uniform sampler2D u_alphaTexture;
1885
- in vec2 v_texCoord;
1886
- out vec4 fragColor;
1887
-
1888
- void main() {
1889
- vec3 color = texture(u_colorTexture, v_texCoord).rgb;
1890
- float alpha = texture(u_alphaTexture, v_texCoord).r;
1891
- fragColor = vec4(color, alpha);
1892
- }
1893
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){w(this.gl);let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){w(this.gl),w(this.program);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){w(this.gl);let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateGpu(e,t){w(this.gl),w(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let n=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),n}updateCpu(e,t){if(!this.worker){let s=new Blob([`(${GT.toString()})()`],{type:"application/javascript"}),a=URL.createObjectURL(s);this.worker=new Worker(a),URL.revokeObjectURL(a),this.worker.addEventListener("message",o=>{let c=o.data,l=this.pendingRequests.get(c.id);l&&(this.pendingRequests.delete(c.id),"error"in c?l.reject(new Error(c.error)):l.resolve(c.frame))}),this.worker.addEventListener("error",o=>{let c=new Error(o.message||"Color/alpha merge worker error.");for(let l of this.pendingRequests.values())l.reject(c);this.pendingRequests.clear()})}let n=this.nextRequestId++,i=nt();return this.pendingRequests.set(n,i),this.worker.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),i.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=new Error("Color/alpha merger closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};el.forceCpu=!0;var GT=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{let{id:l,color:u,alpha:d}=c.data;t=t.then(async()=>{try{let h=await n(u,d);self.postMessage({id:l,frame:h},{transfer:[h]})}catch(h){self.postMessage({id:l,error:h.message})}finally{u.close(),d.close()}})});let n=async(c,l)=>{let u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let h=u.includes("P10"),f=u.includes("P12"),p=d.includes("P10"),m=d.includes("P12");if(p!==h||m!==f)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);let g=c.codedWidth,y=c.codedHeight;if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await i(c,l,g,y,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await s(c,l,g,y,u);if(u==="NV12")return await a(c,l,g,y);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},i=async(c,l,u,d,h)=>{let f=u*d,p=new Uint8Array(f*4);await c.copyTo(p);let m=await o(l,u,d,1);for(let b=0,k=3;b<f;b++,k+=4)p[k]=m[b];let y={format:h==="RGBX"||h==="RGBA"?"RGBA":"BGRA",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},s=async(c,l,u,d,h)=>{let f=h.includes("P10"),p=h.includes("P12"),m=f||p?2:1,g,y;h.startsWith("I420")?(g=Math.ceil(u/2),y=Math.ceil(d/2)):h.startsWith("I422")?(g=Math.ceil(u/2),y=d):(g=u,y=d);let b=u*d,k=g*y,T=b*m,x=k*m,v=b*m,M=T+2*x+v,C=new Uint8Array(M);await c.copyTo(C);let _=await o(l,u,d,m),F=T+2*x;C.set(_,F);let O={format:h.slice(0,4)+"A"+h.slice(4),codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,O)},a=async(c,l,u,d)=>{let h=u*d,f=Math.ceil(u/2),p=Math.ceil(d/2),m=f*p,g=c.allocationSize();(!e||e.byteLength!==g)&&(e=new Uint8Array(g)),await c.copyTo(e);let y=new Uint8Array(h+2*m+h);y.set(e.subarray(0,h),0);let b=h,k=h+m,T=h;for(let M=0;M<m;M++)y[b+M]=e[T+M*2],y[k+M]=e[T+M*2+1];let x=await o(l,u,d,1);y.set(x,h+2*m);let v={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,v)},o=async(c,l,u,d)=>{let h=c.allocationSize();(!r||r.byteLength!==h)&&(r=new Uint8Array(h)),await c.copyTo(r);let f=c.format;if(f==="RGBA"||f==="BGRA"||f==="RGBX"||f==="BGRX"){let p=f==="RGBA"||f==="RGBX"?0:2,m=l*u;for(let g=0;g<m;g++)r[g]=r[g*4+p];return r.subarray(0,m)}else return r.subarray(0,l*u*d)}},KT=r=>{if(!r||typeof r!="object")throw new TypeError("decoderOptions must be an object.");if(r.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r.optimizeForLatency!==void 0&&typeof r.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")},Aa=class extends Jc{constructor(e,t={}){if(!(e instanceof Xn))throw new TypeError("videoTrack must be an InputVideoTrack.");KT(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=await this._track.getCodec(),i=await this._track.getRotation(),s=await this._track.getDecoderConfig(),a=await this._track.getTimeResolution();return w(n&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new kd(e,t,n,s,i,a)}_createPacketSink(){return new bn(this._track)}async getSample(e,t={}){Zi(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}};var Ji=class r{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Xn}isAudioTrack(){return this instanceof es}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Xe(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Xe(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Xe(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Xe(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Xe(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),n=(t?.timestamp??0)+(t?.duration??0);return Bn(n,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new bn(this),i=1/0,s=-1/0,a=0,o=0;for await(let c of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=s)break;i=Math.min(i,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-i)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(s-i)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(kn({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(kn({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(kn({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(kn({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(kn({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Sd(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Sd(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Sd(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},Xe=(r,e,t)=>{if(r instanceof Promise)throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},Sd=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{let t=i=>{if(typeof i!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return i},n=r(e);return n instanceof Promise?n.then(t):t(n)}:void 0},Xn=class extends Ji{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Xe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Xe(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Xe(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Xe(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Xe(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Xe(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Ln({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Ln({num:Xe(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Xe(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Xe(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Xe(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let i=Xe(e,"displayWidth","getDisplayWidth");if(i!==null)return i}let n=Xe(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Xe(n,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let i=Xe(e,"displayHeight","getDisplayHeight");if(i!==null)return i}let n=Xe(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Xe(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return w(t!==null),Zc.some(i=>i.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return we._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let t=await this.getCodec();if(t===null)return null;let n=await this.getDecoderConfig();return w(n),hn(t,n,e.data)}},es=class extends Ji{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Xe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Xe(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Xe(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return w(t!==null),yd.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return we._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}};var xd=r=>-(r??-1/0),ts=r=>-r,rs=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{let t=i=>{if(typeof i!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return i},n=r.filter(e);return n instanceof Promise?n.then(t):t(n)}:void 0,sortBy:r.sortBy?e=>{let t=i=>{if(typeof i!="number"&&(!Array.isArray(i)||!i.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return i},n=r.sortBy(e);return n instanceof Promise?n.then(t):t(n)}:void 0}},kn=(r,e)=>({filter:r?.filter||e?.filter?t=>{let n=r?.filter?.(t)??!0,i=s=>s===!1?!1:e?.filter?.(t)??!0;return n instanceof Promise?n.then(i):i(n)}:void 0,sortBy:r?.sortBy||e?.sortBy?t=>{let n=r?.sortBy?.(t)??[],i=e?.sortBy?.(t)??[],s=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([a,o])=>s(a,o)):s(n,i)}:void 0}),tl=async(r,e)=>{let t=r;if(e?.filter){let a=r.map(c=>e.filter(c));if(a.some(c=>c instanceof Promise)){let c=await Promise.all(a);t=r.filter((l,u)=>c[u])}else t=r.filter((c,l)=>a[l])}if(!e?.sortBy)return t;let n=t.map(a=>e.sortBy(a)),s=n.some(a=>a instanceof Promise)?await Promise.all(n):n;return t.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{let c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){let h=c[d]??0,f=l[d]??0;if(h!==f)return h-f}return 0}).map(a=>a.track)};Ii();var jT=1,Dg=2,Gr=class r extends Vt{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof Mt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof wt||e.source instanceof Gn))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof wt&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof r))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&$g(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof wt?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){w(this._rootSource instanceof Ot);let t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=jT){let n=this._sourceCache.find(a=>a.cacheGroup===t&&ud(a.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let i=this._sourceCachePromises.find(a=>a.cacheGroup===t&&ud(a.request,e));if(i)return i.promise.then(a=>a.sourceRef.source.ref());let s=(async()=>{let a=await this._getSourceUncached(e);if(On(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){let d=Fi(this._sourceCache,f=>f.cacheGroup===t&&f.sourceRef.source._refCount===1?f.age:1/0);w(d!==-1);let h=this._sourceCache[d];this._sourceCache.splice(d,1),h.sourceRef.free(),op(this._sourceRefs,h.sourceRef)}this._sourceRefs.push(a);let l=this._sourceCachePromises.findIndex(d=>d.request===e);return w(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(a=>{let o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new yn(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new va})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),w(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof va)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(i=>i!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(i=>i.getFirstTimestamp()));return Math.min(...n)}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(s=>s!==null);if(n.length===0)return 0;let i=await Promise.all(n.map(s=>s.computeDuration(t)));return Math.max(...i)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(a=>a!==null),s=(await Promise.all(n.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=rs(e);let n=(await this._getTrackBackings()).map(i=>this._wrapBackingAsTrack(i));return tl(n,e)}async getVideoTracks(e){e&&=rs(e);let n=(await this.getTracks()).filter(i=>i.isVideoTrack());return tl(n,e)}async getAudioTracks(e){e&&=rs(e);let n=(await this.getTracks()).filter(i=>i.isAudioTrack());return tl(n,e)}async getPrimaryVideoTrack(e){e&&=rs(e);let t=kn(e,{sortBy:async i=>[ts((await i.getDisposition()).default),ts(await i.hasPairableAudioTrack()),ts(!await i.hasOnlyKeyPackets()),xd(await i.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=rs(e);let t=await this.getPrimaryVideoTrack(),n=kn(e,{sortBy:async s=>[ts(!t||s.canBePairedWith(t)),ts((await s.getDisposition()).default),xd(await s.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let i=e.getType()==="video"?new Xn(this,e):new es(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},va=class extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}},ut=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var yn=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new ut;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let s=new Uint8Array(0);return new yt(s,Ae(s),0,e,e)}let n=e+t,i=this.source._read(e,n,cd,ld);return i instanceof Promise?i.then(s=>s?new yt(s.bytes,s.view,s.offset,e,n):null):i?new yt(i.bytes,i.view,i.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new ut;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Ze(this.fileSizeNonStrict-e,t,n));{let i=this.requestSlice(e,n),s=a=>a||(w(this.fileSizeNonStrict!==null),this.requestSlice(e,Ze(this.fileSizeNonStrict-e,t,n)));return i instanceof Promise?i.then(s):s(i)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let e=1024;return(async()=>{let t=[],n=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(n,0,e);if(a instanceof Promise&&(a=await a),!a||a.length===0)break;let o=ie(a,a.length);t.push(o),n+=a.length}let i=new Uint8Array(n),s=0;for(let a of t)i.set(a,s),s+=a.length;return new yt(i,Ae(i),0,0,n)})()}},yt=class r{constructor(e,t,n,i,s){this.bytes=e,this.view=t,this.offset=n,this.start=i,this.end=s,this.bufferPos=i-n}static tempFromBytes(e){return new r(e,Ae(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new r(this.bytes,this.view,this.offset,e,e+t)}},Ft=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},ie=(r,e)=>{Ft(r,e);let t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},ce=r=>(Ft(r,1),r.view.getUint8(r.bufferPos++)),Xi=(r,e)=>{Ft(r,2);let t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},je=r=>{Ft(r,2);let e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},Zt=r=>{Ft(r,3);let e=Ns(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},ra=r=>{Ft(r,2);let e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Hr=(r,e)=>{Ft(r,4);let t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},j=r=>{Ft(r,4);let e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},zn=r=>{Ft(r,4);let e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Or=r=>{Ft(r,4);let e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},$T=r=>{Ft(r,4);let e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},Ku=(r,e)=>{let t,n;return e?(t=Hr(r,!0),n=Hr(r,!0)):(n=Hr(r,!1),t=Hr(r,!1)),n*4294967296+t},Pt=r=>{let e=j(r),t=j(r);return e*4294967296+t},ig=r=>{let e=Or(r),t=j(r);return e*4294967296+t},gg=r=>{let e=zn(r);return $T(r)*4294967296+e},ag=r=>{Ft(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},dc=r=>{Ft(r,8);let e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},We=(r,e)=>{Ft(r,e);let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},Rc=(r,e,t)=>ot.decode(ie(r,e)).split(`
1894
- `).map(s=>s.trim()).filter(s=>s.length>0&&!t?.ignore?.(s));var Qn;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Qn||(Qn={}));var is;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(is||(is={}));var aa=128,mt=10,ss=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],lg=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=ie(r,aa-3),r.filePos=t;let n=ns(r,30);n&&(e.title??=n);let i=ns(r,30);i&&(e.artist??=i);let s=ns(r,30);s&&(e.album??=s);let a=ns(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(String(o)));let c=ie(r,30),l;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(e.trackNumber??=d),r.skip(-30),l=ns(r,28),r.skip(2)}else r.skip(-30),l=ns(r,30);l&&(e.comment??=l);let u=ce(r);u<ss.length&&(e.genre??=ss[u])},ns=(r,e)=>{let t=ie(r,e),n=Dn(t.indexOf(0),t.length),i=t.subarray(0,n),s="";for(let a=0;a<i.length;a++)s+=String.fromCharCode(i[a]);return s.trimEnd()},It=r=>{let e=r.filePos,t=We(r,3),n=ce(r),i=ce(r),s=ce(r),a=j(r);if(t!=="ID3"||n===255||i===255||(a&2155905152)!==0)return r.filePos=e,null;let o=Ko(a);return s&Qn.Footer&&(o+=mt),{majorVersion:n,revision:i,flags:s,size:o}},pn=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){we._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=e.flags&Qn.Footer?e.size-mt:e.size,i=ie(r,n),s=new Td(e,i);if(e.flags&Qn.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Qn.ExtendedHeader){let a=s.readU32();e.majorVersion===3?s.pos+=a:s.pos+=a-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){let a=s.readId3V2Frame();if(!a)break;let o=s.pos,c=s.pos+a.size,l=!1,u=!1,d=!1;if(e.majorVersion===3?(l=!!(a.flags&64),u=!!(a.flags&128)):e.majorVersion===4&&(l=!!(a.flags&4),u=!!(a.flags&8),d=!!(a.flags&2)||!!(e.flags&Qn.Unsynchronisation)),l){we._warn(`Skipping encrypted ID3v2 frame ${a.id}`),s.pos=c;continue}if(u){we._warn(`Skipping compressed ID3v2 frame ${a.id}`),s.pos=c;continue}if(d&&s.ununsynchronizeRegion(s.pos,c),t.raw??={},a.id==="TXXX"){let h=t.raw.TXXX??={},f=s.readId3V2TextEncoding(),p=s.readId3V2Text(f,c),m=s.readId3V2Text(f,c);h[p]??=m}else a.id[0]==="T"?t.raw[a.id]??=s.readId3V2EncodingAndText(c):t.raw[a.id]??=s.readBytes(a.size);switch(s.pos=o,a.id){case"TIT2":case"TT2":t.title??=s.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":t.description??=s.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":t.artist??=s.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":t.album??=s.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":t.albumArtist??=s.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{let f=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.trackNumber??=p),m&&Number.isInteger(m)&&m>0&&(t.tracksTotal??=m)}break;case"TPOS":case"TPA":{let f=s.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.discNumber??=p),m&&Number.isInteger(m)&&m>0&&(t.discsTotal??=m)}break;case"TCON":case"TCO":{let h=s.readId3V2EncodingAndText(c),f=/^\((\d+)\)/.exec(h);if(f){let p=Number.parseInt(f[1]);if(ss[p]!==void 0){t.genre??=ss[p];break}}if(f=/^\d+$/.exec(h),f){let p=Number.parseInt(f[0]);if(ss[p]!==void 0){t.genre??=ss[p];break}}t.genre??=h}break;case"TDRC":case"TDAT":{let h=s.readId3V2EncodingAndText(c),f=new Date(h);Number.isNaN(f.getTime())||(t.date??=f)}break;case"TYER":case"TYE":{let h=s.readId3V2EncodingAndText(c),f=Number.parseInt(h,10);Number.isInteger(f)&&(t.date??=new Date(String(f)))}break;case"USLT":case"ULT":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,c),t.lyrics??=s.readId3V2Text(h,c)}break;case"COMM":case"COM":{let h=s.readU8();s.pos+=3,s.readId3V2Text(h,c),t.comment??=s.readId3V2Text(h,c)}break;case"APIC":case"PIC":{let h=s.readId3V2TextEncoding(),f;if(e.majorVersion===2){let y=s.readAscii(3);f=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else f=s.readId3V2Text(h,c);let p=s.readU8(),m=s.readId3V2Text(h,c).trimEnd(),g=c-s.pos;if(g>=0){let y=s.readBytes(g);t.images||(t.images=[]),t.images.push({data:y,mimeType:f,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=a.size;break}s.pos=c}},Td=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let a=e;a<t;a++){let o=this.bytes[a];n.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}let i=this.bytes.subarray(0,e),s=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+n.length+s.length),this.bytes.set(i,0),this.bytes.set(n,i.length),this.bytes.set(s,i.length+n.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),n=this.header.majorVersion===4?Ko(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:Ko(t);a(o)&&(n=o)}return this.pos=s,{id:e,size:n,flags:i}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,i=this.readBytes(t-this.pos);switch(e){case is.ISO_8859_1:{let s="";for(let a=0;a<i.length;a++){let o=i[a];if(o===0){this.pos=n+a+1;break}s+=String.fromCharCode(o)}return s}case is.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){let s=new TextDecoder("utf-16le"),a=Dn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else if(i[0]===254&&i[1]===255){let s=new TextDecoder("utf-16be"),a=Dn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else{let s=Dn(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),ot.decode(i.subarray(0,s))}case is.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),a=Dn(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(0,a))}case is.UTF_8:{let s=Dn(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),ot.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var rl=class{constructor(e){this.mutex=new vt,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let i=this.trackTimestampInfo.get(e);if(i){if(n&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),i.maxTimestampBeforeLastKeyPacket!==null&&t<i.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);i.maxTimestamp=Math.max(i.maxTimestamp,t)}else{if(!n)throw new Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,i)}}};var Ad=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var w0=r=>{let e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),n=Math.floor(r%(60*1e3)/1e3),i=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+i.toString().padStart(3,"0")};var Yn=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let s of e.children)s&&this.writeBox(s);let n=this.writer.getPos(),i=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);w(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},Pe=new Uint8Array(8),Gt=new DataView(Pe.buffer),Je=r=>[(r%256+256)%256],xe=r=>(Gt.setUint16(0,r,!1),[Pe[0],Pe[1]]),Pd=r=>(Gt.setInt16(0,r,!1),[Pe[0],Pe[1]]),S0=r=>(Gt.setUint32(0,r,!1),[Pe[1],Pe[2],Pe[3]]),G=r=>(Gt.setUint32(0,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),jr=r=>(Gt.setInt32(0,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),yr=r=>(Gt.setUint32(0,Math.floor(r/2**32),!1),Gt.setUint32(4,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3],Pe[4],Pe[5],Pe[6],Pe[7]]),XT=r=>(Gt.setInt32(0,Math.floor(r/2**32),!1),Gt.setUint32(4,r,!1),[Pe[0],Pe[1],Pe[2],Pe[3],Pe[4],Pe[5],Pe[6],Pe[7]]),x0=r=>(Gt.setInt16(0,2**8*r,!1),[Pe[0],Pe[1]]),sr=r=>(Gt.setInt32(0,2**16*r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),vd=r=>(Gt.setInt32(0,2**30*r,!1),[Pe[0],Pe[1],Pe[2],Pe[3]]),_d=(r,e)=>{let t=[],n=r;do{let i=n&127;n>>=7,t.length>0&&(i|=128),t.push(i),e!==void 0&&e--}while(n>0||e);return t.reverse()},Ge=(r,e=!1)=>{let t=Array(r.length).fill(null).map((n,i)=>r.charCodeAt(i));return e&&t.push(0),t},T0=r=>{let e=r*(Math.PI/180),t=Math.round(Math.cos(e)),n=Math.round(Math.sin(e));return[t,n,0,-n,t,0,0,0,1]},A0=T0(0),v0=r=>[sr(r[0]),sr(r[1]),vd(r[2]),sr(r[3]),sr(r[4]),vd(r[5]),sr(r[6]),sr(r[7]),vd(r[8])],be=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),Ve=(r,e,t,n,i)=>be(r,[Je(e),S0(t),n??[]],i),_0=r=>r.isQuickTime?be("ftyp",[Ge("qt "),G(512),Ge("qt ")]):r.fragmented?r.cmaf?be("ftyp",[Ge("iso5"),G(512),Ge("iso5"),Ge("iso6"),Ge("mp41"),Ge("cmfc"),Ge("dash")]):be("ftyp",[Ge("iso5"),G(512),Ge("iso5"),Ge("iso6"),Ge("mp41")]):be("ftyp",[Ge("isom"),G(512),Ge("isom"),r.holdsAvc?Ge("avc1"):[],Ge("mp41")]),Ed=()=>be("styp",[Ge("iso5"),G(0),Ge("iso5"),Ge("iso6"),Ge("mp41"),Ge("cmfc"),Ge("dash")]),Id=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),Ve("sidx",1,0,[G(1),G(qt),yr($e(r.minWrittenTimestamp,qt)),yr(0),xe(0),xe(1),G(e&2147483647),G($e(t,qt)),G(0)])},_a=r=>({type:"mdat",largeSize:r}),C0=r=>({type:"free",size:r}),as=r=>be("moov",void 0,[QT(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>YT(e,r.creationTime)),r.isFragmented?OA(r.trackDatas):null,GA(r)]),QT=(r,e)=>{let t=Math.max(0,...e.map(a=>$e(nl(a),qt)+$e(a.startTimestampOffset??0,qt))),n=Math.max(0,...e.map(a=>a.track.id))+1,i=!_r(r)||!_r(t),s=i?yr:G;return Ve("mvhd",+i,0,[s(r),s(r),G(qt),s(t),sr(1),x0(1),Array(10).fill(0),v0(A0),Array(24).fill(0),G(n)])},nl=r=>{if(r.samples.length===0)return 0;let e=1/0,t=-1/0;for(let n=0;n<r.samples.length;n++){let i=r.samples[n];i.timestamp<e&&(e=i.timestamp),i.timestamp+i.duration>t&&(t=i.timestamp+i.duration)}return e===1/0?0:t-e},YT=(r,e)=>{let t=O0(r),n=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return be("trak",void 0,[ZT(r,e),n?JT(r,r.startTimestampOffset):null,eA(r,e),t.name!==void 0?be("udta",void 0,[be("name",[..._t.encode(t.name)])]):null])},ZT=(r,e)=>{let t=$e(nl(r),qt)+$e(r.startTimestampOffset??0,qt),n=!_r(e)||!_r(t),i=n?yr:G,s;if(r.type==="video"){let o=r.track.metadata.rotation;s=T0(o??0)}else s=A0;let a=2;return r.track.metadata.disposition?.default!==!1&&(a|=1),Ve("tkhd",+n,a,[i(e),i(e),G(r.track.id),G(0),i(t),Array(8).fill(0),xe(0),xe(r.track.id),x0(r.type==="audio"?1:0),xe(0),v0(s),sr(r.type==="video"?r.info.width:0),sr(r.type==="video"?r.info.height:0)])},JT=(r,e)=>{let t=$e(e,qt),n=$e(nl(r),qt),i=!_r(t)||!_r(n),s=i?yr:G,a=i?XT:jr;return be("edts",void 0,[Ve("elst",i?1:0,0,[G(2),s(t),a(-1),sr(1),s(n),a(0),sr(1)])])},eA=(r,e)=>be("mdia",void 0,[tA(r,e),Md(!0,rA[r.type],nA[r.type]),iA(r)]),tA=(r,e)=>{let t=$e(nl(r),r.timescale),n=!_r(e)||!_r(t),i=n?yr:G;return Ve("mdhd",+n,0,[i(e),i(e),G(r.timescale),i(t),xe(D0(r.track.metadata.languageCode??Ke)),xe(0)])},rA={video:"vide",audio:"soun",subtitle:"text"},nA={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Md=(r,e,t,n="\0\0\0\0")=>Ve("hdlr",0,0,[r?Ge("mhlr"):G(0),Ge(e),Ge(n),G(0),G(0),Ge(t,!0)]),iA=r=>be("minf",void 0,[cA[r.type](),lA(),hA(r)]),sA=()=>Ve("vmhd",0,1,[xe(0),xe(0),xe(0),xe(0)]),aA=()=>Ve("smhd",0,0,[xe(0),xe(0)]),oA=()=>Ve("nmhd",0,0),cA={video:sA,audio:aA,subtitle:oA},lA=()=>be("dinf",void 0,[uA()]),uA=()=>Ve("dref",0,0,[G(1)],[dA()]),dA=()=>Ve("url ",0,1),hA=r=>{let e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return be("stbl",void 0,[fA(r),EA(r),e?BA(r):null,e?DA(r):null,MA(r),FA(r),RA(r),IA(r)])},fA=r=>{let e;if(r.type==="video")e=mA(XA(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){let t=B0(r.track.source._codec,r.muxer.isQuickTime);w(t),e=kA(t,r)}else r.type==="subtitle"&&(e=CA(ZA[r.track.source._codec],r));return w(e),Ve("stsd",0,0,[G(1)],[e])},mA=(r,e)=>be(r,[Array(6).fill(0),xe(1),xe(0),xe(0),Array(12).fill(0),xe(e.info.width),xe(e.info.height),G(4718592),G(4718592),G(0),xe(1),Array(32).fill(0),xe(24),Pd(65535)],[QA[e.track.source._codec](e),pA(e),ip(e.info.decoderConfig.colorSpace)?gA(e):null]),pA=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:be("pasp",[G(r.info.pixelAspectRatio.num),G(r.info.pixelAspectRatio.den)]),gA=r=>be("colr",[Ge(r.muxer.isQuickTime?"nclc":"nclx"),xe(Cr[r.info.decoderConfig.colorSpace.primaries]),xe(Pr[r.info.decoderConfig.colorSpace.transfer]),xe(Er[r.info.decoderConfig.colorSpace.matrix]),r.muxer.isQuickTime?[]:Je((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),yA=r=>r.info.decoderConfig&&be("avcC",[...Ye(r.info.decoderConfig.description)]),wA=r=>r.info.decoderConfig&&be("hvcC",[...Ye(r.info.decoderConfig.description)]),b0=r=>{if(!r.info.decoderConfig)return null;let e=r.info.decoderConfig,t=e.codec.split("."),n=Number(t[1]),i=Number(t[2]),s=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(s<<4)+(a<<1)+o,l=t[5]?Number(t[5]):e.colorSpace?.primaries?Cr[e.colorSpace.primaries]:2,u=t[6]?Number(t[6]):e.colorSpace?.transfer?Pr[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):e.colorSpace?.matrix?Er[e.colorSpace.matrix]:2;return Ve("vpcC",1,0,[Je(n),Je(i),Je(c),Je(l),Je(u),Je(d),xe(0)])},bA=r=>be("av1C",Ap(r.info.decoderConfig.codec)),kA=(r,e)=>{let t=0,n,i=16,s=ht.includes(e.track.source._codec);if(s){let a=e.track.source._codec,{sampleSize:o}=Wt(a);i=8*o,i>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)n=[Array(6).fill(0),xe(1),xe(t),xe(0),G(0),xe(e.info.numberOfChannels),xe(i),xe(0),xe(0),xe(e.info.sampleRate<2**16?e.info.sampleRate:0),xe(0)];else{let a=s?0:-2;n=[Array(6).fill(0),xe(1),xe(t),xe(0),G(0),xe(e.info.numberOfChannels),xe(Math.min(i,16)),Pd(a),xe(0),xe(e.info.sampleRate<2**16?e.info.sampleRate:0),xe(0),s?[G(1),G(i/8),G(e.info.numberOfChannels*i/8)]:[G(0),G(0),G(0)],G(2)]}return be(r,n,[YA(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Cd=r=>{let e;switch(r.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let t=[...Je(e),...Je(21),...S0(0),...G(0),...G(0)];if(r.info.decoderConfig.description){let n=Ye(r.info.decoderConfig.description);t=[...t,...Je(5),..._d(n.byteLength),...n]}return t=[...xe(1),...Je(0),...Je(4),..._d(t.length),...t,...Je(6),...Je(1),...Je(2)],t=[...Je(3),..._d(t.length),...t],Ve("esds",0,0,t)},Sn=r=>be("wave",void 0,[SA(r),xA(r),be("\0\0\0\0")]),SA=r=>be("frma",[Ge(B0(r.track.source._codec,r.muxer.isQuickTime))]),xA=r=>{let{littleEndian:e}=Wt(r.track.source._codec);return be("enda",[xe(+e)])},TA=r=>{let e=r.info.numberOfChannels,t=3840,n=r.info.sampleRate,i=0,s=0,a=new Uint8Array(0),o=r.info.decoderConfig?.description;if(o){w(o.byteLength>=18);let c=Ye(o),l=Yo(c);e=l.outputChannelCount,t=l.preSkip,n=l.inputSampleRate,i=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return be("dOps",[Je(0),Je(e),xe(t),G(n),Pd(i),Je(s),...a])},AA=r=>{let e=r.info.decoderConfig?.description;w(e);let t=Ye(e);return Ve("dfLa",0,0,[...t.subarray(4)])},pr=r=>{let{littleEndian:e,sampleSize:t}=Wt(r.track.source._codec),n=+e;return Ve("pcmC",0,0,[Je(n),Je(8*t)])},vA=r=>{let e=Zo(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let t=new Uint8Array(3),n=new Ie(t);return n.writeBits(2,e.fscod),n.writeBits(5,e.bsid),n.writeBits(3,e.bsmod),n.writeBits(3,e.acmod),n.writeBits(1,e.lfeon),n.writeBits(5,e.bitRateCode),n.writeBits(5,0),be("dac3",[...t])},_A=r=>{let e=Jo(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(let a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;let n=Math.ceil(t/8),i=new Uint8Array(n),s=new Ie(i);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(let a of e.substreams)s.writeBits(2,a.fscod),s.writeBits(5,a.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,a.bsmod),s.writeBits(3,a.acmod),s.writeBits(1,a.lfeon),s.writeBits(3,0),s.writeBits(4,a.numDepSub),a.numDepSub>0?s.writeBits(9,a.chanLoc):s.writeBits(1,0);return be("dec3",[...i])},CA=(r,e)=>be(r,[Array(6).fill(0),xe(1)],[JA[e.track.source._codec](e)]),PA=r=>be("vttC",[..._t.encode(r.info.config.description)]);var EA=r=>Ve("stts",0,0,[G(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[G(e.sampleCount),G(e.sampleDelta)])]),IA=r=>{if(r.samples.every(t=>t.type==="key"))return null;let e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return Ve("stss",0,0,[G(e.length),e.map(([t])=>G(t+1))])},MA=r=>Ve("stsc",0,0,[G(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[G(e.firstChunk),G(e.samplesPerChunk),G(1)])]),FA=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){let{sampleSize:e}=Wt(r.track.source._codec);return Ve("stsz",0,0,[G(e*r.info.numberOfChannels),G(r.samples.reduce((t,n)=>t+$e(n.duration,r.timescale),0))])}return Ve("stsz",0,0,[G(0),G(r.samples.length),r.samples.map(e=>G(e.size))])},RA=r=>r.finalizedChunks.length>0&&ze(r.finalizedChunks).offset>=2**32?Ve("co64",0,0,[G(r.finalizedChunks.length),r.finalizedChunks.map(e=>yr(e.offset))]):Ve("stco",0,0,[G(r.finalizedChunks.length),r.finalizedChunks.map(e=>G(e.offset))]),BA=r=>Ve("ctts",1,0,[G(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[G(e.sampleCount),jr(e.sampleCompositionTimeOffset)])]),DA=r=>{let e=1/0,t=-1/0,n=1/0,i=-1/0;w(r.compositionTimeOffsetTable.length>0),w(r.samples.length>0);for(let a=0;a<r.compositionTimeOffsetTable.length;a++){let o=r.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<r.samples.length;a++){let o=r.samples[a];n=Math.min(n,$e(o.timestamp,r.timescale)),i=Math.max(i,$e(o.timestamp+o.duration,r.timescale))}let s=Math.max(-e,0);return i>=2**31?null:Ve("cslg",0,0,[jr(s),jr(e),jr(t),jr(n),jr(i)])},OA=r=>be("mvex",void 0,r.map(LA)),LA=r=>Ve("trex",0,0,[G(r.track.id),G(1),G(0),G(0),G(0)]),Fd=(r,e)=>be("moof",void 0,[UA(r),...e.map(NA)]),UA=r=>Ve("mfhd",0,0,[G(r)]),P0=r=>{let e=0,t=0,n=0,i=0,s=r.type==="delta";return t|=+s,s?e|=1:e|=2,e<<24|t<<16|n<<8|i},NA=r=>be("traf",void 0,[zA(r),VA(r),HA(r)]),zA=r=>{w(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let t=r.currentChunk.samples[1]??r.currentChunk.samples[0],n={duration:t.timescaleUnitsToNextSample,size:t.size,flags:P0(t)};return Ve("tfhd",0,e,[G(r.track.id),G(n.duration),G(n.size),G(n.flags)])},VA=r=>(w(r.currentChunk),Ve("tfdt",1,0,[yr($e(r.currentChunk.startTimestamp,r.timescale))])),HA=r=>{w(r.currentChunk);let e=r.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(m=>m.size),n=r.currentChunk.samples.map(P0),i=r.currentChunk.samples.map(m=>$e(m.timestamp-m.decodeTimestamp,r.timescale)),s=new Set(e),a=new Set(t),o=new Set(n),c=new Set(i),l=o.size===2&&n[0]!==n[1],u=s.size>1,d=a.size>1,h=!l&&o.size>1,f=c.size>1||[...c].some(m=>m!==0),p=0;return p|=1,p|=4*+l,p|=256*+u,p|=512*+d,p|=1024*+h,p|=2048*+f,Ve("trun",1,p,[G(r.currentChunk.samples.length),G(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?G(n[0]):[],r.currentChunk.samples.map((m,g)=>[u?G(e[g]):[],d?G(t[g]):[],h?G(n[g]):[],f?jr(i[g]):[]])])},E0=r=>be("mfra",void 0,[...r.map(WA),qA()]),WA=(r,e)=>Ve("tfra",1,0,[G(r.track.id),G(63),G(r.finalizedChunks.length),r.finalizedChunks.map(n=>[yr($e(n.samples[0].timestamp,r.timescale)),yr(n.moofOffset),G(e+1),G(1),G(1)])]),qA=()=>Ve("mfro",0,0,[G(0)]),I0=()=>be("vtte"),M0=(r,e,t,n,i)=>be("vttc",void 0,[i!==null?be("vsid",[jr(i)]):null,t!==null?be("iden",[..._t.encode(t)]):null,e!==null?be("ctim",[..._t.encode(w0(e))]):null,n!==null?be("sttg",[..._t.encode(n)]):null,be("payl",[..._t.encode(r)])]),F0=r=>be("vtta",[..._t.encode(r)]),GA=r=>{let e=[],t=r.format._options.metadataFormat??"auto",n=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){let i=jA(n);i&&e.push(i)}else if(t==="mdta"){let i=$A(n);i&&e.push(i)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&KA(e,r.output._metadataTags);return e.length===0?null:be("udta",void 0,e)},KA=(r,e)=>{for(let{key:t,value:n}of qs(e))switch(t){case"title":r.push(gr("\xA9nam",n));break;case"description":r.push(gr("\xA9des",n));break;case"artist":r.push(gr("\xA9ART",n));break;case"album":r.push(gr("\xA9alb",n));break;case"albumArtist":r.push(gr("albr",n));break;case"genre":r.push(gr("\xA9gen",n));break;case"date":r.push(gr("\xA9day",n.toISOString().slice(0,10)));break;case"comment":r.push(gr("\xA9cmt",n));break;case"lyrics":r.push(gr("\xA9lyr",n));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Ct(t)}if(e.raw)for(let t in e.raw){let n=e.raw[t];n==null||t.length!==4||r.some(i=>i.type===t)||(typeof n=="string"?r.push(gr(t,n)):n instanceof Uint8Array&&r.push(be(t,Array.from(n))))}},gr=(r,e)=>{let t=_t.encode(e);return be(r,[xe(t.length),xe(D0("und")),Array.from(t)])},k0={"image/jpeg":13,"image/png":14,"image/bmp":27},R0=(r,e)=>{let t=[];for(let{key:n,value:i}of qs(r))switch(n){case"title":t.push({key:e?"title":"\xA9nam",value:ir(i)});break;case"description":t.push({key:e?"description":"\xA9des",value:ir(i)});break;case"artist":t.push({key:e?"artist":"\xA9ART",value:ir(i)});break;case"album":t.push({key:e?"album":"\xA9alb",value:ir(i)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:ir(i)});break;case"comment":t.push({key:e?"comment":"\xA9cmt",value:ir(i)});break;case"genre":t.push({key:e?"genre":"\xA9gen",value:ir(i)});break;case"lyrics":t.push({key:e?"lyrics":"\xA9lyr",value:ir(i)});break;case"date":t.push({key:e?"date":"\xA9day",value:ir(i.toISOString().slice(0,10))});break;case"images":for(let s of i)s.kind==="coverFront"&&t.push({key:"covr",value:be("data",[G(k0[s.mimeType]??0),G(0),Array.from(s.data)])});break;case"trackNumber":if(e){let s=r.tracksTotal!==void 0?`${i}/${r.tracksTotal}`:i.toString();t.push({key:"track",value:ir(s)})}else t.push({key:"trkn",value:be("data",[G(0),G(0),xe(0),xe(i),xe(r.tracksTotal??0),xe(0)])});break;case"discNumber":e||t.push({key:"disc",value:be("data",[G(0),G(0),xe(0),xe(i),xe(r.discsTotal??0),xe(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Ct(n)}if(r.raw)for(let n in r.raw){let i=r.raw[n];i==null||!e&&n.length!==4||t.some(s=>s.key===n)||(typeof i=="string"?t.push({key:n,value:ir(i)}):i instanceof Uint8Array?t.push({key:n,value:be("data",[G(0),G(0),Array.from(i)])}):i instanceof $t&&t.push({key:n,value:be("data",[G(k0[i.mimeType]??0),G(0),Array.from(i.data)])}))}return t},jA=r=>{let e=R0(r,!1);return e.length===0?null:Ve("meta",0,0,void 0,[Md(!1,"mdir","","appl"),be("ilst",void 0,e.map(t=>be(t.key,void 0,[t.value])))])},$A=r=>{let e=R0(r,!0);return e.length===0?null:be("meta",void 0,[Md(!1,"mdta",""),Ve("keys",0,0,[G(e.length)],e.map(t=>be("mdta",[..._t.encode(t.key)]))),be("ilst",void 0,e.map((t,n)=>{let i=String.fromCharCode(...G(n+1));return be(i,void 0,[t.value])}))])},ir=r=>be("data",[G(1),G(0),..._t.encode(r)]),XA=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},QA={avc:yA,hevc:wA,vp8:b0,vp9:b0,av1:bA},B0=(r,e)=>{switch(r){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(r){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(r){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},YA=(r,e)=>{switch(r){case"aac":return Cd;case"mp3":return Cd;case"opus":return TA;case"vorbis":return Cd;case"flac":return AA;case"ac3":return vA;case"eac3":return _A}if(e)switch(r){case"pcm-s24":return Sn;case"pcm-s24be":return Sn;case"pcm-s32":return Sn;case"pcm-s32be":return Sn;case"pcm-f32":return Sn;case"pcm-f32be":return Sn;case"pcm-f64":return Sn;case"pcm-f64be":return Sn}else switch(r){case"pcm-s16":return pr;case"pcm-s16be":return pr;case"pcm-s24":return pr;case"pcm-s24be":return pr;case"pcm-s32":return pr;case"pcm-s32be":return pr;case"pcm-f32":return pr;case"pcm-f32be":return pr;case"pcm-f64":return pr;case"pcm-f64be":return pr}return null},ZA={webvtt:"wvtt"},JA={webvtt:PA},D0=r=>{w(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};var Zn=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){w(!this.started),this.target._start(),this.started=!0}write(e){w(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return w(this.started&&!this.finalized),this.target._flush()}async finalize(){w(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,i=this.trackedWrites.byteLength;for(;i<n;)i*=2;if(i!==this.trackedWrites.byteLength){let s=new Uint8Array(i);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}};var Rt=class extends Vt{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new il(this,e)}},Rd=2**16,Bd=2**32,ar=class extends Rt{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Rd,{maxByteLength:Bd})}catch{this._buffer=new ArrayBuffer(Rd),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Rd);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Bd)throw new Error(`ArrayBuffer exceeded maximum size of ${Bd} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let n=new ArrayBuffer(t),i=new Uint8Array(n);i.set(this._bytes,0),this._buffer=n,this._bytes=i}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},ev=2**24,tv=2,Ca=class extends Rt{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??ev}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){let n=t-this._lastWriteEnd;this._write(new Uint8Array(n),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(w(this._streamWriter),this._sections.length===0)return;let e=[],t=[...this._sections].sort((n,i)=>n.start-i.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let n=1;n<t.length;n++){let i=e[e.length-1],s=t[n];s.start<=i.start+i.size?i.size=Math.max(i.size,s.start+s.data.byteLength-i.start):e.push({start:s.start,size:s.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let i of this._sections)n.start<=i.start&&i.start<n.start+n.size&&n.data.set(i.data,i.start-n.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(n.data,n.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&n.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data,position:n.start}).catch(i=>{this._writeError??=i}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let n=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);n===-1&&(n=this._createChunk(t));let i=this._chunks[n],s=t-i.start,a=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));i.data.set(a,s);let o={start:s,end:s+a.byteLength};if(this._insertSectionIntoChunk(i,o),i.written[0].start===0&&i.written[0].end===this._chunkSize&&(i.shouldFlush=!0),this._chunks.length>tv){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let n=0,i=e.written.length-1,s=-1;for(;n<=i;){let a=Math.floor(n+(i-n+1)/2);e.written[a].start<=t.start?(n=a+1,s=a):i=a-1}for(e.written.splice(s+1,0,t),(s===-1||e.written[s].end<t.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((i,s)=>i.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){w(this._streamWriter);for(let t=0;t<this._chunks.length;t++){let n=this._chunks[t];if(!(!n.shouldFlush&&!e)){for(let i of n.written){let s=n.start+i.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data.subarray(i.start,i.end),position:s}).catch(a=>{this._writeError??=a}),this._lastFlushEnd=n.start+i.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;w(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}};var il=class extends Rt{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},Jn=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}};var qt=57600,rv=2082844800,O0=r=>{let e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},$e=(r,e,t=!0)=>{let n=r*e;return t?Math.round(n):n},sl=class extends rl{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new ar,this.auxWriter=new Zn(this.auxTarget,!1),this.auxBoxWriter=new Yn(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=nt(),this.creationTime=Math.floor(Date.now()/1e3)+rv,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof cs,this.isCmaf=t instanceof os,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof os?1/0:1)}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":n instanceof ar),this.boxWriter=new Yn(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof ar?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let n=await this.output._getInitTarget(),i=new Zn(n,!0);i.start(),this.initWriter=i,this.initBoxWriter=new Yn(i)}let t=this.output._tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(w(n),this.format._options.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(_0({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:i,start:s}=n.writer.stopTrackingWrites();this.format._options.onFtyp(i,s)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output._tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(w(this.writer),w(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=_a(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return rc({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,n){let i=this.trackDatas.find(h=>h.track===e);if(i)return i;Ep(n),w(n),w(n.decoderConfig);let s={...n.decoderConfig};w(s.codedWidth!==void 0),w(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){let h=Ui(t.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=Up(h),a=!0}else if(e.source._codec==="hevc"&&!s.description){let h=Ni(t.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=Vp(h),a=!0}let o=mp(1/(e.metadata.frameRate??qt),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:Ln({num:c*s.codedHeight,den:l*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:u,decoderConfig:s,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((h,f)=>h.track.id-f.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let i=this.trackDatas.find(c=>c.track===e);if(i)return i;Ip(n),w(n),w(n.decoderConfig);let s={...n.decoderConfig},a=!1;if(e.source._codec==="aac"&&!s.description){let c=rr(yt.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=fr[c.samplingFrequencyIndex],u=on[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=Vo({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),a=!0}let o={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ht.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Mp(t),w(t),w(t.config);let i={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,t,n),a=t.data;if(s.info.requiresAnnexBTransformation){let c=[...Oi(a)].map(l=>a.subarray(l.offset,l.offset+l.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=$o(c,4)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=this.createSampleForTrack(s,a,t.timestamp,t.duration,t.type);await this.registerSample(s,o)}finally{i()}}async addEncodedAudioPacket(e,t,n){let i=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,t,n),a=t.data;if(s.info.requiresAdtsStripping){let u=rr(yt.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");let d=u.crcCheck===null?Hn:tr;a=a.subarray(d)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(s.info.requiresPcmTransformation){let d=Wt(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(c=a.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let h=o-s.info.expectedNextPcmPacketTimestamp;if(h<.01)o=s.info.expectedNextPcmPacketTimestamp;else{let f=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,h);o=s.info.expectedNextPcmPacketTimestamp+f}}s.info.expectedNextPcmPacketTimestamp=o+c}let l=this.createSampleForTrack(s,a,o,c,t.type);await this.registerSample(s,l)}finally{i()}}async padWithSilence(e,t,n){let i=$e(n,e.timescale);if(n=i/e.timescale,i>0){let{sampleSize:s,silentValue:a}=Wt(e.info.decoderConfig.codec),o=i*e.info.numberOfChannels,c=new Uint8Array(s*o).fill(a),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,n,"key");await this.registerSample(e,l)}return n}async addSubtitleCue(e,t,n){let i=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,t.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(t),await this.processWebVTTCues(s,t.timestamp))}finally{i()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let l of e.cueQueue)w(l.timestamp<=t),w(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);let i=[...n].sort((l,u)=>l-u),s=i[0],a=i[1]??s;if(t<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let l=I0();this.auxBoxWriter.writeBox(l);let u=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let u=e.cueQueue[l];if(u.timestamp>=a)break;Ad.lastIndex=0;let d=Ad.test(u.text),h=u.timestamp+u.duration,f=e.cueToSourceId.get(u);if(f===void 0&&a<h&&(f=e.nextSourceId++,e.cueToSourceId.set(u,f)),u.notes){let m=F0(u.notes);this.auxBoxWriter.writeBox(m)}let p=M0(u.text,d?s:null,u.identifier??null,u.settings??null,f??null);this.auxBoxWriter.writeBox(p),h===a&&e.cueQueue.splice(l--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,a-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,i,s){return{timestamp:n,decodeTimestamp:n,duration:i,data:t,size:t.byteLength,type:s,timescaleUnitsToNextSample:$e(i,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let i=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let a=e.timestampProcessingQueue[s],o=$e(a.duration,e.timescale);i+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:i,sampleDelta:1});else{let s=ze(e.timeToSampleTable);s.sampleCount+=i}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(i=>i.timestamp).sort((i,s)=>i-s);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let i=0;i<e.timestampProcessingQueue.length;i++){let s=e.timestampProcessingQueue[i];s.decodeTimestamp=n[i];let a=$e(s.timestamp-s.decodeTimestamp,e.timescale),o=$e(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){w(e.lastSample);let c=$e(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(w(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=ze(e.timeToSampleTable);if(w(u),u.sampleCount===1){u.sampleDelta=l;let h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===l&&(h.sampleCount++,e.timeToSampleTable.pop(),u=h)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let d=ze(e.compositionTimeOffsetTable);w(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=$e(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,w(e.lastSample),w(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){w(t.type==="key");let i=$e(t.timestamp,e.timescale,!1),s=Math.round(i-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){let i=e.track.metadata.maximumPacketCount;if(w(i!==void 0),e.samples.length>i)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${i}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let i=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(a=>{if(e===a)return t.type==="key";let o=a.sampleQueue[0];return o?o.type==="key":a.closed});i>=this.minimumFragmentDuration&&s&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=i>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),w(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(w(!this.isFragmented),w(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((n,i)=>n+$e(i.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||ze(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)w(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(w(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<n&&(t=s,n=s.sampleQueue[0].timestamp)}if(!t)break;let i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!this.isCmaf){w(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let f=this.initBoxWriter??this.boxWriter;w(f),this.format._options.onMoov&&f.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let p=as(this);if(f.writeBox(p),this.format._options.onMoov){let{data:m,start:g}=f.writer.stopTrackingWrites();this.format._options.onMoov(m,g)}if(this.isCmaf){w(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Yn(this.writer);let m=this.boxWriter.measureBox(Ed()),g=this.boxWriter.measureBox(Id(this,0));this.segmentHeaderSize=m+g,this.writer.seek(this.segmentHeaderSize)}}w(this.writer),w(this.boxWriter);let n=this.trackDatas.filter(f=>f.currentChunk),i=Fd(t,n),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(i),o=a+Xt,c=1/0;for(let f of n){f.currentChunk.offset=o,f.currentChunk.moofOffset=s;for(let p of f.currentChunk.samples)o+=p.size;c=Math.min(c,f.currentChunk.startTimestamp)}let l=o-a,u=l>=2**32;if(u)for(let f of n)f.currentChunk.offset+=Br-Xt;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=Fd(t,n);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,p,c)}w(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=_a(u);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(a+(u?Br:Xt));for(let f of n)for(let p of f.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){let{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,p)}for(let f of n)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(w(this.writer),w(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let n=as(this),s=this.boxWriter.measureBox(n)+this.computeSampleTableSizeUpperBound()+4096;w(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=_a(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){w(this.fastStart==="reserve");let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;w(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let t=this.trackDatas.filter(i=>i.type===e);if(t.length===0)continue;if(!t.some(i=>i.track.metadata.disposition?.default!==!1)){let i=t[0];i.track.metadata.disposition={...i.track.metadata.disposition,default:!0}}}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let t of this.trackDatas){await this.finalizeCurrentChunk(t),w(t.startTimestampOffset!==null);for(let n=0;n<t.samples.length;n++){let i=t.samples[n];i.timestamp-=t.startTimestampOffset,i.decodeTimestamp-=t.startTimestampOffset}}if(w(this.writer),w(this.boxWriter),this.fastStart==="in-memory"){this.mdat=_a(!1);let t;for(let i=0;i<2;i++){let s=as(this),a=this.boxWriter.measureBox(s);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(let c of this.finalizedChunks){c.offset=o;for(let{data:l}of c.samples)w(l),o+=l.byteLength,t+=l.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let n=as(this);if(this.boxWriter.writeBox(n),this.format._options.onMoov){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(i,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(let i of this.finalizedChunks)for(let s of i.samples)w(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(i,s)}}else if(this.isFragmented)if(this.isCmaf){let t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(Ed()),this.boxWriter.writeBox(Id(this,t))}else{let t=this.writer.getPos(),n=E0(this.trackDatas);this.boxWriter.writeBox(n);let i=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{w(this.mdat);let t=this.boxWriter.offsets.get(this.mdat);w(t!==void 0);let n=this.writer.getPos()-t;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}let i=as(this);if(this.fastStart==="reserve"){w(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(C0(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){let{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}};var al=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){w(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(n,i)=>n[i*e]:e===1&&t===4?this.channelMixer=(n,i,s)=>n[i*e]*+(s<2):e===1&&t===6?this.channelMixer=(n,i,s)=>n[i*e]*+(s===2):e===2&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return .5*(n[s]+n[s+1])}:e===2&&t===4?this.channelMixer=(n,i,s)=>n[i*e+s]*+(s<2):e===2&&t===6?this.channelMixer=(n,i,s)=>n[i*e+s]*+(s<2):e===4&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return .25*(n[s]+n[s+1]+n[s+2]+n[s+3])}:e===4&&t===2?this.channelMixer=(n,i,s)=>{let a=i*e;return .5*(n[a+s]+n[a+s+2])}:e===4&&t===6?this.channelMixer=(n,i,s)=>{let a=i*e;return s<2?n[a+s]:s===2||s===3?0:n[a+s-2]}:e===6&&t===1?this.channelMixer=(n,i)=>{let s=i*e;return Math.SQRT1_2*(n[s]+n[s+1])+n[s+2]+.5*(n[s+4]+n[s+5])}:e===6&&t===2?this.channelMixer=(n,i,s)=>{let a=i*e;return n[a+s]+Math.SQRT1_2*(n[a+2]+n[a+s+4])}:e===6&&t===4?this.channelMixer=(n,i,s)=>{let a=i*e;return s<2?n[a+s]+Math.SQRT1_2*n[a+2]:n[a+s+2]}:this.channelMixer=(n,i,s)=>s<e?n[i*e+s]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let n=new Float32Array(t);n.set(this.tempSourceBuffer),this.tempSourceBuffer=n}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),w(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:"f32"}),i=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(i,{planeIndex:0,format:"f32"});let s=e.timestamp-this.startTime,a=s+e.duration,o=Math.floor(s*this.targetSampleRate),c=Math.ceil(a*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let u=l-this.bufferStartFrame;w(u<this.bufferSizeInFrames);let f=(l/this.targetSampleRate-s)*this.sourceSampleRate,p=Math.floor(f),m=Math.ceil(f),g=f-p;for(let y=0;y<this.targetNumberOfChannels;y++){let b=0,k=0;p>=0&&p<e.numberOfFrames&&(b=this.channelMixer(i,p,y)),m>=0&&m<e.numberOfFrames&&(k=this.channelMixer(i,m,y));let T=b+g*(k-b),x=u*this.targetNumberOfChannels+y;this.outputBuffer[x]+=T}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;w(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new mr({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}};var ls=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},ei=class extends ls{constructor(e){if(super(),this._connectedTrack=null,!gt.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${gt.join(", ")}.`);this._codec=e}},Dd=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Pa=class extends ei{constructor(e){super(e)}add(e,t){if(!(e instanceof Oe))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Dd(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},Od=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new nn,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.closed=!1,this.lastMuxerPromise=Promise.resolve()}async add(e,t,n){let i=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let s=this.encodingConfig,a=s.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.crop!==void 0||s.transform?.force===!0||o&&a!=="passThrough"){let d=s.transform?.width,h=s.transform?.height,f=s.transform?.fit??"fill";o&&a!=="passThrough"&&(w(this.outputWidth),w(this.outputHeight),w(a!=="deny"),d=this.outputWidth,h=this.outputHeight,f=a);let p=await e.transform({width:d,height:h,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,fit:f,alpha:s.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),t&&e.close(),e=p,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let u=s.transform?.frameRate;if(u!==void 0){let d=e.timestamp+e.duration,h=Au(e.timestamp,u);if(this.frameRateLastSample!==null)if(h<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(h,n);e===i&&(e=e.clone(),t=!0),e.setTimestamp(h),e.setDuration(1/u),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=h,this.frameRateLastEndTimestamp=d}await this.processAndEncode(e,n)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig,i;if(n.transform?.process){let s=n.transform.process(e);if(s instanceof Promise&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]),i=s.map(a=>a instanceof nr?a:typeof VideoFrame<"u"&&a instanceof VideoFrame?new nr(a):new nr(a,{timestamp:e.timestamp,duration:e.duration}))}else i=[e];try{for(let s of i){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(s),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed)break;let a=this.encodingConfig.keyFrameInterval??2,o=Math.floor(s.timestamp/a),c={...s.encodeOptions,...t},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:a===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(s),this.customEncoder){this.customEncoderQueueSize++;let u=s.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).then(()=>this.customEncoderQueueSize--).catch(h=>this.error??=h).finally(()=>{u.close()});this.customEncoderQueueSize>=4&&await d}else{w(this.encoder);let u=s.toVideoFrame(),d=_e(this.preciseTimings,u.timestamp,f=>f.microsecondTimestamp),h=d!==-1?this.preciseTimings[d]:null;if(h&&h.microsecondTimestamp===u.timestamp?(h.timestamp!==s.timestamp&&(h.timestampIsValid=!1),h.duration!==s.duration&&(h.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:s.timestamp,duration:s.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(u,l),u.close();else if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(u,l),u.close();else{let p=u.displayWidth,m=u.displayHeight;this.splitter||(this.splitter=new ol(p,m));let{colorFrame:g,alphaFrame:y}=await this.splitter.update(u);this.alphaFrameQueue.push(y),this.encoder.encode(g,l),g.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let s of i)s!==e&&s.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;w(this.frameRateLastSample);let i=Math.round((e-this.frameRateLastTimestamp)*n);for(let s=1;s<i;s++){let a=this.frameRateLastSample.clone();a.setTimestamp(this.frameRateLastTimestamp+s/n),a.setDuration(1/n),await this.processAndEncode(a,t),a.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=md({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=Yc.find(i=>i.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(i,s)=>{if(!(i instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(s!==void 0&&(!s||typeof s!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Dd(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,s),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,s).catch(a=>{this.error??=a})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(t.alpha="discard",this.encodingConfig.alpha==="keep"&&(t.latencyMode="quality"),(t.width%2===1||t.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let a=[],o=[],c=0,l=0,u=(h,f,p)=>{let m={};if(f){let T=new Uint8Array(f.byteLength);f.copyTo(T),m.alpha=T}let g=Oe.fromEncodedChunk(h,m),y=_e(this.preciseTimings,h.timestamp,T=>T.microsecondTimestamp),b=y!==-1?this.preciseTimings[y]:null,k=null;this.emittedEncoderPackets===0&&g.type==="delta"&&p?.decoderConfig&&(k=hn(this.encodingConfig.codec,p.decoderConfig,g.data)),(b&&b.microsecondTimestamp===h.timestamp||k!==null)&&(g=g.clone({timestamp:b?.timestampIsValid?b.timestamp:void 0,duration:b?.durationIsValid?b.duration:void 0,type:k??void 0})),Dd(this.source._connectedTrack,g),this.encodingConfig.onEncodedPacket?.(g,p),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,g,p).catch(T=>{this.error??=T}),this.emittedEncoderPackets++},d=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(h,f)=>{if(!this.alphaEncoder){u(h,null,f);return}let p=this.alphaFrameQueue.shift();w(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:h.type==="key"}),l++,p.close(),a.push({chunk:h,meta:f})):l===0?u(h,null,f):(o.push(c+l),a.push({chunk:h,meta:f}))},error:h=>{h.stack=d,this.error??=h}}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){let h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(f,p)=>{l--;let m=a.shift();for(w(m!==void 0),u(m.chunk,f,m.meta),c++;o.length>0&&o[0]===c;){o.shift();let g=a.shift();w(g!==void 0),u(g.chunk,null,g.meta)}},error:f=>{f.stack=h,this.error??=f}}),this.alphaEncoder.configure(t)}}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){let t=this.encodingConfig.transform.frameRate,n=Au(this.frameRateLastEndTimestamp,t);await this.padFrameRate(n)}this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},L0=!1,ol=class r{constructor(e,t){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let n=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!r.forceCpu&&n&&!L0)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);let i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(i){this.gl=null,this.canvas=null,L0=!0,we._warn("Falling back to CPU for color/alpha splitting.",i)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){w(this.gl),w(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);let t=this.runColorProgram(e),n=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:n}}createVertexShader(){return w(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
1895
- in vec2 a_position;
1896
- in vec2 a_texCoord;
1897
- out vec2 v_texCoord;
1898
-
1899
- void main() {
1900
- gl_Position = vec4(a_position, 0.0, 1.0);
1901
- v_texCoord = a_texCoord;
1902
- }
1903
- `)}createColorProgram(){w(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
1904
- precision highp float;
1905
-
1906
- uniform sampler2D u_sourceTexture;
1907
- in vec2 v_texCoord;
1908
- out vec4 fragColor;
1909
-
1910
- void main() {
1911
- vec4 source = texture(u_sourceTexture, v_texCoord);
1912
- fragColor = vec4(source.rgb, 1.0);
1913
- }
1914
- `),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
1915
- precision highp float;
1916
-
1917
- uniform sampler2D u_sourceTexture;
1918
- uniform vec2 u_resolution; // The width and height of the canvas
1919
- in vec2 v_texCoord;
1920
- out vec4 fragColor;
1921
-
1922
- // This function determines the value for a single byte in the YUV stream
1923
- float getByteValue(float byteOffset) {
1924
- float width = u_resolution.x;
1925
- float height = u_resolution.y;
1926
-
1927
- float yPlaneSize = width * height;
1928
-
1929
- if (byteOffset < yPlaneSize) {
1930
- // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
1931
- float y = floor(byteOffset / width);
1932
- float x = mod(byteOffset, width);
1933
-
1934
- // Add 0.5 to sample the center of the texel
1935
- vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
1936
-
1937
- // The luma value is the alpha from the source texture
1938
- return texture(u_sourceTexture, sampleCoord).a;
1939
- } else {
1940
- // Write a fixed value for chroma and beyond
1941
- return 128.0 / 255.0;
1942
- }
1943
- }
1944
-
1945
- void main() {
1946
- // Each fragment writes 4 bytes (R, G, B, A)
1947
- float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
1948
- float baseByteOffset = pixelIndex * 4.0;
1949
-
1950
- vec4 result;
1951
- for (int i = 0; i < 4; i++) {
1952
- float currentByteOffset = baseByteOffset + float(i);
1953
- result[i] = getByteValue(currentByteOffset);
1954
- }
1955
-
1956
- fragColor = result;
1957
- }
1958
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){w(this.gl);let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||we._error("Shader compile error:",this.gl.getShaderInfoLog(n)),n}createVAO(){w(this.gl),w(this.colorProgram);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){w(this.gl);let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}runColorProgram(e){return w(this.gl),w(this.canvas),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}runAlphaProgram(e){w(this.gl),w(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:t,height:n}=this.canvas,i=Math.ceil(t/2)*Math.ceil(n/2),s=t*n+i*2,a=Math.ceil(s/(t*4)),o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,s),w(o[t*n]===128),w(o[o.length-1]===128);let c={format:"I420",codedWidth:t,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}updateCpu(e){if(!this.worker){let i=new Blob([`(${nv.toString()})()`],{type:"application/javascript"}),s=URL.createObjectURL(i);this.worker=new Worker(s),URL.revokeObjectURL(s),this.worker.addEventListener("message",a=>{let o=a.data,c=this.pendingRequests.get(o.id);c&&(this.pendingRequests.delete(o.id),"error"in o?c.reject(new Error(o.error)):c.resolve({colorFrame:o.colorFrame,alphaFrame:o.alphaFrame}))}),this.worker.addEventListener("error",a=>{let o=new Error(a.message||"Color/alpha splitter worker error.");for(let c of this.pendingRequests.values())c.reject(o);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=nt();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=new Error("Color/alpha splitter closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};ol.forceCpu=!0;var nv=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",s=>{let{id:a,sourceFrame:o}=s.data;e=e.then(async()=>{try{let{colorFrame:c,alphaFrame:l}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});let t=async s=>{let a=s.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=s.codedWidth,c=s.codedHeight,l=s.allocationSize();if((!r||r.byteLength!==l)&&(r=new Uint8Array(l)),await s.copyTo(r),a==="RGBA"||a==="BGRA")return n(r,o,c,a,s);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return i(r,o,c,a,s);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},n=(s,a,o,c,l)=>{let u=a*o,d=Math.ceil(a/2),h=Math.ceil(o/2),f=u+d*h*2,p=new Uint8Array(f);for(let b=0,k=3;b<u;b++,k+=4)p[b]=s[k];p.fill(128,u);let m=new VideoFrame(s,{format:c==="RGBA"?"RGBX":"BGRX",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),g={format:"I420",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[p.buffer]},y=new VideoFrame(p,g);return{colorFrame:m,alphaFrame:y}},i=(s,a,o,c,l)=>{let u=c.includes("P10"),d=c.includes("P12"),h=u||d?2:1,f,p;c.startsWith("I420")?(f=Math.ceil(a/2),p=Math.ceil(o/2)):c.startsWith("I422")?(f=Math.ceil(a/2),p=o):(f=a,p=o);let m=a*o,g=f*p,y=m*h,b=g*h,k=m*h,T=y+b*2,x=c.replace("A",""),v=Math.ceil(a/2),M=Math.ceil(o/2),C=v*M,_=C*h,F=k+2*_,E=new Uint8Array(F),O=T;E.set(s.subarray(O,O+k),0);let Q=k,ye=u?512:d?2048:128;h===1?E.fill(ye,Q):new Uint16Array(E.buffer,Q,2*C).fill(ye);let Z=u?"I420P10":d?"I420P12":"I420",ee=new VideoFrame(s.subarray(0,T),{format:x,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),ve={format:Z,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[E.buffer]},Re=new VideoFrame(E,ve);return{colorFrame:ee,alphaFrame:Re}}};var Ea=class extends ei{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");s0(t),super(t.codec),this._encoder=new Od(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");let i=new nr(this._canvas,{timestamp:e,duration:t});return this._encoder.add(i,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var us=class extends ls{constructor(e){if(super(),this._connectedTrack=null,!Ht.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ht.join(", ")}.`);this._codec=e}};var Ld=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new nn,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new al({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,onSample:async s=>{await this.processAndEncode(s,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&r0(e.format)!==n.transform.sampleFormat){let i=n0(e,n.transform.sampleFormat);t&&e.close(),e=i,t=!0}if(n.transform?.process){let i=n.transform.process(e);if(i instanceof Promise&&(i=await i),i===null)return;Array.isArray(i)||(i=[i]);for(let s of i){if(!(s instanceof mr))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(s,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed)return;{let n=Math.round(e.timestamp*e.sampleRate),i=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=i;else{let s=n-this.lastEndSampleIndex;if(s>=64){let a=new mr({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let n=e.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(n)).then(()=>this.customEncoderQueueSize--).catch(s=>this.error??=s).finally(()=>{n.close()});this.customEncoderQueueSize>=4&&await i,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{w(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(i=>this.encoder.addEventListener("dequeue",i,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){w(this.outputSampleSize),w(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:i,sampleRate:s,timestamp:a}=e,o=2048,c=[];for(let h=0;h<i;h+=o){let f=Math.min(o,e.numberOfFrames-h),p=f*n*this.outputSampleSize,m=new ArrayBuffer(p),g=new DataView(m);c.push({frameCount:f,view:g})}let l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let h=0;h<n;h++){e.copyTo(u,{planeIndex:h,format:"f32-planar"});for(let f=0;f<c.length;f++){let{frameCount:p,view:m}=c[f];for(let g=0;g<p;g++)this.writeOutputValue(m,(g*n+h)*this.outputSampleSize,u[f*o+g])}}t&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:s}};for(let h=0;h<c.length;h++){let{frameCount:f,view:p}=c[h],m=p.buffer,g=h*o,y=new Oe(new Uint8Array(m),"key",a+g/s,f/s);this.encodingConfig.onEncodedPacket?.(y,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,y,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,i=c0({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(i);let s=gd.find(a=>a.supports(this.encodingConfig.codec,i));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(a,o)=>{if(!(a instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,o),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,o).catch(c=>{this.error??=c})},await this.customEncoder.init();else if(ht.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.numberOfChannels} channels, ${i.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let o=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let d=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?d=!0:d=Ri(Ye(l.decoderConfig.description)).objectType===0,d){let h=Number(ze(i.codec.split(".")));l.decoderConfig.description=Vo({objectType:h,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}let u=Oe.fromEncodedChunk(c);u=u.clone({timestamp:Bn(u.timestamp,i.sampleRate),duration:c.duration!=null?Bn(u.duration,i.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(u,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,l).catch(d=>{this.error??=d})},error:c=>{c.stack=o,this.error??=c}}),this.encoder.configure(i)}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:i}=Wt(e);switch(this.outputSampleSize=n,n){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,Ze((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,Ze(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{let c=Ze(Math.floor(o*32767),-32768,32767);s.setUint8(a,m0(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{let c=Ze(Math.floor(o*32767),-32768,32767);s.setUint8(a,p0(c))}:w(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,Ze((o+1)*32767.5,0,65535),i):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,Ze(Math.round(o*32767),-32768,32767),i):w(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>zs(s,a,Ze((o+1)*83886075e-1,0,16777215),i):t==="signed"?this.writeOutputValue=(s,a,o)=>up(s,a,Ze(Math.round(o*8388607),-8388608,8388607),i):w(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,Ze((o+1)*21474836475e-1,0,4294967295),i):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,Ze(Math.round(o*2147483647),-2147483648,2147483647),i):t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat32(a,o,i):w(!1);break;case 8:t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat64(a,o,i):w(!1);break;default:Ct(n),w(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}};var ti=class extends us{constructor(e){o0(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Ld(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let t=mr._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let n of t)await this._encoder.add(n,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var Ia=class extends ls{constructor(e){if(super(),this._connectedTrack=null,!cn.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${cn.join(", ")}.`);this._codec=e}};var ds=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>gt.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ht.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>cn.includes(e))}_codecUnsupportedHint(e){return""}},hs=class extends ds{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new sl(e,this)}},xn=class extends hs{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...gt,...Ho,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...cn]}_codecUnsupportedHint(e){return new cs().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},os=class extends hs{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...gt,...Ho,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...cn]}},cs=class extends hs{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...gt,...Ht]}_codecUnsupportedHint(e){return new xn().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}};var iv=["video","audio","subtitle"],fs=class r{constructor(e,t,n,i,s){this.id=e,this.output=t,this.type=n,this.source=i,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;let t=_u(this.metadata.group),n=_u(e.metadata.group);for(let i of t)if(this.type!==e.type&&n.some(o=>i===o)||n.some(o=>i._pairedGroups.has(o)))return!0;return!1}},cl=class extends fs{constructor(e,t,n,i){super(e,t,"video",n,i)}},ll=class extends fs{constructor(e,t,n,i){super(e,t,"audio",n,i)}},ul=class extends fs{constructor(e,t,n,i){super(e,t,"subtitle",n,i)}},ms=class r{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}},Ud=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!Ei(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&wp(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof ms)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof ms))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},ri=class extends Vt{get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new ms,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new vt,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof ds))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Rt||e.target instanceof Jn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Rt&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Rt)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Rt&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){w(this._target instanceof Jn);let t=this._target.getTarget(e),n=i=>{if(!(i instanceof Rt))throw new TypeError("getTarget must return a Target.");return i};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){w(this._target instanceof Jn);let t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(w(this._initTarget!==null),this._initTarget instanceof Rt)return this._initTarget;let e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Rt)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=i=>(this.state==="canceled"?i._close():this._rememberTarget(i),this._emit("target",{target:i,request:e,isRoot:!0}),this._rootTarget=i,i);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new Zn(t,typeof e=="boolean"?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof ei))throw new TypeError("source must be a VideoSource.");if(Ud(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new cl(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof us))throw new TypeError("source must be an AudioSource.");Ud(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ll(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Ia))throw new TypeError("source must be a SubtitleSource.");Ud(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ul(this._tracks.length+1,this,e,n))}setMetadataTags(e){if(yp(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let t=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),i=t[e.type].max;if(n===i)throw new Error(i===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${i} ${e.type} track${i===1?"":"s"}.`);let s=t.total.max;if(this._tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){let a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){let e=this.format.getSupportedTrackCounts();for(let n of iv){let i=this._tracks.reduce((a,o)=>a+(o.type===n?1:0),0),s=e[n].min;if(i<s)throw new Error(s===e[n].max?`${this.format._name} requires exactly ${s} ${n} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${n} track${s===1?"":"s"}.`)}let t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(we._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let n=await this._mutex.acquire();try{await this._muxer.start();let i=this._tracks.map(s=>s.source._start());await Promise.all(i)}finally{n()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return we._warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&we._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let t=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(n=>n._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(we._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{let t=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){let n=await this._rootWriterPromise;n.finalized||(await n.flush(),await n.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}};var U0=Symbol.for("mediabunny loaded");globalThis[U0]&&we._error(`[WARNING]
1959
- Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[U0]=!0;var sv=(()=>{let r=[];for(let e=0;;e++){let t=Math.round(64*2**(e/2));if(t>4096)break;r.push(t)}return r})();function ps(r,e){if(e)return 4096;let t=Math.max(1,Math.round(Math.max(r.width,r.height)));return Math.min(t,4096)}function $r(r,e){let t=Number.isFinite(r)?Math.max(0,r):e;if(t>=e)return e;let n=e/Math.SQRT2;for(let i of sv){if(i>=n)return e;if(i>=t)return i}return e}function Ma(r){return $r(0,r)}function gs(r,e){let t=Math.max(e.width,e.height,1),n=r/t;return{width:Math.max(1,Math.round(e.width*n)),height:Math.max(1,Math.round(e.height*n))}}var av=512*1024*1024,ov=2e3,Nd=5e3,cv=3e4,lv=6e4,uv=3,dv=2,hv=16*1024*1024,dl=class{_host;_budget;_policy="interactive";_entries=new Map;_pass=0;_inflight=0;constructor(e,t=av){this._host=e,this._budget=t}get policy(){return this._policy}setPolicy(e){this._policy=e}has(e){return(this._entries.get(e)?.levels.length??0)>0}intrinsicSize(e){return this._entries.get(e)?.intrinsic??null}load(e){let t=this._entry(e);return t.levels.length>0?Promise.resolve():(t.loading??=this._host.decode(e,(n,i)=>(this._learn(t,n,i),this._policy==="exact"?Ma(t.cap):t.lastDemand!==void 0?this._interactiveEdge(t,t.lastDemand):$r(Math.min(Math.max(n.width,n.height),this._host.surfaceEdge()),t.cap))).then(n=>{this._learn(t,n.intrinsic,n.vector),this._add(t,n),this._enforceBudget()}).finally(()=>{t.loading=null,this._pump()}),t.loading)}beginPass(){this._pass++}select(e,t){let n=this._entry(e),i=this._host.now(),s=t!==void 0&&Number.isFinite(t)&&t>0?t:1/0;if(n.levels.length===0)return Number.isFinite(s)&&(n.lastDemand=Math.max(n.lastDemand??0,s)),n.missedPass=this._pass,null;let a=Math.min(s,n.cap);n.passNeed=Math.max(n.passNeed,a),n.passDraws++,n.lastUsed=i;let o;if(this._policy==="exact"){let c=$r(a,n.cap),l=n.levels.find(u=>u.edge===c);!l&&!n.failed.has(c)&&n.wanted.add(c),o=l??fv(n.levels,c)}else o=n.levels.find(c=>c.edge>=a)??n.levels[n.levels.length-1],o.edge<2*a&&(n.passAllOver=!1);return o.lastSelected=i,o.selectedPass=this._pass,o}endPass(){let e=this._host.now();for(let t of this._entries.values()){let n=t.levels[t.levels.length-1];if(t.passDraws>0&&n)if(t.lastDemand=t.passNeed,this._policy==="exact"){for(let i of t.wanted)this._request(t,i,!1);t.wanted.clear()}else t.short=n.edge<t.passNeed,t.short?this._request(t,this._interactiveEdge(t,t.passNeed),!0):t.queue=t.queue.filter(i=>i<=n.edge),t.passAllOver&&!N0(n)?(t.overSince??=e,e-t.overSince>=Nd&&this._request(t,this._interactiveEdge(t,t.passNeed),!0)):t.overSince=null;else t.short=!1;t.passNeed=0,t.passDraws=0,t.passAllOver=!0,this._ageOut(t,e)}this._enforceBudget(),this._pump()}hasPending(){for(let e of this._entries.values())if(this._blocks(e))return!0;return!1}async warm(){if(this._policy==="interactive"){let t=!1;for(let n=0;n<64;n++){let i=[...this._entries.values()].filter(s=>this._blocks(s)).map(s=>s.loading);if(i.length===0)break;t=!0,await Promise.all(i.map(s=>s.catch(()=>{})))}return t}let e=!1;for(let t of this._entries.values()){for(let n of t.wanted)this._request(t,n,!1);t.wanted.clear()}this._pump();for(let t=0;t<64;t++){let n=[...this._entries.values()].map(i=>i.job??i.loading).filter(i=>i!==null);if(n.length===0)break;e=!0,await Promise.all(n.map(i=>i.catch(()=>{}))),this._pump()}return e}hasUpgrades(){if(this._policy!=="interactive")return!1;for(let e of this._entries.values())if(this._upgrading(e))return!0;return!1}async warmUpgrades(){let e=!1;for(let t=0;t<64&&this._policy==="interactive";t++){this._pump();let n=[...this._entries.values()].filter(a=>this._upgrading(a));if(n.length===0)break;let i=n.flatMap(a=>a.job?[a.job]:[]),s=i.length>0?i:[...this._entries.values()].flatMap(a=>a.job?[a.job]:[]);if(s.length===0)break;await Promise.all(s.map(a=>a.catch(()=>{}))),i.length>0&&(e=!0)}return e}stats(){let e=0,t=0,n=0;for(let i of this._entries.values()){e+=i.levels.length;for(let s of i.levels)t+=ys(s);n+=this._host.sourceBytes(i.src)}return{sources:this._entries.size,levels:e,levelBytes:t,sourceBytes:n,inflight:this._inflight}}levelsOf(e){return this._entries.get(e)?.levels??[]}dispose(){for(let e of this._entries.values()){for(let t of e.levels)this._host.released(e.src,t);e.levels=[],e.queue=[]}this._entries.clear()}_entry(e){let t=this._entries.get(e);return t||(t={src:e,intrinsic:null,vector:!1,cap:1,levels:[],lastDemand:void 0,lastUsed:this._host.now(),passNeed:0,passDraws:0,passAllOver:!0,overSince:null,wanted:new Set,queue:[],job:null,failed:new Set,loading:null,missedPass:-1,short:!1},this._entries.set(e,t)),t}_blocks(e){return this._policy==="exact"?e.job!==null||e.queue.length>0||e.wanted.size>0||e.loading!==null:e.levels.length===0&&e.missedPass===this._pass&&e.loading!==null}_upgrading(e){return e.short&&e.levels.length>0&&(e.job!==null||e.queue.length>0)}_interactiveEdge(e,t){return $r(Math.min(t*dv,e.cap),e.cap)}_learn(e,t,n){e.intrinsic={width:t.width,height:t.height},e.vector=n,e.cap=ps(t,n)}_add(e,t){let n=e.levels.findIndex(s=>s.edge===t.edge);n>=0&&(this._host.released(e.src,e.levels[n]),e.levels.splice(n,1));let i={edge:t.edge,width:t.width,height:t.height,pixels:t.pixels,gpu:null,lastSelected:this._host.now(),selectedPass:this._pass};e.levels.push(i),e.levels.sort((s,a)=>s.edge-a.edge)}_request(e,t,n){e.failed.has(t)||!e.intrinsic||e.levels.some(i=>i.edge===t)||(n?e.queue=[t]:e.queue.includes(t)||e.queue.push(t))}_pump(){for(let e of this._entries.values()){if(this._inflight>=uv)return;if(e.job||e.loading)continue;let t=this._nextEdge(e);if(t===void 0)continue;let n=t;this._inflight++,e.job=this._host.decode(e.src,()=>n).then(i=>{if(this._learn(e,i.intrinsic,i.vector),!this._entries.has(e.src)){this._host.released(e.src,{...i,gpu:null,lastSelected:0,selectedPass:0});return}this._add(e,i),this._enforceBudget()},i=>{e.failed.add(n),this._host.onError?.(e.src,i)}).finally(()=>{this._inflight--,e.job=null,this._pump()})}}_nextEdge(e){for(let t=e.queue.shift();t!==void 0;t=e.queue.shift()){if(this._policy==="interactive"&&e.lastDemand!==void 0){let n=Math.min(e.lastDemand,e.cap),i=e.levels[e.levels.length-1];if(i&&t>i.edge&&i.edge>=n)continue;t<n&&(t=this._interactiveEdge(e,n))}if(!e.failed.has(t)&&!e.levels.some(n=>n.edge===t))return t}}_ageOut(e,t){if(e.levels.length<=1)return;let n=e.levels[e.levels.length-1],i=e.levels.filter(s=>t-s.lastSelected<ov||s===n&&N0(s));if(i.length!==e.levels.length){i.length===0&&i.push(e.levels.reduce((s,a)=>a.lastSelected>s.lastSelected?a:s));for(let s of e.levels)i.includes(s)||this._host.released(e.src,s);e.levels=i}}_total(){let e=0;for(let t of this._entries.values()){for(let n of t.levels)e+=ys(n);e+=this._host.sourceBytes(t.src)}return e}_enforceBudget(){let e=this._total();if(e<=this._budget)return;let t=this._host.now(),n=[];for(let i of this._entries.values()){let s=i.levels.some(a=>a.selectedPass>=this._pass);i.levels.forEach((a,o)=>{a.selectedPass>=this._pass||!s&&o===0||n.push({entry:i,level:a})})}n.sort((i,s)=>i.level.lastSelected-s.level.lastSelected||ys(s.level)-ys(i.level));for(let{entry:i,level:s}of n){if(e<=this._budget)return;i.levels.length<=1||(i.levels=i.levels.filter(a=>a!==s),this._host.released(i.src,s),e-=ys(s))}if(this._policy==="interactive")for(let i of this._entries.values()){if(i.lastDemand===void 0)continue;let s=$r(i.lastDemand,i.cap),a=i.levels[i.levels.length-1];a&&a.edge>s&&this._request(i,s,!0)}for(let i of this._entries.values()){if(e<=this._budget)break;if(t-i.lastUsed<cv||i.levels.length===0)continue;let s=i.levels[0];for(let o of i.levels.slice(1))this._host.released(i.src,o),e-=ys(o);i.levels=[s];let a=Ma(i.cap);s.edge>a&&this._request(i,a,!0)}for(let i of this._entries.values()){if(e<=this._budget)break;if(t-i.lastUsed<lv)continue;let s=this._host.sourceBytes(i.src);s!==0&&(this._host.dropSource(i.src),e-=s)}}};function ys(r){return r.width*r.height*4*(r.gpu?2:1)}function N0(r){return r.width*r.height*4<=hv}function fv(r,e){let t=r[0];for(let n of r){let i=Math.abs(Math.log(n.edge/e)),s=Math.abs(Math.log(t.edge/e));(i<s||i===s&&n.edge>t.edge)&&(t=n)}return t}var mv=512*1024*1024,z0=96,V0=32;function H0(r){if(!r||!(r.width>0)||!(r.height>0))return{forward:z0,back:V0};let e=mv/(r.width*r.height*4);return{forward:Math.max(4,Math.min(z0,Math.floor(e*.75))),back:Math.max(1,Math.min(V0,Math.floor(e*.25)))}}var hl=class{level;_cap;_passNeed=0;_passDraws=0;_passAllOver=!0;_overSince=null;constructor(e,t,n,i){this._cap=ps(e,!1),this.level=t==="exact"?Ma(this._cap):$r(n??Math.min(Math.max(e.width,e.height),i),this._cap)}get cap(){return this._cap}note(e){let t=e!==void 0&&Number.isFinite(e)&&e>0?Math.min(e,this._cap):this._cap;this._passNeed=Math.max(this._passNeed,t),this._passDraws++,this.level<2*t&&(this._passAllOver=!1)}accepts(e,t){return e===void 0?!0:t==="exact"?e===this.level:e>=this.level}endPass(e,t,n){let i=this._passDraws,s=this._passNeed,a=this._passAllOver;if(this._passDraws=0,this._passNeed=0,this._passAllOver=!0,i===0)return!1;let o=$r(s,this._cap),c=this.level;return e==="exact"?this.level=o:this.level<s?(this.level=o,this._overSince=null):a&&!t?(this._overSince??=n,n-this._overSince>=Nd&&(this.level=o,this._overSince=null)):this._overSince=null,this.level!==c}};function W0(r){let{data:e}=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function yv(r){return/\.svg(?:[?#]|$)/i.test(r)}var wv={image:[(r,e)=>r.getImageMeta(e)],video:[(r,e)=>r.getVideoMeta(e)],media:[(r,e)=>r.getAudioMeta(e),(r,e)=>r.getVideoMeta(e)]},Kt=class r extends gv{canvasKit;fontMgr;disposed=!1;surface=null;videoSessions=new Map;videoFrames=new Map;videoEchoFrames=new Map;videoPlayhead=new Map;pendingVideoFrames=new Map;pendingEchoFrames=new Map;echoDecodes=new Map;videoFrameClaims=new Map;videoAltSlots=new Map;videoDemand=new Map;playing=!1;decodePolicy="interactive";images;imageSources=new Map;reportedImageErrors=new Set;audioBuffers=new Map;audioCtx=null;fps;registeredFontFamilies=new Set;unknownFontFamilies=new Set;paragraphCache=new fo;fontEpoch=0;static ECHO_CACHE_LIMIT=48;static ALT_SLOT_LIMIT=16;constructor(e,t,n,i){super(t,n),this.canvasKit=e,this.fps=i,this.fontMgr=e.TypefaceFontProvider.Make(),this.images=new dl({now:()=>performance.now(),decode:(s,a)=>this.decodeImage(s,a),released:(s,a)=>{a.gpu?.delete(),a.gpu=null},sourceBytes:s=>this.imageSources.get(s)?.bytes??0,dropSource:s=>this.imageSources.delete(s),surfaceEdge:()=>this.surfaceEdge(),onError:(s,a)=>{this.disposed||this.reportedImageErrors.has(s)||(this.reportedImageErrors.add(s),console.error(`[WebStorageAdapter] image decode failed for ${s}:`,a))}})}getCanvasKit(){return this.canvasKit}setCatalog(e){super.setCatalog(e),this.unknownFontFamilies.clear()}setDecodePolicy(e){this.decodePolicy=e,this.images.setPolicy(e)}getDecodePolicy(){return this.decodePolicy}hasPendingDecodes(){return this.pendingVideoFrames.size>0||this.pendingEchoFrames.size>0||this.echoDecodes.size>0||xl()||this.images.hasPending()}async warmPendingDecodes(){let[e,t]=await Promise.all([this.warmVideo(),this.images.warm()]);return e||t}hasPendingUpgrades(){return this.images.hasUpgrades()}warmPendingUpgrades(){return this.images.warmUpgrades()}warmPendingVideo(){return this.warmPendingDecodes()}_decodeStats(){let e=0,t=0,n=0,i=new Set,s=a=>{for(let{bitmap:o}of a.values())i.has(o)||(i.add(o),n+=(o.width??0)*(o.height??0)*4)};for(let a of this.videoFrames.values())e+=a.size,s(a);for(let a of this.videoEchoFrames.values())t+=a.size,s(a);return{images:this.images.stats(),video:{sessions:this.videoSessions.size,windowFrames:e,echoFrames:t,frameBytes:n}}}async loadImage(e){await this.images.load(e)}getCKImage(e,t){let n=this.images.select(e,t);return n?(n.gpu??=this.makeCKImageFromPixels(n.pixels,n.width,n.height),n.gpu):null}getImagePixels(e,t){return this.images.select(e,t)}getImageSize(e){return this.images.intrinsicSize(e)??this.catalogImageSize(e)}catalogImageSize(e){try{let t=this.catalog.getImageMeta(e);return t.width>0&&t.height>0?{width:t.width,height:t.height}:null}catch{return null}}async decodeImage(e,t){let n=this.assetUrl(e,"image");if(yv(n)){let u=await this.svgSource(e,n),d=u.natural,h=t(d,!0),f=gs(h,d),m=new OffscreenCanvas(f.width,f.height).getContext("2d",{willReadFrequently:!0});if(!m)throw new Error(`loadImage(${e}): could not get 2d context`);return m.drawImage(u.svg,0,0,f.width,f.height),{pixels:W0(m.getImageData(0,0,f.width,f.height)),...f,intrinsic:d,vector:!0,edge:h}}let i=await this.rasterSource(e,n),s=this.catalogImageSize(e),a=null;s||(a=await createImageBitmap(i),s={width:a.width,height:a.height});let o=t(s,!1),c=o>=ps(s,!1)&&Math.max(s.width,s.height)<=4096,l;if(c)l=a??await createImageBitmap(i);else{let u=gs(o,s);try{l=await createImageBitmap(a??i,{resizeWidth:u.width,resizeHeight:u.height,resizeQuality:"high"})}finally{a?.close()}}try{let d=new OffscreenCanvas(l.width,l.height).getContext("2d",{willReadFrequently:!0});if(!d)throw new Error(`loadImage(${e}): could not get 2d context`);return d.drawImage(l,0,0),{pixels:W0(d.getImageData(0,0,l.width,l.height)),width:l.width,height:l.height,intrinsic:s,vector:!1,edge:o}}finally{l.close()}}async rasterSource(e,t){let n=this.imageSources.get(e);if(n?.blob)return n.blob;let i=await this.fetchBlob(t);return this.imageSources.set(e,{blob:i,bytes:i.size}),i}async svgSource(e,t){let n=this.imageSources.get(e);if(n?.svg&&n.natural)return n;let i=await(await this.fetchBlob(t)).text(),s=new Image;s.decoding="sync",await new Promise((c,l)=>{s.onload=()=>c(),s.onerror=()=>l(new Error(`loadImage(${e}): failed to decode SVG`)),s.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(i)}`});let a={width:s.naturalWidth>0?s.naturalWidth:300,height:s.naturalHeight>0?s.naturalHeight:300},o={svg:s,natural:a,bytes:i.length};return this.imageSources.set(e,o),o}surfaceEdge(){let e=this.surface;return e&&typeof e.width=="function"&&typeof e.height=="function"?Math.max(e.width(),e.height()):Math.max(this.viewport.width,this.viewport.height)}async fetchBlob(e){let t=await gl(e);return t||th(e)}assetUrl(e,t){let n=wv[t];for(let i of n)try{let s=i(this.catalog,e).src;if(s)return s}catch{}return e}canvas3DTextures=new Map;upload3DFrame(e,t,n,i){let s=this.surface;if(!s)return null;let a={width:n,height:i,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB},o=this.canvas3DTextures.get(e);if(o&&(o.width()!==n||o.height()!==i)&&(o.delete(),this.canvas3DTextures.delete(e),o=void 0),!o){let c=s.makeImageFromTextureSource(t,a,!1);return c?(this.canvas3DTextures.set(e,c),c):null}return s.updateTextureFromSource(o,t,!1),o}release3DTexture(e){this.canvas3DTextures.get(e)?.delete(),this.canvas3DTextures.delete(e)}setSurface(e){if(e!==this.surface){for(let t of this.videoSessions.values())t.textureImage?.delete(),t.textureImage=null,t.uploadedTs=null,t.uploadedBitmap=null;this.clearVideoAltSlots();for(let t of this.canvas3DTextures.values())t.delete();this.canvas3DTextures.clear(),this.surface=e}}setPlaying(e){this.playing=e}beginRenderPass(){this.videoFrameClaims.clear(),this.images.beginPass()}endRenderPass(){this.images.endPass();let e=performance.now();for(let[t,n]of this.videoSessions){if(!(n.levels?.endPass(this.decodePolicy,this.playing,e)??!1))continue;this.videoDemand.set(t,n.levels.level);let s=gs(n.levels.level,n.intrinsic);n.width=s.width,n.height=s.height,(this.videoFrameClaims.get(t)??[]).forEach((o,c)=>{let l=o*n.frameStep;if(c===0)this.pendingVideoFrames.has(t)||this.pendingVideoFrames.set(t,l);else{let u=this.pendingEchoFrames.get(t);u||(u=new Set,this.pendingEchoFrames.set(t,u)),u.add(l)}}),this.playing&&this.driveSequentialDecode(t,this.videoPlayhead.get(t)??0)}}async loadVideo(e,t,n,i=0,s){if(this.videoSessions.has(e))return;let a=this.assetUrl(e,"video"),o=await gl(a),c=new Gr({formats:dd,source:o?new ha(o):new fa(a)}),l=await c.getPrimaryVideoTrack();if(!l)throw c.dispose(),new Error(`loadVideo(${e}): no video track found`);let u=new Aa(l),d=await c.computeDuration(),h=await this.probeFirstFrame(u),f=this.catalogVideoSize(e)??await this.trackDisplaySize(l,h),p=new hl(f,this.decodePolicy,this.videoDemand.get(e),this.surfaceEdge()),m=gs(p.level,f);this.videoSessions.set(e,{input:c,sink:u,durationSec:d,frameStep:h.frameStep,width:m.width,height:m.height,intrinsic:f,levels:p,canvas:null,textureImage:null,uploadedTs:null,decoding:!1}),this.videoFrames.set(e,new Map),await this.decodeAt(e,i)}getVideoSize(e){return this.videoSessions.get(e)?.intrinsic??this.catalogVideoSize(e)}catalogVideoSize(e){try{let t=this.catalog.getVideoMeta(e);return t.width>0&&t.height>0?{width:t.width,height:t.height}:null}catch{return null}}async trackDisplaySize(e,t){try{let n=await e.getDisplayWidth(),i=await e.getDisplayHeight();if(n>0&&i>0)return{width:n,height:i}}catch{}return{width:Math.max(1,t.width),height:Math.max(1,t.height)}}getVideoFrame(e,t){let n=this.videoSessions.get(e),i=this.videoFrames.get(e);if(!n||!i||!this.surface)return null;Number.isFinite(t)||(t=0),this.videoPlayhead.set(e,t);let s=this.nearestDecoded(i,t,n.frameStep),a=this.quantizeTs(t,n.frameStep);return!!s&&this.quantizeTs(s.timestamp,n.frameStep)===a&&this.accepts(n,s)?this.playing&&this.driveSequentialDecode(e,t):(this.pendingVideoFrames.set(e,t),this.playing&&this.driveSequentialDecode(e,t)),s?this.uploadFrame(e,n,s):null}claimVideoFrame(e,t,n){let i=this.videoSessions.get(e);if(!i||!this.surface)return null;Number.isFinite(t)||(t=0),i.levels?.note(n);let s=this.quantizeTs(t,i.frameStep),a=this.videoFrameClaims.get(e);a||(a=[],this.videoFrameClaims.set(e,a));let o=a.indexOf(s);if(o===0)return i.textureImage;if(o>0)return this.videoAltSlots.get(e)?.[o-1]?.image??null;if(a.length===0){let u=this.getVideoFrame(e,t);return u&&a.push(i.uploadedTs??s),u}let c=Math.min(a.length-1,r.ALT_SLOT_LIMIT-1),l=this.uploadAltFrame(e,i,t,c);return l&&a.push(s),l}clearVideoAltSlots(){for(let e of this.videoAltSlots.values())for(let t of e)t.image?.delete();this.videoAltSlots.clear()}uploadAltFrame(e,t,n,i){if(!this.surface)return null;let a=this.decodedFrameFor(e,t,n);if(!a)return null;let o=this.videoAltSlots.get(e);o||(o=[],this.videoAltSlots.set(e,o));let c=o[i];c||(c={image:null,uploadedTs:null},o[i]=c);let l=this.quantizeTs(a.timestamp,t.frameStep);return c.image&&c.uploadedTs===l&&(c.bitmap===void 0||c.bitmap===a.bitmap)||(this.uploadInto(c,a,t),c.uploadedTs=c.image?l:null),c.image}uploadInto(e,t,n){let i=this.surface,s=t.bitmap.width||n.width,a=t.bitmap.height||n.height;e.image&&(e.width!==s||e.height!==a)&&(e.image.delete(),e.image=null),e.image?i.updateTextureFromSource(e.image,t.bitmap):e.image=i.makeImageFromTextureSource(t.bitmap,{width:s,height:a,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB}),e.width=s,e.height=a,e.bitmap=e.image?t.bitmap:null}decodedFrameFor(e,t,n){let i=t.frameStep,s=Math.max(0,Math.min(n,t.durationSec)),a=f=>this.accepts(t,f),o=this.videoEchoFrames.get(e),c=this.videoFrames.get(e),l=this.nearestWithin(o,s,i,a)??this.nearestWithin(c,s,i,a);if(l)return l;let u=this.pendingEchoFrames.get(e);u||(u=new Set,this.pendingEchoFrames.set(e,u)),u.add(s),this.playing&&this.decodeEchoFrameAt(e,s);let d=o?this.nearestDecoded(o,s,i):null,h=c?this.nearestDecoded(c,s,i):null;return d?h?Math.abs(d.timestamp-s)<=Math.abs(h.timestamp-s)?d:h:d:h}getVideoDuration(e){return this.videoSessions.get(e)?.durationSec??0}getVideoFrameImage(e,t,n){let i=this.videoSessions.get(e);if(!i||!this.surface||!Number.isFinite(t))return null;i.levels?.note(n);let s=Math.max(0,Math.min(t,i.durationSec)),a=i.frameStep,o=l=>this.accepts(i,l),c=this.nearestWithin(this.videoEchoFrames.get(e),s,a,o)??this.nearestWithin(this.videoFrames.get(e),s,a,o);if(!c){let l=this.pendingEchoFrames.get(e);return l||(l=new Set,this.pendingEchoFrames.set(e,l)),l.add(s),null}return this.surface.makeImageFromTextureSource(c.bitmap,{width:c.bitmap.width||i.width,height:c.bitmap.height||i.height,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB})}uploadFrame(e,t,n){if(!this.surface)return null;let i=this.quantizeTs(n.timestamp,t.frameStep);if(t.textureImage&&t.uploadedTs===i&&(t.uploadedBitmap==null||t.uploadedBitmap===n.bitmap))return t.textureImage;let s={image:t.textureImage,uploadedTs:t.uploadedTs,width:t.textureWidth,height:t.textureHeight};return this.uploadInto(s,n,t),t.textureImage=s.image,t.textureWidth=s.width,t.textureHeight=s.height,t.uploadedBitmap=s.bitmap,t.uploadedTs=t.textureImage?i:null,t.textureImage}accepts(e,t){return e.levels?e.levels.accepts(t.level,this.decodePolicy):!0}async warmVideo(){let e=[...this.pendingVideoFrames];this.pendingVideoFrames.clear();let t=[...this.pendingEchoFrames].flatMap(([s,a])=>[...a].map(o=>[s,o]));this.pendingEchoFrames.clear();let n=await Tl(),i=[...this.echoDecodes.values()];return e.length===0&&t.length===0&&i.length===0?n:(await Promise.all([...e.map(([s,a])=>this.decodeAt(s,a)),...t.map(([s,a])=>this.decodeEchoFrameAt(s,a)),...i]),!0)}driveSequentialDecode(e,t){let n=this.videoSessions.get(e);if(!n||n.decoding||!n.sink||!this.videoFrames.get(e))return;let i=n.frameStep,{forward:s}=this.windowFrames(n),a=Math.min(n.durationSec,t+s*i);t>=a||(n.decoding=!0,(async()=>{try{for await(let o of n.sink.samples(t,a+i)){let c=this.videoFrames.get(e);if(this.disposed||!c){o.close();break}let l=this.quantizeTs(o.timestamp,i),u=c.get(l);u&&this.accepts(n,u)?o.close():this.storeFrame(e,c,l,await this.snapshot(n,o));let d=this.videoPlayhead.get(e)??t;if(!this.playing||d<t-i||d>a)break}this.evictVideoWindow(e,this.videoPlayhead.get(e)??t,i)}catch(o){this.disposed||console.error(`[WebStorageAdapter] sequential decode failed for ${e}:`,o)}finally{n.decoding=!1}})())}async decodeAt(e,t){let n=this.videoSessions.get(e);if(!n||!Number.isFinite(t))return;let i=Math.max(0,Math.min(t,n.durationSec)),s=this.quantizeTs(i,n.frameStep),a=this.videoFrames.get(e),o=a?.get(s);if(!(!a||o&&this.accepts(n,o)))try{let c=await n.sink.getSample(i);if(!c)return;if(this.disposed){c.close();return}let l=await this.snapshot(n,c),u=this.videoFrames.get(e);if(!u){l.bitmap.close();return}this.storeFrame(e,u,this.quantizeTs(l.timestamp,n.frameStep),l),this.evictVideoWindow(e,i,n.frameStep)}catch(c){this.disposed||console.error(`[WebStorageAdapter] video decode failed for ${e}@${i}:`,c)}}storeFrame(e,t,n,i){let s=this.videoSessions.get(e),a=t.get(n);if(a&&s&&this.accepts(s,a)&&!this.accepts(s,i)){i.bitmap.close();return}a&&a!==i&&this.videoEchoFrames.get(e)?.get(n)!==a&&a.bitmap.close(),t.set(n,i)}decodeEchoFrameAt(e,t){let n=this.videoSessions.get(e);if(!n||!Number.isFinite(t))return Promise.resolve();let i=Math.max(0,Math.min(t,n.durationSec)),s=this.quantizeTs(i,n.frameStep),a=this.videoEchoFrames.get(e)?.get(s);if(a&&this.accepts(n,a))return Promise.resolve();let o=`${e}#${s}`,c=this.echoDecodes.get(o);if(c)return c;let l=this.decodeEchoFrameNow(e,n,i,s).finally(()=>this.echoDecodes.delete(o));return this.echoDecodes.set(o,l),l}async decodeEchoFrameNow(e,t,n,i){let s=this.videoEchoFrames.get(e),a=this.videoFrames.get(e)?.get(i);try{if(s||(s=new Map,this.videoEchoFrames.set(e,s)),a&&this.accepts(t,a))this.replaceEcho(e,s,i,a);else{let o=await t.sink.getSample(n);if(!o)return;if(this.disposed){o.close();return}let c=await this.snapshot(t,o);if(s=this.videoEchoFrames.get(e),!s){c.bitmap.close();return}this.replaceEcho(e,s,this.quantizeTs(c.timestamp,t.frameStep),c)}this.trimEchoCache(e)}catch(o){this.disposed||console.error(`[WebStorageAdapter] echo decode failed for ${e}@${n}:`,o)}}replaceEcho(e,t,n,i){let s=t.get(n);s&&s!==i&&this.videoFrames.get(e)?.get(n)!==s&&s.bitmap.close(),t.set(n,i)}trimEchoCache(e){let t=this.videoEchoFrames.get(e);if(t)for(;t.size>r.ECHO_CACHE_LIMIT;){let n=t.keys().next().value;if(n===void 0)break;let i=t.get(n);i&&this.videoFrames.get(e)?.get(n)!==i&&i.bitmap.close(),t.delete(n)}}snapshot(e,t){let n=e.levels.level,{width:i,height:s}=gs(n,e.intrinsic);try{let a=e.canvas;(!a||a.width!==i||a.height!==s)&&(a=new OffscreenCanvas(i,s),e.canvas=a);let o=a.getContext("2d");if(!o)throw new Error("video snapshot: could not get 2d context");o.imageSmoothingEnabled=!0,o.imageSmoothingQuality="high",o.clearRect(0,0,i,s),t.drawWithFit(o,{fit:"fill"});let c=createImageBitmap(a),l=t.timestamp;return c.then(u=>({timestamp:l,bitmap:u,level:n}))}finally{t.close()}}windowFrames(e){return H0(e?{width:e.width,height:e.height}:null)}evictVideoWindow(e,t,n){let i=this.videoFrames.get(e);if(!i)return;let{forward:s,back:a}=this.windowFrames(this.videoSessions.get(e)),o=t-a*n,c=t+s*n,l=this.videoEchoFrames.get(e);for(let[u,d]of i)(d.timestamp<o||d.timestamp>c)&&(l?.get(u)!==d&&d.bitmap.close(),i.delete(u))}nearestDecoded(e,t,n){let i=e.get(this.quantizeTs(t,n));if(i)return i;let s=null,a=1/0;for(let o of e.values()){let c=Math.abs(o.timestamp-t);c<a&&(a=c,s=o)}return s}quantizeTs(e,t){return Math.round(e/t)}nearestWithin(e,t,n,i){if(!e||e.size===0)return null;let s=null,a=1/0;for(let o of e.values()){if(i&&!i(o))continue;let c=Math.abs(o.timestamp-t);c<a&&(a=c,s=o)}return s&&a<=n?s:null}async probeFirstFrame(e){try{let t=await e.getSample(0);if(!t)for await(let n of e.samples()){t=n;break}if(t){let n={frameStep:t.duration>0?t.duration:.03333333333333333,width:t.displayWidth,height:t.displayHeight};return t.close(),n}}catch{}return{frameStep:1/30,width:1,height:1}}makeCKImageFromPixels(e,t,n){return this.canvasKit.MakeImage({width:t,height:n,alphaType:this.canvasKit.AlphaType.Unpremul,colorType:this.canvasKit.ColorType.RGBA_8888,colorSpace:this.canvasKit.ColorSpace.SRGB},e,4*t)}async loadAudio(e,t,n,i=0,s){if(this.audioBuffers.has(e))return;this.audioCtx||(this.audioCtx=new AudioContext);let a=await(await this.fetchBlob(this.assetUrl(e,"media"))).arrayBuffer(),o=await this.audioCtx.decodeAudioData(a);this.audioBuffers.set(e,o)}async fetchAudioData(e){return(await this.fetchBlob(this.assetUrl(e,"media"))).arrayBuffer()}getAudioBuffer(e){return this.audioBuffers.get(e)??null}async loadFont(e,t,n){if(this.registeredFontFamilies.has(t))return!0;let i=this.catalog.getFontFamilyMetas(t);if(i.length===0)return this.decodePolicy==="interactive"&&!this.unknownFontFamilies.has(t)&&(this.unknownFontFamilies.add(t),console.warn(`[WebStorageAdapter] No font manifest entry for "${e}"; shaping against the fallback face. Add it to the manifest font record.`)),!1;let s=[...new Set(i.map(o=>o.src))],a=await Promise.all(s.map(async o=>(await this.fetchBlob(o)).arrayBuffer()));for(let o of a)this.fontMgr.registerFont(new Uint8Array(o),t);return this.registeredFontFamilies.add(t),this.unknownFontFamilies.delete(t),this.fontEpoch++,!0}getFontMgr(){return this.fontMgr}getParagraphCache(){return this.paragraphCache}getFontEpoch(){return this.fontEpoch}dispose(){if(this.disposed)return;this.disposed=!0,this.paragraphCache.dispose(),this.images.dispose(),this.imageSources.clear();for(let t of this.canvas3DTextures.values())t.delete();this.canvas3DTextures.clear();let e=new Set;for(let t of this.videoFrames.values())for(let{bitmap:n}of t.values())n.close(),e.add(n);this.videoFrames.clear();for(let t of this.videoEchoFrames.values())for(let{bitmap:n}of t.values())e.has(n)||n.close();this.videoEchoFrames.clear();for(let t of this.videoSessions.values())t.textureImage?.delete(),t.input.dispose();this.videoSessions.clear(),this.clearVideoAltSlots(),this.videoPlayhead.clear(),this.videoFrameClaims.clear(),this.pendingVideoFrames.clear(),this.pendingEchoFrames.clear(),this.echoDecodes.clear(),this.surface=null,this.audioBuffers.clear(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close(),this.audioCtx=null,super.dispose()}};import bv from"@motionscript/canvaskit";var zd=null,fl=null;function kv(){return new URL("@motionscript/canvaskit/canvaskit.wasm",import.meta.url).href}async function Xr(r){if(zd)return zd;if(fl)return fl;let e=r??kv();return fl=bv({locateFile:()=>e}).then(t=>(zd=t,t)),fl}import{DEFAULT_OUTPUT as Sv,ManifestAssetCatalog as xv,Registry as Tv,resolveProjectDocument as Av}from"@motionscript/core";var vv=.2,_v=2e6,Cv=1e8;function G0(r,e,t){let n=r*e*t*vv;return Math.round(Math.min(Cv,Math.max(_v,n)))}var Pv=192e3,Ev=1,Iv=2,Mv={image:{},video:{},audio:{},font:{}},Vd=class{audioOptions;target=new ar;output;video;audio=null;constructor(e,t,n,i={},s={},a="avc"){this.audioOptions=s;let o=n.width!==e.width||n.height!==e.height;this.video=new Ea(e,{codec:a,bitrate:i.bitrate??G0(n.width,n.height,t),hardwareAcceleration:i.hardwareAcceleration??"no-preference",keyFrameInterval:i.keyFrameInterval??Ev,latencyMode:i.latencyMode??"quality",contentHint:i.contentHint??"detail",...i.bitrateMode!==void 0&&{bitrateMode:i.bitrateMode},...o&&{transform:{width:n.width,height:n.height,fit:"fill"}}}),this.output=new ri({format:new xn,target:this.target})}async start(e){this.output.addVideoTrack(this.video,{frameRate:e.fps}),e.hasAudio&&(this.audio=new ti({codec:"aac",bitrate:this.audioOptions.bitrate??Pv}),this.output.addAudioTrack(this.audio)),await this.output.start()}async addFrame(e,t){await this.video.add(e,t)}async addAudio(e){this.audio&&await this.audio.add(e)}async finalize(){this.video.close(),this.audio?.close(),await this.output.finalize();let e=this.target.buffer;if(!e)throw new Error("Export produced no data");return new Uint8Array(e)}};function q0(r){let e=Math.round(r);return e%2===0?e:e+1}var Fv=8192;function Rv(r,e){let t=Math.max(e.width,e.height),n=Math.max(1,Math.round(r));for(;n>1&&t*n>Fv;)n--;return n}async function Bv(r,e,t){if(!r||r==="avc")return"avc";try{if(await pd(r,{width:e.width,height:e.height,bitrate:G0(e.width,e.height,t)}))return r}catch{}return console.warn(`[motionscript] No ${r} encoder available; exporting as H.264 instead.`),"avc"}async function Hd(r){let{document:e,registry:t=new Tv,scale:n=1,filename:i="export.mp4",manifest:s=Mv,theme:a,includeAudio:o=!0,video:c,audio:l={},frames:u,onProgress:d,signal:h,wasmUrl:f,supersample:p=Iv,returnBytes:m=!1}=r,g=Av(e,r,Sv);if(g.tracks.length===0)return;h?.throwIfAborted();let y=g.viewport,b=g.fps,k={width:q0(y.width*n),height:q0(y.height*n)},T=Rv(p,k),x=n*T,v=document.createElement("canvas");v.width=k.width*T,v.height=k.height*T,v.style.display="none",document.body.appendChild(v);let M=await Xr(f),C=new xv(s),_=new Kt(M,C,y,b),F=new cr(M,_);F.mount(v);let E=await Bv(c?.codec,k,b),O;try{O=await mu({project:g,registry:t,theme:a,scale:x,includeAudio:o,frames:u,renderContext:F,storageAdapter:_,assetCatalog:C,sink:new Vd(v,b,k,c,l,E),mixer:new rh(l.sampleRate,C),onProgress:d,signal:h})}finally{F.dispose(),document.body.removeChild(v)}if(!O)return;if(m)return O;let Q=new Blob([O.buffer],{type:"video/mp4"}),ye=URL.createObjectURL(Q),Z=document.createElement("a");Z.href=ye,Z.download=i,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(ye)}import{DEFAULT_OUTPUT as zv,resolveProjectDocument as Vv}from"@motionscript/core";import{DEFAULT_OUTPUT as K0,ManifestAssetCatalog as j0,frameSpecAtTime as Dv,Registry as Ov,resolveProjectDocument as Lv}from"@motionscript/core";var Uv={image:{},video:{},audio:{},font:{}};function Nv(r,e){if(r?.time!==void 0)return Dv(r.time,e);let t=r?.frame;return t===void 0||t==="first"?{kind:"first"}:t==="last"?{kind:"last"}:typeof t=="number"?{kind:"frame",frame:t}:t}function $0(r){return r==="jpeg"?"image/jpeg":"image/png"}var ws=class{canvas;renderContext;storageAdapter;catalog;canvasKit;ownsCanvas;viewportValue;fpsValue;scaleValue;surfaceScale;manifest;theme;registry;disposed=!1;drawn=!1;constructor(e,t){this.canvasKit=e,this.viewportValue=t.viewport??K0.viewport,this.fpsValue=t.fps??K0.fps,this.scaleValue=t.scale??1,this.surfaceScale=this.scaleValue,this.manifest=t.manifest??Uv,this.theme=t.theme,this.registry=t.registry??new Ov,this.ownsCanvas=t.canvas===void 0,this.canvas=t.canvas??document.createElement("canvas"),this.ownsCanvas&&(this.canvas.style.display="none",document.body.appendChild(this.canvas)),this.sizeCanvas(),this.catalog=new j0(this.manifest),this.storageAdapter=new Kt(e,this.catalog,this.viewportValue,this.fpsValue),this.renderContext=new cr(e,this.storageAdapter),this.renderContext.mount(this.canvas)}get viewport(){return this.viewportValue}get fps(){return this.fpsValue}get scale(){return this.scaleValue}async render(e,t){this.assertLive();let n=t?.scale??this.scaleValue;n!==this.surfaceScale&&this.remount(n);let i=Lv(e,{viewport:this.viewportValue},{viewport:this.viewportValue,fps:this.fpsValue}),s=await pu({project:i,registry:this.registry,theme:this.theme,scale:n,renderContext:this.renderContext,storageAdapter:this.storageAdapter,assetCatalog:this.catalog,frame:Nv(t,i.fps)});return this.drawn=!0,s}setTheme(e){this.theme=e}setManifest(e){this.assertLive(),this.manifest=e,this.catalog=new j0(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 Kt(this.canvasKit,this.catalog,e,this.fpsValue),this.renderContext=new cr(this.canvasKit,this.storageAdapter),this.remount(this.scaleValue))}async toBytes(e){let t=await this.toBlob(e);return new Uint8Array(await t.arrayBuffer())}toBlob(e){let t=this.snapshotToCanvas(),{format:n="png",quality:i=.92}=e??{};return new Promise((s,a)=>{t.toBlob(o=>o?s(o):a(new Error("Still encode produced no data.")),$0(n),i)})}toDataURL(e){let{format:t="png",quality:n=.92}=e??{};return this.snapshotToCanvas().toDataURL($0(t),n)}dispose(){this.disposed||(this.disposed=!0,this.renderContext.dispose(),this.ownsCanvas&&this.canvas.remove())}snapshotToCanvas(){this.assertLive();let e=this.drawn?this.renderContext.snapshotPixels():void 0;if(!e)throw new Error("Nothing has been rendered yet.");let t=document.createElement("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");if(!n)throw new Error("Still encode: could not get a 2d context.");return n.putImageData(new ImageData(new Uint8ClampedArray(e.pixels),e.width,e.height),0,0),t}sizeCanvas(){this.canvas.width=this.viewportValue.width*this.surfaceScale,this.canvas.height=this.viewportValue.height*this.surfaceScale}remount(e){this.surfaceScale=e,this.drawn=!1,this.sizeCanvas(),this.renderContext.mount(this.canvas)}assertLive(){if(this.disposed)throw new Error("This StillRenderer has been disposed.")}};async function Wd(r={}){let e=await Xr(r.wasmUrl);return new ws(e,r)}async function Hv(r){let{registry:e,scale:t,manifest:n,theme:i,wasmUrl:s,frame:a,format:o="png",quality:c=.92}=r,l=Vv(r.document,r,zv);if(l.tracks.length===0)throw new Error("The project has no tracks to screenshot.");let u=await Wd({viewport:l.viewport,fps:l.fps,scale:t,manifest:n,theme:i,wasmUrl:s,registry:e});try{return{...await u.render(l,{frame:a}),bytes:await u.toBytes({format:o,quality:c})}}finally{u.dispose()}}var bs=class extends Error{segment;constructor(e,t){super(t),this.segment=e,this.name="ConcatMismatchError"}};function Wv(r,e){if(r.codec!==e.codec||r.codedWidth!==e.codedWidth||r.codedHeight!==e.codedHeight)return!1;let t=X0(r.description),n=X0(e.description);if(t===null||n===null)return t===n;if(t.length!==n.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==n[i])return!1;return!0}function X0(r){return r?ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r):null}var qv=192e3;async function Gv(r,e={}){if(r.length===0)throw new Error("concatVideoSegments: no segments");if(r.length===1&&!e.audio&&!e.stream)return r[0];let t=[];for(let l=0;l<r.length;l++){let d=await new Gr({source:new da(r[l]),formats:[$c]}).getPrimaryVideoTrack();if(!d)throw new bs(l,`Segment ${l} has no video track.`);let h=await d.getDecoderConfig();if(!h)throw new bs(l,`Segment ${l} has no decoder configuration.`);if(t.length>0&&!Wv(t[0].config,h))throw new bs(l,`Segment ${l} was encoded differently from segment 0 (${t[0].config.codec} ${t[0].config.codedWidth}x${t[0].config.codedHeight} vs ${h.codec} ${h.codedWidth}x${h.codedHeight}); joining them would decode as garbage.`);t.push({track:d,config:h,duration:await d.computeDuration()})}let n=e.stream?new Ca(e.stream):new ar,i=new ri({format:new xn,target:n}),s=new Pa(t[0].track.codec);i.addVideoTrack(s);let a=e.audio?new ti({codec:"aac",bitrate:e.audioBitrate??qv}):null;a&&i.addAudioTrack(a),await i.start();let o=0;for(let l of t){let u=!0;for await(let d of new bn(l.track).packets())await s.add(d.clone({timestamp:d.timestamp+o}),u?{decoderConfig:l.config}:void 0),u=!1;o+=l.duration}if(a&&e.audio&&await a.add(e.audio),s.close(),a?.close(),await i.finalize(),e.stream)return new Uint8Array(0);let c=n.buffer;if(!c)throw new Error("concatVideoSegments produced no data");return new Uint8Array(c)}import{DEFAULT_OUTPUT as Kv,ManifestAssetCatalog as jv,AssetTimeline as $v,Registry as Xv,resolveProjectDocument as Qv}from"@motionscript/core";var ml=class{storageAdapter;constructor(e){this.storageAdapter=e}measureText(e,t,n,i=400,s=0,a="normal"){return mo(this.storageAdapter.getCanvasKit(),this.storageAdapter.getFontMgr(),this.storageAdapter.getParagraphCache(),this.storageAdapter.getFontEpoch(),e,t,n,i,s,a)}layoutTextBlock(e){return po(this.storageAdapter.getCanvasKit(),this.storageAdapter.getFontMgr(),e)}};var ni=class extends ml{};var Yv={image:{},video:{},audio:{},font:{}};async function Zv(r){let{registry:e=new Xv,manifest:t=Yv,sampleRate:n,wasmUrl:i}=r,s=Qv(r.document,r,Kv);if(s.tracks.length===0)return null;let a=s.viewport,o=s.fps,c=await Xr(i),l=new jv(t),u=new Kt(c,l,a,o),d=new ni(u),h=new $v(s,{registry:e,viewport:a,fps:o,assets:l,measurer:d},{assets:!1});try{let f=h.run(),p=fu(f);return p.length===0?null:await yl(p,f.totalDuration,{sampleRate:n,catalog:l})}finally{h.dispose(),u.dispose()}}import{Ticker as Jv}from"@motionscript/core";var Fa=class extends Jv{context;ownsContext;fps;playStartCtxTime=0;seekOffset=0;speed=1;reverse=!1;rafId=null;seekEpoch=0;silentSource=null;constructor(e){super(),this.context=e.context??new AudioContext,this.ownsContext=!e.context,this.fps=e.fps}getContext(){return this.context}seek(e){let t=Math.max(0,Math.min(e,this.duration));this.seekOffset=t,this.playStartCtxTime=this.context.currentTime,this.seekEpoch++,this.setCurrentTime(t)}play(e=1,t=!1){this.speed=e,this.reverse=t,this.seekOffset=this.currentTime,this.context.state==="suspended"&&this.context.resume().then(()=>{!this.isPlaying&&this.context.state==="running"&&this.context.suspend()},n=>{console.error("[WebTicker] The audio context could not resume:",n),this.pause()}),this.playStartCtxTime=this.context.currentTime,this.startSilentTicker(),super.play(e,t),this.startLoop()}pause(){this.seekOffset=this.currentTime,this.stopLoop(),this.stopSilentTicker(),this.context.state==="running"&&this.context.suspend(),super.pause()}startSilentTicker(){this.stopSilentTicker();let e=Math.max(.001,this.duration-this.seekOffset),t=this.context.sampleRate,n=this.context.createBuffer(1,Math.ceil(e*t),t),i=this.context.createBufferSource();i.buffer=n,i.connect(this.context.destination),i.start(),this.silentSource=i}stopSilentTicker(){if(this.silentSource){try{this.silentSource.onended=null,this.silentSource.stop(),this.silentSource.disconnect()}catch{}this.silentSource=null}}position(){let e=(this.context.currentTime-this.playStartCtxTime)*this.speed,t=this.reverse?this.seekOffset-e:this.seekOffset+e,n=Math.max(0,Math.min(t,this.duration));return{time:n,ended:this.reverse?n<=0:n>=this.duration}}startLoop(){if(this.rafId!==null)return;let e=1/this.fps,t=this.currentTime,n=async()=>{let i=this.seekEpoch,s=this.position(),a=s.ended,c=Math.abs(s.time-t)>=e||a;this.setCurrentTime(s.time,c);let l=()=>{this.seekEpoch!==i&&(i=this.seekEpoch,t=this.currentTime,a=this.position().ended)};if(l(),c&&(t=this.currentTime,await this.tick(),l()),this.rafId!==null){if(a){this.pause();return}this.rafId=requestAnimationFrame(n)}};this.rafId=requestAnimationFrame(n)}stopLoop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}dispose(){this.stopLoop(),this.stopSilentTicker(),this.ownsContext&&this.context.close(),super.dispose()}};import{Engine as i1}from"@motionscript/core";var pl=_y(Q0(),1);import*as e1 from"@motionscript/core/sdk";function t1(){return new URL("esbuild-wasm/esbuild.wasm",import.meta.url).href}var r1;function n1(r){return r1??=(async()=>(await pl.initialize({wasmURL:r??t1()}),async e=>{let{code:t}=await pl.transform(e,{loader:"ts",format:"cjs",target:"es2020"});return t}))()}function Y0(r,e){return{sdk:r?.sdk??e1,modules:r?.modules,compile:r?.compile??(async t=>(await n1(e))(t))}}var Gd=class{canvasKit;defaults;wasmUrl;still=null;stillRegistry=null;stillQueue=Promise.resolve();constructor(e,t,n){this.canvasKit=e,this.defaults=t,this.wasmUrl=n}async exportVideo(e){let t=e.encode??{};return Hd({document:e.project,registry:e.registry,scale:e.scale,manifest:e.manifest,includeAudio:e.includeAudio,frames:e.frames,video:t.video??this.defaults.video,audio:t.audio??this.defaults.audio,supersample:t.supersample,filename:t.filename,returnBytes:t.download!==!0,onProgress:e.onProgress,signal:e.signal,wasmUrl:this.wasmUrl})}exportStill(e){let t=this.stillQueue.then(()=>this.drawStill(e));return this.stillQueue=t.catch(()=>{}),t}dispose(){this.still?.dispose(),this.still=null}async drawStill(e){let t=this.renderer(e),n=await t.render(e.project,{scale:e.scale,...s1(e.frame)});return{bytes:await t.toBytes({format:e.format,quality:e.quality}),frame:n.frame,totalFrames:n.totalFrames}}renderer(e){let{project:t,registry:n}=e;if(t.viewport===void 0||t.fps===void 0)throw new Error("exportStill takes a project whose fps and viewport are resolved \u2014 see Session.");return this.still&&this.stillRegistry!==n&&this.dispose(),this.still??=new ws(this.canvasKit,{viewport:t.viewport,fps:t.fps,manifest:e.manifest,registry:n}),this.stillRegistry=n,this.still.setViewport(t.viewport),e.manifest&&this.still.setManifest(e.manifest),this.still}};function s1(r){return r.kind==="frame"?{frame:r.frame}:{frame:r.kind}}async function a1(r={}){let e=r.nodes,t=Array.isArray(e)?e.filter(l=>typeof l!="string"):e,n=Array.isArray(e)?e.filter(l=>typeof l=="string"):[],i=Y0(r.dynamicNodes,r.compilerWasmUrl),s=await Xr(r.wasmUrl),a=new Gd(s,{video:r.video,audio:r.audio},r.wasmUrl),o={createStorageAdapter({catalog:l,viewport:u,fps:d}){return new Kt(s,l,u,d)},createRenderContext(l){return new cr(s,l)},createMeasureContext(l){return new ni(l)},createAudioSink(){return new wl},createTicker(l,u){return new Fa({context:u.getContext(),fps:l})},createExporter(){return a},dispose(){a.dispose()}},c=new i1(o,{...r,nodes:t,dynamicNodes:i});for(let l of n)await c.registerNode(l);return c}export{_s as Canvas3DBackend,bs as ConcatMismatchError,Se as EffectRegistry,Us as NothingToDrawError,h0 as QUALITY_HIGH,u0 as QUALITY_LOW,d0 as QUALITY_MEDIUM,f0 as QUALITY_VERY_HIGH,l0 as QUALITY_VERY_LOW,ws as StillRenderer,wl as WebAudioPlayer,ni as WebMeasureContext,cr as WebRenderContext,Kt as WebStorageAdapter,Fa as WebTicker,ci as canvas3DBackend,Gv as concatVideoSegments,a1 as createBrowserEngine,Wd as createStillRenderer,Xa as disposeCanvas3DBackend,Py as encodeWav,Hv as exportScreenshot,Hd as exportVideo,Xr as getCanvasKit,As as loadCanvas3D,yl as mixAudio,Zv as mixTimelineAudio,Cy as setAssetByteSource};
1960
- /*! Bundled license information:
1961
-
1962
- mediabunny/dist/modules/src/misc.js:
1963
- mediabunny/dist/modules/src/logging.js:
1964
- mediabunny/dist/modules/src/metadata.js:
1965
- mediabunny/dist/modules/shared/bitstream.js:
1966
- mediabunny/dist/modules/shared/aac-misc.js:
1967
- mediabunny/dist/modules/src/codec.js:
1968
- mediabunny/dist/modules/shared/mp3-misc.js:
1969
- mediabunny/dist/modules/shared/ac3-misc.js:
1970
- mediabunny/dist/modules/src/codec-data.js:
1971
- mediabunny/dist/modules/src/demuxer.js:
1972
- mediabunny/dist/modules/src/packet.js:
1973
- mediabunny/dist/modules/src/isobmff/isobmff-misc.js:
1974
- mediabunny/dist/modules/src/isobmff/isobmff-reader.js:
1975
- mediabunny/dist/modules/src/aes.js:
1976
- mediabunny/dist/modules/src/isobmff/isobmff-demuxer.js:
1977
- mediabunny/dist/modules/src/matroska/ebml.js:
1978
- mediabunny/dist/modules/src/matroska/matroska-misc.js:
1979
- mediabunny/dist/modules/src/matroska/matroska-demuxer.js:
1980
- mediabunny/dist/modules/src/mp3/mp3-reader.js:
1981
- mediabunny/dist/modules/src/mp3/mp3-demuxer.js:
1982
- mediabunny/dist/modules/src/ogg/ogg-misc.js:
1983
- mediabunny/dist/modules/src/ogg/ogg-reader.js:
1984
- mediabunny/dist/modules/src/ogg/ogg-demuxer.js:
1985
- mediabunny/dist/modules/src/wave/wave-demuxer.js:
1986
- mediabunny/dist/modules/src/adts/adts-reader.js:
1987
- mediabunny/dist/modules/src/adts/adts-demuxer.js:
1988
- mediabunny/dist/modules/src/flac/flac-misc.js:
1989
- mediabunny/dist/modules/src/flac/flac-demuxer.js:
1990
- mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-misc.js:
1991
- mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-demuxer.js:
1992
- mediabunny/dist/modules/src/hls/hls-misc.js:
1993
- mediabunny/dist/modules/src/segmented-input.js:
1994
- mediabunny/dist/modules/src/source.js:
1995
- mediabunny/dist/modules/src/hls/hls-segmented-input.js:
1996
- mediabunny/dist/modules/src/hls/hls-demuxer.js:
1997
- mediabunny/dist/modules/src/input-format.js:
1998
- mediabunny/dist/modules/src/sample.js:
1999
- mediabunny/dist/modules/src/encode.js:
2000
- mediabunny/dist/modules/src/custom-coder.js:
2001
- mediabunny/dist/modules/src/pcm.js:
2002
- mediabunny/dist/modules/src/media-sink.js:
2003
- mediabunny/dist/modules/src/input-track.js:
2004
- mediabunny/dist/modules/src/input.js:
2005
- mediabunny/dist/modules/src/reader.js:
2006
- mediabunny/dist/modules/src/id3.js:
2007
- mediabunny/dist/modules/src/muxer.js:
2008
- mediabunny/dist/modules/src/subtitles.js:
2009
- mediabunny/dist/modules/src/isobmff/isobmff-boxes.js:
2010
- mediabunny/dist/modules/src/writer.js:
2011
- mediabunny/dist/modules/src/target.js:
2012
- mediabunny/dist/modules/src/isobmff/isobmff-muxer.js:
2013
- mediabunny/dist/modules/src/resample.js:
2014
- mediabunny/dist/modules/src/media-source.js:
2015
- mediabunny/dist/modules/src/output-format.js:
2016
- mediabunny/dist/modules/src/output.js:
2017
- mediabunny/dist/modules/src/index.js:
2018
- (*!
2019
- * Copyright (c) 2026-present, Vanilagy and contributors
2020
- *
2021
- * This Source Code Form is subject to the terms of the Mozilla Public
2022
- * License, v. 2.0. If a copy of the MPL was not distributed with this
2023
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
2024
- *)
2025
- */
692
+ })(postMessage)`],{type:"text/javascript"});S=new Worker(URL.createObjectURL(Z))}else{let Z=(ue=>{var pe=(te,ee,U)=>new Promise((C,k)=>{var T=J=>{try{j(U.next(J))}catch(E){k(E)}},I=J=>{try{j(U.throw(J))}catch(E){k(E)}},j=J=>J.done?C(J.value):Promise.resolve(J.value).then(T,I);j((U=U.apply(te,ee)).next())});let me,ne={};for(let te=self;te;te=Object.getPrototypeOf(te))for(let ee of Object.getOwnPropertyNames(te))ee in ne||Object.defineProperty(ne,ee,{get:()=>self[ee]});(()=>{let te=()=>{let C=new Error("not implemented");return C.code="ENOSYS",C};if(!ne.fs){let C="";ne.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1,O_DIRECTORY:-1},writeSync(k,T){C+=U.decode(T);let I=C.lastIndexOf(`
693
+ `);return I!=-1&&(console.log(C.substring(0,I)),C=C.substring(I+1)),T.length},write(k,T,I,j,J,E){if(I!==0||j!==T.length||J!==null){E(te());return}let D=this.writeSync(k,T);E(null,D)},chmod(k,T,I){I(te())},chown(k,T,I,j){j(te())},close(k,T){T(te())},fchmod(k,T,I){I(te())},fchown(k,T,I,j){j(te())},fstat(k,T){T(te())},fsync(k,T){T(null)},ftruncate(k,T,I){I(te())},lchown(k,T,I,j){j(te())},link(k,T,I){I(te())},lstat(k,T){T(te())},mkdir(k,T,I){I(te())},open(k,T,I,j){j(te())},read(k,T,I,j,J,E){E(te())},readdir(k,T){T(te())},readlink(k,T){T(te())},rename(k,T,I){I(te())},rmdir(k,T){T(te())},stat(k,T){T(te())},symlink(k,T,I){I(te())},truncate(k,T,I){I(te())},unlink(k,T){T(te())},utimes(k,T,I,j){j(te())}}}if(ne.process||(ne.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw te()},pid:-1,ppid:-1,umask(){throw te()},cwd(){throw te()},chdir(){throw te()}}),ne.path||(ne.path={resolve(...C){return C.join("/")}}),!ne.crypto)throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");if(!ne.performance)throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");if(!ne.TextEncoder)throw new Error("globalThis.TextEncoder is not available, polyfill required");if(!ne.TextDecoder)throw new Error("globalThis.TextDecoder is not available, polyfill required");let ee=new TextEncoder("utf-8"),U=new TextDecoder("utf-8");ne.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=g=>{g!==0&&console.warn("exit code:",g)},this._exitPromise=new Promise(g=>{this._resolveExitPromise=g}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let C=(g,M)=>{this.mem.setUint32(g+0,M,!0),this.mem.setUint32(g+4,Math.floor(M/4294967296),!0)},k=(g,M)=>{this.mem.setUint32(g+0,M,!0)},T=g=>{let M=this.mem.getUint32(g+0,!0),W=this.mem.getInt32(g+4,!0);return M+W*4294967296},I=g=>{let M=this.mem.getFloat64(g,!0);if(M===0)return;if(!isNaN(M))return M;let W=this.mem.getUint32(g,!0);return this._values[W]},j=(g,M)=>{if(typeof M=="number"&&M!==0){if(isNaN(M)){this.mem.setUint32(g+4,2146959360,!0),this.mem.setUint32(g,0,!0);return}this.mem.setFloat64(g,M,!0);return}if(M===void 0){this.mem.setFloat64(g,0,!0);return}let Q=this._ids.get(M);Q===void 0&&(Q=this._idPool.pop(),Q===void 0&&(Q=this._values.length),this._values[Q]=M,this._goRefCounts[Q]=0,this._ids.set(M,Q)),this._goRefCounts[Q]++;let fe=0;switch(typeof M){case"object":M!==null&&(fe=1);break;case"string":fe=2;break;case"symbol":fe=3;break;case"function":fe=4;break}this.mem.setUint32(g+4,2146959360|fe,!0),this.mem.setUint32(g,Q,!0)},J=g=>{let M=T(g+0),W=T(g+8);return new Uint8Array(this._inst.exports.mem.buffer,M,W)},E=g=>{let M=T(g+0),W=T(g+8),Q=new Array(W);for(let fe=0;fe<W;fe++)Q[fe]=I(M+fe*8);return Q},D=g=>{let M=T(g+0),W=T(g+8);return U.decode(new DataView(this._inst.exports.mem.buffer,M,W))},z=(g,M)=>(this._inst.exports.testExport0(),this._inst.exports.testExport(g,M)),ie=Date.now()-performance.now();this.importObject={_gotest:{add:(g,M)=>g+M,callExport:z},gojs:{"runtime.wasmExit":g=>{g>>>=0;let M=this.mem.getInt32(g+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(M)},"runtime.wasmWrite":g=>{g>>>=0;let M=T(g+8),W=T(g+16),Q=this.mem.getInt32(g+24,!0);ne.fs.writeSync(M,new Uint8Array(this._inst.exports.mem.buffer,W,Q))},"runtime.resetMemoryDataView":g=>{g>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":g=>{g>>>=0,C(g+8,(ie+performance.now())*1e6)},"runtime.walltime":g=>{g>>>=0;let M=new Date().getTime();C(g+8,M/1e3),this.mem.setInt32(g+16,M%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":g=>{g>>>=0;let M=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(M,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(M);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},T(g+8))),this.mem.setInt32(g+16,M,!0)},"runtime.clearTimeoutEvent":g=>{g>>>=0;let M=this.mem.getInt32(g+8,!0);clearTimeout(this._scheduledTimeouts.get(M)),this._scheduledTimeouts.delete(M)},"runtime.getRandomData":g=>{g>>>=0,crypto.getRandomValues(J(g+8))},"syscall/js.finalizeRef":g=>{g>>>=0;let M=this.mem.getUint32(g+8,!0);if(this._goRefCounts[M]--,this._goRefCounts[M]===0){let W=this._values[M];this._values[M]=null,this._ids.delete(W),this._idPool.push(M)}},"syscall/js.stringVal":g=>{g>>>=0,j(g+24,D(g+8))},"syscall/js.valueGet":g=>{g>>>=0;let M=Reflect.get(I(g+8),D(g+16));g=this._inst.exports.getsp()>>>0,j(g+32,M)},"syscall/js.valueSet":g=>{g>>>=0,Reflect.set(I(g+8),D(g+16),I(g+32))},"syscall/js.valueDelete":g=>{g>>>=0,Reflect.deleteProperty(I(g+8),D(g+16))},"syscall/js.valueIndex":g=>{g>>>=0,j(g+24,Reflect.get(I(g+8),T(g+16)))},"syscall/js.valueSetIndex":g=>{g>>>=0,Reflect.set(I(g+8),T(g+16),I(g+24))},"syscall/js.valueCall":g=>{g>>>=0;try{let M=I(g+8),W=Reflect.get(M,D(g+16)),Q=E(g+32),fe=Reflect.apply(W,M,Q);g=this._inst.exports.getsp()>>>0,j(g+56,fe),this.mem.setUint8(g+64,1)}catch(M){g=this._inst.exports.getsp()>>>0,j(g+56,M),this.mem.setUint8(g+64,0)}},"syscall/js.valueInvoke":g=>{g>>>=0;try{let M=I(g+8),W=E(g+16),Q=Reflect.apply(M,void 0,W);g=this._inst.exports.getsp()>>>0,j(g+40,Q),this.mem.setUint8(g+48,1)}catch(M){g=this._inst.exports.getsp()>>>0,j(g+40,M),this.mem.setUint8(g+48,0)}},"syscall/js.valueNew":g=>{g>>>=0;try{let M=I(g+8),W=E(g+16),Q=Reflect.construct(M,W);g=this._inst.exports.getsp()>>>0,j(g+40,Q),this.mem.setUint8(g+48,1)}catch(M){g=this._inst.exports.getsp()>>>0,j(g+40,M),this.mem.setUint8(g+48,0)}},"syscall/js.valueLength":g=>{g>>>=0,C(g+16,parseInt(I(g+8).length))},"syscall/js.valuePrepareString":g=>{g>>>=0;let M=ee.encode(String(I(g+8)));j(g+16,M),C(g+24,M.length)},"syscall/js.valueLoadString":g=>{g>>>=0;let M=I(g+8);J(g+16).set(M)},"syscall/js.valueInstanceOf":g=>{g>>>=0,this.mem.setUint8(g+24,I(g+8)instanceof I(g+16)?1:0)},"syscall/js.copyBytesToGo":g=>{g>>>=0;let M=J(g+8),W=I(g+32);if(!(W instanceof Uint8Array||W instanceof Uint8ClampedArray)){this.mem.setUint8(g+48,0);return}let Q=W.subarray(0,M.length);M.set(Q),C(g+40,Q.length),this.mem.setUint8(g+48,1)},"syscall/js.copyBytesToJS":g=>{g>>>=0;let M=I(g+8),W=J(g+16);if(!(M instanceof Uint8Array||M instanceof Uint8ClampedArray)){this.mem.setUint8(g+48,0);return}let Q=W.subarray(0,M.length);M.set(Q),C(g+40,Q.length),this.mem.setUint8(g+48,1)},debug:g=>{console.log(g)}}}}run(C){return pe(this,null,function*(){if(!(C instanceof WebAssembly.Instance))throw new Error("Go.run: WebAssembly.Instance expected");this._inst=C,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,ne,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[ne,5],[this,6]]),this._idPool=[],this.exited=!1;let k=4096,T=z=>{let ie=k,g=ee.encode(z+"\0");return new Uint8Array(this.mem.buffer,k,g.length).set(g),k+=g.length,k%8!==0&&(k+=8-k%8),ie},I=this.argv.length,j=[];this.argv.forEach(z=>{j.push(T(z))}),j.push(0),Object.keys(this.env).sort().forEach(z=>{j.push(T(`${z}=${this.env[z]}`))}),j.push(0);let E=k;if(j.forEach(z=>{this.mem.setUint32(k,z,!0),this.mem.setUint32(k+4,0,!0),k+=8}),k>=12288)throw new Error("total length of command line and environment variables exceeds limit");this._inst.exports.run(I,E),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(C){let k=this;return function(){let T={id:C,this:this,args:arguments};return k._pendingEvent=T,k._resume(),T.result}}}})(),me=({data:te})=>{let ee=new TextDecoder,U=ne.fs,C="";U.writeSync=(J,E)=>{if(J===1)ue(E);else if(J===2){C+=ee.decode(E);let D=C.split(`
694
+ `);D.length>1&&console.log(D.slice(0,-1).join(`
695
+ `)),C=D[D.length-1]}else throw new Error("Bad write");return E.length};let k=[],T,I=0;me=({data:J})=>(J.length>0&&(k.push(J),T&&T()),j),U.read=(J,E,D,z,ie,g)=>{if(J!==0||D!==0||z!==E.length||ie!==null)throw new Error("Bad read");if(k.length===0){T=()=>U.read(J,E,D,z,ie,g);return}let M=k[0],W=Math.max(0,Math.min(z,M.length-I));E.set(M.subarray(I,I+W),D),I+=W,I===M.length&&(k.shift(),I=0),g(null,W)};let j=new ne.Go;return j.argv=["","--service=0.28.2"],Ee(te,j).then(J=>{ue(null),j.run(J)},J=>{ue(J)}),j};function Ee(te,ee){return pe(this,null,function*(){if(te instanceof WebAssembly.Module)return WebAssembly.instantiate(te,ee.importObject);let U=yield fetch(te);if(!U.ok)throw new Error(`Failed to download ${JSON.stringify(te)}`);if("instantiateStreaming"in WebAssembly&&/^application\/wasm($|;)/i.test(U.headers.get("Content-Type")||""))return(yield WebAssembly.instantiateStreaming(U,ee.importObject)).instance;let C=yield U.arrayBuffer();return(yield WebAssembly.instantiate(C,ee.importObject)).instance})}return te=>me(te)})(ue=>S.onmessage({data:ue})),he;S={onmessage:null,postMessage:ue=>setTimeout(()=>{try{he=Z({data:ue})}catch(pe){O(pe)}}),terminate(){if(he)for(let ue of he._scheduledTimeouts.values())clearTimeout(ue)}}}let P,V,x=new Promise((Z,he)=>{P=Z,V=he});S.onmessage=({data:Z})=>{S.onmessage=({data:he})=>N(he),Z?V(Z):P()},S.postMessage(m||new URL(h,location.href).toString());let{readFromStdout:N,service:G}=Ea({writeToStdin(Z){S.postMessage(Z)},isSync:!1,hasFS:!1,esbuild:c});yield x,yn=()=>{S.terminate(),ct=void 0,yn=void 0,vn=void 0},vn={build:Z=>new Promise((he,ue)=>{$.then(ue),G.buildOrContext({callName:"build",refs:null,options:Z,isTTY:!1,defaultWD:"/",callback:(pe,me)=>pe?ue(pe):he(me)})}),context:Z=>new Promise((he,ue)=>{$.then(ue),G.buildOrContext({callName:"context",refs:null,options:Z,isTTY:!1,defaultWD:"/",callback:(pe,me)=>pe?ue(pe):he(me)})}),transform:(Z,he)=>new Promise((ue,pe)=>{$.then(pe),G.transform({callName:"transform",refs:null,input:Z,options:he||{},isTTY:!1,fs:{readFile(me,ne){ne(new Error("Internal error"),null)},writeFile(me,ne){ne(null)}},callback:(me,ne)=>me?pe(me):ue(ne)})}),formatMessages:(Z,he)=>new Promise((ue,pe)=>{$.then(pe),G.formatMessages({callName:"formatMessages",refs:null,messages:Z,options:he,callback:(me,ne)=>me?pe(me):ue(ne)})}),analyzeMetafile:(Z,he)=>new Promise((ue,pe)=>{$.then(pe),G.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof Z=="string"?Z:JSON.stringify(Z),options:he,callback:(me,ne)=>me?pe(me):ue(ne)})})}}),Ha=c})(typeof es=="object"?es:{set exports(e){(typeof self<"u"?self:this).esbuild=e}})});import{DEFAULT_OUTPUT as Wd,ManifestAssetCatalog as Vd,Registry as Gd,resolveProjectDocument as zd}from"@motionscript/core";import{AssetManager as xs,AudioSink as so,ClipStore as io,AssetTimeline as ao,isFatalRenderIssue as oo,RenderBackendError as lo,renderIssueKey as co,renderSettled as uo,SETTLE_PASSES as fo,setTheme as ho,toRenderIssue as _o,spansCovering as ks,StateEvaluator as po,yieldToScheduler as mo}from"@motionscript/core";var kn=class extends so{get schedulesAudio(){return!1}has(t){return!0}async append(t,n){}retain(t){}schedule(t){}syncTo(t){}play(t,n,r){}stop(){}};function er(e,t,n){for(let r of e.takeRenderIssues()){let s=_o(r);if(oo(s))throw new lo(s);let i=co(s);t.has(i)||(t.add(i),n?.(s))}}async function Ms({renderContext:e,storageAdapter:t},n,r){await uo(()=>e.execute(n),t,()=>!0)==="exhausted"&&console.warn(`[export] frame ${r} still had pending decodes after ${fo} renders; it may not be exact.`)}function Ss(e){let t=e.getDecodePolicy();return e.setDecodePolicy("exact"),()=>e.setDecodePolicy(t)}function go(e){let{fps:t,viewport:n}=e;if(t===void 0||n===void 0)throw new Error("Rendering takes a project whose fps and viewport are resolved \u2014 see Session.");return{fps:t,viewport:n}}function bo(e,t){if(!e)return{start:0,end:t};let{start:n,end:r}=e;if(!Number.isInteger(n)||!Number.isInteger(r)||n<0||r<=n||r>t)throw new RangeError(`Frames ${n} to ${r} are not a range inside this timeline's ${t} frames.`);return{start:n,end:r}}function As(e){let{project:t,registry:n,assetCatalog:r,renderContext:s}=e,{fps:i,viewport:a}=go(t),o=()=>ho(t.theme??e.theme);o();let l=s,c={registry:n,viewport:a,fps:i,assets:r,measurer:l},u={},f=new io(t,c,{isReady:p=>u.manager?.isReady(p)??!1}),d=new ao(t,c,{store:f}),_=new po(t,c,f);return{store:f,precomper:d,stateEvaluator:_,measurer:l,fps:i,viewport:a,loads:u,applyTheme:o}}async function Es(e,t,n){let r=n.flatMap(s=>e.layoutGates(s).filter(i=>!t.isReady(i.src)));r.length>0&&await t.loadRecords(r),e.settleGates(n)}function tr(e){let t=[];for(let n of e.tracks){let r=n.startFrame/e.fps;for(let s of n.audioRequests)t.push({request:s,globalOffset:r})}return t}async function Sn(e){let{scale:t=1,sink:n,mixer:r,onProgress:s,signal:i,includeAudio:a=!0}=e,o=e,{renderContext:l,storageAdapter:c}=o;if(e.project.tracks.length===0)return;i?.throwIfAborted(),l.pixelRatio=t;let{store:u,precomper:f,stateEvaluator:d,measurer:_,fps:p,viewport:w,loads:R,applyTheme:L}=As(e),F=Ss(c),H=new Set;try{l.takeRenderIssues();let{start:se,end:X}=bo(e.frames,f.result().totalFrames),ye=e.frames?u.spans.filter(ae=>ae.startFrame<X&&ae.endFrame>=se).map(ae=>ae.id):e.project.tracks.map(ae=>ae.id);if(e.frames)for(let ae of ye)u.discover(ae);let ve=e.frames?f.result():f.run(),{totalDuration:q}=ve,oe=X-se;Ps(u,ve,se,X-1);let K=R.manager=new xs(ve,c,new kn);await Es(u,K,ye);let B=tr(ve),xe=a&&!e.frames&&B.length>0&&r!==void 0;await n.start({width:w.width*t,height:w.height*t,fps:p,totalFrames:oe,hasAudio:xe});let we=1/p,Te=0;c.setPlaying(!0);try{for(let ae=se;ae<X;ae++){i?.throwIfAborted(),await K.loadAt(ae),L(),d.stateAt(ae),d.layout(_),await Ms(o,()=>d.render(l),ae),er(l,H,e.onIssue),await n.addFrame(Te,we),Te+=we;let Ae=ae-se+1;s?.(Ae/oe*(xe?.85:1)),(ae+1)%4===0&&await mo()}}finally{c.setPlaying(!1)}if(xe){let ae=await r.mix(B,q);ae!==null&&n.addAudio&&await n.addAudio(ae),s?.(.97)}er(l,H,e.onIssue);let Ue=await n.finalize();return s?.(1),Ue}finally{F(),d.dispose(),u.dispose()}}var Mn=class extends Error{frame;failures;name="NothingToDrawError";constructor(t,n){let r=n.map(s=>` ${s.trackId}: ${s.message}`).join(`
696
+ `);super(`Frame ${t} has nothing to draw \u2014 every track on it failed to build:
697
+ ${r}`),this.frame=t,this.failures=n}};async function Ts(e){let{scale:t=1,frame:n,project:r}=e,s=e,{renderContext:i,storageAdapter:a}=s;if(r.tracks.length===0)throw new Error("The project has no tracks to render.");i.pixelRatio=t;let{store:o,precomper:l,stateEvaluator:c,measurer:u,loads:f}=As(e),d=Ss(a);try{let{totalFrames:_}=l.result(),p=n.kind==="first"?0:n.kind==="last"?_-1:n.frame,w=Math.max(0,Math.min(_-1,Math.floor(p))),R=l.ensureCovering(w);Ps(o,R,w);let L=f.manager=new xs(R,a,new kn);return await Es(o,L,ks(o.spans,w).map(F=>F.id)),await L.loadAt(w),c.stateAt(w),c.layout(u),i.takeRenderIssues(),await Ms(s,()=>c.render(i),w),er(i,new Set,e.onIssue),{frame:w,totalFrames:_}}finally{d(),c.dispose(),o.dispose()}}function Ps(e,t,n,r=n){let s=new Map(t.buildErrors.filter(i=>e.failed(i.trackId)).map(i=>[i.trackId,i]));if(s.size!==0)for(let i=n;i<=r;i++){let a=ks(e.spans,i);if(a.length>0&&a.every(o=>s.has(o.id)))throw new Mn(i,a.map(o=>s.get(o.id)))}}import{CanvasRenderContext2D as wo,Effects as A,StorageAdapter as yo,WGSL_CONTRACT as Is,alignmentOps as vo,cornerRadiusOps as Rs,cornerStyleOps as xo,cylinderRadii as ko,describeEffect as Mo,evaluateParametric as So,evaluateRoundedBox as Ao,fillOps as Eo,forEachTexture3D as To,isStrokeMarker as Dt,isSurfaceTexture3D as Po,isWgslShader as ki,normalizeUniforms as Mi,parseColor as Si,pathOps as Ai,renderIssueKey as Io,resolveAsciiCharset as Ro,resolveCameraPlacement as Co,resolveEffectAxis as vt,resolveEffectColor as xt,resolveMotionBlurAlignment as Oo,resolvePivotPosition as $o,resolveShadowOptions3D as Do,resolveShapeAlignment as Lo,resolveShapePivot as Fo,resolveSurfaceSource as Bo,resolveTexture3D as Ei,resolveVideoTimestamp as Uo,segmentsOf as Cs,shaderContractOf as jo,shadowOps as No,stripShapeAlignmentKeys as Wo,strokeOps as Vo,toPathString as Ti,withEllipseDescriptor as Go,withLineDescriptor as zo,withPathDescriptor as Ho,withPolygonDescriptor as Ko,withPolygramDescriptor as qo,withRectDescriptor as Jo,withRichTextDescriptor as Yo,withTextDescriptor as Pi}from"@motionscript/core";var Os=Object.defineProperty,le=(e,t)=>{let n={};for(var r in e)Os(n,r,{get:e[r],enumerable:!0});return t||Os(n,Symbol.toStringTag,{value:"Module"}),n},Xo=1379091505;function gt(e){if(e===void 0)return{x:0,y:0,z:0};if(typeof e=="number")return{x:e,y:e,z:e};if(Array.isArray(e))return{x:e[0]??0,y:e[1]??0,z:e[2]??0};let t=e;return{x:t.x??0,y:t.y??0,z:t.z??0}}var Zo={XYZ:0,YXZ:1,ZXY:2,ZYX:3,YZX:4,XZY:5},Qo={none:0,linear:1,reinhard:2,cineon:3,aces:4,agx:5,neutral:6},De={box:0,sphere:1,plane:2,cylinder:3,cone:4,torus:5,torusKnot:6,circle:7,ring:8,buffer:9,capsule:10,polyhedron:11,lathe:12,tube:13,edges:14,wireframe:15},el={tetrahedron:0,octahedron:1,icosahedron:2,dodecahedron:3},tl={basic:0,standard:1,physical:2,lambert:3,phong:4,normal:5,points:6,lineBasic:7,lineDashed:8,sprite:9,shadow:10,toon:11,matcap:12,depth:13,shader:14},nl={ambient:0,hemisphere:1,directional:2,point:3,spot:4,area:5},rl={front:0,back:1,both:2},sl={normal:0,additive:1,subtractive:2,multiply:3,none:4},il=["map","gradientMap","alphaMap","aoMap","normalMap","roughnessMap","metalnessMap","emissionMap","envMap","lightMap","displacementMap"],al=class{byKey=new Map;next=1;pending=[];all=new Map;id(e,t){let n=Ei(e),r="src"in n?n.src:n,s=this.byKey.get(r);s||this.byKey.set(r,s=new Map);let i=s.get(t);if(i===void 0){i=this.next++,s.set(t,i);let a={id:i,srgb:t,texture:n};this.pending.push(a),this.all.set(i,a)}return i}},Ii=class{buf=new ArrayBuffer(65536);u32=new Uint32Array(this.buf);f32=new Float32Array(this.buf);n=0;room(e){if(this.n+e<=this.u32.length)return;let t=this.buf.byteLength*2;for(;t/4<this.n+e;)t*=2;let n=new ArrayBuffer(t);new Uint32Array(n).set(this.u32.subarray(0,this.n)),this.buf=n,this.u32=new Uint32Array(n),this.f32=new Float32Array(n)}u(e){this.room(1),this.u32[this.n++]=e>>>0}f(e){this.room(1),this.f32[this.n++]=e===void 0?NaN:e}v3(e){this.f(e.x),this.f(e.y),this.f(e.z)}floats(e){this.room(e.length);for(let t=0;t<e.length;t++)this.f32[this.n++]=e[t]}words(e){this.room(e.length);for(let t=0;t<e.length;t++)this.u32[this.n++]=e[t]>>>0}color(e){if(e===void 0){this.u(0),this.f(0),this.f(0),this.f(0),this.f(0);return}let[t,n,r,s]=typeof e=="string"?Si(e):e;this.u(1),this.f(t),this.f(n),this.f(r),this.f(s??1)}segments(e){if(e===void 0){this.u(0),this.f(NaN),this.f(NaN),this.f(NaN);return}if(typeof e=="number"){this.u(1),this.f(e),this.f(NaN),this.f(NaN);return}this.u(2),this.f(e[0]),this.f(e[1]),this.f(e[2])}result(){return this.u32.slice(0,this.n)}key(e){return Array.prototype.join.call(this.u32.subarray(e,this.n),",")}copy(e){return this.u32.slice(e,this.n)}same(e,t){if(this.n-e!==t.length)return!1;let n=this.u32;for(let r=0;r<t.length;r++)if(n[e+r]!==t[r])return!1;return!0}set(e,t){this.u32[e]=t>>>0}append(e){this.room(e.n),this.u32.set(e.u32.subarray(0,e.n),this.n),this.n+=e.n}};function ze(e,t){if(!t){e.u(0);return}let n=0;if(t.position!==void 0&&(n|=1),t.rotation!==void 0&&(n|=2),t.quaternion!==void 0&&(n|=4),t.scale!==void 0&&(n|=8),t.lookAt!==void 0&&(n|=16),t.visible===!1&&(n|=32),t.shadow!==void 0&&(n|=64),t.renderOrder!==void 0&&(n|=128),e.u(n),n&1&&e.v3(gt(t.position)),n&2&&(e.v3(gt(t.rotation)),e.u(Zo[t.rotation.order??"XYZ"]??0)),n&4){let r=t.quaternion;e.f(r.x),e.f(r.y),e.f(r.z),e.f(r.w)}if(n&8&&e.v3(gt(t.scale)),n&16&&e.v3(gt(t.lookAt)),n&64){let r=t.shadow;e.u(r===!1?0:r===!0?1:r==="cast"?2:r==="receive"?3:4)}n&128&&e.f(t.renderOrder)}function nr(e,t){let n=Math.floor(t.position.length/3),r=(t.normal?1:0)|(t.uv?2:0)|(t.color?4:0)|(t.index?8:0)|(t.computeNormals?16:0);e.u(De.buffer),e.u(r),e.u(n),e.u(t.index?.length??0),e.floats(t.position),t.normal&&e.floats(t.normal),t.uv&&e.floats(t.uv),t.color&&e.floats(t.color),t.index&&e.words(t.index)}function on(e,t,n){switch(t.type){case"box":if((t.cornerRadius??0)>0){let[r,s,i]=Cs(t.segments,[1,1,1]);nr(e,Ao({width:t.width??1,height:t.height??1,depth:t.depth??1,radius:t.cornerRadius,segments:[r,s,i]}));return}e.u(De.box),e.f(t.width),e.f(t.height),e.f(t.depth),e.segments(t.segments);return;case"sphere":e.u(De.sphere),e.f(t.radius),e.segments(t.segments),e.f(t.startAngle),e.f(t.sweep),e.f(t.startLatitude),e.f(t.latitudeSweep);return;case"plane":e.u(De.plane),e.f(t.width),e.f(t.height),e.segments(t.segments);return;case"cylinder":{let[r,s]=ko(t.radius);e.u(De.cylinder),e.f(r),e.f(s),e.f(t.height),e.segments(t.segments),e.u(t.capped===!1?0:1),e.f(t.startAngle),e.f(t.sweep);return}case"cone":e.u(De.cone),e.f(t.radius),e.f(t.height),e.segments(t.segments),e.u(t.capped===!1?0:1),e.f(t.startAngle),e.f(t.sweep);return;case"torus":e.u(De.torus),e.f(t.radius),e.f(t.thickness),e.segments(t.segments),e.f(t.startAngle),e.f(t.sweep);return;case"torusKnot":e.u(De.torusKnot),e.f(t.radius),e.f(t.thickness),e.segments(t.segments),e.f(t.windings?.[0]),e.f(t.windings?.[1]);return;case"circle":e.u(De.circle),e.f(t.radius),e.segments(t.segments),e.f(t.startAngle),e.f(t.sweep);return;case"ring":e.u(De.ring),e.f(t.radius),e.f(t.innerRadius),e.segments(t.segments),e.f(t.startAngle),e.f(t.sweep);return;case"buffer":nr(e,t);return;case"parametric":nr(e,So(t));return;case"capsule":e.u(De.capsule),e.f(t.radius),e.f(t.height),e.segments(t.segments);return;case"polyhedron":e.u(De.polyhedron),e.u(el[t.shape??"icosahedron"]??2),e.f(t.radius),e.f(t.segments===void 0?0:Cs(t.segments,[1])[0]);return;case"lathe":e.u(De.lathe),e.u(t.points.length);for(let r of t.points){let s=gt(r);e.f(s.x),e.f(s.y)}e.segments(t.segments),e.f(t.startAngle),e.f(t.sweep);return;case"tube":e.u(De.tube),e.u(t.points.length);for(let r of t.points)e.v3(gt(r));e.u(t.closed?1:0),e.f(t.radius),e.segments(t.segments);return;case"edges":e.u(De.edges),e.f(t.thresholdAngle),on(e,t.source,n);return;case"wireframe":e.u(De.wireframe),on(e,t.source,n);return;default:n.unsupported.add(`geometry:${t.type}`),e.u(255)}}function Ri(e){switch(e.type){case"buffer":case"parametric":return"slot";case"box":return(e.cornerRadius??0)>0?"rounded":"fixed";case"edges":case"wireframe":return Ri(e.source)==="fixed"?"fixed":"slot";default:return"fixed"}}function Ci(e){let t=e,n=e.type;for(let r of Object.keys(t).sort()){let s=t[r];r==="type"||r==="revision"||r==="staticData"||s===void 0||typeof s=="function"||(r==="source"?n+=`|source=${Ci(s)}`:ArrayBuffer.isView(s)||Array.isArray(s)&&s.length>3?n+=`|${r}#${s.length}`:n+=`|${r}=${typeof s=="object"?JSON.stringify(s):String(s)}`)}return n}function ol(e){return e.type!=="buffer"?[]:[e.position,e.normal,e.uv,e.color,e.index,e.computeNormals]}var ll=class{next=1;byKey=new Map;slots=new Map;live=new Set;nth=new Map;defs=new Ii;count=0;begin(){this.live.clear(),this.nth.clear(),this.defs.n=0,this.count=0}end(e){e.u(this.count),e.append(this.defs);for(let[t,n]of this.byKey)this.live.has(n)||this.byKey.delete(t);for(let[t,n]of this.slots)this.live.has(n.id)||this.slots.delete(t)}ref(e,t,n,r){let s=this.defs,i=Ri(e);if(i!=="slot"){let p;if(i==="rounded"){let F=e;p=`rounded|${F.width}|${F.height}|${F.depth}|${F.cornerRadius}|${JSON.stringify(F.segments)}`;let H=this.byKey.get(p);if(H!==void 0)return this.use(H)}let w=s.n;s.u(0),on(s,e,r),p??=s.key(w+1);let R=this.byKey.get(p);if(R!==void 0)return s.n=w,this.use(R);let L=this.add(w);return this.byKey.set(p,L),L}let a=`${t}|${n}|${Ci(e)}`,o=this.nth.get(a)??0;this.nth.set(a,o+1);let l=`${a}|${o}`,c=this.slots.get(l),u=e.revision,f=ol(e);if(c&&c.revision===u){if(e.type==="parametric"&&u!==void 0)return this.use(c.id);if(e.type==="buffer"&&(u!==void 0||e.staticData===!0)&&f.every((p,w)=>p===c.arrays[w]))return this.use(c.id)}let d=s.n;if(s.u(0),on(s,e,r),c&&s.same(d+1,c.words))return s.n=d,c.revision=u,c.arrays=f,this.use(c.id);let _=this.add(d);return this.slots.set(l,{id:_,revision:u,arrays:f,words:s.copy(d+1)}),_}use(e){return this.live.add(e),e}add(e){let t=this.next++;return this.defs.set(e,t),this.count++,this.use(t)}},$s={clamp:0,repeat:1,mirror:2};function rr(e,t){if(e===void 0)return[t,t];if(Array.isArray(e))return[e[0]??t,e[1]??t];let n=e;return[n.x??t,n.y??t]}function Ds(e,t,n,r){if(t===void 0||!n){t!==void 0&&r.unsupported.add("texture:map"),e.u(0),e.u(0),e.f(1),e.f(0),e.f(0),e.f(0),e.f(1),e.f(0),e.u(0);return}let s=Ei(t),i=s.colorSpace!=="linear";e.u(1),e.u(n.id(t,i));let[a,o]=rr(s.offset,0),[l,c]=rr(s.repeat,1),[u,f]=rr(s.center,0),d=(s.rotation??0)*Math.PI/180,_=Math.cos(d),p=Math.sin(d);e.f(l*_),e.f(l*p),e.f(-l*(_*u+p*f)+u+a),e.f(-c*p),e.f(c*_),e.f(-c*(-p*u+_*f)+f+o);let w=s.flipY??!("data"in s);e.u(($s[s.wrapS??"clamp"]??0)|($s[s.wrapT??"clamp"]??0)<<2|(w?16:0)|(s.magFilter==="nearest"?32:0)|(s.minFilter==="nearest"?64:0))}function Ht(e,t,n,r){let s=t;e.u(tl[t.type]??1),["basic","standard","physical","lambert","phong","normal","lineBasic","lineDashed","sprite","shadow","points","toon","depth"].includes(t.type)||n.unsupported.add(`material:${t.type}`);for(let a of il)a!=="map"&&a!=="gradientMap"&&s[a]!==void 0&&n.unsupported.add(`texture:${a}`);s.gradientMap!==void 0&&t.type!=="toon"&&n.unsupported.add("texture:gradientMap");for(let a of["sheen","iridescence","anisotropy","dispersion"])typeof s[a]=="number"&&s[a]>0&&n.unsupported.add(`physical:${a}`);e.color(s.color),e.f(s.opacity),e.f(s.roughness),e.f(s.metalness),e.color(s.emission),e.f(s.emissionStrength),e.f(s.envMapIntensity);let i=0;s.transparent===!0&&(i|=1),s.wireframe===!0&&(i|=4),s.vertexColors===!0&&(i|=8),s.shading==="flat"&&(i|=16),s.toneMapped===!1&&(i|=32),s.visible===!1&&(i|=64),s.depthTest===!1&&(i|=128),s.depthWrite!==void 0&&(i|=256|(s.depthWrite?512:0)),s.sizeAttenuation===!1&&(i|=1024),e.u(i),e.u(rl[s.faces??"front"]??0),e.u(sl[s.blend??"normal"]??0),e.f(s.alphaTest),e.f(s.size),e.color(s.specular),e.f(s.shininess),Ds(e,s.map,r,n),e.f(s.clearcoat),e.f(s.clearcoatRoughness),e.f(s.transmission),e.f(s.thickness),e.f(s.ior),e.f(s.attenuationDistance),e.color(s.attenuationColor),e.f(s.dashSize),e.f(s.gapSize),e.f(s.scale),Ds(e,t.type==="toon"?s.gradientMap:void 0,r,n)}function cl(e,t,n){let r=t;e.u(nl[t.type]??0),e.color(r.color),e.f(t.intensity),e.color(r.sky),e.color(r.ground),e.f(r.distance),e.f(r.decay),e.f(r.angle),e.f(r.penumbra);let s=r.target;e.u(s===void 0?0:1),e.v3(gt(s));let i=r.shadow,a=i===void 0?null:Do(i);e.u(a?1:0),e.f(a?.softness),e.f(a?.extent),e.f(r.width),e.f(r.height),ze(e,n)}function ul(e,t){e.u(t.type==="orthographic"?1:0);let n=Co(t);ze(e,{...t,position:n.position,lookAt:n.lookAt}),e.f(t.type==="perspective"?t.fov:void 0),e.f(t.zoom),e.f(t.type==="orthographic"?t.frustumHeight:void 0),e.f(t.near),e.f(t.far),e.f(t.distance)}function fl(e,t={unsupported:new Set},n,r){let s=new Ii;r?.begin();let i=[""],a=(d,_)=>{if(!r)return on(s,d,t);s.u(16),s.u(r.ref(d,i[i.length-1],_,t))};s.u(Xo),s.u(3);let o=e.toneSettings();s.u(Qo[o?.mapping??"aces"]??4),s.f(o?.exposure);let l=e.shadowSettings();s.u(l?.enabled===!0?1:0),s.u(l?.quality==="low"?0:l?.quality==="high"?2:1);let c=e.fogDescriptor();s.u(c?c.density!==void 0?2:1:0),s.color(c?.color),s.f(c?.near),s.f(c?.far),s.f(c?.density);let u=e.environmentDescriptor();s.u(u?.preset==="studio"?1:0),s.f(u?.intensity),s.u(u?.background?1:0),s.f(u?.blur),e.postEffects().length>0&&t.unsupported.add("post");let f=e.ops();s.u(f.length);for(let d of f)switch(d.kind){case"push":{let _=d.transform?.key;i.push(_===void 0?`${i[i.length-1]}/${i.length}`:String(_)),s.u(1),ze(s,d.transform);break}case"pop":i.length>1&&i.pop(),s.u(2);break;case"light":s.u(3),cl(s,d.light,d.transform);break;case"camera":s.u(4),ul(s,d.camera);break;case"mesh":{s.u(5),a(d.geometry,d.kind);let _=Array.isArray(d.material)?d.material:[d.material];s.u(Array.isArray(d.material)?_.length:1);for(let p of _)Ht(s,p,t,n);ze(s,d.transform);break}case"instances":{s.u(6),a(d.geometry,d.kind),Ht(s,d.material,t,n),ze(s,d.transform),s.u(d.instances.length);for(let p of d.instances)ze(s,p);let _=d.colors??[];s.u(_.length);for(let p of _){let[w,R,L,F]=typeof p=="string"?Si(p):p;s.f(w),s.f(R),s.f(L),s.f(F??1)}break}case"points":s.u(7),a(d.geometry,d.kind),Ht(s,d.material,t,n),ze(s,d.transform);break;case"line":s.u(8),a(d.geometry,d.kind),Ht(s,d.material,t,n),s.u(d.mode==="segments"?1:d.mode==="loop"?2:0),ze(s,d.transform);break;case"sprite":s.u(9),Ht(s,d.material,t,n),ze(s,d.transform);break;case"model":t.unsupported.add("model"),s.u(10),ze(s,d.transform);break}return r?r.end(s):s.u(0),s.result()}var Pr=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,js.unregister(this),e}free(){let e=this.__destroy_into_raw();y.__wbg_mstext_free(e,0)}glyph_path(e,t,n,r){let s=y.mstext_glyph_path(this.__wbg_ptr,e,t,n,r);var i=mt(s[0],s[1]).slice();return y.__wbindgen_free(s[0],s[1]*4,4),i}layout(e,t,n,r,s,i,a){let o=+r,l=+s,c=+i,u=+a,f,d,_,p,w,R;try{f=Oe(e,y.__wbindgen_malloc,y.__wbindgen_realloc),d=be,_=An(t,y.__wbindgen_malloc),p=be,w=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),R=be}catch(H){throw w&&y.__wbindgen_free(w,R*1,1),_&&y.__wbindgen_free(_,p*4,4),f&&y.__wbindgen_free(f,d*1,1),H}let L=y.mstext_layout(this.__wbg_ptr,f,d,_,p,w,R,o,l,c,u);var F=mt(L[0],L[1]).slice();return y.__wbindgen_free(L[0],L[1]*4,4),F}measure_text(e,t,n,r,s,i){let a=+t,o=+r,l=+s,c=+i,u,f,d,_;try{u=Oe(e,y.__wbindgen_malloc,y.__wbindgen_realloc),f=be,d=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),_=be}catch(R){throw d&&y.__wbindgen_free(d,_*1,1),u&&y.__wbindgen_free(u,f*1,1),R}let p=y.mstext_measure_text(this.__wbg_ptr,u,f,a,d,_,o,l,c);var w=mt(p[0],p[1]).slice();return y.__wbindgen_free(p[0],p[1]*4,4),w}constructor(){let e=y.mstext_new();return this.__wbg_ptr=e,js.register(this,this.__wbg_ptr,this),this}register_font(e,t){let n,r,s,i;try{n=Rr(e,y.__wbindgen_malloc),r=be,s=Oe(t,y.__wbindgen_malloc,y.__wbindgen_realloc),i=be}catch(a){throw s&&y.__wbindgen_free(s,i*1,1),n&&y.__wbindgen_free(n,r*1,1),a}return y.mstext_register_font(this.__wbg_ptr,n,r,s,i)}set_default_fallbacks(e){let t=Ir(e,y.__wbindgen_malloc),n=be;y.mstext_set_default_fallbacks(this.__wbg_ptr,t,n)}set_family_fallbacks(e,t){let n,r,s,i;try{n=Oe(e,y.__wbindgen_malloc,y.__wbindgen_realloc),r=be,s=Ir(t,y.__wbindgen_malloc),i=be}catch(a){throw s&&y.__wbindgen_free(s,i*4,4),n&&y.__wbindgen_free(n,r*1,1),a}y.mstext_set_family_fallbacks(this.__wbg_ptr,n,r,s,i)}text_block(e,t,n,r,s,i,a,o,l,c,u){let f=+r,d=+s,_=+i,p=+a,w=+o,R=+l,L=+c,F=+u,H,se,X,ye,ve,q;try{H=Oe(e,y.__wbindgen_malloc,y.__wbindgen_realloc),se=be,X=An(t,y.__wbindgen_malloc),ye=be,ve=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),q=be}catch(B){throw ve&&y.__wbindgen_free(ve,q*1,1),X&&y.__wbindgen_free(X,ye*4,4),H&&y.__wbindgen_free(H,se*1,1),B}let oe=y.mstext_text_block(this.__wbg_ptr,H,se,X,ye,ve,q,f,d,_,p,w,R,L,F);var K=mt(oe[0],oe[1]).slice();return y.__wbindgen_free(oe[0],oe[1]*4,4),K}text_on_path(e,t,n,r,s,i){let a=+r,o=+s,l,c,u,f,d,_,p,w;try{l=Oe(e,y.__wbindgen_malloc,y.__wbindgen_realloc),c=be,u=An(t,y.__wbindgen_malloc),f=be,d=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),_=be,p=An(i,y.__wbindgen_malloc),w=be}catch(F){throw p&&y.__wbindgen_free(p,w*4,4),d&&y.__wbindgen_free(d,_*1,1),u&&y.__wbindgen_free(u,f*4,4),l&&y.__wbindgen_free(l,c*1,1),F}let R=y.mstext_text_on_path(this.__wbg_ptr,l,c,u,f,d,_,a,o,p,w);var L=mt(R[0],R[1]).slice();return y.__wbindgen_free(R[0],R[1]*4,4),L}};Symbol.dispose&&(Pr.prototype[Symbol.dispose]=Pr.prototype.free);var Lt=class Oi{static __wrap(t){let n=Object.create(Oi.prototype);return n.__wbg_ptr=t,Ns.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Ns.unregister(this),t}free(){let t=this.__destroy_into_raw();y.__wbg_renderer_free(t,0)}adapter_info(){let t,n;try{let r=y.renderer_adapter_info(this.__wbg_ptr);return t=r[0],n=r[1],Se(r[0],r[1])}finally{y.__wbindgen_free(t,n,1)}}apply(t){let n=y.renderer_apply(this.__wbg_ptr,t);if(n[1])throw nt(n[0])}static create(t,n,r){return y.renderer_create(t,n,r)}delta_buffer(t){return y.renderer_delta_buffer(this.__wbg_ptr,t)>>>0}delta_capacity(){return y.renderer_delta_capacity(this.__wbg_ptr)>>>0}effect_names(){let t=y.renderer_effect_names(this.__wbg_ptr);var n=fr(t[0],t[1]);return y.__wbindgen_free(t[0],t[1]*4,4),n}static forget_device(){y.renderer_forget_device()}free_image(t){y.renderer_free_image(this.__wbg_ptr,t)}gpu_device(){return y.renderer_gpu_device(this.__wbg_ptr)}invalidate(){y.renderer_invalidate(this.__wbg_ptr)}measure_text(t,n,r,s,i,a){let o=+n,l=+s,c=+i,u=+a,f,d,_,p;try{f=Oe(t,y.__wbindgen_malloc,y.__wbindgen_realloc),d=be,_=Oe(r,y.__wbindgen_malloc,y.__wbindgen_realloc),p=be}catch(L){throw _&&y.__wbindgen_free(_,p*1,1),f&&y.__wbindgen_free(f,d*1,1),L}let w=y.renderer_measure_text(this.__wbg_ptr,f,d,o,_,p,l,c,u);var R=mt(w[0],w[1]).slice();return y.__wbindgen_free(w[0],w[1]*4,4),R}static prewarm(){return y.renderer_prewarm()}read_pixels(){return y.renderer_read_pixels(this.__wbg_ptr)}register_font(t,n){let r,s,i,a;try{r=Rr(t,y.__wbindgen_malloc),s=be,i=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),a=be}catch(o){throw i&&y.__wbindgen_free(i,a*1,1),r&&y.__wbindgen_free(r,s*1,1),o}return y.renderer_register_font(this.__wbg_ptr,r,s,i,a)}render(){let t=y.renderer_render(this.__wbg_ptr);if(t[1])throw nt(t[0])}resize(t,n){y.renderer_resize(this.__wbg_ptr,t,n)}scene3d_bind(t,n,r,s){y.renderer_scene3d_bind(this.__wbg_ptr,t,n,r,s)}scene3d_pixels(t,n,r,s,i,a){let o=+t,l=+n,c=+s,u=+i,f=+a,d=Rr(r,y.__wbindgen_malloc),_=be;y.renderer_scene3d_pixels(this.__wbg_ptr,o,l,d,_,c,u,f)}scene3d_skipped(t){let n=y.renderer_scene3d_skipped(this.__wbg_ptr,t);var r=fr(n[0],n[1]);return y.__wbindgen_free(n[0],n[1]*4,4),r}set_options(t,n){y.renderer_set_options(this.__wbg_ptr,t,n)}set_scene3d(t,n,r,s){let i=+t,a=+n,o=+r,l=Ir(s,y.__wbindgen_malloc),c=be,u=y.renderer_set_scene3d(this.__wbg_ptr,i,a,o,l,c);if(u[1])throw nt(u[0])}set_surface(t,n,r,s){y.renderer_set_surface(this.__wbg_ptr,t,n,r,s)}shader_add(t,n,r){let s,i;try{let a=+t,o=+n,l=Oe(r,y.__wbindgen_malloc,y.__wbindgen_realloc),c=be,u=y.renderer_shader_add(this.__wbg_ptr,a,o,l,c);return s=u[0],i=u[1],Se(u[0],u[1])}finally{y.__wbindgen_free(s,i,1)}}shader_build(t){y.renderer_shader_build(this.__wbg_ptr,t)}shader_formats(t){let n=y.renderer_shader_formats(this.__wbg_ptr,t);var r=fr(n[0],n[1]);return y.__wbindgen_free(n[0],n[1]*4,4),r}shader_remove(t){y.renderer_shader_remove(this.__wbg_ptr,t)}stats(){let t=y.renderer_stats(this.__wbg_ptr);var n=Fl(t[0],t[1]).slice();return y.__wbindgen_free(t[0],t[1]*8,8),n}text_block_layout(t){let n=y.renderer_text_block_layout(this.__wbg_ptr,t);var r=mt(n[0],n[1]).slice();return y.__wbindgen_free(n[0],n[1]*4,4),r}upload_image(t,n,r){let s=y.renderer_upload_image(this.__wbg_ptr,t,n,r);if(s[1])throw nt(s[0])}wait_gpu(){return y.renderer_wait_gpu(this.__wbg_ptr)}};Symbol.dispose&&(Lt.prototype[Symbol.dispose]=Lt.prototype.free);function dl(e){y.set_panic_listener(Xe(e)?0:He(e))}function hl(e,t){let n,r;try{let s=+e,i=Oe(t,y.__wbindgen_malloc,y.__wbindgen_realloc),a=be,o=y.validate_shader(s,i,a);return n=o[0],r=o[1],Se(o[0],o[1])}finally{y.__wbindgen_free(n,r,1)}}function _l(){return{__proto__:null,"./ms_renderer_bg.js":{__proto__:null,__wbg_Error_208446807d0d1e30:function(e,t){return Error(Se(e,t))},__wbg_Window_2805651c516cb7aa:function(e){return e.Window},__wbg_WorkerGlobalScope_174390815d0a4893:function(e){return e.WorkerGlobalScope},__wbg___wbindgen_debug_string_f249a2a76caa9a55:function(e,t){let n=Oe($i(t),y.__wbindgen_malloc,y.__wbindgen_realloc),r=be;We().setInt32((e>>>0)+4,r,!0),We().setInt32((e>>>0)+0,n,!0)},__wbg___wbindgen_is_function_741ff2bb612836f5:function(e){return typeof e=="function"},__wbg___wbindgen_is_null_c22311b1cc228e3a:function(e){return e===null},__wbg___wbindgen_is_string_fc456fee5d3317de:function(e){return typeof e=="string"},__wbg___wbindgen_is_undefined_be5b34249ff1fc15:function(e){return e===void 0},__wbg___wbindgen_throw_4c88d8bf264fd984:function(e,t){throw new Error(Se(e,t))},__wbg__wbg_cb_unref_09736879a3f67559:function(e){e._wbg_cb_unref()},__wbg_beginRenderPass_597e3973321fd369:function(){return Re(function(e,t){return e.beginRenderPass(t)},arguments)},__wbg_call_40b008ba32f73991:function(){return Re(function(e,t){return e.call(t)},arguments)},__wbg_call_a410eb4b59ed5965:function(){return Re(function(e,t,n){return e.call(t,n)},arguments)},__wbg_clearBuffer_3d5a3057c3c8a9bf:function(e,t,n,r){e.clearBuffer(t,n,r)},__wbg_clearBuffer_82ba999c294f42fb:function(e,t,n){e.clearBuffer(t,n)},__wbg_configure_8e04ab1a867d31e1:function(){return Re(function(e,t){e.configure(t)},arguments)},__wbg_copyExternalImageToTexture_9d1383f644366eae:function(){return Re(function(e,t,n,r){e.copyExternalImageToTexture(t,n,r)},arguments)},__wbg_copyTextureToBuffer_2a1eda98bb347f8c:function(){return Re(function(e,t,n,r){e.copyTextureToBuffer(t,n,r)},arguments)},__wbg_createBindGroupLayout_5699617270d84042:function(){return Re(function(e,t){return e.createBindGroupLayout(t)},arguments)},__wbg_createBindGroup_f539b26ca341308f:function(e,t){return e.createBindGroup(t)},__wbg_createBuffer_b8c5b520d2c822b8:function(){return Re(function(e,t){return e.createBuffer(t)},arguments)},__wbg_createCommandEncoder_3352d1ffc36c6fc0:function(e,t){return e.createCommandEncoder(t)},__wbg_createPipelineLayout_6eab52c327118937:function(e,t){return e.createPipelineLayout(t)},__wbg_createRenderPipeline_58390ba302107691:function(){return Re(function(e,t){return e.createRenderPipeline(t)},arguments)},__wbg_createSampler_9bd91d7e928c0060:function(e,t){return e.createSampler(t)},__wbg_createShaderModule_cefa51336cb288ae:function(e,t){return e.createShaderModule(t)},__wbg_createTexture_2c95e64f50008aea:function(){return Re(function(e,t){return e.createTexture(t)},arguments)},__wbg_createView_96e5e405cc3c01e8:function(){return Re(function(e,t){return e.createView(t)},arguments)},__wbg_description_7a568e202a00293f:function(e,t){let n=t.description,r=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),s=be;We().setInt32((e>>>0)+4,s,!0),We().setInt32((e>>>0)+0,r,!0)},__wbg_destroy_249478e98a7943d5:function(e){e.destroy()},__wbg_destroy_637537007d9eaa44:function(e){e.destroy()},__wbg_displayHeight_fb2700c23cca6739:function(e){return e.displayHeight},__wbg_displayWidth_9e9d6031a3036613:function(e){return e.displayWidth},__wbg_document_3b5c3071b43e97ee:function(e){let t=e.document;return Xe(t)?0:He(t)},__wbg_drawIndexed_638959aae942557c:function(e,t,n,r,s,i){e.drawIndexed(t>>>0,n>>>0,r>>>0,s,i>>>0)},__wbg_draw_086a9578fc9898c2:function(e,t,n,r,s){e.draw(t>>>0,n>>>0,r>>>0,s>>>0)},__wbg_end_b57473834b877409:function(e){e.end()},__wbg_error_757e9472f8410341:function(e,t){let n,r;try{n=e,r=t,console.error(Se(e,t))}finally{y.__wbindgen_free(n,r,1)}},__wbg_finish_09ec094c10f41e7b:function(e){return e.finish()},__wbg_finish_ec1c191f66a895b1:function(e,t){return e.finish(t)},__wbg_getContext_1938edb9a972f63d:function(){return Re(function(e,t,n){let r=e.getContext(Se(t,n));return Xe(r)?0:He(r)},arguments)},__wbg_getContext_d93f904b714852ae:function(){return Re(function(e,t,n){let r=e.getContext(Se(t,n));return Xe(r)?0:He(r)},arguments)},__wbg_getCurrentTexture_c3b1727224d7f6e6:function(){return Re(function(e){return e.getCurrentTexture()},arguments)},__wbg_getMappedRange_28e816a763520e01:function(){return Re(function(e,t,n){return e.getMappedRange(t,n)},arguments)},__wbg_getPreferredCanvasFormat_0ef5034c8902201b:function(e){let t=e.getPreferredCanvasFormat();return(ut.indexOf(t)+1||102)-1},__wbg_get_0c55869fe53c7d14:function(e,t){let n=e[t>>>0];return Xe(n)?0:He(n)},__wbg_gpu_514705c6dd1f0dab:function(e){return e.gpu},__wbg_height_a587c99454238459:function(e){return e.height},__wbg_height_a6466ebf29036658:function(e){return e.height},__wbg_height_ac6f1c3f49c13fe2:function(e){return e.height},__wbg_info_8554cb7af37427b6:function(e){return e.info},__wbg_instanceof_HtmlCanvasElement_89f280683e987b9e:function(e){let t;try{t=e instanceof HTMLCanvasElement}catch{t=!1}return t},__wbg_instanceof_HtmlImageElement_f22acd64d72ae23a:function(e){let t;try{t=e instanceof HTMLImageElement}catch{t=!1}return t},__wbg_instanceof_HtmlVideoElement_64f13b58baf30810:function(e){let t;try{t=e instanceof HTMLVideoElement}catch{t=!1}return t},__wbg_instanceof_ImageBitmap_536fdba57df2c6ac:function(e){let t;try{t=e instanceof ImageBitmap}catch{t=!1}return t},__wbg_instanceof_OffscreenCanvas_fcf6ec01367f54ec:function(e){let t;try{t=e instanceof OffscreenCanvas}catch{t=!1}return t},__wbg_instanceof_VideoFrame_cd5d3aac6098cfc2:function(e){let t;try{t=e instanceof VideoFrame}catch{t=!1}return t},__wbg_instanceof_Window_5cf453f5639aa1a2:function(e){let t;try{t=e instanceof Window}catch{t=!1}return t},__wbg_isFallbackAdapter_6a4fa7356d18310b:function(e){return e.isFallbackAdapter},__wbg_label_fceb40a43a358e62:function(e,t){let n=t.label,r=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),s=be;We().setInt32((e>>>0)+4,s,!0),We().setInt32((e>>>0)+0,r,!0)},__wbg_length_186163212ffe79c3:function(e){return e.length},__wbg_limits_4e444eb8c2e61c45:function(e){return e.limits},__wbg_limits_98515cc885d709ef:function(e){return e.limits},__wbg_lost_25273dba897db03c:function(e){return e.lost},__wbg_mapAsync_b0597127f5037286:function(e,t,n,r){return e.mapAsync(t>>>0,n,r)},__wbg_maxBindGroupsPlusVertexBuffers_1face4afb5363937:function(e){return e.maxBindGroupsPlusVertexBuffers},__wbg_maxBindGroups_a0b7e55762f095b9:function(e){return e.maxBindGroups},__wbg_maxBindingsPerBindGroup_ec9067be38d6ec72:function(e){return e.maxBindingsPerBindGroup},__wbg_maxBufferSize_a9ce15e541c64cd2:function(e){return e.maxBufferSize},__wbg_maxColorAttachmentBytesPerSample_44089e129e1a2a1d:function(e){return e.maxColorAttachmentBytesPerSample},__wbg_maxColorAttachments_6bd8156394ba618c:function(e){return e.maxColorAttachments},__wbg_maxComputeInvocationsPerWorkgroup_7b086f15ef868934:function(e){return e.maxComputeInvocationsPerWorkgroup},__wbg_maxComputeWorkgroupSizeX_8bbe505e0ac8dc18:function(e){return e.maxComputeWorkgroupSizeX},__wbg_maxComputeWorkgroupSizeY_7228ed3935eecc31:function(e){return e.maxComputeWorkgroupSizeY},__wbg_maxComputeWorkgroupSizeZ_6092b56a967f6f8d:function(e){return e.maxComputeWorkgroupSizeZ},__wbg_maxComputeWorkgroupStorageSize_4773e3bd3936df36:function(e){return e.maxComputeWorkgroupStorageSize},__wbg_maxComputeWorkgroupsPerDimension_79222bf8e8a90fbd:function(e){return e.maxComputeWorkgroupsPerDimension},__wbg_maxDynamicStorageBuffersPerPipelineLayout_3ab5762b1b2c7fc2:function(e){return e.maxDynamicStorageBuffersPerPipelineLayout},__wbg_maxDynamicUniformBuffersPerPipelineLayout_722da31d0de1c256:function(e){return e.maxDynamicUniformBuffersPerPipelineLayout},__wbg_maxInterStageShaderVariables_821096d4b3020715:function(e){return e.maxInterStageShaderVariables},__wbg_maxSampledTexturesPerShaderStage_c6aea9e05c0a02ca:function(e){return e.maxSampledTexturesPerShaderStage},__wbg_maxSamplersPerShaderStage_3aa30f6c002d3a99:function(e){return e.maxSamplersPerShaderStage},__wbg_maxStorageBufferBindingSize_84a2c2433627fca2:function(e){return e.maxStorageBufferBindingSize},__wbg_maxStorageBuffersPerShaderStage_25b96748df28dc20:function(e){return e.maxStorageBuffersPerShaderStage},__wbg_maxStorageTexturesPerShaderStage_53ed734f26e6c1ad:function(e){return e.maxStorageTexturesPerShaderStage},__wbg_maxTextureArrayLayers_9ec487f1ce102992:function(e){return e.maxTextureArrayLayers},__wbg_maxTextureDimension1D_faef91b2e9fa6740:function(e){return e.maxTextureDimension1D},__wbg_maxTextureDimension2D_3a923eb2df4d9124:function(e){return e.maxTextureDimension2D},__wbg_maxTextureDimension3D_943321fe5945464e:function(e){return e.maxTextureDimension3D},__wbg_maxUniformBufferBindingSize_21e89ff761d576db:function(e){return e.maxUniformBufferBindingSize},__wbg_maxUniformBuffersPerShaderStage_19a0bfb0189f7254:function(e){return e.maxUniformBuffersPerShaderStage},__wbg_maxVertexAttributes_49aef6c51d07a280:function(e){return e.maxVertexAttributes},__wbg_maxVertexBufferArrayStride_f68c4029e6f047ec:function(e){return e.maxVertexBufferArrayStride},__wbg_maxVertexBuffers_ce9f15a623f9aac7:function(e){return e.maxVertexBuffers},__wbg_message_5223ba7df7256eac:function(e,t){let n=t.message,r=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),s=be;We().setInt32((e>>>0)+4,s,!0),We().setInt32((e>>>0)+0,r,!0)},__wbg_minStorageBufferOffsetAlignment_529f1f52e61188fc:function(e){return e.minStorageBufferOffsetAlignment},__wbg_minUniformBufferOffsetAlignment_519e26287e1996a3:function(e){return e.minUniformBufferOffsetAlignment},__wbg_naturalHeight_fb7d27a9642e796c:function(e){return e.naturalHeight},__wbg_naturalWidth_c3b5a9ac32cd185e:function(e){return e.naturalWidth},__wbg_navigator_9641ab32fa612dd1:function(e){return e.navigator},__wbg_navigator_c17f443a6fe5d38d:function(e){return e.navigator},__wbg_new_2bfd0f45e60518b1:function(){return Re(function(e,t){return new OffscreenCanvas(e>>>0,t>>>0)},arguments)},__wbg_new_ba40181b3f24ac80:function(e,t){try{var n={a:e,b:t},r=(s,i)=>{let a=n.a;n.a=0;try{return Ls(a,n.b,s,i)}finally{n.a=a}};return new Promise(r)}finally{n.a=0}},__wbg_new_bb74001155cb8ca8:function(){return new Error},__wbg_new_cd4348290afae586:function(){return new Object},__wbg_new_typed_6b60b99917da27d6:function(){return new Object},__wbg_new_typed_e09da9dae6ee5935:function(e,t){try{var n={a:e,b:t},r=(s,i)=>{let a=n.a;n.a=0;try{return Ls(a,n.b,s,i)}finally{n.a=a}};return new Promise(r)}finally{n.a=0}},__wbg_new_with_byte_offset_and_length_3cd32055a417f095:function(e,t,n){return new Uint8Array(e,t>>>0,n>>>0)},__wbg_new_with_length_01b143a7e5dd5a3e:function(e){return new Uint8Array(e>>>0)},__wbg_now_84237b99fa85a391:function(){return performance.now()},__wbg_onSubmittedWorkDone_1190213cee1ecf7e:function(e){return e.onSubmittedWorkDone()},__wbg_prototypesetcall_13162965d1fe7aa3:function(e,t,n){Uint8Array.prototype.set.call(Kt(e,t),n)},__wbg_querySelectorAll_6c1bd81d448fb480:function(){return Re(function(e,t,n){return e.querySelectorAll(Se(t,n))},arguments)},__wbg_queueMicrotask_1e8503a8a690f0a3:function(e){return e.queueMicrotask},__wbg_queueMicrotask_4a1a4d8dd332373b:function(e){queueMicrotask(e)},__wbg_queue_e250e2ebc49b39e0:function(e){return e.queue},__wbg_reason_53e762e714b67b72:function(e){let t=e.reason;return(Al.indexOf(t)+1||3)-1},__wbg_renderer_new:function(e){return Lt.__wrap(e)},__wbg_requestAdapter_a539af006419f2e9:function(e,t){return e.requestAdapter(t)},__wbg_requestDevice_5cb8a582e55d08cb:function(e,t){return e.requestDevice(t)},__wbg_resolve_dbf78ab4942478b0:function(e){return Promise.resolve(e)},__wbg_setBindGroup_418c3e0eb6943ce0:function(e,t,n){e.setBindGroup(t>>>0,n)},__wbg_setBindGroup_82d014e8f799f053:function(){return Re(function(e,t,n,r,s,i,a){e.setBindGroup(t>>>0,n,Bl(r,s),i,a>>>0)},arguments)},__wbg_setIndexBuffer_241097e303986c14:function(e,t,n,r,s){e.setIndexBuffer(t,Us[n],r,s)},__wbg_setPipeline_b6f981027e02cd16:function(e,t){e.setPipeline(t)},__wbg_setScissorRect_889235eeb784732b:function(e,t,n,r,s){e.setScissorRect(t>>>0,n>>>0,r>>>0,s>>>0)},__wbg_setVertexBuffer_6db3b60e99280744:function(e,t,n,r){e.setVertexBuffer(t>>>0,n,r)},__wbg_setVertexBuffer_cbf4ca1627c02f4c:function(e,t,n,r,s){e.setVertexBuffer(t>>>0,n,r,s)},__wbg_setViewport_c0be08dcc8965ccf:function(e,t,n,r,s,i,a){e.setViewport(t,n,r,s,i,a)},__wbg_set_118fefd528ab0a79:function(e,t,n){e.set(t,n>>>0)},__wbg_set_2793479888329cb6:function(){return Re(function(e,t,n){return Reflect.set(e,t,n)},arguments)},__wbg_set_a_1c94f1413a06c773:function(e,t){e.a=t},__wbg_set_access_b0a6fbebfbe53242:function(e,t){e.access=Cl[t]},__wbg_set_address_mode_u_a39aefdf030758ae:function(e,t){e.addressModeU=sr[t]},__wbg_set_address_mode_v_999ec6ed4d587e8c:function(e,t){e.addressModeV=sr[t]},__wbg_set_address_mode_w_a936c884ccf08234:function(e,t){e.addressModeW=sr[t]},__wbg_set_alpha_84214d12347c6647:function(e,t){e.alpha=t},__wbg_set_alpha_mode_278c6649365aff36:function(e,t){e.alphaMode=kl[t]},__wbg_set_alpha_to_coverage_enabled_1e879520cab4bb05:function(e,t){e.alphaToCoverageEnabled=t!==0},__wbg_set_array_layer_count_bd7a074559a0abaa:function(e,t){e.arrayLayerCount=t>>>0},__wbg_set_array_stride_f64_b132c6a79afeae43:function(e,t){e.arrayStride=t},__wbg_set_aspect_1db857832468d61f:function(e,t){e.aspect=cr[t]},__wbg_set_aspect_3b0dceed92671cc1:function(e,t){e.aspect=cr[t]},__wbg_set_aspect_8c866a3891032753:function(e,t){e.aspect=cr[t]},__wbg_set_attributes_67bbc44b08e038d6:function(e,t,n){e.attributes=Ve(t,n)},__wbg_set_b_a93bcfdd1c29a0bd:function(e,t){e.b=t},__wbg_set_base_array_layer_e745f84c2e5437e2:function(e,t){e.baseArrayLayer=t>>>0},__wbg_set_base_mip_level_fe08854fab09de85:function(e,t){e.baseMipLevel=t>>>0},__wbg_set_beginning_of_pass_write_index_a13b608f19d6a2f0:function(e,t){e.beginningOfPassWriteIndex=t>>>0},__wbg_set_bind_group_layouts_383f681565a30d8a:function(e,t,n){e.bindGroupLayouts=Ve(t,n)},__wbg_set_binding_bd7d6b01bb08823a:function(e,t){e.binding=t>>>0},__wbg_set_binding_dbed4a234264971a:function(e,t){e.binding=t>>>0},__wbg_set_blend_1f3e5b36f9c246cb:function(e,t){e.blend=t},__wbg_set_buffer_292fb3c30928dc50:function(e,t){e.buffer=t},__wbg_set_buffer_76841cdbff393f1d:function(e,t){e.buffer=t},__wbg_set_buffer_91f4e8e05066c37a:function(e,t){e.buffer=t},__wbg_set_buffers_47665c552e27672c:function(e,t,n){e.buffers=Ve(t,n)},__wbg_set_bytes_per_row_4ef9c2c51932b041:function(e,t){e.bytesPerRow=t>>>0},__wbg_set_bytes_per_row_75441352f606ebc8:function(e,t){e.bytesPerRow=t>>>0},__wbg_set_clear_value_gpu_color_dict_303e0009591e5d26:function(e,t){e.clearValue=t},__wbg_set_code_130aebc49c4cadd3:function(e,t,n){e.code=Se(t,n)},__wbg_set_color_6d2de56a2224ec57:function(e,t){e.color=t},__wbg_set_color_attachments_e83f79badceda8b4:function(e,t,n){e.colorAttachments=Ve(t,n)},__wbg_set_compare_159af15eb77dbcd2:function(e,t){e.compare=ir[t]},__wbg_set_compare_4db27ced1edc0322:function(e,t){e.compare=ir[t]},__wbg_set_count_4d1e9559a7f1b993:function(e,t){e.count=t>>>0},__wbg_set_cull_mode_31293d13bc064271:function(e,t){e.cullMode=Sl[t]},__wbg_set_depth_bias_b30728f3ab3f643e:function(e,t){e.depthBias=t},__wbg_set_depth_bias_clamp_5b58fd4819283038:function(e,t){e.depthBiasClamp=t},__wbg_set_depth_bias_slope_scale_8b8b20db6b43c43b:function(e,t){e.depthBiasSlopeScale=t},__wbg_set_depth_clear_value_1165941523836019:function(e,t){e.depthClearValue=t},__wbg_set_depth_compare_81dd71de7e433cc2:function(e,t){e.depthCompare=ir[t]},__wbg_set_depth_fail_op_ddf822c573cdf0c1:function(e,t){e.depthFailOp=or[t]},__wbg_set_depth_load_op_ca270acab0c1ca69:function(e,t){e.depthLoadOp=ar[t]},__wbg_set_depth_or_array_layers_e59f3988a095ccac:function(e,t){e.depthOrArrayLayers=t>>>0},__wbg_set_depth_read_only_49ca399f98b97955:function(e,t){e.depthReadOnly=t!==0},__wbg_set_depth_stencil_41e94739225cb2c3:function(e,t){e.depthStencil=t},__wbg_set_depth_stencil_attachment_36ce3695dfcb6b85:function(e,t){e.depthStencilAttachment=t},__wbg_set_depth_store_op_6cd6bdde49f9050d:function(e,t){e.depthStoreOp=lr[t]},__wbg_set_depth_write_enabled_4b5da11c77fbdab7:function(e,t){e.depthWriteEnabled=t!==0},__wbg_set_device_1940fd5f9e2a7fee:function(e,t){e.device=t},__wbg_set_dimension_88d0c9f16bb079fb:function(e,t){e.dimension=Ol[t]},__wbg_set_dimension_bab9530fa3e311d8:function(e,t){e.dimension=ur[t]},__wbg_set_dst_factor_80c13f29a3e117cb:function(e,t){e.dstFactor=Fs[t]},__wbg_set_end_of_pass_write_index_793fcfe3141dc357:function(e,t){e.endOfPassWriteIndex=t>>>0},__wbg_set_entries_552f52b2aa3b346d:function(e,t,n){e.entries=Ve(t,n)},__wbg_set_entries_d9929dbfa2aaa9a7:function(e,t,n){e.entries=Ve(t,n)},__wbg_set_entry_point_0eacf7b26b3637b0:function(e,t,n){e.entryPoint=Se(t,n)},__wbg_set_entry_point_bb3692db4a6065d0:function(e,t,n){e.entryPoint=Se(t,n)},__wbg_set_external_texture_1bef5ba626275d0a:function(e,t){e.externalTexture=t},__wbg_set_fail_op_739cc3815d38c95f:function(e,t){e.failOp=or[t]},__wbg_set_feb3714f475485ba:function(e,t,n){e.set(Kt(t,n))},__wbg_set_flip_y_ab62f34abbe69be1:function(e,t){e.flipY=t!==0},__wbg_set_format_1119b9930bd324e1:function(e,t){e.format=ut[t]},__wbg_set_format_443ea19e2d25a1e2:function(e,t){e.format=ut[t]},__wbg_set_format_459792306baadae5:function(e,t){e.format=ut[t]},__wbg_set_format_46b1c6b3acc10b24:function(e,t){e.format=ut[t]},__wbg_set_format_5a62f31a4690f935:function(e,t){e.format=Dl[t]},__wbg_set_format_efec4f7d9471ddbb:function(e,t){e.format=ut[t]},__wbg_set_format_fd579d96fa4e468c:function(e,t){e.format=ut[t]},__wbg_set_fragment_bea523f8973c326e:function(e,t){e.fragment=t},__wbg_set_front_face_30951d0404e9e6d4:function(e,t){e.frontFace=El[t]},__wbg_set_g_90eacc6608e549f8:function(e,t){e.g=t},__wbg_set_has_dynamic_offset_6e5f3385eb579529:function(e,t){e.hasDynamicOffset=t!==0},__wbg_set_height_3f64e19acf29f5fb:function(e,t){e.height=t>>>0},__wbg_set_height_ae0610d318c3428c:function(e,t){e.height=t>>>0},__wbg_set_height_ae24c2f7d580ae0a:function(e,t){e.height=t>>>0},__wbg_set_label_08745022b1ec7b66:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_11c9eb57693a8459:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_20c42b4ebeb250d5:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_22e3966c8d513ba6:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_5347fc976d15e94c:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_644bc1b32c7917b0:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_73c99dab6708c962:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_85a21b5fdd57fd91:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_89d2ffaf598df6a4:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_9e68078b9533426b:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_a80ced9a51c33d0f:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_cba03ffef7ae90a3:function(e,t,n){e.label=Se(t,n)},__wbg_set_label_f654bcb731d4d9ca:function(e,t,n){e.label=Se(t,n)},__wbg_set_layout_200fc3b143da0a9e:function(e,t){e.layout=t},__wbg_set_layout_3f0cb99635c33123:function(e,t){e.layout=t},__wbg_set_layout_gpu_auto_layout_mode_2e8a53f8643b4f69:function(e,t){e.layout=yl[t]},__wbg_set_load_op_e8c33d4bdd2772aa:function(e,t){e.loadOp=ar[t]},__wbg_set_lod_max_clamp_fcbef26e87120fac:function(e,t){e.lodMaxClamp=t},__wbg_set_lod_min_clamp_f5b6ddca1e4d813f:function(e,t){e.lodMinClamp=t},__wbg_set_mag_filter_ba0a2f25ad41eea8:function(e,t){e.magFilter=Bs[t]},__wbg_set_mapped_at_creation_8af5b87ccb898bbe:function(e,t){e.mappedAtCreation=t!==0},__wbg_set_mask_0de0e782abec3c25:function(e,t){e.mask=t>>>0},__wbg_set_max_anisotropy_8361213d3df93532:function(e,t){e.maxAnisotropy=t},__wbg_set_min_binding_size_f64_c6d68d773b7051d3:function(e,t){e.minBindingSize=t},__wbg_set_min_filter_8aa8b0f7523a0281:function(e,t){e.minFilter=Bs[t]},__wbg_set_mip_level_102afeb158e4f728:function(e,t){e.mipLevel=t>>>0},__wbg_set_mip_level_count_c0ac46de264d83ec:function(e,t){e.mipLevelCount=t>>>0},__wbg_set_mip_level_count_cd650972803ed9eb:function(e,t){e.mipLevelCount=t>>>0},__wbg_set_mip_level_f0c5ed95eedda453:function(e,t){e.mipLevel=t>>>0},__wbg_set_mipmap_filter_1cbdec28d1b54d9d:function(e,t){e.mipmapFilter=Tl[t]},__wbg_set_mode_51d2c5a5ac0f7ac9:function(e,t){e.mode=Ml[t]},__wbg_set_module_3dec1a50bca7870a:function(e,t){e.module=t},__wbg_set_module_b42baf3925e2a94a:function(e,t){e.module=t},__wbg_set_multisample_6af76792fae6efb1:function(e,t){e.multisample=t},__wbg_set_multisampled_ae3f9f01a324f57c:function(e,t){e.multisampled=t!==0},__wbg_set_offset_f64_15176b737de7dde0:function(e,t){e.offset=t},__wbg_set_offset_f64_18de9c771f307302:function(e,t){e.offset=t},__wbg_set_offset_f64_52f728fc5c98a52c:function(e,t){e.offset=t},__wbg_set_offset_f64_9374d9e912985773:function(e,t){e.offset=t},__wbg_set_operation_e103287df7ac9cf6:function(e,t){e.operation=vl[t]},__wbg_set_origin_gpu_origin_2d_dict_0e541bd50713ae04:function(e,t){e.origin=t},__wbg_set_origin_gpu_origin_3d_dict_26016670147a706c:function(e,t){e.origin=t},__wbg_set_origin_gpu_origin_3d_dict_4e6802818d9d43c7:function(e,t){e.origin=t},__wbg_set_pass_op_4d08c3105f64a17a:function(e,t){e.passOp=or[t]},__wbg_set_power_preference_6bc1d2697a0e7374:function(e,t){e.powerPreference=Pl[t]},__wbg_set_premultiplied_alpha_3625f78af5f2fed6:function(e,t){e.premultipliedAlpha=t!==0},__wbg_set_primitive_ef867d733c4efb1c:function(e,t){e.primitive=t},__wbg_set_query_set_765c4c9ab99342cb:function(e,t){e.querySet=t},__wbg_set_r_1116d6a5f656263d:function(e,t){e.r=t},__wbg_set_required_features_5bda1420e19461b2:function(e,t,n){e.requiredFeatures=Ve(t,n)},__wbg_set_required_limits_e78b923d73f9b596:function(e,t){e.requiredLimits=t},__wbg_set_resolve_target_gpu_texture_view_a7a97a7c04d84698:function(e,t){e.resolveTarget=t},__wbg_set_resource_0f960a4279e7e400:function(e,t){e.resource=t},__wbg_set_resource_gpu_buffer_binding_53a2189a77dd38be:function(e,t){e.resource=t},__wbg_set_resource_gpu_texture_view_9153a2356b958667:function(e,t){e.resource=t},__wbg_set_rows_per_image_11e9552fb5c5c5ab:function(e,t){e.rowsPerImage=t>>>0},__wbg_set_rows_per_image_df6af33a5492c1cf:function(e,t){e.rowsPerImage=t>>>0},__wbg_set_sample_count_8262aacc91878e4d:function(e,t){e.sampleCount=t>>>0},__wbg_set_sample_type_563589178fc892fe:function(e,t){e.sampleType=$l[t]},__wbg_set_sampler_ccdca76ef8e642ca:function(e,t){e.sampler=t},__wbg_set_shader_location_31dc427c303a32aa:function(e,t){e.shaderLocation=t>>>0},__wbg_set_size_f64_3ff72c0d736c42a1:function(e,t){e.size=t},__wbg_set_size_f64_9b65e4916b2eb111:function(e,t){e.size=t},__wbg_set_size_gpu_extent_3d_dict_bba6669c79c26190:function(e,t){e.size=t},__wbg_set_source_b5f82926b86ec9d9:function(e,t){e.source=t},__wbg_set_source_html_canvas_element_a9840c24a328a44e:function(e,t){e.source=t},__wbg_set_source_html_image_element_b2803013cdaaa4f6:function(e,t){e.source=t},__wbg_set_source_html_video_element_9fd22376f74c9aff:function(e,t){e.source=t},__wbg_set_source_image_data_2d6a4979315db9d8:function(e,t){e.source=t},__wbg_set_source_offscreen_canvas_ef8e002b1f9c1fd8:function(e,t){e.source=t},__wbg_set_source_video_frame_e98ea9a6467ae147:function(e,t){e.source=t},__wbg_set_src_factor_7e90d4b7d8227fc5:function(e,t){e.srcFactor=Fs[t]},__wbg_set_stencil_back_6b5aeefbb90ae3ae:function(e,t){e.stencilBack=t},__wbg_set_stencil_clear_value_56fa848198a9b430:function(e,t){e.stencilClearValue=t>>>0},__wbg_set_stencil_front_4ffeca9473bca095:function(e,t){e.stencilFront=t},__wbg_set_stencil_load_op_b7a9fe3ad789b6c6:function(e,t){e.stencilLoadOp=ar[t]},__wbg_set_stencil_read_mask_7cfe0945679de134:function(e,t){e.stencilReadMask=t>>>0},__wbg_set_stencil_read_only_0dde0c073192b5fa:function(e,t){e.stencilReadOnly=t!==0},__wbg_set_stencil_store_op_d320bcbb72456a4c:function(e,t){e.stencilStoreOp=lr[t]},__wbg_set_stencil_write_mask_765017d5830ee98a:function(e,t){e.stencilWriteMask=t>>>0},__wbg_set_step_mode_2b1318f00e2ddc02:function(e,t){e.stepMode=Ll[t]},__wbg_set_storage_texture_b9e95e260c9d49a3:function(e,t){e.storageTexture=t},__wbg_set_store_op_e2b740eddfd2713f:function(e,t){e.storeOp=lr[t]},__wbg_set_strip_index_format_22ddab1b8f352c1d:function(e,t){e.stripIndexFormat=Us[t]},__wbg_set_targets_07e15f3cca640faf:function(e,t,n){e.targets=Ve(t,n)},__wbg_set_texture_7b9ace323bfe7938:function(e,t){e.texture=t},__wbg_set_texture_84a5f84f0f451291:function(e,t){e.texture=t},__wbg_set_texture_b35a4d6a35c491fa:function(e,t){e.texture=t},__wbg_set_timestamp_writes_1d304b9eb09ff227:function(e,t){e.timestampWrites=t},__wbg_set_tone_mapping_23fcd4f846a61048:function(e,t){e.toneMapping=t},__wbg_set_topology_b29804e5549370f5:function(e,t){e.topology=Il[t]},__wbg_set_type_ac87cc570da17000:function(e,t){e.type=xl[t]},__wbg_set_type_f3d1ad35dc7889f9:function(e,t){e.type=Rl[t]},__wbg_set_unclipped_depth_59155eb615f193fe:function(e,t){e.unclippedDepth=t!==0},__wbg_set_usage_5ba672bf81ba9859:function(e,t){e.usage=t>>>0},__wbg_set_usage_b0070c2ce47149a6:function(e,t){e.usage=t>>>0},__wbg_set_usage_bac3cabe90090275:function(e,t){e.usage=t>>>0},__wbg_set_usage_f3e1a48118ff483a:function(e,t){e.usage=t>>>0},__wbg_set_vertex_00b1e17dc3fe7fb3:function(e,t){e.vertex=t},__wbg_set_view_dimension_e9e9cd07d7ad686d:function(e,t){e.viewDimension=ur[t]},__wbg_set_view_dimension_eb197c35c45e572c:function(e,t){e.viewDimension=ur[t]},__wbg_set_view_formats_2540cdb8dde31055:function(e,t,n){e.viewFormats=Ve(t,n)},__wbg_set_view_formats_845b425c1d19e1af:function(e,t,n){e.viewFormats=Ve(t,n)},__wbg_set_view_gpu_texture_view_9a3c34ba4d1969b8:function(e,t){e.view=t},__wbg_set_view_gpu_texture_view_efa644c1ce3c4deb:function(e,t){e.view=t},__wbg_set_visibility_65413465e7b24eb6:function(e,t){e.visibility=t>>>0},__wbg_set_width_5f89a551b5472887:function(e,t){e.width=t>>>0},__wbg_set_width_a2410cafbdefeb5a:function(e,t){e.width=t>>>0},__wbg_set_width_eb3001e1dcabb909:function(e,t){e.width=t>>>0},__wbg_set_write_mask_39ce121635fd4296:function(e,t){e.writeMask=t>>>0},__wbg_set_x_b078c58009aa57bd:function(e,t){e.x=t>>>0},__wbg_set_x_d851b2611b154969:function(e,t){e.x=t>>>0},__wbg_set_y_3df92c4bcff23616:function(e,t){e.y=t>>>0},__wbg_set_y_76a6f85fc60d74e5:function(e,t){e.y=t>>>0},__wbg_set_z_3633c53887a9ff5e:function(e,t){e.z=t>>>0},__wbg_stack_575c4e0918581b9c:function(e,t){let n=t.stack,r=Oe(n,y.__wbindgen_malloc,y.__wbindgen_realloc),s=be;We().setInt32((e>>>0)+4,s,!0),We().setInt32((e>>>0)+0,r,!0)},__wbg_static_accessor_GLOBAL_THIS_003ee833af9699fc:function(){let e=typeof globalThis>"u"?void 0:globalThis;return Xe(e)?0:He(e)},__wbg_static_accessor_GLOBAL_e4293fb22cbe77da:function(){let e=typeof global>"u"?void 0:global;return Xe(e)?0:He(e)},__wbg_static_accessor_SELF_53bb20457401453d:function(){let e=typeof self>"u"?void 0:self;return Xe(e)?0:He(e)},__wbg_static_accessor_WINDOW_b5e0810bfecb7feb:function(){let e=typeof window>"u"?void 0:window;return Xe(e)?0:He(e)},__wbg_subgroupMaxSize_3586e822dc3603f6:function(e){return e.subgroupMaxSize},__wbg_subgroupMinSize_17f758985cdd1dab:function(e){return e.subgroupMinSize},__wbg_submit_077c85cc28e36892:function(e,t,n){e.submit(Ve(t,n))},__wbg_then_3a4f899454bcf8c9:function(e,t){return e.then(t)},__wbg_then_656f253a5dd7d8ea:function(e,t,n){return e.then(t,n)},__wbg_then_e3f7f2d365708be8:function(e,t){return e.then(t)},__wbg_unconfigure_835307f58dc68d80:function(e){e.unconfigure()},__wbg_unmap_6a96b14c9ef5f7f5:function(e){e.unmap()},__wbg_videoHeight_0d108b7f03cde4ef:function(e){return e.videoHeight},__wbg_videoWidth_34b4e257cb35c6ca:function(e){return e.videoWidth},__wbg_width_000813f5f73b7341:function(e){return e.width},__wbg_width_babc5dc7654771b1:function(e){return e.width},__wbg_width_f84552448726a9a9:function(e){return e.width},__wbg_writeBuffer_d7640e64ceb69371:function(){return Re(function(e,t,n,r,s,i,a){e.writeBuffer(t,n,Kt(r,s),i,a)},arguments)},__wbg_writeTexture_dba1e801af087dfd:function(){return Re(function(e,t,n,r,s,i){e.writeTexture(t,Kt(n,r),s,i)},arguments)},__wbindgen_generic_0000000000000001:function(e,t){return qt(e,t,ml)},__wbindgen_generic_0000000000000002:function(e,t){return qt(e,t,gl)},__wbindgen_generic_0000000000000003:function(e,t){return qt(e,t,pl)},__wbindgen_generic_0000000000000004:function(e,t){return qt(e,t,bl)},__wbindgen_generic_0000000000000005:function(e,t){return qt(e,t,wl)},__wbindgen_generic_0000000000000006:function(e){return e},__wbindgen_generic_0000000000000007:function(e,t){return Kt(e,t)},__wbindgen_generic_0000000000000008:function(e,t){return Se(e,t)},__wbindgen_init_externref_table:function(){let e=y.__wbindgen_externrefs;e.set(0,void 0),e.set(1024,void 0),e.set(1025,null),e.set(1026,!0),e.set(1027,!1)}}}}function pl(e,t,n){y.wasm_bindgen_1191a70febc59fc___convert__closures_____invoke___wgpu_1da0beaa27c83114___backend__webgpu__webgpu_sys__gen_GpuDeviceLostInfo__GpuDeviceLostInfo______true_(e,t,n)}function ml(e,t,n){let r=y.wasm_bindgen_1191a70febc59fc___convert__closures_____invoke___wasm_bindgen_1191a70febc59fc___JsValue__core_37ee0ce0c4cd57d5___result__Result_____wasm_bindgen_1191a70febc59fc___JsError___true_(e,t,n);if(r[1])throw nt(r[0])}function gl(e,t,n){let r=y.wasm_bindgen_1191a70febc59fc___convert__closures_____invoke___wasm_bindgen_1191a70febc59fc___sys__JsNullable_wgpu_1da0beaa27c83114___backend__webgpu__webgpu_sys__gen_GpuError__GpuError___core_37ee0ce0c4cd57d5___result__Result_____wasm_bindgen_1191a70febc59fc___JsError___true_(e,t,n);if(r[1])throw nt(r[0])}function bl(e,t,n){let r=y.wasm_bindgen_1191a70febc59fc___convert__closures_____invoke___wasm_bindgen_1191a70febc59fc___sys__JsNullable_wgpu_1da0beaa27c83114___backend__webgpu__webgpu_sys__gen_GpuError__GpuError___core_37ee0ce0c4cd57d5___result__Result_____wasm_bindgen_1191a70febc59fc___JsError___true__46(e,t,n);if(r[1])throw nt(r[0])}function wl(e,t,n){let r=y.wasm_bindgen_1191a70febc59fc___convert__closures_____invoke___wasm_bindgen_1191a70febc59fc___sys__JsNullable_wgpu_1da0beaa27c83114___backend__webgpu__webgpu_sys__gen_GpuError__GpuError___core_37ee0ce0c4cd57d5___result__Result_____wasm_bindgen_1191a70febc59fc___JsError___true__47(e,t,n);if(r[1])throw nt(r[0])}function Ls(e,t,n,r){y.wasm_bindgen_1191a70febc59fc___convert__closures_____invoke___js_sys_2044d24e9c2bb073___Function_fn_wasm_bindgen_1191a70febc59fc___JsValue_____wasm_bindgen_1191a70febc59fc___sys__Undefined___js_sys_2044d24e9c2bb073___Function_fn_wasm_bindgen_1191a70febc59fc___JsValue_____wasm_bindgen_1191a70febc59fc___sys__Undefined_______true_(e,t,n,r)}var sr=["clamp-to-edge","repeat","mirror-repeat"],yl=["auto"],Fs=["zero","one","src","one-minus-src","src-alpha","one-minus-src-alpha","dst","one-minus-dst","dst-alpha","one-minus-dst-alpha","src-alpha-saturated","constant","one-minus-constant","src1","one-minus-src1","src1-alpha","one-minus-src1-alpha"],vl=["add","subtract","reverse-subtract","min","max"],xl=["uniform","storage","read-only-storage"],kl=["opaque","premultiplied"],Ml=["standard","extended"],ir=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],Sl=["none","front","back"],Al=["unknown","destroyed"],Bs=["nearest","linear"],El=["ccw","cw"],Us=["uint16","uint32"],ar=["load","clear"],Tl=["nearest","linear"],Pl=["low-power","high-performance"],Il=["point-list","line-list","line-strip","triangle-list","triangle-strip"],Rl=["filtering","non-filtering","comparison"],or=["keep","zero","replace","invert","increment-clamp","decrement-clamp","increment-wrap","decrement-wrap"],Cl=["write-only","read-only","read-write"],lr=["store","discard"],cr=["all","stencil-only","depth-only"],Ol=["1d","2d","3d"],ut=["r8unorm","r8snorm","r8uint","r8sint","r16unorm","r16snorm","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32uint","r32sint","r32float","rg16unorm","rg16snorm","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb9e5ufloat","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rg32uint","rg32sint","rg32float","rgba16unorm","rgba16snorm","rgba16uint","rgba16sint","rgba16float","rgba32uint","rgba32sint","rgba32float","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm","etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb","astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],$l=["float","unfilterable-float","depth","sint","uint"],ur=["1d","2d","2d-array","cube","cube-array","3d"],Dl=["uint8","uint8x2","uint8x4","sint8","sint8x2","sint8x4","unorm8","unorm8x2","unorm8x4","snorm8","snorm8x2","snorm8x4","uint16","uint16x2","uint16x4","sint16","sint16x2","sint16x4","unorm16","unorm16x2","unorm16x4","snorm16","snorm16x2","snorm16x4","float16","float16x2","float16x4","float32","float32x2","float32x3","float32x4","uint32","uint32x2","uint32x3","uint32x4","sint32","sint32x2","sint32x3","sint32x4","unorm10-10-10-2","unorm8x4-bgra"],Ll=["vertex","instance"],js=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>y.__wbg_mstext_free(e,1)),Ns=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>y.__wbg_renderer_free(e,1));function He(e){let t=y.__externref_table_alloc();return y.__wbindgen_externrefs.set(t,e),t}var Ws=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>y.__wbindgen_destroy_closure(e.a,e.b));function $i(e){switch(typeof e){case"number":case"boolean":case"undefined":return`${e}`;case"string":return JSON.stringify(e);case"bigint":return`${e}n`;case"symbol":return e.description!==void 0?`Symbol(${e.description})`:"Symbol";case"function":return typeof e.name=="string"&&e.name!==""?`Function(${e.name})`:"Function";case"object":{if(e===null)return"null";if(Array.isArray(e))return"["+Array.from(e,$i).join(", ")+"]";if(e instanceof Error)return`${e.name}: ${e.message}
698
+ ${e.stack}`;let t=toString.call(e),n=/\[object ([^\]]+)\]/.exec(t)?.[1];if(n===void 0)return t;if(n==="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return n}}}function mt(e,t){return e=e>>>0,Di().subarray(e/4,e/4+t)}function Fl(e,t){return e=e>>>0,Ul().subarray(e/8,e/8+t)}function fr(e,t){e=e>>>0;let n=We(),r=[];for(let s=e;s<e+4*t;s+=4)r.push(y.__wbindgen_externrefs.get(n.getUint32(s,!0)));return y.__externref_drop_slice(e,t),r}function Ve(e,t){e=e>>>0;let n=We(),r=[];for(let s=e;s<e+4*t;s+=4)r.push(y.__wbindgen_externrefs.get(n.getUint32(s,!0)));return r}function Bl(e,t){return e=e>>>0,Li().subarray(e/4,e/4+t)}function Kt(e,t){return e=e>>>0,$t().subarray(e/1,e/1+t)}var pt=null;function We(){return(pt===null||pt.buffer.detached===!0||pt.buffer.detached===void 0&&pt.buffer!==y.memory.buffer)&&(pt=new DataView(y.memory.buffer)),pt}var en=null;function Di(){return(en===null||en.byteLength===0)&&(en=new Float32Array(y.memory.buffer)),en}var tn=null;function Ul(){return(tn===null||tn.byteLength===0)&&(tn=new Float64Array(y.memory.buffer)),tn}function Se(e,t){return e=e>>>0,Nl($t().subarray(e,e+t))}var nn=null;function Li(){return(nn===null||nn.byteLength===0)&&(nn=new Uint32Array(y.memory.buffer)),nn}var rn=null;function $t(){return(rn===null||rn.byteLength===0)&&(rn=new Uint8Array(y.memory.buffer)),rn}function Re(e,t){try{return e.apply(this,t)}catch(n){let r=He(n);y.__wbindgen_exn_store(r)}}function Xe(e){return e==null}function qt(e,t,n){let r={a:e,b:t,cnt:1},s=(...i)=>{r.cnt++;let a=r.a;r.a=0;try{return n(a,r.b,...i)}finally{r.a=a,s._wbg_cb_unref()}};return s._wbg_cb_unref=()=>{--r.cnt===0&&(y.__wbindgen_destroy_closure(r.a,r.b),r.a=0,Ws.unregister(r))},Ws.register(s,r,r),s}function Ir(e,t){let n=t(e.length*4,4)>>>0;return Li().set(e,n/4),be=e.length,n}function Rr(e,t){let n=t(e.length*1,1)>>>0;return $t().set(e,n/1),be=e.length,n}function An(e,t){let n=t(e.length*4,4)>>>0;return Di().set(e,n/4),be=e.length,n}function Oe(e,t,n){if(n===void 0){let o=an.encode(e),l=t(o.length,1)>>>0;return $t().subarray(l,l+o.length).set(o),be=o.length,l}let r=e.length,s=t(r,1)>>>0,i=$t(),a=0;for(;a<r;a++){let o=e.charCodeAt(a);if(o>127)break;i[s+a]=o}if(a!==r){a!==0&&(e=e.slice(a)),s=n(s,r,r=a+e.length*3,1)>>>0;let o=$t().subarray(s+a,s+r),l=an.encodeInto(e,o);a+=l.written,s=n(s,r,a,1)>>>0}return be=a,s}function nt(e){let t=y.__wbindgen_externrefs.get(e);return y.__externref_table_dealloc(e),t}var Cn=new TextDecoder("utf-8",{ignoreBOM:!0});Cn.decode();var jl=2146435072,dr=0;function Nl(e){return dr+=e.length,dr>=jl&&(Cn=new TextDecoder("utf-8",{ignoreBOM:!0}),Cn.decode(),dr=e.length),Cn.decode(e)}var an=new TextEncoder;"encodeInto"in an||(an.encodeInto=function(e,t){let n=an.encode(e);return t.set(n),{read:e.length,written:n.length}});var be=0,y;function Wl(e,t){return y=e.exports,pt=null,en=null,tn=null,nn=null,rn=null,y.__wbindgen_start(),y}async function Vl(e,t){if(typeof Response=="function"&&e instanceof Response){if(!e.ok)throw new Error(`failed to fetch Wasm: ${e.status} ${e.statusText} fetching '${e.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(s){if(n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",s);else throw s}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}var Jt;async function Gl(e){return y!==void 0?y:(Jt===void 0&&(Jt=zl(e),Jt.catch(()=>{Jt=void 0})),Jt)}async function zl(e){e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL("ms_renderer_bg.wasm",import.meta.url));let t=_l();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Vl(await e,t);return Wl(n,r)}var Fi=["normal","multiply","screen","overlay","darken","lighten","colorDodge","colorBurn","hardLight","softLight","difference","exclusion","hue","saturation","color","luminosity","plus"],Ce={move:0,line:1,quad:2,cubic:3,close:4},Hl={group:0,rect:1,ellipse:2,path:3,compound:4,text:5},Kl={union:0,cut:1,intersect:2,exclude:3},ql={alpha:1,luminance:2,invertAlpha:3,invertLuminance:4,invertAlphaEroded:5,alphaDilated:6},ke={CREATE:1,CHILDREN:2,TRANSFORM:4,SIZE:8,RADII:16,FILL:32,STROKE:64,SHADOWS:128,OPACITY:256,BLEND:512,CLIP:1024,FILTER:2048,PATH:4096,MEMBERS:8192,MASK:16384,TEXT:32768,EFFECTS:65536,ALL:(1<<17)-1},Jl=class{id;kind;children=[];transform=[1,0,0,1,0,0];opacity=1;blend="normal";w=0;h=0;radii=[0,0,0,0];fill;stroke;shadows=[];clip;mask;members;text;effects;effectTime;effectBox;filter;path;evenOdd=!1;dirty=ke.ALL;constructor(e,t){this.id=e,this.kind=t}},Bi=class{width;height;background;root;nodes=[];images=[];dirty=new Set;nextId=0;constructor(e,t,n){this.width=e,this.height=t,this.background=n,this.root=this.make("group",{})}make(e,t){let n=new Jl(this.nextId++,e);return Object.assign(n,t),this.nodes.push(n),this.dirty.add(n),n}add(e,t,n){let r=this.make(t,n);return e.children.push(r),this.touch(e,ke.CHILDREN),r}group(e,t={}){return this.add(e,"group",t)}rect(e,t){return this.add(e,"rect",t)}ellipse(e,t){return this.add(e,"ellipse",t)}pathNode(e,t){return this.add(e,"path",t)}compound(e,t){return this.add(e,"compound",t)}textNode(e,t){return this.add(e,"text",t)}addImage(e,t,n,r={}){let s={id:this.images.length,width:t,height:n,source:e,mipmaps:r.mipmaps??!0,version:1};return this.images.push(s),s}addScene3D(e,t,n,r){let s={id:this.images.length,width:t,height:n,source:null,mipmaps:!1,version:1,scene3d:e,links3d:r};return this.images.push(s),s}detached(e={}){return this.make("group",e)}addSurface(e,t,n){let r={id:this.images.length,width:t,height:n,source:null,mipmaps:!1,version:1,surface:e};return this.images.push(r),r}touch(e,t){e.dirty|=t,this.dirty.add(e)}touchAll(){for(let e of this.nodes)this.touch(e,ke.ALL)}};function On(e){return e.length===9&&(e[6]!==0||e[7]!==0||e[8]!==1)}function Vs(e){return e.length===9?[e[0],e[2],e[4],e[1],e[3],e[5],e[6],e[7],e[8]]:[e[0],e[2],e[4],e[1],e[3],e[5],0,0,1]}function Yl(e,t){let n=Vs(e),r=Vs(t),s=new Array(9);for(let i=0;i<3;i++)for(let a=0;a<3;a++)s[i*3+a]=n[i*3]*r[a]+n[i*3+1]*r[3+a]+n[i*3+2]*r[6+a];return[s[0],s[3],s[1],s[4],s[2],s[5],s[6],s[7],s[8]]}function hr(e,t){return e.length===9||t.length===9?Yl(e,t):[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}var at=class{verbs=[];pts=[];moveTo(e,t){return this.verbs.push(Ce.move),this.pts.push(e,t),this}lineTo(e,t){return this.verbs.push(Ce.line),this.pts.push(e,t),this}quadTo(e,t,n,r){return this.verbs.push(Ce.quad),this.pts.push(e,t,n,r),this}cubicTo(e,t,n,r,s,i){return this.verbs.push(Ce.cubic),this.pts.push(e,t,n,r,s,i),this}close(){return this.verbs.push(Ce.close),this}build(){return{verbs:Uint8Array.from(this.verbs),points:Float32Array.from(this.pts)}}};function Gs(e,t){let n=new Float32Array(e.points.length);for(let r=0;r<n.length;r+=2){let s=e.points[r],i=e.points[r+1];n[r]=t[0]*s+t[2]*i+t[4],n[r+1]=t[1]*s+t[3]*i+t[5]}return{verbs:e.verbs,points:n}}function et(e){let t=1/0,n=1/0,r=-1/0,s=-1/0;for(let i=0;i<e.points.length;i+=2)t=Math.min(t,e.points[i]),r=Math.max(r,e.points[i]),n=Math.min(n,e.points[i+1]),s=Math.max(s,e.points[i+1]);return Number.isFinite(t)?[t,n,r,s]:[0,0,0,0]}function Xl(e){return e.op??(e.cut?"cut":"union")}function Zl(e){if(e.matrix)return{m:e.matrix,tile:e.tile??"clamp"};let{sx:t,sy:n,ox:r,oy:s,tile:i}=Ql(e);return{m:[t,0,0,n,r,s],tile:i}}function Ql(e){let[t,n,r,s]=e.box,i=e.image.width,a=e.image.height,o=e.fit??"fill";if(o==="stretch")return{sx:r/i,sy:s/a,ox:t,oy:n,tile:"clamp"};if(o==="tile")return{sx:1,sy:1,ox:t,oy:n,tile:"repeat"};let l=o==="fill"?Math.max(r/i,s/a):Math.min(r/i,s/a);return{sx:l,sy:l,ox:t+(r-i*l)/2,oy:n+(s-a*l)/2,tile:o==="fill"?"clamp":"decal"}}var Me={CREATE:1,DESTROY:2,CHILDREN:3,TRANSFORM:4,SIZE:5,RADII:6,FILL:7,STROKE:8,SHADOWS:9,OPACITY:10,BLEND:11,CLIP:12,FILTER:13,PATH:14,MEMBERS:15,MASK:16,TEXT:17,EFFECTS:18,TRANSFORM3:19,DEF_PAINT:20,DEF_PATH:21,DEF_DASH:22,FREE_PATH:24,ROOT:30,VIEWPORT:31},ft=4294967295,ec=class{sink;memory;u32;f32;pos=0;cap=0;written=0;constructor(e,t){this.sink=e,this.memory=t,this.refresh(0)}refresh(e){let t=this.sink.delta_buffer(e);this.cap=this.sink.delta_capacity(),this.u32=new Uint32Array(this.memory.buffer,t,this.cap),this.f32=new Float32Array(this.memory.buffer,t,this.cap)}begin(e){this.u32.buffer!==this.memory.buffer&&this.refresh(0),this.pos+e>this.cap&&(this.flush(),e>this.cap&&this.refresh(e))}u(e){this.u32[this.pos++]=e>>>0}f(e){this.f32[this.pos++]=e}flush(){this.pos>0&&(this.written+=this.pos,this.sink.apply(this.pos),this.pos=0),this.u32.buffer!==this.memory.buffer&&this.refresh(0)}takeCount(){let e=this.written;return this.written=0,e}},tc=le({MAX_PARAMS:()=>64,definePort:()=>ce,fieldFloats:()=>Ui,layout:()=>Wi}),zs={f32:1,vec2f:2,vec3f:3,vec4f:4},Ui=e=>typeof e=="string"?zs[e]:e.array*zs[e.of],ji={number:"f32",boolean:"f32",enum:"f32",color:"vec4f",vec2:"vec2f",axis:"vec2f"};function nc(e,t){switch(e.kind){case"number":return t;case"boolean":return t?1:0;case"enum":return Math.max(0,e.options.indexOf(t));case"color":return xt(t);case"vec2":{let n=t;return[n.x,n.y]}case"axis":{let n=vt(t);return[n.x,n.y]}default:throw new Error(`effect param "${e.name}" (${e.kind}) has no default encoding; give it a value()`)}}function Ni(e,t){let n=Mo(e)?.params.find(r=>r.name===t);if(!n)throw new Error(`effect "${e}": "${t}" is not a parameter of its core spec`);if(!ji[n.kind])throw new Error(`effect "${e}": "${t}" (${n.kind}) has no default encoding`);return n}function Wi(e){let t=0,n=Object.entries(e.params).map(([r,s])=>{let i=s==="param"?ji[Ni(e.type,r).kind]:s.type,a=Ui(i),o={name:r,type:i,offset:t,floats:a};return t+=a,o});if(t>64)throw new Error(`effect "${e.type}" lays out ${t} params; a pass takes 64`);return n}function ce(e){let t=Wi(e),n=t.reduce((s,i)=>s+i.floats,0),r=t.map(s=>{let i=e.params[s.name];if(i!=="param")return i.value;let a=Ni(e.type,s.name);return o=>nc(a,o[s.name])});return{type:e.type,surface:e.surface,backdropOnly:e.backdropOnly,spec:e,cases:e.cases,pack(s){let i=e.prepare?e.prepare(s):{};if(i===null)return null;let a=new Array(n).fill(0);return t.forEach((o,l)=>{let c=r[l](s,i),u=typeof c=="number"?1:c.length;if(u>o.floats)throw new Error(`effect "${e.type}": "${o.name}" is ${u} floats, laid out as ${o.floats}`);if(typeof c=="number")a[o.offset]=c;else for(let f=0;f<u;f++)a[o.offset+f]=c[f]}),{params:a,...e.extras?e.extras(s,i):{}}}}}var rc=le({default:()=>sc}),sc=ce({type:"alpha",surface:"filter",params:{matrix:{type:{array:20,of:"f32"},value:e=>[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,Math.max(0,Math.min(1,e.amount)),0]}},cases:()=>[]}),ic=le({default:()=>uc}),ac="Inter",oc=e=>typeof document<"u"&&document.fonts.check(`12px "${e}"`),lc=e=>Math.max(4,Math.min(64,Math.round(Math.max(8,e*2)))),Qe=1;function cc(e,t,n){let r=[...e].slice(0,256),s=n*Qe,i=new OffscreenCanvas(s*r.length,s),a=i.getContext("2d",{willReadFrequently:!0});a.fillStyle="#000",a.fillRect(0,0,i.width,i.height),a.fillStyle="#fff",a.font=`${n*.8*Qe}px "${t}"`,a.textBaseline="alphabetic",a.textAlign="left",a.fontKerning="none",r.forEach((u,f)=>{let d=a.measureText(u).width;a.fillText(u,f*s+(s-d)/2,s*.78)});let o=a.getImageData(0,0,i.width,i.height).data,l=n*r.length,c=new Uint8ClampedArray(l*n*4);for(let u=0;u<n;u++)for(let f=0;f<l;f++){let d=0;for(let w=0;w<Qe;w++)for(let R=0;R<Qe;R++)d+=o[((u*Qe+w)*i.width+f*Qe+R)*4];let _=d/(Qe*Qe),p=(u*l+f)*4;c[p]=c[p+1]=c[p+2]=_,c[p+3]=255}return{glyphs:r.length,pixels:c,width:l}}var uc=ce({type:"ascii",surface:"shader",params:{size:"param",glyphs:{type:"f32",uses:["charset","fontFamily"],value:(e,t)=>t.atlas.glyphs},cell:{type:"f32",value:(e,t)=>t.cell},ink:"param",background:"param",colored:"param"},prepare(e){let t=Ro(e.charset);if(t.length===0)return null;let n=oc(e.fontFamily)?e.fontFamily:ac,r=lc(e.size);return{family:n,cell:r,charset:t,atlas:cc(t,n,r)}},extras:(e,t)=>({aux:{key:`ascii|${t.family}|${t.cell}|${t.charset}`,width:t.atlas.width,height:t.cell,pixels:t.atlas.pixels}}),cases:()=>[A.ascii().list[0],A.ascii({size:10,charset:"hex",fontFamily:"Fira Mono",ink:"#6f6",background:"#001",colored:!1}).list[0],A.ascii({size:14,colored:!0,background:"transparent",ink:"white"}).list[0],A.ascii({size:8,ink:"black",background:"white",charset:" .oO@"}).list[0]]}),fc=le({default:()=>_c}),dc={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"]},hc=e=>{let t=parseInt(e.slice(1),16);return[16,8,0].map(n=>Number(((t>>n&255)/255).toFixed(4)))},_c=ce({type:"bitCrush",surface:"shader",params:{bits:"param",amount:"param",count:{type:"f32",uses:["palette"],value:(e,t)=>t.palette.length},palette:{type:{array:16,of:"vec3f"},value:(e,t)=>t.palette.flatMap(hc)}},prepare(e){return!(e.amount>0)||e.palette==="none"&&e.bits>=8?null:{palette:e.palette==="none"?[]:dc[e.palette]}},cases:()=>[A.bitCrush().list[0],A.bitCrush({palette:"gameboy"}).list[0],A.bitCrush({palette:"nes",amount:.7}).list[0],A.bitCrush({palette:"cga"}).list[0]]}),pc=le({default:()=>mc}),mc=ce({type:"blockDisplace",surface:"shader",params:{amount:"param",size:"param",density:"param",seed:"param",axis:"param"},prepare(e){if(!(e.amount>0)||!(e.density>0))return null;let t=vt(e.axis);return t.x===0&&t.y===0?null:{}},extras(e){let t=vt(e.axis);return{reach:e.amount*Math.max(Math.abs(t.x),Math.abs(t.y))}},cases:()=>[A.blockDisplace().list[0],A.blockDisplace({amount:40,size:10,density:.6,seed:3}).list[0],A.blockDisplace({amount:30,size:24,axis:"y",seed:1}).list[0]]}),gc=le({default:()=>bc}),bc=ce({type:"bloom",surface:"filter",params:{scale:{type:"f32",uses:["threshold"],value:(e,t)=>t.scale},bias:{type:"f32",value:(e,t)=>-t.t*t.scale},intensity:"param"},uses:["radius"],prepare(e){if(e.radius<=0||e.intensity<=0)return null;let t=Math.max(0,Math.min(1,e.threshold));return{t,scale:t<1?1/(1-t):1,sigma:e.radius/2}},extras:(e,t)=>({blur:[t.sigma,t.sigma,0],reach:3*t.sigma}),cases:()=>[A.bloom().list[0],A.bloom({threshold:.4,radius:24,intensity:1.5}).list[0],A.bloom({threshold:0,radius:6,intensity:.6}).list[0]]}),wc=le({default:()=>yc}),yc=ce({type:"blur",surface:"filter",params:{},uses:["radius"],prepare:e=>e.radius>0?{}:null,extras(e){let t=e.radius/2;return{blur:[t,t,0],reach:3*t}},cases:()=>[A.blur(8).list[0],A.blur(24).list[0],A.blur(2).list[0]]}),vc=le({default:()=>xc}),xc=ce({type:"bulge",surface:"shader",params:{strength:"param",center:"param"},prepare:e=>e.strength===0?null:{},extras(e){let t=2*Math.hypot(e.center.x-.5,e.center.y-.5)*360;if(e.strength<0){let n=e.strength*.8,r=1;for(;r<4&&r*(1+n*r*r)/(1+n)>-1;)r+=.01;t=Math.min((r-1+2*Math.hypot(e.center.x-.5,e.center.y-.5))*360,800)}return{reach:t}},cases:()=>[A.bulge(.6).list[0],A.bulge(-.7).list[0],A.bulge({strength:.9,center:{x:.3,y:.6}}).list[0]]}),kc=le({default:()=>Ac}),Mc=[1.4,-.2,-.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],Sc=[0,0,0,0,0,0,0,0,0,0,-.2,-.2,1.4,0,0,0,0,0,1,0],Ac=ce({type:"chromaticAberration",surface:"filter",params:{red:{type:{array:20,of:"f32"},value:()=>Mc},blue:{type:{array:20,of:"f32"},value:()=>Sc},offset:{type:"vec2f",uses:["amount","angle"],value(e){let t=e.angle*Math.PI/180;return[Math.cos(t)*e.amount,Math.sin(t)*e.amount]}}},prepare:e=>e.amount<=0?null:{},extras:e=>({reach:e.amount}),cases:()=>[A.chromaticAberration().list[0],A.chromaticAberration({amount:8,angle:45}).list[0],A.chromaticAberration({amount:2.5,angle:200}).list[0]]}),Ec=le({default:()=>Ic}),bt=.2126,tt=.7152,Ze=.0722;function Tc(e,t){let n=new Array(20).fill(0);for(let r=0;r<4;r++)for(let s=0;s<5;s++){let i=0;for(let a=0;a<4;a++)i+=e[r*5+a]*t[a*5+s];s===4&&(i+=e[r*5+4]),n[r*5+s]=i}return n}var Yt=(e,t)=>[e,0,0,0,t,0,e,0,0,t,0,0,e,0,t,0,0,0,1,0],Hs=(e,t,n)=>[1,0,0,0,e,0,1,0,0,t,0,0,1,0,n,0,0,0,1,0];function Ks(e){let t=1-e;return[e+t*bt,t*tt,t*Ze,0,0,t*bt,e+t*tt,t*Ze,0,0,t*bt,t*tt,e+t*Ze,0,0,0,0,0,1,0]}function Pc(e){let t=e*Math.PI/180,n=Math.cos(t),r=Math.sin(t);return[bt+n*(1-bt)+r*-.2126,tt+n*-.7152+r*-.7152,Ze+n*-.0722+r*(1-Ze),0,0,bt+n*-.2126+r*.143,tt+n*(1-tt)+r*.14,Ze+n*-.0722+r*-.283,0,0,bt+n*-.2126+r*-.7874,tt+n*-.7152+r*tt,Ze+n*(1-Ze)+r*Ze,0,0,0,0,0,1,0]}var Ic=ce({type:"colorAdjustment",surface:"filter",params:{matrix:{type:{array:20,of:"f32"},uses:["brightness","contrast","saturation","hue","vibrance","temperature","tint","shadows","highlights"],value:(e,t)=>t.matrix}},prepare(e){let t=Yt(1,0),n=!1,r=_=>{t=Tc(_,t),n=!0},s=e.brightness??0;s!==0&&r(Yt(1,s));let i=e.contrast??1;i!==1&&r(Yt(i,.5*(1-i)));let a=e.saturation??1;a!==1&&r(Ks(a));let o=((e.hue??0)%360+360)%360;o!==0&&r(Pc(o));let l=e.vibrance??0;l!==0&&r(Ks(1+l*.7));let c=e.temperature??0;c!==0&&r(Hs(c*.1,0,-c*.1));let u=e.tint??0;u!==0&&r(Hs(u*.05,-u*.1,u*.05));let f=e.shadows??0;f!==0&&r(Yt(1-.2*f,.2*f));let d=e.highlights??0;return d!==0&&r(Yt(1+.2*d,-.1*d)),n?{matrix:t}:null},cases:()=>[A.colorAdjustment({brightness:.1,contrast:1.3,saturation:1.4}).list[0],A.colorAdjustment({hue:120,vibrance:.5}).list[0],A.colorAdjustment({temperature:.6,tint:-.4,shadows:.5,highlights:-.5}).list[0],A.colorAdjustment({contrast:.6,saturation:0}).list[0]]}),Rc=le({default:()=>Cc}),Cc=ce({type:"colorMatrix",surface:"filter",params:{matrix:{type:{array:20,of:"f32"},value:e=>Array.from(e.matrix).slice(0,20)}},cases:()=>[]}),Oc=le({default:()=>Fc}),$n=32;function $c(e,t){if(e.length===0)return t;if(t<=e[0][0])return e[0][1];let n=e[e.length-1];if(t>=n[0])return n[1];for(let r=0;r<e.length-1;r++){let[s,i]=e[r],[a,o]=e[r+1];if(t>=s&&t<=a)return i+(o-i)*(a===s?0:(t-s)/(a-s))}return t}function Dc(e){let t=[...e].sort((r,s)=>r[0]-s[0]),n=[];for(let r=0;r<=$n;r++){let s=$c(t,r/$n);n.push(Number.isFinite(s)?Math.max(0,Math.min(1,s)):r/$n)}return n}var Lc={r:[1,0,0,0],g:[0,1,0,0],b:[0,0,1,0],a:[0,0,0,1]},Fc=ce({type:"curves",surface:"shader",params:{mask:{type:"vec4f",uses:["channel"],value:e=>Lc[e.channel??"rgb"]??[1,1,1,0]},curve:{type:{array:33,of:"f32"},uses:["points"],value:(e,t)=>t.values}},prepare(e){let t=Dc(e.points??[]);return t.every((n,r)=>Math.abs(n-r/$n)<1e-4)?null:{values:t}},cases:()=>[A.curves({points:[[0,0],[.25,.15],[.75,.88],[1,1]]}).list[0],A.curves({points:[[0,.2],[.5,.7],[1,1]],channel:"r"}).list[0],A.curves({points:[[0,0],[.6,.3],[1,.8]],channel:"a"}).list[0]]}),Bc=le({default:()=>Uc}),Uc=ce({type:"directionalBlur",surface:"filter",params:{sigma:{type:"f32",uses:["radius"],value:(e,t)=>t.sigma},axis:{type:"vec2f",uses:["angle"],value:(e,t)=>[Math.cos(t.rad),Math.sin(t.rad)]}},prepare:e=>e.radius<=0?null:{sigma:e.radius/2,rad:e.angle*Math.PI/180},extras:(e,t)=>({blur:[t.sigma,0,t.rad],reach:3*t.sigma}),cases:()=>[A.directionalBlur(20).list[0],A.directionalBlur({radius:30,angle:45}).list[0],A.directionalBlur({radius:12,angle:100}).list[0],A.directionalBlur({radius:120,angle:-20}).list[0]]}),jc=le({default:()=>Gc}),Nc="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==",Wc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ot=64,_r=null;function Vc(){if(_r)return _r;let e=Nc.replace(/[^A-Za-z0-9+/]/g,""),t=new Uint8Array(e.length*3>>2),n=0,r=0,s=0;for(let a=0;a<e.length;a++)n=n<<6|Wc.indexOf(e[a]),r+=6,r>=8&&(r-=8,t[s++]=n>>r&255);let i=new Uint8ClampedArray(Ot*Ot*4);for(let a=0;a<Ot*Ot;a++)i.fill(t[a],a*4,a*4+3),i[a*4+3]=255;return _r=i}var Gc=ce({type:"dither",surface:"shader",params:{levels:"param",scale:"param",monochrome:"param",noise:"param",matrix:{type:"f32",value:e=>e.matrix}},prepare:e=>e.levels>=256?null:{},extras:e=>({aux:e.noise==="blue"?{key:"dither-blue-noise",width:Ot,height:Ot,pixels:Vc()}:void 0}),cases:()=>[A.dither().list[0],A.dither({levels:4,matrix:8,scale:2,monochrome:!0}).list[0],A.dither({noise:"blue",levels:3}).list[0],A.dither({matrix:2,levels:6,scale:3}).list[0]]}),zc=le({default:()=>Hc}),Hc=ce({type:"dropShadow",surface:"shader",params:{offset:{type:"vec2f",uses:["offsetX","offsetY"],value:(e,t)=>[t.ox,t.oy]},sigma:{type:"f32",uses:["blur"],value:(e,t)=>t.sigma},color:"param",spread:{type:"f32",value:(e,t)=>t.spread}},prepare(e){if(xt(e.color)[3]<=0)return null;let t=e.offsetX,n=-e.offsetY,r=Math.max(0,e.blur)/2,s=Math.max(0,e.spread);return t===0&&n===0&&r===0&&s===0?null:{ox:t,oy:n,sigma:r,spread:s}},extras:(e,t)=>({reach:Math.hypot(t.ox,t.oy)+3*t.sigma+t.spread}),cases:()=>[A.dropShadow().list[0],A.dropShadow({offsetX:10,offsetY:10,blur:24,color:"#0008"}).list[0],A.dropShadow({offsetX:0,offsetY:0,blur:0,spread:6,color:"#f40"}).list[0],A.dropShadow({offsetX:-12,offsetY:-6,blur:40,spread:4,color:"#04f"}).list[0]]}),Kc=le({default:()=>Xc}),qc=.2126,Jc=.7152,Yc=.0722,Xc=ce({type:"duotone",surface:"filter",params:{matrix:{type:{array:20,of:"f32"},uses:["amount","shadows","highlights"],value(e){let t=Math.max(0,Math.min(1,e.amount)),n=xt(e.shadows),r=xt(e.highlights),s=i=>{let a=(r[i]-n[i])*t,o=[a*qc,a*Jc,a*Yc,0,n[i]*t];return o[i]+=1-t,o};return[...s(0),...s(1),...s(2),0,0,0,1,0]}}},prepare:e=>e.amount<=0?null:{},cases:()=>[A.duotone().list[0],A.duotone({shadows:"#1a0b3d",highlights:"#ffcc66"}).list[0],A.duotone({amount:.5,shadows:"#003344",highlights:"#ff6699"}).list[0]]}),Zc=le({default:()=>Qc}),Qc=ce({type:"edges",surface:"shader",params:{strength:"param",kernel:"param",colored:"param"},prepare:e=>e.strength>0?{}:null,extras:()=>({reach:1}),cases:()=>[A.edges().list[0],A.edges({strength:2,kernel:"prewitt",colored:!0}).list[0],A.edges({strength:1.5,kernel:"laplacian"}).list[0]]}),eu=le({default:()=>tu}),tu=ce({type:"exposure",surface:"filter",params:{matrix:{type:{array:20,of:"f32"},value:e=>[e.amount,0,0,0,0,0,e.amount,0,0,0,0,0,e.amount,0,0,0,0,0,1,0]}},cases:()=>[]}),nu=le({default:()=>cu}),qs=e=>Math.min(1,Math.max(0,e)),ru=.35,su=1,iu=.1,au=.06,ou=.7,lu=.3,Js=.25,cu=ce({type:"glass",surface:"shader",backdropOnly:!0,params:{depth:"param",refraction:{type:"f32",value:e=>Math.max(0,e.refraction/100)},spread:{type:"f32",uses:["dispersion"],value:e=>qs(e.dispersion/100)*ru},light:{type:"vec2f",uses:["lightAngle"],value(e){let t=e.lightAngle*Math.PI/180;return[Math.sin(t),-Math.cos(t)]}},rim:{type:"f32",uses:["lightIntensity"],value:(e,t)=>t.light*su},shade_near:{type:"f32",uses:["splay"],value:(e,t)=>t.light*iu*(1-Js*t.splay)},shade_far:{type:"f32",value:(e,t)=>t.light*au*(1-Js*t.splay)},shade_reach:{type:"f32",value:(e,t)=>ou+lu*t.splay},frost:{type:"f32",value:(e,t)=>t.frost}},prepare(e){return e.depth>0?{light:Math.max(0,e.lightIntensity/100),splay:qs(e.splay/100),frost:Math.max(0,e.frost)*.5}:null},extras:(e,t)=>({reach:3*t.frost+2,blur:t.frost>0?[t.frost,t.frost,0]:void 0,field:!0}),cases:()=>[A.glass().list[0],A.glass({dispersion:0,frost:0,depth:30}).list[0]]}),uu=le({default:()=>du}),fu=["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],du=ce({type:"glow",surface:"shader",params:{channel:"param",threshold:"param",spread:{type:"f32",value:e=>Math.max(0,e.spread)},intensity:"param",tint:"param",original:"param",blend:{type:"f32",value:e=>Math.max(0,fu.indexOf(e.blend))},count:{type:"f32",value:(e,t)=>t.colors.length},cycles:"param",phase:{type:"f32",value:e=>e.phase/360},mirror:{type:"f32",uses:["loopStyle"],value:e=>e.loopStyle==="mirror"?1:0},stops:{type:{array:8,of:"f32"},value(e,t){let n=[],r=0;for(let s=0;s<t.colors.length;s++)r=Math.max(r,Math.min(1,e.stops[s]??s/Math.max(1,t.colors.length-1))),n.push(r);return n}},colors:{type:{array:8,of:"vec4f"},uses:["color"],value:(e,t)=>t.colors.flatMap(n=>xt(n))}},uses:["radius","axis"],prepare(e){return e.radius<=0&&e.spread<=0||e.intensity<=0?null:{colors:(e.tint==="solid"?[e.color]:e.colors).slice(0,8)}},extras(e){let t=vt(e.axis),n=Math.max(0,e.radius)/2;return{blur:[n*t.x,n*t.y,0],reach:3*n+Math.max(0,e.spread)}},cases:()=>[A.glow().list[0],A.glow({radius:12,threshold:.3,intensity:1.5,original:"front"}).list[0],A.glow({channel:"alpha",radius:20,spread:4,tint:"solid",color:"#4cf"}).list[0],A.glow({radius:30,tint:"ramp",colors:["#ff3","#f0f","#0ff"],stops:[0,.5,1],blend:"lighten"}).list[0]]}),hu=le({default:()=>_u}),_u=ce({type:"grain",surface:"shader",params:{amount:"param",size:"param",seed:"param",colored:"param",animated:"param"},prepare:e=>e.amount>0?{}:null,cases:()=>[A.grain().list[0],A.grain({amount:.5,size:3,seed:7,colored:!0}).list[0],A.grain({amount:.15,size:2}).list[0]]}),pu=le({default:()=>mu}),pr=.2126,mr=.7152,gr=.0722,mu=ce({type:"grayscale",surface:"filter",params:{matrix:{type:{array:20,of:"f32"},uses:["amount"],value(e){let t=Math.max(0,Math.min(1,e.amount));return[1-t+t*pr,t*mr,t*gr,0,0,t*pr,1-t+t*mr,t*gr,0,0,t*pr,t*mr,1-t+t*gr,0,0,0,0,0,1,0]}}},cases:()=>[A.grayscale(1).list[0],A.grayscale(.5).list[0]]}),gu=le({default:()=>bu}),bu=ce({type:"halftone",surface:"shader",params:{size:"param",angle:{type:"f32",value:e=>e.angle*Math.PI/180},shape:"param",separation:"param"},extras:e=>({reach:e.size}),cases:()=>[A.halftone().list[0],A.halftone({size:10,angle:20,shape:"line",separation:"rgb"}).list[0],A.halftone({size:12,shape:"cross",separation:"cmyk"}).list[0]]}),wu=le({default:()=>xu}),Pt=.2126,It=.7152,Rt=.0722,yu=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];function vu(e){switch(e){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*Pt-1,2*It,2*Rt,0,0,2*Pt,2*It-1,2*Rt,0,0,2*Pt,2*It,2*Rt-1,0,0,0,0,0,1,0];case"luminance":return[1-2*Pt,-2*It,-2*Rt,0,1,-2*Pt,1-2*It,-2*Rt,0,1,-2*Pt,-2*It,1-2*Rt,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 xu=ce({type:"invert",surface:"filter",params:{matrix:{type:{array:20,of:"f32"},uses:["channel","strength"],value:(e,t)=>t.matrix}},prepare(e){let t=Math.max(0,Math.min(1,e.strength));if(t===0)return null;let n=vu(e.channel);return{matrix:yu.map((r,s)=>r+(n[s]-r)*t)}},extras:(e,t)=>t.matrix[19]>0?{reach:4096}:{},cases:()=>[A.invert().list[0],A.invert({channel:"hue",strength:.7}).list[0],A.invert({channel:"luminance"}).list[0],A.invert({channel:"alpha",strength:.5}).list[0]]}),ku=le({default:()=>Mu}),Mu=ce({type:"kaleidoscope",surface:"shader",params:{wedge:{type:"f32",uses:["segments"],value:(e,t)=>2*Math.PI/t.segments},angle:{type:"f32",value:e=>e.angle*Math.PI/180},offset:"param",amount:{type:"f32",value:e=>Math.max(0,Math.min(1,e.amount))},center:"param"},prepare(e){let t=Math.round(e.segments);return t<2||e.amount<=0?null:{segments:t}},extras:e=>({reach:Math.min((Math.SQRT2-1+Math.abs(e.offset)+2*Math.hypot(e.center.x-.5,e.center.y-.5))*360,800)}),cases:()=>[A.kaleidoscope().list[0],A.kaleidoscope({segments:8,angle:20,offset:.15}).list[0],A.kaleidoscope({segments:3,amount:.6,center:{x:.4,y:.55}}).list[0]]}),Su=le({default:()=>Tu}),Ys=new WeakMap,Au=0,br=e=>Number.isFinite(e)?Math.max(0,Math.min(255,Math.round(e*255))):0;function Eu(e,t){let n=Ys.get(e);if(n&&n.height===t)return n;let r=t*t,s=new Uint8ClampedArray(r*t*4);for(let a=0;a<t;a++)for(let o=0;o<t;o++)for(let l=0;l<t;l++){let c=((a*t+o)*t+l)*3,u=(o*r+a*t+l)*4;s[u+3]=255,!(c+2>=e.length)&&(s[u]=br(e[c]),s[u+1]=br(e[c+1]),s[u+2]=br(e[c+2]))}let i={key:`lut-${Au++}`,width:r,height:t,pixels:s};return Ys.set(e,i),i}function Xs(e){let t=new Float32Array(e*e*e*3);for(let n=0;n<e;n++)for(let r=0;r<e;r++)for(let s=0;s<e;s++){let[i,a,o]=[s/(e-1),r/(e-1),n/(e-1)],l=((n*e+r)*e+s)*3;t[l]=.05+.95*Math.pow(i,.8),t[l+1]=.85*a+.1*o+.03,t[l+2]=1-Math.pow(1-o,1.4)*.9-.08*i}return t}var wr=null,Tu=ce({type:"lut",surface:"shader",params:{size:"param",amount:"param"},uses:["table"],prepare:e=>e.amount<=0||!Number.isInteger(e.size)||e.size<2?null:{},extras:e=>({aux:Eu(e.table,e.size)}),cases:()=>(wr??=[Xs(17),Xs(33)],[A.lut({table:wr[1],size:33}).list[0],A.lut({table:wr[0],size:17,amount:.6}).list[0]])}),Pu=le({default:()=>Iu}),Iu=ce({type:"magnify",surface:"shader",backdropOnly:!0,params:{scale:"param",center:"param"},prepare:e=>e.scale===1||e.scale<=0?null:{},extras:e=>({reach:e.scale<1?Math.min((1/e.scale-1)*360,800):0}),cases:()=>[A.magnify({scale:2}).list[0],A.magnify({scale:1.6,center:{x:.3,y:.7}}).list[0]]}),Ru=le({default:()=>Cu}),Cu=ce({type:"oilPaint",surface:"shader",params:{radius:"param"},prepare:e=>e.radius>0?{}:null,extras:e=>({reach:e.radius}),cases:()=>[A.oilPaint().list[0],A.oilPaint({radius:5}).list[0],A.oilPaint({radius:1.5}).list[0]]}),Ou=le({default:()=>Du}),$u={outside:0,inside:1,center:2},Du=ce({type:"outline",surface:"shader",params:{width:"param",position:{type:"f32",value:(e,t)=>t.position},color:"param"},prepare(e){return!(e.width>0)||xt(e.color)[3]<=0?null:{position:$u[e.position]??0}},extras:(e,t)=>({reach:t.position===1?0:t.position===2?e.width/2:e.width}),cases:()=>[A.outline().list[0],A.outline({width:8,color:"#f80",position:"inside"}).list[0],A.outline({width:6,color:"#0cf",position:"center"}).list[0]]}),Lu=le({default:()=>Fu}),Fu=ce({type:"pixelate",surface:"filter",params:{blocks:"param",sharpColors:"param"},extras:e=>({reach:e.sharpColors?0:100}),cases:()=>[A.pixelate(40).list[0],A.pixelate({blocks:{x:40,y:24},sharpColors:!1}).list[0],A.pixelate({blocks:{x:12.5,y:40/3}}).list[0]]}),Bu=le({default:()=>Uu}),Uu=ce({type:"posterize",surface:"shader",params:{levels:"param"},prepare:e=>e.levels<2?null:{},cases:()=>[A.posterize().list[0],A.posterize(2).list[0],A.posterize(7).list[0]]}),ju=le({default:()=>Nu}),Nu=ce({type:"progressiveBlur",surface:"shader",params:{center:"param",direction:{type:"vec2f",uses:["angle"],value(e){let t=e.angle*Math.PI/180;return[Math.cos(t),Math.sin(t)]}},radius:"param",start_radius:{type:"f32",uses:["startRadius"],value:(e,t)=>t.start0},start:"param",end:"param",shape:"param",samples:{type:"f32",value:e=>Math.max(2,Math.min(32,Math.round(e.samples)))}},prepare(e){let t=e.startRadius??0;return e.radius<=0&&t<=0?null:{start0:t}},extras:(e,t)=>({reach:Math.max(e.radius,t.start0,0)}),cases:()=>[A.progressiveBlur().list[0],A.progressiveBlur({radius:30,angle:0,start:.3,end:.9,samples:28}).list[0],A.progressiveBlur({radius:28,startRadius:4,shape:"radial",center:{x:.4,y:.5}}).list[0]]}),Wu=le({default:()=>Vu}),Vu=ce({type:"radialBlur",surface:"shader",params:{amount:"param",style:"param",center:"param",samples:{type:"f32",value:e=>Math.round(Math.max(2,Math.min(32,e.samples)))}},prepare:e=>e.amount>0?{}:null,extras(e){let t=e.style==="spin"?Math.SQRT2-1:1/Math.max(1-e.amount/2,.25)-1;return{reach:Math.min((t+2*Math.hypot(e.center.x-.5,e.center.y-.5))*360,800)}},cases:()=>[A.radialBlur().list[0],A.radialBlur({amount:.8,style:"spin",samples:24}).list[0],A.radialBlur({amount:.3,center:{x:.3,y:.4},samples:8}).list[0]]}),Gu=le({default:()=>zu}),zu=ce({type:"rgbShift",surface:"shader",params:{red:"param",green:"param",blue:"param"},prepare(e){let{red:t,green:n,blue:r}=e;return!t.x&&!t.y&&!n.x&&!n.y&&!r.x&&!r.y?null:{}},extras:({red:e,green:t,blue:n})=>({reach:Math.max(Math.abs(e.x),Math.abs(e.y),Math.abs(t.x),Math.abs(t.y),Math.abs(n.x),Math.abs(n.y))}),cases:()=>[A.rgbShift().list[0],A.rgbShift({amount:12}).list[0],A.rgbShift({red:{x:6,y:-4},green:{x:-3,y:5},blue:{x:0,y:9}}).list[0]]}),Hu=le({default:()=>Ku}),Ku=ce({type:"scanlines",surface:"shader",params:{spacing:"param",thickness:"param",darkness:"param",offset:"param",direction:{type:"vec2f",uses:["angle"],value(e){let t=e.angle*Math.PI/180;return[Math.cos(t),Math.sin(t)]}}},prepare:e=>e.darkness>0?{}:null,cases:()=>[A.scanlines().list[0],A.scanlines({spacing:7,thickness:.3,darkness:.8,offset:2,angle:30}).list[0],A.scanlines({spacing:5,thickness:.7,angle:90}).list[0]]}),qu=le({default:()=>Ju}),Ju=ce({type:"scatter",surface:"shader",params:{offset:{type:"vec2f",uses:["strength","axis"],value(e){let t=vt(e.axis);return[e.strength*t.x,e.strength*t.y]}}},prepare:e=>e.strength>0?{}:null,extras(e){let t=vt(e.axis);return{reach:e.strength*Math.max(Math.abs(t.x),Math.abs(t.y))}},cases:()=>[A.scatter().list[0],A.scatter({strength:24,axis:"x"}).list[0],A.scatter({strength:6,axis:"y"}).list[0]]}),Yu=le({default:()=>Xu}),Xu=ce({type:"sharpen",surface:"shader",params:{amount:"param",radius:{type:"f32",value:e=>Math.max(e.radius,0)}},prepare:e=>e.amount===0?null:{},cases:()=>[A.sharpen().list[0],A.sharpen({amount:2.5,radius:3}).list[0]]}),Zu=le({default:()=>Qu}),Qu=ce({type:"streak",surface:"filter",params:{scale:{type:"f32",uses:["threshold"],value:(e,t)=>t.scale},bias:{type:"f32",value:(e,t)=>-t.t*t.scale},intensity:"param",sigma:{type:"f32",uses:["length"],value:(e,t)=>t.sigma},axis:{type:"vec2f",uses:["angle"],value:(e,t)=>[Math.cos(t.rad),Math.sin(t.rad)]}},prepare(e){if(e.intensity<=0||e.length<=0)return null;let t=Math.max(0,Math.min(1,e.threshold));return{t,scale:t<1?1/(1-t):1,sigma:e.length/2,rad:e.angle*Math.PI/180}},extras:(e,t)=>({blur:[t.sigma,.01,t.rad],reach:3*t.sigma}),cases:()=>[A.streak().list[0],A.streak({angle:30,length:80,threshold:.5,intensity:1.5}).list[0],A.streak({angle:90,length:60,threshold:.3,intensity:.7}).list[0]]}),ef=le({default:()=>tf}),tf=ce({type:"threshold",surface:"shader",params:{level:"param",smoothness:"param"},cases:()=>[A.threshold().list[0],A.threshold({level:.3,smoothness:0}).list[0],A.threshold({level:.6,smoothness:.4}).list[0]]}),nf=le({default:()=>rf}),rf=ce({type:"twirl",surface:"shader",params:{angle:{type:"f32",value:e=>e.angle*Math.PI/180},radius:"param",center:"param"},prepare:e=>e.angle===0||e.radius<=0?null:{},extras(e){let t=Math.min(e.radius,Math.SQRT2);return{reach:Math.min((Math.max(t-1,0)+2*Math.hypot(e.center.x-.5,e.center.y-.5))*360,800)}},cases:()=>[A.twirl().list[0],A.twirl({angle:-120,radius:.6}).list[0],A.twirl({angle:300,radius:1.4,center:{x:.35,y:.55}}).list[0]]}),sf=le({default:()=>af}),af=ce({type:"vignette",surface:"shader",params:{color:"param",amount:"param",radius:"param",softness:"param"},prepare:e=>e.amount<=0||xt(e.color)[3]<=0?null:{},cases:()=>[A.vignette().list[0],A.vignette({amount:.9,radius:.4,softness:.3}).list[0],A.vignette({amount:.7,color:"#ff8800",radius:.6,softness:.8}).list[0]]}),of=le({default:()=>lf}),lf=ce({type:"vintage",surface:"filter",params:{matrix:{type:{array:20,of:"f32"},uses:["amount","warmth"],value(e){let t=Math.max(0,Math.min(1,e.amount)),n=Math.max(-1,Math.min(1,e.warmth)),r=(l,c)=>l+(c-l)*t,s=n>0?n*.15:0,i=n<0?-n*.15:0,a=n<0?-n*.05:0,o=n>0?n*.05:0;return[r(1,.393),r(0,.769),r(0,.189),0,s-a,r(0,.349),r(1,.686),r(0,.168),0,0,r(0,.272),r(0,.534),r(1,.131),0,-i+o,0,0,0,1,0]}}},prepare:e=>e.amount<=0&&e.warmth===0?null:{},cases:()=>[A.vintage().list[0],A.vintage({amount:.5,warmth:-.8}).list[0],A.vintage({amount:0,warmth:1}).list[0]]}),cf=le({default:()=>uf}),uf=ce({type:"wave",surface:"shader",params:{amplitude:"param",wavelength:{type:"f32",value:e=>Math.max(e.wavelength,.01)},phase:{type:"f32",value:e=>(e.phase%360+360)%360*Math.PI/180},direction:{type:"vec2f",uses:["angle"],value(e){let t=e.angle*Math.PI/180;return[Math.cos(t),Math.sin(t)]}},shape:"param",center:"param"},prepare:e=>e.amplitude.x===0&&e.amplitude.y===0?null:{},extras:e=>({reach:Math.max(Math.abs(e.amplitude.x),Math.abs(e.amplitude.y))}),cases:()=>[A.wave().list[0],A.wave({amplitude:{x:8,y:14},wavelength:60,phase:70,angle:35}).list[0],A.wave({amplitude:16,shape:"radial",wavelength:80,center:{x:.4,y:.6}}).list[0]]}),Zs=new Map(Object.entries(Object.assign({"./_pack.ts":tc,"./alpha.ts":rc,"./ascii.ts":ic,"./bitCrush.ts":fc,"./blockDisplace.ts":pc,"./bloom.ts":gc,"./blur.ts":wc,"./bulge.ts":vc,"./chromaticAberration.ts":kc,"./colorAdjustment.ts":Ec,"./colorMatrix.ts":Rc,"./curves.ts":Oc,"./directionalBlur.ts":Bc,"./dither.ts":jc,"./dropShadow.ts":zc,"./duotone.ts":Kc,"./edges.ts":Zc,"./exposure.ts":eu,"./glass.ts":nu,"./glow.ts":uu,"./grain.ts":hu,"./grayscale.ts":pu,"./halftone.ts":gu,"./invert.ts":wu,"./kaleidoscope.ts":ku,"./lut.ts":Su,"./magnify.ts":Pu,"./oilPaint.ts":Ru,"./outline.ts":Ou,"./pixelate.ts":Lu,"./posterize.ts":Bu,"./progressiveBlur.ts":ju,"./radialBlur.ts":Wu,"./rgbShift.ts":Gu,"./scanlines.ts":Hu,"./scatter.ts":qu,"./sharpen.ts":Yu,"./streak.ts":Zu,"./threshold.ts":ef,"./twirl.ts":nf,"./vignette.ts":sf,"./vintage.ts":of,"./wave.ts":cf})).filter(([e])=>!e.includes("/_")).map(([,e])=>[e.default.type,e.default])),Cr={fill:0,effect:1};function Vi(e){let t=JSON.parse(e);for(let n of t.diagnostics)n.source="naga";return t}function Gi(e,t){return Vi(hl(Cr[e],t))}function Qs(e,t,n){let r=new Uint32Array(Math.ceil(t/4)),s=new Float32Array(r.buffer),i=new Int32Array(r.buffer);for(let a of e){let o=n[a.name];if(o===void 0)continue;let l=typeof o=="number"?[o]:o.flat(1/0);for(let c=0;c<a.elements;c++)for(let u=0;u<a.components;u++){let f=l[c*a.components+u];if(f===void 0)continue;let d=a.offset+c*a.stride+u*4>>2;d>=r.length||(a.scalar===0?s[d]=f:a.scalar===1?i[d]=Math.round(f):r[d]=Math.max(0,Math.round(f)))}}return r}var ff=64,ei=1e4;function ti(e,t){let n,r=new Promise((s,i)=>{n=setTimeout(()=>i(new Error(`the browser took over ${ei/1e3} s to ${t}`)),ei)});return Promise.race([e,r]).finally(()=>clearTimeout(n))}var df=class{r;onReady;programs=new Map;nextId=0;pending=new Set;constructor(e,t){this.r=e,this.onReady=t}program(e,t){let n=`${e}
699
+ ${t}`,r=this.programs.get(n);if(r)return this.programs.delete(n),this.programs.set(n,r),r;if(this.programs.size>=ff){let[o,l]=this.programs.entries().next().value;this.programs.delete(o),l.state!=="compiling"&&this.r.shader_remove(l.id)}let s=this.nextId++,i=Vi(this.r.shader_add(s,Cr[e],t)),a={id:s,scope:e,report:i,state:i.ok?"compiling":"failed",browser:[],settled:Promise.resolve()};if(i.ok){let o=this.compile(a).finally(()=>this.pending.delete(o));this.pending.add(o),a.settled=o}return this.programs.set(n,a),a}hasPending(){return this.pending.size>0}async whenReady(){for(;this.pending.size;)await Promise.all([...this.pending])}async compile(e){let t=this.r.gpu_device(),n=e.report.wgsl;try{if(t){let r=t.createShaderModule({code:n}),s=await ti(r.getCompilationInfo(),"compile it");if(e.browser=hf(s.messages,n),s.messages.some(a=>a.type==="error")){e.state="failed",this.r.shader_remove(e.id);return}let i=this.r.shader_formats(Cr[e.scope]);await ti(Promise.all(i.map(a=>t.createRenderPipelineAsync(bf(t,r,e.scope,a)).catch(()=>null))),"build its pipelines"),this.r.shader_build(e.id)}else this.r.shader_build(e.id);e.state="ready",this.onReady()}catch(r){e.state="failed",e.browser.push({line:0,column:0,length:0,message:`error: ${String(r?.message??r)}`,source:"browser"})}}};function hf(e,t){let n=t.indexOf(`// \u2500\u2500 the author's code \u2500\u2500
700
+ `),r=n<0?0:t.slice(0,n).split(`
701
+ `).length+1;return e.map(s=>{let i=s.lineNum>=r&&r>0?s.lineNum-r+1:0;return{line:i,column:i?s.linePos:0,length:s.length??0,message:`${s.type}: ${s.message}`,source:"browser"}})}var _f=3,pf={fill:[["uniform","storage","storage","storage","storage","storage","unfilterable-2d-array","storage"],["texture","sampler"],["uniform"]],effect:[["texture","texture","texture","sampler","sampler","uniform","texture"],["uniform"]]},mf={uniform:{buffer:{type:"uniform",hasDynamicOffset:!0}},storage:{buffer:{type:"read-only-storage"}},texture:{texture:{sampleType:"float",viewDimension:"2d"}},sampler:{sampler:{type:"filtering"}},"unfilterable-2d-array":{texture:{sampleType:"unfilterable-float",viewDimension:"2d-array"}}};function gf(e,t){return pf[t].map(n=>e.createBindGroupLayout({entries:n.map((r,s)=>({binding:s,visibility:_f,...mf[r]}))}))}function bf(e,t,n,r){let s={srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},i=n==="fill";return{layout:e.createPipelineLayout({bindGroupLayouts:gf(e,n)}),vertex:{module:t,entryPoint:i?"ms_vs_quad":"ms_vs_effect",buffers:[]},primitive:{topology:"triangle-list",cullMode:"none"},multisample:{count:1},fragment:{module:t,entryPoint:i?"ms_fs_prim":"ms_fs_effect",targets:[{format:r,...i?{blend:{color:s,alpha:s}}:{},writeMask:15}]}}}var wf={normal:0,multiply:1,screen:2,overlay:3,darken:4,lighten:5,"color-dodge":6,"color-burn":7,"hard-light":8,"soft-light":9,difference:10,exclusion:11,hue:12,saturation:13,color:14,luminosity:15},yf="A shader fill is written in SkSL, which Motion Script no longer runs, so it draws nothing. Port it to WGSL (fn fill(in: FillIn) -> vec4f).",vf="A shader effect is written in SkSL, which Motion Script no longer runs, so it is skipped. Port it to WGSL (fn effect(in: EffectIn) -> vec4f).",xf=1073741824,Or=null;function cn(e){return Or??=Gl(e?{module_or_path:e}:void 0),Or}var Dn=null;function Br(){return Dn??=cn().then(()=>Lt.prewarm()).catch(e=>{throw Dn=null,e}),Dn}function kf(){Dn=null,Or&&Lt.forget_device()}var Mf={miter:0,round:1,bevel:2},Sf={butt:0,round:1,square:2},ni={clamp:0,repeat:1,mirror:2,decal:3},Af={rect:1,ellipse:2,path:3},Ef={left:0,right:1,center:2,justify:3},Tf={top:0,center:1,bottom:2},ri=new TextEncoder,Pf=120;function If(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e[n],16777619);return t>>>0}function Rf(e){let t=new Uint32Array(e.points.buffer,e.points.byteOffset,e.points.length),n=2166136261,r=16777619^e.points.length;for(let s=0;s<e.verbs.length;s++)n=Math.imul(n^e.verbs[s],16777619),r=Math.imul(r^e.verbs[s],1540483477);for(let s=0;s<t.length;s++)n=Math.imul(n^t[s],16777619),r=Math.imul(r^t[s],1540483477);return`${e.verbs.length}:${t.length}:${n>>>0}:${r>>>0}`}var zi=class{name="wgpu";r;w;paintIds=new WeakMap;paintByKey=new Map;freePaints=[];pathIds=new WeakMap;pathByKey=new Map;freePaths=[];generation=0;collectUnused=!1;dashIds=new Map;nextPaint=0;nextPath=0;nextDash=0;synced=!1;viewport={w:0,h:0};lastDeltaWords=0;async init(e,t,n){let r=await cn();await Br().catch(()=>{}),this.r=await Lt.create(e,t,n),this.w=new ec(this.r,r.memory),this.effectIndex=new Map(this.r.effect_names().map((s,i)=>[s,i])),this.viewport={w:t,h:n},this.shaders=new df(this.r,()=>this.onShaderReady?.())}shaders;onShaderReady;shaderIssues=new Set;whenShadersReady(){return this.shaders.whenReady()}userProgram(e,t){let n=this.shaders.program(e,t),r=n.report.diagnostics[0]??n.browser.find(s=>s.message.startsWith("error"));return n.state==="failed"&&r&&this.shaderIssues.add(`A WGSL shader ${e} does not compile${r.line?` (line ${r.line}:${r.column})`:""}: ${r.message}`),n}adapterInfo(){return this.r.adapter_info()}gpuDevice(){return this.r.gpu_device()}setOptions(e,t){this.r.set_options(e,t)}resize(e,t){this.r.resize(e,t),this.viewport={w:e,h:t},this.synced=!1}paint(e){if(!e)return ft;let t=this.paintIds.get(e);if(t?.live)return t.used=this.generation,t.id;let n=e.kind==="image"?`image:${e.image.id}:${e.fit??"fill"}:${e.box.join(",")}:${e.matrix?.join(",")??""}:${e.tile??""}`:e.kind==="shader"?`shader:${this.userProgram("fill",e.source).id}:${e.box.join(",")}:${e.time}:${e.texture?.id??""}:${JSON.stringify(e.uniforms)}`:JSON.stringify(e),r=this.paintByKey.get(n);if(r)r.used=this.generation;else{r={id:this.freePaints.pop()??this.nextPaint++,used:this.generation,live:!0},this.paintByKey.set(n,r);let s=r.id,i=this.w;if(e.kind==="procedural")return this.procedural(s,e),this.paintIds.set(e,r),s;if(e.kind==="shader")return this.shaderPaint(s,e),this.paintIds.set(e,r),s;let a=e.kind==="solid"||e.kind==="image"?[]:e.stops;if(i.begin(12+a.length*5),i.u(Me.DEF_PAINT),i.u(s),e.kind==="solid"){i.u(0);for(let o=0;o<4;o++)i.f(0);for(let o of e.color)i.f(o)}else if(e.kind==="image"){let{m:o,tile:l}=Zl(e),c=o[0]*o[3]-o[1]*o[2]||1,u=e.image.width,f=e.image.height,d=o[3]/c,_=-o[1]/c,p=-o[2]/c,w=o[0]/c,R=(o[2]*o[5]-o[3]*o[4])/c,L=(o[1]*o[4]-o[0]*o[5])/c;i.u(4|ni[l]<<8),i.f(d/u),i.f(_/f),i.f(p/u),i.f(w/f),i.f(R/u),i.f(L/f),i.f(e.image.id),i.f(0)}else{let o=e.kind==="linear"?1:e.kind==="radial"?2:3;i.u(o|ni[e.tile??"clamp"]<<8),e.kind==="linear"?(i.f(e.from[0]),i.f(e.from[1]),i.f(e.to[0]),i.f(e.to[1])):e.kind==="radial"?(i.f(e.center[0]),i.f(e.center[1]),i.f(e.radius),i.f(0)):(i.f(e.center[0]),i.f(e.center[1]),i.f(e.startAngle),i.f(e.endAngle));for(let l of a[0].color)i.f(l)}i.u(a.length);for(let o of a){i.f(o.offset);for(let l of o.color)i.f(l)}}return this.paintIds.set(e,r),r.id}shaderPaint(e,t){let n=this.userProgram("fill",t.source),r=n.report.ok?Qs(n.report.fields,n.report.size,t.uniforms):new Uint32Array(0),s=Math.ceil(r.length/4),i=this.w;i.begin(12+s*5),i.u(Me.DEF_PAINT),i.u(e),i.u(10);for(let a of t.box)i.f(a);i.f(t.time),i.f(t.texture?t.texture.id:-1),i.f(n.id),i.f(0),i.u(s);for(let a=0;a<s;a++){i.f(0);for(let o=0;o<4;o++)i.u(r[a*4+o]??0)}}procedural(e,t){let n=t.fill,[r,s,i,a]=t.box,o,l,c,u=[],f=[],d=w=>[Math.round(w[0]*255)/255,Math.round(w[1]*255)/255,Math.round(w[2]*255)/255,w[3]];if(n.type==="dotGrid")o=5,l=[r+n.offset.x,s+n.offset.y,Math.max(.01,n.spacing),Math.max(0,n.radius)],c=[...n.color];else if(n.type==="grid")o=6,l=[r+n.offset.x,s+n.offset.y,i,a],c=[...n.color],u.push([Math.max(1e-4,n.divisions),Math.max(1,Math.round(n.subdivisions)),Math.max(0,n.strokeWidth)*.5,Math.max(0,n.subdivisionWidth)*.5]);else if(n.type==="stripe"){o=7;let w=(n.angle??-45)*Math.PI/180;l=[r,s,Math.max(1,Math.round(n.gap??8)),n.strokeWidth??1],c=d(n.color??[0,0,0,1]),u.push([Math.cos(w),Math.sin(w),r,0])}else if(n.type==="noise"){o=8,l=[r,s,Math.ceil(i),Math.ceil(a)];let w=d(n.color);c=[w[0],w[1],w[2],Math.round(n.color[3]*255)/255],u.push([Math.max(1,Math.round(n.size.x)),Math.max(1,Math.round(n.size.y)),Math.min(1,Math.max(0,n.density)),Math.round(n.seed)])}else{o=9,l=[r,s,i,a];let w=n.angle*Math.PI/180,R={value:0,simplex:1,ridged:2,worley:3}[n.basis]??1;u.push([n.frequency.x,n.frequency.y,n.offset.x,n.offset.y]),u.push([n.lacunarity,n.gain,n.seed,n.contrast]),u.push([Math.cos(w),Math.sin(w),R,n.octaves]);let L=Math.max(2,Math.min(8,n.colors.length));for(let F=0;F<L;F++)f.push({offset:n.stops[Math.min(F,n.stops.length-1)]??F/(L-1),color:[...n.colors[Math.min(F,n.colors.length-1)]]});c=f[0].color}let _=u.length+f.length,p=this.w;p.begin(12+_*5),p.u(Me.DEF_PAINT),p.u(e),p.u(o);for(let w of l)p.f(w);for(let w of c)p.f(w);p.u(_);for(let w of u){p.f(0);for(let R of w)p.f(R)}for(let w of f){p.f(w.offset);for(let R of w.color)p.f(R)}}pathId(e){let t=this.pathIds.get(e);if(t?.live)return t.used=this.generation,t.id;let n=Rf(e),r=this.pathByKey.get(n);if(r)return r.used=this.generation,this.pathIds.set(e,r),r.id;let s={id:this.freePaths.pop()??this.nextPath++,used:this.generation,live:!0};this.pathByKey.set(n,s);let i=s.id,a=this.w,o=Math.ceil(e.verbs.length/4);a.begin(4+o+e.points.length),a.u(Me.DEF_PATH),a.u(i),a.u(e.verbs.length),a.u(e.points.length/2);for(let l=0;l<o;l++){let c=e.verbs,u=l*4;a.u((c[u]??0)|(c[u+1]??0)<<8|(c[u+2]??0)<<16|(c[u+3]??0)<<24)}for(let l=0;l<e.points.length;l++)a.f(e.points[l]);return this.pathIds.set(e,s),i}sweep(){let e=this.generation-Pf;for(let[t,n]of this.pathByKey)n.used>=e||(n.live=!1,this.pathByKey.delete(t),this.w.begin(2),this.w.u(Me.FREE_PATH),this.w.u(n.id),this.freePaths.push(n.id));for(let[t,n]of this.paintByKey)n.used>=e||(n.live=!1,this.paintByKey.delete(t),this.freePaints.push(n.id))}dash(e,t=0){if(!e||e.length===0)return ft;let n=e.join(",")+"@"+t,r=this.dashIds.get(n);if(r===void 0){r=this.nextDash++,this.dashIds.set(n,r);let s=this.w;s.begin(4+e.length),s.u(Me.DEF_DASH),s.u(r),s.u(e.length),s.f(t);for(let i of e)s.f(i)}return r}writeNode(e,t){let n=this.w,r=e.id;if(t&ke.CREATE&&(n.begin(3),n.u(Me.CREATE),n.u(r),n.u(Hl[e.kind])),t&ke.TRANSFORM){let s=e.transform;if(On(s)){n.begin(11),n.u(Me.TRANSFORM3),n.u(r);for(let i of s)n.f(i)}else{n.begin(8),n.u(Me.TRANSFORM),n.u(r);for(let i=0;i<6;i++)n.f(s[i])}}if(t&ke.EFFECTS&&(e.effects?.length||!(t&ke.CREATE))&&this.writeEffects(e),t&ke.OPACITY&&(e.opacity!==1||!(t&ke.CREATE))&&(n.begin(3),n.u(Me.OPACITY),n.u(r),n.f(e.opacity)),t&ke.BLEND&&(e.blend!=="normal"||!(t&ke.CREATE))&&(n.begin(3),n.u(Me.BLEND),n.u(r),n.u(Fi.indexOf(e.blend))),e.kind==="group"){if(t&ke.CLIP&&(e.clip||!(t&ke.CREATE))){let s=e.clip,i=s?.path?this.pathId(s.path):ft,a=s?.path?et(s.path):[s?.x??0,s?.y??0,(s?.x??0)+(s?.w??0),(s?.y??0)+(s?.h??0)];n.begin(10),n.u(Me.CLIP),n.u(r),n.u(s?1:0);for(let o of a)n.f(o);n.f(s?.r??0),n.u(i),n.u(s?.evenOdd?1:0)}if(t&ke.MASK&&(e.mask||!(t&ke.CREATE))&&(n.begin(3),n.u(Me.MASK),n.u(r),n.u(e.mask?ql[e.mask]:0)),t&ke.FILTER&&(e.filter||!(t&ke.CREATE))){let s=e.filter;if(n.begin(10),n.u(Me.FILTER),n.u(r),s)if(s.kind==="blur"){n.u(1),n.f(s.sigma);for(let i=0;i<6;i++)n.f(0)}else{n.u(2),n.f(s.sigma),n.f(s.dx),n.f(s.dy);for(let i of s.color)n.f(i)}else{n.u(0);for(let i=0;i<7;i++)n.f(0)}}if(t&ke.CHILDREN){n.begin(3+e.children.length),n.u(Me.CHILDREN),n.u(r),n.u(e.children.length);for(let s of e.children)n.u(s.id)}return}if(t&ke.SIZE&&(n.begin(4),n.u(Me.SIZE),n.u(r),n.f(e.w),n.f(e.h)),t&ke.RADII&&e.kind==="rect"){n.begin(6),n.u(Me.RADII),n.u(r);for(let s of e.radii)n.f(s)}if(t&ke.MEMBERS&&e.members){let s=e.members,i=s.map(a=>a.kind==="path"&&a.path?this.pathId(a.path):ft);n.begin(3+s.length*16),n.u(Me.MEMBERS),n.u(r),n.u(s.length),s.forEach((a,o)=>{n.u(Af[a.kind]),n.u(Kl[Xl(a)]);for(let l of a.transform??[1,0,0,1,0,0])n.f(l);n.f(a.w??0),n.f(a.h??0);for(let l of a.radii??[0,0,0,0])n.f(l);n.u(i[o]),n.u(a.evenOdd?1:0)})}if(t&ke.TEXT&&e.text){let s=e.text,i=s.runs.map(c=>[ri.encode(c.family),ri.encode(c.text)]),a=i.reduce((c,[u,f])=>c+2+Math.ceil(u.length/4)+Math.ceil(f.length/4)+6,0),o=s.path?this.pathId(s.path):ft,l=s.runs.map(c=>this.paint(c.paint));n.begin(12+a),n.u(Me.TEXT),n.u(r),n.u(Ef[s.align??"center"]),n.u(Tf[s.verticalAlign??"center"]),n.u(s.wrap?1:0),n.f(s.fontSize==="autofit"?0:s.runs.length===1?s.runs[0].size:0),n.f(s.minFontSize??0),n.f(s.lineHeight??0),n.f(s.width??0),n.f(s.height??0),n.u(s.runs.length),s.runs.forEach((c,u)=>{n.u(c.decoration==="underline"?1:c.decoration==="lineThrough"?2:0),n.u(l[u]),n.f(c.size),n.f(c.weight??400),n.u(c.italic?1:0),n.f(c.letterSpacing??0);for(let f of i[u]){n.u(f.length);for(let d=0;d<f.length;d+=4)n.u((f[d]??0)|(f[d+1]??0)<<8|(f[d+2]??0)<<16|(f[d+3]??0)<<24)}}),n.u(o)}if(t&ke.PATH&&e.path){let s=this.pathId(e.path);n.begin(4),n.u(Me.PATH),n.u(r),n.u(s),n.u(e.evenOdd?1:0)}if(t&ke.FILL){let s=this.paint(e.fill);n.begin(3),n.u(Me.FILL),n.u(r),n.u(s)}if(t&ke.STROKE&&(e.stroke||!(t&ke.CREATE))){let s=e.stroke,i=this.paint(s?.paint),a=this.dash(s?.dash,s?.dashPhase);n.begin(8),n.u(Me.STROKE),n.u(r),n.u(i),n.f(s?.width??0),n.u(Mf[s?.join??"miter"]),n.u(Sf[s?.cap??"butt"]),n.f(s?.miter??4),n.u(a)}if(t&ke.SHADOWS&&(e.shadows.length||!(t&ke.CREATE))){n.begin(3+e.shadows.length*8),n.u(Me.SHADOWS),n.u(r),n.u(e.shadows.length);for(let s of e.shadows){n.f(s.dx),n.f(s.dy),n.f(s.sigma),n.f(s.spread);for(let i of s.color)n.f(i)}}}uploaded=new Map;missing3d=new Set;textures3d=new Map;geometries3d=new Map;bindTextures3d(e,t){for(let n of t.pending.splice(0)){let r=n.texture;if("data"in r){this.r.scene3d_pixels(e.id,n.id,Uint8Array.from(r.data),r.width,r.height,n.srgb);continue}let s="src"in r?e.links3d?.images?.[r.src]:e.links3d?.surfaces?.get(r);s?this.r.scene3d_bind(e.id,n.id,s.id,n.srgb):this.missing3d.add("src"in r?`image:${r.src}`:"surface")}}scene3dSigs=new Map;encode3dMs=0;words3d=0;effectIndex=new Map;auxIds=new Map;missing=new Set;effectTypes(){return[...this.effectIndex.keys()].filter(e=>Zs.has(e))}auxId(e){if(!e)return ft;let t=this.auxIds.get(e.key);if(t===void 0){t=1e6+this.auxIds.size;let n=new OffscreenCanvas(e.width,e.height);n.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(e.pixels),e.width,e.height),0,0),this.r.upload_image(t,n,!1),this.auxIds.set(e.key,t)}return t}writeEffects(e){let t=e.effects??[],n=[];for(let[i,a]of[["shader",!1],["filter",!1],["filter",!0],["shader",!0]])for(let o of t){if(o.type==="shader"){if(o.mode==="backdrop"!==a||(a?"shader":"filter")!==i)continue;let f=this.userEffect(o);f&&n.push({...f,flags:(o.clip?1:0)|(a?2:0)});continue}let l=Zs.get(o.type),c=this.effectIndex.get(o.type);if(!l||c===void 0){this.missing.has(o.type)||console.info(`effect "${o.type}" has no WGSL port yet; skipped`),this.missing.add(o.type);continue}if(l.surface!==i||o.mode==="backdrop"!==a||l.backdropOnly&&!a)continue;let u=l.pack(o);u&&n.push({index:c,flags:(o.clip?1:0)|(a?2:0)|(a&&i==="filter"?4:0)|(u.field?8:0),aux:this.auxId(u.aux),p:u})}let r=this.w,s=e.effectBox??[0,0,0,0];r.begin(8+n.reduce((i,a)=>i+8+a.p.params.length+(a.words?.length??0),0)),r.u(Me.EFFECTS),r.u(e.id);for(let i of s)r.f(i);r.f(e.effectTime??0),r.u(n.length);for(let i of n){r.u(i.index),r.u(i.flags),r.u(i.aux),r.f(i.p.reach??0);let a=i.p.blur??[0,0,0];r.f(a[0]),r.f(a[1]),r.f(a[2]),r.u(i.p.params.length+(i.words?.length??0));for(let o of i.p.params)r.f(o);if(i.words)for(let o of i.words)r.u(o)}}userEffect(e){if(!e.source?.trim())return null;if(!ki(e))return this.shaderIssues.add(vf),null;let t=this.userProgram("effect",e.source);if(!t.report.ok)return null;let n=Mi(e.uniforms),r=e.mode!=="backdrop"&&e.blendMode?(wf[e.blendMode]??-1)+1:0;return{index:xf+t.id,aux:ft,p:{params:[r],reach:Math.max(0,e.reach??0)},words:Qs(t.report.fields,t.report.size,n)}}frameCanvases=new Map;colorCorrect(e){if(typeof VideoFrame>"u"||!(e.source instanceof VideoFrame))return e.source;let t=this.frameCanvases.get(e.id);return(!t||t.width!==e.width||t.height!==e.height)&&(t=new OffscreenCanvas(e.width,e.height),this.frameCanvases.set(e.id,t)),t.getContext("2d").drawImage(e.source,0,0),t}sync(e){this.generation++,this.encode3dMs=0,this.words3d=0;for(let n of e.images)if(this.uploaded.get(n.id)!==n.version){if(n.surface)this.r.set_surface(n.id,n.surface.id,n.width,n.height);else if(n.scene3d){let r=this.viewport.w/e.width,s={unsupported:new Set},i=this.textures3d.get(n.id);i||this.textures3d.set(n.id,i=new al);let[a,o]=n.scale3d?[Math.ceil(n.width*n.scale3d),Math.ceil(n.height*n.scale3d)]:[Math.round(n.width*r),Math.round(n.height*r)],l=performance.now(),c=this.geometries3d.get(n.id);c||this.geometries3d.set(n.id,c=new ll);let u=fl(n.scene3d,s,i,c),f=`${a}x${o}:${u.length}:${If(u)}`;if(this.encode3dMs+=performance.now()-l,this.words3d+=u.length,this.scene3dSigs.get(n.id)!==f){try{this.r.set_scene3d(n.id,a,o,u)}catch(d){throw this.geometries3d.delete(n.id),this.scene3dSigs.delete(n.id),d}this.scene3dSigs.set(n.id,f)}for(let d of s.unsupported)this.missing3d.add(d);this.bindTextures3d(n,i)}else this.r.upload_image(n.id,this.colorCorrect(n),n.mipmaps);this.uploaded.set(n.id,n.version)}let t=this.w;if(this.synced)for(let n of e.dirty)this.writeNode(n,n.dirty);else{for(let n of e.nodes)this.writeNode(n,ke.ALL);t.begin(2),t.u(Me.ROOT),t.u(e.root.id),t.begin(8),t.u(Me.VIEWPORT),t.u(this.viewport.w),t.u(this.viewport.h),t.f(this.viewport.w/e.width);for(let n of e.background)t.f(n);this.synced=!0}for(let n of e.dirty)n.dirty=0;e.dirty.clear(),this.collectUnused&&this.generation%30===0&&this.sweep(),t.flush(),this.lastDeltaWords=t.takeCount()}render(){this.r.render()}invalidate(){this.r.invalidate()}waitGpu(){return this.r.wait_gpu()}async readPixels(){return await this.r.read_pixels()}stats(){let e=this.r.stats();return{buildMs:e[0],encodeMs:e[1],applyMs:e[2],prims:e[3],ops:e[4],layers:e[5],passes:e[6],draws:e[7],culled:e[8],tessellated:e[9],poolTextures:e[10],poolMiB:e[11],geomVertices:e[12],reusedPrims:e[13],cleanPrims:e[14],deltaWords:this.lastDeltaWords,scene3dEncodeMs:this.encode3dMs,scene3dWords:this.words3d,scene3dSetMs:e[15],scene3dDrawMs:e[16],scene3dMapsMs:e[17],surfacesDrawn:e[18],surfaces:e[19]}}registerFont(e,t){this.r.register_font(e,t)}destroy(){this.r.free()}},wt=e=>e.replace(/^\.?\//,""),yr=8192,Cf=12,vr=e=>e.toFixed(4);async function Of(e){let t=await fetch(e);if(!t.ok)throw new Error(`${e}: HTTP ${t.status}`);return t.blob()}var $f=class extends yo{fps;loadBytes;images=new Map;videos=new Map;fonts=[];fontListeners=new Set;registeredFamilies=new Set;pending=new Map;vectors=new Map;upgrades=new Map;settlers=new Set;audioData=new Map;constructor(e,t,n,r=Of){super(e,t),this.fps=n,this.loadBytes=r}get size(){return this.viewport}addSettler(e){return this.settlers.add(e),()=>this.settlers.delete(e)}onFont(e){return this.fontListeners.add(e),()=>this.fontListeners.delete(e)}async loadImage(e){let t=wt(e);if(this.images.has(t))return;let n=this.url(e,a=>a.getImageMeta(e)),r=await this.loadBytes(n),s;if(r.type==="image/svg+xml"||/\.svg(\?|#|$)/i.test(n)){let a=new Image;a.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(await r.text())}`,await a.decode(),s=await createImageBitmap(a),this.vectors.set(t,{img:a,edge:Math.max(s.width,s.height)})}else s=await createImageBitmap(r,{colorSpaceConversion:"none"});let i=Math.max(s.width,s.height);if(i>yr){let a=yr/i,o=await createImageBitmap(s,{resizeWidth:Math.max(1,Math.round(s.width*a)),resizeHeight:Math.max(1,Math.round(s.height*a)),resizeQuality:"high"});s.close(),s=o}this.images.set(t,{bitmap:s,bytes:new Uint8Array(0),width:s.width,height:s.height})}async loadVideo(e){let t=wt(e);if(this.videos.has(t))return;let n=this.url(e,a=>a.getVideoMeta(e)),r=new xn({source:new ls(await this.loadBytes(n)),formats:us}),s=await r.getPrimaryVideoTrack();if(!s)throw r.dispose(),new Error(`loadVideo(${e}): no video track`);let i=await r.computeDuration();this.videos.set(t,{duration:i,sink:new hs(s),input:r,frames:new Map,last:null})}videoFrame(e,t){let n=wt(e),r=this.videos.get(n);if(!r)return null;let s=r.frames.get(vr(t));return s||(this.pending.set(`${n}@${vr(t)}`,{src:n,time:t}),r.last)}wantImageEdge(e,t){let n=wt(e),r=this.vectors.get(n),s=this.images.get(n);if(!r||!s||t<=r.edge)return;let i=Math.max(s.width,s.height),a=Math.min(yr,i*2**Math.ceil(Math.log2(t/i)));a>r.edge&&a>(this.upgrades.get(n)??0)&&this.upgrades.set(n,a)}hasPendingUpgrades(){return this.upgrades.size>0}async warmPendingUpgrades(){if(this.upgrades.size===0)return!1;let e=[...this.upgrades];this.upgrades.clear();for(let[t,n]of e){let r=this.vectors.get(t),s=this.images.get(t);if(!r||!s)continue;let i=n/Math.max(s.width,s.height),a=new OffscreenCanvas(Math.max(1,Math.round(s.width*i)),Math.max(1,Math.round(s.height*i)));a.getContext("2d").drawImage(r.img,0,0,a.width,a.height);let o=s.bitmap;s.bitmap=await createImageBitmap(a),r.edge=n,queueMicrotask(()=>o.close())}return!0}hasPendingDecodes(){return this.pending.size>0}async warmPendingDecodes(){let e=[...this.settlers].map(n=>n()).filter(n=>n!==null);if(this.pending.size===0&&e.length===0)return!1;let t=[...this.pending.values()];return this.pending.clear(),await Promise.all([...t.map(({src:n,time:r})=>this.decodeFrame(n,r)),...e]),!0}async decodeFrame(e,t){let n=this.videos.get(e);if(!n)return;let r=await n.sink.getSample(t);if(!r)return;let s=r.toVideoFrame(),i;try{i=await createImageBitmap(s)}finally{s.close(),r.close()}for(n.frames.set(vr(t),i),n.last=i;n.frames.size>Cf;){let[a,o]=n.frames.entries().next().value;n.frames.delete(a),o!==n.last&&queueMicrotask(()=>o.close())}}async loadAudio(){}fetchAudioData(e){let t=this.audioData.get(e);if(!t){let n=this.url(e,r=>{try{return r.getAudioMeta(e)}catch{return r.getVideoMeta(e)}});t=(async()=>(await this.loadBytes(n)).arrayBuffer())(),this.audioData.set(e,t),t.catch(()=>this.audioData.delete(e))}return t.then(n=>n.slice(0))}async loadFont(e,t){if(this.registeredFamilies.has(t))return!0;let n=this.catalog.getFontFamilyMetas(t);if(n.length===0)return this.getDecodePolicy()==="interactive"&&console.warn(`[WgpuStorageAdapter] No font manifest entry for "${e}".`),!1;let r=[...new Set(n.map(i=>i.src))],s=await Promise.all(r.map(async i=>new Uint8Array(await(await this.loadBytes(i)).arrayBuffer())));if(this.registeredFamilies.has(t))return!0;for(let i of s){let a={bytes:i,family:t};this.fonts.push(a);for(let o of this.fontListeners)o(a)}return this.registeredFamilies.add(t),!0}dispose(){for(let e of this.images.values())e.bitmap.close();this.images.clear();for(let e of this.videos.values()){for(let t of e.frames.values())t.close();e.input.dispose()}this.videos.clear(),this.pending.clear(),this.vectors.clear(),this.upgrades.clear(),this.fontListeners.clear(),super.dispose()}url(e,t){try{return t(this.catalog).src||e}catch{return e}}};function si(e,t,n,r){if(n.matrix)return n.matrix instanceof Float32Array?Array.from(n.matrix):n.matrix.flat();let s=n.zoom??1;if(!r)return[s,0,0,0,s,0,0,0,1];let i=n.fit??"fill",a=r.right-r.left,o=r.bottom-r.top,l=i==="tile"?void 0:n.crop,c=l?l.left*e:0,u=l?l.top*t:0,f=l?e*(1-l.left-l.right):e,d=l?t*(1-l.top-l.bottom):t;if(f<=0||d<=0)return[s,0,r.left,0,s,r.top,0,0,1];let _,p;if(i==="fit"?_=p=Math.min(a/f,o/d):i==="stretch"?(_=a/f,p=o/d):i==="tile"?_=p=1:_=p=Math.max(a/f,o/d),_*=s,p*=s,i==="tile")return[_,0,r.left,0,p,r.top,0,0,1];let w=n.anchor??{x:0,y:0},R=(w.x+1)/2,L=(1-w.y)/2,F=r.left+R*(a-f*_)-c*_,H=r.top+L*(o-d*p)-u*p;return[_,0,F,0,p,H,0,0,1]}function En(e,t,n){let r=(n[0]+n[2])/2,s=(n[1]+n[3])/2;return[r+e*((n[2]-n[0])/2),s-t*((n[3]-n[1])/2)]}function xr(e,t){return e.map((n,r)=>({offset:t[r]??r/Math.max(1,e.length-1),color:[n[0],n[1],n[2],n[3]]}))}function dt(e,t,n,r){let s=e,i=r?a=>r.image(a):void 0;switch(s.type){case"video":{let a=r?.video(s);if(!a)return n.add("fill:video-not-decoded"),null;let o=si(a.width,a.height,s,{left:t[0],top:t[1],right:t[2],bottom:t[3]}),l=s.fit??"fill",c=l==="tile"?"repeat":l!=="fit"&&(s.zoom??1)>=1?"clamp":"decal";return{kind:"image",image:a,box:[t[0],t[1],t[2]-t[0],t[3]-t[1]],matrix:[o[0],o[3],o[1],o[4],o[2],o[5]],tile:c}}case"canvas3D":{if(!r)return null;let a=t[2]-t[0],o=t[3]-t[1];if(!(a>0)||!(o>0))return null;let l=Math.min(s.maxPixelRatio??2,Math.max(r.deviceScale(),1));return{kind:"image",image:r.scene3d(s.scene,a,o,l),box:[t[0],t[1],a,o],fit:"stretch"}}case"image":{let a=i?.(s.src);if(!a)return n.add("fill:image-not-loaded"),null;let o=si(a.width,a.height,s,{left:t[0],top:t[1],right:t[2],bottom:t[3]}),l=[o[0],o[3],o[1],o[4],o[2],o[5]];if(r?.imageEdge){let f=r.deviceScale();r.imageEdge(s.src,Math.max(a.width*Math.hypot(l[0],l[1]),a.height*Math.hypot(l[2],l[3]))*f)}let c=s.fit??"fill",u=c==="tile"?"repeat":c!=="fit"&&(s.zoom??1)>=1?"clamp":"decal";return{kind:"image",image:a,box:[t[0],t[1],t[2]-t[0],t[3]-t[1]],matrix:l,tile:u}}case"solid":return{kind:"solid",color:[s.color[0],s.color[1],s.color[2],s.color[3]]};case"linear-gradient":return{kind:"linear",from:En(s.start.x,s.start.y,t),to:En(s.end.x,s.end.y,t),stops:xr(s.colors,s.stops)};case"conic-gradient":{let a=s.startAngle??0,o=s.stops.length===s.colors.length?s.stops:[];return{kind:"sweep",center:En(s.center.x,s.center.y,t),startAngle:a,endAngle:a+360,stops:xr(s.colors,o)}}case"radial-gradient":return{kind:"radial",center:En(s.center.x,s.center.y,t),radius:s.radius,stops:xr(s.colors,s.stops)};case"shader":{if(!s.source?.trim())return null;if(!ki(s))break;r?.checkShader?.(s);let a=s.textures?.[0]?i?.(s.textures[0].src):void 0;return s.textures?.[0]&&!a?(n.add("fill:image-not-loaded"),null):{kind:"shader",source:s.source,uniforms:s.uniforms??{},time:r?.time?.()??0,box:[t[0],t[1],t[2]-t[0],t[3]-t[1]],...a?{texture:a}:{}}}case"dotGrid":case"grid":case"stripe":case"noise":case"fractalNoise":return{kind:"procedural",fill:s,box:[t[0],t[1],t[2]-t[0],t[3]-t[1]]}}return n.add(s.type==="shader"?"fill:shader-sksl":`fill:${s.type}`),null}function Df(e,t){let n=e.fill[0],r=n?.type==="solid"?n.color:[0,0,0,1];return{dx:e.offset?.x??0,dy:-(e.offset?.y??0),sigma:e.blur/2,spread:e.spread,color:[r[0],r[1],r[2],r[3]*(n?.opacity??1)]}}var Ct=new Map,Lf=64;function Ff(e,t){let n=`${e}
702
+ ${t}`,r=Ct.get(n);if(r===void 0){try{let s=Gi(e,t);r=s.ok?s.fields.map(i=>i.name):null}catch{return null}Ct.size>=Lf&&Ct.delete(Ct.keys().next().value)}else Ct.delete(n);return Ct.set(n,r),r}function Bf(e,t){let n=t.source??"",r=jo(t);if(!n.trim()||r===void 0)return[];let s=[];r>Is&&s.push({kind:"shader",feature:`${e}:contract-${r}`,message:`A WGSL shader ${e} is written for shader contract ${r}; this renderer implements ${Is}, so it may not draw as intended.`});let i=Ff(e,n);if(!i)return s;let a=Mi(t.uniforms??{});for(let o of Object.keys(a))i.includes(o)||s.push({kind:"params",feature:`params:${o}`,message:`A WGSL shader ${e} is given "${o}", which names no member of its struct Params, so the value is ignored.`});for(let o of i)o in a||s.push({kind:"params",feature:`params:${o}`,message:`A WGSL shader ${e}'s Params.${o} is given no value, so it reads 0.`});return s}var Uf=32;function yt(e,t){let n=e.p,r=1-t;return e.kind==="line"?[n[0]+(n[2]-n[0])*t,n[1]+(n[3]-n[1])*t]:e.kind==="quad"?[r*r*n[0]+2*r*t*n[2]+t*t*n[4],r*r*n[1]+2*r*t*n[3]+t*t*n[5]]:[r*r*r*n[0]+3*r*r*t*n[2]+3*r*t*t*n[4]+t*t*t*n[6],r*r*r*n[1]+3*r*r*t*n[3]+3*r*t*t*n[5]+t*t*t*n[7]]}function Tn(e,t){let n=[0],r=e==="line"?1:Uf,s={kind:e,p:t,len:0,table:n},i=yt(s,0);for(let a=1;a<=r;a++){let o=yt(s,a/r);n.push(n[a-1]+Math.hypot(o[0]-i[0],o[1]-i[1])),i=o}return s.len=n[r],s}function $r(e,t){let n=e.table.length-1;if(t<=0)return 0;if(t>=e.len)return 1;let r=1;for(;e.table[r]<t;)r++;let s=e.table[r-1],i=e.table[r];return(r-1+(i>s?(t-s)/(i-s):0))/n}function jf(e,t,n){let r=e.p;if(e.kind==="line")return[...yt(e,t),...yt(e,n)];let s=(a,o)=>{let l=a.length/2,c=[a];for(let d=1;d<l;d++){let _=c[d-1],p=[];for(let w=0;w<_.length-2;w+=2)p.push(_[w]+(_[w+2]-_[w])*o,_[w+1]+(_[w+3]-_[w+1])*o);c.push(p)}let u=[],f=[];for(let d=0;d<l;d++)u.push(c[d][0],c[d][1]);for(let d=l-1;d>=0;d--)f.push(c[d][c[d].length-2],c[d][c[d].length-1]);return[u,f]},[i]=n<1?s(r,n):[r];return t<=0?i:s(i,t/n)[1]}function Ur(e){let t=[],n=null,r=0,s=0,i=0,a=0,o=0,l=e.points;for(let c of e.verbs)if(c===Ce.move)r=i=l[o++],s=a=l[o++],n={segs:[],closed:!1},t.push(n);else if(c===Ce.line){let u=l[o++],f=l[o++];n.segs.push(Tn("line",[r,s,u,f])),r=u,s=f}else if(c===Ce.quad){let u=[r,s,l[o],l[o+1],l[o+2],l[o+3]];o+=4,n.segs.push(Tn("quad",u)),r=u[4],s=u[5]}else if(c===Ce.cubic){let u=[r,s,l[o],l[o+1],l[o+2],l[o+3],l[o+4],l[o+5]];o+=6,n.segs.push(Tn("cubic",u)),r=u[6],s=u[7]}else c===Ce.close&&(n&&((r!==i||s!==a)&&n.segs.push(Tn("line",[r,s,i,a])),n.closed=!0),r=i,s=a);return t.filter(c=>c.segs.length>0)}function Nf(e){let t=0,n=0,r=0,s=0,i=0,a=0,o=e.points,l=(c,u)=>{t+=i*u-c*a,i=c,a=u};for(let c of e.verbs)if(c===Ce.move)l(r,s),r=i=o[n++],s=a=o[n++];else if(c!==Ce.close){let u=c===Ce.line?1:c===Ce.quad?2:3;for(let f=0;f<u;f++,n+=2)l(o[n],o[n+1])}return l(r,s),t/2}function Wf(e){let t=new at,n=e.points,r=0,s=0,i=e.verbs;for(;s<i.length;){if(i[s]!==Ce.move){s++;continue}let a=n[r++],o=n[r++],l=[],c=!1;for(s++;s<i.length&&i[s]!==Ce.move;s++){let u=i[s];if(u===Ce.close){c=!0;continue}let f=u===Ce.line?1:u===Ce.quad?2:3,d=[a,o];for(let _=0;_<f;_++,r+=2)d.push(n[r],n[r+1]);a=d[d.length-2],o=d[d.length-1],l.push({v:u,p:d})}t.moveTo(a,o);for(let u=l.length-1;u>=0;u--){let{v:f,p:d}=l[u];f===Ce.line?t.lineTo(d[0],d[1]):f===Ce.quad?t.quadTo(d[2],d[3],d[0],d[1]):t.cubicTo(d[4],d[5],d[2],d[3],d[0],d[1])}c&&t.close()}return t.build()}function ii(e){let t=Ur(e);return t.length>0&&t.every(n=>n.closed)}function Hi(e,t,n,r){let s=0,i=!1;for(let a of e){let o=s,l=s+a.len;if(s=l,l<=t||o>=n)continue;let c=jf(a,$r(a,t-o),$r(a,n-o));i||(r.moveTo(c[0],c[1]),i=!0),a.kind==="line"?r.lineTo(c[2],c[3]):a.kind==="quad"?r.quadTo(c[2],c[3],c[4],c[5]):r.cubicTo(c[2],c[3],c[4],c[5],c[6],c[7])}return i}function Dr(e,t,n){let r=Ur(e),s=r.reduce((u,f)=>u+f.segs.reduce((d,_)=>d+_.len,0),0);if(s<=0)return e;let i=t*s,a=n*s,o=new at,l=0,c=!1;for(let u of r){let f=u.segs.reduce((p,w)=>p+w.len,0),d=l,_=l+f;l=_,_>i&&d<a&&(c=Hi(u.segs,Math.max(0,i-d),Math.min(f,a-d),o)||c)}return c?o.build():{verbs:new Uint8Array(0),points:new Float32Array(0)}}function Vf(e,t){let n=e.p,r=1-t;return e.kind==="line"?[n[2]-n[0],n[3]-n[1]]:e.kind==="quad"?[2*(r*(n[2]-n[0])+t*(n[4]-n[2])),2*(r*(n[3]-n[1])+t*(n[5]-n[3]))]:[3*(r*r*(n[2]-n[0])+2*r*t*(n[4]-n[2])+t*t*(n[6]-n[4])),3*(r*r*(n[3]-n[1])+2*r*t*(n[5]-n[3])+t*t*(n[7]-n[5]))]}function Gf(e){return Ur(e).map(t=>{let n=t.segs.filter(s=>s.len>0),r=n.reduce((s,i)=>s+i.len,0);return{length:r,closed:t.closed,posTan(s){s=Math.max(0,Math.min(r,s));let i=0,a=n[n.length-1];for(let _ of n){if(i+_.len>=s){a=_;break}i+=_.len}let o=$r(a,s-i),[l,c]=yt(a,o),[u,f]=Vf(a,o);if(Math.hypot(u,f)<1e-9){let _=yt(a,Math.max(0,o-.001)),p=yt(a,Math.min(1,o+.001));u=p[0]-_[0],f=p[1]-_[1]}let d=Math.hypot(u,f)||1;return[l,c,u/d,f/d]},segment:(s,i,a)=>Hi(n,s,i,a)}}).filter(t=>t.length>0)}var Ln=.001;function zf(e,t){let n=0,r=!1;for(let i of e)n+=i.length,i.closed||(r=!0);let s=Ai.dashScale(t,{length:n,closed:!0},n);return s===null?null:{scale:s,total:n,open:r}}function Ki(e,t,n){return e.closed?n.scale:Ai.dashScale(t,{length:e.length,closed:!1},n.total)??n.scale}function qi(e,t,n,r){let s=t.map(_=>_*r),i=s.reduce((_,p)=>_+p,0),a=[];if(!(i>0))return a;let o=(n*r%i+i)%i,l=0,c=0;for(;c+s[l]<=o&&l<s.length&&!(s[l]<=Ln&&Math.abs(o-c)<1e-6||(c+=s[l],l=(l+1)%s.length,l===0)););let u=s[l]-(o-c),f=l%2===0,d=0;for(;d<e.length-1e-6;){let _=Math.min(u,e.length-d);f&&a.push([d,d+_]),d+=_,u-=_,u<=1e-6&&(l=(l+1)%s.length,u=s[l],f=!f)}return f&&u<=1e-6&&!e.closed&&a.push([e.length,e.length]),a}function Hf(e,t,n,r,s){let i=new at,a=!1;for(let o of e)for(let[l,c]of qi(o,t,n,Ki(o,t,s)))if(c-l>Ln)a=o.segment(l,c,i)||a;else if(r){let[u,f,d,_]=o.posTan(l),p=l>o.length-Ln?-.001:Ln;i.moveTo(u,f).lineTo(u+d*p,f+_*p),a=!0}return a?i.build():null}var Bt=class{fullState;geo;constructor(e){this.fullState=this.resolveState(e)}get geometry(){return this.geo??=this.computeGeometry()}needsTrim(){return this.fullState.start!==0||this.fullState.end!==1}getTrimRange(){return{start:this.fullState.start,end:this.fullState.end}}buildSVGAlignInterior(e){return null}supportsSpread(){return!1}buildSpreadSVGPath(e,t){return null}computeBounds(e){}};function rt(e){return e.radius>0?e.radius:0}function Pn(e,t,n,r,s,i,a){return a.radius<=0?"":Ji(e,t,n,r,s,i,a.radius,a.radius,a.style)}function Ji(e,t,n,r,s,i,a,o,l){let c=e+s*a,u=t+i*a;return l==="angled"?`L ${c} ${u}`:`A ${o} ${o} 0 0 ${n*i-r*s<0?1:0} ${c} ${u}`}var st=Math.PI/180,Yi=class extends Bt{resolveState(e){return Go(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:r,halfHeight:s,ratio:i}=e;if(i>=1)return"";if(!e.isFullShape)return i<=0?ai(e):oi(e);let a=Xt(t,n,r,s,0);return i<=0?a:`${a} ${Xt(t,n,r*i,s*i,1)}`}ringOutline(e){return e.ratio<1?null:e.isFullShape?Xt(e.cx,e.cy,e.halfWidth,e.halfHeight,0):Kf(e)}buildSVGAlignInterior(e){return e.isFullShape?e.ratio>=1?Xt(e.cx,e.cy,e.halfWidth,e.halfHeight,0):null:e.ratio>=1||e.ratio<=0?ai(e):oi(e)}supportsSpread(){return!0}buildSpreadSVGPath(e,t){if(!e.isFullShape||e.ratio>=1)return null;let n=e.halfWidth+t,r=e.halfHeight+t;return n<=0||r<=0?null:Xt(e.cx,e.cy,n,r,0)}computeBounds(e){let{cx:t,cy:n,halfWidth:r,halfHeight:s}=e;return{left:t-r,top:n-s,right:t+r,bottom:n+s}}};function Xt(e,t,n,r,s){let i=e-n;return`M ${i} ${t} A ${n} ${r} 0 1 ${s} ${e+n} ${t} A ${n} ${r} 0 1 ${s} ${i} ${t} Z`}function jr(e){let{cx:t,cy:n,halfWidth:r,halfHeight:s,startAngle:i,sweep:a}=e,o=i+a,l=Math.abs(a)>180?1:0,c=a>0?1:0,u=t+r*Math.cos(i*st),f=n+s*Math.sin(i*st),d=t+r*Math.cos(o*st),_=n+s*Math.sin(o*st);return{start:`${u} ${f}`,arc:`A ${r} ${s} 0 ${l} ${c} ${d} ${_}`}}function Kf(e){let{start:t,arc:n}=jr(e);return`M ${t} ${n}`}function ai(e){let{start:t,arc:n}=jr(e);return`M ${e.cx} ${e.cy} L ${t} ${n} Z`}function oi(e){let{cx:t,cy:n,halfWidth:r,halfHeight:s,startAngle:i,sweep:a,ratio:o}=e,{start:l,arc:c}=jr(e),u=i+a,f=r*o,d=s*o,_=t+f*Math.cos(i*st),p=n+d*Math.sin(i*st);return`M ${l} ${c} L ${t+f*Math.cos(u*st)} ${n+d*Math.sin(u*st)} A ${f} ${d} 0 ${Math.abs(a)>180?1:0} ${a>0?0:1} ${_} ${p} Z`}function qf(e,t,n){if(e.length===0)return"M 0 0";if(e.length===1)return`M ${e[0].x} ${e[0].y}`;let r=Math.max(0,t),s=[],i=e.length,a=(o,l)=>{let c=l.x-o.x,u=l.y-o.y,f=Math.sqrt(c*c+u*u);return f>0?{dx:c/f,dy:u/f,len:f}:{dx:0,dy:0,len:0}};if(r===0){s.push(`M ${e[0].x} ${e[0].y}`);for(let o=1;o<i;o++)s.push(`L ${e[o].x} ${e[o].y}`)}else{let o=n?i:i-1;for(let l=0;l<=o;l++){let c=e[(l-1+i)%i],u=e[l%i],f=e[(l+1)%i];if(!n&&l===0){s.push(`M ${u.x} ${u.y}`);continue}if(!n&&l===i-1){s.push(`L ${u.x} ${u.y}`);continue}let d=a(c,u),_=a(u,f),p=Math.min(r,d.len/2),w=Math.min(r,_.len/2),R=u.x-d.dx*p,L=u.y-d.dy*p,F=u.x+_.dx*w,H=u.y+_.dy*w;s.push(`${l===0&&n?"M":"L"} ${R} ${L}`),s.push(`Q ${u.x} ${u.y} ${F} ${H}`)}}return n&&s.push("Z"),s.join(" ")}var Jf=class extends Bt{resolveState(e){return zo(e)}computeGeometry(){let{points:e,radius:t,closed:n}=this.fullState;return{points:e,radius:t,closed:n}}buildSVGPath(e){return qf(e.points,e.radius,e.closed)}},Yf=class extends Bt{resolveState(e){return Ho(e)}computeGeometry(){return{data:this.fullState.data}}buildSVGPath(e){return Ti(e.data)}};function Xi(e,t,n){if(t.cornerRadius<=0){let i=e.map(([a,o],l)=>`${l===0?"M":"L"} ${a} ${o}`);return i.push("Z"),i.join(" ")}let r=e.length,s=[];for(let i=0;i<r;i++){let a=e[i];if(!n(i)){s.push(`${s.length===0?"M":"L"} ${a[0]} ${a[1]}`);continue}let o=e[(i-1+r)%r],l=e[(i+1)%r],c=o[0]-a[0],u=o[1]-a[1],f=Math.hypot(c,u),d=c/f,_=u/f,p=l[0]-a[0],w=l[1]-a[1],R=Math.hypot(p,w),L=p/R,F=w/R,H=Math.max(-1,Math.min(1,d*L+_*F)),se=Math.tan(Math.acos(H)/2),X=Math.min(t.cornerRadius/se,Math.min(f,R)/2),ye=X*se;s.push(`${s.length===0?"M":"L"} ${a[0]+d*X} ${a[1]+_*X}`),s.push(Ji(a[0],a[1],d,_,L,F,X,ye,t.cornerStyle))}return s.push("Z"),s.join(" ")}var Zi=e=>({left:e.cx-e.rx,top:e.cy-e.ry,right:e.cx+e.rx,bottom:e.cy+e.ry}),Xf=class extends Bt{resolveState(e){return Ko(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:1,cornerRadius:e.cornerRadius,cornerStyle:e.cornerStyle}}buildSVGPath(e){let t=2*Math.PI/e.sides,n=[];for(let r=0;r<e.sides;r++){let s=-Math.PI/2+r*t;n.push([e.cx+e.rx*Math.cos(s),e.cy+e.ry*Math.sin(s)])}return Xi(n,e,()=>!0)}computeBounds(e){return Zi(e)}},Zf=class extends Bt{resolveState(e){return qo(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){let t=Math.PI/e.sides,n=[];for(let r=0;r<e.sides*2;r++){let s=-Math.PI/2+r*t,i=r%2===0?1:e.ratio;n.push([e.cx+e.rx*i*Math.cos(s),e.cy+e.ry*i*Math.sin(s)])}return Xi(n,e,r=>r%2===0)}computeBounds(e){return Zi(e)}};function li(e,t,n,r,s,i,a,o){let l=rt(s),c=rt(i),u=rt(a),f=rt(o);return[`M ${e+l} ${t}`,`L ${n-c} ${t}`,Pn(n,t,-1,0,0,1,i),`L ${n} ${r-u}`,Pn(n,r,0,-1,-1,0,a),`L ${e+f} ${r}`,Pn(e,r,1,0,0,-1,o),`L ${e} ${t+l}`,Pn(e,t,0,1,1,0,s),"Z"].filter(Boolean).join(" ")}var ci=(e,t,n,r)=>`M ${e} ${t} L ${n} ${t} L ${n} ${r} L ${e} ${r} Z`,Qf=class extends Bt{resolveState(e){return Jo(e)}computeGeometry(){let e=this.fullState,t=e.x-e.width/2,n=e.y-e.height/2,r=e.x+e.width/2,s=e.y+e.height/2,i=Rs.resolve(e.cornerRadius),a=xo.resolve(e.cornerStyle),o={radius:Math.max(0,i.topLeft),style:a.topLeft},l={radius:Math.max(0,i.topRight),style:a.topRight},c={radius:Math.max(0,i.bottomRight),style:a.bottomRight},u={radius:Math.max(0,i.bottomLeft),style:a.bottomLeft},f=ui(e.width,e.height,o,l,c,u);return o.radius*=f,l.radius*=f,c.radius*=f,u.radius*=f,{left:t,top:n,right:r,bottom:s,tl:o,tr:l,br:c,bl:u,isZero:Rs.isZero({topLeft:o.radius,topRight:l.radius,bottomRight:c.radius,bottomLeft:u.radius})}}buildSVGPath(e){let{left:t,top:n,right:r,bottom:s,tl:i,tr:a,br:o,bl:l,isZero:c}=e;return c?ci(t,n,r,s):li(t,n,r,s,i,a,o,l)}supportsSpread(){return!0}buildSpreadSVGPath(e,t){let n=e.left-t,r=e.top-t,s=e.right+t,i=e.bottom+t,a=s-n,o=i-r;if(a<=0||o<=0)return null;let l={...e.tl,radius:Math.max(0,e.tl.radius+t)},c={...e.tr,radius:Math.max(0,e.tr.radius+t)},u={...e.br,radius:Math.max(0,e.br.radius+t)},f={...e.bl,radius:Math.max(0,e.bl.radius+t)},d=ui(a,o,l,c,u,f);return l.radius*=d,c.radius*=d,u.radius*=d,f.radius*=d,l.radius===0&&c.radius===0&&u.radius===0&&f.radius===0?ci(n,r,s,i):li(n,r,s,i,l,c,u,f)}computeBounds(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}};function ui(e,t,n,r,s,i){let a=rt(n),o=rt(r),l=rt(s),c=rt(i),u=a+o>0?Math.min(1,e/(a+o)):1,f=c+l>0?Math.min(1,e/(c+l)):1,d=a+c>0?Math.min(1,t/(a+c)):1,_=o+l>0?Math.min(1,t/(o+l)):1;return Math.min(u,f,d,_)}function ed(e,t,n,r,s,i,a,o,l,c){if(r===0||s===0){e.lineTo(l,c);return}r=Math.abs(r),s=Math.abs(s);let u=Math.cos(i),f=Math.sin(i),d=(t-l)/2,_=(n-c)/2,p=u*d+f*_,w=-f*d+u*_,R=p*p/(r*r)+w*w/(s*s);R>1&&(r*=Math.sqrt(R),s*=Math.sqrt(R));let L=r*r*s*s-r*r*w*w-s*s*p*p,F=r*r*w*w+s*s*p*p,H=Math.sqrt(Math.max(0,L/F));a===o&&(H=-H);let se=H*r*w/s,X=-H*s*p/r,ye=u*se-f*X+(t+l)/2,ve=f*se+u*X+(n+c)/2,q=(ae,Ae,$e,Mt)=>Math.atan2(ae*Mt-Ae*$e,ae*$e+Ae*Mt),oe=q(1,0,(p-se)/r,(w-X)/s),K=q((p-se)/r,(w-X)/s,(-p-se)/r,(-w-X)/s);!o&&K>0?K-=2*Math.PI:o&&K<0&&(K+=2*Math.PI);let B=Math.ceil(Math.abs(K)/(Math.PI/2)-1e-9),xe=K/B,we=4/3*Math.tan(xe/4),Te=ae=>[ye+r*Math.cos(ae)*u-s*Math.sin(ae)*f,ve+r*Math.cos(ae)*f+s*Math.sin(ae)*u],Ue=ae=>[-r*Math.sin(ae)*u-s*Math.cos(ae)*f,-r*Math.sin(ae)*f+s*Math.cos(ae)*u];for(let ae=0;ae<B;ae++){let Ae=oe+ae*xe,$e=Ae+xe,[Mt,zn]=Te(Ae),[Nt,Wt]=Te($e),[Hn,_n]=Ue(Ae),[pn,Kn]=Ue($e);e.cubicTo(Mt+we*Hn,zn+we*_n,Nt-we*pn,Wt-we*Kn,ae===B-1?l:Nt,ae===B-1?c:Wt)}}function Nr(e){let t=new at,n=e.match(/[a-zA-Z]|-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g)??[],r=0,s="",i=0,a=0,o=0,l=0,c=0,u=0,f=0,d=0,_="",p=()=>Number(n[r++]),w=()=>r<n.length&&!/[a-zA-Z]/.test(n[r]);for(;r<n.length;){/[a-zA-Z]/.test(n[r])&&(s=n[r++]);let R=s===s.toLowerCase(),L=s.toUpperCase(),F=R?i:0,H=R?a:0;switch(L){case"M":i=F+p(),a=H+p(),t.moveTo(i,a),o=i,l=a,s=R?"l":"L";break;case"L":i=F+p(),a=H+p(),t.lineTo(i,a);break;case"H":i=(R?i:0)+p(),t.lineTo(i,a);break;case"V":a=(R?a:0)+p(),t.lineTo(i,a);break;case"C":{let se=F+p(),X=H+p(),ye=F+p(),ve=H+p();i=F+p(),a=H+p(),t.cubicTo(se,X,ye,ve,i,a),c=ye,u=ve;break}case"S":{let se=_==="C"||_==="S",X=se?2*i-c:i,ye=se?2*a-u:a,ve=F+p(),q=H+p();i=F+p(),a=H+p(),t.cubicTo(X,ye,ve,q,i,a),c=ve,u=q;break}case"Q":f=F+p(),d=H+p(),i=F+p(),a=H+p(),t.quadTo(f,d,i,a);break;case"T":{let se=_==="Q"||_==="T";f=se?2*i-f:i,d=se?2*a-d:a,i=F+p(),a=H+p(),t.quadTo(f,d,i,a);break}case"A":{let se=p(),X=p(),ye=p()*Math.PI/180,ve=p()!==0,q=p()!==0,oe=F+p(),K=H+p();ed(t,i,a,se,X,ye,ve,q,oe,K),i=oe,a=K;break}case"Z":t.close(),i=o,a=l;break;default:r++}_=L,L==="Z"&&w()&&(s="L")}return t.build()}function sn(e,t,n){let r=$o(e,t,n),{x:s,y:i,pivot:a}=Lo(r,t,n);return{...Wo(r),x:s,y:-i,pivot:a}}var Qi=e=>e==null?e:-e;function ea(e,t){let n=new Float32Array(e.points.length);for(let r=0;r<n.length;r+=2){let s=e.points[r],i=e.points[r+1];n[r]=t[0]*s+t[2]*i+t[4],n[r+1]=t[1]*s+t[3]*i+t[5]}return{...e,points:n}}function ta(e,t){let n=e.rotation??0,r=e.scale??1;if(n===0&&r===1)return t;let s=e.pivot??{x:0,y:0},i=(e.x??0)+s.x*((e.width??0)/2),a=(e.y??0)-s.y*((e.height??0)/2),o=n*Math.PI/180,l=Math.cos(o)*r,c=Math.sin(o)*r,u=l,f=-c,d=c,_=l;return ea(t,[u,d,f,_,i-u*i-f*a,a-d*i-_*a])}var td={left:"left",right:"right",center:"center",justify:"justify",start:"left",end:"right"};function nd(e,t){let n=Pi(sn(e,e.width??0,e.height??0)),r=n.path!=null?Nr(Ti(n.path)):void 0,s=n.fontSize==="autofit",i={runs:[{text:n.text,family:n.fontFamily,size:s?100:n.fontSize,weight:n.fontWeight,italic:n.fontStyle==="italic"||n.fontStyle==="oblique",letterSpacing:n.letterSpacing,decoration:n.textDecoration==="underline"?"underline":n.textDecoration==="line-through"?"lineThrough":void 0}],align:td[n.textAlign]??"left",verticalAlign:n.verticalAlign,wrap:n.wrap&&n.width>0,width:n.width,height:n.height,lineHeight:n.lineHeight,fontSize:s?"autofit":void 0,minFontSize:n.minFontSize,path:r};if(r)return{spec:i,transform:[1,0,0,1,0,0],size:[n.width,n.height]};let[a,o]=t(i),l=Fo(n.pivot),c=n.width>0&&n.height>0,u=c?n.width:a,f=c?n.height:o,d=!c&&l.x!==0?n.x-l.x*(a/2):n.x,_=!c&&l.y!==0?n.y+l.y*(o/2):n.y,p=[1,0,0,1,d,_];if((n.rotation??0)!==0||(n.scale??1)!==1){let w=d+l.x*(u/2),R=_-l.y*(f/2),L=(n.rotation??0)*Math.PI/180,F=n.scale??1,H=Math.cos(L)*F,se=Math.sin(L)*F;p=[H,se,-se,H,w+H*(d-w)-se*(_-R),R+se*(d-w)+H*(_-R)]}return{spec:i,transform:p,size:[u,f]}}function In(e,t){return e?ta(t,Nr(e)):null}function Zt(e,t){let n=new e(t),r=n.fullState,s=n.geometry,i=In(n.buildSVGPath(s),r),a=n.needsTrim(),o=a?n.getTrimRange():null,l=i&&o?Dr(i,o.start,o.end):i,c=l,u=n instanceof Yi?n.ringOutline(s):null;if(u!=null){let w=In(u,r);c=w&&o?Dr(w,o.start,o.end):w}let f=n.buildSVGAlignInterior(s),d=f!=null?In(f,r):a?i:l,_=n.computeBounds(s),p=n.supportsSpread()?w=>In(n.buildSpreadSVGPath(s,w),r):void 0;return{fill:l,stroke:c,interior:d,bounds:_?[_.left,_.top,_.right,_.bottom]:null,spread:p,trimmed:!!o}}function rd(e){let t=new Yf(e),n=t.fullState,r=Nr(t.buildSVGPath(t.geometry)),[s,i,a,o]=n.centerBounds??et(r),l=ea(r,[1,0,0,1,-(s+(a-s)/2),-(i+(o-i)/2)]),c=ta({...n,x:0,y:0},l),u=t.needsTrim()?t.getTrimRange():null,f=u?Dr(c,u.start,u.end):c;return{fill:f,stroke:f,interior:u?c:f,bounds:null,trimmed:!!u}}var sd=e=>{let t={...e,y:Qi(e.y)};if(Array.isArray(e.data)&&(t.data=e.data.map(n=>{switch(n.type){case"M":case"m":case"L":case"l":case"T":case"t":case"V":case"v":return{...n,y:-n.y};case"C":case"c":return{...n,y1:-n.y1,y2:-n.y2,y:-n.y};case"S":case"s":return{...n,y2:-n.y2,y:-n.y};case"Q":case"q":return{...n,y1:-n.y1,y:-n.y};case"A":case"a":return{...n,y:-n.y,sweep:n.sweep===1?0:1};default:return n}}),e.centerBounds)){let[n,r,s,i]=e.centerBounds;t.centerBounds=[n,-i,s,-r]}return t};function kr(e){let t=e.state;switch(e.kind){case"rect":return Zt(Qf,sn(t,t.width??0,t.height??0));case"ellipse":{let n=sn(t,t.width??0,t.height??0);return t.startAngle!=null&&(n.startAngle=-t.startAngle),t.sweep!=null&&(n.sweep=-t.sweep),Zt(Yi,n)}case"polygon":return Zt(Xf,sn(t,t.width??0,t.height??0));case"polygram":return Zt(Zf,sn(t,t.width??0,t.height??0));case"line":{let n=t.points?t.points.map(r=>({x:r.x,y:-r.y})):t.points;return Zt(Jf,{...t,y:Qi(t.y),points:n})}case"path":return rd(sd(t))}return null}function id(e,t,n){if(n<=0||e.strength<=0||e.length<=0)return null;let r=vt(e.axis),s=e.length/100,i=t.x*n*r.x*s*e.strength,a=t.y*n*r.y*s*e.strength,o=Math.hypot(i,a);return o<.01?null:{angle:Math.atan2(a,i)*180/Math.PI,radius:o,phase:Oo(e.alignment),samples:e.samples}}var it=.5,na=Math.hypot(1,it),fi=it/na,ad=1/na,od=.35;function ra(e){return e==="arrow"||e==="triangle"||e==="stealth"}function ld(e,t,n){return ra(e)?Math.min(t,n/(2*it)):0}function cd(e,t,n){let r=t/2;switch(e){case"dot":return null;case"triangle":return[0,0,-t,t*it,-t,-t*it];case"stealth":return[0,0,-t,t*it,-t*(1-od),0,-t,-t*it];case"arrow":return ud(t,n);case"box":return[-r,-r,r,-r,r,r,-r,r];case"diamond":return[r,0,0,r,-r,0,0,-r];case"bar":return[-n/2,-r,n/2,-r,n/2,r,-n/2,r]}}function ud(e,t){let n=e*it,r=-e-t*fi,s=n-t*ad;if(s<=0)return[0,0,-e,n,-e,-n];let i=-t/fi;return[0,0,-e,n,r,s,i,0,r,-s,-e,-n]}function fd(e,t,n,r){let s=!!e.dash?.length,i=e.startCap??e.cap,a=e.endCap??e.cap,o=s?e.cap:Dt(a)?"butt":a,l=i!==o||a!==o;if(!s&&!l)return{cap:o,ends:[]};let c=Gf(t),u=s?zf(c,e.dash):null;if(s&&!u)return{cap:o,ends:l?Mr(c,e,i,a,o,n,null):[]};if(!u)return{cap:o,ends:Mr(c,e,i,a,o,n,null)};let d=l?Mr(c,e,i,a,o,n,_=>qi(_,e.dash,e.dashOffset??0,Ki(_,e.dash,u))):[];if(r||d.length||u.open){let _=Hf(c,e.dash,e.dashOffset??0,e.cap!=="butt",u);return _?{cap:o,ends:d,source:_}:null}return{cap:o,ends:d,dash:e.dash.map(_=>_*u.scale),dashPhase:(e.dashOffset??0)*u.scale}}function Mr(e,t,n,r,s,i,a){let o=[],l=(Dt(n)?1:0)+(Dt(r)?1:0),c=i/2,u=Math.min(c,1)/2,f=t.cap!=="butt"?c:0;for(let d of e){if(d.closed)continue;let _=Math.min(t.capScale*i,d.length/Math.max(1,l)),p=a?.(d),w=R=>!p||p.some(([L,F])=>R>=L-f-1e-6&&R<=F+f+1e-6);n!==s&&di(o,d.posTan(0),d.posTan(_),-1,n,_,i,w(u)),r!==s&&di(o,d.posTan(d.length),d.posTan(d.length-_),1,r,_,i,w(d.length-u))}return o}function di(e,[t,n,r,s],i,a,o,l,c,u){let f=a*r,d=a*s;Dt(o)&&ra(o)&&Math.hypot(t-i[0],n-i[1])>1e-6&&(f=t-i[0],d=n-i[1]);let _=Math.hypot(f,d);_<1e-9||e.push({x:t,y:n,dx:f/_,dy:d/_,cap:o,size:l,weight:c,reached:u})}function Sr({x:e,y:t,dx:n,dy:r},s,i){let a=-r*i,o=n*i,l=n*s,c=r*s;return new at().moveTo(e-a,t-o).lineTo(e-a+l,t-o+c).lineTo(e+a+l,t+o+c).lineTo(e+a,t+o).close().build()}function dd({x:e,y:t,dx:n,dy:r},s){let i=new at,a=32;for(let o=0;o<=a;o++){let l=-Math.PI/2+Math.PI*o/a,c=Math.cos(l)*s,u=Math.sin(l)*s,f=e+c*n-u*r,d=t+c*r+u*n;o===0?i.moveTo(f,d):i.lineTo(f,d)}return i.close().build()}function hd(e,t){let{x:n,y:r,dx:s,dy:i,size:a,weight:o}=e,l=cd(t,a,o),c=new at;if(!l){let u=a/2,f=.5522848*u;return c.moveTo(n+u,r).cubicTo(n+u,r+f,n+f,r+u,n,r+u).cubicTo(n-f,r+u,n-u,r+f,n-u,r).cubicTo(n-u,r-f,n-f,r-u,n,r-u).cubicTo(n+f,r-u,n+u,r-f,n+u,r),c.close().build()}for(let u=0;u<l.length;u+=2){let f=n+l[u]*s-l[u+1]*i,d=r+l[u]*i+l[u+1]*s;u===0?c.moveTo(f,d):c.lineTo(f,d)}return c.close().build()}function ht(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((i,a)=>i+a.verbs.length,0)),n=new Float32Array(e.reduce((i,a)=>i+a.points.length,0)),r=0,s=0;for(let i of e)t.set(i.verbs,r),r+=i.verbs.length,n.set(i.points,s),s+=i.points.length;return{verbs:t,points:n}}var _d=class extends Set{node;nodes=new Map;constructor(e){super(),this.node=e}add(e){super.add(e);let t=this.node?.();if(t!==void 0){let n=this.nodes.get(e);n||this.nodes.set(e,n=new Set),n.add(t)}return this}clear(){super.clear(),this.nodes.clear()}},hi=new Set(["rect","ellipse","path","line","polygon","polygram","text","richText"]),_t={kind:"solid",color:[0,0,0,1]},_i={union:"union",subtract:"cut",intersect:"intersect",exclude:"exclude"};function Ar(e){let t=null;for(let n of e){let r=et(n.path),s=n.op??"union";t?s==="union"||s==="exclude"?t=[Math.min(t[0],r[0]),Math.min(t[1],r[1]),Math.max(t[2],r[2]),Math.max(t[3],r[3])]:s==="intersect"&&(t=[Math.max(t[0],r[0]),Math.max(t[1],r[1]),Math.min(t[2],r[2]),Math.min(t[3],r[3])],(t[2]<t[0]||t[3]<t[1])&&(t=[t[0],t[1],t[0],t[1]])):(s==="union"||s==="exclude")&&(t=r)}return t}function pd(e){let t=e[0]*e[3]-e[1]*e[2];if(!t)return null;let n=e[3]/t,r=-e[1]/t,s=-e[2]/t,i=e[0]/t;return[n,r,s,i,-(n*e[4]+s*e[5]),-(r*e[4]+i*e[5])]}var pi=1<<20;function Er(e){let t=(e==="plus-lighter"?"plus":e).replace(/-(\w)/g,(n,r)=>r.toUpperCase());return Fi.includes(t)?t:null}var mi=new WeakMap,md=1<<24;function gi(e){let t=mi.get(e);return t===void 0&&mi.set(e,t=md++),t}var gd=class extends wo{width;height;measure;readsSpaceRects=!0;drawsVisibleOnly=!0;pixelRatio=1;doc;missing=new _d(()=>this.currentNodeStack[this.currentNodeStack.length-1]);shaderIssues=[];storage=null;images=new Map;frameImages=new Map;assets={image:e=>this.image(e),scene3d:(e,t,n,r)=>{let s=new Map;To(e,o=>{if(Po(o)&&!s.has(o)){let l=this.surfaceOf(o);l&&s.set(o,l)}});let i=new Proxy({},{get:(o,l)=>typeof l=="string"?this.image(l)??void 0:void 0}),a=this.doc.addScene3D(e,t,n,{images:i,surfaces:s});return a.scale3d=r,a.version=++pi,a},video:(e,t)=>{let n=this.storage,r=t??this.videoTime(e);if(!n||r===null)return null;let s=n.videoFrame(e.src,r);if(!s)return null;let i=`${wt(e.src)}@${r.toFixed(6)}`,a=this.frameImages.get(i);return a||(a=this.doc.addImage(s,s.width,s.height,{mipmaps:!1}),a.version=gi(s),this.frameImages.set(i,a)),a},imageEdge:(e,t)=>this.storage?.wantImageEdge?.(e,t),deviceScale:()=>{let e=this.device();return Math.sqrt(Math.abs(e[0]*e[3]-e[1]*e[2]))},time:()=>this.elapsed(),checkShader:e=>this.checkShader("fill",e)};image=e=>{let t=wt(e),n=this.frameImages.get(t);if(n)return n;let r=this.images.get(t);return r?(n=this.doc.addImage(r.bitmap,r.width,r.height),n.version=gi(r.bitmap),this.frameImages.set(t,n),n):null};stack=[];scopes=[];worldAlpha=1;shapes=[];painted=!1;shadows=[];constructor(e,t,n){super(),this.width=e,this.height=t,this.measure=n}get cur(){return this.stack[this.stack.length-1]}measureText(e,t,n,r=400,s=0,i){return this.measure(e,t,n,r,s,i)}execute(e){this.doc=new Bi(this.width,this.height,this.clearColor()),this.frameImages.clear(),this.missing.clear(),this.shaderIssues.length=0;let t=this.doc.group(this.doc.root,{transform:this.rootTransform()}),n=this.frameGroup(t);this.stack=n===t?[t]:[t,n],this.scopes=[],this.worldAlpha=1,this.masks=[],this.cameras=[],this.clips=[],this.booleans=[],this.resetSurface(),e()}rootTransform(){return[1,0,0,1,this.width/2,this.height/2]}clearColor(){return[0,0,0,1]}frameGroup(e){return e}screenshot(){}unmount(){}begin(e){super.begin(e),this.scopes.push({groups:1,worldAlpha:this.worldAlpha}),this.stack.push(this.doc.group(this.cur)),this.resetSurface()}end(){let e=this.scopes.pop();if(e){for(let t=0;t<e.groups;t++)this.stack.pop();this.worldAlpha=e.worldAlpha}super.end()}transform(e){let t=e.x??0,n=e.y??0,r=e.width??0,s=e.height??0,i=e.opacity??1,a=e.blend??"pass-through",o,l=e.matrix;if(l)o=[l.a,l.b,l.c,l.d,l.e,l.f,l.g??0,l.h??0,l.i??1];else{let f=e.pivot??{x:0,y:0},d=f.x*(r/2),_=-f.y*(s/2),p=(e.rotation??0)*Math.PI/180,w=e.scale??1,R=Math.cos(p)*w,L=Math.sin(p)*w;o=[R,L,-L,R,t+d-(R*d-L*_),n+_-(L*d+R*_)]}let c=this.cur;c.transform=hr(c.transform,On(o)?o:o.slice(0,6));let u=this.motionBlur((e.effects??[]).filter(f=>f.mode!=="backdrop"));for(let f of u)f.type==="shader"&&this.checkShader("effect",f);if(u.length&&(c.effects=u,c.effectBox=[-r/2,-s/2,r,s],c.effectTime=this.elapsed()),a!=="pass-through"){let f=Er(a);f||this.missing.add(`blend:${a}`),this.stack.push(this.doc.group(c,{opacity:this.worldAlpha*(i<1?i:1),blend:f??"normal"})),this.scopes[this.scopes.length-1].groups++,this.worldAlpha=1}else i<1&&(this.worldAlpha*=i);return this}resetSurface(){this.shapes=[],this.painted=!1,this.shadows=[]}drawGraphics(e){let t=this.worldAlpha,n=e;if(n.needsGroupLayer?.()){let c=n.groupOpacity();c<1&&(this.worldAlpha*=c)}let r=n.groupTransform?.(),s=null;if(r){let{x:c,y:u}=this.groupCenter(e,r.center),f=r.rotation*Math.PI/180,d=Math.cos(f)*r.scale,_=Math.sin(f)*r.scale;s=this.doc.group(this.cur,{transform:[d,_,-_,d,c-(d*c-_*u),u-(_*c+d*u)]}),this.stack.push(s)}let i=e.ops(),a=this.effectSegments(i),o=null;for(let c=0;c<i.length;c++){let u=i[c],f=a.get(c);switch(f&&(o=this.doc.group(this.cur,{effects:f,effectBox:this.viewportBox(),effectTime:this.elapsed()}),this.stack.push(o)),u.kind){case"rect":case"ellipse":case"polygon":case"polygram":case"line":case"path":{this.painted&&this.resetSurface();let d=kr(u);if(!d)break;this.booleans.length?this.collect(d):this.shapes.push(d);break}case"cut":this.cut();break;case"richText":this.painted&&this.resetSurface(),this.richText(u.state);break;case"text":{this.painted&&this.resetSurface();let d=nd(u.state,_=>{let p=_.runs[0],w=this.measureText(p.text,p.size,p.family,p.weight,p.letterSpacing,p.italic?"italic":"normal");return[w.width,w.height]});if(d){let[_,p]=d.size,w=d.transform[4],R=d.transform[5];this.shapes.push({fill:null,stroke:null,interior:null,bounds:[w-_/2,R-p/2,w+_/2,R+p/2],text:d})}else this.missing.add("text:path");break}case"fill":this.fill(Eo.resolve(u.fills));break;case"stroke":this.stroke(Vo.resolve(u.strokes));break;case"shadow":this.shadows=No.resolve(u.shadows);break;case"effects":o&&(this.stack.splice(this.stack.lastIndexOf(o)),o=null),this.resetSurface();break;case"mask":this.beginMask(u.options);break;case"applyMask":this.applyMask();break;case"endMask":this.endMask();break;default:this.missing.add(`op:${u.kind}`)}}let l=s??o;l&&this.stack.splice(this.stack.lastIndexOf(l)),this.worldAlpha=t}effectSegments(e){let t=new Map,n=0,r=!1;return e.forEach((s,i)=>{if(hi.has(s.kind))r&&(n=i,r=!1);else if(s.kind==="fill"||s.kind==="stroke"||s.kind==="shadow")r=!0;else if(s.kind==="effects"){let a=this.motionBlur(s.effects.filter(o=>o.mode!=="backdrop"));a.length&&t.set(n,a),n=i+1,r=!1}}),t}motionBlur(e){if(!e.some(n=>n.type==="motionBlur"))return e;let t=this.currentRenderState();return e.flatMap(n=>{if(n.type!=="motionBlur")return[n];let r=t?id(n,t.velocity,t.dt):null;return r?((r.phase!==0||Math.round(r.samples)>32)&&this.missing.add("effect:motionBlur-shutter"),[{type:"directionalBlur",radius:r.radius,angle:r.angle}]):[]})}groupCenter(e,t){if(t!==void 0&&typeof t!="string")return{x:t.x,y:t.y};let n=null;for(let a of e.ops()){let o=hi.has(a.kind)&&a.kind!=="text"&&a.kind!=="richText"?kr(a)?.fill:null;if(!o||!o.verbs.length)continue;let l=et(o);n=n?[Math.min(n[0],l[0]),Math.min(n[1],l[1]),Math.max(n[2],l[2]),Math.max(n[3],l[3])]:l}if(!n)return{x:0,y:0};let r=(n[0]+n[2])/2,s=(n[1]+n[3])/2;if(t===void 0)return{x:r,y:s};let i=vo.resolve(t);return{x:r+i.x*((n[2]-n[0])/2),y:s-i.y*((n[3]-n[1])/2)}}viewportBox(){let[e,t,n,r]=this.spaceBounds({space:"global"},[0,0,0,0]);return[e,t,n-e,r-t]}surface(e){let t=this.shapes.map(n=>n[e]).filter(n=>!!n&&n.verbs.length>0);return e==="fill"&&t.length>1&&(t=t.map(n=>Nf(n)<0?Wf(n):n)),t.length?ht(t):null}bounds(e){let t=this.shapes.map(n=>n.bounds).filter(n=>n!==null);return e&&t.length!==this.shapes.length?et(e):t.length?t.reduce((n,r)=>[Math.min(n[0],r[0]),Math.min(n[1],r[1]),Math.max(n[2],r[2]),Math.max(n[3],r[3])]):[0,0,0,0]}leaf(e,t,n){return"members"in t?this.doc.compound(e,{...n,members:t.members}):this.doc.pathNode(e,{...n,path:t.path})}geomBounds(e){return"members"in e?Ar(e.members)??[0,0,0,0]:et(e.path)}spreadGeom(e,t,n){if(!t||"members"in e)return e;let r=[];for(let s of this.shapes){if(s.members||!s.fill||!s.fill.verbs.length)continue;let i=s.spread?s.spread(t):s.fill;i&&i.verbs.length?r.push(i):n||r.push(s.fill)}return r.length?{path:ht(r)}:null}clipTo(e,t){if("path"in t){let[r,s,i,a]=et(t.path);return this.doc.group(e,{clip:{x:r,y:s,w:i-r,h:a-s,r:0,path:t.path}})}let n=this.doc.group(e,{mask:"alpha"});return this.doc.compound(n,{members:t.members,fill:_t}),n}clipOutside(e,t){let n=this.doc.group(e,{mask:"invertAlpha"});return this.leaf(n,t,{fill:_t}),n}fill(e){this.painted=!0,!this.booleans.length&&this.deferring("fill",()=>this.paintFill(e))}deferring(e,t){let n=this.masks[this.masks.length-1],r=n?.apply&&!n.apply.has(e)&&!this.inVectorMask?n.after:null;if(!r)return t();this.stack.push(r);try{t()}finally{this.stack.splice(this.stack.lastIndexOf(r))}}paintFill(e){if(this.paintText(e,null),!e.length)return;let t=this.surface("fill"),n=t?[{path:t}]:[];for(let i of this.shapes)i.members&&n.push({members:i.members});if(!n.length)return;let r=this.bounds(t),s=this.shadows;this.shadows=[];for(let i of n)this.fillGeom(i,r,e,s)}fillGeom(e,t,n,r){if(this.inVectorMask){this.leaf(this.cur,e,{fill:_t});return}let s=[];for(let i of r){if(i.inner)continue;if(i.fill.length===1&&i.fill[0].type==="solid"){let u=Df(i,this.missing);u&&s.push(u);continue}let a=i.offset?.x??0,o=-(i.offset?.y??0),l=this.doc.group(this.cur,{transform:[1,0,0,1,a,o],filter:i.blur>0?{kind:"blur",sigma:i.blur/2}:void 0}),c=this.spreadGeom(e,i.spread??0,!1);for(let u of i.fill){let f=dt(u,this.spaceBounds(u,t),this.missing,this.assets);f&&this.leaf(l,c,{fill:f,opacity:this.worldAlpha*(u.opacity??1)})}}n.forEach((i,a)=>{let o=this.spaceBounds(i,t),l=dt(i,o,this.missing,this.assets);if(!l)return;let c=this.worldAlpha*(i.opacity??1),u=a===0?s:[],f=i.type==="video"?i.preset?.adjustments?.find(_=>_.type==="echo"):void 0;if(f&&f.echoes>0&&f.delay>0){this.echoStack(e,i,o,t,l,c,u,f);return}let d=i.preset?.intensity??1;if(d>0&&d<1&&this.pixelAdjustments(i).length){let _=this.doc.group(this.cur,{opacity:c,blend:this.blendOf(i)});this.mediaPreset(this.leaf(_,e,{fill:l,shadows:u}),i,t),this.leaf(_,e,{fill:l,opacity:1-d});return}this.mediaPreset(this.leaf(this.cur,e,{fill:l,opacity:c,shadows:u,blend:this.blendOf(i)}),i,t)});for(let i of r){if(!i.inner)continue;let a=this.spreadGeom(e,-(i.spread??0),!0),o=i.offset?.x??0,l=-(i.offset?.y??0),[c,u,f,d]=this.geomBounds(e),_=Math.abs(o)+Math.abs(l)+i.blur*2+2,p=this.clipTo(this.cur,e);for(let w of i.fill){let R=dt(w,this.spaceBounds(w,t),this.missing,this.assets);if(!R)continue;let L=this.doc.group(p,{opacity:this.worldAlpha*(w.opacity??1),filter:i.blur>0?{kind:"blur",sigma:i.blur/2}:void 0}),F=this.doc.group(L,a?{mask:"invertAlpha"}:{});a&&this.leaf(F,a,{transform:[1,0,0,1,o,l],fill:_t}),this.doc.rect(F,{transform:[1,0,0,1,c-_,u-_],w:f-c+2*_,h:d-u+2*_,fill:R})}}}richText(e){let t=Yo(e),n=t.spans;if(!n.length)return;let r=[-t.width/2,-t.height/2,t.width/2,t.height/2],s={kind:"solid",color:[0,0,0,0]},i=u=>(u[0]?dt(u[0],r,this.missing,this.assets):null)??s,a=n.map(u=>({text:u.text,family:u.fontFamily,size:u.fontSize,weight:u.fontWeight,italic:u.fontStyle==="italic"||u.fontStyle==="oblique",letterSpacing:u.letterSpacing})),o={runs:a,align:{start:"left",end:"right"}[t.textAlign]??t.textAlign,wrap:t.width>0,width:t.width,lineHeight:t.lineHeight},l=Math.max(1,...n.map(u=>u.fill.length));for(let u=0;u<l;u++){let f=a.map((d,_)=>({...d,paint:i(n[_].fill.slice(u,u+1))}));this.doc.textNode(this.cur,{text:{...o,runs:f},fill:s,opacity:this.worldAlpha})}let c=new Map;n.forEach((u,f)=>u.stroke.forEach((d,_)=>{let p=`${_}|${d.weight}|${d.join}|${d.cap}|${d.miterLimit}`,w=c.get(p);w||c.set(p,w={k:_,st:d,paints:n.map(()=>s)}),w.paints[f]=i(d.fill)}));for(let{st:u,paints:f}of[...c.values()].sort((d,_)=>d.k-_.k)){let d=a.map((_,p)=>({..._,paint:f[p]}));this.doc.textNode(this.cur,{text:{...o,runs:d},opacity:this.worldAlpha,stroke:{paint:s,width:u.weight,join:u.join,cap:u.cap,miter:u.miterLimit}})}}paintText(e,t){for(let n of this.shapes){let r=n.text;if(!r)continue;let s=n.bounds,i=[s[0]-r.transform[4],s[1]-r.transform[5],s[2]-r.transform[4],s[3]-r.transform[5]];for(let a of e){let o=dt(a,i,this.missing,this.assets);if(!o)continue;let l=this.worldAlpha*(a.opacity??1);if(t){let c=p=>({paint:o,width:p,join:t.join,cap:t.cap,miter:t.miterLimit,dash:t.dash,dashPhase:t.dashOffset}),u=Math.max(-1,Math.min(1,t.align??0));if(u===0){this.doc.textNode(this.cur,{transform:r.transform,text:r.spec,opacity:l,stroke:c(t.weight)});continue}let f=p=>this.doc.textNode(p,{transform:r.transform,text:r.spec,fill:_t}),d=(p,w)=>this.doc.textNode(p,{transform:r.transform,text:r.spec,stroke:{paint:_t,width:w,join:t.join,miter:t.miterLimit}}),_=p=>{if(u>0){let L=this.doc.group(this.cur,{mask:"invertAlpha"}),F=this.doc.group(L,{mask:"invertAlpha"});return d(F,p),f(F),L}let w=this.doc.group(this.cur,{mask:"alpha"}),R=this.doc.group(w);return f(R),d(R,p),w};if(Math.abs(u)>=1){let p=this.doc.group(this.cur,{mask:u>0?"invertAlphaEroded":"alphaDilated"});f(p),this.doc.textNode(p,{transform:r.transform,text:r.spec,opacity:l,stroke:c(2*t.weight)})}else{let p=(1+u)*t.weight/2,w=(1-u)*t.weight/2;this.doc.textNode(_(2*(u>0?w:p)),{transform:r.transform,text:r.spec,opacity:l,stroke:c(2*Math.max(p,w))})}}else this.doc.textNode(this.cur,{transform:r.transform,text:r.spec,opacity:l,fill:o})}}}surfaceOf(e){let t=Math.max(1,Math.min(e.maxPixelRatio??1,4)),n=e.width??512,r=e.height??512,s=Math.max(1,Math.ceil(n*t)),i=Math.max(1,Math.ceil(r*t)),a=this.doc.detached({transform:[t,0,0,t,n*t/2,r*t/2]}),o={stack:this.stack,scopes:this.scopes,alpha:this.worldAlpha,shapes:this.shapes,painted:this.painted,shadows:this.shadows,masks:this.masks,clips:this.clips,cameras:this.cameras};this.stack=[a],this.scopes=[],this.worldAlpha=1,this.masks=[],this.clips=[],this.cameras=[],this.resetSurface();try{let c=Bo(e.source);c.kind==="graphics"?this.draw(c.graphics):(c.node.layout({x:0,y:0,width:n,height:r},this),c.node.render(this))}catch(c){this.missing.add("surface:error"),console.warn(c)}finally{Object.assign(this,{stack:o.stack,scopes:o.scopes,worldAlpha:o.alpha,shapes:o.shapes,painted:o.painted,shadows:o.shadows,masks:o.masks,clips:o.clips,cameras:o.cameras})}let l=this.doc.addSurface(a,s,i);return l.version=++pi,l}mediaPreset(e,t,n){let r=this.pixelAdjustments(t);!r.length||(t.preset.intensity??1)<=0||(e.effects=r.map(s=>({...s,clip:!0})),e.effectBox=[n[0],n[1],n[2]-n[0],n[3]-n[1]],e.effectTime=this.elapsed())}pixelAdjustments(e){let t=e;return t.type!=="image"&&t.type!=="video"||!t.preset?[]:(t.preset.adjustments??[]).filter(n=>n.type!=="echo"&&n.type!=="posterizeTime")}echoStack(e,t,n,r,s,i,a,o){let l=Er(o.blend??"screen")??"screen",c=o.decay??.5,u=Math.min(Math.max(0,Math.floor(o.echoes)),32),f=this.videoTime(t);a.length&&this.leaf(this.cur,e,{fill:{kind:"solid",color:[0,0,0,0]},opacity:i,shadows:a});for(let d=u;d>=1&&f!==null;d--){let _=f-d*o.delay;if(_<0)continue;let p=dt(t,n,this.missing,{...this.assets,video:w=>this.assets.video(w,_)});p&&this.leaf(this.cur,e,{fill:p,opacity:i*Math.pow(c,d),blend:l})}this.mediaPreset(this.leaf(this.cur,e,{fill:s,opacity:i,blend:l}),t,r)}videoTime(e){let t=this.storage?.videos.get(wt(e.src));return t?Uo(e,this.currentRenderState()?.elapsed??0,t.duration):null}elapsed(){return this.currentRenderState()?.elapsed??0}spaceBounds(e,t){let n=e.space??"local";if(n==="parent"){let r=this.currentSpaceRects().parent;return r?[r.left,r.top,r.right,r.bottom]:t}if(n==="global"){let r=this.device(),s=r[0]*r[3]-r[1]*r[2];if(!s)return t;let i=(u,f)=>{let d=u-r[4],_=f-r[5];return[(r[3]*d-r[2]*_)/s,(-r[1]*d+r[0]*_)/s]},a=this.width*this.pixelRatio,o=this.height*this.pixelRatio,l=i(0,0),c=i(a,o);return[Math.min(l[0],c[0]),Math.min(l[1],c[1]),Math.max(l[0],c[0]),Math.max(l[1],c[1])]}return t}blendOf(e){let t=e.blend;if(!t||t==="normal")return"normal";let n=Er(t);return n||this.missing.add(`fill:blend:${t}`),n??"normal"}device(){let e=[this.pixelRatio,0,0,this.pixelRatio,0,0];for(let t of this.stack)e=hr(e,t.transform);return e}snap(e,t,n){if(t<=0||Math.abs(n[1])>1e-6||Math.abs(n[2])>1e-6||n[0]===0||n[3]===0)return null;let[r,s,i,a]=et(e);if(i-r<=0||a-s<=0)return null;let o=n[0],l=n[3],c=n[4],u=n[5],f=c+o*r,d=u+l*s,_=c+o*i,p=u+l*a,w=t%2===0?0:.5,R=Math.round(f-w)+w,L=Math.round(d-w)+w,F=Math.round(_-w)+w,H=Math.round(p-w)+w;if(F-R<1||H-L<1)return null;let se=(F-R)/(_-f),X=(H-L)/(p-d);return Math.abs(se-1)<1e-4&&Math.abs(X-1)<1e-4&&Math.abs(R-f)<1e-4&&Math.abs(L-d)<1e-4?null:[se,0,0,X,(R-c)/o-se*r,(L-u)/l-X*s]}stroke(e){this.painted=!0,!this.booleans.length&&this.deferring("stroke",()=>this.paintStroke(e))}paintStroke(e){for(let i of e)this.paintText(i.fill,i);let t=this.surface("fill"),n=this.device(),r=Math.sqrt(Math.abs(n[0]*n[3]-n[1]*n[2])),s=On(n)||Math.abs(n[1])>1e-6||Math.abs(n[2])>1e-6;for(let i of e){let a=i.weight,o=-1;!s&&a>0&&r>0&&a*r<2.5&&(o=Math.max(1,Math.round(a*r)),a=o/r);for(let l of this.strokeShapes()){let c,u,f={cap:i.cap,ends:[],dash:i.dash,dashPhase:i.dashOffset};if(l.members)c=u={members:l.members};else{if(!l.stroke||!l.stroke.verbs.length)continue;let L=fd(i,l.stroke,a,o>0);if(!L)continue;f=L,c={path:L.source??l.stroke},u=l.alignInterior?{members:l.alignInterior}:l.interior&&ii(l.interior)?{path:l.interior}:null}let d=this.bounds(t??("path"in c?c.path:null)),_=Math.max(-1,Math.min(1,i.align??0)),p=_!==0&&u!==null&&!f.ends.some(L=>Dt(L.cap))?[[(1+_)*a,"out"],[(1-_)*a,"in"]]:[[a,"both"]],w=l.fill?this.snap(l.fill,o,n):null,R=w?this.doc.group(this.cur,{transform:w}):this.cur;for(let L of i.fill){let F=dt(L,this.spaceBounds(L,d),this.missing,this.assets);if(!F)continue;let H=this.worldAlpha*(L.opacity??1);for(let[se,X]of p){if(se<=0)continue;let ye={paint:F,width:se,join:i.join,cap:f.cap,miter:i.miterLimit,dash:f.dash,dashPhase:f.dashPhase};X==="both"?this.strokeLeaf(R,c,{opacity:H,stroke:ye,blend:this.blendOf(L)},f.ends):this.strokeLeaf(X==="in"?this.clipTo(R,u):this.clipOutside(R,u),c,{opacity:H,stroke:ye},f.ends)}}}}}strokeShapes(){if(this.shapes.some(r=>r.text))return this.shapes;let e=this.shapes.filter(r=>r.members||r.fill&&r.fill.verbs.length).sort((r,s)=>(s.members?1:0)-(r.members?1:0));if(e.length<2)return this.shapes;let t=[];for(let r of e)r.members?r.members.forEach((s,i)=>t.push({...s,op:i===0?"union":s.op})):t.push({kind:"path",path:r.fill,op:"union"});e.filter(r=>r.members).length>1&&this.missing.add("stroke:union-of-booleans");let n=e.every(r=>r.bounds)?e.map(r=>r.bounds).reduce((r,s)=>[Math.min(r[0],s[0]),Math.min(r[1],s[1]),Math.max(r[2],s[2]),Math.max(r[3],s[3])]):null;return e.some(r=>!r.members&&(r.stroke!==r.fill||r.trimmed||!ii(r.fill)))?e.some(r=>r.members)?this.shapes:[{fill:ht(e.map(r=>r.fill)),stroke:ht(e.map(r=>r.stroke??r.fill)),interior:null,alignInterior:t,bounds:n}]:[{fill:null,stroke:null,interior:null,bounds:n,members:t}]}strokeLeaf(e,t,n,r){if(!r.length)return this.leaf(e,t,n);let s=n.stroke.width/2,i=s*1.01+.5,a=n.stroke.cap!=="butt",o=[],l=[];for(let f of r){if(Dt(f.cap)){let d=ld(f.cap,f.size,f.weight);(d>0||a)&&o.push(Sr({...f,x:f.x-f.dx*d,y:f.y-f.dy*d},d+i,i)),l.push(hd(f,f.cap));continue}a&&o.push(Sr(f,i,i)),f.reached&&f.cap!=="butt"&&l.push(f.cap==="round"?dd(f,s):Sr(f,s,s))}let c=this.doc.group(e,{opacity:n.opacity??1,blend:n.blend??"normal"}),u={...n,opacity:1,blend:"normal"};if(o.length){let f=this.doc.group(c,{mask:"invertAlpha"});this.doc.pathNode(f,{path:ht(o),fill:_t}),this.leaf(f,t,u)}else this.leaf(c,t,u);return l.length&&this.doc.pathNode(c,{path:ht(l),fill:n.stroke.paint}),c}booleans=[];beginBoolean(e){this.booleans.push({op:e,base:pd(this.device()),members:[]}),this.resetSurface()}endBoolean(){let e=this.booleans.pop();if(this.resetSurface(),!e||!e.members.length)return;let t=this.booleans[this.booleans.length-1];if(!t){this.shapes.push({fill:null,stroke:null,interior:null,bounds:Ar(e.members),members:e.members});return}let n=this.relative(t.base),r=_i[t.op],s=!t.members.length;!s&&!e.members.slice(1).every(i=>i.op===(r==="cut"?"union":r))&&this.missing.add("boolean:nested"),e.members.forEach((i,a)=>{let o=i.op??"union",l=s?o:a===0||r==="cut"?r:o;t.members.push({kind:"path",path:n?Gs(i.path,n):i.path,op:l})})}relative(e){let t=this.device();return!e||On(t)?null:hr(e,t)}collect(e){let t=this.booleans[this.booleans.length-1],n=e.fill;if(!n||!n.verbs.length)return;let r=this.relative(t.base);r||this.missing.add("boolean:projective"),t.members.push({kind:"path",path:r?Gs(n,r):n,op:t.members.length?_i[t.op]:"union"})}cut(){let e=this.shapes.filter(n=>n.members||n.fill&&n.fill.verbs.length);if(this.resetSurface(),!e.length)return;let t=[];e.forEach((n,r)=>{let s=r>0&&r===e.length-1?"cut":"union";if(!n.members){t.push({kind:"path",path:n.fill,op:s});return}r>0&&this.missing.add("cut:compound"),n.members.forEach((i,a)=>t.push({...i,op:a===0?s:i.op}))}),this.shapes.push({fill:null,stroke:null,interior:null,bounds:Ar(t),members:t})}masks=[];get inVectorMask(){let e=this.masks[this.masks.length-1];return!!e&&e.open&&e.vector}beginMask(e){let t=e?.mode??"alpha",n=t==="luminance",r=e?.inverted?n?"invertLuminance":"invertAlpha":n?"luminance":"alpha",s=this.doc.group(this.cur,{mask:r}),i=e?.apply?new Set(Array.isArray(e.apply)?e.apply:[e.apply]):null,a=i?this.doc.group(this.cur):null;this.stack.push(s,this.doc.group(s)),this.masks.push({vector:t==="vector",open:!0,apply:i,after:a}),this.resetSurface()}applyMask(){let e=this.masks[this.masks.length-1];e?.open&&(e.open=!1,this.stack.pop(),this.resetSurface())}endMask(){let e=this.masks.pop();e&&(e.open&&this.stack.pop(),this.stack.pop(),this.resetSurface())}clips=[];clipGeom(e){let t=[];for(let n of e.ops()){if(n.kind==="cut"){t.length>1&&(t[t.length-1].op="cut");continue}let r=kr(n)?.fill;r&&r.verbs.length&&t.push({kind:"path",path:r,op:"union"})}return t.length?t.some(n=>n.op==="cut")?{members:t}:{path:ht(t.map(n=>n.path))}:null}beginClip(e){let t=this.clipGeom(e);if(!t){this.clips.push({pushed:0,geom:null});return}let n=this.clipTo(this.cur,t);"members"in t?this.stack.push(n,this.doc.group(n)):this.stack.push(n),this.clips.push({pushed:"members"in t?2:1,geom:t})}endClip(){let e=this.clips.pop()?.pushed??0;for(let t=0;t<e;t++)this.stack.pop()}cameras=[];beginCamera(e,t,n,r){let s=this.doc.group(this.cur,{clip:{x:e.x-e.width/2,y:e.y-e.height/2,w:e.width,h:e.height,r:0}}),i=-r*Math.PI/180,a=Math.cos(i)*n,o=Math.sin(i)*n,l=-t.x,c=t.y,u=this.doc.group(s,{transform:[a,o,-o,a,e.x+a*l-o*c,e.y+o*l+a*c]});this.stack.push(s,u),this.cameras.push(2)}endCamera(){let e=this.cameras.pop()??0;for(let t=0;t<e;t++)this.stack.pop()}beginEffects(e,t,n,r){if(t!=="backdrop")return;for(let i of e)i?.type==="shader"&&this.checkShader("effect",i);let s=this.clips[this.clips.length-1]?.geom;if(!s){let[i,a,o,l]=this.viewportBox();s={path:new at().moveTo(i,a).lineTo(i+o,a).lineTo(i+o,a+l).lineTo(i,a+l).close().build()}}this.leaf(this.cur,s,{effects:e,effectBox:[-n/2,-r/2,n,r],effectTime:this.elapsed()})}endEffects(){}checkShader(e,t){let n=this.currentNodeStack[this.currentNodeStack.length-1];for(let r of Bf(e,t))this.shaderIssues.push(n===void 0?r:{...r,nodeId:n})}rasterize(){return this.missing.add("rasterize"),null}},sa={normal:0,italic:1,oblique:2},bd={left:0,right:1,center:2,justify:3,start:4,end:5},wd={top:0,center:1,bottom:2},bi=new WeakMap;function ia(e){let t=bi.get(e);if(!t){let n=t=new Pr;for(let r of e.fonts)n.register_font(r.bytes,r.family);e.onFont(r=>n.register_font(r.bytes,r.family)),bi.set(e,n)}return t}function aa(e,t,n,r,s=400,i=0,a){let[o,l]=e.measure_text(t,n,r,s,i,sa[a??"normal"]??0);return{width:o,height:l}}function yd(e,t){let n=Pi(t);if(n.path!=null)return null;let r=n.fontSize==="autofit",s={text:String(n.text??""),fontFamily:n.fontFamily,fontSize:r?100:n.fontSize,fontWeight:n.fontWeight,fontStyle:n.fontStyle,letterSpacing:n.letterSpacing},i=Array.isArray(n.segments)&&n.segments.length?n.segments:[s];if(i.some(p=>(p.x??0)!==0||(p.y??0)!==0||(p.rotation??0)!==0||(p.scale??1)!==1))return null;let a=[],o=[],l="";for(let p of i){let w=p.fontFamily??s.fontFamily??"",R=a.indexOf(w);R<0&&(R=a.push(w)-1);let L=String(p.text??"");l+=L,o.push(L.length,p.fontSize??s.fontSize,p.fontWeight??s.fontWeight??400,sa[p.fontStyle??s.fontStyle??"normal"]??0,p.letterSpacing??s.letterSpacing??0,R)}let c=n.width??0,u=n.height??0,f=e.text_block(l,new Float32Array(o),a.join(`
703
+ `),r?NaN:s.fontSize,n.minFontSize??0,n.lineHeight??0,bd[n.textAlign??"center"]??2,wd[n.verticalAlign??"center"]??1,!!n.wrap&&c>0,c,u);if(!f.length)return null;let d=[],_=3;for(let p=0;p<f[2];p++){let[w,R,L,F,H]=f.subarray(_,_+5);d.push({start:w,end:R,top:L,bottom:F,carets:Array.from(f.subarray(_+5,_+5+H))}),_+=5+H}return{lines:d,width:f[0],height:f[1]}}var vd=3,xd=6e4,kd=32,Lr=new Set,ln=new Set,wi=new WeakSet,Qt=[],Md=0,Ft=null,yi=!1;function Sd(e){return Lr.add(e),()=>Lr.delete(e)}function Ad(){return Ft}function Ed(e){return Rd(),ln.add(e),Ft!==null&&(e.queueIssue(oa(Ft)),e.halt()),()=>ln.delete(e)}function Td(e){let t=e;!t||wi.has(t)||(wi.add(t),t.addEventListener?.("uncapturederror",n=>Pd(n.error)),t.lost.then(n=>Id(n.reason??"unknown",n.message??"")))}function Fn(e){for(let t of[...Lr])try{t(e)}catch(n){console.error("[wgpu] a fault listener threw:",n)}}function Wr(e){for(let t of ln)t.queueIssue(e)}function Pd(e){if(++Md>kd)return;let t=e?.constructor?.name??"",n=t==="GPUOutOfMemoryError"?"out-of-memory":t==="GPUInternalError"?"internal":"validation",r=`WebGPU ${n} error: ${e?.message??String(e)}`;Wr({kind:"gpu",feature:`gpu:${n}`,message:r}),Fn({type:"gpu-error",error:n,message:r})}function Id(e,t){if(Ft!==null)return;kf();let n=performance.now();for(;Qt.length&&n-Qt[0]>xd;)Qt.shift();let r=`The GPU device was lost (${e}${t?`: ${t}`:""}); the renderer is drawing on a new one.`;if(Fn({type:"device-lost",reason:e,message:r}),Qt.length>=vd){Fr("The GPU device was lost 4 times within a minute; the renderer stopped asking for a new one.");return}Qt.push(n),Wr({kind:"device-lost",message:r});for(let s of[...ln])s.remount();Br().then(()=>Fn({type:"device-restored"}),s=>Fr(`No GPU device after a loss: ${String(s?.message??s)}`))}function oa(e){return{kind:"crashed",message:e}}function Fr(e){Ft===null&&(Ft=e,queueMicrotask(()=>{Wr(oa(e));for(let t of[...ln])t.halt();Fn({type:"crashed",message:e})}))}function Rd(){yi||(yi=!0,dl(e=>Fr(`The renderer panicked and draws nothing more on this page (reload to recover): ${e}`)))}var vi=new Set,Cd=/-not-(?:decoded|loaded)$/,Rn={"text:path":"Text on a path",rasterize:"rasterize()","boolean:nested":"A boolean nested in one of another kind","boolean:projective":"A boolean under a 3D (projective) transform","cut:compound":"A cut through a compound shape","stroke:union-of-booleans":"One stroke around several booleans","effect:motionBlur-shutter":"Motion blur with an off-centre shutter or over 32 samples","surface:error":"A surface texture that failed to draw","blend:":"The blend mode","fill:blend:":"The fill blend mode","op:":"The drawing op","fill:":"The fill","effect:":"The effect","3d:":"In 3D,"};function Tr(e){if(Rn[e])return`${Rn[e]} is not drawn by the WebGPU renderer.`;let t=Object.keys(Rn).filter(n=>n.endsWith(":")&&e.startsWith(n)).sort((n,r)=>r.length-n.length)[0];return t?`${Rn[t]} "${e.slice(t.length)}" is not drawn by the WebGPU renderer.`:`Not drawn by the WebGPU renderer: ${e}.`}var Od=class extends gd{store;view={zoom:1,x:0,y:0};frame=null;clipToFrame=!0;frameBackground="black";canvas=null;size={width:1,height:1};backend=null;starting=null;startFailed=!1;startToken=null;lastDoc=null;viewportKey="";shaper;stopFonts;stopSettle;stopFaults;faults=[];halted=!1;constructor(e,t){let n=ia(e);super(t.width,t.height,(r,s,i,a,o,l)=>aa(n,r,s,i,a,o,l)),this.store=e,this.shaper=n,this.storage=e,this.images=e.images,this.stopFonts=e.onFont(r=>this.backend?.registerFont(r.bytes,r.family)),this.stopSettle=e.addSettler(()=>this.starting&&!this.startFailed?this.starting.catch(()=>{}):this.backend?.shaders.hasPending()?this.backend.whenShadersReady():null),this.stopFaults=Ed({queueIssue:r=>this.faults.push(r),remount:()=>this.remount(),halt:()=>this.halt()})}stats(){return this.backend?.stats()??null}mount(e){let t=e;if(this.size={width:Math.max(1,t.width),height:Math.max(1,t.height)},t===this.canvas&&(this.backend||this.starting)){this.present();return}if(this.releaseBackend(),this.canvas=t,this.halted||Ad()!==null)return;let n={};this.startToken=n,this.startFailed=!1;let r=this.starting=(async()=>{let s=new zi;if(await s.init(t,this.size.width,this.size.height),this.startToken!==n){this.halted||s.destroy();return}Td(s.gpuDevice()),s.setOptions(!1,!1),s.collectUnused=!0,s.onShaderReady=()=>this.present();for(let i of this.store.fonts)s.registerFont(i.bytes,i.family);this.backend=s,this.starting=null,this.present()})();r.catch(s=>{this.starting===r&&(this.startFailed=!0),console.error("[wgpu] the renderer failed to start:",s)})}whenMounted(){return this.starting??Promise.resolve()}unmount(){this.releaseBackend(),this.canvas=null}execute(e){if(!(!this.canvas||this.isDisposed())){this.width=this.size.width/this.pixelRatio,this.height=this.size.height/this.pixelRatio;try{super.execute(e)}finally{this.lastDoc=this.doc,this.present();for(let t of this.missing)vi.has(t)||t.endsWith("-not-decoded")||(vi.add(t),console.warn(`[wgpu] not drawn yet: ${t}`))}}}takeRenderIssues(){let e=new Map,t=r=>e.set(Io(r),r);for(let r of this.faults.splice(0))t(r);let n=this.halted?null:this.backend;for(let r of n?.shaderIssues??[])t({kind:"shader",...r==="A shader effect is written in SkSL, which Motion Script no longer runs, so it is skipped. Port it to WGSL (fn effect(in: EffectIn) -> vec4f)."&&{feature:"effect:shader-sksl"},message:r});n?.shaderIssues.clear();for(let r of this.shaderIssues)t(r);for(let r of this.missing){if(Cd.test(r))continue;let s=r==="fill:shader-sksl"?{kind:"shader",feature:r,message:yf}:{kind:"missing",feature:r,message:Tr(r)},i=this.missing.nodes.get(r);if(!i?.size)t(s);else for(let a of i)t({...s,nodeId:a})}for(let r of n?.missing??[])t({kind:"missing",feature:`effect:${r}`,message:Tr(`effect:${r}`)});for(let r of n?.missing3d??[])t({kind:"missing",feature:`3d:${r}`,message:Tr(`3d:${r}`)});return[...e.values()]}whenShadersReady(){return this.backend?.whenShadersReady()??Promise.resolve()}layoutTextBlock(e){return yd(this.shaper,e)}screenshot(e="image/png",t){return this.snapshotCanvas()?.toDataURL(e,t)}snapshotCanvas(){let e=this.canvas;if(!e||!this.backend||!this.lastDoc)return;this.present();let[t,n,r,s]=[0,0,e.width,e.height];if(this.frame){let o=this.pixelRatio,l=this.view.zoom,c=e.width/2+this.view.x*o,u=e.height/2+this.view.y*o,f=this.frame.width*l*o,d=this.frame.height*l*o;t=Math.max(0,Math.round(c-f/2)),n=Math.max(0,Math.round(u-d/2)),r=Math.max(1,Math.min(e.width-t,Math.round(f))),s=Math.max(1,Math.min(e.height-n,Math.round(d)))}let i=document.createElement("canvas");i.width=r,i.height=s;let a=i.getContext("2d");if(a)return a.drawImage(e,t,n,r,s,0,0,r,s),i}dispose(){this.releaseBackend(),this.stopFonts(),this.stopSettle(),this.stopFaults(),this.canvas=null,this.lastDoc=null,this.store.dispose(),super.dispose()}rootTransform(){let e=this.view.zoom;return[e,0,0,e,this.width/2+this.view.x,this.height/2+this.view.y]}clearColor(){return this.frame?[0,0,0,0]:[0,0,0,1]}frameGroup(e){let t=this.frame;if(!t)return e;let n={x:-t.width/2,y:-t.height/2,w:t.width,h:t.height};return this.frameBackground==="black"&&this.doc.rect(e,{transform:[1,0,0,1,n.x,n.y],w:n.w,h:n.h,fill:{kind:"solid",color:[0,0,0,1]}}),this.clipToFrame?this.doc.group(e,{clip:{...n,r:0}}):e}present(){let e=this.backend,t=this.canvas,n=this.lastDoc;if(!e||!t||!n||this.halted)return;let{width:r,height:s}=this.size,i=`${r}x${s}/${n.width}/${n.background.join(",")}`;(i!==this.viewportKey||t.width!==r||t.height!==s)&&(e.resize(r,s),this.viewportKey=i);try{e.sync(n),e.render()}catch(a){console.error("[wgpu] frame failed:",a)}}releaseBackend(){this.starting=null,this.startToken=null,this.halted||this.backend?.destroy(),this.backend=null,this.viewportKey=""}remount(){let e=this.canvas;!e||this.isDisposed()||this.halted||(this.releaseBackend(),this.mount(e))}halt(){this.halted=!0,this.releaseBackend()}};async function $d(e,t,n){return await cn(n),Gi(e,t)}var Dd={fill:`// Provided to every WGSL fill:
704
+ struct FillIn {
705
+ uv: vec2f, // 0\u20131 across the fill's box, y down
706
+ local: vec2f, // px from the box's top-left
707
+ size: vec2f, // the box, px
708
+ time: f32, // the node's elapsed seconds
709
+ scale: f32, // device px per px
710
+ }
711
+ var<uniform> u: Params; // your struct Params, if you declare one
712
+ fn sample_texture(uv: vec2f) -> vec4f // the fill's first texture, premultiplied
713
+
714
+ // You write:
715
+ fn fill(in: FillIn) -> vec4f // premultiplied rgba, opacity not folded in
716
+ `,effect:`// Provided to every WGSL effect:
717
+ struct EffectIn {
718
+ uv: vec2f, // 0\u20131 across the node's box, y down
719
+ px: vec2f, // device px (what sample_src_px takes)
720
+ local: vec2f, // px from the box's top-left
721
+ size: vec2f, // the box, px
722
+ time: f32, // the node's elapsed seconds
723
+ scale: f32, // device px per px
724
+ node: vec2f, // 0\u20131 across the node's own box: turns and scales with it
725
+ node_size: vec2f, // the node's own box, px
726
+ }
727
+ var<uniform> u: Params; // your struct Params, if you declare one
728
+ fn sample_src(uv: vec2f) -> vec4f // the input at box uv: the node's layer, or the backdrop
729
+ fn sample_src_px(px: vec2f) -> vec4f // the same at device px; clamped at the input's edge
730
+
731
+ // You write:
732
+ fn effect(in: EffectIn) -> vec4f // premultiplied rgba
733
+ `},Ld=.14,Fd=.06,xi=[[.98,.45,.4],[.35,.8,.5],[.35,.65,.98]],Bd=class la{backend;canvas;onDraw=null;last=null;images=new WeakMap;version=0;size="";constructor(t,n){this.backend=t,this.canvas=n}static async create(t,n){await cn(n);let r=new zi;await r.init(t,Math.max(1,t.width),Math.max(1,t.height)),r.setOptions(!1,!1),r.collectUnused=!0;let s=new la(r,t);return r.onShaderReady=()=>{s.last&&(s.draw(s.last),s.onDraw?.())},s}draw(t){this.last=t;let n=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.size!==`${n}x${r}`&&(this.backend.resize(n,r),this.size=`${n}x${r}`);let s=this.build(t,n,r);return this.backend.sync(s),this.backend.render(),this.status(t.scope,t.source)}async pixels(t){this.draw(t),await this.whenReady(),this.draw(t);let n=await this.backend.readPixels(),r=Math.max(1,this.canvas.width),s=Math.max(1,this.canvas.height),i=Uint8ClampedArray.from(n.subarray(0,r*s*4));for(let a=0;a<i.length;a+=4){let o=i[a+3];o===0||o===255||(i[a]=i[a]*255/o,i[a+1]=i[a+1]*255/o,i[a+2]=i[a+2]*255/o)}return new ImageData(i,r,s)}async snapshot(t,n="image/png",r){let s=await this.pixels(t),i=new OffscreenCanvas(s.width,s.height);return i.getContext("2d").putImageData(s,0,0),i.convertToBlob({type:n,quality:r})}whenReady(){return this.backend.whenShadersReady()}status(t,n){if(!n.trim())return{state:"empty",diagnostics:[]};let r=this.backend.shaders.program(t,n);return{state:r.state,diagnostics:[...r.report.diagnostics,...r.browser]}}destroy(){this.backend.onShaderReady=void 0,this.backend.destroy(),this.last=null}build(t,n,r){let s=new Bi(n,r,[0,0,0,0]),i=s.root,a=w=>t.image?this.cover(s,w,t.image,n,r):Ud(s,w,n,r),o=t.split==null?0:Math.min(1,Math.max(0,t.split))*n;if(t.scope==="fill"){t.image&&a(i);let w={kind:"shader",source:t.source,uniforms:t.uniforms,box:[0,0,n,r],time:t.time,...t.texture?{texture:this.asset(s,t.texture)}:{}},R=o>0?s.group(i,{clip:{x:o,y:0,w:n-o,h:r,r:0}}):i;return s.rect(R,{w:n,h:r,fill:w}),s}a(i);let l=Math.min(n,r),c=t.frame==="inset",u=c?l*Ld:0,f={x:u,y:u,w:n-2*u,h:r-2*u,r:c?l*Fd:0},d={type:"shader",language:"wgsl",source:t.source,uniforms:t.uniforms,mode:t.backdrop?"backdrop":"foreground",...t.blendMode&&!t.backdrop?{blendMode:t.blendMode}:{},...t.reach?{reach:t.reach}:{}},_=o>0?s.group(i,{clip:{x:o,y:0,w:n-o,h:r,r:0}}):i,p=[f.x,f.y,f.w,f.h];return t.backdrop?s.rect(_,{transform:[1,0,0,1,f.x,f.y],w:f.w,h:f.h,radii:[f.r,f.r,f.r,f.r],effects:[d],effectBox:[0,0,f.w,f.h],effectTime:t.time}):a(s.group(_,{clip:f,effects:[d],effectBox:p,effectTime:t.time})),s}asset(t,n){let r=t.addImage(n,n.width,n.height,{mipmaps:!1}),s=this.images.get(n);return s===void 0&&this.images.set(n,s=++this.version),r.version=s,r}cover(t,n,r,s,i){t.rect(n,{w:s,h:i,fill:{kind:"image",image:this.asset(t,r),fit:"fill",box:[0,0,s,i]}})}};function Ud(e,t,n,r){e.rect(t,{w:n,h:r,fill:{kind:"linear",from:[0,0],to:[n,r],stops:[{offset:0,color:[.16,.2,.42,1]},{offset:1,color:[.55,.25,.45,1]}]}});let s=Math.min(n,r),i=Math.max(12,Math.round(s/12)),a={kind:"solid",color:[1,1,1,.3]};for(let f=i;f<n;f+=i)e.rect(t,{transform:[1,0,0,1,f-.5,0],w:1,h:r,fill:a});for(let f=i;f<r;f+=i)e.rect(t,{transform:[1,0,0,1,0,f-.5],w:n,h:1,fill:a});let o=n/2,l=r/2,c=s*.1;xi.forEach((f,d)=>{let _=-Math.PI/2+d*2*Math.PI/xi.length,p=o+Math.cos(_)*s*.17,w=l+Math.sin(_)*s*.17;e.ellipse(t,{transform:[1,0,0,1,p-c,w-c],w:2*c,h:2*c,fill:{kind:"solid",color:[...f,1]}})});let u=s*.3;e.ellipse(t,{transform:[1,0,0,1,o-u,l-u],w:2*u,h:2*u,stroke:{paint:{kind:"solid",color:[1,1,1,.85]},width:Math.max(1.5,s/90)}})}async function Vr(){let e=navigator.gpu;if(!e)return!1;try{return await e.requestAdapter()!=null}catch{return!1}}async function ca(e={}){await cn(e.wasmUrl),Br().catch(()=>{});let{loadBytes:t}=e;return{createStorageAdapter({catalog:n,viewport:r,fps:s}){return new $f(n,r,s,t)},createRenderContext(n){return new Od(n,n.size)},createMeasureContext(n){let r=ia(n);return{measureText:(...s)=>aa(r,...s)}}}}var Bn=class extends Error{constructor(){super("Motion Script draws with WebGPU, and this browser has no WebGPU adapter."),this.name="WebGpuUnavailableError"}};async function ot(e={},{gpu:t=!0}={}){if(t&&!await Vr())throw new Bn;return ca({wasmUrl:e.rendererWasmUrl,loadBytes:qn})}function Un(e,t){if(t.returnBytes)return e;let n=new Blob([e.buffer],{type:t.mimeType}),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=t.filename,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(r)}var zr={mp4:{kind:"video",extension:"mp4",mimeType:"video/mp4",container:()=>new Xn,audioCodec:"aac",video:{codecs:["avc","hevc","av1","vp9"],fallback:"avc"}},webm:{kind:"video",extension:"webm",mimeType:"video/webm",container:()=>new bs,audioCodec:"opus",video:{codecs:["vp9","av1","vp8"],fallback:"vp8"}},wav:{kind:"audio",extension:"wav",mimeType:"audio/wav",container:()=>new ys,audioCodec:"pcm-s16"},mp3:{kind:"audio",extension:"mp3",mimeType:"audio/mpeg",container:()=>new ws,audioCodec:"mp3"},m4a:{kind:"audio",extension:"m4a",mimeType:"audio/mp4",container:()=>new Xn,audioCodec:"aac"}},jd=zr;function Be(e){let t=zr[e];if(!t)throw new RangeError(`"${String(e)}" is not an export format; expected one of ${Object.keys(zr).join(", ")}.`);return t}function ua(e){return Be(e).kind==="audio"}var Hr=192e3,Nd=48e3;function Ut(e,t=Hr){let n=Be(e).audioCodec;return new gs({codec:n,bitrate:t,...n==="opus"&&{transform:{sampleRate:Nd}}})}var Gr=null;async function jn(e){let t=Be(e).audioCodec;if(t==="mp3"){Gr??=(async()=>{if(await Yn("mp3"))return;let{registerMp3Encoder:n}=await import("./chunks/mediabunny-mp3-encoder-ZCIHVVTJ.js");n()})();try{await Gr}catch(n){throw Gr=null,n}return}if(!t.startsWith("pcm-")&&!await Yn(t))throw new Error(`This browser has no ${t.toUpperCase()} encoder, so it cannot export ${e.toUpperCase()} audio.`)}var Hd=.2,Kd=2e6,qd=1e8;function ha(e,t,n){let r=e*t*n*Hd;return Math.round(Math.min(qd,Math.max(Kd,r)))}var Jd=1,Yd=2,Xd={image:{},video:{},audio:{},font:{}},un=class{format;audioOptions;target=new Et;output;video;audio=null;constructor(t,n,r,s,i={}){this.format=r,this.audioOptions=i;let a=n.width!==t.width||n.height!==t.height;this.video=new ms(t,{codec:s.codec,bitrate:s.bitrate,hardwareAcceleration:s.hardwareAcceleration,keyFrameInterval:s.keyFrameInterval,latencyMode:s.latencyMode,contentHint:s.contentHint,...s.bitrateMode!==void 0&&{bitrateMode:s.bitrateMode},...a&&{transform:{width:n.width,height:n.height,fit:"fill"}}}),this.output=new Tt({format:Be(r).container(),target:this.target})}async start(t){this.output.addVideoTrack(this.video,{frameRate:t.fps}),t.hasAudio&&(await jn(this.format),this.audio=Ut(this.format,this.audioOptions.bitrate??Hr),this.output.addAudioTrack(this.audio)),await this.output.start()}async addFrame(t,n){await this.video.add(t,n)}async addAudio(t){this.audio&&await this.audio.add(t)}async finalize(){this.video.close(),this.audio?.close(),await this.output.finalize();let t=this.target.buffer;if(!t)throw new Error("Export produced no data");return new Uint8Array(t)}};function fa(e){let t=Math.round(e);return t%2===0?t:t+1}var Zd=8192;function Qd(e,t){let n=Math.max(t.width,t.height),r=Math.max(1,Math.round(e));for(;r>1&&n*r>Zd;)r--;return r}async function eh(e,t,n,r){let{codecs:s,fallback:i}=Be(t).video,a=e??s[0];s.includes(a)||(console.warn(`[motionscript] ${t.toUpperCase()} cannot hold ${a}; exporting as ${da[s[0]]} instead.`),a=s[0]);for(let o of new Set([a,s[0],i]))if(o===i||await th(o,n,r))return o!==a&&console.warn(`[motionscript] No ${a} encoder available; exporting as ${da[o]} instead.`),o;return i}var da={avc:"H.264",hevc:"HEVC",vp9:"VP9",av1:"AV1",vp8:"VP8"};async function th(e,t,n){try{return await fs(e,{width:t.width,height:t.height,bitrate:ha(t.width,t.height,n)})}catch{return!1}}async function Kr(e,t,n,r){return{codec:await eh(e?.codec,t,n,r),bitrate:e?.bitrate??ha(n.width,n.height,r),hardwareAcceleration:e?.hardwareAcceleration??"no-preference",keyFrameInterval:e?.keyFrameInterval??Jd,latencyMode:e?.latencyMode??"quality",contentHint:e?.contentHint??"detail",...e?.bitrateMode!==void 0&&{bitrateMode:e.bitrateMode}}}function _a(e,t){let{bitrate:n}=e;return typeof n=="number"?{...e,bitrate:n}:{...e,bitrate:n._toVideoBitrate(e.codec,t.width,t.height)}}function fn(e,t,n){let r={width:fa(e.width*t),height:fa(e.height*t)},s=Qd(n,r);return{output:r,oversample:s,renderScale:t*s}}async function qr(e){let t=document.createElement("canvas");t.width=e.canvasSize.width,t.height=e.canvasSize.height,t.style.display="none",document.body.appendChild(t);try{let n=new Vd(e.manifest),r=await ot(e),s=r.createStorageAdapter({catalog:n,viewport:e.viewport,fps:e.fps}),i=r.createRenderContext(s);return i.mount(t),await i.whenMounted?.(),{canvas:t,renderContext:i,storageAdapter:s,assetCatalog:n,dispose:()=>{i.dispose(),t.remove()}}}catch(n){throw t.remove(),n}}async function Jr(e){let{document:t,registry:n=new Gd,scale:r=1,format:s="mp4",manifest:i=Xd,theme:a,includeAudio:o=!0,video:l,audio:c={},frames:u,onProgress:f,signal:d,rendererWasmUrl:_,supersample:p=Yd,returnBytes:w=!1}=e,R=Be(s);if(R.kind!=="video")throw new RangeError(`exportVideo writes video; "${s}" is audio, which exportAudio writes.`);let L=e.filename??`export.${R.extension}`,F=zd(t,e,Wd);if(F.tracks.length===0)return;d?.throwIfAborted();let H=F.viewport,se=F.fps,{output:X,oversample:ye,renderScale:ve}=fn(H,r,p),q=await qr({canvasSize:{width:X.width*ye,height:X.height*ye},viewport:H,fps:se,manifest:i,rendererWasmUrl:_}),oe;try{let K=await Kr(l,s,X,se);oe=await Sn({project:F,registry:n,theme:a,scale:ve,includeAudio:o,frames:u,renderContext:q.renderContext,storageAdapter:q.storageAdapter,assetCatalog:q.assetCatalog,sink:new un(q.canvas,X,s,K,c),mixer:new vs(c.sampleRate,q.assetCatalog),onProgress:f,onIssue:e.onIssue,signal:d})}finally{q.dispose()}if(oe)return Un(oe,{returnBytes:w,filename:L,mimeType:R.mimeType})}import{DEFAULT_OUTPUT as nh,ManifestAssetCatalog as rh,AssetTimeline as sh,Registry as ih,resolveProjectDocument as ah}from"@motionscript/core";var oh={image:{},video:{},audio:{},font:{}};async function dn(e){let{registry:t=new ih,manifest:n=oh,sampleRate:r}=e,s=ah(e.document,e,nh);if(s.tracks.length===0)return null;let i=s.viewport,a=s.fps,o=await ot(e,{gpu:!1}),l=new rh(n),c=o.createStorageAdapter({catalog:l,viewport:i,fps:a}),u=o.createMeasureContext(c),f=new sh(s,{registry:t,viewport:i,fps:a,assets:l,measurer:u},{assets:!1});try{let d=f.run(),_=tr(d);return _.length===0?null:await Zn(_,d.totalDuration,{sampleRate:r,catalog:l})}finally{f.dispose(),c.dispose()}}var Nn=class extends Error{name="NoAudioError";constructor(){super("The timeline has no audio to export.")}};async function Yr(e){let{format:t="wav",audio:n={},onProgress:r,signal:s,returnBytes:i=!1}=e,a=Be(t);if(a.kind!=="audio")throw new RangeError(`exportAudio writes audio; "${t}" is video, which exportVideo writes.`);s?.throwIfAborted(),await jn(t);let o=await dn({document:e.document,registry:e.registry,viewport:e.viewport,fps:e.fps,manifest:e.manifest,sampleRate:n.sampleRate,rendererWasmUrl:e.rendererWasmUrl});if(o===null)throw new Nn;s?.throwIfAborted(),r?.(.5);let l=new Et,c=new Tt({format:a.container(),target:l}),u=Ut(t,n.bitrate);if(c.addAudioTrack(u),await c.start(),await u.add(o),u.close(),await c.finalize(),!l.buffer)throw new Error("Export produced no data");return r?.(1),Un(new Uint8Array(l.buffer),{returnBytes:i,filename:e.filename??`export.${a.extension}`,mimeType:a.mimeType})}import{DEFAULT_OUTPUT as hh,resolveProjectDocument as _h}from"@motionscript/core";import{DEFAULT_OUTPUT as pa,ManifestAssetCatalog as ma,frameSpecAtTime as lh,Registry as ch,resolveProjectDocument as uh}from"@motionscript/core";var fh={image:{},video:{},audio:{},font:{}};function dh(e,t){if(e?.time!==void 0)return lh(e.time,t);let n=e?.frame;return n===void 0||n==="first"?{kind:"first"}:n==="last"?{kind:"last"}:typeof n=="number"?{kind:"frame",frame:n}:n}function ga(e){return e==="jpeg"?"image/jpeg":"image/png"}var jt=class{canvas;renderContext;storageAdapter;catalog;backend;ownsCanvas;viewportValue;fpsValue;scaleValue;surfaceScale;manifest;theme;registry;disposed=!1;drawn=!1;constructor(t,n){this.backend=t,this.viewportValue=n.viewport??pa.viewport,this.fpsValue=n.fps??pa.fps,this.scaleValue=n.scale??1,this.surfaceScale=this.scaleValue,this.manifest=n.manifest??fh,this.theme=n.theme,this.registry=n.registry??new ch,this.ownsCanvas=n.canvas===void 0,this.canvas=n.canvas??document.createElement("canvas"),this.ownsCanvas&&(this.canvas.style.display="none",document.body.appendChild(this.canvas)),this.sizeCanvas(),this.catalog=new ma(this.manifest),this.storageAdapter=this.backend.createStorageAdapter({catalog:this.catalog,viewport:this.viewportValue,fps:this.fpsValue}),this.renderContext=this.backend.createRenderContext(this.storageAdapter),this.renderContext.mount(this.canvas)}get viewport(){return this.viewportValue}get fps(){return this.fpsValue}get scale(){return this.scaleValue}async render(t,n){this.assertLive();let r=n?.scale??this.scaleValue;r!==this.surfaceScale&&this.remount(r),await this.renderContext.whenMounted?.();let s=uh(t,{viewport:this.viewportValue},{viewport:this.viewportValue,fps:this.fpsValue}),i=await Ts({project:s,registry:this.registry,theme:this.theme,scale:r,renderContext:this.renderContext,storageAdapter:this.storageAdapter,assetCatalog:this.catalog,frame:dh(n,s.fps),onIssue:n?.onIssue});return this.drawn=!0,i}setTheme(t){this.theme=t}setManifest(t){this.assertLive(),this.manifest=t,this.catalog=new ma(t),this.storageAdapter.setCatalog(this.catalog)}setViewport(t){this.assertLive(),!(t.width===this.viewportValue.width&&t.height===this.viewportValue.height)&&(this.viewportValue=t,this.renderContext.dispose(),this.storageAdapter=this.backend.createStorageAdapter({catalog:this.catalog,viewport:t,fps:this.fpsValue}),this.renderContext=this.backend.createRenderContext(this.storageAdapter),this.remount(this.scaleValue))}async toBytes(t){let n=await this.toBlob(t);return new Uint8Array(await n.arrayBuffer())}toBlob(t){let n=this.snapshotToCanvas(),{format:r="png",quality:s=.92}=t??{};return new Promise((i,a)=>{n.toBlob(o=>o?i(o):a(new Error("Still encode produced no data.")),ga(r),s)})}toDataURL(t){let{format:n="png",quality:r=.92}=t??{};return this.snapshotToCanvas().toDataURL(ga(n),r)}dispose(){this.disposed||(this.disposed=!0,this.renderContext.dispose(),this.ownsCanvas&&this.canvas.remove())}snapshotToCanvas(){if(this.assertLive(),!this.drawn)throw new Error("Nothing has been rendered yet.");let t=this.renderContext.snapshotCanvas?.();if(!t)throw new Error("Still encode: could not read the surface into a 2d canvas.");return t}sizeCanvas(){this.canvas.width=this.viewportValue.width*this.surfaceScale,this.canvas.height=this.viewportValue.height*this.surfaceScale}remount(t){this.surfaceScale=t,this.drawn=!1,this.sizeCanvas(),this.renderContext.mount(this.canvas)}assertLive(){if(this.disposed)throw new Error("This StillRenderer has been disposed.")}};async function Xr(e={}){return new jt(await ot(e),e)}async function ph(e){let{registry:t,scale:n,manifest:r,theme:s,rendererWasmUrl:i,frame:a,format:o="png",quality:l=.92}=e,c=_h(e.document,e,hh);if(c.tracks.length===0)throw new Error("The project has no tracks to screenshot.");let u=await Xr({viewport:c.viewport,fps:c.fps,scale:n,manifest:r,theme:s,rendererWasmUrl:i,registry:t});try{return{...await u.render(c,{frame:a}),bytes:await u.toBytes({format:o,quality:l})}}finally{u.dispose()}}var kt=class extends Error{segment;constructor(t,n){super(n),this.segment=t,this.name="ConcatMismatchError"}};function mh(e,t){if(e.codec!==t.codec||e.codedWidth!==t.codedWidth||e.codedHeight!==t.codedHeight)return!1;let n=ba(e.description),r=ba(t.description);if(n===null||r===null)return n===r;if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++)if(n[s]!==r[s])return!1;return!0}function ba(e){return e?ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e):null}function Wn(e={}){let t=null,n=null,r=null,s=null,i=null,a=0,o=0,l=async c=>{i=e.stream?new _s(e.stream):new Et,n=new Tt({format:Be(c.format).container(),target:i}),r=new ps(c.track.codec),n.addVideoTrack(r),s=e.audio?Ut(c.format,e.audioBitrate):null,s&&n.addAudioTrack(s),await n.start(),s&&e.audio&&await s.add(e.audio)};return{async append(c){let u=a++,f=new xn({source:new os(c),formats:[cs,Jn]});try{let d=await gh(f,u,t);t||(t=d,await l(d));let _=!0;for await(let p of new ds(d.track).packets())await r.add(p.clone({timestamp:p.timestamp+o}),_?{decoderConfig:d.config}:void 0),_=!1;o+=d.duration}finally{f.dispose()}},async finish(){if(!n)throw new Error("concatVideoSegments: no segments");if(r.close(),s?.close(),await n.finalize(),e.stream)return new Uint8Array(0);let c=i.buffer;if(!c)throw new Error("concatVideoSegments produced no data");return new Uint8Array(c)},async cancel(){n&&n.state!=="finalized"&&n.state!=="canceled"&&await n.cancel()}}}async function gh(e,t,n){let r=await e.getFormat()===Jn?"webm":"mp4";if(n&&r!==n.format)throw new kt(t,`Segment ${t} is ${r} and segment 0 is ${n.format}.`);let s=await e.getPrimaryVideoTrack();if(!s)throw new kt(t,`Segment ${t} has no video track.`);let i=await s.getDecoderConfig();if(!i)throw new kt(t,`Segment ${t} has no decoder configuration.`);if(n&&!mh(n.config,i))throw new kt(t,`Segment ${t} was encoded differently from segment 0 (${n.config.codec} ${n.config.codedWidth}x${n.config.codedHeight} vs ${i.codec} ${i.codedWidth}x${i.codedHeight}); joining them would decode as garbage.`);return{format:r,track:s,config:i,duration:await s.computeDuration()}}async function bh(e,t={}){if(e.length===0)throw new Error("concatVideoSegments: no segments");if(e.length===1&&!t.audio&&!t.stream)return e[0];let n=Wn(t);try{for(let r of e)await n.append(r);return await n.finish()}catch(r){throw await n.cancel().catch(()=>{}),r}}import{DEFAULT_OUTPUT as yh,placeTracks as vh,Registry as xh,renderIssueKey as kh,resolveProjectDocument as Mh,totalFramesOf as Sh}from"@motionscript/core";function wa(e,t){if(!Number.isInteger(e)||e<=0)return[];let n=Math.max(1,Math.round(t.fps*(t.keyFrameInterval>0?t.keyFrameInterval:1))),r=t.chunkSeconds??Math.min(6,Math.max(2,e/t.fps/(Math.max(1,t.lanes)*4))),s=Math.max(n,Math.round(r*t.fps/n)*n),i=[];for(let o=0;o<e;o+=s)i.push({index:i.length,start:o,end:Math.min(e,o+s)});let a=i[i.length-1];return i.length>1&&a.end-a.start<n&&(i.pop(),i[i.length-1].end=a.end),i}var Vn=class{_options;_active=1;_settled;_window=ya();_previousFps=0;_newestFirstAt=null;_windowMs;_minFrames;_maxWaitShare;_minGain;_warmupMs;constructor(t){this._options=t,this._windowMs=t.windowMs??1500,this._minFrames=t.minFrames??24,this._maxWaitShare=t.maxWaitShare??.45,this._minGain=t.minGain??1.1,this._warmupMs=t.warmupMs??300,this._settled=t.lanes<=1}get active(){return this._active}get settled(){return this._settled}laneLost(t){this._active=Math.max(1,Math.min(this._active,t)),this._settled=!0}record(t){if(this._settled||t.lane>=this._active)return null;let n=this._window;if(n.start===null)return t.lane!==this._active-1||(this._newestFirstAt??=t.at,t.at-this._newestFirstAt>=this._warmupMs&&(n.start=t.at)),null;n.frames+=t.frames,n.busyMs+=t.busyMs,n.waitMs+=t.waitMs;let r=t.at-n.start;if(r<this._windowMs||n.frames<this._minFrames)return null;let s=n.frames*1e3/r,i=n.waitMs/Math.max(1,n.busyMs+n.waitMs),a=this._active;return this._active>1&&s<this._previousFps*this._minGain?(this._active-=1,this._settled=!0):i<=this._maxWaitShare&&this._active<this._options.lanes?(this._previousFps=s,this._active+=1):this._settled=!0,this._window=ya(),this._newestFirstAt=null,this._active!==a?this._active:null}};function ya(){return{start:null,frames:0,busyMs:0,waitMs:0}}var wh=2;async function va(e){let{lanes:t,spec:n,chunks:r,signal:s}=e,i=e.now??(()=>performance.now());if(t.length===0)throw new Error("runLanes: no lanes");if(r.length===0)return;let a=new AbortController,o=()=>a.abort(s?.reason);s?.aborted&&o(),s?.addEventListener("abort",o,{once:!0});let l=new Vn({lanes:t.length,...e.governor}),c=r.map(q=>({chunk:q,attempts:0})),u=new Map,f=new Set,d=0,_=r.reduce((q,oe)=>q+(oe.end-oe.start),0),p=null,w=()=>{},R=new Promise(q=>w=q),L=()=>{let q=w;R=new Promise(oe=>w=oe),q()};a.signal.addEventListener("abort",L,{once:!0});let F=()=>t.length-f.size,H=q=>{let oe=0;for(let K=0;K<q;K++)f.has(K)||oe++;return oe<l.active},se=q=>{f.add(q),l.laneLost(F()),e.onActive?.(l.active),L()},X=()=>{let q=d;for(let oe of u.values())q+=oe;return q},ye=()=>{let q=c.shift();if(!l.settled||q.attempts>0)return q;let oe=c.reduce((xe,we)=>xe+(we.chunk.end-we.chunk.start),q.chunk.end-q.chunk.start),K=Math.ceil(oe/(l.active===1?1:l.active*2)),{end:B}=q.chunk;for(;c.length>0&&c[0].attempts===0&&c[0].chunk.start===B&&B-q.chunk.start<K;)B=c.shift().chunk.end;return{chunk:{...q.chunk,end:B},attempts:0}},ve=async q=>{for(;!H(q)&&_>0&&!a.signal.aborted&&!f.has(q);)await R;if(_===0||a.signal.aborted||f.has(q))return;let oe;try{oe=await t[q].open(n,a.signal)}catch(K){if(a.signal.aborted)return;if(F()<=1)throw K;console.warn(`[motionscript] export lane ${q} failed to open; continuing without it.`,K),se(q);return}try{for(;;){if(a.signal.throwIfAborted(),_===0)return;if(!H(q)||c.length===0){await R;continue}let K=ye(),B=K.chunk.end-K.chunk.start,xe={frames:0,busyMs:0,waitMs:0};u.set(K,0);try{let we=await oe.render(K.chunk,Te=>{let Ue=l.record({lane:q,frames:Te.frames-xe.frames,busyMs:Te.busyMs-xe.busyMs,waitMs:Te.waitMs-xe.waitMs,at:i()});for(let ae of Te.issues??[])e.onIssue?.(ae);Object.assign(xe,{frames:Te.frames,busyMs:Te.busyMs,waitMs:Te.waitMs}),u.set(K,Te.frames),e.onFrames?.(X()),Ue!==null&&(e.onActive?.(Ue),L())},a.signal);u.delete(K),d+=B,_-=B,e.onFrames?.(X()),e.onChunk(K.chunk,we),L()}catch(we){if(u.delete(K),a.signal.aborted||++K.attempts>=wh||F()<=1)throw we;console.warn(`[motionscript] export lane ${q} failed frames ${K.chunk.start} to ${K.chunk.end}; retrying on another lane.`,we),c.unshift(K),e.onFrames?.(X()),se(q);return}}}finally{oe.close()}};try{if(await Promise.all(t.map((q,oe)=>ve(oe).catch(K=>{p??=K,a.abort(K)}))),p)throw p;if(_>0)throw new Error(`runLanes: ${_} frames were never rendered.`)}finally{s?.removeEventListener("abort",o)}}var Ah={image:{},video:{},audio:{},font:{}},Eh=2,Th=.97;async function Ph(e){let{registry:t=new xh,scale:n=1,format:r="mp4",manifest:s=Ah,includeAudio:i=!0,audio:a={},signal:o,onProgress:l,supersample:c=Eh}=e;if(Be(r).kind!=="video")throw new RangeError(`exportVideoParallel writes video; "${r}" is audio, which exportAudio writes.`);let u=Mh(e.document,e,yh);if(u.tracks.length===0)throw new Error("exportVideoParallel: the project has no tracks.");o?.throwIfAborted();let f=u.fps,d=Sh(vh(u.tracks,f)),{output:_}=fn(u.viewport,n,c),p=_a(await Kr(e.video,r,_,f),_),w={project:u,manifest:s,theme:e.theme,scale:n,supersample:c,format:r,encoding:p,host:e.host},R=wa(d,{fps:f,keyFrameInterval:p.keyFrameInterval,lanes:e.lanes.length,chunkSeconds:e.chunkSeconds}),L=i?dn({document:u,registry:t,manifest:s,sampleRate:a.sampleRate,rendererWasmUrl:e.rendererWasmUrl}):Promise.resolve(null);L.catch(()=>{});let F=0,H=new Set,se=xe=>{xe<=F||(F=xe,l?.(xe))},X=new AbortController,ye=()=>X.abort(o?.reason);o?.aborted&&ye(),o?.addEventListener("abort",ye,{once:!0});let ve=new Map,q=0,oe=Promise.resolve(),K=null,B=()=>(oe=oe.then(async()=>{for(;ve.has(q);){K??=Wn({stream:e.stream,audio:await L,audioBitrate:a.bitrate});let{end:xe,bytes:we}=ve.get(q);ve.delete(q),q=xe,await K.append(we)}}),oe);try{if(await va({lanes:e.lanes,spec:w,chunks:R,signal:X.signal,onIssue:we=>{let Te=kh(we);H.has(Te)||(H.add(Te),e.onIssue?.(we))},onFrames:we=>se(Th*Math.min(1,we/d)),onActive:e.onLanes,onChunk:(we,Te)=>{ve.set(we.start,{end:we.end,bytes:Te}),B().catch(Ue=>X.abort(Ue))}}),await B(),q!==d)throw new Error(`exportVideoParallel: joined ${q} of ${d} frames.`);let xe=await K.finish();return se(1),xe}catch(xe){throw await oe.catch(()=>{}),await K?.cancel().catch(()=>{}),xe}finally{o?.removeEventListener("abort",ye)}}import{Registry as Ih}from"@motionscript/core";var Rh=100;async function Qr(e,t){let{project:n}=e,r=n.viewport,s=n.fps,i=t.registry??new Ih,{output:a,oversample:o,renderScale:l}=fn(r,e.scale,e.supersample),c=await qr({canvasSize:{width:a.width*o,height:a.height*o},viewport:r,fps:s,manifest:e.manifest,rendererWasmUrl:t.rendererWasmUrl});return{async render(u,f,d){let _=new Zr(new un(c.canvas,a,e.format,e.encoding),f),p=await Sn({project:n,registry:i,theme:e.theme,scale:l,includeAudio:!1,frames:{start:u.start,end:u.end},renderContext:c.renderContext,storageAdapter:c.storageAdapter,assetCatalog:c.assetCatalog,sink:_,signal:d,onIssue:w=>_.issues.push(w)});if(_.flush(),!p)throw new Error(`Frames ${u.start} to ${u.end} produced no bytes.`);return p},close:()=>c.dispose()}}var Zr=class{_inner;_onReport;issues=[];_frames=0;_busyMs=0;_waitMs=0;_lastEnd=0;_lastReport=0;constructor(t,n){this._inner=t,this._onReport=n}async start(t){await this._inner.start(t),this._lastEnd=this._lastReport=performance.now()}async addFrame(t,n){let r=performance.now();this._busyMs+=r-this._lastEnd,await this._inner.addFrame(t,n);let s=performance.now();this._waitMs+=s-r,this._lastEnd=s,this._frames++,s-this._lastReport>=Rh&&(this._lastReport=s,this.flush())}finalize(){return this._inner.finalize()}flush(){let t=this.issues.splice(0);this._onReport({frames:this._frames,busyMs:this._busyMs,waitMs:this._waitMs,...t.length>0&&{issues:t}})}};function Ch(e={}){return{open:t=>Qr(t,e)}}function Oh(e,t){let n=new Error(e);return n.name=t,n}function $h(e,t={}){let n=1,r=null,s=new Map;e.addEventListener("message",o=>{let l=o.data,c=s.get(l.id);if(c){if(l.t==="report"){c.onReport?.(l.report);return}s.delete(l.id),l.t==="error"?c.reject(Oh(l.message,l.name)):c.resolve(l)}}),e.start();let i=o=>{r??=new Error(o);for(let l of s.values())l.reject(r);s.clear()};e.addEventListener("close",()=>i("The export lane closed.")),t.lost?.then(()=>i("The export lane was lost."),()=>i("The export lane was lost."));let a=(o,l,c)=>new Promise((u,f)=>{if(r)return f(r);if(l.aborted)return f(l.reason);let d=()=>{s.delete(o.id),e.postMessage({t:"abort",id:o.id}),f(l.reason)};l.addEventListener("abort",d,{once:!0}),s.set(o.id,{resolve:_=>{l.removeEventListener("abort",d),u(_)},reject:_=>{l.removeEventListener("abort",d),f(_)},onReport:c}),e.postMessage(o)});return{async open(o,l){let c=n++;return await a({t:"open",id:c,spec:o},l),{async render(u,f,d){return(await a({t:"render",id:n++,session:c,chunk:u},d,f)).bytes},close(){r||e.postMessage({t:"close",id:c})}}}}}function Dh(e,t){let n=new Map,r=new Map,s=(o,l=[])=>e.postMessage(o,l),i=(o,l)=>s({t:"error",id:o,message:l instanceof Error?l.message:String(l),name:l instanceof Error?l.name:"Error"}),a=async o=>{let l=o.data;switch(l.t){case"open":{let c=Promise.resolve(t(l.spec)).then(u=>Qr(l.spec,u));n.set(l.id,c);try{await c,s({t:"opened",id:l.id})}catch(u){n.delete(l.id),i(l.id,u)}return}case"render":{let c=new AbortController;r.set(l.id,c);try{let u=await n.get(l.session);if(!u)throw new Error(`No open export session ${l.session}.`);let f=await u.render(l.chunk,_=>s({t:"report",id:l.id,report:_}),c.signal),d=f.byteOffset===0&&f.byteLength===f.buffer.byteLength?f:f.slice();s({t:"done",id:l.id,bytes:d},[d.buffer])}catch(u){c.signal.aborted||i(l.id,u)}finally{r.delete(l.id)}return}case"abort":r.get(l.id)?.abort(new DOMException("Export cancelled.","AbortError"));return;case"close":{let c=n.get(l.id);n.delete(l.id),c?.then(u=>u.close(),()=>{});return}}};return e.addEventListener("message",a),e.start(),()=>{e.removeEventListener("message",a);for(let o of r.values())o.abort(new DOMException("Export cancelled.","AbortError"));for(let o of n.values())o.then(l=>l.close(),()=>{});n.clear()}}import{Ticker as Lh}from"@motionscript/core";var hn=class extends Lh{contextOf;ownsContext;_context=null;fps;playStartCtxTime=0;seekOffset=0;speed=1;reverse=!1;rafId=null;seekEpoch=0;silentSource=null;constructor(t){super();let{context:n}=t;this.contextOf=typeof n=="function"?n:()=>n??new AudioContext,this.ownsContext=!n,this.fps=t.fps}getContext(){return this._context??=this.contextOf(),this._context}get context(){return this.getContext()}seek(t){let n=Math.max(0,Math.min(t,this.duration));this.seekOffset=n,this.isPlaying&&(this.playStartCtxTime=this.context.currentTime),this.seekEpoch++,this.setCurrentTime(n)}play(t=1,n=!1){this.speed=t,this.reverse=n,this.seekOffset=this.currentTime,this.context.state==="suspended"&&this.context.resume().then(()=>{!this.isPlaying&&this.context.state==="running"&&this.context.suspend()},r=>{console.error("[WebTicker] The audio context could not resume:",r),this.pause()}),this.playStartCtxTime=this.context.currentTime,this.startSilentTicker(),super.play(t,n),this.startLoop()}pause(){this.seekOffset=this.currentTime,this.stopLoop(),this.stopSilentTicker(),this._context?.state==="running"&&this._context.suspend(),super.pause()}startSilentTicker(){this.stopSilentTicker();let t=Math.max(.001,this.duration-this.seekOffset),n=this.context.sampleRate,r=this.context.createBuffer(1,Math.ceil(t*n),n),s=this.context.createBufferSource();s.buffer=r,s.connect(this.context.destination),s.start(),this.silentSource=s}stopSilentTicker(){if(this.silentSource){try{this.silentSource.onended=null,this.silentSource.stop(),this.silentSource.disconnect()}catch{}this.silentSource=null}}position(){let t=(this.context.currentTime-this.playStartCtxTime)*this.speed,n=this.reverse?this.seekOffset-t:this.seekOffset+t,r=Math.max(0,Math.min(n,this.duration));return{time:r,ended:this.reverse?r<=0:r>=this.duration}}startLoop(){if(this.rafId!==null)return;let t=a=>Math.floor(a*this.fps+1e-6),n=t(this.currentTime),r=null,s=a=>{let o=this.position(),l=o.time;if(!o.ended&&r&&r.epoch===this.seekEpoch){let c=(a-r.at)/1e3*this.speed,u=this.reverse?r.time-c:r.time+c,f=o.time-u,d=u+f*.05;Math.abs(f)<=.05&&d>0&&d<this.duration&&(l=d)}return r={time:l,at:a,epoch:this.seekEpoch},{time:l,ended:o.ended}},i=async a=>{let o=this.seekEpoch,l=s(a),c=l.ended,f=t(l.time)!==n||c;this.setCurrentTime(l.time,f);let d=()=>{this.seekEpoch!==o&&(o=this.seekEpoch,n=t(this.currentTime),c=this.position().ended)};if(d(),f&&(n=t(this.currentTime),await this.tick(),d()),this.rafId!==null){if(c){this.pause();return}this.rafId=requestAnimationFrame(i)}};this.rafId=requestAnimationFrame(i)}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 Nh}from"@motionscript/core";var Gn=Ya(xa(),1);import*as Fh from"@motionscript/core/sdk";function Bh(){return new URL("esbuild-wasm/esbuild.wasm",import.meta.url).href}var Uh;function jh(e){return Uh??=(async()=>(await Gn.initialize({wasmURL:e??Bh()}),async t=>{let{code:n}=await Gn.transform(t,{loader:"ts",format:"cjs",target:"es2020"});return n}))()}function ka(e,t){return{sdk:e?.sdk??Fh,modules:e?.modules,compile:e?.compile??(async n=>(await jh(t))(n))}}var ts=class{backend;defaults;still=null;stillRegistry=null;stillQueue=Promise.resolve();constructor(t,n){this.backend=t,this.defaults=n}async exportVideo(t){let n=t.encode??{};return n.format&&ua(n.format)?Yr({document:t.project,registry:t.registry,manifest:t.manifest,format:n.format,audio:n.audio??this.defaults.audio,filename:n.filename,returnBytes:n.download!==!0,onProgress:t.onProgress,signal:t.signal,rendererWasmUrl:this.defaults.rendererWasmUrl}):Jr({document:t.project,registry:t.registry,scale:t.scale,manifest:t.manifest,includeAudio:t.includeAudio,frames:t.frames,format:n.format,video:n.video??this.defaults.video,audio:n.audio??this.defaults.audio,supersample:n.supersample,filename:n.filename,returnBytes:n.download!==!0,onProgress:t.onProgress,onIssue:t.onIssue,signal:t.signal,rendererWasmUrl:this.defaults.rendererWasmUrl})}exportStill(t){let n=this.stillQueue.then(()=>this.drawStill(t));return this.stillQueue=n.catch(()=>{}),n}dispose(){this.still?.dispose(),this.still=null}async drawStill(t){let n=this.renderer(t),r=await n.render(t.project,{scale:t.scale,onIssue:t.onIssue,...Wh(t.frame)});return{bytes:await n.toBytes({format:t.format,quality:t.quality}),frame:r.frame,totalFrames:r.totalFrames}}renderer(t){let{project:n,registry:r}=t;if(n.viewport===void 0||n.fps===void 0)throw new Error("exportStill takes a project whose fps and viewport are resolved \u2014 see Session.");return this.still&&this.stillRegistry!==r&&this.dispose(),this.still??=new jt(this.backend,{viewport:n.viewport,fps:n.fps,manifest:t.manifest,registry:r}),this.stillRegistry=r,this.still.setViewport(n.viewport),t.manifest&&this.still.setManifest(t.manifest),this.still}};function Wh(e){return e.kind==="frame"?{frame:e.frame}:{frame:e.kind}}async function Vh(e={}){let t=e.nodes,n=Array.isArray(t)?t.filter(c=>typeof c!="string"):t,r=Array.isArray(t)?t.filter(c=>typeof c=="string"):[],s=ka(e.dynamicNodes,e.compilerWasmUrl),i=await ot(e),a=new ts(i,{video:e.video,audio:e.audio,rendererWasmUrl:e.rendererWasmUrl}),o={createStorageAdapter:c=>i.createStorageAdapter(c),createRenderContext:c=>i.createRenderContext(c),createMeasureContext:c=>i.createMeasureContext(c),createAudioSink(){return new Qn},createTicker(c,u){let f=u;return new hn({context:()=>f.getContext(),fps:c})},createExporter(){return a},dispose(){a.dispose(),i.dispose?.()}},l=new Nh(o,{...e,nodes:n,dynamicNodes:s});for(let c of r)await l.registerNode(c);return l}export{kt as ConcatMismatchError,jd as EXPORT_FORMATS,Nn as NoAudioError,Mn as NothingToDrawError,to as QUALITY_HIGH,Qa as QUALITY_LOW,eo as QUALITY_MEDIUM,no as QUALITY_VERY_HIGH,Za as QUALITY_VERY_LOW,Bd as ShaderPreview,jt as StillRenderer,Dd as WGSL_PRELUDE,Qn as WebAudioPlayer,Bn as WebGpuUnavailableError,hn as WebTicker,bh as concatVideoSegments,Vh as createBrowserEngine,Wn as createSegmentJoiner,Xr as createStillRenderer,ro as encodeWav,Yr as exportAudio,ph as exportScreenshot,Jr as exportVideo,Ph as exportVideoParallel,Vr as isWgpuSupported,qn as loadAssetBytes,Ch as localLane,$h as messagePortLane,Zn as mixAudio,dn as mixTimelineAudio,Sd as onWgpuEvent,Dh as serveExportLane,Xa as setAssetByteSource,$d as validateShader};
2026
734
  //# sourceMappingURL=index.js.map