@clipkit/renderer 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +71 -0
- package/dist/.tmp-harness.js +2011 -0
- package/dist/harness/embedded.d.ts +2 -0
- package/dist/harness/embedded.d.ts.map +1 -0
- package/dist/harness/embedded.js +2015 -0
- package/dist/harness/embedded.js.map +1 -0
- package/dist/harness/harness.d.ts +23 -0
- package/dist/harness/harness.d.ts.map +1 -0
- package/dist/harness/harness.js +93 -0
- package/dist/harness/harness.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/render.d.ts +14 -0
- package/dist/render.d.ts.map +1 -0
- package/dist/render.js +148 -0
- package/dist/render.js.map +1 -0
- package/dist/still.d.ts +21 -0
- package/dist/still.d.ts.map +1 -0
- package/dist/still.js +119 -0
- package/dist/still.js.map +1 -0
- package/dist/types.d.ts +40 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +56 -0
|
@@ -0,0 +1,2015 @@
|
|
|
1
|
+
// AUTO-GENERATED — do not edit by hand.
|
|
2
|
+
// Source: scripts/build-harness.mjs (runs via npm run prebuild).
|
|
3
|
+
export const HARNESS_JS = `"use strict";(()=>{var qd=Object.defineProperty;var jd=(e,t)=>{for(var i in t)qd(e,i,{get:t[i],enumerable:!0})};function je(e,t,i,s,r,n,a,o=0,c=0,l=!1){let u=e/n*2-1,h=-(t/a*2-1),f=r*Math.PI/180,p=Math.cos(f),m=Math.sin(f),g=Math.tan(-o*Math.PI/180),y=i*p/n,w=-(i*m)/a,x=s*m/n,b=s*p/a,S=i!==0?s/i:0,v=x+g*y*S,T=b+g*w*S,C=Math.tan(c*Math.PI/180),P=s!==0?i/s:0,E=y-C*x*P,U=w-C*b*P,H=l?-1:1;return new Float32Array([E,U*H,0,0,v,T*H,0,0,0,0,1,0,u,h*H,0,1])}function lr(e,t,i,s,r,n,a,o,c,l){let u=r*Math.PI/180,h=o*Math.PI/180,f=c*Math.PI/180,p=Math.cos(u),m=Math.sin(u),g=Math.cos(h),y=Math.sin(h),w=Math.cos(f),x=Math.sin(f),b=Math.tan(n*Math.PI/180),S=Math.tan(a*Math.PI/180),v=i/2,T=S*i/2,C=-b*s/2,P=-s/2,E=(L,re)=>{let te=re*g,K=re*y,q=L*w+K*x,V=-L*x+K*w;return[q*p-te*m,q*m+te*p,V]},[U,H,Q]=E(v,T),[J,D,z]=E(C,P);return[U,H,Q,0,J,D,z,0,x*g*p+y*m,x*g*m-y*p,w*g,0,e,t,l,1]}function St(e,t,i,s=!1){let r=s?-1:1,n=2/t,a=-2/i*r,o=new Float32Array(16);for(let c=0;c<4;c++){let l=e[c*4],u=e[c*4+1],h=e[c*4+3];o[c*4]=n*l-h,o[c*4+1]=a*u+r*h,o[c*4+2]=0,o[c*4+3]=h}return o}function Mt(e,t,i,s,r,n){return{cx:e+i*(.5-r),cy:t+s*(.5-n)}}function Hr(e,t){return new Float32Array([e[0],e[1],e[2]/t,e[3],e[4],e[5]/t,e[6]*t,e[7]*t,e[8]])}function Gr(e){let t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],a=e[5],o=e[6],c=e[7],l=e[8],u=n*l-c*a,h=c*s-i*l,f=i*a-n*s,p=t*u+r*h+o*f;if(!Number.isFinite(p)||Math.abs(p)<1e-12)return null;let m=1/p;return new Float32Array([u*m,h*m,f*m,(o*a-r*l)*m,(t*l-o*s)*m,(r*s-t*a)*m,(r*c-o*n)*m,(o*i-t*c)*m,(t*n-r*i)*m])}var $d={debug:(e,...t)=>console.debug(\`[clipkit] \${e}\`,...t),info:(e,...t)=>console.info(\`[clipkit] \${e}\`,...t),warn:(e,...t)=>console.warn(\`[clipkit] \${e}\`,...t),error:(e,...t)=>console.error(\`[clipkit] \${e}\`,...t)},Yd=$d;function $(){return Yd}function ea(e){return e==="overlay"||e==="hard-light"||e==="soft-light"}var Vr={pixelate:0,dither:1,halftone:2,ascii:3,drop_shadow:4,glow:5,stroke:6,chroma_key:7,luma_key:8,levels:9,lut:10,fractal_noise:11,turbulent_displace:12,bloom_bright:13};var Xd=\`
|
|
4
|
+
struct ShadowUniforms {
|
|
5
|
+
transform: mat4x4<f32>, // 64 bytes, offset 0
|
|
6
|
+
color: vec4<f32>, // 16 bytes, offset 64 \\u2014 shadow color, premultiplied
|
|
7
|
+
cornerRadius: f32, // 4 bytes, offset 80
|
|
8
|
+
shapeType: f32, // 4 bytes, offset 84
|
|
9
|
+
blur: f32, // 4 bytes, offset 88
|
|
10
|
+
_pad0: f32, // 4 bytes, offset 92 \\u2014 std140 alignment
|
|
11
|
+
size: vec2<f32>, // 8 bytes, offset 96 \\u2014 shape size
|
|
12
|
+
quadSize: vec2<f32>, // 8 bytes, offset 104 \\u2014 rendered-quad size
|
|
13
|
+
_pad1: vec4<f32>, // 16 bytes, offset 112 \\u2014 pad to 128
|
|
14
|
+
}
|
|
15
|
+
@group(0) @binding(0) var<uniform> u: ShadowUniforms;
|
|
16
|
+
|
|
17
|
+
struct VsOut {
|
|
18
|
+
@builtin(position) position: vec4<f32>,
|
|
19
|
+
@location(0) uv: vec2<f32>,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
@vertex
|
|
23
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
24
|
+
var out: VsOut;
|
|
25
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
26
|
+
out.uv = uv;
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
@fragment
|
|
31
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
32
|
+
let p = in.uv * u.quadSize;
|
|
33
|
+
let shapeHalf = u.size * 0.5;
|
|
34
|
+
let quadHalf = u.quadSize * 0.5;
|
|
35
|
+
let ps = p - quadHalf + shapeHalf;
|
|
36
|
+
var dist: f32;
|
|
37
|
+
if (u.shapeType > 0.5) {
|
|
38
|
+
let d = (ps - shapeHalf) / shapeHalf;
|
|
39
|
+
dist = (sqrt(dot(d, d)) - 1.0) * min(shapeHalf.x, shapeHalf.y);
|
|
40
|
+
} else {
|
|
41
|
+
let r = u.cornerRadius;
|
|
42
|
+
let q = abs(ps - shapeHalf) - shapeHalf + vec2<f32>(r, r);
|
|
43
|
+
dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0, 0.0))) - r;
|
|
44
|
+
}
|
|
45
|
+
if (dist > u.blur) { discard; }
|
|
46
|
+
// Symmetric falloff around the shape edge \\u2014 matches CSS box-shadow's
|
|
47
|
+
// Gaussian-blur erfc shape closely enough: alpha ~1.0 deep inside,
|
|
48
|
+
// ~0.5 at the edge, ~0 at +blur past the edge.
|
|
49
|
+
let alpha = 1.0 - smoothstep(-u.blur, u.blur, dist);
|
|
50
|
+
if (alpha < 0.001) { discard; }
|
|
51
|
+
return u.color * alpha;
|
|
52
|
+
}
|
|
53
|
+
\`,Zd=\`
|
|
54
|
+
struct ShapeUniforms {
|
|
55
|
+
transform: mat4x4<f32>, // 64 bytes, offset 0
|
|
56
|
+
color: vec4<f32>, // 16 bytes, offset 64 \\u2014 fill, premultiplied
|
|
57
|
+
strokeColor: vec4<f32>, // 16 bytes, offset 80 \\u2014 stroke, premultiplied
|
|
58
|
+
cornerRadius: f32, // 4 bytes, offset 96 \\u2014 PIXELS
|
|
59
|
+
shapeType: f32, // 4 bytes, offset 100 \\u2014 0.0 = rect, 1.0 = ellipse
|
|
60
|
+
size: vec2<f32>, // 8 bytes, offset 104 \\u2014 pixel (width, height)
|
|
61
|
+
strokeWidth: f32, // 4 bytes, offset 112 \\u2014 PIXELS; 0 disables
|
|
62
|
+
_pad: f32, // 4 bytes, offset 116 \\u2014 std140 alignment pad
|
|
63
|
+
} // total: 120 bytes (round to 128 for uniform alignment)
|
|
64
|
+
@group(0) @binding(0) var<uniform> u: ShapeUniforms;
|
|
65
|
+
|
|
66
|
+
struct VsOut {
|
|
67
|
+
@builtin(position) position: vec4<f32>,
|
|
68
|
+
@location(0) uv: vec2<f32>,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
@vertex
|
|
72
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
73
|
+
var out: VsOut;
|
|
74
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
75
|
+
out.uv = uv;
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
@fragment
|
|
80
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
81
|
+
let p = in.uv * u.size;
|
|
82
|
+
let half = u.size * 0.5;
|
|
83
|
+
var dist: f32;
|
|
84
|
+
if (u.shapeType > 0.5) {
|
|
85
|
+
// Ellipse \\u2014 approximate signed pixel distance via normalized space.
|
|
86
|
+
let d = (p - half) / half;
|
|
87
|
+
dist = (sqrt(dot(d, d)) - 1.0) * min(half.x, half.y);
|
|
88
|
+
} else {
|
|
89
|
+
// Rectangle / rounded rectangle SDF. r = 0 collapses to sharp rect.
|
|
90
|
+
let r = u.cornerRadius;
|
|
91
|
+
let q = abs(p - half) - half + vec2<f32>(r, r);
|
|
92
|
+
dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0, 0.0))) - r;
|
|
93
|
+
}
|
|
94
|
+
// Anti-aliased boundary via screen-space derivative \\u2014 same approach
|
|
95
|
+
// as the WebGL backend. Band width = 2 \\xD7 fwidth(dist) for visibly
|
|
96
|
+
// smooth edges even when the canvas is downsampled to a smaller
|
|
97
|
+
// preview.
|
|
98
|
+
let aa = fwidth(dist);
|
|
99
|
+
let outerAlpha = 1.0 - smoothstep(-aa, aa, dist);
|
|
100
|
+
if (outerAlpha < 0.001) { discard; }
|
|
101
|
+
|
|
102
|
+
var base: vec4<f32>;
|
|
103
|
+
if (u.strokeWidth > 0.0) {
|
|
104
|
+
// strokeAlpha = 0 in the fill interior, 1 in the stroke band.
|
|
105
|
+
let strokeAlpha = smoothstep(-u.strokeWidth - aa, -u.strokeWidth + aa, dist);
|
|
106
|
+
base = mix(u.color, u.strokeColor, strokeAlpha);
|
|
107
|
+
} else {
|
|
108
|
+
base = u.color;
|
|
109
|
+
}
|
|
110
|
+
return base * outerAlpha;
|
|
111
|
+
}
|
|
112
|
+
\`,To=\`
|
|
113
|
+
struct LitUniforms {
|
|
114
|
+
transform: mat4x4<f32>, // offset 0 \\u2014 clip-space projection
|
|
115
|
+
worldMatrix: mat4x4<f32>, // offset 64 \\u2014 unit quad \\u2192 world (camera-free)
|
|
116
|
+
albedo: vec4<f32>, // offset 128 \\u2014 shape: straight albedo | textured: premul tint
|
|
117
|
+
strokeAlbedo: vec4<f32>, // offset 144 \\u2014 shape: straight stroke | textured: uvRect
|
|
118
|
+
normal: vec4<f32>, // offset 160 \\u2014 world face normal (xyz)
|
|
119
|
+
eye: vec4<f32>, // offset 176 \\u2014 world eye position (xyz)
|
|
120
|
+
ambient: vec4<f32>, // offset 192 \\u2014 summed ambient color (xyz)
|
|
121
|
+
params0: vec4<f32>, // offset 208 \\u2014 (cornerRadius, shapeType, strokeWidth, numLights)
|
|
122
|
+
params1: vec4<f32>, // offset 224 \\u2014 (roughness, metalness, reflectivity, emissive)
|
|
123
|
+
size: vec4<f32>, // offset 240 \\u2014 (width_px, height_px, _, _)
|
|
124
|
+
lightDir: array<vec4<f32>, 4>, // offset 256 \\u2014 world light directions (xyz)
|
|
125
|
+
lightColor: array<vec4<f32>, 4>, // offset 320 \\u2014 light color \\xD7 intensity (xyz)
|
|
126
|
+
envColor: array<vec4<f32>, 4>, // offset 384 \\u2014 environment gradient stops (xyz)
|
|
127
|
+
envParams: vec4<f32>, // offset 448 \\u2014 (stopCount, normalScale, hasNormalMap, _)
|
|
128
|
+
envOffsets: vec4<f32>, // offset 464 \\u2014 up to 4 stop offsets
|
|
129
|
+
envAvg: vec4<f32>, // offset 480 \\u2014 mean env color (xyz)
|
|
130
|
+
tangent: vec4<f32>, // offset 496 \\u2014 world +U for normal mapping (xyz)
|
|
131
|
+
bitangent: vec4<f32>, // offset 512 \\u2014 world +V (xyz)
|
|
132
|
+
} // total: 528 bytes
|
|
133
|
+
@group(0) @binding(0) var<uniform> u: LitUniforms;
|
|
134
|
+
\`,Eo=\`
|
|
135
|
+
const PI = 3.14159265;
|
|
136
|
+
fn ggxD(NdotH: f32, a: f32) -> f32 {
|
|
137
|
+
let a2 = a * a;
|
|
138
|
+
let d = NdotH * NdotH * (a2 - 1.0) + 1.0;
|
|
139
|
+
return a2 / (PI * d * d);
|
|
140
|
+
}
|
|
141
|
+
fn gSchlick(x: f32, k: f32) -> f32 { return x / (x * (1.0 - k) + k); }
|
|
142
|
+
fn sampleEnv(t: f32, count: i32) -> vec3<f32> {
|
|
143
|
+
var c = u.envColor[0].xyz;
|
|
144
|
+
if (count > 1) {
|
|
145
|
+
var last = u.envColor[1].xyz;
|
|
146
|
+
if (count > 2) { last = u.envColor[2].xyz; }
|
|
147
|
+
if (count > 3) { last = u.envColor[3].xyz; }
|
|
148
|
+
let o0 = u.envOffsets.x; let o1 = u.envOffsets.y; let o2 = u.envOffsets.z; let o3 = u.envOffsets.w;
|
|
149
|
+
if (t <= o1) {
|
|
150
|
+
c = mix(u.envColor[0].xyz, u.envColor[1].xyz, clamp((t - o0) / max(o1 - o0, 1e-4), 0.0, 1.0));
|
|
151
|
+
} else if (count > 2 && t <= o2) {
|
|
152
|
+
c = mix(u.envColor[1].xyz, u.envColor[2].xyz, clamp((t - o1) / max(o2 - o1, 1e-4), 0.0, 1.0));
|
|
153
|
+
} else if (count > 3 && t <= o3) {
|
|
154
|
+
c = mix(u.envColor[2].xyz, u.envColor[3].xyz, clamp((t - o2) / max(o3 - o2, 1e-4), 0.0, 1.0));
|
|
155
|
+
} else {
|
|
156
|
+
c = last;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return c;
|
|
160
|
+
}
|
|
161
|
+
// Shade a fragment given its straight albedo, world normal, view vector.
|
|
162
|
+
fn shadePBR(albedo: vec3<f32>, Nin: vec3<f32>, V: vec3<f32>) -> vec3<f32> {
|
|
163
|
+
var N = Nin;
|
|
164
|
+
if (dot(N, V) < 0.0) { N = -N; } // two-sided
|
|
165
|
+
let NdotV = max(dot(N, V), 1e-4);
|
|
166
|
+
let rough = u.params1.x;
|
|
167
|
+
let metal = u.params1.y;
|
|
168
|
+
let F0 = mix(vec3<f32>(0.04), albedo, metal);
|
|
169
|
+
let a = rough * rough;
|
|
170
|
+
let k = (rough + 1.0) * (rough + 1.0) / 8.0;
|
|
171
|
+
let numLights = i32(u.params0.w);
|
|
172
|
+
|
|
173
|
+
var color = albedo * u.ambient.xyz; // ambient (flat fill) term
|
|
174
|
+
for (var i: i32 = 0; i < 4; i = i + 1) {
|
|
175
|
+
if (i >= numLights) { break; }
|
|
176
|
+
let L = normalize(u.lightDir[i].xyz);
|
|
177
|
+
let H = normalize(V + L);
|
|
178
|
+
let NdotL = max(dot(N, L), 0.0);
|
|
179
|
+
let NdotH = max(dot(N, H), 0.0);
|
|
180
|
+
let VdotH = max(dot(V, H), 0.0);
|
|
181
|
+
let F = F0 + (vec3<f32>(1.0) - F0) * pow(1.0 - VdotH, 5.0);
|
|
182
|
+
let D = ggxD(NdotH, a);
|
|
183
|
+
let G = gSchlick(NdotL, k) * gSchlick(NdotV, k);
|
|
184
|
+
let spec = (D * G) * F / max(4.0 * NdotL * NdotV, 1e-3);
|
|
185
|
+
let kd = (vec3<f32>(1.0) - F) * (1.0 - metal);
|
|
186
|
+
color = color + (kd * albedo + spec) * u.lightColor[i].xyz * NdotL;
|
|
187
|
+
}
|
|
188
|
+
let envCount = i32(u.envParams.x);
|
|
189
|
+
let envIsImage = u.envParams.w > 0.5;
|
|
190
|
+
if (envCount > 0 || envIsImage) {
|
|
191
|
+
let R = reflect(-V, N);
|
|
192
|
+
var sharp: vec3<f32>;
|
|
193
|
+
if (envIsImage) {
|
|
194
|
+
// Equirect (lat-long) sample along the reflection ray. Up = \\u2212y.
|
|
195
|
+
let Rn = normalize(R);
|
|
196
|
+
let euv = vec2<f32>(atan2(Rn.x, Rn.z) / (2.0 * PI) + 0.5, acos(clamp(-Rn.y, -1.0, 1.0)) / PI);
|
|
197
|
+
sharp = textureSampleLevel(envTex, samp, euv, 0.0).rgb;
|
|
198
|
+
} else {
|
|
199
|
+
let t = clamp(0.5 - 0.5 * (R.y / max(length(R), 1e-4)), 0.0, 1.0); // up\\u21921, down\\u21920
|
|
200
|
+
sharp = sampleEnv(t, envCount);
|
|
201
|
+
}
|
|
202
|
+
let envc = mix(sharp, u.envAvg.xyz, rough);
|
|
203
|
+
let Fr = F0 + (max(vec3<f32>(1.0 - rough), F0) - F0) * pow(1.0 - NdotV, 5.0);
|
|
204
|
+
let kdEnv = (vec3<f32>(1.0) - Fr) * (1.0 - metal);
|
|
205
|
+
color = color + (kdEnv * albedo * u.envAvg.xyz + envc * Fr) * u.params1.z;
|
|
206
|
+
}
|
|
207
|
+
color = mix(color, albedo, clamp(u.params1.w, 0.0, 1.0)); // emissive
|
|
208
|
+
return clamp(color, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
209
|
+
}
|
|
210
|
+
\`,Uo=\`
|
|
211
|
+
fn perturbNormal(N: vec3<f32>, uv: vec2<f32>, nmap: texture_2d<f32>, nsamp: sampler) -> vec3<f32> {
|
|
212
|
+
if (u.envParams.z < 0.5) { return N; }
|
|
213
|
+
let s = textureSample(nmap, nsamp, uv).rgb * 2.0 - 1.0;
|
|
214
|
+
let sc = s.xy * u.envParams.y;
|
|
215
|
+
return normalize(sc.x * normalize(u.tangent.xyz) + sc.y * normalize(u.bitangent.xyz) + s.z * N);
|
|
216
|
+
}
|
|
217
|
+
\`,Qd=To+\`
|
|
218
|
+
@group(0) @binding(1) var samp: sampler;
|
|
219
|
+
@group(0) @binding(2) var normalTex: texture_2d<f32>;
|
|
220
|
+
@group(0) @binding(3) var envTex: texture_2d<f32>;
|
|
221
|
+
|
|
222
|
+
struct VsOut {
|
|
223
|
+
@builtin(position) position: vec4<f32>,
|
|
224
|
+
@location(0) uv: vec2<f32>,
|
|
225
|
+
@location(1) worldPos: vec3<f32>,
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
@vertex
|
|
229
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
230
|
+
var out: VsOut;
|
|
231
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
232
|
+
out.uv = uv;
|
|
233
|
+
let wp = u.worldMatrix * vec4<f32>(pos, 0.0, 1.0);
|
|
234
|
+
out.worldPos = wp.xyz;
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
\`+Eo+Uo+\`
|
|
238
|
+
@fragment
|
|
239
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
240
|
+
let p = in.uv * u.size.xy;
|
|
241
|
+
let half = u.size.xy * 0.5;
|
|
242
|
+
let cornerRadius = u.params0.x;
|
|
243
|
+
let shapeType = u.params0.y;
|
|
244
|
+
let strokeWidth = u.params0.z;
|
|
245
|
+
|
|
246
|
+
var dist: f32;
|
|
247
|
+
if (shapeType > 0.5) {
|
|
248
|
+
let d = (p - half) / half;
|
|
249
|
+
dist = (sqrt(dot(d, d)) - 1.0) * min(half.x, half.y);
|
|
250
|
+
} else {
|
|
251
|
+
let r = cornerRadius;
|
|
252
|
+
let q = abs(p - half) - half + vec2<f32>(r, r);
|
|
253
|
+
dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0, 0.0))) - r;
|
|
254
|
+
}
|
|
255
|
+
let aa = fwidth(dist);
|
|
256
|
+
let outerAlpha = 1.0 - smoothstep(-aa, aa, dist);
|
|
257
|
+
if (outerAlpha < 0.001) { discard; }
|
|
258
|
+
|
|
259
|
+
var alb = u.albedo;
|
|
260
|
+
if (strokeWidth > 0.0) {
|
|
261
|
+
let sa = smoothstep(-strokeWidth - aa, -strokeWidth + aa, dist);
|
|
262
|
+
alb = mix(u.albedo, u.strokeAlbedo, sa);
|
|
263
|
+
}
|
|
264
|
+
let N = perturbNormal(normalize(u.normal.xyz), in.uv, normalTex, samp);
|
|
265
|
+
let color = shadePBR(alb.rgb, N, normalize(u.eye.xyz - in.worldPos));
|
|
266
|
+
let outA = alb.a * outerAlpha;
|
|
267
|
+
return vec4<f32>(color * outA, outA); // premultiplied
|
|
268
|
+
}
|
|
269
|
+
\`,Kd=To+\`
|
|
270
|
+
@group(0) @binding(1) var samp: sampler;
|
|
271
|
+
@group(0) @binding(2) var tex: texture_2d<f32>;
|
|
272
|
+
@group(0) @binding(3) var normalTex: texture_2d<f32>;
|
|
273
|
+
@group(0) @binding(4) var envTex: texture_2d<f32>;
|
|
274
|
+
|
|
275
|
+
struct VsOut {
|
|
276
|
+
@builtin(position) position: vec4<f32>,
|
|
277
|
+
@location(0) uv: vec2<f32>,
|
|
278
|
+
@location(1) quadPos: vec2<f32>,
|
|
279
|
+
@location(2) worldPos: vec3<f32>,
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
@vertex
|
|
283
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
284
|
+
var out: VsOut;
|
|
285
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
286
|
+
out.uv = mix(u.strokeAlbedo.xy, u.strokeAlbedo.zw, uv); // strokeAlbedo = uvRect
|
|
287
|
+
out.quadPos = uv;
|
|
288
|
+
let wp = u.worldMatrix * vec4<f32>(pos, 0.0, 1.0);
|
|
289
|
+
out.worldPos = wp.xyz;
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
\`+Eo+Uo+\`
|
|
293
|
+
@fragment
|
|
294
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
295
|
+
let s = textureSample(tex, samp, in.uv); // premultiplied
|
|
296
|
+
let cov = s.a;
|
|
297
|
+
var albedo = select(s.rgb, s.rgb / cov, cov > 0.0); // straight albedo
|
|
298
|
+
let tint = u.albedo; // premultiplied tint
|
|
299
|
+
let tintRgb = select(vec3<f32>(1.0), tint.rgb / tint.a, tint.a > 0.0);
|
|
300
|
+
albedo = albedo * tintRgb;
|
|
301
|
+
|
|
302
|
+
var maskAlpha = 1.0;
|
|
303
|
+
let cornerRadius = u.params0.x;
|
|
304
|
+
if (cornerRadius > 0.0) {
|
|
305
|
+
let p = in.quadPos * u.size.xy;
|
|
306
|
+
let half = u.size.xy * 0.5;
|
|
307
|
+
let r = cornerRadius;
|
|
308
|
+
let q = abs(p - half) - half + vec2<f32>(r, r);
|
|
309
|
+
let dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0, 0.0))) - r;
|
|
310
|
+
let aa = fwidth(dist);
|
|
311
|
+
maskAlpha = 1.0 - smoothstep(-aa, aa, dist);
|
|
312
|
+
if (maskAlpha < 0.001) { discard; }
|
|
313
|
+
}
|
|
314
|
+
let N = perturbNormal(normalize(u.normal.xyz), in.quadPos, normalTex, samp);
|
|
315
|
+
let color = shadePBR(albedo, N, normalize(u.eye.xyz - in.worldPos));
|
|
316
|
+
let outA = cov * tint.a * maskAlpha;
|
|
317
|
+
return vec4<f32>(color * outA, outA); // premultiplied
|
|
318
|
+
}
|
|
319
|
+
\`,Jd=\`
|
|
320
|
+
struct GradientUniforms {
|
|
321
|
+
transform: mat4x4<f32>, // offset 0, size 64
|
|
322
|
+
flags: vec4<f32>, // offset 64, size 16 \\u2014 cornerRadius (PIXELS), shapeType, fillType, numStops ("meta" is a reserved WGSL keyword)
|
|
323
|
+
params: vec4<f32>, // offset 80, size 16 \\u2014 linear:(cos,sin,_,_) | radial:(cx,cy,radius,_)
|
|
324
|
+
size: vec4<f32>, // offset 96, size 16 \\u2014 (width_px, height_px, _, _)
|
|
325
|
+
stop0: vec4<f32>, // offset 112, size 16
|
|
326
|
+
stop1: vec4<f32>, // offset 128, size 16
|
|
327
|
+
stop2: vec4<f32>, // offset 144, size 16
|
|
328
|
+
stop3: vec4<f32>, // offset 160, size 16
|
|
329
|
+
stopOffsets: vec4<f32>, // offset 176, size 16
|
|
330
|
+
} // total: 192 bytes
|
|
331
|
+
@group(0) @binding(0) var<uniform> u: GradientUniforms;
|
|
332
|
+
|
|
333
|
+
struct VsOut {
|
|
334
|
+
@builtin(position) position: vec4<f32>,
|
|
335
|
+
@location(0) uv: vec2<f32>,
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
@vertex
|
|
339
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
340
|
+
var out: VsOut;
|
|
341
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
342
|
+
out.uv = uv;
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
@fragment
|
|
347
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
348
|
+
let uv = in.uv;
|
|
349
|
+
let cornerRadius = u.flags.x;
|
|
350
|
+
let shapeType = u.flags.y;
|
|
351
|
+
let fillType = u.flags.z;
|
|
352
|
+
|
|
353
|
+
// Shape masking \\u2014 SDF in PIXEL space so corners are circular even on
|
|
354
|
+
// non-square rectangles. Gradient parameter t still runs in UV space.
|
|
355
|
+
let pxSize = u.size.xy;
|
|
356
|
+
let p = uv * pxSize;
|
|
357
|
+
let half = pxSize * 0.5;
|
|
358
|
+
|
|
359
|
+
if (shapeType > 0.5) {
|
|
360
|
+
let d = (p - half) / half;
|
|
361
|
+
if (dot(d, d) > 1.0) { discard; }
|
|
362
|
+
} else if (cornerRadius > 0.0) {
|
|
363
|
+
let r = cornerRadius;
|
|
364
|
+
let q = abs(p - half) - (half - vec2<f32>(r, r));
|
|
365
|
+
let outside = max(q, vec2<f32>(0.0, 0.0));
|
|
366
|
+
if (length(outside) > r) { discard; }
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// Compute gradient parameter t in [0, 1] (still in UV space \\u2014 gradient
|
|
370
|
+
// directions are expressed relative to the shape's normalized bounding box).
|
|
371
|
+
var t: f32 = 0.0;
|
|
372
|
+
if (fillType > 0.5) {
|
|
373
|
+
let radius = max(u.params.z, 0.0001);
|
|
374
|
+
t = clamp(distance(uv, u.params.xy) / radius, 0.0, 1.0);
|
|
375
|
+
} else {
|
|
376
|
+
let dir = u.params.xy;
|
|
377
|
+
let centered = uv - vec2<f32>(0.5, 0.5);
|
|
378
|
+
t = clamp(dot(centered, dir) + 0.5, 0.0, 1.0);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
let off0 = u.stopOffsets.x;
|
|
382
|
+
let off1 = u.stopOffsets.y;
|
|
383
|
+
let off2 = u.stopOffsets.z;
|
|
384
|
+
let off3 = u.stopOffsets.w;
|
|
385
|
+
|
|
386
|
+
var color: vec4<f32>;
|
|
387
|
+
if (t <= off1) {
|
|
388
|
+
let denom = max(off1 - off0, 0.0001);
|
|
389
|
+
let segT = clamp((t - off0) / denom, 0.0, 1.0);
|
|
390
|
+
color = mix(u.stop0, u.stop1, segT);
|
|
391
|
+
} else if (t <= off2) {
|
|
392
|
+
let denom = max(off2 - off1, 0.0001);
|
|
393
|
+
let segT = clamp((t - off1) / denom, 0.0, 1.0);
|
|
394
|
+
color = mix(u.stop1, u.stop2, segT);
|
|
395
|
+
} else if (t <= off3) {
|
|
396
|
+
let denom = max(off3 - off2, 0.0001);
|
|
397
|
+
let segT = clamp((t - off2) / denom, 0.0, 1.0);
|
|
398
|
+
color = mix(u.stop2, u.stop3, segT);
|
|
399
|
+
} else {
|
|
400
|
+
color = u.stop3;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
return color;
|
|
404
|
+
}
|
|
405
|
+
\`,eu=\`
|
|
406
|
+
struct TexturedUniforms {
|
|
407
|
+
transform: mat4x4<f32>, // 64 bytes, offset 0
|
|
408
|
+
uvRect: vec4<f32>, // 16 bytes, offset 64 \\u2014 (u0, v0, u1, v1)
|
|
409
|
+
tint: vec4<f32>, // 16 bytes, offset 80 \\u2014 premultiplied
|
|
410
|
+
cornerRadius: f32, // 4 bytes, offset 96
|
|
411
|
+
alphaGamma: f32, // 4 bytes, offset 100 \\u2014 coverage exponent; 1 = no-op
|
|
412
|
+
size: vec2<f32>, // 8 bytes, offset 104 \\u2014 pixel (w, h) of the quad
|
|
413
|
+
_pad1: vec4<f32>, // 16 bytes, offset 112 \\u2014 pad to 128
|
|
414
|
+
} // total: 128 bytes (aligned to 16)
|
|
415
|
+
@group(0) @binding(0) var<uniform> u: TexturedUniforms;
|
|
416
|
+
@group(0) @binding(1) var samp: sampler;
|
|
417
|
+
@group(0) @binding(2) var tex: texture_2d<f32>;
|
|
418
|
+
|
|
419
|
+
struct VsOut {
|
|
420
|
+
@builtin(position) position: vec4<f32>,
|
|
421
|
+
@location(0) uv: vec2<f32>,
|
|
422
|
+
@location(1) quadPos: vec2<f32>,
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
@vertex
|
|
426
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
427
|
+
var out: VsOut;
|
|
428
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
429
|
+
// Remap default 0..1 UVs into the sub-rect specified by uvRect.
|
|
430
|
+
out.uv = mix(u.uvRect.xy, u.uvRect.zw, uv);
|
|
431
|
+
out.quadPos = uv;
|
|
432
|
+
return out;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
@fragment
|
|
436
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
437
|
+
var sample = textureSample(tex, samp, in.uv); // already premultiplied (texture upload set premultipliedAlpha: true)
|
|
438
|
+
if (u.alphaGamma != 1.0) {
|
|
439
|
+
// Reshape coverage: a' = a^g. Premultiplied, so scale the whole
|
|
440
|
+
// sample by a^(g-1); the max() guard keeps g<1 finite at a=0.
|
|
441
|
+
sample = sample * pow(max(sample.a, 1e-5), u.alphaGamma - 1.0);
|
|
442
|
+
}
|
|
443
|
+
var maskAlpha: f32 = 1.0;
|
|
444
|
+
if (u.cornerRadius > 0.0) {
|
|
445
|
+
// Rounded-rect SDF in quad-local pixel space (matches SHAPE_FS).
|
|
446
|
+
let p = in.quadPos * u.size;
|
|
447
|
+
let half = u.size * 0.5;
|
|
448
|
+
let r = u.cornerRadius;
|
|
449
|
+
let q = abs(p - half) - half + vec2<f32>(r, r);
|
|
450
|
+
let dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0, 0.0))) - r;
|
|
451
|
+
let aa = fwidth(dist);
|
|
452
|
+
maskAlpha = 1.0 - smoothstep(-aa, aa, dist);
|
|
453
|
+
if (maskAlpha < 0.001) { discard; }
|
|
454
|
+
}
|
|
455
|
+
return sample * u.tint * maskAlpha;
|
|
456
|
+
}
|
|
457
|
+
\`,tu=\`
|
|
458
|
+
struct MaskedUniforms {
|
|
459
|
+
transform: mat4x4<f32>, // 64 bytes, offset 0
|
|
460
|
+
tint: vec4<f32>, // 16 bytes, offset 64 \\u2014 premultiplied
|
|
461
|
+
mode: f32, // 4 bytes, offset 80 \\u2014 0 alpha, 1 alpha-inv, 2 luma, 3 luma-inv
|
|
462
|
+
_pad0: f32,
|
|
463
|
+
_pad1: vec2<f32>, // pad to 96
|
|
464
|
+
}
|
|
465
|
+
@group(0) @binding(0) var<uniform> u: MaskedUniforms;
|
|
466
|
+
@group(0) @binding(1) var samp: sampler;
|
|
467
|
+
@group(0) @binding(2) var contentTex: texture_2d<f32>;
|
|
468
|
+
@group(0) @binding(3) var maskTex: texture_2d<f32>;
|
|
469
|
+
|
|
470
|
+
struct VsOut {
|
|
471
|
+
@builtin(position) position: vec4<f32>,
|
|
472
|
+
@location(0) uv: vec2<f32>,
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
@vertex
|
|
476
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
477
|
+
var out: VsOut;
|
|
478
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
479
|
+
out.uv = uv;
|
|
480
|
+
return out;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
@fragment
|
|
484
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
485
|
+
let c = textureSample(contentTex, samp, in.uv) * u.tint;
|
|
486
|
+
let m = textureSample(maskTex, samp, in.uv);
|
|
487
|
+
var f: f32;
|
|
488
|
+
if (u.mode < 0.5) {
|
|
489
|
+
f = m.a;
|
|
490
|
+
} else if (u.mode < 1.5) {
|
|
491
|
+
f = 1.0 - m.a;
|
|
492
|
+
} else {
|
|
493
|
+
let luma = dot(m.rgb, vec3<f32>(0.2126, 0.7152, 0.0722));
|
|
494
|
+
f = select(1.0 - luma, luma, u.mode < 2.5);
|
|
495
|
+
}
|
|
496
|
+
return c * f;
|
|
497
|
+
}
|
|
498
|
+
\`,iu=\`
|
|
499
|
+
struct BBUniforms {
|
|
500
|
+
transform: mat4x4<f32>, // 64 bytes
|
|
501
|
+
mode: f32, // 0 overlay, 1 hard-light, 2 soft-light
|
|
502
|
+
backdropFlipY: f32,
|
|
503
|
+
_pad: vec2<f32>, // pad to 80
|
|
504
|
+
}
|
|
505
|
+
@group(0) @binding(0) var<uniform> u: BBUniforms;
|
|
506
|
+
@group(0) @binding(1) var samp: sampler;
|
|
507
|
+
@group(0) @binding(2) var srcTex: texture_2d<f32>;
|
|
508
|
+
@group(0) @binding(3) var backdropTex: texture_2d<f32>;
|
|
509
|
+
|
|
510
|
+
struct VsOut {
|
|
511
|
+
@builtin(position) position: vec4<f32>,
|
|
512
|
+
@location(0) uv: vec2<f32>,
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
@vertex
|
|
516
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
517
|
+
var out: VsOut;
|
|
518
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
519
|
+
out.uv = uv;
|
|
520
|
+
return out;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
fn blendCh(mode: f32, cb: f32, cs: f32) -> f32 {
|
|
524
|
+
if (mode < 0.5) { // overlay
|
|
525
|
+
return select(1.0 - 2.0*(1.0-cb)*(1.0-cs), 2.0*cb*cs, cb <= 0.5);
|
|
526
|
+
} else if (mode < 1.5) { // hard-light = overlay(src, backdrop)
|
|
527
|
+
return select(1.0 - 2.0*(1.0-cs)*(1.0-cb), 2.0*cs*cb, cs <= 0.5);
|
|
528
|
+
} else { // soft-light (W3C)
|
|
529
|
+
if (cs <= 0.5) {
|
|
530
|
+
return cb - (1.0 - 2.0*cs) * cb * (1.0 - cb);
|
|
531
|
+
}
|
|
532
|
+
let d = select(sqrt(cb), ((16.0*cb - 12.0)*cb + 4.0)*cb, cb <= 0.25);
|
|
533
|
+
return cb + (2.0*cs - 1.0) * (d - cb);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
@fragment
|
|
538
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
539
|
+
let s = textureSample(srcTex, samp, in.uv);
|
|
540
|
+
let buv = vec2<f32>(in.uv.x, select(in.uv.y, 1.0 - in.uv.y, u.backdropFlipY > 0.5));
|
|
541
|
+
let b = textureSample(backdropTex, samp, buv);
|
|
542
|
+
let sa = s.a;
|
|
543
|
+
let ba = b.a;
|
|
544
|
+
let Cs = select(vec3<f32>(0.0), s.rgb / sa, sa > 0.0);
|
|
545
|
+
let Cb = select(vec3<f32>(0.0), b.rgb / ba, ba > 0.0);
|
|
546
|
+
let Bc = vec3<f32>(blendCh(u.mode, Cb.r, Cs.r), blendCh(u.mode, Cb.g, Cs.g), blendCh(u.mode, Cb.b, Cs.b));
|
|
547
|
+
let co = sa*(1.0-ba)*Cs + sa*ba*Bc + (1.0-sa)*ba*Cb; // premultiplied
|
|
548
|
+
let ao = sa + ba*(1.0-sa);
|
|
549
|
+
return vec4<f32>(co, ao);
|
|
550
|
+
}
|
|
551
|
+
\`,su=\`
|
|
552
|
+
struct FilteredUniforms {
|
|
553
|
+
transform: mat4x4<f32>, // 64 bytes, offset 0
|
|
554
|
+
tint: vec4<f32>, // 16 bytes, offset 64 \\u2014 premultiplied
|
|
555
|
+
texel: vec2<f32>, // 8 bytes, offset 80 \\u2014 blur dir \\xF7 tex physical dims
|
|
556
|
+
sigma: f32, // 4 bytes, offset 88 \\u2014 Gaussian \\u03C3 in PHYSICAL px; 0 = off
|
|
557
|
+
_pad0: f32, // 4 bytes, offset 92
|
|
558
|
+
colorOps: vec4<f32>, // 16 bytes, offset 96 \\u2014 (brightness, contrast, saturation, hue radians)
|
|
559
|
+
} // total: 112, buffer rounded to 128
|
|
560
|
+
@group(0) @binding(0) var<uniform> u: FilteredUniforms;
|
|
561
|
+
@group(0) @binding(1) var samp: sampler;
|
|
562
|
+
@group(0) @binding(2) var tex: texture_2d<f32>;
|
|
563
|
+
|
|
564
|
+
struct VsOut {
|
|
565
|
+
@builtin(position) position: vec4<f32>,
|
|
566
|
+
@location(0) uv: vec2<f32>,
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
@vertex
|
|
570
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
571
|
+
var out: VsOut;
|
|
572
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
573
|
+
out.uv = uv;
|
|
574
|
+
return out;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
@fragment
|
|
578
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
579
|
+
var acc: vec4<f32>;
|
|
580
|
+
if (u.sigma > 0.0) {
|
|
581
|
+
acc = vec4<f32>(0.0);
|
|
582
|
+
var wsum: f32 = 0.0;
|
|
583
|
+
for (var i: i32 = -12; i <= 12; i++) {
|
|
584
|
+
let d = f32(i) * u.sigma * 0.25; // taps cover \\xB13\\u03C3
|
|
585
|
+
let w = exp(-0.5 * d * d / (u.sigma * u.sigma));
|
|
586
|
+
acc += textureSampleLevel(tex, samp, in.uv + u.texel * d, 0.0) * w;
|
|
587
|
+
wsum += w;
|
|
588
|
+
}
|
|
589
|
+
acc /= wsum;
|
|
590
|
+
} else {
|
|
591
|
+
acc = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
592
|
+
}
|
|
593
|
+
let a = acc.a;
|
|
594
|
+
var c = select(vec3<f32>(0.0), acc.rgb / a, a > 0.0);
|
|
595
|
+
c *= u.colorOps.x; // brightness
|
|
596
|
+
c = (c - 0.5) * u.colorOps.y + 0.5; // contrast
|
|
597
|
+
let l = dot(c, vec3<f32>(0.2126, 0.7152, 0.0722)); // Rec. 709 luma
|
|
598
|
+
c = mix(vec3<f32>(l), c, u.colorOps.z); // saturation
|
|
599
|
+
if (u.colorOps.w != 0.0) { // hue rotate (SVG matrix)
|
|
600
|
+
let hc = cos(u.colorOps.w);
|
|
601
|
+
let hs = sin(u.colorOps.w);
|
|
602
|
+
c = mat3x3<f32>(
|
|
603
|
+
vec3<f32>(0.213 + 0.787*hc - 0.213*hs, 0.213 - 0.213*hc + 0.143*hs, 0.213 - 0.213*hc - 0.787*hs),
|
|
604
|
+
vec3<f32>(0.715 - 0.715*hc - 0.715*hs, 0.715 + 0.285*hc + 0.140*hs, 0.715 - 0.715*hc + 0.715*hs),
|
|
605
|
+
vec3<f32>(0.072 - 0.072*hc + 0.928*hs, 0.072 - 0.072*hc - 0.283*hs, 0.072 + 0.928*hc + 0.072*hs)
|
|
606
|
+
) * c;
|
|
607
|
+
}
|
|
608
|
+
c = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
609
|
+
return vec4<f32>(c * a, a) * u.tint;
|
|
610
|
+
}
|
|
611
|
+
\`,ru=\`
|
|
612
|
+
struct StylizedUniforms {
|
|
613
|
+
transform: mat4x4<f32>, // 64 bytes, offset 0
|
|
614
|
+
tint: vec4<f32>, // 16 bytes, offset 64 \\u2014 premultiplied
|
|
615
|
+
texSize: vec2<f32>, // 8 bytes, offset 80 \\u2014 layer PHYSICAL dims
|
|
616
|
+
mode: f32, // 4 bytes, offset 88 \\u2014 0 pixelate, 1 dither, 2 halftone, 3 ascii
|
|
617
|
+
p0: f32, // 4 bytes, offset 92 \\u2014 px params pre-scaled to PHYSICAL
|
|
618
|
+
p1: f32, // 4 bytes, offset 96
|
|
619
|
+
pixelRatio: f32, // 100 \\u2014 for resolution-independent dither cells
|
|
620
|
+
_pad1: f32, // 104
|
|
621
|
+
_pad2: f32, // 108 \\u2014 struct size 112
|
|
622
|
+
}
|
|
623
|
+
@group(0) @binding(0) var<uniform> u: StylizedUniforms;
|
|
624
|
+
@group(0) @binding(1) var samp: sampler;
|
|
625
|
+
@group(0) @binding(2) var tex: texture_2d<f32>;
|
|
626
|
+
@group(0) @binding(3) var aux: texture_2d<f32>;
|
|
627
|
+
|
|
628
|
+
const BAYER = array<f32, 16>(
|
|
629
|
+
0., 8., 2., 10.,
|
|
630
|
+
12., 4., 14., 6.,
|
|
631
|
+
3., 11., 1., 9.,
|
|
632
|
+
15., 7., 13., 5.);
|
|
633
|
+
|
|
634
|
+
struct VsOut {
|
|
635
|
+
@builtin(position) position: vec4<f32>,
|
|
636
|
+
@location(0) uv: vec2<f32>,
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
@vertex
|
|
640
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
641
|
+
var out: VsOut;
|
|
642
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
643
|
+
out.uv = uv;
|
|
644
|
+
return out;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
fn straight(s: vec4<f32>) -> vec3<f32> {
|
|
648
|
+
return select(vec3<f32>(0.0), s.rgb / s.a, s.a > 0.0);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// \\u2500\\u2500 Normative noise (\\xA74.7 fractal_noise / turbulent_displace) \\u2500\\u2500
|
|
652
|
+
// Must match the WebGL helpers exactly: PCG hash \\u2192 value noise
|
|
653
|
+
// (quintic fade) \\u2192 fBM (lacunarity 2, gain 0.5, per-octave seed+o).
|
|
654
|
+
fn pcg(v: u32) -> u32 {
|
|
655
|
+
let s = v * 747796405u + 2891336453u;
|
|
656
|
+
let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
|
|
657
|
+
return (w >> 22u) ^ w;
|
|
658
|
+
}
|
|
659
|
+
fn h01(c: vec3<i32>, seed: u32) -> f32 {
|
|
660
|
+
return f32(pcg(bitcast<u32>(c.x) ^ pcg(bitcast<u32>(c.y) ^ pcg(bitcast<u32>(c.z) ^ pcg(seed))))) / 4294967295.0;
|
|
661
|
+
}
|
|
662
|
+
fn vnoise(p: vec3<f32>, seed: u32) -> f32 {
|
|
663
|
+
let i = floor(p);
|
|
664
|
+
let f = p - i;
|
|
665
|
+
let uu = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
|
|
666
|
+
let c = vec3<i32>(i);
|
|
667
|
+
let n000 = h01(c, seed);
|
|
668
|
+
let n100 = h01(c + vec3<i32>(1, 0, 0), seed);
|
|
669
|
+
let n010 = h01(c + vec3<i32>(0, 1, 0), seed);
|
|
670
|
+
let n110 = h01(c + vec3<i32>(1, 1, 0), seed);
|
|
671
|
+
let n001 = h01(c + vec3<i32>(0, 0, 1), seed);
|
|
672
|
+
let n101 = h01(c + vec3<i32>(1, 0, 1), seed);
|
|
673
|
+
let n011 = h01(c + vec3<i32>(0, 1, 1), seed);
|
|
674
|
+
let n111 = h01(c + vec3<i32>(1, 1, 1), seed);
|
|
675
|
+
return mix(
|
|
676
|
+
mix(mix(n000, n100, uu.x), mix(n010, n110, uu.x), uu.y),
|
|
677
|
+
mix(mix(n001, n101, uu.x), mix(n011, n111, uu.x), uu.y), uu.z);
|
|
678
|
+
}
|
|
679
|
+
fn fbm(p0: vec3<f32>, octaves: i32, seed: u32) -> f32 {
|
|
680
|
+
var p = p0;
|
|
681
|
+
var v = 0.0;
|
|
682
|
+
var amp = 1.0;
|
|
683
|
+
var wsum = 0.0;
|
|
684
|
+
for (var o = 0; o < 8; o++) {
|
|
685
|
+
if (o >= octaves) { break; }
|
|
686
|
+
v += amp * vnoise(p, seed + u32(o));
|
|
687
|
+
wsum += amp;
|
|
688
|
+
p *= 2.0;
|
|
689
|
+
amp *= 0.5;
|
|
690
|
+
}
|
|
691
|
+
return v / wsum;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
@fragment
|
|
695
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {
|
|
696
|
+
let px = in.uv * u.texSize;
|
|
697
|
+
if (u.mode < 0.5) {
|
|
698
|
+
// pixelate \\u2014 every pixel takes its cell's center sample.
|
|
699
|
+
let cell = max(u.p0, 1.0);
|
|
700
|
+
let center = (floor(px / cell) + 0.5) * cell;
|
|
701
|
+
return textureSampleLevel(tex, samp, center / u.texSize, 0.0) * u.tint;
|
|
702
|
+
} else if (u.mode < 1.5) {
|
|
703
|
+
// dither \\u2014 per-channel quantize to N levels, 4\\xD74 Bayer threshold.
|
|
704
|
+
let s = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
705
|
+
let a = s.a;
|
|
706
|
+
var c = straight(s);
|
|
707
|
+
// Bayer cells of u.p1 (pixel_size) LOGICAL px: divide device px by
|
|
708
|
+
// (pixelRatio \\xB7 pixel_size). Resolution-independent \\u2014 stable across
|
|
709
|
+
// preview DPI / export and survives the editor fit-to-stage downscale.
|
|
710
|
+
let ip = vec2<i32>(px / max(u.pixelRatio * u.p1, 1.0));
|
|
711
|
+
var bayer = BAYER; // const arrays can't be dynamically indexed
|
|
712
|
+
let t = (bayer[(ip.y % 4) * 4 + (ip.x % 4)] + 0.5) / 16.0;
|
|
713
|
+
let n = max(u.p0, 2.0) - 1.0;
|
|
714
|
+
c = clamp(floor(c * n + t) / n, vec3<f32>(0.0), vec3<f32>(1.0));
|
|
715
|
+
return vec4<f32>(c * a, a) * u.tint;
|
|
716
|
+
} else if (u.mode < 2.5) {
|
|
717
|
+
// halftone \\u2014 rotated dot grid, radius \\u221D sqrt(luma), cell-color dots.
|
|
718
|
+
let cell = max(u.p0, 2.0);
|
|
719
|
+
let ang = radians(u.p1);
|
|
720
|
+
let cs = cos(ang);
|
|
721
|
+
let sn = sin(ang);
|
|
722
|
+
let rot = mat2x2<f32>(vec2<f32>(cs, -sn), vec2<f32>(sn, cs));
|
|
723
|
+
let inv = mat2x2<f32>(vec2<f32>(cs, sn), vec2<f32>(-sn, cs));
|
|
724
|
+
let rp = rot * px;
|
|
725
|
+
let centerR = (floor(rp / cell) + 0.5) * cell;
|
|
726
|
+
let s = textureSampleLevel(tex, samp, (inv * centerR) / u.texSize, 0.0);
|
|
727
|
+
let a = s.a;
|
|
728
|
+
let c = straight(s);
|
|
729
|
+
let luma = dot(c, vec3<f32>(0.2126, 0.7152, 0.0722)) * a;
|
|
730
|
+
let r = 0.5 * cell * sqrt(luma);
|
|
731
|
+
let d = length(rp - centerR);
|
|
732
|
+
let ink = (1.0 - smoothstep(r - 1.0, r + 1.0, d)) * clamp(r, 0.0, 1.0);
|
|
733
|
+
return vec4<f32>(c, 1.0) * (a * ink) * u.tint;
|
|
734
|
+
} else if (u.mode < 3.5) {
|
|
735
|
+
// ascii \\u2014 10-glyph density ramp from the atlas, cell-color tint.
|
|
736
|
+
let cell = max(u.p0, 4.0);
|
|
737
|
+
let cellOrigin = floor(px / cell) * cell;
|
|
738
|
+
let s = textureSampleLevel(tex, samp, (cellOrigin + 0.5 * cell) / u.texSize, 0.0);
|
|
739
|
+
let a = s.a;
|
|
740
|
+
let c = straight(s);
|
|
741
|
+
let luma = dot(c, vec3<f32>(0.2126, 0.7152, 0.0722)) * a;
|
|
742
|
+
let idx = clamp(floor(luma * 10.0), 0.0, 9.0);
|
|
743
|
+
let g = clamp(floor((px - cellOrigin) / cell * 8.0), vec2<f32>(0.0), vec2<f32>(7.0));
|
|
744
|
+
let auxUv = vec2<f32>((idx * 8.0 + g.x + 0.5) / 80.0, (g.y + 0.5) / 8.0);
|
|
745
|
+
let ink = textureSampleLevel(aux, samp, auxUv, 0.0).a;
|
|
746
|
+
return vec4<f32>(c, 1.0) * (a * ink) * u.tint;
|
|
747
|
+
} else if (u.mode < 4.5) {
|
|
748
|
+
// drop_shadow \\u2014 aux is the ladder-blurred layer; its alpha, offset
|
|
749
|
+
// and tinted, composites UNDER the content.
|
|
750
|
+
let c = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
751
|
+
let texel = 1.0 / u.texSize;
|
|
752
|
+
let ouv = clamp(in.uv - vec2<f32>(u.p0, u.p1) * texel, vec2<f32>(0.0), vec2<f32>(1.0));
|
|
753
|
+
let sa = textureSampleLevel(aux, samp, ouv, 0.0).a;
|
|
754
|
+
return c + u.tint * (sa * (1.0 - c.a));
|
|
755
|
+
} else if (u.mode < 5.5) {
|
|
756
|
+
// glow \\u2014 blurred silhouette \\xD7 intensity \\xD7 color, under the content.
|
|
757
|
+
let c = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
758
|
+
let ga = clamp(textureSampleLevel(aux, samp, in.uv, 0.0).a * u.p0, 0.0, 1.0);
|
|
759
|
+
return c + u.tint * (ga * (1.0 - c.a));
|
|
760
|
+
} else if (u.mode < 6.5) {
|
|
761
|
+
// stroke \\u2014 outline band outside the silhouette: max alpha over a
|
|
762
|
+
// 16-tap ring at the stroke width, under the content.
|
|
763
|
+
let c = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
764
|
+
let texel = 1.0 / u.texSize;
|
|
765
|
+
let w = max(u.p0, 1.0);
|
|
766
|
+
var s = 0.0;
|
|
767
|
+
for (var i = 0; i < 16; i++) {
|
|
768
|
+
let ang = 6.2831853 * f32(i) / 16.0;
|
|
769
|
+
let tuv = clamp(in.uv + vec2<f32>(cos(ang), sin(ang)) * w * texel, vec2<f32>(0.0), vec2<f32>(1.0));
|
|
770
|
+
s = max(s, textureSampleLevel(tex, samp, tuv, 0.0).a);
|
|
771
|
+
}
|
|
772
|
+
return c + u.tint * (s * (1.0 - c.a));
|
|
773
|
+
} else if (u.mode < 7.5) {
|
|
774
|
+
// chroma_key \\u2014 BT.709 CbCr distance ramp (\\xA74.7). u.tint.rgb = key
|
|
775
|
+
// color (STRAIGHT), u.tint.a = spill; p0 tolerance, p1 softness.
|
|
776
|
+
let s = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
777
|
+
var c = straight(s);
|
|
778
|
+
let k = u.tint.rgb;
|
|
779
|
+
let LUMA = vec3<f32>(0.2126, 0.7152, 0.0722);
|
|
780
|
+
let cy = dot(c, LUMA);
|
|
781
|
+
let ky = dot(k, LUMA);
|
|
782
|
+
let cc = vec2<f32>((c.b - cy) / 1.8556, (c.r - cy) / 1.5748);
|
|
783
|
+
let kc = vec2<f32>((k.b - ky) / 1.8556, (k.r - ky) / 1.5748);
|
|
784
|
+
let d = distance(cc, kc);
|
|
785
|
+
var a = select(
|
|
786
|
+
select(1.0, 0.0, d <= u.p0),
|
|
787
|
+
clamp((d - u.p0) / u.p1, 0.0, 1.0),
|
|
788
|
+
u.p1 > 0.0);
|
|
789
|
+
// Spill suppression: cap the key's dominant channel (ties g\\u2192r\\u2192b)
|
|
790
|
+
// at the max of the other two, scaled by spill.
|
|
791
|
+
if (k.g >= k.r && k.g >= k.b) {
|
|
792
|
+
c.g -= u.tint.a * max(0.0, c.g - max(c.r, c.b));
|
|
793
|
+
} else if (k.r >= k.b) {
|
|
794
|
+
c.r -= u.tint.a * max(0.0, c.r - max(c.g, c.b));
|
|
795
|
+
} else {
|
|
796
|
+
c.b -= u.tint.a * max(0.0, c.b - max(c.r, c.g));
|
|
797
|
+
}
|
|
798
|
+
let ao = s.a * a;
|
|
799
|
+
return vec4<f32>(c * ao, ao);
|
|
800
|
+
} else if (u.mode < 8.5) {
|
|
801
|
+
// luma_key \\u2014 p0 threshold, p1 softness, u.tint.r = invert flag.
|
|
802
|
+
let s = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
803
|
+
let c = straight(s);
|
|
804
|
+
let y = dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
|
|
805
|
+
var a = select(
|
|
806
|
+
select(1.0, 0.0, y <= u.p0),
|
|
807
|
+
clamp((y - u.p0) / u.p1, 0.0, 1.0),
|
|
808
|
+
u.p1 > 0.0);
|
|
809
|
+
if (u.tint.x > 0.5) { a = 1.0 - a; }
|
|
810
|
+
let ao = s.a * a;
|
|
811
|
+
return vec4<f32>(c * ao, ao);
|
|
812
|
+
} else if (u.mode < 9.5) {
|
|
813
|
+
// levels \\u2014 per-channel remap (\\xA74.7): u.tint = (in_black, in_white,
|
|
814
|
+
// out_black, out_white), p0 = gamma; y = x^(1/gamma).
|
|
815
|
+
let s = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
816
|
+
let c = straight(s);
|
|
817
|
+
var x = clamp((c - u.tint.x) / max(u.tint.y - u.tint.x, 1e-5), vec3<f32>(0.0), vec3<f32>(1.0));
|
|
818
|
+
x = pow(x, vec3<f32>(1.0 / max(u.p0, 1e-5)));
|
|
819
|
+
let o = clamp(u.tint.z + x * (u.tint.w - u.tint.z), vec3<f32>(0.0), vec3<f32>(1.0));
|
|
820
|
+
return vec4<f32>(o * s.a, s.a);
|
|
821
|
+
} else if (u.mode < 10.5) {
|
|
822
|
+
// lut \\u2014 3D lattice packed as N slices along x in a 2D atlas (aux,
|
|
823
|
+
// N\\xB2\\xD7N, slice index = blue). Manual trilinear: two bilinear taps
|
|
824
|
+
// mixed across the blue axis. p0 = N, p1 = intensity.
|
|
825
|
+
let s = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
826
|
+
let c = straight(s);
|
|
827
|
+
let n = max(u.p0, 2.0);
|
|
828
|
+
let b = clamp(c.b, 0.0, 1.0) * (n - 1.0);
|
|
829
|
+
let b0 = floor(b);
|
|
830
|
+
let b1 = min(b0 + 1.0, n - 1.0);
|
|
831
|
+
let cellUv = vec2<f32>(
|
|
832
|
+
(clamp(c.r, 0.0, 1.0) * (n - 1.0) + 0.5) / (n * n),
|
|
833
|
+
(clamp(c.g, 0.0, 1.0) * (n - 1.0) + 0.5) / n);
|
|
834
|
+
let lo = textureSampleLevel(aux, samp, cellUv + vec2<f32>(b0 / n, 0.0), 0.0).rgb;
|
|
835
|
+
let hi = textureSampleLevel(aux, samp, cellUv + vec2<f32>(b1 / n, 0.0), 0.0).rgb;
|
|
836
|
+
let graded = mix(c, mix(lo, hi, b - b0), clamp(u.p1, 0.0, 1.0));
|
|
837
|
+
return vec4<f32>(clamp(graded, vec3<f32>(0.0), vec3<f32>(1.0)) * s.a, s.a);
|
|
838
|
+
} else if (u.mode < 11.5) {
|
|
839
|
+
// fractal_noise \\u2014 grayscale fBM over the element's footprint.
|
|
840
|
+
// p0 = scale px, p1 = evolution,
|
|
841
|
+
// u.tint = (offset_x/scale, offset_y/scale, octaves, seed).
|
|
842
|
+
let s = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
843
|
+
let v = fbm(
|
|
844
|
+
vec3<f32>(px / max(u.p0, 1e-3) + u.tint.xy, u.p1),
|
|
845
|
+
i32(u.tint.z + 0.5), u32(u.tint.w + 0.5));
|
|
846
|
+
return vec4<f32>(vec3<f32>(v) * s.a, s.a);
|
|
847
|
+
} else if (u.mode < 12.5) {
|
|
848
|
+
// turbulent_displace \\u2014 sample the layer at p + noise vector.
|
|
849
|
+
// p0 = amount px, p1 = scale px, u.tint = (evolution, octaves, seed, 0).
|
|
850
|
+
let sc = max(u.p1, 1e-3);
|
|
851
|
+
let oct = i32(u.tint.y + 0.5);
|
|
852
|
+
let sd = u32(u.tint.z + 0.5);
|
|
853
|
+
let dx = fbm(vec3<f32>(px / sc, u.tint.x), oct, sd) - 0.5;
|
|
854
|
+
let dy = fbm(vec3<f32>(px / sc, u.tint.x), oct, sd + 7919u) - 0.5;
|
|
855
|
+
let duv = vec2<f32>(dx, dy) * 2.0 * u.p0 / u.texSize;
|
|
856
|
+
return textureSampleLevel(tex, samp, clamp(in.uv + duv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
|
|
857
|
+
} else {
|
|
858
|
+
// bloom_bright \\u2014 extract pixels above a soft luma threshold for a
|
|
859
|
+
// whole-frame bloom pass. p0 = threshold, p1 = knee. Straight bright
|
|
860
|
+
// color, alpha 1, so the subsequent blur spreads it cleanly.
|
|
861
|
+
let s = textureSampleLevel(tex, samp, in.uv, 0.0);
|
|
862
|
+
let c = select(vec3<f32>(0.0), s.rgb / s.a, s.a > 0.0);
|
|
863
|
+
let l = dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
|
|
864
|
+
let f = clamp((l - u.p0) / max(u.p1, 1e-3), 0.0, 1.0);
|
|
865
|
+
return vec4<f32>(c * f, 1.0);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
\`,wo=e=>\`
|
|
869
|
+
struct GlassUniforms {
|
|
870
|
+
transform: mat4x4<f32>, // 64 bytes, offset 0
|
|
871
|
+
tint: vec4<f32>, // 16 bytes, offset 64 \\u2014 STRAIGHT rgba
|
|
872
|
+
texSize: vec2<f32>, // 8 bytes, offset 80 \\u2014 surface PHYSICAL dims
|
|
873
|
+
paneCenter: vec2<f32>, // 8 bytes, offset 88 \\u2014 PHYSICAL px
|
|
874
|
+
paneHalf: vec2<f32>, // 8 bytes, offset 96 \\u2014 PHYSICAL px
|
|
875
|
+
rot: vec2<f32>, // 8 bytes, offset 104 \\u2014 (cos \\u03B8, sin \\u03B8)
|
|
876
|
+
geo: vec4<f32>, // 16 bytes, offset 112 \\u2014 (radius, zRadius, bevelMode, bdFlip)
|
|
877
|
+
optics: vec4<f32>, // 16 bytes, offset 128 \\u2014 (refract, chroma, edgeHL, fresnel)
|
|
878
|
+
look: vec4<f32>, // 16 bytes, offset 144 \\u2014 (specular, saturation, alpha, 0)
|
|
879
|
+
shadow: vec4<f32>, // 16 bytes, offset 160 \\u2014 (alpha, spread, offY, 0)\${e?\`
|
|
880
|
+
hcol0: vec4<f32>, // 16 bytes, offset 176 \\u2014 pane\\u2192surface H, column 0 (xyz)
|
|
881
|
+
hcol1: vec4<f32>, // 16 bytes, offset 192
|
|
882
|
+
hcol2: vec4<f32>, // 16 bytes, offset 208
|
|
883
|
+
hicol0: vec4<f32>, // 16 bytes, offset 224 \\u2014 inverse H columns
|
|
884
|
+
hicol1: vec4<f32>, // 16 bytes, offset 240
|
|
885
|
+
hicol2: vec4<f32>, // 16 bytes, offset 256
|
|
886
|
+
} // total: 272\`:\`
|
|
887
|
+
} // total: 176\`}
|
|
888
|
+
@group(0) @binding(0) var<uniform> u: GlassUniforms;
|
|
889
|
+
@group(0) @binding(1) var samp: sampler;
|
|
890
|
+
@group(0) @binding(2) var backdropTex: texture_2d<f32>; // frosted
|
|
891
|
+
@group(0) @binding(3) var sharpTex: texture_2d<f32>; // unblurred
|
|
892
|
+
|
|
893
|
+
struct VsOut {
|
|
894
|
+
@builtin(position) position: vec4<f32>,
|
|
895
|
+
@location(0) uv: vec2<f32>,
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
@vertex
|
|
899
|
+
fn vsMain(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VsOut {
|
|
900
|
+
var out: VsOut;
|
|
901
|
+
out.position = u.transform * vec4<f32>(pos, 0.0, 1.0);
|
|
902
|
+
out.uv = uv;
|
|
903
|
+
return out;
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
fn rrSDF(p: vec2<f32>, b: vec2<f32>, r: f32) -> f32 {
|
|
907
|
+
let q = abs(p) - b + vec2<f32>(r, r);
|
|
908
|
+
return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0, 0.0))) - r;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// Half-circle bevel height field (reference bevelHeight).
|
|
912
|
+
fn bevelHeight(d: f32, zR: f32) -> f32 {
|
|
913
|
+
if (d <= 0.0) { return 0.0; }
|
|
914
|
+
if (d >= zR) { return zR; }
|
|
915
|
+
return sqrt(d * (2.0 * zR - d));
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
fn straight3(s: vec4<f32>) -> vec3<f32> {
|
|
919
|
+
return select(vec3<f32>(0.0), s.rgb / s.a, s.a > 0.0);
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
@fragment
|
|
923
|
+
fn fsMain(in: VsOut) -> @location(0) vec4<f32> {\${e?\`
|
|
924
|
+
// Pane-local coordinates: invert the pane\\u2192surface homography. A
|
|
925
|
+
// non-positive w means the fragment looks past the plane's horizon
|
|
926
|
+
// (behind the camera) \\u2014 nothing there.
|
|
927
|
+
let px = in.uv * u.texSize;
|
|
928
|
+
let Hi = mat3x3<f32>(u.hicol0.xyz, u.hicol1.xyz, u.hicol2.xyz);
|
|
929
|
+
let lh = Hi * vec3<f32>(px, 1.0);
|
|
930
|
+
if (lh.z <= 0.0) { return vec4<f32>(0.0, 0.0, 0.0, 0.0); }
|
|
931
|
+
let p = lh.xy / lh.z;\`:\`
|
|
932
|
+
// Pane-local coordinates (rotate surface px by \\u2212\\u03B8 around the centre).
|
|
933
|
+
let px = in.uv * u.texSize;
|
|
934
|
+
let rel = px - u.paneCenter;
|
|
935
|
+
let p = vec2<f32>(rel.x * u.rot.x + rel.y * u.rot.y,
|
|
936
|
+
-rel.x * u.rot.y + rel.y * u.rot.x);\`}
|
|
937
|
+
let half_ = u.paneHalf;
|
|
938
|
+
let r = min(u.geo.x, min(half_.x, half_.y));
|
|
939
|
+
let sdf = rrSDF(p, half_, r);
|
|
940
|
+
|
|
941
|
+
// \\u2500\\u2500 Drop shadow \\u2014 OUTSIDE the panel only \\u2500\\u2500
|
|
942
|
+
if (sdf > 0.0) {
|
|
943
|
+
var a = 0.0;
|
|
944
|
+
if (u.shadow.x > 0.0) {
|
|
945
|
+
let sdfShadow = rrSDF(p - vec2<f32>(0.0, u.shadow.z), half_, r);
|
|
946
|
+
let d = max(sdfShadow - 1.0, 0.0);
|
|
947
|
+
let spread = max(u.shadow.y, 1.0);
|
|
948
|
+
let falloff = 1.0 / (spread * spread);
|
|
949
|
+
let outerShadow = exp(-d * d * falloff) * 0.65;
|
|
950
|
+
let contactShadow = exp(-d * 0.08 / max(spread * 0.04, 0.01)) * 0.35;
|
|
951
|
+
a = (outerShadow + contactShadow) * u.shadow.x;
|
|
952
|
+
}
|
|
953
|
+
return vec4<f32>(0.0, 0.0, 0.0, a);
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
let mask = 1.0 - smoothstep(-1.5, 0.5, sdf);
|
|
957
|
+
|
|
958
|
+
let maxD = min(half_.x, half_.y);
|
|
959
|
+
let inside = -sdf;
|
|
960
|
+
let edge = smoothstep(maxD * 0.35, 0.0, inside);
|
|
961
|
+
|
|
962
|
+
// \\u2500\\u2500 Surface normal via the bevel height field (e = 2px, analytic) \\u2500\\u2500
|
|
963
|
+
let zR = u.geo.y;
|
|
964
|
+
let e = 2.0;
|
|
965
|
+
let hC = bevelHeight(inside, zR);
|
|
966
|
+
let hGrad = vec2<f32>(
|
|
967
|
+
bevelHeight(-rrSDF(p + vec2<f32>(e, 0.0), half_, r), zR) -
|
|
968
|
+
bevelHeight(-rrSDF(p - vec2<f32>(e, 0.0), half_, r), zR),
|
|
969
|
+
bevelHeight(-rrSDF(p + vec2<f32>(0.0, e), half_, r), zR) -
|
|
970
|
+
bevelHeight(-rrSDF(p - vec2<f32>(0.0, e), half_, r), zR)) / (2.0 * e);
|
|
971
|
+
let N = normalize(vec3<f32>(-hGrad, 1.0));
|
|
972
|
+
|
|
973
|
+
let depth = smoothstep(0.0, zR, inside);
|
|
974
|
+
|
|
975
|
+
// \\u2500\\u2500 Refraction \\u2500\\u2500
|
|
976
|
+
let refrPow = 1.0 - 1.0 / 1.5;
|
|
977
|
+
let thickNorm = (hC * 2.0) / max(zR * 2.0, 1.0);
|
|
978
|
+
var refrPx: vec2<f32>;
|
|
979
|
+
if (u.geo.z < 0.5) {
|
|
980
|
+
// Biconvex pill: entry + exit + through-thickness refraction,
|
|
981
|
+
// plus a depth-scaled magnification pull toward the centre.
|
|
982
|
+
let surfRefr = hGrad * refrPow;
|
|
983
|
+
refrPx = (surfRefr * 2.0 + surfRefr * thickNorm * 0.5) * u.optics.x * 30.0;
|
|
984
|
+
let centerDir = -p / max(half_, vec2<f32>(1.0, 1.0));
|
|
985
|
+
refrPx += centerDir * u.optics.x * 4.0 * depth;
|
|
986
|
+
} else {
|
|
987
|
+
// Dome: uniform magnification \\u2014 contract sampling toward centre.
|
|
988
|
+
refrPx = -p * u.optics.x * depth * 0.35;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// \\u2500\\u2500 Chromatic aberration \\u2500\\u2500
|
|
992
|
+
let caS = u.optics.y * 18.0 * (edge * 0.7 + 0.3) * 2.0;
|
|
993
|
+
let caD = N.xy * caS;
|
|
994
|
+
|
|
995
|
+
\${e?\` // Pane-local sample points \\u2192 surface px via the FORWARD homography
|
|
996
|
+
// (refraction and aberration computed in the pane's frame).
|
|
997
|
+
let Hm = mat3x3<f32>(u.hcol0.xyz, u.hcol1.xyz, u.hcol2.xyz);
|
|
998
|
+
let fR = Hm * vec3<f32>(p + refrPx + caD, 1.0);
|
|
999
|
+
let fG = Hm * vec3<f32>(p + refrPx, 1.0);
|
|
1000
|
+
let fB = Hm * vec3<f32>(p + refrPx - caD, 1.0);
|
|
1001
|
+
var uvR = clamp(fR.xy / (max(fR.z, 1e-4) * u.texSize), vec2<f32>(0.0), vec2<f32>(1.0));
|
|
1002
|
+
var uvG = clamp(fG.xy / (max(fG.z, 1e-4) * u.texSize), vec2<f32>(0.0), vec2<f32>(1.0));
|
|
1003
|
+
var uvB = clamp(fB.xy / (max(fB.z, 1e-4) * u.texSize), vec2<f32>(0.0), vec2<f32>(1.0));\`:\` // Pane-local offsets \\u2192 surface space (rotate by +\\u03B8) \\u2192 uv.
|
|
1004
|
+
let refrW = vec2<f32>(refrPx.x * u.rot.x - refrPx.y * u.rot.y,
|
|
1005
|
+
refrPx.x * u.rot.y + refrPx.y * u.rot.x);
|
|
1006
|
+
let caW = vec2<f32>(caD.x * u.rot.x - caD.y * u.rot.y,
|
|
1007
|
+
caD.x * u.rot.y + caD.y * u.rot.x);
|
|
1008
|
+
let base = in.uv + refrW / u.texSize;
|
|
1009
|
+
let oCA = caW / u.texSize;
|
|
1010
|
+
var uvR = clamp(base + oCA, vec2<f32>(0.0), vec2<f32>(1.0));
|
|
1011
|
+
var uvG = clamp(base, vec2<f32>(0.0), vec2<f32>(1.0));
|
|
1012
|
+
var uvB = clamp(base - oCA, vec2<f32>(0.0), vec2<f32>(1.0));\`}
|
|
1013
|
+
if (u.geo.w > 0.5) { // GL-canvas snapshots are bottom-up
|
|
1014
|
+
uvR.y = 1.0 - uvR.y; uvG.y = 1.0 - uvG.y; uvB.y = 1.0 - uvB.y;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
let sharpC = vec3<f32>(
|
|
1018
|
+
straight3(textureSampleLevel(sharpTex, samp, uvR, 0.0)).r,
|
|
1019
|
+
straight3(textureSampleLevel(sharpTex, samp, uvG, 0.0)).g,
|
|
1020
|
+
straight3(textureSampleLevel(sharpTex, samp, uvB, 0.0)).b);
|
|
1021
|
+
let blurC = vec3<f32>(
|
|
1022
|
+
straight3(textureSampleLevel(backdropTex, samp, uvR, 0.0)).r,
|
|
1023
|
+
straight3(textureSampleLevel(backdropTex, samp, uvG, 0.0)).g,
|
|
1024
|
+
straight3(textureSampleLevel(backdropTex, samp, uvB, 0.0)).b);
|
|
1025
|
+
// Edge-weighted blur mix: centre fully frosted, rim 15% sharp.
|
|
1026
|
+
let edgeMix = 1.0 - edge * 0.15;
|
|
1027
|
+
var col = mix(sharpC, blurC, edgeMix);
|
|
1028
|
+
|
|
1029
|
+
// \\u2500\\u2500 Saturation (0 = unchanged) \\u2500\\u2500
|
|
1030
|
+
let lum = dot(col, vec3<f32>(0.299, 0.587, 0.114));
|
|
1031
|
+
col = mix(vec3<f32>(lum), col, 1.0 + u.look.y);
|
|
1032
|
+
|
|
1033
|
+
// \\u2500\\u2500 Tint \\u2500\\u2500
|
|
1034
|
+
col = mix(col, u.tint.rgb, u.tint.a);
|
|
1035
|
+
col *= 1.0 + 0.06 * depth;
|
|
1036
|
+
|
|
1037
|
+
// \\u2500\\u2500 Fresnel \\u2500\\u2500
|
|
1038
|
+
let fres = pow(1.0 - abs(N.z), 4.0) * u.optics.w;
|
|
1039
|
+
|
|
1040
|
+
// \\u2500\\u2500 Specular highlights (multi-light Blinn-Phong, reference lights) \\u2500\\u2500
|
|
1041
|
+
let V = vec3<f32>(0.0, 0.0, 1.0);
|
|
1042
|
+
let L1 = normalize(vec3<f32>(0.4, 0.7, 1.0));
|
|
1043
|
+
var sp = pow(max(dot(N, normalize(L1 + V)), 0.0), 90.0);
|
|
1044
|
+
let L2 = normalize(vec3<f32>(-0.3, -0.5, 1.0));
|
|
1045
|
+
sp += pow(max(dot(N, normalize(L2 + V)), 0.0), 50.0) * 0.3;
|
|
1046
|
+
let L3 = normalize(vec3<f32>(0.1, 0.3, 1.0));
|
|
1047
|
+
sp += pow(max(dot(N, L3), 0.0), 6.0) * 0.1;
|
|
1048
|
+
let L4 = normalize(vec3<f32>(0.0, 0.9, 0.4));
|
|
1049
|
+
sp += pow(max(dot(N, normalize(L4 + V)), 0.0), 120.0) * 0.6;
|
|
1050
|
+
let totalSpec = sp * u.look.x;
|
|
1051
|
+
|
|
1052
|
+
// \\u2500\\u2500 Inner border / stroke highlight \\u2500\\u2500
|
|
1053
|
+
let borderWidth = 1.5;
|
|
1054
|
+
var innerStroke = smoothstep(-borderWidth - 1.0, -borderWidth, sdf)
|
|
1055
|
+
* (1.0 - smoothstep(-1.0, 0.0, sdf));
|
|
1056
|
+
let topBias = 0.5 + 0.5 * (-p.y / half_.y);
|
|
1057
|
+
innerStroke *= (0.4 + 0.6 * topBias);
|
|
1058
|
+
|
|
1059
|
+
// \\u2500\\u2500 Edge highlight & inner glow \\u2500\\u2500
|
|
1060
|
+
let rim = edge * u.optics.z * 0.22;
|
|
1061
|
+
let innerGlow = smoothstep(5.0, 0.0, -sdf) * u.optics.z * 0.15;
|
|
1062
|
+
|
|
1063
|
+
// \\u2500\\u2500 Environment-like reflection (fake) \\u2500\\u2500
|
|
1064
|
+
let envRefl = (N.y * 0.5 + 0.5) * fres * 0.08;
|
|
1065
|
+
|
|
1066
|
+
// \\u2500\\u2500 Composite \\u2500\\u2500
|
|
1067
|
+
var fin = col;
|
|
1068
|
+
fin += vec3<f32>(totalSpec);
|
|
1069
|
+
fin += vec3<f32>(rim + innerGlow);
|
|
1070
|
+
fin += vec3<f32>(innerStroke * u.optics.z * 0.55);
|
|
1071
|
+
fin += vec3<f32>(envRefl);
|
|
1072
|
+
fin = mix(fin, vec3<f32>(1.0), fres * 0.2);
|
|
1073
|
+
|
|
1074
|
+
let outA = mask * u.look.z;
|
|
1075
|
+
return vec4<f32>(clamp(fin, vec3<f32>(0.0), vec3<f32>(1.0)), 1.0) * outA;
|
|
1076
|
+
}
|
|
1077
|
+
\`,So=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]),nu=16,Wr=class e{canvas;width;height;capabilities;device;context;format;sampler;vertexBuffer;shapePipeline;litShapePipeline;litShapeBindGroupLayout;litTexturedPipeline;litTexturedBindGroupLayout;flatNormalView=null;shadowPipeline;gradientPipeline;texturedPipeline;maskedPipeline;filteredPipeline;stylizedPipeline;glassPipeline;backdropBlendPipeline;glass3dPipeline=null;blendVariants=new Map;shapeBindGroupLayout;shadowBindGroupLayout;gradientBindGroupLayout;texturedBindGroupLayout;maskedBindGroupLayout;commandEncoder=null;passEncoder=null;canvasView=null;canvasTexture=null;pixelRatio=1;surfaceStack=[];renderTargets=new Set;currentSurface(){let t=this.surfaceStack[this.surfaceStack.length-1];return t||{view:this.canvasView,width:this.width,height:this.height}}uniformBufferPool=[];uniformBufferIndex=0;uniformScratch=new Float32Array(136);static UNIFORM_SIZE=544;nextTextureId=1;videoDirectCopyBroken=!1;videoBlitCanvas=null;liveTextures=new Set;disposed=!1;constructor(t){this.canvas=t,this.width=t.width,this.height=t.height}async init(){let t=$();if(typeof navigator>"u"||!("gpu"in navigator)||!navigator.gpu)return t.warn("WebGPU not available in this environment"),!1;try{let i=await navigator.gpu.requestAdapter();if(!i)return t.warn("No WebGPU adapter available"),!1;this.device=await i.requestDevice(),this.device.addEventListener("uncapturederror",r=>{t.error("WebGPU uncaptured error:",r.error.message)}),this.device.lost.then(r=>{t.error("WebGPU device lost:",r.message,r.reason)});let s=this.canvas.getContext("webgpu");return s?(this.context=s,this.format=navigator.gpu.getPreferredCanvasFormat(),this.context.configure({device:this.device,format:this.format,alphaMode:"premultiplied",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.sampler=this.device.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.vertexBuffer=this.device.createBuffer({size:So.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.device.queue.writeBuffer(this.vertexBuffer,0,So),await this.buildShapePipeline(),await this.buildShadowPipeline(),await this.buildGradientPipeline(),await this.buildTexturedPipeline(),this.capabilities={api:"webgpu",maxTextureSize:this.device.limits.maxTextureDimension2D},t.info(\`WebGPU backend ready (maxTextureSize=\${this.capabilities.maxTextureSize})\`),!0):(t.error("Failed to get WebGPU canvas context"),!1)}catch(i){return t.error("WebGPU init failed:",i instanceof Error?i.message:String(i)),!1}}resize(t,i,s=1){if(this.disposed)return;let r=Math.max(1,Math.round(t*s)),n=Math.max(1,Math.round(i*s));t===this.width&&i===this.height&&this.canvas.width===r&&this.canvas.height===n||(this.width=t,this.height=i,this.pixelRatio=s,this.canvas.width=r,this.canvas.height=n,this.context.configure({device:this.device,format:this.format,alphaMode:"premultiplied",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}))}makePipeline(t,i,s,r){return this.device.createRenderPipeline({label:t,layout:this.device.createPipelineLayout({bindGroupLayouts:[s]}),vertex:{module:i,entryPoint:"vsMain",buffers:[{arrayStride:nu,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"}]}]},fragment:{module:i,entryPoint:"fsMain",targets:[{format:this.format,blend:r}]},primitive:{topology:"triangle-list"}})}makeBlendablePipeline(t,i,s){for(let r of["multiply","screen","add"])this.blendVariants.set(\`\${t}:\${r}\`,this.makePipeline(\`\${t} pipeline (\${r})\`,i,s,ou[r]));return this.makePipeline(\`\${t} pipeline\`,i,s,ko)}pipelineFor(t,i,s){return!s||s==="normal"?t:this.blendVariants.get(\`\${i}:\${s}\`)??t}async buildShapePipeline(){let t=this.device.createShaderModule({code:Zd,label:"shape"});await this.checkShaderCompilation(t,"shape"),this.shapeBindGroupLayout=this.device.createBindGroupLayout({label:"shape bgl",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.shapePipeline=this.makeBlendablePipeline("shape",t,this.shapeBindGroupLayout);let i=this.device.createShaderModule({code:Qd,label:"litShape"});await this.checkShaderCompilation(i,"litShape"),this.litShapeBindGroupLayout=this.device.createBindGroupLayout({label:"litShape bgl",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.litShapePipeline=this.makeBlendablePipeline("litShape",i,this.litShapeBindGroupLayout)}async buildShadowPipeline(){let t=this.device.createShaderModule({code:Xd,label:"shadow"});await this.checkShaderCompilation(t,"shadow"),this.shadowBindGroupLayout=this.device.createBindGroupLayout({label:"shadow bgl",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.shadowPipeline=this.makePipeline("shadow pipeline",t,this.shadowBindGroupLayout,ko)}async buildGradientPipeline(){let t=this.device.createShaderModule({code:Jd,label:"gradient"});await this.checkShaderCompilation(t,"gradient"),this.gradientBindGroupLayout=this.device.createBindGroupLayout({label:"gradient bgl",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.gradientPipeline=this.makeBlendablePipeline("gradient",t,this.gradientBindGroupLayout)}async buildTexturedPipeline(){let t=this.device.createShaderModule({code:eu,label:"textured"});await this.checkShaderCompilation(t,"textured"),this.texturedBindGroupLayout=this.device.createBindGroupLayout({label:"textured bgl",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.texturedPipeline=this.makeBlendablePipeline("textured",t,this.texturedBindGroupLayout);let i=this.device.createShaderModule({code:Kd,label:"litTextured"});await this.checkShaderCompilation(i,"litTextured"),this.litTexturedBindGroupLayout=this.device.createBindGroupLayout({label:"litTextured bgl",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.litTexturedPipeline=this.makeBlendablePipeline("litTextured",i,this.litTexturedBindGroupLayout);let s=this.device.createShaderModule({code:tu,label:"masked"});await this.checkShaderCompilation(s,"masked"),this.maskedBindGroupLayout=this.device.createBindGroupLayout({label:"masked bgl",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.maskedPipeline=this.makeBlendablePipeline("masked",s,this.maskedBindGroupLayout);let r=this.device.createShaderModule({code:su,label:"filtered"});await this.checkShaderCompilation(r,"filtered"),this.filteredPipeline=this.makeBlendablePipeline("filtered",r,this.texturedBindGroupLayout);let n=this.device.createShaderModule({code:ru,label:"stylized"});await this.checkShaderCompilation(n,"stylized"),this.stylizedPipeline=this.makeBlendablePipeline("stylized",n,this.maskedBindGroupLayout);let a=this.device.createShaderModule({code:wo(!1),label:"glass"});await this.checkShaderCompilation(a,"glass"),this.glassPipeline=this.makeBlendablePipeline("glass",a,this.maskedBindGroupLayout);let o=this.device.createShaderModule({code:iu,label:"backdropBlend"});await this.checkShaderCompilation(o,"backdropBlend"),this.backdropBlendPipeline=this.makePipeline("backdropBlend",o,this.maskedBindGroupLayout,au)}async checkShaderCompilation(t,i){let s=await t.getCompilationInfo(),r=$();for(let n of s.messages){let a=\`\${i}.wgsl:\${n.lineNum}:\${n.linePos}\`;n.type==="error"?r.error(\`Shader \${a}: \${n.message}\`):n.type==="warning"&&r.warn(\`Shader \${a}: \${n.message}\`)}}createTexture(t){let{width:i,height:s}=cu(t),r=this.device.createTexture({size:{width:i,height:s,depthOrArrayLayers:1},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});this.uploadToTexture(r,t,i,s);let n={id:this.nextTextureId++,width:i,height:s,gpuTexture:r,view:r.createView()};return this.liveTextures.add(n),n}updateTexture(t,i){let s=t;this.uploadToTexture(s.gpuTexture,i,s.width,s.height)}uploadToTexture(t,i,s,r){if(typeof VideoFrame<"u"&&i instanceof VideoFrame){if(!this.videoDirectCopyBroken)try{this.device.queue.copyExternalImageToTexture({source:i},{texture:t,premultipliedAlpha:!0},{width:s,height:r});return}catch{this.videoDirectCopyBroken=!0,$().warn("Direct VideoFrame\\u2192GPUTexture copy unavailable; using canvas blit.")}let n=this.videoBlitCanvas;n||(n=new OffscreenCanvas(s,r),this.videoBlitCanvas=n),(n.width!==s||n.height!==r)&&(n.width=s,n.height=r),n.getContext("2d").drawImage(i,0,0,s,r),this.device.queue.copyExternalImageToTexture({source:n},{texture:t,premultipliedAlpha:!0},{width:s,height:r});return}this.device.queue.copyExternalImageToTexture({source:i},{texture:t,premultipliedAlpha:!0},{width:s,height:r})}destroyTexture(t){let i=t;this.liveTextures.delete(i)&&i.gpuTexture.destroy()}beginFrame(t=[0,0,0,1]){this.passEncoder&&($().warn("beginFrame called while another frame is in progress; ending the previous one"),this.endFrame()),this.commandEncoder=this.device.createCommandEncoder({label:"frame"}),this.canvasTexture=this.context.getCurrentTexture(),this.canvasView=this.canvasTexture.createView(),this.surfaceStack.length=0,this.passEncoder=this.commandEncoder.beginRenderPass({label:"main pass",colorAttachments:[{view:this.canvasView,loadOp:"clear",storeOp:"store",clearValue:{r:t[0],g:t[1],b:t[2],a:t[3]}}]}),this.passEncoder.setVertexBuffer(0,this.vertexBuffer),this.uniformBufferIndex=0}restartPass(t,i,s=[0,0,0,0]){this.commandEncoder&&(this.passEncoder?.end(),this.passEncoder=this.commandEncoder.beginRenderPass({label:i==="clear"?"target pass":"resume pass",colorAttachments:[{view:t,loadOp:i,storeOp:"store",clearValue:{r:s[0],g:s[1],b:s[2],a:s[3]}}]}),this.passEncoder.setVertexBuffer(0,this.vertexBuffer))}createRenderTarget(t,i){let s=Math.max(1,Math.round(t*this.pixelRatio)),r=Math.max(1,Math.round(i*this.pixelRatio)),n=this.device.createTexture({label:"render target",size:{width:s,height:r},format:this.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST}),a={id:this.nextTextureId++,width:s,height:r,gpuTexture:n,view:n.createView()};this.liveTextures.add(a);let o={texture:a,width:t,height:i};return this.renderTargets.add(o),o}destroyRenderTarget(t){this.renderTargets.delete(t),this.destroyTexture(t.texture)}pushTarget(t,i=[0,0,0,0]){if(!this.passEncoder)return;if(!this.renderTargets.has(t)){$().warn("pushTarget with unknown / destroyed target \\u2014 ignored");return}let s=t.texture;this.surfaceStack.push({view:s.view,texture:s.gpuTexture,width:t.width,height:t.height}),this.restartPass(s.view,"clear",i)}popTarget(){if(this.surfaceStack.length===0){$().warn("popTarget without matching pushTarget \\u2014 ignored");return}this.surfaceStack.pop();let t=this.currentSurface();t.view&&this.restartPass(t.view,"load")}acquireUniformBuffer(){let t=this.uniformBufferPool[this.uniformBufferIndex];return t||(t=this.device.createBuffer({label:\`pooled uniform [\${this.uniformBufferIndex}]\`,size:e.UNIFORM_SIZE,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.uniformBufferPool.push(t)),this.uniformBufferIndex++,t}endFrame(){!this.passEncoder||!this.commandEncoder||(this.passEncoder.end(),this.device.queue.submit([this.commandEncoder.finish()]),this.passEncoder=null,this.commandEncoder=null)}drawShapeShadow(t){if(!this.passEncoder||t.blur<=0&&t.offsetX===0&&t.offsetY===0)return;let i=Math.max(0,t.blur),s=t.width+i*2,r=t.height+i*2,n=this.currentSurface(),a=t.transform?St(t.transform,n.width,n.height,!1):je(t.cx+t.offsetX,t.cy+t.offsetY,s,r,t.rotation,n.width,n.height,t.skewX??0,t.skewY??0),o=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),c=t.shape==="ellipse"?1:0,l=this.uniformScratch;l.set(a,0),l.set(t.color,16),l[20]=o,l[21]=c,l[22]=i,l[23]=0,l[24]=t.width,l[25]=t.height,l[26]=s,l[27]=r,l[28]=0,l[29]=0,l[30]=0,l[31]=0;let u=this.acquireUniformBuffer();this.device.queue.writeBuffer(u,0,l.buffer,l.byteOffset,128);let h=this.device.createBindGroup({layout:this.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:u}}]});this.passEncoder.setPipeline(this.shadowPipeline),this.passEncoder.setBindGroup(0,h),this.passEncoder.draw(6,1,0,0)}drawShape(t){if(!this.passEncoder)return;if(t.gradient){this.drawGradientShape(t);return}if(t.lit){this.drawLitShape(t);return}let i=this.currentSurface(),s=t.transform?St(t.transform,i.width,i.height,!1):je(t.cx,t.cy,t.width,t.height,t.rotation,i.width,i.height,t.skewX??0,t.skewY??0),r=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),n=t.shape==="ellipse"?1:0,a=t.strokeWidth??0,o=t.strokeColor??t.color,c=this.uniformScratch;c.set(s,0),c.set(t.color,16),c.set(o,20),c[24]=r,c[25]=n,c[26]=t.width,c[27]=t.height,c[28]=a,c[29]=0;let l=this.acquireUniformBuffer();this.device.queue.writeBuffer(l,0,c.buffer,c.byteOffset,128);let u=this.device.createBindGroup({layout:this.shapeBindGroupLayout,entries:[{binding:0,resource:{buffer:l}}]});this.passEncoder.setPipeline(this.pipelineFor(this.shapePipeline,"shape",t.blend)),this.passEncoder.setBindGroup(0,u),this.passEncoder.draw(6,1,0,0)}drawLitShape(t){if(!this.passEncoder||!t.lit)return;let i=t.lit,s=this.currentSurface(),r=t.transform?St(t.transform,s.width,s.height,!1):je(t.cx,t.cy,t.width,t.height,t.rotation,s.width,s.height,t.skewX??0,t.skewY??0),n=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),a=t.shape==="ellipse"?1:0,o=t.strokeWidth??0,c=i.strokeAlbedo??i.albedo,l=this.uniformScratch;l.set(r,0),l.set(i.albedo,32),l.set(c,36),l[52]=n,l[53]=a,l[54]=o,l[60]=t.width,l[61]=t.height,l[62]=0,l[63]=0,this.packLitPbr(l,i);let u=this.acquireUniformBuffer();this.device.queue.writeBuffer(u,0,l.buffer,l.byteOffset,528);let h=i.normalMap?i.normalMap.texture.view:this.getFlatNormalView(),f=i.env?.image?i.env.image.view:this.getFlatNormalView(),p=this.device.createBindGroup({layout:this.litShapeBindGroupLayout,entries:[{binding:0,resource:{buffer:u}},{binding:1,resource:this.sampler},{binding:2,resource:h},{binding:3,resource:f}]});this.passEncoder.setPipeline(this.pipelineFor(this.litShapePipeline,"litShape",t.blend)),this.passEncoder.setBindGroup(0,p),this.passEncoder.draw(6,1,0,0)}packLitPbr(t,i){t.set(i.worldMatrix,16),t[40]=i.normal[0],t[41]=i.normal[1],t[42]=i.normal[2],t[43]=0,t[44]=i.eye[0],t[45]=i.eye[1],t[46]=i.eye[2],t[47]=0,t[48]=i.ambient[0],t[49]=i.ambient[1],t[50]=i.ambient[2],t[51]=0,t[55]=Math.min(4,i.lightDirs.length),t[56]=i.roughness,t[57]=i.metalness,t[58]=i.reflectivity,t[59]=i.emissive;for(let o=0;o<4;o++){let c=i.lightDirs[o],l=64+o*4;t[l]=c?c[0]:0,t[l+1]=c?c[1]:0,t[l+2]=c?c[2]:0,t[l+3]=0}for(let o=0;o<4;o++){let c=i.lightColors[o],l=80+o*4;t[l]=c?c[0]:0,t[l+1]=c?c[1]:0,t[l+2]=c?c[2]:0,t[l+3]=0}let s=i.env,r=s?Math.min(4,s.stopColors.length):0;for(let o=0;o<4;o++){let c=s&&o<r?s.stopColors[o]:void 0,l=96+o*4;t[l]=c?c[0]:0,t[l+1]=c?c[1]:0,t[l+2]=c?c[2]:0,t[l+3]=0}let n=i.normalMap,a=i.env?.image?1:0;t[112]=r,t[113]=n?n.scale:1,t[114]=n?1:0,t[115]=a;for(let o=0;o<4;o++)t[116+o]=s&&o<r?s.stopOffsets[o]:0;t[120]=s?s.avg[0]:0,t[121]=s?s.avg[1]:0,t[122]=s?s.avg[2]:0,t[123]=0,t[124]=n?n.tangent[0]:1,t[125]=n?n.tangent[1]:0,t[126]=n?n.tangent[2]:0,t[127]=0,t[128]=n?n.bitangent[0]:0,t[129]=n?n.bitangent[1]:1,t[130]=n?n.bitangent[2]:0,t[131]=0}getFlatNormalView(){if(!this.flatNormalView){let t=this.device.createTexture({size:{width:1,height:1},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:t},new Uint8Array([128,128,255,255]),{bytesPerRow:4,rowsPerImage:1},{width:1,height:1}),this.flatNormalView=t.createView()}return this.flatNormalView}drawLitTexturedQuad(t){if(!this.passEncoder||!t.lit)return;let i=t.lit,s=this.currentSurface(),r=t.transform?St(t.transform,s.width,s.height,!1):je(t.cx,t.cy,t.width,t.height,t.rotation,s.width,s.height,t.skewX??0,t.skewY??0),n=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),a=t.uvRect??[0,0,1,1],o=t.tint??[1,1,1,1],c=this.uniformScratch;c.set(r,0),c[32]=o[0],c[33]=o[1],c[34]=o[2],c[35]=o[3],c[36]=a[0],c[37]=a[1],c[38]=a[2],c[39]=a[3],c[52]=n,c[53]=0,c[54]=0,c[60]=t.width,c[61]=t.height,c[62]=0,c[63]=0,this.packLitPbr(c,i);let l=this.acquireUniformBuffer();this.device.queue.writeBuffer(l,0,c.buffer,c.byteOffset,528);let u=t.texture,h=i.normalMap?i.normalMap.texture.view:this.getFlatNormalView(),f=i.env?.image?i.env.image.view:this.getFlatNormalView(),p=this.device.createBindGroup({layout:this.litTexturedBindGroupLayout,entries:[{binding:0,resource:{buffer:l}},{binding:1,resource:this.sampler},{binding:2,resource:u.view},{binding:3,resource:h},{binding:4,resource:f}]});this.passEncoder.setPipeline(this.pipelineFor(this.litTexturedPipeline,"litTextured",t.blend)),this.passEncoder.setBindGroup(0,p),this.passEncoder.draw(6,1,0,0)}drawGradientShape(t){if(!this.passEncoder||!t.gradient)return;let i=this.currentSurface(),s=t.transform?St(t.transform,i.width,i.height,!1):je(t.cx,t.cy,t.width,t.height,t.rotation,i.width,i.height,t.skewX??0,t.skewY??0),r=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),n=t.shape==="ellipse"?1:0,a=t.gradient,o=a.type==="radial"?1:0,c=a.stops.slice(0,4),l=Math.max(2,c.length),u=this.uniformScratch;u.set(s,0),u[16]=r,u[17]=n,u[18]=o,u[19]=l,a.type==="linear"?(u[20]=Math.cos(a.angle),u[21]=Math.sin(a.angle),u[22]=0,u[23]=0):(u[20]=a.cx,u[21]=a.cy,u[22]=a.radius,u[23]=0),u[24]=t.width,u[25]=t.height,u[26]=0,u[27]=0;for(let p=0;p<4;p++){let m=c[p]??c[c.length-1],g=28+p*4;u[g]=m.color[0],u[g+1]=m.color[1],u[g+2]=m.color[2],u[g+3]=m.color[3]}for(let p=0;p<4;p++){let m=c[p];u[44+p]=m?m.offset:1}let h=this.acquireUniformBuffer();this.device.queue.writeBuffer(h,0,u.buffer,u.byteOffset,192);let f=this.device.createBindGroup({layout:this.gradientBindGroupLayout,entries:[{binding:0,resource:{buffer:h}}]});this.passEncoder.setPipeline(this.pipelineFor(this.gradientPipeline,"gradient",t.blend)),this.passEncoder.setBindGroup(0,f),this.passEncoder.draw(6,1,0,0)}drawTexturedQuad(t){if(!this.passEncoder)return;if(t.lit){this.drawLitTexturedQuad(t);return}let i=this.currentSurface(),s=t.transform?St(t.transform,i.width,i.height,!1):je(t.cx,t.cy,t.width,t.height,t.rotation,i.width,i.height,t.skewX??0,t.skewY??0),r=t.uvRect??[0,0,1,1],n=t.tint??[1,1,1,1],a=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),o=this.uniformScratch;o.set(s,0),o.set(r,16),o.set(n,20),o[24]=a,o[25]=t.alphaGamma??1,o[26]=t.width,o[27]=t.height,o[28]=0,o[29]=0,o[30]=0,o[31]=0;let c=this.acquireUniformBuffer();this.device.queue.writeBuffer(c,0,o.buffer,o.byteOffset,128);let l=t.texture,u=this.device.createBindGroup({layout:this.texturedBindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:this.sampler},{binding:2,resource:l.view}]});this.passEncoder.setPipeline(this.pipelineFor(this.texturedPipeline,"textured",t.blend)),this.passEncoder.setBindGroup(0,u),this.passEncoder.draw(6,1,0,0)}drawMaskedQuad(t){if(!this.passEncoder)return;let i=this.currentSurface(),s=t.transform?St(t.transform,i.width,i.height,!1):je(t.cx,t.cy,t.width,t.height,t.rotation,i.width,i.height),r=t.tint??[1,1,1,1],n=t.mode==="alpha"?0:t.mode==="alpha-inverted"?1:t.mode==="luma"?2:3,a=this.uniformScratch;a.set(s,0),a.set(r,16),a[20]=n,a[21]=0,a[22]=0,a[23]=0;let o=this.acquireUniformBuffer();this.device.queue.writeBuffer(o,0,a.buffer,a.byteOffset,96);let c=t.content,l=t.mask,u=this.device.createBindGroup({layout:this.maskedBindGroupLayout,entries:[{binding:0,resource:{buffer:o}},{binding:1,resource:this.sampler},{binding:2,resource:c.view},{binding:3,resource:l.view}]});this.passEncoder.setPipeline(this.pipelineFor(this.maskedPipeline,"masked",t.blend)),this.passEncoder.setBindGroup(0,u),this.passEncoder.draw(6,1,0,0)}drawBackdropBlend(t){if(!this.passEncoder)return;let i=this.currentSurface(),s=je(t.width/2,t.height/2,t.width,t.height,0,i.width,i.height),r=t.mode==="overlay"?0:t.mode==="hard-light"?1:2,n=this.uniformScratch;n.set(s,0),n[16]=r,n[17]=t.backdropFlipY?1:0,n[18]=0,n[19]=0;let a=this.acquireUniformBuffer();this.device.queue.writeBuffer(a,0,n.buffer,n.byteOffset,80);let o=t.src,c=t.backdrop,l=this.device.createBindGroup({layout:this.maskedBindGroupLayout,entries:[{binding:0,resource:{buffer:a}},{binding:1,resource:this.sampler},{binding:2,resource:o.view},{binding:3,resource:c.view}]});this.passEncoder.setPipeline(this.backdropBlendPipeline),this.passEncoder.setBindGroup(0,l),this.passEncoder.draw(6,1,0,0)}drawFilteredQuad(t){if(!this.passEncoder)return;let i=this.currentSurface(),s=je(t.cx,t.cy,t.width,t.height,0,i.width,i.height),r=t.tint??[1,1,1,1],n=t.texture,a=t.blurRadius*this.pixelRatio,o=this.uniformScratch;o.set(s,0),o.set(r,16),o[20]=t.blurDir[0]/n.width,o[21]=t.blurDir[1]/n.height,o[22]=a,o[23]=0,o[24]=t.brightness,o[25]=t.contrast,o[26]=t.saturation,o[27]=(t.hueRotate??0)*Math.PI/180,o[28]=0,o[29]=0,o[30]=0,o[31]=0;let c=this.acquireUniformBuffer();this.device.queue.writeBuffer(c,0,o.buffer,o.byteOffset,128);let l=this.device.createBindGroup({layout:this.texturedBindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:this.sampler},{binding:2,resource:n.view}]});this.passEncoder.setPipeline(this.pipelineFor(this.filteredPipeline,"filtered",t.blend)),this.passEncoder.setBindGroup(0,l),this.passEncoder.draw(6,1,0,0)}drawStylizedQuad(t){if(!this.passEncoder)return;let i=this.currentSurface(),s=je(t.cx,t.cy,t.width,t.height,0,i.width,i.height),r=t.tint??[1,1,1,1],n=t.texture,a=t.aux??t.texture,o=t.mode!=="dither"&&t.mode!=="glow"&&t.mode!=="chroma_key"&&t.mode!=="luma_key"&&t.mode!=="levels"&&t.mode!=="lut",c=t.mode==="drop_shadow"||t.mode==="turbulent_displace",l=o?t.p0*this.pixelRatio:t.p0,u=c?(t.p1??0)*this.pixelRatio:t.p1??0,h=Vr[t.mode],f=this.uniformScratch;f.set(s,0),f.set(r,16),f[20]=n.width,f[21]=n.height,f[22]=h,f[23]=l,f[24]=u,f[25]=this.pixelRatio,f[26]=0,f[27]=0;let p=this.acquireUniformBuffer();this.device.queue.writeBuffer(p,0,f.buffer,f.byteOffset,112);let m=this.device.createBindGroup({layout:this.maskedBindGroupLayout,entries:[{binding:0,resource:{buffer:p}},{binding:1,resource:this.sampler},{binding:2,resource:n.view},{binding:3,resource:a.view}]});this.passEncoder.setPipeline(this.pipelineFor(this.stylizedPipeline,"stylized",t.blend)),this.passEncoder.setBindGroup(0,m),this.passEncoder.draw(6,1,0,0)}drawGlassQuad(t){if(!this.passEncoder)return;let i=this.currentSurface(),s=je(t.cx,t.cy,t.width,t.height,0,i.width,i.height),r=t.backdrop,n=t.backdropSharp,a=this.pixelRatio,o=t.rotation*Math.PI/180,c=this.uniformScratch;c.set(s,0),c.set(t.tint,16),c[20]=i.width*a,c[21]=i.height*a,c[22]=t.paneCx*a,c[23]=t.paneCy*a,c[24]=t.paneHalfW*a,c[25]=t.paneHalfH*a,c[26]=Math.cos(o),c[27]=Math.sin(o),c[28]=t.cornerRadius*a,c[29]=t.zRadius*a,c[30]=t.bevelMode,c[31]=t.backdropFlipY?1:0,c[32]=t.refract,c[33]=t.chroma,c[34]=t.edgeHighlight,c[35]=t.fresnel,c[36]=t.specular,c[37]=t.saturation,c[38]=t.alpha,c[39]=0,c[40]=t.shadowAlpha,c[41]=t.shadowSpread*a,c[42]=t.shadowOffY*a,c[43]=0;let l=!1;if(t.paneHomography){let f=Hr(t.paneHomography,a),p=Gr(f);if(!p)return;l=!0;for(let m=0;m<3;m++)c[44+m*4]=f[m*3],c[45+m*4]=f[m*3+1],c[46+m*4]=f[m*3+2],c[47+m*4]=0,c[56+m*4]=p[m*3],c[57+m*4]=p[m*3+1],c[58+m*4]=p[m*3+2],c[59+m*4]=0;if(!this.glass3dPipeline){let m=this.device.createShaderModule({code:wo(!0),label:"glass3d"});this.glass3dPipeline=this.makeBlendablePipeline("glass3d",m,this.maskedBindGroupLayout)}}let u=this.acquireUniformBuffer();this.device.queue.writeBuffer(u,0,c.buffer,c.byteOffset,l?272:176);let h=this.device.createBindGroup({layout:this.maskedBindGroupLayout,entries:[{binding:0,resource:{buffer:u}},{binding:1,resource:this.sampler},{binding:2,resource:r.view},{binding:3,resource:n.view}]});this.passEncoder.setPipeline(l?this.pipelineFor(this.glass3dPipeline,"glass3d",t.blend):this.pipelineFor(this.glassPipeline,"glass",t.blend)),this.passEncoder.setBindGroup(0,h),this.passEncoder.draw(6,1,0,0)}copySurfaceTo(t){if(!this.commandEncoder)return{flippedY:!1};if(!this.renderTargets.has(t))return $().warn("copySurfaceTo with unknown / destroyed target \\u2014 ignored"),{flippedY:!1};let i=this.surfaceStack[this.surfaceStack.length-1],s=i?i.texture:this.canvasTexture,r=i?i.view:this.canvasView;if(!s||!r)return{flippedY:!1};let n=t.texture;return this.passEncoder?.end(),this.passEncoder=null,this.commandEncoder.copyTextureToTexture({texture:s},{texture:n.gpuTexture},{width:Math.min(s.width,n.gpuTexture.width),height:Math.min(s.height,n.gpuTexture.height)}),this.restartPass(r,"load"),{flippedY:!1}}async finish(){await this.device.queue.onSubmittedWorkDone()}dispose(){if(!this.disposed){this.disposed=!0,this.passEncoder&&(this.passEncoder.end(),this.passEncoder=null),this.commandEncoder=null;for(let t of this.liveTextures)t.gpuTexture.destroy();this.liveTextures.clear();for(let t of this.uniformBufferPool)t.destroy();this.uniformBufferPool.length=0,this.vertexBuffer&&this.vertexBuffer.destroy()}}},ko={color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},au={color:{srcFactor:"one",dstFactor:"zero",operation:"add"},alpha:{srcFactor:"one",dstFactor:"zero",operation:"add"}},ta={srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},ou={add:{color:{srcFactor:"one",dstFactor:"one",operation:"add"},alpha:ta},multiply:{color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:ta},screen:{color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"},alpha:ta}};function cu(e){return"codedWidth"in e&&"codedHeight"in e?{width:e.codedWidth,height:e.codedHeight}:"videoWidth"in e&&"videoHeight"in e?{width:e.videoWidth,height:e.videoHeight}:"naturalWidth"in e&&"naturalHeight"in e?{width:e.naturalWidth,height:e.naturalHeight}:{width:e.width,height:e.height}}var Bo=\`#version 300 es
|
|
1078
|
+
in vec2 a_pos;
|
|
1079
|
+
in vec2 a_uv;
|
|
1080
|
+
out vec2 v_uv;
|
|
1081
|
+
uniform mat4 u_transform;
|
|
1082
|
+
void main() {
|
|
1083
|
+
gl_Position = u_transform * vec4(a_pos, 0.0, 1.0);
|
|
1084
|
+
v_uv = a_uv;
|
|
1085
|
+
}
|
|
1086
|
+
\`,lu=\`#version 300 es
|
|
1087
|
+
precision highp float;
|
|
1088
|
+
in vec2 v_uv;
|
|
1089
|
+
out vec4 fragColor;
|
|
1090
|
+
uniform vec4 u_color; // shadow color, premultiplied
|
|
1091
|
+
uniform float u_blur; // PIXELS; falloff distance past edge
|
|
1092
|
+
uniform float u_cornerRadius; // PIXELS, of the SHAPE (not quad)
|
|
1093
|
+
uniform float u_shapeType; // 0.0 rect, 1.0 ellipse
|
|
1094
|
+
uniform vec2 u_size; // pixel (width, height) of the SHAPE
|
|
1095
|
+
uniform vec2 u_quadSize; // pixel (width, height) of the rendered quad
|
|
1096
|
+
void main() {
|
|
1097
|
+
// Pixel position in quad-local space. The shape sits centered, with
|
|
1098
|
+
// blur-sized margins on every side, so subtracting half the quad's
|
|
1099
|
+
// size and adding half the shape's size positions us in shape-local
|
|
1100
|
+
// coords for the SDF calculation.
|
|
1101
|
+
vec2 p = v_uv * u_quadSize;
|
|
1102
|
+
vec2 shapeHalf = u_size * 0.5;
|
|
1103
|
+
vec2 quadHalf = u_quadSize * 0.5;
|
|
1104
|
+
vec2 ps = p - quadHalf + shapeHalf; // pixel position in SHAPE's local frame
|
|
1105
|
+
float dist;
|
|
1106
|
+
if (u_shapeType > 0.5) {
|
|
1107
|
+
vec2 d = (ps - shapeHalf) / shapeHalf;
|
|
1108
|
+
dist = (sqrt(dot(d, d)) - 1.0) * min(shapeHalf.x, shapeHalf.y);
|
|
1109
|
+
} else {
|
|
1110
|
+
float r = u_cornerRadius;
|
|
1111
|
+
vec2 q = abs(ps - shapeHalf) - shapeHalf + vec2(r);
|
|
1112
|
+
dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2(0.0))) - r;
|
|
1113
|
+
}
|
|
1114
|
+
// CSS box-shadow is a Gaussian BLUR of an offset shape, not a
|
|
1115
|
+
// hard-edge falloff: alpha is ~1.0 deep inside the shape, ~0.5
|
|
1116
|
+
// right at the edge, and tails to 0 about u_blur pixels past the
|
|
1117
|
+
// edge. Symmetric smoothstep approximates the erfc shape closely
|
|
1118
|
+
// enough \\u2014 without it the shape-edge alpha is 1.0 instead of 0.5,
|
|
1119
|
+
// making shadows look much darker and extend further than CSS.
|
|
1120
|
+
if (dist > u_blur) discard;
|
|
1121
|
+
float alpha = 1.0 - smoothstep(-u_blur, u_blur, dist);
|
|
1122
|
+
if (alpha < 0.001) discard;
|
|
1123
|
+
fragColor = u_color * alpha;
|
|
1124
|
+
}
|
|
1125
|
+
\`,du=\`#version 300 es
|
|
1126
|
+
precision highp float;
|
|
1127
|
+
in vec2 v_uv;
|
|
1128
|
+
out vec4 fragColor;
|
|
1129
|
+
uniform vec4 u_color; // fill, premultiplied
|
|
1130
|
+
uniform vec4 u_strokeColor; // stroke, premultiplied
|
|
1131
|
+
uniform float u_strokeWidth; // PIXELS; 0 disables stroke
|
|
1132
|
+
uniform float u_cornerRadius; // PIXELS
|
|
1133
|
+
uniform float u_shapeType; // 0.0 rect, 1.0 ellipse
|
|
1134
|
+
uniform vec2 u_size; // pixel (width, height)
|
|
1135
|
+
void main() {
|
|
1136
|
+
// Signed pixel distance from the shape boundary: negative inside,
|
|
1137
|
+
// positive outside. Used both to discard outside pixels and to
|
|
1138
|
+
// decide whether a pixel falls in the stroke band (boundary-side
|
|
1139
|
+
// strokeWidth pixels deep).
|
|
1140
|
+
vec2 p = v_uv * u_size;
|
|
1141
|
+
vec2 half_ = u_size * 0.5;
|
|
1142
|
+
float dist;
|
|
1143
|
+
if (u_shapeType > 0.5) {
|
|
1144
|
+
// Ellipse \\u2014 exact pixel SDF is hard; use a normalized-space
|
|
1145
|
+
// approximation scaled by the smaller half-axis. Exact for
|
|
1146
|
+
// circles; underestimates the boundary distance for elongated
|
|
1147
|
+
// ellipses, which means the stroke band reads slightly thin near
|
|
1148
|
+
// the long-axis ends. Good enough for icon-shaped uses.
|
|
1149
|
+
vec2 d = (p - half_) / half_;
|
|
1150
|
+
dist = (sqrt(dot(d, d)) - 1.0) * min(half_.x, half_.y);
|
|
1151
|
+
} else {
|
|
1152
|
+
// Rectangle / rounded rectangle. r = 0 collapses to a sharp rect.
|
|
1153
|
+
float r = u_cornerRadius;
|
|
1154
|
+
vec2 q = abs(p - half_) - half_ + vec2(r);
|
|
1155
|
+
dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2(0.0))) - r;
|
|
1156
|
+
}
|
|
1157
|
+
// Anti-aliased boundary: use screen-space derivative to find the
|
|
1158
|
+
// AA band around dist = 0, and blend out as we exit the shape.
|
|
1159
|
+
// Without this, rotated rectangles show jagged stairstep edges
|
|
1160
|
+
// (the rotated geometry no longer aligns with pixel rows). Band
|
|
1161
|
+
// width = 2 \\xD7 fwidth(dist) \\u2014 wider than the standard 1 px so edges
|
|
1162
|
+
// stay visibly smooth even when the canvas is downsampled to a
|
|
1163
|
+
// smaller preview or the display has higher pixel density than the
|
|
1164
|
+
// canvas backing store.
|
|
1165
|
+
float aa = fwidth(dist);
|
|
1166
|
+
float outerAlpha = 1.0 - smoothstep(-aa, aa, dist);
|
|
1167
|
+
if (outerAlpha < 0.001) discard;
|
|
1168
|
+
|
|
1169
|
+
vec4 base;
|
|
1170
|
+
if (u_strokeWidth > 0.0) {
|
|
1171
|
+
// Stroke band is the [-strokeWidth, 0] interval of dist; the fill
|
|
1172
|
+
// interior is dist <= -strokeWidth. strokeAlpha rises from 0 (fill)
|
|
1173
|
+
// to 1 (stroke) as dist crosses -strokeWidth, with the same ~1px
|
|
1174
|
+
// AA softness applied at the inner boundary so the stroke doesn't
|
|
1175
|
+
// stair-step against the fill.
|
|
1176
|
+
float strokeAlpha = smoothstep(-u_strokeWidth - aa, -u_strokeWidth + aa, dist);
|
|
1177
|
+
base = mix(u_color, u_strokeColor, strokeAlpha);
|
|
1178
|
+
} else {
|
|
1179
|
+
base = u_color;
|
|
1180
|
+
}
|
|
1181
|
+
// Premultiplied output: scaling all channels by outerAlpha is correct.
|
|
1182
|
+
fragColor = base * outerAlpha;
|
|
1183
|
+
}
|
|
1184
|
+
\`,uu=\`#version 300 es
|
|
1185
|
+
in vec2 a_pos;
|
|
1186
|
+
in vec2 a_uv;
|
|
1187
|
+
out vec2 v_uv;
|
|
1188
|
+
out vec3 v_worldPos;
|
|
1189
|
+
uniform mat4 u_transform;
|
|
1190
|
+
uniform mat4 u_worldMatrix;
|
|
1191
|
+
void main() {
|
|
1192
|
+
gl_Position = u_transform * vec4(a_pos, 0.0, 1.0);
|
|
1193
|
+
v_uv = a_uv;
|
|
1194
|
+
vec4 wp = u_worldMatrix * vec4(a_pos, 0.0, 1.0);
|
|
1195
|
+
v_worldPos = wp.xyz;
|
|
1196
|
+
}
|
|
1197
|
+
\`,Co=\`
|
|
1198
|
+
uniform vec3 u_normal;
|
|
1199
|
+
uniform vec3 u_eye;
|
|
1200
|
+
uniform float u_rough;
|
|
1201
|
+
uniform float u_metal;
|
|
1202
|
+
uniform float u_reflect;
|
|
1203
|
+
uniform float u_emissive;
|
|
1204
|
+
uniform vec3 u_ambient;
|
|
1205
|
+
uniform int u_numLights;
|
|
1206
|
+
uniform vec3 u_lightDir[4];
|
|
1207
|
+
uniform vec3 u_lightColor[4];
|
|
1208
|
+
uniform int u_envCount; // 0 \\u21D2 no environment reflection
|
|
1209
|
+
uniform vec3 u_envColor[4]; // straight RGB, sorted by offset
|
|
1210
|
+
uniform float u_envOffset[4];
|
|
1211
|
+
uniform vec3 u_envAvg; // mean env color (irradiance / rough fallback)
|
|
1212
|
+
uniform vec3 u_tangent; // world +U (normal mapping)
|
|
1213
|
+
uniform vec3 u_bitangent; // world +V
|
|
1214
|
+
uniform float u_normalScale;
|
|
1215
|
+
uniform int u_hasNormalMap; // 0 \\u21D2 flat face normal
|
|
1216
|
+
uniform sampler2D u_normalMap;
|
|
1217
|
+
uniform int u_envIsImage; // 1 \\u21D2 sample u_envMap as equirect
|
|
1218
|
+
uniform sampler2D u_envMap;
|
|
1219
|
+
const float PI = 3.14159265;
|
|
1220
|
+
float ggxD(float NdotH, float a) { float a2 = a * a; float d = NdotH * NdotH * (a2 - 1.0) + 1.0; return a2 / (PI * d * d); }
|
|
1221
|
+
float gSchlick(float x, float k) { return x / (x * (1.0 - k) + k); }
|
|
1222
|
+
// Sample the gradient environment at parameter t\\u2208[0,1] (const-indexed for
|
|
1223
|
+
// portability \\u2014 matches the WGSL path). Stops are sorted by offset.
|
|
1224
|
+
vec3 sampleEnv(float t) {
|
|
1225
|
+
vec3 c = u_envColor[0];
|
|
1226
|
+
if (u_envCount > 1) {
|
|
1227
|
+
vec3 last = u_envColor[1];
|
|
1228
|
+
if (u_envCount > 2) last = u_envColor[2];
|
|
1229
|
+
if (u_envCount > 3) last = u_envColor[3];
|
|
1230
|
+
if (t <= u_envOffset[1]) {
|
|
1231
|
+
c = mix(u_envColor[0], u_envColor[1], clamp((t - u_envOffset[0]) / max(u_envOffset[1] - u_envOffset[0], 1e-4), 0.0, 1.0));
|
|
1232
|
+
} else if (u_envCount > 2 && t <= u_envOffset[2]) {
|
|
1233
|
+
c = mix(u_envColor[1], u_envColor[2], clamp((t - u_envOffset[1]) / max(u_envOffset[2] - u_envOffset[1], 1e-4), 0.0, 1.0));
|
|
1234
|
+
} else if (u_envCount > 3 && t <= u_envOffset[3]) {
|
|
1235
|
+
c = mix(u_envColor[2], u_envColor[3], clamp((t - u_envOffset[2]) / max(u_envOffset[3] - u_envOffset[2], 1e-4), 0.0, 1.0));
|
|
1236
|
+
} else {
|
|
1237
|
+
c = last;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
return c;
|
|
1241
|
+
}
|
|
1242
|
+
// Perturb the face normal by a tangent-space normal map (flat = #8080ff).
|
|
1243
|
+
vec3 perturbNormal(vec3 N, vec2 uv) {
|
|
1244
|
+
if (u_hasNormalMap == 0) return N;
|
|
1245
|
+
vec3 s = texture(u_normalMap, uv).rgb * 2.0 - 1.0;
|
|
1246
|
+
s.xy *= u_normalScale;
|
|
1247
|
+
return normalize(s.x * normalize(u_tangent) + s.y * normalize(u_bitangent) + s.z * N);
|
|
1248
|
+
}
|
|
1249
|
+
// Shade a fragment given its straight-alpha albedo, world normal, view
|
|
1250
|
+
// vector. Returns clamped straight RGB (ambient + direct + env + emissive).
|
|
1251
|
+
vec3 shadePBR(vec3 albedo, vec3 Nin, vec3 V) {
|
|
1252
|
+
vec3 N = Nin;
|
|
1253
|
+
if (dot(N, V) < 0.0) N = -N; // two-sided
|
|
1254
|
+
float NdotV = max(dot(N, V), 1e-4);
|
|
1255
|
+
vec3 F0 = mix(vec3(0.04), albedo, u_metal);
|
|
1256
|
+
float a = u_rough * u_rough;
|
|
1257
|
+
float k = (u_rough + 1.0) * (u_rough + 1.0) / 8.0;
|
|
1258
|
+
|
|
1259
|
+
vec3 color = albedo * u_ambient; // ambient (flat fill) term
|
|
1260
|
+
for (int i = 0; i < 4; i++) {
|
|
1261
|
+
if (i >= u_numLights) break;
|
|
1262
|
+
vec3 L = normalize(u_lightDir[i]);
|
|
1263
|
+
vec3 H = normalize(V + L);
|
|
1264
|
+
float NdotL = max(dot(N, L), 0.0);
|
|
1265
|
+
float NdotH = max(dot(N, H), 0.0);
|
|
1266
|
+
float VdotH = max(dot(V, H), 0.0);
|
|
1267
|
+
vec3 F = F0 + (1.0 - F0) * pow(1.0 - VdotH, 5.0);
|
|
1268
|
+
float D = ggxD(NdotH, a);
|
|
1269
|
+
float G = gSchlick(NdotL, k) * gSchlick(NdotV, k);
|
|
1270
|
+
vec3 spec = (D * G) * F / max(4.0 * NdotL * NdotV, 1e-3);
|
|
1271
|
+
vec3 kd = (1.0 - F) * (1.0 - u_metal);
|
|
1272
|
+
color += (kd * albedo + spec) * u_lightColor[i] * NdotL;
|
|
1273
|
+
}
|
|
1274
|
+
// Environment reflection: mirror the gradient sky along R, roughness-
|
|
1275
|
+
// blurred toward the average; IBL split (diffuse + Fresnel specular).
|
|
1276
|
+
if (u_envCount > 0 || u_envIsImage == 1) {
|
|
1277
|
+
vec3 R = reflect(-V, N);
|
|
1278
|
+
vec3 sharp;
|
|
1279
|
+
if (u_envIsImage == 1) {
|
|
1280
|
+
// Equirect (lat-long) sample along the reflection ray. Up = \\u2212y.
|
|
1281
|
+
vec3 Rn = normalize(R);
|
|
1282
|
+
vec2 euv = vec2(atan(Rn.x, Rn.z) / (2.0 * PI) + 0.5, acos(clamp(-Rn.y, -1.0, 1.0)) / PI);
|
|
1283
|
+
sharp = texture(u_envMap, euv).rgb;
|
|
1284
|
+
} else {
|
|
1285
|
+
float t = clamp(0.5 - 0.5 * (R.y / max(length(R), 1e-4)), 0.0, 1.0); // up\\u21921, down\\u21920
|
|
1286
|
+
sharp = sampleEnv(t);
|
|
1287
|
+
}
|
|
1288
|
+
vec3 envc = mix(sharp, u_envAvg, u_rough);
|
|
1289
|
+
vec3 Fr = F0 + (max(vec3(1.0 - u_rough), F0) - F0) * pow(1.0 - NdotV, 5.0);
|
|
1290
|
+
vec3 kdEnv = (1.0 - Fr) * (1.0 - u_metal);
|
|
1291
|
+
color += (kdEnv * albedo * u_envAvg + envc * Fr) * u_reflect;
|
|
1292
|
+
}
|
|
1293
|
+
color = mix(color, albedo, clamp(u_emissive, 0.0, 1.0));
|
|
1294
|
+
return clamp(color, 0.0, 1.0);
|
|
1295
|
+
}
|
|
1296
|
+
\`,hu=\`#version 300 es
|
|
1297
|
+
precision highp float;
|
|
1298
|
+
in vec2 v_uv;
|
|
1299
|
+
in vec3 v_worldPos;
|
|
1300
|
+
out vec4 fragColor;
|
|
1301
|
+
uniform vec4 u_albedo; // straight (non-premultiplied)
|
|
1302
|
+
uniform vec4 u_strokeAlbedo; // straight
|
|
1303
|
+
uniform float u_strokeWidth;
|
|
1304
|
+
uniform float u_cornerRadius;
|
|
1305
|
+
uniform float u_shapeType;
|
|
1306
|
+
uniform vec2 u_size;
|
|
1307
|
+
\${Co}
|
|
1308
|
+
void main() {
|
|
1309
|
+
vec2 p = v_uv * u_size;
|
|
1310
|
+
vec2 half_ = u_size * 0.5;
|
|
1311
|
+
float dist;
|
|
1312
|
+
if (u_shapeType > 0.5) {
|
|
1313
|
+
vec2 d = (p - half_) / half_;
|
|
1314
|
+
dist = (sqrt(dot(d, d)) - 1.0) * min(half_.x, half_.y);
|
|
1315
|
+
} else {
|
|
1316
|
+
float r = u_cornerRadius;
|
|
1317
|
+
vec2 q = abs(p - half_) - half_ + vec2(r);
|
|
1318
|
+
dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2(0.0))) - r;
|
|
1319
|
+
}
|
|
1320
|
+
float aa = fwidth(dist);
|
|
1321
|
+
float outerAlpha = 1.0 - smoothstep(-aa, aa, dist);
|
|
1322
|
+
if (outerAlpha < 0.001) discard;
|
|
1323
|
+
|
|
1324
|
+
vec4 alb = u_albedo;
|
|
1325
|
+
if (u_strokeWidth > 0.0) {
|
|
1326
|
+
float sa = smoothstep(-u_strokeWidth - aa, -u_strokeWidth + aa, dist);
|
|
1327
|
+
alb = mix(u_albedo, u_strokeAlbedo, sa);
|
|
1328
|
+
}
|
|
1329
|
+
vec3 N = perturbNormal(normalize(u_normal), v_uv);
|
|
1330
|
+
vec3 color = shadePBR(alb.rgb, N, normalize(u_eye - v_worldPos));
|
|
1331
|
+
float outA = alb.a * outerAlpha;
|
|
1332
|
+
fragColor = vec4(color * outA, outA); // premultiplied
|
|
1333
|
+
}\`,fu=\`#version 300 es
|
|
1334
|
+
in vec2 a_pos;
|
|
1335
|
+
in vec2 a_uv;
|
|
1336
|
+
out vec2 v_uv;
|
|
1337
|
+
out vec2 v_quadPos;
|
|
1338
|
+
out vec3 v_worldPos;
|
|
1339
|
+
uniform mat4 u_transform;
|
|
1340
|
+
uniform mat4 u_worldMatrix;
|
|
1341
|
+
uniform vec4 u_uvRect; // (u0, v0, u1, v1)
|
|
1342
|
+
void main() {
|
|
1343
|
+
gl_Position = u_transform * vec4(a_pos, 0.0, 1.0);
|
|
1344
|
+
v_uv = mix(u_uvRect.xy, u_uvRect.zw, a_uv);
|
|
1345
|
+
v_quadPos = a_uv;
|
|
1346
|
+
vec4 wp = u_worldMatrix * vec4(a_pos, 0.0, 1.0);
|
|
1347
|
+
v_worldPos = wp.xyz;
|
|
1348
|
+
}\`,pu=\`#version 300 es
|
|
1349
|
+
precision highp float;
|
|
1350
|
+
in vec2 v_uv;
|
|
1351
|
+
in vec2 v_quadPos;
|
|
1352
|
+
in vec3 v_worldPos;
|
|
1353
|
+
out vec4 fragColor;
|
|
1354
|
+
uniform sampler2D u_tex;
|
|
1355
|
+
uniform vec4 u_tint; // premultiplied
|
|
1356
|
+
uniform float u_cornerRadius; // PIXELS; 0 disables masking
|
|
1357
|
+
uniform vec2 u_size; // pixel (width, height) of the quad
|
|
1358
|
+
\${Co}
|
|
1359
|
+
void main() {
|
|
1360
|
+
vec4 s = texture(u_tex, v_uv); // premultiplied
|
|
1361
|
+
float cov = s.a;
|
|
1362
|
+
vec3 albedo = cov > 0.0 ? s.rgb / cov : s.rgb; // straight albedo
|
|
1363
|
+
// tint as straight color \\xD7 opacity (group layers pass (o,o,o,o)).
|
|
1364
|
+
vec3 tintRgb = u_tint.a > 0.0 ? u_tint.rgb / u_tint.a : vec3(1.0);
|
|
1365
|
+
albedo *= tintRgb;
|
|
1366
|
+
|
|
1367
|
+
float maskAlpha = 1.0;
|
|
1368
|
+
if (u_cornerRadius > 0.0) {
|
|
1369
|
+
vec2 p = v_quadPos * u_size;
|
|
1370
|
+
vec2 half_ = u_size * 0.5;
|
|
1371
|
+
float r = u_cornerRadius;
|
|
1372
|
+
vec2 q = abs(p - half_) - half_ + vec2(r);
|
|
1373
|
+
float dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2(0.0))) - r;
|
|
1374
|
+
float aa = fwidth(dist);
|
|
1375
|
+
maskAlpha = 1.0 - smoothstep(-aa, aa, dist);
|
|
1376
|
+
if (maskAlpha < 0.001) discard;
|
|
1377
|
+
}
|
|
1378
|
+
vec3 N = perturbNormal(normalize(u_normal), v_quadPos);
|
|
1379
|
+
vec3 color = shadePBR(albedo, N, normalize(u_eye - v_worldPos));
|
|
1380
|
+
float outA = cov * u_tint.a * maskAlpha;
|
|
1381
|
+
fragColor = vec4(color * outA, outA); // premultiplied
|
|
1382
|
+
}\`,mu=\`#version 300 es
|
|
1383
|
+
in vec2 a_pos;
|
|
1384
|
+
in vec2 a_uv;
|
|
1385
|
+
out vec2 v_uv;
|
|
1386
|
+
uniform mat4 u_transform;
|
|
1387
|
+
void main() {
|
|
1388
|
+
gl_Position = u_transform * vec4(a_pos, 0.0, 1.0);
|
|
1389
|
+
v_uv = a_uv;
|
|
1390
|
+
}
|
|
1391
|
+
\`,gu=\`#version 300 es
|
|
1392
|
+
precision highp float;
|
|
1393
|
+
in vec2 v_uv;
|
|
1394
|
+
out vec4 fragColor;
|
|
1395
|
+
uniform vec4 u_meta; // cornerRadius (PIXELS), shapeType, fillType, numStops
|
|
1396
|
+
uniform vec4 u_params; // linear:(cos,sin,_,_) | radial:(cx,cy,radius,_)
|
|
1397
|
+
uniform vec2 u_size; // pixel (width, height)
|
|
1398
|
+
uniform vec4 u_stops[4]; // 4 stop colors (premultiplied)
|
|
1399
|
+
uniform vec4 u_stopOffsets; // 4 stop offsets
|
|
1400
|
+
|
|
1401
|
+
void main() {
|
|
1402
|
+
vec2 uv = v_uv;
|
|
1403
|
+
float cornerRadius = u_meta.x;
|
|
1404
|
+
float shapeType = u_meta.y;
|
|
1405
|
+
float fillType = u_meta.z;
|
|
1406
|
+
int nStops = int(u_meta.w);
|
|
1407
|
+
|
|
1408
|
+
// Shape masking \\u2014 SDF in pixel space (corners stay circular).
|
|
1409
|
+
vec2 p_px = uv * u_size;
|
|
1410
|
+
vec2 half_ = u_size * 0.5;
|
|
1411
|
+
if (shapeType > 0.5) {
|
|
1412
|
+
vec2 d = (p_px - half_) / half_;
|
|
1413
|
+
if (dot(d, d) > 1.0) discard;
|
|
1414
|
+
} else if (cornerRadius > 0.0) {
|
|
1415
|
+
float r = cornerRadius;
|
|
1416
|
+
vec2 q = abs(p_px - half_) - (half_ - vec2(r));
|
|
1417
|
+
vec2 outside = max(q, vec2(0.0));
|
|
1418
|
+
if (length(outside) > r) discard;
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
// Gradient parameter t \\u2014 runs in UV space (gradient directions are
|
|
1422
|
+
// relative to the shape's normalized bounding box).
|
|
1423
|
+
float t;
|
|
1424
|
+
if (fillType > 0.5) {
|
|
1425
|
+
float radius = max(u_params.z, 0.0001);
|
|
1426
|
+
t = clamp(distance(uv, u_params.xy) / radius, 0.0, 1.0);
|
|
1427
|
+
} else {
|
|
1428
|
+
vec2 dir = u_params.xy;
|
|
1429
|
+
vec2 centered = uv - vec2(0.5);
|
|
1430
|
+
t = clamp(dot(centered, dir) + 0.5, 0.0, 1.0);
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
vec4 color = u_stops[0];
|
|
1434
|
+
for (int i = 0; i < 3; i++) {
|
|
1435
|
+
if (i >= nStops - 1) break;
|
|
1436
|
+
float off0 = u_stopOffsets[i];
|
|
1437
|
+
float off1 = u_stopOffsets[i + 1];
|
|
1438
|
+
if (t >= off0 && t <= off1) {
|
|
1439
|
+
float segT = (t - off0) / max(off1 - off0, 0.0001);
|
|
1440
|
+
color = mix(u_stops[i], u_stops[i + 1], segT);
|
|
1441
|
+
break;
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
if (t >= u_stopOffsets[nStops - 1]) {
|
|
1445
|
+
color = u_stops[nStops - 1];
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
fragColor = color;
|
|
1449
|
+
}
|
|
1450
|
+
\`,Yi=\`#version 300 es
|
|
1451
|
+
in vec2 a_pos;
|
|
1452
|
+
in vec2 a_uv;
|
|
1453
|
+
out vec2 v_uv;
|
|
1454
|
+
out vec2 v_quadPos;
|
|
1455
|
+
uniform mat4 u_transform;
|
|
1456
|
+
uniform vec4 u_uvRect; // (u0, v0, u1, v1)
|
|
1457
|
+
void main() {
|
|
1458
|
+
gl_Position = u_transform * vec4(a_pos, 0.0, 1.0);
|
|
1459
|
+
v_uv = mix(u_uvRect.xy, u_uvRect.zw, a_uv);
|
|
1460
|
+
v_quadPos = a_uv;
|
|
1461
|
+
}
|
|
1462
|
+
\`,_u=\`#version 300 es
|
|
1463
|
+
precision highp float;
|
|
1464
|
+
in vec2 v_uv;
|
|
1465
|
+
in vec2 v_quadPos;
|
|
1466
|
+
out vec4 fragColor;
|
|
1467
|
+
uniform sampler2D u_tex;
|
|
1468
|
+
uniform vec4 u_tint; // premultiplied
|
|
1469
|
+
uniform float u_cornerRadius; // PIXELS; 0 disables masking
|
|
1470
|
+
uniform vec2 u_size; // pixel (width, height) of the quad
|
|
1471
|
+
uniform float u_alphaGamma; // coverage exponent; 1 = no-op (see backend.ts)
|
|
1472
|
+
void main() {
|
|
1473
|
+
vec4 s = texture(u_tex, v_uv); // already premultiplied (UNPACK_PREMULTIPLY_ALPHA_WEBGL)
|
|
1474
|
+
if (u_alphaGamma != 1.0) {
|
|
1475
|
+
// Reshape coverage: a' = a^g. Premultiplied, so scale the whole
|
|
1476
|
+
// sample by a^(g-1); the max() guard keeps g<1 finite at a=0.
|
|
1477
|
+
s *= pow(max(s.a, 1e-5), u_alphaGamma - 1.0);
|
|
1478
|
+
}
|
|
1479
|
+
float maskAlpha = 1.0;
|
|
1480
|
+
if (u_cornerRadius > 0.0) {
|
|
1481
|
+
// Same rounded-rect SDF as SHAPE_FS, evaluated in the quad's
|
|
1482
|
+
// local pixel space (v_quadPos is the un-remapped 0..1 vertex
|
|
1483
|
+
// attribute, not the sampling UV).
|
|
1484
|
+
vec2 p = v_quadPos * u_size;
|
|
1485
|
+
vec2 half_ = u_size * 0.5;
|
|
1486
|
+
float r = u_cornerRadius;
|
|
1487
|
+
vec2 q = abs(p - half_) - half_ + vec2(r);
|
|
1488
|
+
float dist = min(max(q.x, q.y), 0.0) + length(max(q, vec2(0.0))) - r;
|
|
1489
|
+
float aa = fwidth(dist);
|
|
1490
|
+
maskAlpha = 1.0 - smoothstep(-aa, aa, dist);
|
|
1491
|
+
if (maskAlpha < 0.001) discard;
|
|
1492
|
+
}
|
|
1493
|
+
fragColor = s * u_tint * maskAlpha;
|
|
1494
|
+
}
|
|
1495
|
+
\`,xu=\`#version 300 es
|
|
1496
|
+
precision highp float;
|
|
1497
|
+
in vec2 v_uv;
|
|
1498
|
+
in vec2 v_quadPos;
|
|
1499
|
+
out vec4 fragColor;
|
|
1500
|
+
uniform sampler2D u_tex; // content (premultiplied)
|
|
1501
|
+
uniform sampler2D u_mask; // mask (premultiplied)
|
|
1502
|
+
uniform vec4 u_tint; // premultiplied
|
|
1503
|
+
uniform float u_mode; // 0 alpha, 1 alpha-inverted, 2 luma, 3 luma-inverted
|
|
1504
|
+
void main() {
|
|
1505
|
+
vec4 c = texture(u_tex, v_uv) * u_tint;
|
|
1506
|
+
vec4 m = texture(u_mask, v_uv);
|
|
1507
|
+
float f;
|
|
1508
|
+
if (u_mode < 0.5) f = m.a;
|
|
1509
|
+
else if (u_mode < 1.5) f = 1.0 - m.a;
|
|
1510
|
+
else {
|
|
1511
|
+
float luma = dot(m.rgb, vec3(0.2126, 0.7152, 0.0722));
|
|
1512
|
+
f = (u_mode < 2.5) ? luma : (1.0 - luma);
|
|
1513
|
+
}
|
|
1514
|
+
fragColor = c * f;
|
|
1515
|
+
}
|
|
1516
|
+
\`,yu=\`#version 300 es
|
|
1517
|
+
precision highp float;
|
|
1518
|
+
in vec2 v_uv;
|
|
1519
|
+
out vec4 fragColor;
|
|
1520
|
+
uniform sampler2D u_src; // element layer, premultiplied
|
|
1521
|
+
uniform sampler2D u_backdrop; // backdrop snapshot, premultiplied
|
|
1522
|
+
uniform int u_mode; // 0 overlay, 1 hard-light, 2 soft-light
|
|
1523
|
+
uniform float u_backdropFlipY; // 1.0 flips backdrop v
|
|
1524
|
+
float blendCh(int mode, float cb, float cs) {
|
|
1525
|
+
if (mode == 0) { // overlay
|
|
1526
|
+
return cb <= 0.5 ? (2.0*cb*cs) : (1.0 - 2.0*(1.0-cb)*(1.0-cs));
|
|
1527
|
+
} else if (mode == 1) { // hard-light = overlay(src,backdrop)
|
|
1528
|
+
return cs <= 0.5 ? (2.0*cs*cb) : (1.0 - 2.0*(1.0-cs)*(1.0-cb));
|
|
1529
|
+
} else { // soft-light (W3C)
|
|
1530
|
+
if (cs <= 0.5) return cb - (1.0 - 2.0*cs) * cb * (1.0 - cb);
|
|
1531
|
+
float d = cb <= 0.25 ? (((16.0*cb - 12.0)*cb + 4.0)*cb) : sqrt(cb);
|
|
1532
|
+
return cb + (2.0*cs - 1.0) * (d - cb);
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
void main() {
|
|
1536
|
+
vec4 s = texture(u_src, v_uv);
|
|
1537
|
+
vec2 buv = vec2(v_uv.x, mix(v_uv.y, 1.0 - v_uv.y, u_backdropFlipY));
|
|
1538
|
+
vec4 b = texture(u_backdrop, buv);
|
|
1539
|
+
float as = s.a, ab = b.a;
|
|
1540
|
+
vec3 Cs = as > 0.0 ? s.rgb / as : vec3(0.0);
|
|
1541
|
+
vec3 Cb = ab > 0.0 ? b.rgb / ab : vec3(0.0);
|
|
1542
|
+
vec3 Bc = vec3(blendCh(u_mode, Cb.r, Cs.r), blendCh(u_mode, Cb.g, Cs.g), blendCh(u_mode, Cb.b, Cs.b));
|
|
1543
|
+
vec3 co = as*(1.0-ab)*Cs + as*ab*Bc + (1.0-as)*ab*Cb; // premultiplied
|
|
1544
|
+
float ao = as + ab*(1.0-as);
|
|
1545
|
+
fragColor = vec4(co, ao);
|
|
1546
|
+
}
|
|
1547
|
+
\`,bu=\`#version 300 es
|
|
1548
|
+
precision highp float;
|
|
1549
|
+
in vec2 v_uv;
|
|
1550
|
+
out vec4 fragColor;
|
|
1551
|
+
uniform sampler2D u_tex; // layer (premultiplied)
|
|
1552
|
+
uniform vec2 u_texel; // blur direction \\xF7 texture PHYSICAL dims
|
|
1553
|
+
uniform float u_sigma; // Gaussian \\u03C3 in PHYSICAL pixels; 0 = no blur
|
|
1554
|
+
uniform vec4 u_colorOps; // (brightness, contrast, saturation, hue radians)
|
|
1555
|
+
uniform vec4 u_tint; // premultiplied
|
|
1556
|
+
void main() {
|
|
1557
|
+
vec4 acc;
|
|
1558
|
+
if (u_sigma > 0.0) {
|
|
1559
|
+
acc = vec4(0.0);
|
|
1560
|
+
float wsum = 0.0;
|
|
1561
|
+
for (int i = -12; i <= 12; i++) {
|
|
1562
|
+
float d = float(i) * u_sigma * 0.25; // taps cover \\xB13\\u03C3
|
|
1563
|
+
float w = exp(-0.5 * d * d / (u_sigma * u_sigma));
|
|
1564
|
+
acc += texture(u_tex, v_uv + u_texel * d) * w;
|
|
1565
|
+
wsum += w;
|
|
1566
|
+
}
|
|
1567
|
+
acc /= wsum;
|
|
1568
|
+
} else {
|
|
1569
|
+
acc = texture(u_tex, v_uv);
|
|
1570
|
+
}
|
|
1571
|
+
float a = acc.a;
|
|
1572
|
+
vec3 c = a > 0.0 ? acc.rgb / a : vec3(0.0);
|
|
1573
|
+
c *= u_colorOps.x; // brightness
|
|
1574
|
+
c = (c - 0.5) * u_colorOps.y + 0.5; // contrast
|
|
1575
|
+
float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // Rec. 709 luma
|
|
1576
|
+
c = mix(vec3(l), c, u_colorOps.z); // saturation
|
|
1577
|
+
if (u_colorOps.w != 0.0) { // hue rotate (SVG matrix)
|
|
1578
|
+
float hc = cos(u_colorOps.w);
|
|
1579
|
+
float hs = sin(u_colorOps.w);
|
|
1580
|
+
c = mat3(
|
|
1581
|
+
0.213 + 0.787*hc - 0.213*hs, 0.213 - 0.213*hc + 0.143*hs, 0.213 - 0.213*hc - 0.787*hs,
|
|
1582
|
+
0.715 - 0.715*hc - 0.715*hs, 0.715 + 0.285*hc + 0.140*hs, 0.715 - 0.715*hc + 0.715*hs,
|
|
1583
|
+
0.072 - 0.072*hc + 0.928*hs, 0.072 - 0.072*hc - 0.283*hs, 0.072 + 0.928*hc + 0.072*hs
|
|
1584
|
+
) * c;
|
|
1585
|
+
}
|
|
1586
|
+
c = clamp(c, 0.0, 1.0);
|
|
1587
|
+
fragColor = vec4(c * a, a) * u_tint;
|
|
1588
|
+
}
|
|
1589
|
+
\`,vu=\`#version 300 es
|
|
1590
|
+
precision highp float;
|
|
1591
|
+
in vec2 v_uv;
|
|
1592
|
+
out vec4 fragColor;
|
|
1593
|
+
uniform sampler2D u_tex; // layer (premultiplied)
|
|
1594
|
+
uniform sampler2D u_aux; // ascii glyph atlas (80\\xD78); layer tex when unused
|
|
1595
|
+
uniform vec2 u_texSize; // layer PHYSICAL dims
|
|
1596
|
+
uniform vec4 u_params; // (mode, p0, p1, 0) \\u2014 px params pre-scaled to PHYSICAL
|
|
1597
|
+
uniform vec4 u_tint; // premultiplied
|
|
1598
|
+
|
|
1599
|
+
const float BAYER[16] = float[16](
|
|
1600
|
+
0., 8., 2., 10.,
|
|
1601
|
+
12., 4., 14., 6.,
|
|
1602
|
+
3., 11., 1., 9.,
|
|
1603
|
+
15., 7., 13., 5.);
|
|
1604
|
+
|
|
1605
|
+
// \\u2500\\u2500 Normative noise (\\xA74.7 fractal_noise / turbulent_displace) \\u2500\\u2500
|
|
1606
|
+
// PCG integer hash \\u2192 value noise (quintic fade) \\u2192 fBM (lacunarity 2,
|
|
1607
|
+
// gain 0.5, per-octave seed+o). Integer ops are bit-exact everywhere.
|
|
1608
|
+
uint pcg(uint v) {
|
|
1609
|
+
uint s = v * 747796405u + 2891336453u;
|
|
1610
|
+
uint w = ((s >> ((s >> 28) + 4u)) ^ s) * 277803737u;
|
|
1611
|
+
return (w >> 22) ^ w;
|
|
1612
|
+
}
|
|
1613
|
+
float h01(ivec3 c, uint seed) {
|
|
1614
|
+
return float(pcg(uint(c.x) ^ pcg(uint(c.y) ^ pcg(uint(c.z) ^ pcg(seed))))) / 4294967295.0;
|
|
1615
|
+
}
|
|
1616
|
+
float vnoise(vec3 p, uint seed) {
|
|
1617
|
+
vec3 i = floor(p);
|
|
1618
|
+
vec3 f = p - i;
|
|
1619
|
+
vec3 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
|
|
1620
|
+
ivec3 c = ivec3(i);
|
|
1621
|
+
float n000 = h01(c, seed);
|
|
1622
|
+
float n100 = h01(c + ivec3(1, 0, 0), seed);
|
|
1623
|
+
float n010 = h01(c + ivec3(0, 1, 0), seed);
|
|
1624
|
+
float n110 = h01(c + ivec3(1, 1, 0), seed);
|
|
1625
|
+
float n001 = h01(c + ivec3(0, 0, 1), seed);
|
|
1626
|
+
float n101 = h01(c + ivec3(1, 0, 1), seed);
|
|
1627
|
+
float n011 = h01(c + ivec3(0, 1, 1), seed);
|
|
1628
|
+
float n111 = h01(c + ivec3(1, 1, 1), seed);
|
|
1629
|
+
return mix(
|
|
1630
|
+
mix(mix(n000, n100, u.x), mix(n010, n110, u.x), u.y),
|
|
1631
|
+
mix(mix(n001, n101, u.x), mix(n011, n111, u.x), u.y), u.z);
|
|
1632
|
+
}
|
|
1633
|
+
float fbm(vec3 p, int octaves, uint seed) {
|
|
1634
|
+
float v = 0.0;
|
|
1635
|
+
float amp = 1.0;
|
|
1636
|
+
float wsum = 0.0;
|
|
1637
|
+
for (int o = 0; o < 8; o++) {
|
|
1638
|
+
if (o >= octaves) break;
|
|
1639
|
+
v += amp * vnoise(p, seed + uint(o));
|
|
1640
|
+
wsum += amp;
|
|
1641
|
+
p *= 2.0;
|
|
1642
|
+
amp *= 0.5;
|
|
1643
|
+
}
|
|
1644
|
+
return v / wsum;
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
void main() {
|
|
1648
|
+
float mode = u_params.x;
|
|
1649
|
+
vec2 px = v_uv * u_texSize;
|
|
1650
|
+
if (mode < 0.5) {
|
|
1651
|
+
// pixelate \\u2014 every pixel takes its cell's center sample.
|
|
1652
|
+
float cell = max(u_params.y, 1.0);
|
|
1653
|
+
vec2 center = (floor(px / cell) + 0.5) * cell;
|
|
1654
|
+
fragColor = texture(u_tex, center / u_texSize) * u_tint;
|
|
1655
|
+
} else if (mode < 1.5) {
|
|
1656
|
+
// dither \\u2014 per-channel quantize to N levels, 4\\xD74 Bayer threshold
|
|
1657
|
+
// indexed by output pixel coords. Alpha (coverage) is untouched.
|
|
1658
|
+
vec4 s = texture(u_tex, v_uv);
|
|
1659
|
+
float a = s.a;
|
|
1660
|
+
vec3 c = a > 0.0 ? s.rgb / a : vec3(0.0);
|
|
1661
|
+
// Bayer cells of u_params.z (pixel_size) LOGICAL px: divide device px
|
|
1662
|
+
// by (pixelRatio \\xB7 pixel_size). Resolution-independent \\u2014 the dot size
|
|
1663
|
+
// is stable across preview DPI / export and survives the editor's
|
|
1664
|
+
// fit-to-stage downscale instead of smearing into mush.
|
|
1665
|
+
ivec2 ip = ivec2(px / max(u_params.w * u_params.z, 1.0));
|
|
1666
|
+
float t = (BAYER[(ip.y % 4) * 4 + (ip.x % 4)] + 0.5) / 16.0;
|
|
1667
|
+
float n = max(u_params.y, 2.0) - 1.0;
|
|
1668
|
+
c = clamp(floor(c * n + t) / n, 0.0, 1.0);
|
|
1669
|
+
fragColor = vec4(c * a, a) * u_tint;
|
|
1670
|
+
} else if (mode < 2.5) {
|
|
1671
|
+
// halftone \\u2014 rotated dot grid; dot radius \\u221D sqrt(luma) so ink AREA
|
|
1672
|
+
// tracks luminance; dots tinted with the cell's color. The
|
|
1673
|
+
// clamp(r,0,1) factor fades sub-pixel dots instead of popping.
|
|
1674
|
+
float cell = max(u_params.y, 2.0);
|
|
1675
|
+
float ang = radians(u_params.z);
|
|
1676
|
+
mat2 rot = mat2(cos(ang), -sin(ang), sin(ang), cos(ang));
|
|
1677
|
+
mat2 inv = mat2(cos(ang), sin(ang), -sin(ang), cos(ang));
|
|
1678
|
+
vec2 rp = rot * px;
|
|
1679
|
+
vec2 centerR = (floor(rp / cell) + 0.5) * cell;
|
|
1680
|
+
vec4 s = texture(u_tex, (inv * centerR) / u_texSize);
|
|
1681
|
+
float a = s.a;
|
|
1682
|
+
vec3 c = a > 0.0 ? s.rgb / a : vec3(0.0);
|
|
1683
|
+
float luma = dot(c, vec3(0.2126, 0.7152, 0.0722)) * a;
|
|
1684
|
+
float r = 0.5 * cell * sqrt(luma);
|
|
1685
|
+
float d = length(rp - centerR);
|
|
1686
|
+
float ink = (1.0 - smoothstep(r - 1.0, r + 1.0, d)) * clamp(r, 0.0, 1.0);
|
|
1687
|
+
fragColor = vec4(c, 1.0) * (a * ink) * u_tint;
|
|
1688
|
+
} else if (mode < 3.5) {
|
|
1689
|
+
// ascii \\u2014 cells map to the 10-glyph density ramp in the atlas,
|
|
1690
|
+
// tinted with the cell's sampled color.
|
|
1691
|
+
float cell = max(u_params.y, 4.0);
|
|
1692
|
+
vec2 cellOrigin = floor(px / cell) * cell;
|
|
1693
|
+
vec4 s = texture(u_tex, (cellOrigin + 0.5 * cell) / u_texSize);
|
|
1694
|
+
float a = s.a;
|
|
1695
|
+
vec3 c = a > 0.0 ? s.rgb / a : vec3(0.0);
|
|
1696
|
+
float luma = dot(c, vec3(0.2126, 0.7152, 0.0722)) * a;
|
|
1697
|
+
float idx = clamp(floor(luma * 10.0), 0.0, 9.0);
|
|
1698
|
+
vec2 g = clamp(floor((px - cellOrigin) / cell * 8.0), 0.0, 7.0);
|
|
1699
|
+
vec2 auxUv = vec2((idx * 8.0 + g.x + 0.5) / 80.0, (g.y + 0.5) / 8.0);
|
|
1700
|
+
float ink = texture(u_aux, auxUv).a;
|
|
1701
|
+
fragColor = vec4(c, 1.0) * (a * ink) * u_tint;
|
|
1702
|
+
} else if (mode < 4.5) {
|
|
1703
|
+
// drop_shadow \\u2014 aux is the ladder-blurred layer; its alpha,
|
|
1704
|
+
// offset and tinted, composites UNDER the content (premultiplied
|
|
1705
|
+
// under-operator: dst \\xD7 (1 \\u2212 src.a)).
|
|
1706
|
+
vec4 c = texture(u_tex, v_uv);
|
|
1707
|
+
vec2 texel = 1.0 / u_texSize;
|
|
1708
|
+
vec2 ouv = clamp(v_uv - vec2(u_params.y, u_params.z) * texel, vec2(0.0), vec2(1.0));
|
|
1709
|
+
float sa = texture(u_aux, ouv).a;
|
|
1710
|
+
fragColor = c + u_tint * (sa * (1.0 - c.a));
|
|
1711
|
+
} else if (mode < 5.5) {
|
|
1712
|
+
// glow \\u2014 blurred silhouette \\xD7 intensity \\xD7 color, under the content.
|
|
1713
|
+
vec4 c = texture(u_tex, v_uv);
|
|
1714
|
+
float ga = clamp(texture(u_aux, v_uv).a * u_params.y, 0.0, 1.0);
|
|
1715
|
+
fragColor = c + u_tint * (ga * (1.0 - c.a));
|
|
1716
|
+
} else if (mode < 6.5) {
|
|
1717
|
+
// stroke \\u2014 outline band outside the silhouette: max alpha over a
|
|
1718
|
+
// 16-tap ring at the stroke width, under the content.
|
|
1719
|
+
vec4 c = texture(u_tex, v_uv);
|
|
1720
|
+
vec2 texel = 1.0 / u_texSize;
|
|
1721
|
+
float w = max(u_params.y, 1.0);
|
|
1722
|
+
float s = 0.0;
|
|
1723
|
+
for (int i = 0; i < 16; i++) {
|
|
1724
|
+
float ang = 6.2831853 * float(i) / 16.0;
|
|
1725
|
+
s = max(s, texture(u_tex, clamp(v_uv + vec2(cos(ang), sin(ang)) * w * texel, vec2(0.0), vec2(1.0))).a);
|
|
1726
|
+
}
|
|
1727
|
+
fragColor = c + u_tint * (s * (1.0 - c.a));
|
|
1728
|
+
} else if (mode < 7.5) {
|
|
1729
|
+
// chroma_key \\u2014 BT.709 CbCr distance ramp (\\xA74.7). u_tint.rgb = key
|
|
1730
|
+
// color (STRAIGHT), u_tint.a = spill; p0 tolerance, p1 softness.
|
|
1731
|
+
vec4 s = texture(u_tex, v_uv);
|
|
1732
|
+
vec3 c = s.a > 0.0 ? s.rgb / s.a : vec3(0.0);
|
|
1733
|
+
vec3 k = u_tint.rgb;
|
|
1734
|
+
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
|
|
1735
|
+
float cy = dot(c, LUMA);
|
|
1736
|
+
float ky = dot(k, LUMA);
|
|
1737
|
+
vec2 cc = vec2((c.b - cy) / 1.8556, (c.r - cy) / 1.5748);
|
|
1738
|
+
vec2 kc = vec2((k.b - ky) / 1.8556, (k.r - ky) / 1.5748);
|
|
1739
|
+
float d = distance(cc, kc);
|
|
1740
|
+
float a = u_params.z > 0.0
|
|
1741
|
+
? clamp((d - u_params.y) / u_params.z, 0.0, 1.0)
|
|
1742
|
+
: (d > u_params.y ? 1.0 : 0.0);
|
|
1743
|
+
// Spill suppression: cap the key's dominant channel (ties g\\u2192r\\u2192b)
|
|
1744
|
+
// at the max of the other two, scaled by spill.
|
|
1745
|
+
if (k.g >= k.r && k.g >= k.b) c.g -= u_tint.a * max(0.0, c.g - max(c.r, c.b));
|
|
1746
|
+
else if (k.r >= k.b) c.r -= u_tint.a * max(0.0, c.r - max(c.g, c.b));
|
|
1747
|
+
else c.b -= u_tint.a * max(0.0, c.b - max(c.r, c.g));
|
|
1748
|
+
float ao = s.a * a;
|
|
1749
|
+
fragColor = vec4(c * ao, ao);
|
|
1750
|
+
} else if (mode < 8.5) {
|
|
1751
|
+
// luma_key \\u2014 p0 threshold, p1 softness, u_tint.r = invert flag.
|
|
1752
|
+
vec4 s = texture(u_tex, v_uv);
|
|
1753
|
+
vec3 c = s.a > 0.0 ? s.rgb / s.a : vec3(0.0);
|
|
1754
|
+
float y = dot(c, vec3(0.2126, 0.7152, 0.0722));
|
|
1755
|
+
float a = u_params.z > 0.0
|
|
1756
|
+
? clamp((y - u_params.y) / u_params.z, 0.0, 1.0)
|
|
1757
|
+
: (y > u_params.y ? 1.0 : 0.0);
|
|
1758
|
+
if (u_tint.x > 0.5) a = 1.0 - a;
|
|
1759
|
+
float ao = s.a * a;
|
|
1760
|
+
fragColor = vec4(c * ao, ao);
|
|
1761
|
+
} else if (mode < 9.5) {
|
|
1762
|
+
// levels \\u2014 per-channel remap (\\xA74.7): u_tint = (in_black, in_white,
|
|
1763
|
+
// out_black, out_white), p0 = gamma; y = x^(1/gamma).
|
|
1764
|
+
vec4 s = texture(u_tex, v_uv);
|
|
1765
|
+
vec3 c = s.a > 0.0 ? s.rgb / s.a : vec3(0.0);
|
|
1766
|
+
vec3 x = clamp((c - u_tint.x) / max(u_tint.y - u_tint.x, 1e-5), 0.0, 1.0);
|
|
1767
|
+
x = pow(x, vec3(1.0 / max(u_params.y, 1e-5)));
|
|
1768
|
+
c = clamp(u_tint.z + x * (u_tint.w - u_tint.z), 0.0, 1.0);
|
|
1769
|
+
fragColor = vec4(c * s.a, s.a);
|
|
1770
|
+
} else if (mode < 10.5) {
|
|
1771
|
+
// lut \\u2014 3D lattice packed as N slices along x in a 2D atlas (aux,
|
|
1772
|
+
// N\\xB2\\xD7N, slice index = blue). Manual trilinear: two bilinear taps
|
|
1773
|
+
// mixed across the blue axis. p0 = N, p1 = intensity.
|
|
1774
|
+
vec4 s = texture(u_tex, v_uv);
|
|
1775
|
+
vec3 c = s.a > 0.0 ? s.rgb / s.a : vec3(0.0);
|
|
1776
|
+
float n = max(u_params.y, 2.0);
|
|
1777
|
+
float b = clamp(c.b, 0.0, 1.0) * (n - 1.0);
|
|
1778
|
+
float b0 = floor(b);
|
|
1779
|
+
float b1 = min(b0 + 1.0, n - 1.0);
|
|
1780
|
+
vec2 cellUv = vec2(
|
|
1781
|
+
(clamp(c.r, 0.0, 1.0) * (n - 1.0) + 0.5) / (n * n),
|
|
1782
|
+
(clamp(c.g, 0.0, 1.0) * (n - 1.0) + 0.5) / n);
|
|
1783
|
+
vec3 lo = texture(u_aux, cellUv + vec2(b0 / n, 0.0)).rgb;
|
|
1784
|
+
vec3 hi = texture(u_aux, cellUv + vec2(b1 / n, 0.0)).rgb;
|
|
1785
|
+
c = mix(c, mix(lo, hi, b - b0), clamp(u_params.z, 0.0, 1.0));
|
|
1786
|
+
fragColor = vec4(clamp(c, 0.0, 1.0) * s.a, s.a);
|
|
1787
|
+
} else if (mode < 11.5) {
|
|
1788
|
+
// fractal_noise \\u2014 grayscale fBM over the element's footprint.
|
|
1789
|
+
// p0 = scale px, p1 = evolution,
|
|
1790
|
+
// u_tint = (offset_x/scale, offset_y/scale, octaves, seed).
|
|
1791
|
+
vec4 s = texture(u_tex, v_uv);
|
|
1792
|
+
float v = fbm(
|
|
1793
|
+
vec3(px / max(u_params.y, 1e-3) + u_tint.xy, u_params.z),
|
|
1794
|
+
int(u_tint.z + 0.5), uint(u_tint.w + 0.5));
|
|
1795
|
+
fragColor = vec4(vec3(v) * s.a, s.a);
|
|
1796
|
+
} else if (mode < 12.5) {
|
|
1797
|
+
// turbulent_displace \\u2014 sample the layer at p + noise vector.
|
|
1798
|
+
// p0 = amount px, p1 = scale px, u_tint = (evolution, octaves, seed, 0).
|
|
1799
|
+
float sc = max(u_params.z, 1e-3);
|
|
1800
|
+
int oct = int(u_tint.y + 0.5);
|
|
1801
|
+
uint sd = uint(u_tint.z + 0.5);
|
|
1802
|
+
float dx = fbm(vec3(px / sc, u_tint.x), oct, sd) - 0.5;
|
|
1803
|
+
float dy = fbm(vec3(px / sc, u_tint.x), oct, sd + 7919u) - 0.5;
|
|
1804
|
+
vec2 duv = vec2(dx, dy) * 2.0 * u_params.y / u_texSize;
|
|
1805
|
+
fragColor = texture(u_tex, clamp(v_uv + duv, vec2(0.0), vec2(1.0)));
|
|
1806
|
+
} else {
|
|
1807
|
+
// bloom_bright \\u2014 extract pixels brighter than a soft threshold for a
|
|
1808
|
+
// whole-frame bloom pass. p0 = threshold, p1 = knee. Output is the
|
|
1809
|
+
// straight bright color with alpha 1 so the subsequent blur spreads
|
|
1810
|
+
// it cleanly; the composite adds it back \\xD7 intensity.
|
|
1811
|
+
vec4 s = texture(u_tex, v_uv);
|
|
1812
|
+
vec3 c = s.a > 0.0 ? s.rgb / s.a : vec3(0.0);
|
|
1813
|
+
float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
|
|
1814
|
+
float f = clamp((l - u_params.y) / max(u_params.z, 1e-3), 0.0, 1.0);
|
|
1815
|
+
fragColor = vec4(c * f, 1.0);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
\`,Ao=e=>\`#version 300 es
|
|
1819
|
+
precision highp float;
|
|
1820
|
+
in vec2 v_uv;
|
|
1821
|
+
out vec4 fragColor;
|
|
1822
|
+
uniform sampler2D u_backdrop; // FROSTED snapshot (premultiplied)
|
|
1823
|
+
uniform sampler2D u_sharp; // UNBLURRED snapshot (premultiplied)
|
|
1824
|
+
uniform vec2 u_texSize; // surface PHYSICAL dims
|
|
1825
|
+
uniform vec2 u_paneCenter; // pane centre, PHYSICAL px
|
|
1826
|
+
uniform vec2 u_paneHalf; // pane half-size, PHYSICAL px
|
|
1827
|
+
uniform vec2 u_rot; // (cos \\u03B8, sin \\u03B8) of pane rotation
|
|
1828
|
+
uniform vec4 u_geo; // (cornerRadius, zRadius, bevelMode, bdFlip) PHYSICAL
|
|
1829
|
+
uniform vec4 u_optics; // (refract, chroma, edgeHL, fresnel)
|
|
1830
|
+
uniform vec4 u_look; // (specular, saturation \\u22121..1, alpha, 0)
|
|
1831
|
+
uniform vec4 u_shadow; // (alpha, spread, offY, 0) PHYSICAL
|
|
1832
|
+
uniform vec4 u_tint; // STRAIGHT rgba \\u2014 alpha = strength\${e?\`
|
|
1833
|
+
uniform mat3 u_h; // pane-local \\u2192 surface px (projective)
|
|
1834
|
+
uniform mat3 u_hinv; // surface px \\u2192 pane-local\`:""}
|
|
1835
|
+
|
|
1836
|
+
float rrSDF(vec2 p, vec2 b, float r) {
|
|
1837
|
+
vec2 q = abs(p) - b + vec2(r);
|
|
1838
|
+
return min(max(q.x, q.y), 0.0) + length(max(q, vec2(0.0))) - r;
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
// Half-circle bevel height field (reference bevelHeight).
|
|
1842
|
+
float bevelHeight(float d, float zR) {
|
|
1843
|
+
if (d <= 0.0) return 0.0;
|
|
1844
|
+
if (d >= zR) return zR;
|
|
1845
|
+
return sqrt(d * (2.0 * zR - d));
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
vec3 straight3(vec4 s) {
|
|
1849
|
+
return s.a > 0.0 ? s.rgb / s.a : vec3(0.0);
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
void main() {\${e?\`
|
|
1853
|
+
// Pane-local coordinates: invert the pane\\u2192surface homography. A
|
|
1854
|
+
// non-positive w means the fragment looks past the plane's horizon
|
|
1855
|
+
// (behind the camera) \\u2014 nothing there.
|
|
1856
|
+
vec2 px = v_uv * u_texSize;
|
|
1857
|
+
vec3 lh = u_hinv * vec3(px, 1.0);
|
|
1858
|
+
if (lh.z <= 0.0) { fragColor = vec4(0.0); return; }
|
|
1859
|
+
vec2 p = lh.xy / lh.z;\`:\`
|
|
1860
|
+
// Pane-local coordinates (rotate surface px by \\u2212\\u03B8 around the centre).
|
|
1861
|
+
vec2 px = v_uv * u_texSize;
|
|
1862
|
+
vec2 rel = px - u_paneCenter;
|
|
1863
|
+
vec2 p = vec2(rel.x * u_rot.x + rel.y * u_rot.y,
|
|
1864
|
+
-rel.x * u_rot.y + rel.y * u_rot.x);\`}
|
|
1865
|
+
vec2 half_ = u_paneHalf;
|
|
1866
|
+
float r = min(u_geo.x, min(half_.x, half_.y));
|
|
1867
|
+
float sdf = rrSDF(p, half_, r);
|
|
1868
|
+
|
|
1869
|
+
// \\u2500\\u2500 Drop shadow \\u2014 OUTSIDE the panel only \\u2500\\u2500
|
|
1870
|
+
if (sdf > 0.0) {
|
|
1871
|
+
float a = 0.0;
|
|
1872
|
+
if (u_shadow.x > 0.0) {
|
|
1873
|
+
float sdfShadow = rrSDF(p - vec2(0.0, u_shadow.z), half_, r);
|
|
1874
|
+
float d = max(sdfShadow - 1.0, 0.0);
|
|
1875
|
+
float spread = max(u_shadow.y, 1.0);
|
|
1876
|
+
float falloff = 1.0 / (spread * spread);
|
|
1877
|
+
float outerShadow = exp(-d * d * falloff) * 0.65;
|
|
1878
|
+
float contactShadow = exp(-d * 0.08 / max(spread * 0.04, 0.01)) * 0.35;
|
|
1879
|
+
a = (outerShadow + contactShadow) * u_shadow.x;
|
|
1880
|
+
}
|
|
1881
|
+
fragColor = vec4(0.0, 0.0, 0.0, a);
|
|
1882
|
+
return;
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
float mask = 1.0 - smoothstep(-1.5, 0.5, sdf);
|
|
1886
|
+
|
|
1887
|
+
float maxD = min(half_.x, half_.y);
|
|
1888
|
+
float inside = -sdf;
|
|
1889
|
+
float edge = smoothstep(maxD * 0.35, 0.0, inside);
|
|
1890
|
+
|
|
1891
|
+
// \\u2500\\u2500 Surface normal via the bevel height field (e = 2px, analytic SDF
|
|
1892
|
+
// \\u2014 no blurred-field facets, no measured-gradient lip) \\u2500\\u2500
|
|
1893
|
+
float zR = u_geo.y;
|
|
1894
|
+
float e = 2.0;
|
|
1895
|
+
float hC = bevelHeight(inside, zR);
|
|
1896
|
+
vec2 hGrad = vec2(
|
|
1897
|
+
bevelHeight(-rrSDF(p + vec2(e, 0.0), half_, r), zR) -
|
|
1898
|
+
bevelHeight(-rrSDF(p - vec2(e, 0.0), half_, r), zR),
|
|
1899
|
+
bevelHeight(-rrSDF(p + vec2(0.0, e), half_, r), zR) -
|
|
1900
|
+
bevelHeight(-rrSDF(p - vec2(0.0, e), half_, r), zR)) / (2.0 * e);
|
|
1901
|
+
vec3 N = normalize(vec3(-hGrad, 1.0));
|
|
1902
|
+
|
|
1903
|
+
float depth = smoothstep(0.0, zR, inside);
|
|
1904
|
+
|
|
1905
|
+
// \\u2500\\u2500 Refraction \\u2500\\u2500
|
|
1906
|
+
float refrPow = 1.0 - 1.0 / 1.5;
|
|
1907
|
+
float thickNorm = (hC * 2.0) / max(zR * 2.0, 1.0);
|
|
1908
|
+
vec2 refrPx;
|
|
1909
|
+
if (u_geo.z < 0.5) {
|
|
1910
|
+
// Biconvex pill: entry + exit + through-thickness refraction,
|
|
1911
|
+
// plus a depth-scaled magnification pull toward the centre.
|
|
1912
|
+
vec2 surfRefr = hGrad * refrPow;
|
|
1913
|
+
refrPx = (surfRefr * 2.0 + surfRefr * thickNorm * 0.5) * u_optics.x * 30.0;
|
|
1914
|
+
vec2 centerDir = -p / max(half_, vec2(1.0));
|
|
1915
|
+
refrPx += centerDir * u_optics.x * 4.0 * depth;
|
|
1916
|
+
} else {
|
|
1917
|
+
// Dome: uniform magnification \\u2014 contract sampling toward centre.
|
|
1918
|
+
refrPx = -p * u_optics.x * depth * 0.35;
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
// \\u2500\\u2500 Chromatic aberration \\u2500\\u2500
|
|
1922
|
+
float caS = u_optics.y * 18.0 * (edge * 0.7 + 0.3) * 2.0;
|
|
1923
|
+
vec2 caD = N.xy * caS;
|
|
1924
|
+
|
|
1925
|
+
\${e?\` // Pane-local sample points \\u2192 surface px via the FORWARD homography
|
|
1926
|
+
// (refraction and aberration computed in the pane's frame).
|
|
1927
|
+
vec3 fR = u_h * vec3(p + refrPx + caD, 1.0);
|
|
1928
|
+
vec3 fG = u_h * vec3(p + refrPx, 1.0);
|
|
1929
|
+
vec3 fB = u_h * vec3(p + refrPx - caD, 1.0);
|
|
1930
|
+
vec2 uvR = clamp(fR.xy / (max(fR.z, 1e-4) * u_texSize), vec2(0.0), vec2(1.0));
|
|
1931
|
+
vec2 uvG = clamp(fG.xy / (max(fG.z, 1e-4) * u_texSize), vec2(0.0), vec2(1.0));
|
|
1932
|
+
vec2 uvB = clamp(fB.xy / (max(fB.z, 1e-4) * u_texSize), vec2(0.0), vec2(1.0));\`:\` // Pane-local offsets \\u2192 surface space (rotate by +\\u03B8) \\u2192 uv.
|
|
1933
|
+
vec2 refrW = vec2(refrPx.x * u_rot.x - refrPx.y * u_rot.y,
|
|
1934
|
+
refrPx.x * u_rot.y + refrPx.y * u_rot.x);
|
|
1935
|
+
vec2 caW = vec2(caD.x * u_rot.x - caD.y * u_rot.y,
|
|
1936
|
+
caD.x * u_rot.y + caD.y * u_rot.x);
|
|
1937
|
+
vec2 base = v_uv + refrW / u_texSize;
|
|
1938
|
+
vec2 oCA = caW / u_texSize;
|
|
1939
|
+
vec2 uvR = clamp(base + oCA, vec2(0.0), vec2(1.0));
|
|
1940
|
+
vec2 uvG = clamp(base, vec2(0.0), vec2(1.0));
|
|
1941
|
+
vec2 uvB = clamp(base - oCA, vec2(0.0), vec2(1.0));\`}
|
|
1942
|
+
if (u_geo.w > 0.5) { // GL-canvas snapshots are bottom-up
|
|
1943
|
+
uvR.y = 1.0 - uvR.y; uvG.y = 1.0 - uvG.y; uvB.y = 1.0 - uvB.y;
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
vec3 sharp = vec3(
|
|
1947
|
+
straight3(texture(u_sharp, uvR)).r,
|
|
1948
|
+
straight3(texture(u_sharp, uvG)).g,
|
|
1949
|
+
straight3(texture(u_sharp, uvB)).b);
|
|
1950
|
+
vec3 blur = vec3(
|
|
1951
|
+
straight3(texture(u_backdrop, uvR)).r,
|
|
1952
|
+
straight3(texture(u_backdrop, uvG)).g,
|
|
1953
|
+
straight3(texture(u_backdrop, uvB)).b);
|
|
1954
|
+
// Edge-weighted blur mix: centre fully frosted, rim 15% sharp.
|
|
1955
|
+
float edgeMix = 1.0 - edge * 0.15;
|
|
1956
|
+
vec3 col = mix(sharp, blur, edgeMix);
|
|
1957
|
+
|
|
1958
|
+
// \\u2500\\u2500 Saturation (reference: 0 = unchanged) \\u2500\\u2500
|
|
1959
|
+
float lum = dot(col, vec3(0.299, 0.587, 0.114));
|
|
1960
|
+
col = mix(vec3(lum), col, 1.0 + u_look.y);
|
|
1961
|
+
|
|
1962
|
+
// \\u2500\\u2500 Tint (our color param in place of the reference's fixed cool tint) \\u2500\\u2500
|
|
1963
|
+
col = mix(col, u_tint.rgb, u_tint.a);
|
|
1964
|
+
col *= 1.0 + 0.06 * depth;
|
|
1965
|
+
|
|
1966
|
+
// \\u2500\\u2500 Fresnel \\u2500\\u2500
|
|
1967
|
+
float fres = pow(1.0 - abs(N.z), 4.0) * u_optics.w;
|
|
1968
|
+
|
|
1969
|
+
// \\u2500\\u2500 Specular highlights (multi-light Blinn-Phong, reference lights) \\u2500\\u2500
|
|
1970
|
+
vec3 V = vec3(0.0, 0.0, 1.0);
|
|
1971
|
+
vec3 L1 = normalize(vec3(0.4, 0.7, 1.0));
|
|
1972
|
+
float sp = pow(max(dot(N, normalize(L1 + V)), 0.0), 90.0);
|
|
1973
|
+
vec3 L2 = normalize(vec3(-0.3, -0.5, 1.0));
|
|
1974
|
+
sp += pow(max(dot(N, normalize(L2 + V)), 0.0), 50.0) * 0.3;
|
|
1975
|
+
vec3 L3 = normalize(vec3(0.1, 0.3, 1.0));
|
|
1976
|
+
sp += pow(max(dot(N, L3), 0.0), 6.0) * 0.1;
|
|
1977
|
+
vec3 L4 = normalize(vec3(0.0, 0.9, 0.4));
|
|
1978
|
+
sp += pow(max(dot(N, normalize(L4 + V)), 0.0), 120.0) * 0.6;
|
|
1979
|
+
float totalSpec = sp * u_look.x;
|
|
1980
|
+
|
|
1981
|
+
// \\u2500\\u2500 Inner border / stroke highlight \\u2500\\u2500
|
|
1982
|
+
float borderWidth = 1.5;
|
|
1983
|
+
float innerStroke = smoothstep(-borderWidth - 1.0, -borderWidth, sdf)
|
|
1984
|
+
* (1.0 - smoothstep(-1.0, 0.0, sdf));
|
|
1985
|
+
float topBias = 0.5 + 0.5 * (-p.y / half_.y);
|
|
1986
|
+
innerStroke *= (0.4 + 0.6 * topBias);
|
|
1987
|
+
|
|
1988
|
+
// \\u2500\\u2500 Edge highlight & inner glow \\u2500\\u2500
|
|
1989
|
+
float rim = edge * u_optics.z * 0.22;
|
|
1990
|
+
float innerGlow = smoothstep(5.0, 0.0, -sdf) * u_optics.z * 0.15;
|
|
1991
|
+
|
|
1992
|
+
// \\u2500\\u2500 Environment-like reflection (fake) \\u2500\\u2500
|
|
1993
|
+
float envRefl = (N.y * 0.5 + 0.5) * fres * 0.08;
|
|
1994
|
+
|
|
1995
|
+
// \\u2500\\u2500 Composite \\u2500\\u2500
|
|
1996
|
+
vec3 fin = col;
|
|
1997
|
+
fin += vec3(totalSpec);
|
|
1998
|
+
fin += vec3(rim + innerGlow);
|
|
1999
|
+
fin += vec3(innerStroke * u_optics.z * 0.55);
|
|
2000
|
+
fin += vec3(envRefl);
|
|
2001
|
+
fin = mix(fin, vec3(1.0), fres * 0.2);
|
|
2002
|
+
|
|
2003
|
+
float outA = mask * u_look.z;
|
|
2004
|
+
fragColor = vec4(clamp(fin, 0.0, 1.0), 1.0) * outA;
|
|
2005
|
+
}
|
|
2006
|
+
\`,wu=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]),qr=class{canvas;width;height;capabilities;gl;vbo;vao;shapeProgram;shapeLocs;shadowProgram;shadowLocs;gradientProgram;gradientLocs;texturedProgram;texturedLocs;maskedProgram;maskedLocs;backdropBlendProgram;backdropBlendLocs;filteredProgram;filteredLocs;stylizedProgram;stylizedLocs;glassProgram;glassLocs;glass3dProgram=null;glass3dLocs=null;litShapeProgram=null;litShapeLocs=null;litTexturedProgram=null;litTexturedLocs=null;nextTextureId=1;liveTextures=new Set;framingActive=!1;disposed=!1;pixelRatio=1;surfaceStack=[];renderTargetFbos=new Map;applyBlend(t){let i=this.gl;switch(t){case"add":i.blendFuncSeparate(i.ONE,i.ONE,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case"multiply":i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case"screen":i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;default:i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA)}}currentSurface(){let t=this.surfaceStack[this.surfaceStack.length-1];return t||{fbo:null,width:this.width,height:this.height,physWidth:this.canvas.width,physHeight:this.canvas.height,flipY:!1}}constructor(t){this.canvas=t,this.width=t.width,this.height=t.height}async init(){let t=$(),i=this.canvas.getContext("webgl2",{alpha:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!1,antialias:!0});if(!i)return t.warn("WebGL2 not available in this environment"),!1;this.gl=i;try{this.shapeProgram=this.buildProgram(Bo,du,"shape"),this.shapeLocs={aPos:i.getAttribLocation(this.shapeProgram,"a_pos"),aUv:i.getAttribLocation(this.shapeProgram,"a_uv"),uTransform:i.getUniformLocation(this.shapeProgram,"u_transform"),uColor:i.getUniformLocation(this.shapeProgram,"u_color"),uStrokeColor:i.getUniformLocation(this.shapeProgram,"u_strokeColor"),uStrokeWidth:i.getUniformLocation(this.shapeProgram,"u_strokeWidth"),uCornerRadius:i.getUniformLocation(this.shapeProgram,"u_cornerRadius"),uShapeType:i.getUniformLocation(this.shapeProgram,"u_shapeType"),uSize:i.getUniformLocation(this.shapeProgram,"u_size")},this.shadowProgram=this.buildProgram(Bo,lu,"shadow"),this.shadowLocs={aPos:i.getAttribLocation(this.shadowProgram,"a_pos"),aUv:i.getAttribLocation(this.shadowProgram,"a_uv"),uTransform:i.getUniformLocation(this.shadowProgram,"u_transform"),uColor:i.getUniformLocation(this.shadowProgram,"u_color"),uBlur:i.getUniformLocation(this.shadowProgram,"u_blur"),uCornerRadius:i.getUniformLocation(this.shadowProgram,"u_cornerRadius"),uShapeType:i.getUniformLocation(this.shadowProgram,"u_shapeType"),uSize:i.getUniformLocation(this.shadowProgram,"u_size"),uQuadSize:i.getUniformLocation(this.shadowProgram,"u_quadSize")},this.gradientProgram=this.buildProgram(mu,gu,"gradient"),this.gradientLocs={aPos:i.getAttribLocation(this.gradientProgram,"a_pos"),aUv:i.getAttribLocation(this.gradientProgram,"a_uv"),uTransform:i.getUniformLocation(this.gradientProgram,"u_transform"),uMeta:i.getUniformLocation(this.gradientProgram,"u_meta"),uParams:i.getUniformLocation(this.gradientProgram,"u_params"),uSize:i.getUniformLocation(this.gradientProgram,"u_size"),uStops:i.getUniformLocation(this.gradientProgram,"u_stops"),uStopOffsets:i.getUniformLocation(this.gradientProgram,"u_stopOffsets")},this.texturedProgram=this.buildProgram(Yi,_u,"textured"),this.texturedLocs={aPos:i.getAttribLocation(this.texturedProgram,"a_pos"),aUv:i.getAttribLocation(this.texturedProgram,"a_uv"),uTransform:i.getUniformLocation(this.texturedProgram,"u_transform"),uUvRect:i.getUniformLocation(this.texturedProgram,"u_uvRect"),uTint:i.getUniformLocation(this.texturedProgram,"u_tint"),uTex:i.getUniformLocation(this.texturedProgram,"u_tex"),uCornerRadius:i.getUniformLocation(this.texturedProgram,"u_cornerRadius"),uSize:i.getUniformLocation(this.texturedProgram,"u_size"),uAlphaGamma:i.getUniformLocation(this.texturedProgram,"u_alphaGamma")},this.maskedProgram=this.buildProgram(Yi,xu,"masked"),this.maskedLocs={aPos:i.getAttribLocation(this.maskedProgram,"a_pos"),aUv:i.getAttribLocation(this.maskedProgram,"a_uv"),uTransform:i.getUniformLocation(this.maskedProgram,"u_transform"),uUvRect:i.getUniformLocation(this.maskedProgram,"u_uvRect"),uTex:i.getUniformLocation(this.maskedProgram,"u_tex"),uMask:i.getUniformLocation(this.maskedProgram,"u_mask"),uTint:i.getUniformLocation(this.maskedProgram,"u_tint"),uMode:i.getUniformLocation(this.maskedProgram,"u_mode")},this.filteredProgram=this.buildProgram(Yi,bu,"filtered"),this.filteredLocs={aPos:i.getAttribLocation(this.filteredProgram,"a_pos"),aUv:i.getAttribLocation(this.filteredProgram,"a_uv"),uTransform:i.getUniformLocation(this.filteredProgram,"u_transform"),uUvRect:i.getUniformLocation(this.filteredProgram,"u_uvRect"),uTex:i.getUniformLocation(this.filteredProgram,"u_tex"),uTexel:i.getUniformLocation(this.filteredProgram,"u_texel"),uSigma:i.getUniformLocation(this.filteredProgram,"u_sigma"),uColorOps:i.getUniformLocation(this.filteredProgram,"u_colorOps"),uTint:i.getUniformLocation(this.filteredProgram,"u_tint")},this.stylizedProgram=this.buildProgram(Yi,vu,"stylized"),this.stylizedLocs={aPos:i.getAttribLocation(this.stylizedProgram,"a_pos"),aUv:i.getAttribLocation(this.stylizedProgram,"a_uv"),uTransform:i.getUniformLocation(this.stylizedProgram,"u_transform"),uUvRect:i.getUniformLocation(this.stylizedProgram,"u_uvRect"),uTex:i.getUniformLocation(this.stylizedProgram,"u_tex"),uAux:i.getUniformLocation(this.stylizedProgram,"u_aux"),uTexSize:i.getUniformLocation(this.stylizedProgram,"u_texSize"),uParams:i.getUniformLocation(this.stylizedProgram,"u_params"),uTint:i.getUniformLocation(this.stylizedProgram,"u_tint")},this.glassProgram=this.buildProgram(Yi,Ao(!1),"glass"),this.glassLocs=this.glassLocsOf(this.glassProgram),this.backdropBlendProgram=this.buildProgram(Yi,yu,"backdropBlend"),this.backdropBlendLocs={aPos:i.getAttribLocation(this.backdropBlendProgram,"a_pos"),aUv:i.getAttribLocation(this.backdropBlendProgram,"a_uv"),uTransform:i.getUniformLocation(this.backdropBlendProgram,"u_transform"),uUvRect:i.getUniformLocation(this.backdropBlendProgram,"u_uvRect"),uSrc:i.getUniformLocation(this.backdropBlendProgram,"u_src"),uBackdrop:i.getUniformLocation(this.backdropBlendProgram,"u_backdrop"),uMode:i.getUniformLocation(this.backdropBlendProgram,"u_mode"),uBackdropFlipY:i.getUniformLocation(this.backdropBlendProgram,"u_backdropFlipY")}}catch(s){return t.error("WebGL2 shader compile failed:",s instanceof Error?s.message:String(s)),!1}return this.vbo=i.createBuffer(),i.bindBuffer(i.ARRAY_BUFFER,this.vbo),i.bufferData(i.ARRAY_BUFFER,wu,i.STATIC_DRAW),this.vao=i.createVertexArray(),i.bindVertexArray(this.vao),i.bindBuffer(i.ARRAY_BUFFER,this.vbo),this.setupVertexAttribs(this.shapeLocs.aPos,this.shapeLocs.aUv),i.bindVertexArray(null),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!1),this.capabilities={api:"webgl2",maxTextureSize:i.getParameter(i.MAX_TEXTURE_SIZE)},t.info(\`WebGL2 backend ready (maxTextureSize=\${this.capabilities.maxTextureSize})\`),!0}buildProgram(t,i,s){let r=this.gl,n=this.compileShader(r.VERTEX_SHADER,t,\`\${s}.vs\`),a=this.compileShader(r.FRAGMENT_SHADER,i,\`\${s}.fs\`),o=r.createProgram();if(r.attachShader(o,n),r.attachShader(o,a),r.linkProgram(o),!r.getProgramParameter(o,r.LINK_STATUS)){let c=r.getProgramInfoLog(o);throw new Error(\`Link error (\${s}): \${c}\`)}return r.deleteShader(n),r.deleteShader(a),o}compileShader(t,i,s){let r=this.gl,n=r.createShader(t);if(r.shaderSource(n,i),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS)){let a=r.getShaderInfoLog(n);throw new Error(\`Compile error (\${s}): \${a}\`)}return n}setupVertexAttribs(t,i){let s=this.gl;s.enableVertexAttribArray(t),s.vertexAttribPointer(t,2,s.FLOAT,!1,16,0),s.enableVertexAttribArray(i),s.vertexAttribPointer(i,2,s.FLOAT,!1,16,8)}resize(t,i,s=1){if(this.disposed)return;let r=Math.max(1,Math.round(t*s)),n=Math.max(1,Math.round(i*s));t===this.width&&i===this.height&&this.canvas.width===r&&this.canvas.height===n||(this.width=t,this.height=i,this.pixelRatio=s,this.canvas.width=r,this.canvas.height=n,this.gl.viewport(0,0,r,n))}createTexture(t){let{width:i,height:s}=Su(t),r=this.gl,n=r.createTexture();r.bindTexture(r.TEXTURE_2D,n),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),this.uploadToTexture(n,t);let a={id:this.nextTextureId++,width:i,height:s,handle:n};return this.liveTextures.add(a),a}updateTexture(t,i){let s=t;this.uploadToTexture(s.handle,i)}uploadToTexture(t,i){let s=this.gl;s.bindTexture(s.TEXTURE_2D,t),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,i)}destroyTexture(t){let i=t;this.liveTextures.delete(i)&&this.gl.deleteTexture(i.handle)}beginFrame(t=[0,0,0,1]){this.framingActive&&($().warn("beginFrame called while another frame is in progress"),this.endFrame()),this.framingActive=!0,this.surfaceStack.length=0;let i=this.gl;i.bindFramebuffer(i.FRAMEBUFFER,null),i.viewport(0,0,this.canvas.width,this.canvas.height),i.clearColor(t[0],t[1],t[2],t[3]),i.clear(i.COLOR_BUFFER_BIT),i.bindVertexArray(this.vao)}endFrame(){this.framingActive&&(this.framingActive=!1,this.surfaceStack.length>0&&($().warn("endFrame with unbalanced pushTarget \\u2014 restoring canvas"),this.surfaceStack.length=0,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null)),this.gl.bindVertexArray(null))}createRenderTarget(t,i){let s=this.gl,r=Math.max(1,Math.round(t*this.pixelRatio)),n=Math.max(1,Math.round(i*this.pixelRatio)),a=s.createTexture();s.bindTexture(s.TEXTURE_2D,a),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,r,n,0,s.RGBA,s.UNSIGNED_BYTE,null);let o={id:this.nextTextureId++,width:r,height:n,handle:a};this.liveTextures.add(o);let c=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,c),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a,0);let l=s.checkFramebufferStatus(s.FRAMEBUFFER);if(s.bindFramebuffer(s.FRAMEBUFFER,this.currentSurface().fbo),l!==s.FRAMEBUFFER_COMPLETE)throw new Error(\`render target framebuffer incomplete (0x\${l.toString(16)})\`);let u={texture:o,width:t,height:i};return this.renderTargetFbos.set(u,c),u}destroyRenderTarget(t){let i=this.renderTargetFbos.get(t);i&&(this.gl.deleteFramebuffer(i),this.renderTargetFbos.delete(t)),this.destroyTexture(t.texture)}pushTarget(t,i=[0,0,0,0]){let s=this.renderTargetFbos.get(t);if(!s){$().warn("pushTarget with unknown / destroyed target \\u2014 ignored");return}let r=this.gl,n=t.texture;this.surfaceStack.push({fbo:s,width:t.width,height:t.height,physWidth:n.width,physHeight:n.height,flipY:!0}),r.bindFramebuffer(r.FRAMEBUFFER,s),r.viewport(0,0,n.width,n.height),r.clearColor(i[0],i[1],i[2],i[3]),r.clear(r.COLOR_BUFFER_BIT)}popTarget(){if(this.surfaceStack.length===0){$().warn("popTarget without matching pushTarget \\u2014 ignored");return}this.surfaceStack.pop();let t=this.currentSurface(),i=this.gl;i.bindFramebuffer(i.FRAMEBUFFER,t.fbo),i.viewport(0,0,t.physWidth,t.physHeight)}drawShapeShadow(t){if(!this.framingActive||(this.applyBlend(void 0),t.blur<=0&&t.offsetX===0&&t.offsetY===0))return;let i=this.gl,s=Math.max(0,t.blur),r=t.width+s*2,n=t.height+s*2,a=this.currentSurface(),o=t.transform?St(t.transform,a.width,a.height,a.flipY):je(t.cx+t.offsetX,t.cy+t.offsetY,r,n,t.rotation,a.width,a.height,t.skewX??0,t.skewY??0,a.flipY),c=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),l=t.shape==="ellipse"?1:0;i.useProgram(this.shadowProgram),this.setupVertexAttribs(this.shadowLocs.aPos,this.shadowLocs.aUv),this.shadowLocs.uTransform&&i.uniformMatrix4fv(this.shadowLocs.uTransform,!1,o),this.shadowLocs.uColor&&i.uniform4f(this.shadowLocs.uColor,t.color[0],t.color[1],t.color[2],t.color[3]),this.shadowLocs.uBlur&&i.uniform1f(this.shadowLocs.uBlur,s),this.shadowLocs.uCornerRadius&&i.uniform1f(this.shadowLocs.uCornerRadius,c),this.shadowLocs.uShapeType&&i.uniform1f(this.shadowLocs.uShapeType,l),this.shadowLocs.uSize&&i.uniform2f(this.shadowLocs.uSize,t.width,t.height),this.shadowLocs.uQuadSize&&i.uniform2f(this.shadowLocs.uQuadSize,r,n),i.drawArrays(i.TRIANGLES,0,6)}drawShape(t){if(!this.framingActive)return;if(t.gradient){this.drawGradientShape(t);return}if(t.lit){this.drawLitShape(t);return}let i=this.gl;this.applyBlend(t.blend);let s=this.currentSurface(),r=t.transform?St(t.transform,s.width,s.height,s.flipY):je(t.cx,t.cy,t.width,t.height,t.rotation,s.width,s.height,t.skewX??0,t.skewY??0,s.flipY),n=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),a=t.shape==="ellipse"?1:0;i.useProgram(this.shapeProgram),this.setupVertexAttribs(this.shapeLocs.aPos,this.shapeLocs.aUv),this.shapeLocs.uTransform&&i.uniformMatrix4fv(this.shapeLocs.uTransform,!1,r),this.shapeLocs.uColor&&i.uniform4f(this.shapeLocs.uColor,t.color[0],t.color[1],t.color[2],t.color[3]);let o=t.strokeWidth??0,c=t.strokeColor??t.color;this.shapeLocs.uStrokeColor&&i.uniform4f(this.shapeLocs.uStrokeColor,c[0],c[1],c[2],c[3]),this.shapeLocs.uStrokeWidth&&i.uniform1f(this.shapeLocs.uStrokeWidth,o),this.shapeLocs.uCornerRadius&&i.uniform1f(this.shapeLocs.uCornerRadius,n),this.shapeLocs.uShapeType&&i.uniform1f(this.shapeLocs.uShapeType,a),this.shapeLocs.uSize&&i.uniform2f(this.shapeLocs.uSize,t.width,t.height),i.drawArrays(i.TRIANGLES,0,6)}getLitShapeProgram(){if(!this.litShapeProgram){let t=this.gl,i=this.buildProgram(uu,hu,"litShape"),s=r=>t.getUniformLocation(i,r);this.litShapeProgram=i,this.litShapeLocs={aPos:t.getAttribLocation(i,"a_pos"),aUv:t.getAttribLocation(i,"a_uv"),u:{transform:s("u_transform"),worldMatrix:s("u_worldMatrix"),albedo:s("u_albedo"),strokeAlbedo:s("u_strokeAlbedo"),strokeWidth:s("u_strokeWidth"),cornerRadius:s("u_cornerRadius"),shapeType:s("u_shapeType"),size:s("u_size"),normal:s("u_normal"),eye:s("u_eye"),rough:s("u_rough"),metal:s("u_metal"),reflect:s("u_reflect"),emissive:s("u_emissive"),ambient:s("u_ambient"),numLights:s("u_numLights"),lightDir:s("u_lightDir"),lightColor:s("u_lightColor"),envCount:s("u_envCount"),envColor:s("u_envColor"),envOffset:s("u_envOffset"),envAvg:s("u_envAvg"),tangent:s("u_tangent"),bitangent:s("u_bitangent"),normalScale:s("u_normalScale"),hasNormalMap:s("u_hasNormalMap"),normalMap:s("u_normalMap"),envIsImage:s("u_envIsImage"),envMap:s("u_envMap")}}}return this.litShapeProgram}drawLitShape(t){let i=t.lit,s=this.gl;this.applyBlend(t.blend);let r=this.currentSurface(),n=t.transform?St(t.transform,r.width,r.height,r.flipY):je(t.cx,t.cy,t.width,t.height,t.rotation,r.width,r.height,t.skewX??0,t.skewY??0,r.flipY),a=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),o=t.shape==="ellipse"?1:0;this.getLitShapeProgram();let{aPos:c,aUv:l,u}=this.litShapeLocs;s.useProgram(this.litShapeProgram),this.setupVertexAttribs(c,l),u.transform&&s.uniformMatrix4fv(u.transform,!1,n),u.worldMatrix&&s.uniformMatrix4fv(u.worldMatrix,!1,Array.from(i.worldMatrix));let h=i.albedo;u.albedo&&s.uniform4f(u.albedo,h[0],h[1],h[2],h[3]);let f=i.strokeAlbedo??h;u.strokeAlbedo&&s.uniform4f(u.strokeAlbedo,f[0],f[1],f[2],f[3]),u.strokeWidth&&s.uniform1f(u.strokeWidth,t.strokeWidth??0),u.cornerRadius&&s.uniform1f(u.cornerRadius,a),u.shapeType&&s.uniform1f(u.shapeType,o),u.size&&s.uniform2f(u.size,t.width,t.height),this.setLitPbrUniforms(u,i),s.drawArrays(s.TRIANGLES,0,6)}setLitPbrUniforms(t,i){let s=this.gl;t.normal&&s.uniform3f(t.normal,i.normal[0],i.normal[1],i.normal[2]),t.eye&&s.uniform3f(t.eye,i.eye[0],i.eye[1],i.eye[2]),t.rough&&s.uniform1f(t.rough,i.roughness),t.metal&&s.uniform1f(t.metal,i.metalness),t.reflect&&s.uniform1f(t.reflect,i.reflectivity),t.emissive&&s.uniform1f(t.emissive,i.emissive),t.ambient&&s.uniform3f(t.ambient,i.ambient[0],i.ambient[1],i.ambient[2]);let r=Math.min(4,i.lightDirs.length);if(t.numLights&&s.uniform1i(t.numLights,r),r>0){let l=new Float32Array(12),u=new Float32Array(12);for(let h=0;h<r;h++)l[h*3]=i.lightDirs[h][0],l[h*3+1]=i.lightDirs[h][1],l[h*3+2]=i.lightDirs[h][2],u[h*3]=i.lightColors[h][0],u[h*3+1]=i.lightColors[h][1],u[h*3+2]=i.lightColors[h][2];t.lightDir&&s.uniform3fv(t.lightDir,l.subarray(0,r*3)),t.lightColor&&s.uniform3fv(t.lightColor,u.subarray(0,r*3))}let n=i.env,a=n?Math.min(4,n.stopColors.length):0;if(t.envCount&&s.uniform1i(t.envCount,a),a>0&&n){let l=new Float32Array(12),u=new Float32Array(4);for(let h=0;h<a;h++)l[h*3]=n.stopColors[h][0],l[h*3+1]=n.stopColors[h][1],l[h*3+2]=n.stopColors[h][2],u[h]=n.stopOffsets[h];t.envColor&&s.uniform3fv(t.envColor,l.subarray(0,a*3)),t.envOffset&&s.uniform1fv(t.envOffset,u.subarray(0,a))}n&&t.envAvg&&s.uniform3f(t.envAvg,n.avg[0],n.avg[1],n.avg[2]);let o=i.normalMap;t.hasNormalMap&&s.uniform1i(t.hasNormalMap,o?1:0),t.normalScale&&s.uniform1f(t.normalScale,o?o.scale:1),o&&(t.tangent&&s.uniform3f(t.tangent,o.tangent[0],o.tangent[1],o.tangent[2]),t.bitangent&&s.uniform3f(t.bitangent,o.bitangent[0],o.bitangent[1],o.bitangent[2])),s.activeTexture(s.TEXTURE1),s.bindTexture(s.TEXTURE_2D,o?o.texture.handle:this.getFlatNormalTexture()),t.normalMap&&s.uniform1i(t.normalMap,1);let c=n?.image;t.envIsImage&&s.uniform1i(t.envIsImage,c?1:0),s.activeTexture(s.TEXTURE2),s.bindTexture(s.TEXTURE_2D,c?c.handle:this.getFlatNormalTexture()),t.envMap&&s.uniform1i(t.envMap,2),s.activeTexture(s.TEXTURE0)}flatNormalTex=null;getFlatNormalTexture(){if(!this.flatNormalTex){let t=this.gl,i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([128,128,255,255])),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),this.flatNormalTex=i}return this.flatNormalTex}getLitTexturedProgram(){if(!this.litTexturedProgram){let t=this.gl,i=this.buildProgram(fu,pu,"litTextured"),s=r=>t.getUniformLocation(i,r);this.litTexturedProgram=i,this.litTexturedLocs={aPos:t.getAttribLocation(i,"a_pos"),aUv:t.getAttribLocation(i,"a_uv"),u:{transform:s("u_transform"),worldMatrix:s("u_worldMatrix"),uvRect:s("u_uvRect"),tex:s("u_tex"),tint:s("u_tint"),cornerRadius:s("u_cornerRadius"),size:s("u_size"),normal:s("u_normal"),eye:s("u_eye"),rough:s("u_rough"),metal:s("u_metal"),reflect:s("u_reflect"),emissive:s("u_emissive"),ambient:s("u_ambient"),numLights:s("u_numLights"),lightDir:s("u_lightDir"),lightColor:s("u_lightColor"),envCount:s("u_envCount"),envColor:s("u_envColor"),envOffset:s("u_envOffset"),envAvg:s("u_envAvg"),tangent:s("u_tangent"),bitangent:s("u_bitangent"),normalScale:s("u_normalScale"),hasNormalMap:s("u_hasNormalMap"),normalMap:s("u_normalMap"),envIsImage:s("u_envIsImage"),envMap:s("u_envMap")}}}return this.litTexturedProgram}drawLitTexturedQuad(t){let i=t.lit,s=this.gl;this.applyBlend(t.blend);let r=this.currentSurface(),n=t.transform?St(t.transform,r.width,r.height,r.flipY):je(t.cx,t.cy,t.width,t.height,t.rotation,r.width,r.height,t.skewX??0,t.skewY??0,r.flipY),a=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),o=t.uvRect??[0,0,1,1],c=t.tint??[1,1,1,1];this.getLitTexturedProgram();let{aPos:l,aUv:u,u:h}=this.litTexturedLocs;s.useProgram(this.litTexturedProgram),this.setupVertexAttribs(l,u),h.transform&&s.uniformMatrix4fv(h.transform,!1,n),h.worldMatrix&&s.uniformMatrix4fv(h.worldMatrix,!1,Array.from(i.worldMatrix)),h.uvRect&&s.uniform4f(h.uvRect,o[0],o[1],o[2],o[3]),h.tint&&s.uniform4f(h.tint,c[0],c[1],c[2],c[3]),h.cornerRadius&&s.uniform1f(h.cornerRadius,a),h.size&&s.uniform2f(h.size,t.width,t.height),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,t.texture.handle),h.tex&&s.uniform1i(h.tex,0),this.setLitPbrUniforms(h,i),s.drawArrays(s.TRIANGLES,0,6)}drawGradientShape(t){if(!this.framingActive||!t.gradient)return;let i=this.gl;this.applyBlend(t.blend);let s=this.currentSurface(),r=t.transform?St(t.transform,s.width,s.height,s.flipY):je(t.cx,t.cy,t.width,t.height,t.rotation,s.width,s.height,t.skewX??0,t.skewY??0,s.flipY),n=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5)),a=t.shape==="ellipse"?1:0,o=t.gradient,c=o.type==="radial"?1:0,l=o.stops.slice(0,4),u=Math.max(2,l.length),h=new Float32Array(16);for(let p=0;p<4;p++){let m=l[p]??l[l.length-1];h[p*4]=m.color[0],h[p*4+1]=m.color[1],h[p*4+2]=m.color[2],h[p*4+3]=m.color[3]}let f=new Float32Array(4);for(let p=0;p<4;p++)f[p]=l[p]?l[p].offset:1;i.useProgram(this.gradientProgram),this.setupVertexAttribs(this.gradientLocs.aPos,this.gradientLocs.aUv),this.gradientLocs.uTransform&&i.uniformMatrix4fv(this.gradientLocs.uTransform,!1,r),this.gradientLocs.uMeta&&i.uniform4f(this.gradientLocs.uMeta,n,a,c,u),this.gradientLocs.uSize&&i.uniform2f(this.gradientLocs.uSize,t.width,t.height),this.gradientLocs.uParams&&(o.type==="linear"?i.uniform4f(this.gradientLocs.uParams,Math.cos(o.angle),Math.sin(o.angle),0,0):i.uniform4f(this.gradientLocs.uParams,o.cx,o.cy,o.radius,0)),this.gradientLocs.uStops&&i.uniform4fv(this.gradientLocs.uStops,h),this.gradientLocs.uStopOffsets&&i.uniform4fv(this.gradientLocs.uStopOffsets,f),i.drawArrays(i.TRIANGLES,0,6)}drawTexturedQuad(t){if(!this.framingActive)return;if(t.lit){this.drawLitTexturedQuad(t);return}let i=this.gl;this.applyBlend(t.blend);let s=this.currentSurface(),r=t.transform?St(t.transform,s.width,s.height,s.flipY):je(t.cx,t.cy,t.width,t.height,t.rotation,s.width,s.height,t.skewX??0,t.skewY??0,s.flipY),n=t.uvRect??[0,0,1,1],a=t.tint??[1,1,1,1];i.useProgram(this.texturedProgram),this.setupVertexAttribs(this.texturedLocs.aPos,this.texturedLocs.aUv),this.texturedLocs.uTransform&&i.uniformMatrix4fv(this.texturedLocs.uTransform,!1,r),this.texturedLocs.uUvRect&&i.uniform4f(this.texturedLocs.uUvRect,n[0],n[1],n[2],n[3]),this.texturedLocs.uTint&&i.uniform4f(this.texturedLocs.uTint,a[0],a[1],a[2],a[3]);let o=Math.max(0,Math.min(t.cornerRadius??0,Math.min(t.width,t.height)*.5));this.texturedLocs.uCornerRadius&&i.uniform1f(this.texturedLocs.uCornerRadius,o),this.texturedLocs.uSize&&i.uniform2f(this.texturedLocs.uSize,t.width,t.height),this.texturedLocs.uAlphaGamma&&i.uniform1f(this.texturedLocs.uAlphaGamma,t.alphaGamma??1);let c=t.texture;i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,c.handle),this.texturedLocs.uTex&&i.uniform1i(this.texturedLocs.uTex,0),i.drawArrays(i.TRIANGLES,0,6)}drawMaskedQuad(t){if(!this.framingActive)return;let i=this.gl;this.applyBlend(t.blend);let s=this.currentSurface(),r=t.transform?St(t.transform,s.width,s.height,s.flipY):je(t.cx,t.cy,t.width,t.height,t.rotation,s.width,s.height,0,0,s.flipY),n=t.tint??[1,1,1,1],a=t.mode==="alpha"?0:t.mode==="alpha-inverted"?1:t.mode==="luma"?2:3;i.useProgram(this.maskedProgram),this.setupVertexAttribs(this.maskedLocs.aPos,this.maskedLocs.aUv),this.maskedLocs.uTransform&&i.uniformMatrix4fv(this.maskedLocs.uTransform,!1,r),this.maskedLocs.uUvRect&&i.uniform4f(this.maskedLocs.uUvRect,0,0,1,1),this.maskedLocs.uTint&&i.uniform4f(this.maskedLocs.uTint,n[0],n[1],n[2],n[3]),this.maskedLocs.uMode&&i.uniform1f(this.maskedLocs.uMode,a);let o=t.content,c=t.mask;i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,o.handle),this.maskedLocs.uTex&&i.uniform1i(this.maskedLocs.uTex,0),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,c.handle),this.maskedLocs.uMask&&i.uniform1i(this.maskedLocs.uMask,1),i.drawArrays(i.TRIANGLES,0,6),i.activeTexture(i.TEXTURE0)}drawFilteredQuad(t){if(!this.framingActive)return;let i=this.gl;this.applyBlend(t.blend);let s=this.currentSurface(),r=je(t.cx,t.cy,t.width,t.height,0,s.width,s.height,0,0,s.flipY),n=t.tint??[1,1,1,1],a=t.texture,o=t.blurRadius*this.pixelRatio;i.useProgram(this.filteredProgram),this.setupVertexAttribs(this.filteredLocs.aPos,this.filteredLocs.aUv),this.filteredLocs.uTransform&&i.uniformMatrix4fv(this.filteredLocs.uTransform,!1,r),this.filteredLocs.uUvRect&&i.uniform4f(this.filteredLocs.uUvRect,0,0,1,1),this.filteredLocs.uTexel&&i.uniform2f(this.filteredLocs.uTexel,t.blurDir[0]/a.width,t.blurDir[1]/a.height),this.filteredLocs.uSigma&&i.uniform1f(this.filteredLocs.uSigma,o),this.filteredLocs.uColorOps&&i.uniform4f(this.filteredLocs.uColorOps,t.brightness,t.contrast,t.saturation,(t.hueRotate??0)*Math.PI/180),this.filteredLocs.uTint&&i.uniform4f(this.filteredLocs.uTint,n[0],n[1],n[2],n[3]),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,a.handle),this.filteredLocs.uTex&&i.uniform1i(this.filteredLocs.uTex,0),i.drawArrays(i.TRIANGLES,0,6)}drawBackdropBlend(t){if(!this.framingActive)return;let i=this.gl,s=this.currentSurface(),r=je(t.width/2,t.height/2,t.width,t.height,0,s.width,s.height,0,0,s.flipY),n=t.mode==="overlay"?0:t.mode==="hard-light"?1:2;i.useProgram(this.backdropBlendProgram),this.setupVertexAttribs(this.backdropBlendLocs.aPos,this.backdropBlendLocs.aUv),i.blendFunc(i.ONE,i.ZERO),this.backdropBlendLocs.uTransform&&i.uniformMatrix4fv(this.backdropBlendLocs.uTransform,!1,r),this.backdropBlendLocs.uUvRect&&i.uniform4f(this.backdropBlendLocs.uUvRect,0,0,1,1),this.backdropBlendLocs.uMode&&i.uniform1i(this.backdropBlendLocs.uMode,n),this.backdropBlendLocs.uBackdropFlipY&&i.uniform1f(this.backdropBlendLocs.uBackdropFlipY,t.backdropFlipY?1:0);let a=t.src,o=t.backdrop;i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,a.handle),this.backdropBlendLocs.uSrc&&i.uniform1i(this.backdropBlendLocs.uSrc,0),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,o.handle),this.backdropBlendLocs.uBackdrop&&i.uniform1i(this.backdropBlendLocs.uBackdrop,1),i.drawArrays(i.TRIANGLES,0,6),i.activeTexture(i.TEXTURE0)}drawStylizedQuad(t){if(!this.framingActive)return;let i=this.gl;this.applyBlend(t.blend);let s=this.currentSurface(),r=je(t.cx,t.cy,t.width,t.height,0,s.width,s.height,0,0,s.flipY),n=t.tint??[1,1,1,1],a=t.texture,o=t.aux??t.texture,c=t.mode!=="dither"&&t.mode!=="glow"&&t.mode!=="chroma_key"&&t.mode!=="luma_key"&&t.mode!=="levels"&&t.mode!=="lut",l=t.mode==="drop_shadow"||t.mode==="turbulent_displace",u=c?t.p0*this.pixelRatio:t.p0,h=l?(t.p1??0)*this.pixelRatio:t.p1??0,f=Vr[t.mode];i.useProgram(this.stylizedProgram),this.setupVertexAttribs(this.stylizedLocs.aPos,this.stylizedLocs.aUv),this.stylizedLocs.uTransform&&i.uniformMatrix4fv(this.stylizedLocs.uTransform,!1,r),this.stylizedLocs.uUvRect&&i.uniform4f(this.stylizedLocs.uUvRect,0,0,1,1),this.stylizedLocs.uTexSize&&i.uniform2f(this.stylizedLocs.uTexSize,a.width,a.height),this.stylizedLocs.uParams&&i.uniform4f(this.stylizedLocs.uParams,f,u,h,this.pixelRatio),this.stylizedLocs.uTint&&i.uniform4f(this.stylizedLocs.uTint,n[0],n[1],n[2],n[3]),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,a.handle),this.stylizedLocs.uTex&&i.uniform1i(this.stylizedLocs.uTex,0),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,o.handle),this.stylizedLocs.uAux&&i.uniform1i(this.stylizedLocs.uAux,1),i.drawArrays(i.TRIANGLES,0,6),i.activeTexture(i.TEXTURE0)}drawGlassQuad(t){if(!this.framingActive)return;let i=this.gl;this.applyBlend(t.blend);let s=this.currentSurface(),r=je(t.cx,t.cy,t.width,t.height,0,s.width,s.height,0,0,s.flipY),n=t.backdrop,a=t.backdropSharp,o=this.pixelRatio,c=t.rotation*Math.PI/180,l=null,u=null;if(t.paneHomography){if(l=Hr(t.paneHomography,o),u=Gr(l),!u)return;this.glass3dProgram||(this.glass3dProgram=this.buildProgram(Yi,Ao(!0),"glass3d"),this.glass3dLocs=this.glassLocsOf(this.glass3dProgram))}let h=l?this.glass3dProgram:this.glassProgram,f=l?this.glass3dLocs:this.glassLocs;i.useProgram(h),this.setupVertexAttribs(f.aPos,f.aUv),f.uTransform&&i.uniformMatrix4fv(f.uTransform,!1,r),f.uUvRect&&i.uniform4f(f.uUvRect,0,0,1,1),f.uTexSize&&i.uniform2f(f.uTexSize,s.physWidth,s.physHeight),f.uPaneCenter&&i.uniform2f(f.uPaneCenter,t.paneCx*o,t.paneCy*o),f.uPaneHalf&&i.uniform2f(f.uPaneHalf,t.paneHalfW*o,t.paneHalfH*o),f.uRot&&i.uniform2f(f.uRot,Math.cos(c),Math.sin(c)),f.uGeo&&i.uniform4f(f.uGeo,t.cornerRadius*o,t.zRadius*o,t.bevelMode,t.backdropFlipY?1:0),f.uOptics&&i.uniform4f(f.uOptics,t.refract,t.chroma,t.edgeHighlight,t.fresnel),f.uLook&&i.uniform4f(f.uLook,t.specular,t.saturation,t.alpha,0),f.uShadow&&i.uniform4f(f.uShadow,t.shadowAlpha,t.shadowSpread*o,t.shadowOffY*o,0),f.uTint&&i.uniform4f(f.uTint,t.tint[0],t.tint[1],t.tint[2],t.tint[3]),l&&f.uH&&i.uniformMatrix3fv(f.uH,!1,l),u&&f.uHinv&&i.uniformMatrix3fv(f.uHinv,!1,u),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,n.handle),f.uBackdrop&&i.uniform1i(f.uBackdrop,0),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,a.handle),f.uSharp&&i.uniform1i(f.uSharp,1),i.drawArrays(i.TRIANGLES,0,6),i.activeTexture(i.TEXTURE0)}glassLocsOf(t){let i=this.gl;return{aPos:i.getAttribLocation(t,"a_pos"),aUv:i.getAttribLocation(t,"a_uv"),uTransform:i.getUniformLocation(t,"u_transform"),uUvRect:i.getUniformLocation(t,"u_uvRect"),uBackdrop:i.getUniformLocation(t,"u_backdrop"),uSharp:i.getUniformLocation(t,"u_sharp"),uTexSize:i.getUniformLocation(t,"u_texSize"),uPaneCenter:i.getUniformLocation(t,"u_paneCenter"),uPaneHalf:i.getUniformLocation(t,"u_paneHalf"),uRot:i.getUniformLocation(t,"u_rot"),uGeo:i.getUniformLocation(t,"u_geo"),uOptics:i.getUniformLocation(t,"u_optics"),uLook:i.getUniformLocation(t,"u_look"),uShadow:i.getUniformLocation(t,"u_shadow"),uTint:i.getUniformLocation(t,"u_tint"),uH:i.getUniformLocation(t,"u_h"),uHinv:i.getUniformLocation(t,"u_hinv")}}copySurfaceTo(t){let i=this.gl,s=this.renderTargetFbos.get(t);if(!s)return $().warn("copySurfaceTo with unknown / destroyed target \\u2014 ignored"),{flippedY:!1};let r=this.currentSurface(),n=t.texture;return i.bindFramebuffer(i.READ_FRAMEBUFFER,r.fbo),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),i.blitFramebuffer(0,0,r.physWidth,r.physHeight,0,0,n.width,n.height,i.COLOR_BUFFER_BIT,i.NEAREST),i.bindFramebuffer(i.FRAMEBUFFER,r.fbo),{flippedY:r.fbo===null}}async finish(){this.gl.finish()}dispose(){if(this.disposed)return;this.disposed=!0;let t=this.gl;if(t){for(let i of this.liveTextures)t.deleteTexture(i.handle);this.liveTextures.clear(),this.vbo&&t.deleteBuffer(this.vbo),this.vao&&t.deleteVertexArray(this.vao),this.shapeProgram&&t.deleteProgram(this.shapeProgram),this.gradientProgram&&t.deleteProgram(this.gradientProgram),this.texturedProgram&&t.deleteProgram(this.texturedProgram)}}};function Su(e){return"codedWidth"in e&&"codedHeight"in e?{width:e.codedWidth,height:e.codedHeight}:"videoWidth"in e&&"videoHeight"in e?{width:e.videoWidth,height:e.videoHeight}:"naturalWidth"in e&&"naturalHeight"in e?{width:e.naturalWidth,height:e.naturalHeight}:{width:e.width,height:e.height}}var si=class{store=new Map;inFlight=new Map;async getOrLoad(t,i){let s=this.store.get(t);if(s!==void 0)return s;let r=this.inFlight.get(t);if(r)return r;let n=i().then(a=>(this.store.set(t,a),this.inFlight.delete(t),a)).catch(a=>{throw this.inFlight.delete(t),a});return this.inFlight.set(t,n),n}has(t){return this.store.has(t)}get(t){return this.store.get(t)}set(t,i){this.store.set(t,i)}delete(t){let i=this.store.get(t);return this.store.delete(t),i}clear(){this.store.clear(),this.inFlight.clear()}get size(){return this.store.size}entries(){return this.store.entries()}};function ia(){if(typeof document<"u"&&document.fonts)return document.fonts;if(typeof self<"u"){let e=self;if(e.fonts)return e.fonts}return null}var ku=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]);async function zo(e,t="normal",i="normal"){let s=ia();if(!s)return;let r=e.split(",").map(a=>a.trim().replace(/^["']|["']$/g,"")).find(a=>a&&!ku.has(a.toLowerCase()));if(!r)return;let n=\`\${i} \${t} 16px "\${r}"\`;try{(await s.load(n)).length===0&&$().warn(\`Font "\${r}" (\${t} \${i}) was requested but no matching FontFace was found. Declare it in the Source's fonts[] (family + src), or add the @font-face to the page. Text will render with the browser default.\`)}catch(a){$().warn(\`Loading font "\${r}" failed:\`,a instanceof Error?a.message:String(a))}}async function Po(){let e=ia();e&&await e.ready}var Mo=new Set;async function Io(e){let t=ia();if(!t||typeof FontFace>"u")return;let i=[];for(let s of e){let r=s.weight===void 0?"normal":String(s.weight),n=s.style??"normal",a=\`\${s.family}|\${r}|\${n}|\${s.src}\`;if(!Mo.has(a)){Mo.add(a);try{let o=new FontFace(s.family,\`url(\${s.src})\`,{weight:r,style:n,...s.unicode_range?{unicodeRange:s.unicode_range}:{}});t.add(o),i.push(o.load().catch(c=>{$().warn(\`Failed to load Source font "\${s.family}" (\${r} \${n}) from \${s.src}:\`,c instanceof Error?c.message:String(c))}))}catch(o){$().warn(\`Failed to register Source font "\${s.family}" (\${r} \${n}):\`,o instanceof Error?o.message:String(o))}}}await Promise.all(i)}async function Ro(e){let t=new AbortController,i=setTimeout(()=>t.abort(),1e4),s;try{s=await fetch(e,{mode:"cors",signal:t.signal})}finally{clearTimeout(i)}if(!s.ok)throw new Error(\`Failed to fetch image \${e}: HTTP \${s.status}\`);let r=await s.blob();return createImageBitmap(r,{imageOrientation:"from-image",premultiplyAlpha:"none",colorSpaceConversion:"none"})}async function Fo(e){let t=document.createElement("video");return t.crossOrigin="anonymous",t.muted=!0,t.playsInline=!0,t.preload="auto",t.src=e,await new Promise((i,s)=>{let r=()=>{a(),i()},n=()=>{a(),s(new Error(\`Failed to load video \${e}\`))},a=()=>{t.removeEventListener("loadeddata",r),t.removeEventListener("error",n)};t.addEventListener("loadeddata",r),t.addEventListener("error",n)}),t}function Lo(e,t){return new Promise(i=>{let s=Math.max(0,Math.min(e.duration||Number.POSITIVE_INFINITY,t));if(Math.abs(e.currentTime-s)<1e-4){i();return}let r=()=>{e.removeEventListener("seeked",r),i()};e.addEventListener("seeked",r),e.currentTime=s})}async function Oo(e){let t=new AbortController,i=setTimeout(()=>t.abort(),1e4),s;try{s=await fetch(e,{signal:t.signal})}finally{clearTimeout(i)}if(!s.ok)throw new Error(\`fetch failed: \${s.status}\`);let r=await s.text(),n=0,a=[];for(let u of r.split(/\\r?\\n/)){let h=u.trim();if(!h||h.startsWith("#"))continue;let f=h.toUpperCase();if(f.startsWith("TITLE"))continue;if(f.startsWith("DOMAIN_MIN")||f.startsWith("DOMAIN_MAX")){let m=f.startsWith("DOMAIN_MIN")?0:1;if(h.split(/\\s+/).slice(1).map(Number).some(y=>y!==m))throw new Error("non-default DOMAIN not supported");continue}if(f.startsWith("LUT_1D_SIZE"))throw new Error("1D LUTs not supported");if(f.startsWith("LUT_3D_SIZE")){n=parseInt(h.split(/\\s+/)[1]??"0",10);continue}let p=h.split(/\\s+/);if(p.length>=3){let m=Number(p[0]),g=Number(p[1]),y=Number(p[2]);Number.isFinite(m)&&Number.isFinite(g)&&Number.isFinite(y)&&a.push(m,g,y)}}if(!Number.isInteger(n)||n<2||n>256)throw new Error("missing or invalid LUT_3D_SIZE");if(a.length<n*n*n*3)throw new Error("truncated LUT data");let o=new Uint8ClampedArray(n*n*n*4),c=0;for(let u=0;u<n;u++)for(let h=0;h<n;h++)for(let f=0;f<n;f++){let p=(h*n*n+(u*n+f))*4;o[p]=Math.round(Math.min(1,Math.max(0,a[c++]))*255),o[p+1]=Math.round(Math.min(1,Math.max(0,a[c++]))*255),o[p+2]=Math.round(Math.min(1,Math.max(0,a[c++]))*255),o[p+3]=255}return{bitmap:await createImageBitmap(new ImageData(o,n*n,n)),size:n}}var Tu=Object.defineProperty,$o=(e,t)=>{for(var i in t)Tu(e,i,{get:t[i],enumerable:!0})},sa=Math.pow(2,32),ot=Math.pow(2,32)-1,Eu=1,Uu=2,Bu=4,Yr=1,Xr=2,Zr=8,Qr=16,Kr=32,Do=131072,hr=1,Jr=4,fr=256,pr=512,mr=1024,gr=2048,Yo=-1,zi=0,Nt=1,Ii=class Xo extends ArrayBuffer{constructor(t){super(t),this.fileStart=0,this.usedBytes=0}static fromArrayBuffer(t,i){let s=new Xo(t.byteLength);return new Uint8Array(s).set(new Uint8Array(t)),s.fileStart=i,s}},la=(e=>(e[e.BIG_ENDIAN=1]="BIG_ENDIAN",e[e.LITTLE_ENDIAN=2]="LITTLE_ENDIAN",e))(la||{}),Dt=class Ue{constructor(t,i,s){this._byteLength=0,this.failurePosition=0,this._dynamicSize=1,this._byteOffset=i||0,t instanceof ArrayBuffer?this.buffer=Ii.fromArrayBuffer(t,0):t instanceof DataView?(this.dataView=t,i&&(this._byteOffset+=i)):this.buffer=new Ii(t||0),this.position=0,this.endianness=s||2}static{this.ENDIANNESS=new Int8Array(new Int16Array([1]).buffer)[0]>0?2:1}getPosition(){return this.position}_realloc(t){if(!this._dynamicSize)return;let i=this._byteOffset+this.position+t,s=this._buffer.byteLength;if(i<=s){i>this._byteLength&&(this._byteLength=i);return}for(s<1&&(s=1);i>s;)s*=2;let r=new Ii(s),n=new Uint8Array(this._buffer);new Uint8Array(r,0,n.length).set(n),this.buffer=r,this._byteLength=i}_trimAlloc(){if(this._byteLength===this._buffer.byteLength)return;let t=new Ii(this._byteLength),i=new Uint8Array(t),s=new Uint8Array(this._buffer,0,i.length);i.set(s),this.buffer=t}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(t){this._buffer=t,this._dataView=new DataView(t,this._byteOffset),this._byteLength=t.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(t){this._byteOffset=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(t){this._byteOffset=t.byteOffset,this._buffer=Ii.fromArrayBuffer(t.buffer,0),this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+t.byteLength}seek(t){let i=Math.max(0,Math.min(this.byteLength,t));this.position=isNaN(i)||!isFinite(i)?0:i}isEof(){return this.position>=this._byteLength}#e(t){return Array.isArray(t)&&t.length===3&&t[0]==="[]"}mapUint8Array(t){this._realloc(t*1);let i=new Uint8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=t*1,i}readInt32Array(t,i){t=t===void 0?this.byteLength-this.position/4:t;let s=new Int32Array(t);return Ue.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,t*s.BYTES_PER_ELEMENT),Ue.arrayToNative(s,i??this.endianness),this.position+=s.byteLength,s}readInt16Array(t,i){t=t===void 0?this.byteLength-this.position/2:t;let s=new Int16Array(t);return Ue.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,t*s.BYTES_PER_ELEMENT),Ue.arrayToNative(s,i??this.endianness),this.position+=s.byteLength,s}readInt8Array(t){t=t===void 0?this.byteLength-this.position:t;let i=new Int8Array(t);return Ue.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),this.position+=i.byteLength,i}readUint32Array(t,i){t=t===void 0?this.byteLength-this.position/4:t;let s=new Uint32Array(t);return Ue.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,t*s.BYTES_PER_ELEMENT),Ue.arrayToNative(s,i??this.endianness),this.position+=s.byteLength,s}readUint16Array(t,i){t=t===void 0?this.byteLength-this.position/2:t;let s=new Uint16Array(t);return Ue.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,t*s.BYTES_PER_ELEMENT),Ue.arrayToNative(s,i??this.endianness),this.position+=s.byteLength,s}readUint8Array(t){t=t===void 0?this.byteLength-this.position:t;let i=new Uint8Array(t);return Ue.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),this.position+=i.byteLength,i}readFloat64Array(t,i){t=t===void 0?this.byteLength-this.position/8:t;let s=new Float64Array(t);return Ue.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,t*s.BYTES_PER_ELEMENT),Ue.arrayToNative(s,i??this.endianness),this.position+=s.byteLength,s}readFloat32Array(t,i){t=t===void 0?this.byteLength-this.position/4:t;let s=new Float32Array(t);return Ue.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,t*s.BYTES_PER_ELEMENT),Ue.arrayToNative(s,i??this.endianness),this.position+=s.byteLength,s}readInt32(t){let i=this._dataView.getInt32(this.position,(t??this.endianness)===2);return this.position+=4,i}readInt16(t){let i=this._dataView.getInt16(this.position,(t??this.endianness)===2);return this.position+=2,i}readInt8(){let t=this._dataView.getInt8(this.position);return this.position+=1,t}readUint32(t){let i=this._dataView.getUint32(this.position,(t??this.endianness)===2);return this.position+=4,i}readUint16(t){let i=this._dataView.getUint16(this.position,(t??this.endianness)===2);return this.position+=2,i}readUint8(){let t=this._dataView.getUint8(this.position);return this.position+=1,t}readFloat32(t){let i=this._dataView.getFloat32(this.position,(t??this.endianness)===2);return this.position+=4,i}readFloat64(t){let i=this._dataView.getFloat64(this.position,(t??this.endianness)===2);return this.position+=8,i}static memcpy(t,i,s,r,n){let a=new Uint8Array(t,i,n),o=new Uint8Array(s,r,n);a.set(o)}static arrayToNative(t,i){return i===Ue.ENDIANNESS?t:this.flipArrayEndianness(t)}static nativeToEndian(t,i){return i&&Ue.ENDIANNESS===2?t:this.flipArrayEndianness(t)}static flipArrayEndianness(t){let i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<t.byteLength;s+=t.BYTES_PER_ELEMENT)for(let r=s+t.BYTES_PER_ELEMENT-1,n=s;r>n;r--,n++){let a=i[n];i[n]=i[r],i[r]=a}return t}readString(t,i){return i===void 0||i==="ASCII"?No(this.mapUint8Array(t===void 0?this.byteLength-this.position:t)):new TextDecoder(i).decode(this.mapUint8Array(t))}readCString(t){let i=0,s=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),n=t!==void 0?Math.min(t,s):s;for(;i<n&&r[i]!==0;i++);let a=No(this.mapUint8Array(i));return t!==void 0?this.position+=n-i:i!==s&&(this.position+=1),a}readInt64(){return this.readInt32()*sa+this.readUint32()}readUint64(){return this.readUint32()*sa+this.readUint32()}readUint24(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()}save(t){let i=new Blob([this.buffer]);if(typeof window<"u"&&typeof document<"u")if(window.URL&&URL.createObjectURL){let s=window.URL.createObjectURL(i),r=document.createElement("a");document.body.appendChild(r),r.setAttribute("href",s),r.setAttribute("download",t),r.setAttribute("target","_self"),r.click(),window.URL.revokeObjectURL(s),document.body.removeChild(r)}else throw new Error("DataStream.save: Can't create object URL.");return i}get dynamicSize(){return this._dynamicSize}set dynamicSize(t){t||this._trimAlloc(),this._dynamicSize=t}shift(t){let i=new Ii(this._byteLength-t),s=new Uint8Array(i),r=new Uint8Array(this._buffer,t,s.length);s.set(r),this.buffer=i,this.position-=t}writeInt32Array(t,i){if(this._realloc(t.length*4),t instanceof Int32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)Ue.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt32Array(t.length,i);else for(let s=0;s<t.length;s++)this.writeInt32(t[s],i)}writeInt16Array(t,i){if(this._realloc(t.length*2),t instanceof Int16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)Ue.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt16Array(t.length,i);else for(let s=0;s<t.length;s++)this.writeInt16(t[s],i)}writeInt8Array(t){if(this._realloc(t.length*1),t instanceof Int8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)Ue.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt8Array(t.length);else for(let i=0;i<t.length;i++)this.writeInt8(t[i])}writeUint32Array(t,i){if(this._realloc(t.length*4),t instanceof Uint32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)Ue.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint32Array(t.length,i);else for(let s=0;s<t.length;s++)this.writeUint32(t[s],i)}writeUint16Array(t,i){if(this._realloc(t.length*2),t instanceof Uint16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)Ue.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint16Array(t.length,i);else for(let s=0;s<t.length;s++)this.writeUint16(t[s],i)}writeUint8Array(t){if(this._realloc(t.length*1),t instanceof Uint8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)Ue.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint8Array(t.length);else for(let i=0;i<t.length;i++)this.writeUint8(t[i])}writeFloat64Array(t,i){if(this._realloc(t.length*8),t instanceof Float64Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)Ue.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat64Array(t.length,i);else for(let s=0;s<t.length;s++)this.writeFloat64(t[s],i)}writeFloat32Array(t,i){if(this._realloc(t.length*4),t instanceof Float32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)Ue.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat32Array(t.length,i);else for(let s=0;s<t.length;s++)this.writeFloat32(t[s],i)}writeInt64(t,i){this._realloc(8),this._dataView.setBigInt64(this.position,BigInt(t),(i??this.endianness)===2),this.position+=8}writeInt32(t,i){this._realloc(4),this._dataView.setInt32(this.position,t,(i??this.endianness)===2),this.position+=4}writeInt16(t,i){this._realloc(2),this._dataView.setInt16(this.position,t,(i??this.endianness)===2),this.position+=2}writeInt8(t){this._realloc(1),this._dataView.setInt8(this.position,t),this.position+=1}writeUint32(t,i){this._realloc(4),this._dataView.setUint32(this.position,t,(i??this.endianness)===2),this.position+=4}writeUint16(t,i){this._realloc(2),this._dataView.setUint16(this.position,t,(i??this.endianness)===2),this.position+=2}writeUint8(t){this._realloc(1),this._dataView.setUint8(this.position,t),this.position+=1}writeFloat32(t,i){this._realloc(4),this._dataView.setFloat32(this.position,t,(i??this.endianness)===2),this.position+=4}writeFloat64(t,i){this._realloc(8),this._dataView.setFloat64(this.position,t,(i??this.endianness)===2),this.position+=8}writeUCS2String(t,i,s){s===void 0&&(s=t.length);let r;for(r=0;r<t.length&&r<s;r++)this.writeUint16(t.charCodeAt(r),i);for(;r<s;r++)this.writeUint16(0)}writeString(t,i,s){let r=0;if(i===void 0||i==="ASCII")if(s!==void 0){let n=Math.min(t.length,s);for(r=0;r<n;r++)this.writeUint8(t.charCodeAt(r));for(;r<s;r++)this.writeUint8(0)}else for(r=0;r<t.length;r++)this.writeUint8(t.charCodeAt(r));else this.writeUint8Array(new TextEncoder(i).encode(t.substring(0,s)))}writeCString(t,i){let s=0;if(i!==void 0){let r=Math.min(t.length,i);for(s=0;s<r;s++)this.writeUint8(t.charCodeAt(s));for(;s<i;s++)this.writeUint8(0)}else{for(s=0;s<t.length;s++)this.writeUint8(t.charCodeAt(s));this.writeUint8(0)}}writeStruct(t,i){for(let s=0;s<t.length;s++){let[r,n]=t[s],a=i[r];this.writeType(n,a,i)}}writeType(t,i,s){if(typeof t=="function")return t(this,i);if(typeof t=="object"&&!(t instanceof Array))return t.set(this,i,s);let r,n="ASCII",a=this.position,o=t;if(typeof t=="string"&&/:/.test(t)){let c=t.split(":");o=c[0],r=parseInt(c[1])}if(typeof o=="string"&&/,/.test(o)){let c=o.split(",");o=c[0],n=c[1]}switch(o){case"uint8":this.writeUint8(i);break;case"int8":this.writeInt8(i);break;case"uint16":this.writeUint16(i,this.endianness);break;case"int16":this.writeInt16(i,this.endianness);break;case"uint32":this.writeUint32(i,this.endianness);break;case"int32":this.writeInt32(i,this.endianness);break;case"float32":this.writeFloat32(i,this.endianness);break;case"float64":this.writeFloat64(i,this.endianness);break;case"uint16be":this.writeUint16(i,1);break;case"int16be":this.writeInt16(i,1);break;case"uint32be":this.writeUint32(i,1);break;case"int32be":this.writeInt32(i,1);break;case"float32be":this.writeFloat32(i,1);break;case"float64be":this.writeFloat64(i,1);break;case"uint16le":this.writeUint16(i,2);break;case"int16le":this.writeInt16(i,2);break;case"uint32le":this.writeUint32(i,2);break;case"int32le":this.writeInt32(i,2);break;case"float32le":this.writeFloat32(i,2);break;case"float64le":this.writeFloat64(i,2);break;case"cstring":this.writeCString(i,r);break;case"string":this.writeString(i,n,r);break;case"u16string":this.writeUCS2String(i,this.endianness,r);break;case"u16stringle":this.writeUCS2String(i,2,r);break;case"u16stringbe":this.writeUCS2String(i,1,r);break;default:if(this.#e(o)){let[,c]=o;for(let l=0;l<i.length;l++)this.writeType(c,i[l]);break}else{this.writeStruct(o,i);break}}r&&(this.position=a,this._realloc(r),this.position=a+r)}writeUint64(t){let i=Math.floor(t/sa);this.writeUint32(i),this.writeUint32(t&4294967295)}writeUint24(t){this.writeUint8((t&16711680)>>16),this.writeUint8((t&65280)>>8),this.writeUint8(t&255)}adjustUint32(t,i){let s=this.position;this.seek(t),this.writeUint32(i),this.seek(s)}readStruct(t){let i={},s=this.position;for(let r=0;r<t.length;r+=1){let n=t[r][1],a=this.readType(n,i);if(!a){this.failurePosition===0&&(this.failurePosition=this.position),this.position=s;return}i[t[r][0]]=a}return i}readUCS2String(t,i){return String.fromCharCode.apply(void 0,this.readUint16Array(t,i))}readType(t,i){if(typeof t=="function")return t(this,i);if(typeof t=="object"&&!(t instanceof Array))return t.get(this,i);if(t instanceof Array&&t.length!==3)return this.readStruct(t);let s,r,n="ASCII",a=this.position,o=t;if(typeof o=="string"&&/:/.test(o)){let c=o.split(":");o=c[0],r=parseInt(c[1])}if(typeof o=="string"&&/,/.test(o)){let c=o.split(",");o=c[0],n=c[1]}switch(o){case"uint8":s=this.readUint8();break;case"int8":s=this.readInt8();break;case"uint16":s=this.readUint16(this.endianness);break;case"int16":s=this.readInt16(this.endianness);break;case"uint32":s=this.readUint32(this.endianness);break;case"int32":s=this.readInt32(this.endianness);break;case"float32":s=this.readFloat32(this.endianness);break;case"float64":s=this.readFloat64(this.endianness);break;case"uint16be":s=this.readUint16(1);break;case"int16be":s=this.readInt16(1);break;case"uint32be":s=this.readUint32(1);break;case"int32be":s=this.readInt32(1);break;case"float32be":s=this.readFloat32(1);break;case"float64be":s=this.readFloat64(1);break;case"uint16le":s=this.readUint16(2);break;case"int16le":s=this.readInt16(2);break;case"uint32le":s=this.readUint32(2);break;case"int32le":s=this.readInt32(2);break;case"float32le":s=this.readFloat32(2);break;case"float64le":s=this.readFloat64(2);break;case"cstring":s=this.readCString(r);break;case"string":s=this.readString(r,n);break;case"u16string":s=this.readUCS2String(r,this.endianness);break;case"u16stringle":s=this.readUCS2String(r,2);break;case"u16stringbe":s=this.readUCS2String(r,1);break;default:if(this.#e(o)){let[,c,l]=o,u=typeof l=="function"?l(i,this,o):typeof l=="string"&&i[l]!==void 0?parseInt(i[l]):typeof l=="number"?l:l==="*"?void 0:parseInt(l);if(typeof c=="string"){let h=c.replace(/(le|be)$/,""),f;switch(/le$/.test(c)?f=2:/be$/.test(c)&&(f=1),h){case"uint8":s=this.readUint8Array(u);break;case"uint16":s=this.readUint16Array(u,f);break;case"uint32":s=this.readUint32Array(u,f);break;case"int8":s=this.readInt8Array(u);break;case"int16":s=this.readInt16Array(u,f);break;case"int32":s=this.readInt32Array(u,f);break;case"float32":s=this.readFloat32Array(u,f);break;case"float64":s=this.readFloat64Array(u,f);break;case"cstring":case"utf16string":case"string":if(u){s=new Array(u);for(let p=0;p<u;p++)s[p]=this.readType(c,i)}else for(s=[];!this.isEof();){let p=this.readType(c,i);if(!p)break;s.push(p)}break}}else if(u){s=new Array(u);for(let h=0;h<u;h++){let f=this.readType(c,i);if(!f)return;s[h]=f}}else for(s=[];;){let h=this.position;try{let f=this.readType(c,i);if(!f){this.position=h;break}s.push(f)}catch{this.position=h;break}}break}}return r&&(this.position=a+r),s}mapInt32Array(t,i){this._realloc(t*4);let s=new Int32Array(this._buffer,this.byteOffset+this.position,t);return Ue.arrayToNative(s,i??this.endianness),this.position+=t*4,s}mapInt16Array(t,i){this._realloc(t*2);let s=new Int16Array(this._buffer,this.byteOffset+this.position,t);return Ue.arrayToNative(s,i??this.endianness),this.position+=t*2,s}mapInt8Array(t,i){this._realloc(t*1);let s=new Int8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=t*1,s}mapUint32Array(t,i){this._realloc(t*4);let s=new Uint32Array(this._buffer,this.byteOffset+this.position,t);return Ue.arrayToNative(s,i??this.endianness),this.position+=t*4,s}mapUint16Array(t,i){this._realloc(t*2);let s=new Uint16Array(this._buffer,this.byteOffset+this.position,t);return Ue.arrayToNative(s,i??this.endianness),this.position+=t*2,s}mapFloat64Array(t,i){this._realloc(t*8);let s=new Float64Array(this._buffer,this.byteOffset+this.position,t);return Ue.arrayToNative(s,i??this.endianness),this.position+=t*8,s}mapFloat32Array(t,i){this._realloc(t*4);let s=new Float32Array(this._buffer,this.byteOffset+this.position,t);return Ue.arrayToNative(s,i??this.endianness),this.position+=t*4,s}};function No(e){let t=[];for(let i=0;i<e.length;i++)t[i]=e[i];return String.fromCharCode.apply(void 0,t)}var jr=new Date,en=4,Ho=3,Go=2,Vo=1,wi=en,k={setLogLevel(e){e===this.debug?wi=Vo:e===this.info?wi=Go:e===this.warn?wi=Ho:(this.error,wi=en)},debug(e,t){console.debug===void 0&&(console.debug=console.log),Vo>=wi&&console.debug("["+k.getDurationString(new Date().getTime()-jr.getTime(),1e3)+"]","["+e+"]",t)},log(e,t){this.debug(e.msg)},info(e,t){Go>=wi&&console.info("["+k.getDurationString(new Date().getTime()-jr.getTime(),1e3)+"]","["+e+"]",t)},warn(e,t){Ho>=wi&&console.warn("["+k.getDurationString(new Date().getTime()-jr.getTime(),1e3)+"]","["+e+"]",t)},error(e,t,i){i?.onError?i.onError(e,t):en>=wi&&console.error("["+k.getDurationString(new Date().getTime()-jr.getTime(),1e3)+"]","["+e+"]",t)},getDurationString(e,t){let i;function s(l,u){let f=(""+l).split(".");for(;f[0].length<u;)f[0]="0"+f[0];return f.join(".")}e<0?(i=!0,e=-e):i=!1;let n=e/(t||1),a=Math.floor(n/3600);n-=a*3600;let o=Math.floor(n/60);n-=o*60;let c=n*1e3;return n=Math.floor(n),c-=n*1e3,c=Math.floor(c),(i?"-":"")+a+":"+s(o,2)+":"+s(n,2)+"."+s(c,3)},printRanges(e){let t=e.length;if(t>0){let i="";for(let s=0;s<t;s++)s>0&&(i+=","),i+="["+k.getDurationString(e.start(s))+","+k.getDurationString(e.end(s))+"]";return i}else return"(empty)"}};function Au(e,t){k.debug("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));let i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer}var tn=class extends Dt{constructor(e){super(new ArrayBuffer,0,1),this.buffers=[],this.bufferIndex=-1,e&&(this.insertBuffer(e),this.bufferIndex=0)}initialized(){if(this.bufferIndex>-1)return!0;if(this.buffers.length>0){let e=this.buffers[0];return e.fileStart===0?(this.buffer=e,this.bufferIndex=0,k.debug("MultiBufferStream","Stream ready for parsing"),!0):(k.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)}else return k.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1}reduceBuffer(e,t,i){let s=new Uint8Array(i);return s.set(new Uint8Array(e,t,i)),s.buffer.fileStart=e.fileStart+t,s.buffer.usedBytes=0,s.buffer}insertBuffer(e){let t=!0,i=0;for(;i<this.buffers.length;i++){let s=this.buffers[i];if(e.fileStart<=s.fileStart){if(e.fileStart===s.fileStart)if(e.byteLength>s.byteLength){this.buffers.splice(i,1),i--;continue}else k.warn("MultiBufferStream","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring");else e.fileStart+e.byteLength<=s.fileStart||(e=this.reduceBuffer(e,0,s.fileStart-e.fileStart)),k.debug("MultiBufferStream","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")"),this.buffers.splice(i,0,e),i===0&&(this.buffer=e);t=!1;break}else if(e.fileStart<s.fileStart+s.byteLength){let r=s.fileStart+s.byteLength-e.fileStart,n=e.byteLength-r;if(n>0)e=this.reduceBuffer(e,r,n);else{t=!1;break}}}t&&(k.debug("MultiBufferStream","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")"),this.buffers.push(e),i===0&&(this.buffer=e))}logBufferLevel(e){let t=[],i="",s,r=0,n=0;for(let o=0;o<this.buffers.length;o++){let c=this.buffers[o];o===0?(s={start:c.fileStart,end:c.fileStart+c.byteLength},t.push(s),i+="["+s.start+"-"):s.end===c.fileStart?s.end=c.fileStart+c.byteLength:(s={start:c.fileStart,end:c.fileStart+c.byteLength},i+=t[t.length-1].end-1+"], ["+s.start+"-",t.push(s)),r+=c.usedBytes,n+=c.byteLength}t.length>0&&(i+=s.end-1+"]");let a=e?k.info:k.debug;this.buffers.length===0?a("MultiBufferStream","No more buffer in memory"):a("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+r+"/"+n+" bytes), continuous ranges: "+i)}cleanBuffers(){for(let e=0;e<this.buffers.length;e++){let t=this.buffers[e];t.usedBytes===t.byteLength&&(k.debug("MultiBufferStream","Removing buffer #"+e),this.buffers.splice(e,1),e--)}}mergeNextBuffer(){if(this.bufferIndex+1<this.buffers.length){let e=this.buffers[this.bufferIndex+1];if(e.fileStart===this.buffer.fileStart+this.buffer.byteLength){let t=this.buffer.byteLength,i=this.buffer.usedBytes,s=this.buffer.fileStart;return this.buffers[this.bufferIndex]=Au(this.buffer,e),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=i,this.buffer.fileStart=s,k.debug("ISOFile","Concatenating buffer for box parsing (length: "+t+"->"+this.buffer.byteLength+")"),!0}else return!1}else return!1}findPosition(e,t,i){let s=-1,r=e===!0?0:this.bufferIndex;for(;r<this.buffers.length;){let a=this.buffers[r];if(a&&a.fileStart<=t)s=r,i&&(a.fileStart+a.byteLength<=t?a.usedBytes=a.byteLength:a.usedBytes=t-a.fileStart,this.logBufferLevel());else break;r++}if(s===-1)return-1;let n=this.buffers[s];return n.fileStart+n.byteLength>=t?(k.debug("MultiBufferStream","Found position in existing buffer #"+s),s):-1}findEndContiguousBuf(e){let t=e!==void 0?e:this.bufferIndex,i=this.buffers[t];if(this.buffers.length>t+1)for(let s=t+1;s<this.buffers.length;s++){let r=this.buffers[s];if(r.fileStart===i.fileStart+i.byteLength)i=r;else break}return i.fileStart+i.byteLength}getEndFilePositionAfter(e){let t=this.findPosition(!0,e,!1);return t!==-1?this.findEndContiguousBuf(t):e}addUsedBytes(e){this.buffer.usedBytes+=e,this.logBufferLevel()}setAllUsedBytes(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()}seek(e,t,i){let s=this.findPosition(t,e,i);return s!==-1?(this.buffer=this.buffers[s],this.bufferIndex=s,this.position=e-this.buffer.fileStart,k.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(k.debug("MultiBufferStream","Position "+e+" not found in buffered data"),!1)}getPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.position}getLength(){return this.byteLength}getEndPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.byteLength}getAbsoluteEndPosition(){if(this.buffers.length===0)return 0;let e=this.buffers[this.buffers.length-1];return e.fileStart+e.byteLength}},Wo=class{constructor(e){if(this.position=0,e instanceof ArrayBuffer)this.buffer=e,this.dataview=new DataView(e);else throw new Error("Needs an array buffer")}getPosition(){return this.position}getEndPosition(){return this.buffer.byteLength}getLength(){return this.buffer.byteLength}seek(e){let t=Math.max(0,Math.min(this.buffer.byteLength,e));return this.position=isNaN(t)||!isFinite(t)?0:t,!0}isEos(){return this.getPosition()>=this.getEndPosition()}readAnyInt(e,t){let i=0;if(this.position+e<=this.buffer.byteLength){switch(e){case 1:t?i=this.dataview.getInt8(this.position):i=this.dataview.getUint8(this.position);break;case 2:t?i=this.dataview.getInt16(this.position):i=this.dataview.getUint16(this.position);break;case 3:if(t)throw new Error("No method for reading signed 24 bits values");i=this.dataview.getUint8(this.position)<<16,i|=this.dataview.getUint8(this.position+1)<<8,i|=this.dataview.getUint8(this.position+2);break;case 4:t?i=this.dataview.getInt32(this.position):i=this.dataview.getUint32(this.position);break;case 8:if(t)throw new Error("No method for reading signed 64 bits values");i=this.dataview.getUint32(this.position)<<32,i|=this.dataview.getUint32(this.position+4);break;default:throw new Error("readInt method not implemented for size: "+e)}return this.position+=e,i}else throw new Error("Not enough bytes in buffer")}readUint8(){return this.readAnyInt(1,!1)}readUint16(){return this.readAnyInt(2,!1)}readUint24(){return this.readAnyInt(3,!1)}readUint32(){return this.readAnyInt(4,!1)}readUint64(){return this.readAnyInt(8,!1)}readString(e){if(this.position+e<=this.buffer.byteLength){let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(this.readUint8());return t}else throw new Error("Not enough bytes in buffer")}readCString(){let e=[];for(;;){let t=this.readUint8();if(t!==0)e.push(t);else break}return String.fromCharCode.apply(void 0,e)}readInt8(){return this.readAnyInt(1,!0)}readInt16(){return this.readAnyInt(2,!0)}readInt32(){return this.readAnyInt(4,!0)}readInt64(){return this.readAnyInt(8,!1)}readUint8Array(e){let t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=this.readUint8();return t}readInt16Array(e){let t=new Int16Array(e);for(let i=0;i<e;i++)t[i]=this.readInt16();return t}readUint16Array(e){let t=new Int16Array(e);for(let i=0;i<e;i++)t[i]=this.readUint16();return t}readUint32Array(e){let t=new Uint32Array(e);for(let i=0;i<e;i++)t[i]=this.readUint32();return t}readInt32Array(e){let t=new Int32Array(e);for(let i=0;i<e;i++)t[i]=this.readInt32();return t}},O=class{constructor(e=0){this.size=e}static{this.registryId=Symbol.for("BoxIdentifier")}#e;get type(){return this.constructor.fourcc??this.#e}set type(e){this.#e=e}addBox(e){return this.boxes||(this.boxes=[]),this.boxes.push(e),this[e.type+"s"]?this[e.type+"s"].push(e):this[e.type]=e,e}set(e,t){return this[e]=t,this}addEntry(e,t){let i=t||"entries";return this[i]||(this[i]=[]),this[i].push(e),this}writeHeader(e,t){if(this.size+=8,(this.size>ot||this.original_size===1)&&(this.size+=8),this.type==="uuid"&&(this.size+=16),k.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.getPosition()+(t||"")),this.original_size===0?e.writeUint32(0):this.size>ot||this.original_size===1?e.writeUint32(1):(this.sizePosition=e.getPosition(),e.writeUint32(this.size)),e.writeString(this.type,void 0,4),this.type==="uuid"){let i=new Uint8Array(16);for(let s=0;s<16;s++)i[s]=parseInt(this.uuid.substring(s*2,s*2+2),16);e.writeUint8Array(i)}(this.size>ot||this.original_size===1)&&(this.sizePosition=e.getPosition(),e.writeUint64(this.size))}write(e){if(this.type==="mdat"){let t=this;if(t.stream){this.size=t.stream.getAbsoluteEndPosition(),this.writeHeader(e);for(let i of t.stream.buffers){let s=new Uint8Array(i);e.writeUint8Array(s)}}else t.data&&(this.size=t.data.length,this.writeHeader(e),e.writeUint8Array(t.data))}else this.size=this.data?this.data.length:0,this.writeHeader(e),this.data&&e.writeUint8Array(this.data)}printHeader(e){this.size+=8,this.size>ot&&(this.size+=8),this.type==="uuid"&&(this.size+=16),e.log(e.indent+"size:"+this.size),e.log(e.indent+"type:"+this.type)}print(e){this.printHeader(e)}parse(e){this.type!=="mdat"?this.data=e.readUint8Array(this.size-this.hdr_size):this.size===0?e.seek(e.getEndPosition()):e.seek(this.start+this.size)}parseDataAndRewind(e){this.data=e.readUint8Array(this.size-this.hdr_size),e.seek(this.start+this.hdr_size)}parseLanguage(e){this.language=e.readUint16();let t=[];t[0]=this.language>>10&31,t[1]=this.language>>5&31,t[2]=this.language&31,this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96)}computeSize(e){let t=e||new tn;t.endianness=1,this.write(t)}isEndOfBox(e){let t=e.getPosition(),i=this.start+this.size;return t===i}},B=class extends O{constructor(){super(...arguments),this.flags=0,this.version=0}writeHeader(e){this.size+=4,super.writeHeader(e," v="+this.version+" f="+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)}printHeader(e){this.size+=4,super.printHeader(e),e.log(e.indent+"version:"+this.version),e.log(e.indent+"flags:"+this.flags)}parseDataAndRewind(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.seek(this.start+this.hdr_size)}parseFullHeader(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4}parse(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)}},tt=class{constructor(e){this.grouping_type=e}static{this.registryId=Symbol.for("SampleGroupEntryIdentifier")}write(e){e.writeUint8Array(this.data)}parse(e){k.warn("BoxParser",\`Unknown sample group type: '\${this.grouping_type}'\`),this.data=e.readUint8Array(this.description_length)}},Cu=class extends B{parse(e){this.parseFullHeader(e),this.track_group_id=e.readUint32()}},Mu=class extends O{constructor(e,t,i,s,r){super(t),this.box_name=i,this.hdr_size=s,this.start=r,this.type=e}parse(e){this.from_item_ID=e.readUint16();let t=e.readUint16();this.references=[];for(let i=0;i<t;i++)this.references[i]={to_item_ID:e.readUint16()}}},zu=class extends O{constructor(e,t,i,s,r){super(t),this.box_name=i,this.hdr_size=s,this.start=r,this.type=e}parse(e){this.from_item_ID=e.readUint32();let t=e.readUint16();this.references=[];for(let i=0;i<t;i++)this.references[i]={to_item_ID:e.readUint32()}}},Pu=class extends O{constructor(e,t,i,s){super(t),this.hdr_size=i,this.start=s,this.type=e}parse(e){this.track_ids=e.readUint32Array((this.size-this.hdr_size)/4)}write(e){this.size=this.track_ids.length*4,this.writeHeader(e),e.writeUint32Array(this.track_ids)}},na=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],Iu=["compatible_brands","matrix","opcolor","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"];function Ru(e,t){if(e&&!t)return!1;let i;for(i in e)if(!na.find(s=>s===i)){if(e[i]instanceof O||t[i]instanceof O)continue;if(typeof e[i]>"u"||typeof t[i]>"u")continue;if(typeof e[i]=="function"||typeof t[i]=="function")continue;if("subBoxNames"in e&&e.subBoxNames.indexOf(i.slice(0,4))>-1||"subBoxNames"in t&&t.subBoxNames.indexOf(i.slice(0,4))>-1)continue;if(i==="data"||i==="start"||i==="size"||i==="creation_time"||i==="modification_time")continue;if(Iu.find(s=>s===i))continue;if(e[i]!==t[i])return!1}return!0}function Zo(e,t){if(!Ru(e,t))return!1;for(let i=0;i<na.length;i++){let s=na[i];if(e[s]&&t[s]&&!Zo(e[s],t[s]))return!1}return!0}function da(e){let t=e;for(;t;){if("registryId"in t)return t.registryId;t=Object.getPrototypeOf(t)}}var Fu=e=>{let t=Symbol.for("SampleGroupEntryIdentifier");return da(e)===t},Lu=e=>{let t=Symbol.for("SampleEntryIdentifier");return da(e)===t},Ou=e=>{let t=Symbol.for("BoxIdentifier");return da(e)===t},zt={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};function Du(e){let t={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};for(let[i,s]of Object.entries(e)){if(Fu(s)){let r="grouping_type"in s?s.grouping_type:void 0;if(!r)throw new Error(\`SampleGroupEntry class \${i} does not have a valid static grouping_type. Please ensure it is defined correctly.\`);if(r in t.sampleGroupEntry)throw new Error(\`SampleGroupEntry class \${i} has a grouping_type that is already registered. Please ensure it is unique.\`);t.sampleGroupEntry[r]=s;continue}if(Lu(s)){let r="fourcc"in s?s.fourcc:void 0;if(!r)throw new Error(\`SampleEntry class \${i} does not have a valid static fourcc. Please ensure it is defined correctly.\`);if(r in t.sampleEntry)throw new Error(\`SampleEntry class \${i} has a fourcc that is already registered. Please ensure it is unique.\`);t.sampleEntry[r]=s;continue}if(Ou(s)){let r="fourcc"in s?s.fourcc:void 0,n="uuid"in s?s.uuid:void 0;if(r==="uuid"){if(!n)throw new Error(\`Box class \${i} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.\`);if(n in t.uuid)throw new Error(\`Box class \${i} has a uuid that is already registered. Please ensure it is unique.\`);t.uuid[n]=s;continue}t.box[r]=s;continue}throw new Error(\`Box class \${i} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.\`)}return zt.uuid={...t.uuid},zt.sampleEntry={...t.sampleEntry},zt.sampleGroupEntry={...t.sampleGroupEntry},zt.box={...t.box},zt}var an={};function Nu(e){return Object.entries(e).forEach(([t,i])=>an[t]=i),an}function Hu(e){return Xi(e)}function Xi(e){let t="";for(let i=0;i<16;i++){let s=e.readUint8().toString(16);t+=s.length===1?"0"+s:s}return t}function li(e,t,i){let s,r,n=e.getPosition(),a=0,o;if(e.getEndPosition()-n<8)return k.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:zi};if(i&&i<8)return k.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:zi};let c=e.readUint32(),l=e.readString(4);if(l.length!==4||!/^[\\x20-\\x7E]{4}$/.test(l))return k.error("BoxParser",\`Invalid box type: '\${l}'\`),{code:Yo,start:n,type:l};let u=l;if(k.debug("BoxParser","Found box of type '"+l+"' and size "+c+" at position "+n),a=8,l==="uuid"){if(e.getEndPosition()-e.getPosition()<16||i-a<16)return e.seek(n),k.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:zi};o=Hu(e),a+=16,u=o}if(c===1){if(e.getEndPosition()-e.getPosition()<8||i&&i-a<8)return e.seek(n),k.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+l+'" box'),{code:zi};r=c,c=e.readUint64(),a+=8}else if(c===0){if(i)c=i;else if(l!=="mdat")return k.error("BoxParser","Unlimited box size not supported for type: '"+l+"'"),s=new O(c),s.type=l,{code:Nt,box:s,size:s.size}}if(c!==0&&c<a)return k.error("BoxParser","Box of type "+l+" has an invalid size "+c+" (too small to be a box)"),{code:zi,type:l,size:c,hdr_size:a,start:n};if(c!==0&&i&&c>i)return k.error("BoxParser","Box of type '"+l+"' has a size "+c+" greater than its container size "+i),{code:zi,type:l,size:c,hdr_size:a,start:n};if(c!==0&&n+c>e.getEndPosition())return e.seek(n),k.info("BoxParser","Not enough data in stream to parse the entire '"+l+"' box"),{code:zi,type:l,size:c,hdr_size:a,start:n,original_size:r};if(t)return{code:Nt,type:l,size:c,hdr_size:a,start:n};l in zt.box?s=new zt.box[l](c):l!=="uuid"?(k.warn("BoxParser",\`Unknown box type: '\${l}'\`),s=new O(c),s.type=l,s.has_unparsed_data=!0):o in zt.uuid?s=new zt.uuid[o](c):(k.warn("BoxParser",\`Unknown UUID box type: '\${o}'\`),s=new O(c),s.type=l,s.uuid=o,s.has_unparsed_data=!0),s.original_size=r,s.hdr_size=a,s.start=n,s.write===O.prototype.write&&s.type!=="mdat"&&(k.info("BoxParser","'"+u+"' box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(e)),s.parse(e);let h=e.getPosition()-(s.start+s.size);return h<0?(k.warn("BoxParser","Parsing of box '"+u+"' did not read the entire indicated box data size (missing "+-h+" bytes), seeking forward"),e.seek(s.start+s.size)):h>0&&s.size!==0&&(k.error("BoxParser","Parsing of box '"+u+"' read "+h+" more bytes than the indicated box data size, seeking backwards"),e.seek(s.start+s.size)),{code:Nt,box:s,size:s.size}}var Be=class extends O{write(e){if(this.size=0,this.writeHeader(e),this.boxes)for(let t=0;t<this.boxes.length;t++)this.boxes[t]&&(this.boxes[t].write(e),this.size+=this.boxes[t].size);k.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)}print(e){this.printHeader(e);for(let t=0;t<this.boxes.length;t++)if(this.boxes[t]){let i=e.indent;e.indent+=" ",this.boxes[t].print(e),e.indent=i}}parse(e){let t;for(;e.getPosition()<this.start+this.size;)if(t=li(e,!1,this.size-(e.getPosition()-this.start)),t.code===Nt){let i=t.box;if(this.boxes||(this.boxes=[]),this.boxes.push(i),this.subBoxNames&&this.subBoxNames.indexOf(i.type)!==-1){let s=this.subBoxNames[this.subBoxNames.indexOf(i.type)]+"s";this[s]||(this[s]=[]),this[s].push(i)}else{let s=i.type!=="uuid"?i.type:i.uuid;this[s]?k.warn("ContainerBox",\`Box of type \${s} already exists in container box \${this.type}.\`):this[s]=i}}else return}},Si=class extends Be{constructor(e,t,i){super(e),this.hdr_size=t,this.start=i}static{this.registryId=Symbol.for("SampleEntryIdentifier")}isVideo(){return!1}isAudio(){return!1}isSubtitle(){return!1}isMetadata(){return!1}isHint(){return!1}getCodec(){return this.type.replace(".","")}getWidth(){return""}getHeight(){return""}getChannelCount(){return""}getSampleRate(){return""}getSampleSize(){return""}parseHeader(e){e.readUint8Array(6),this.data_reference_index=e.readUint16(),this.hdr_size+=8}parse(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)}parseDataAndRewind(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,e.seek(this.start+this.hdr_size)}parseFooter(e){super.parse(e)}writeHeader(e){this.size=8,super.writeHeader(e),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint16(this.data_reference_index)}writeFooter(e){if(this.boxes)for(let t=0;t<this.boxes.length;t++)this.boxes[t].write(e),this.size+=this.boxes[t].size;k.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)}write(e){this.writeHeader(e),e.writeUint8Array(this.data),this.size+=this.data.length,k.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)}},qo=class extends Si{},Ms=class extends Si{isMetadata(){return!0}},Zi=class extends Si{isSubtitle(){return!0}},Gu=class extends Si{},$e=class extends Si{parse(e){this.parseHeader(e),e.readUint16(),e.readUint16(),e.readUint32Array(3),this.width=e.readUint16(),this.height=e.readUint16(),this.horizresolution=e.readUint32(),this.vertresolution=e.readUint32(),e.readUint32(),this.frame_count=e.readUint16();let t=Math.min(31,e.readUint8());this.compressorname=e.readString(t),t<31&&e.readString(31-t),this.depth=e.readUint16(),e.readUint16(),this.parseFooter(e)}isVideo(){return!0}getWidth(){return this.width}getHeight(){return this.height}write(e){this.writeHeader(e),this.size+=2*7+6*4+32,e.writeUint16(0),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.width),e.writeUint16(this.height),e.writeUint32(this.horizresolution),e.writeUint32(this.vertresolution),e.writeUint32(0),e.writeUint16(this.frame_count),e.writeUint8(Math.min(31,this.compressorname.length)),e.writeString(this.compressorname,void 0,31),e.writeUint16(this.depth),e.writeInt16(-1),this.writeFooter(e)}},Pt=class extends Si{parse(e){this.parseHeader(e),e.readUint32Array(2),this.channel_count=e.readUint16(),this.samplesize=e.readUint16(),e.readUint16(),e.readUint16(),this.samplerate=e.readUint32()/65536,this.parseFooter(e)}isAudio(){return!0}getChannelCount(){return this.channel_count}getSampleRate(){return this.samplerate}getSampleSize(){return this.samplesize}write(e){this.writeHeader(e),this.size+=2*4+3*4,e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.channel_count),e.writeUint16(this.samplesize),e.writeUint16(0),e.writeUint16(0),e.writeUint32(this.samplerate<<16),this.writeFooter(e)}},ua=class extends Si{parse(e){this.parseHeader(e),this.parseFooter(e)}write(e){this.writeHeader(e),this.writeFooter(e)}},jo=class extends Array{toString(){let e="<table class='inner-table'>";e+="<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",e+="<tbody>";for(let t=0;t<this.length;t++){let i=this[t];e+="<tr>",e+="<td>"+i.length+"</td>",e+="<td>",e+=i.data.reduce(function(s,r){return s+r.toString(16).padStart(2,"0")},"0x"),e+="</td></tr>"}return e+="</tbody></table>",e}},Qo=class extends O{constructor(){super(...arguments),this.box_name="AVCConfigurationBox"}static{this.fourcc="avcC"}parse(e){this.configurationVersion=e.readUint8(),this.AVCProfileIndication=e.readUint8(),this.profile_compatibility=e.readUint8(),this.AVCLevelIndication=e.readUint8(),this.lengthSizeMinusOne=e.readUint8()&3,this.nb_SPS_nalus=e.readUint8()&31;let t=this.size-this.hdr_size-6;this.SPS=new jo;for(let i=0;i<this.nb_SPS_nalus;i++){let s=e.readUint16();this.SPS.push({length:s,data:e.readUint8Array(s)}),t-=2+s}this.nb_PPS_nalus=e.readUint8(),t--,this.PPS=new jo;for(let i=0;i<this.nb_PPS_nalus;i++){let s=e.readUint16();this.PPS.push({length:s,data:e.readUint8Array(s)}),t-=2+s}t>0&&(this.ext=e.readUint8Array(t))}write(e){this.size=7;for(let t=0;t<this.SPS.length;t++)this.size+=2+this.SPS[t].length;for(let t=0;t<this.PPS.length;t++)this.size+=2+this.PPS[t].length;this.ext&&(this.size+=this.ext.length),this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8(this.AVCProfileIndication),e.writeUint8(this.profile_compatibility),e.writeUint8(this.AVCLevelIndication),e.writeUint8(this.lengthSizeMinusOne+252),e.writeUint8(this.SPS.length+224);for(let t=0;t<this.SPS.length;t++)e.writeUint16(this.SPS[t].length),e.writeUint8Array(this.SPS[t].data);e.writeUint8(this.PPS.length);for(let t=0;t<this.PPS.length;t++)e.writeUint16(this.PPS[t].length),e.writeUint8Array(this.PPS[t].data);this.ext&&e.writeUint8Array(this.ext)}},sn=class extends O{constructor(){super(...arguments),this.box_name="MediaDataBox"}static{this.fourcc="mdat"}},Vu=class extends O{constructor(){super(...arguments),this.box_name="ItemDataBox"}static{this.fourcc="idat"}},Wu=class extends O{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}static{this.fourcc="free"}},qu=class extends O{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}static{this.fourcc="skip"}},Ko=class extends B{constructor(){super(...arguments),this.box_name="HintMediaHeaderBox"}static{this.fourcc="hmhd"}},rn=class extends B{constructor(){super(...arguments),this.box_name="NullMediaHeaderBox"}static{this.fourcc="nmhd"}},ju=class extends B{constructor(){super(...arguments),this.box_name="ObjectDescriptorBox"}static{this.fourcc="iods"}},$u=class extends B{constructor(){super(...arguments),this.box_name="XMLBox"}static{this.fourcc="xml "}},Yu=class extends B{constructor(){super(...arguments),this.box_name="BinaryXMLBox"}static{this.fourcc="bxml"}},Xu=class extends B{constructor(){super(...arguments),this.box_name="ItemProtectionBox",this.sinfs=[]}static{this.fourcc="ipro"}get protections(){return this.sinfs}},aa=class extends Be{constructor(){super(...arguments),this.box_name="MovieBox",this.traks=[],this.psshs=[],this.subBoxNames=["trak","pssh"]}static{this.fourcc="moov"}},Jo=class extends Be{constructor(){super(...arguments),this.box_name="TrackBox",this.samples=[]}static{this.fourcc="trak"}},Zu=class extends Be{constructor(){super(...arguments),this.box_name="EditBox"}static{this.fourcc="edts"}},ec=class extends Be{constructor(){super(...arguments),this.box_name="MediaBox"}static{this.fourcc="mdia"}},tc=class extends Be{constructor(){super(...arguments),this.box_name="MediaInformationBox"}static{this.fourcc="minf"}},ic=class extends Be{constructor(){super(...arguments),this.box_name="DataInformationBox"}static{this.fourcc="dinf"}},sc=class extends Be{constructor(){super(...arguments),this.box_name="SampleTableBox",this.sgpds=[],this.sbgps=[],this.subBoxNames=["sgpd","sbgp"]}static{this.fourcc="stbl"}},oa=class extends Be{constructor(){super(...arguments),this.box_name="MovieExtendsBox",this.trexs=[],this.subBoxNames=["trex"]}static{this.fourcc="mvex"}},rc=class extends Be{constructor(){super(...arguments),this.box_name="MovieFragmentBox",this.trafs=[],this.subBoxNames=["traf"]}static{this.fourcc="moof"}},nc=class extends Be{constructor(){super(...arguments),this.box_name="TrackFragmentBox",this.truns=[],this.sgpds=[],this.sbgps=[],this.subBoxNames=["trun","sgpd","sbgp"]}static{this.fourcc="traf"}},Qu=class extends Be{constructor(){super(...arguments),this.box_name="VTTCueBox"}static{this.fourcc="vttc"}},Ku=class extends Be{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessBox",this.tfras=[],this.subBoxNames=["tfra"]}static{this.fourcc="mfra"}},Ju=class extends Be{constructor(){super(...arguments),this.box_name="AdditionalMetadataContainerBox"}static{this.fourcc="meco"}},eh=class extends Be{constructor(){super(...arguments),this.box_name="trackhintinformation",this.subBoxNames=["sdp ","rtp "]}static{this.fourcc="hnti"}},th=class extends Be{constructor(){super(...arguments),this.box_name="hintstatisticsbox",this.maxrs=[],this.subBoxNames=["maxr"]}static{this.fourcc="hinf"}},ih=class extends Be{constructor(){super(...arguments),this.box_name="SubTrackBox"}static{this.fourcc="strk"}},sh=class extends Be{constructor(){super(...arguments),this.box_name="SubTrackDefinitionBox"}static{this.fourcc="strd"}},rh=class extends Be{constructor(){super(...arguments),this.box_name="ProtectionSchemeInfoBox"}static{this.fourcc="sinf"}},nh=class extends Be{constructor(){super(...arguments),this.box_name="RestrictedSchemeInfoBox"}static{this.fourcc="rinf"}},ah=class extends Be{constructor(){super(...arguments),this.box_name="SchemeInformationBox"}static{this.fourcc="schi"}},oh=class extends Be{constructor(){super(...arguments),this.box_name="TrackGroupBox"}static{this.fourcc="trgr"}},ch=class extends Be{constructor(){super(...arguments),this.box_name="UserDataBox",this.kinds=[],this.strks=[],this.subBoxNames=["kind","strk"]}static{this.fourcc="udta"}},lh=class extends Be{constructor(){super(...arguments),this.box_name="ItemPropertiesBox",this.ipmas=[],this.subBoxNames=["ipma"]}static{this.fourcc="iprp"}},dh=class extends Be{constructor(){super(...arguments),this.box_name="ItemPropertyContainerBox",this.hvcCs=[],this.ispes=[],this.claps=[],this.irots=[],this.subBoxNames=["hvcC","ispe","clap","irot"]}static{this.fourcc="ipco"}},uh=class extends Be{constructor(){super(...arguments),this.box_name="GroupsListBox"}static{this.fourcc="grpl"}},hh=class extends Be{constructor(){super(...arguments),this.box_name="J2KHeaderInfoBox"}static{this.fourcc="j2kH"}},fh=class extends Be{constructor(){super(...arguments),this.box_name="ExtendedTypeBox",this.tycos=[],this.subBoxNames=["tyco"]}static{this.fourcc="etyp"}},ph=class extends Be{constructor(){super(...arguments),this.box_name="ProjectedOmniVideoBox",this.subBoxNames=["prfr"]}static{this.fourcc="povd"}},ac=class extends B{constructor(){super(...arguments),this.box_name="DataReferenceBox"}static{this.fourcc="dref"}parse(e){this.parseFullHeader(e),this.entries=[];let t=e.readUint32();for(let i=0;i<t;i++){let s=li(e,!1,this.size-(e.getPosition()-this.start));if(s.code===Nt){let r=s.box;this.entries.push(r)}else return}}write(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.entries.length);for(let t=0;t<this.entries.length;t++)this.entries[t].write(e),this.size+=this.entries[t].size;k.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)}},oc=class extends B{constructor(){super(...arguments),this.box_name="ExtendedLanguageBox"}static{this.fourcc="elng"}parse(e){this.parseFullHeader(e),this.extended_language=e.readString(this.size-this.hdr_size)}write(e){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(e),e.writeString(this.extended_language)}},cc=class extends O{constructor(){super(...arguments),this.box_name="FileTypeBox"}static{this.fourcc="ftyp"}parse(e){let t=this.size-this.hdr_size;this.major_brand=e.readString(4),this.minor_version=e.readUint32(),t-=8,this.compatible_brands=[];let i=0;for(;t>=4;)this.compatible_brands[i]=e.readString(4),t-=4,i++}write(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,void 0,4),e.writeUint32(this.minor_version);for(let t=0;t<this.compatible_brands.length;t++)e.writeString(this.compatible_brands[t],void 0,4)}},lc=class extends B{constructor(){super(...arguments),this.box_name="HandlerBox"}static{this.fourcc="hdlr"}parse(e){this.parseFullHeader(e),this.version===0&&(e.readUint32(),this.handler=e.readString(4),e.readUint32Array(3),this.isEndOfBox(e)||(this.name=e.readCString()))}write(e){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(e),e.writeUint32(0),e.writeString(this.handler,void 0,4),e.writeUint32Array([0,0,0]),e.writeCString(this.name)}},dc=class extends O{constructor(){super(...arguments),this.box_name="HEVCConfigurationBox"}static{this.fourcc="hvcC"}parse(e){this.configurationVersion=e.readUint8();let t=e.readUint8();this.general_profile_space=t>>6,this.general_tier_flag=(t&32)>>5,this.general_profile_idc=t&31,this.general_profile_compatibility=e.readUint32(),this.general_constraint_indicator=e.readUint8Array(6),this.general_level_idc=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,this.chroma_format_idc=e.readUint8()&3,this.bit_depth_luma_minus8=e.readUint8()&7,this.bit_depth_chroma_minus8=e.readUint8()&7,this.avgFrameRate=e.readUint16(),t=e.readUint8(),this.constantFrameRate=t>>6,this.numTemporalLayers=(t&13)>>3,this.temporalIdNested=(t&4)>>2,this.lengthSizeMinusOne=t&3,this.nalu_arrays=[];let i=e.readUint8();for(let s=0;s<i;s++){let r=[];this.nalu_arrays.push(r),t=e.readUint8(),r.completeness=(t&128)>>7,r.nalu_type=t&63;let n=e.readUint16();for(let a=0;a<n;a++){let o=e.readUint16();r.push({data:e.readUint8Array(o)})}}}write(e){this.size=23;for(let t=0;t<this.nalu_arrays.length;t++){this.size+=3;for(let i=0;i<this.nalu_arrays[t].length;i++)this.size+=2+this.nalu_arrays[t][i].data.length}this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),e.writeUint32(this.general_profile_compatibility),e.writeUint8Array(this.general_constraint_indicator),e.writeUint8(this.general_level_idc),e.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),e.writeUint8(this.parallelismType+252),e.writeUint8(this.chroma_format_idc+252),e.writeUint8(this.bit_depth_luma_minus8+248),e.writeUint8(this.bit_depth_chroma_minus8+248),e.writeUint16(this.avgFrameRate),e.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),e.writeUint8(this.nalu_arrays.length);for(let t=0;t<this.nalu_arrays.length;t++){e.writeUint8((this.nalu_arrays[t].completeness<<7)+this.nalu_arrays[t].nalu_type),e.writeUint16(this.nalu_arrays[t].length);for(let i=0;i<this.nalu_arrays[t].length;i++)e.writeUint16(this.nalu_arrays[t][i].data.length),e.writeUint8Array(this.nalu_arrays[t][i].data)}}},uc=class extends B{constructor(){super(...arguments),this.box_name="MediaHeaderBox"}static{this.fourcc="mdhd"}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.parseLanguage(e),e.readUint16()}write(e){let t=this.modification_time>ot||this.creation_time>ot||this.duration>ot||this.version===1;this.version=t?1:0,this.size=4*4+2*2,this.size+=t?3*4:0,this.flags=0,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.timescale),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration)),e.writeUint16(this.language),e.writeUint16(0)}},hc=class extends B{constructor(){super(...arguments),this.box_name="MovieExtendsHeaderBox"}static{this.fourcc="mehd"}parse(e){this.parseFullHeader(e),this.flags&1&&(k.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version===1?this.fragment_duration=e.readUint64():this.fragment_duration=e.readUint32()}write(e){let t=this.fragment_duration>ot||this.version===1;this.version=t?1:0,this.size=4,this.size+=t?4:0,this.flags=0,this.writeHeader(e),t?e.writeUint64(this.fragment_duration):e.writeUint32(this.fragment_duration)}},mh=class extends B{constructor(){super(...arguments),this.box_name="ItemInfoEntry"}static{this.fourcc="infe"}parse(e){if(this.parseFullHeader(e),(this.version===0||this.version===1)&&(this.item_ID=e.readUint16(),this.item_protection_index=e.readUint16(),this.item_name=e.readCString(),this.content_type=e.readCString(),this.isEndOfBox(e)||(this.content_encoding=e.readCString())),this.version===1){this.extension_type=e.readString(4),k.warn("BoxParser","Cannot parse extension type"),e.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=e.readUint16():this.version===3&&(this.item_ID=e.readUint32()),this.item_protection_index=e.readUint16(),this.item_type=e.readString(4),this.item_name=e.readCString(),this.item_type==="mime"?(this.content_type=e.readCString(),this.content_encoding=e.readCString()):this.item_type==="uri "&&(this.item_uri_type=e.readCString()))}},gh=class extends B{constructor(){super(...arguments),this.box_name="ItemInfoBox"}static{this.fourcc="iinf"}parse(e){this.parseFullHeader(e),this.version===0?this.entry_count=e.readUint16():this.entry_count=e.readUint32(),this.item_infos=[];for(let t=0;t<this.entry_count;t++){let i=li(e,!1,this.size-(e.getPosition()-this.start));if(i.code===Nt){let s=i.box;s.type==="infe"?this.item_infos[t]=s:k.error("BoxParser","Expected 'infe' box, got "+i.box.type,e.isofile)}else return}}},_h=class extends B{constructor(){super(...arguments),this.box_name="ItemLocationBox"}static{this.fourcc="iloc"}parse(e){this.parseFullHeader(e);let t;t=e.readUint8(),this.offset_size=t>>4&15,this.length_size=t&15,t=e.readUint8(),this.base_offset_size=t>>4&15,this.version===1||this.version===2?this.index_size=t&15:this.index_size=0,this.items=[];let i=0;if(this.version<2)i=e.readUint16();else if(this.version===2)i=e.readUint32();else throw new Error("version of iloc box not supported");for(let s=0;s<i;s++){let r=0,n=0,a=0;if(this.version<2)r=e.readUint16();else if(this.version===2)r=e.readUint32();else throw new Error("version of iloc box not supported");this.version===1||this.version===2?n=e.readUint16()&15:n=0;let o=e.readUint16();switch(this.base_offset_size){case 0:a=0;break;case 4:a=e.readUint32();break;case 8:a=e.readUint64();break;default:throw new Error("Error reading base offset size")}let c=[],l=e.readUint16();for(let u=0;u<l;u++){let h=0,f=0,p=0;if(this.version===1||this.version===2)switch(this.index_size){case 0:h=0;break;case 4:h=e.readUint32();break;case 8:h=e.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.offset_size){case 0:f=0;break;case 4:f=e.readUint32();break;case 8:f=e.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.length_size){case 0:p=0;break;case 4:p=e.readUint32();break;case 8:p=e.readUint64();break;default:throw new Error("Error reading extent index")}c.push({extent_index:h,extent_length:p,extent_offset:f})}this.items.push({base_offset:a,construction_method:n,item_ID:r,data_reference_index:o,extents:c})}}},xh={auxl:"Auxiliary image item",base:"Pre-derived image item base",cdsc:"Item describes referenced item",dimg:"Derived image item",dpnd:"Item coding dependency",eroi:"Region",evir:"EVC slice",exbl:"Scalable image item","fdl ":"File delivery",font:"Font item",iloc:"Item data location",mask:"Region mask",mint:"Data integrity",pred:"Predictively coded item",prem:"Pre-multiplied item",tbas:"HEVC tile track base item",thmb:"Thumbnail image item"},yh=class fc extends B{constructor(){super(...arguments),this.box_name="ItemReferenceBox",this.references=[]}static{this.fourcc="iref"}static{this.allowed_types=["auxl","base","cdsc","dimg","dpnd","eroi","evir","exbl","fdl ","font","iloc","mask","mint","pred","prem","tbas","thmb"]}parse(t){for(this.parseFullHeader(t),this.references=[];t.getPosition()<this.start+this.size;){let i=li(t,!0,this.size-(t.getPosition()-this.start));if(i.code===Nt){let s="Unknown item reference";fc.allowed_types.includes(i.type)?s=xh[i.type]:k.warn("BoxParser",\`Unknown item reference type: '\${i.type}'\`);let r=this.version===0?new Mu(i.type,i.size,s,i.hdr_size,i.start):new zu(i.type,i.size,s,i.hdr_size,i.start);r.write===O.prototype.write&&r.type!=="mdat"&&(k.warn("BoxParser",r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(t)),r.parse(t),this.references.push(r)}else return}}},bh=class extends B{constructor(){super(...arguments),this.box_name="PrimaryItemBox"}static{this.fourcc="pitm"}parse(e){this.parseFullHeader(e),this.version===0?this.item_id=e.readUint16():this.item_id=e.readUint32()}},vh=class extends B{constructor(){super(...arguments),this.box_name="MetaBox",this.isQT=!1}static{this.fourcc="meta"}parse(e){let t=e.getPosition();if(this.size>8){switch(e.readUint32(),e.readString(4)){case"hdlr":case"mhdr":case"keys":case"ilst":case"ctry":case"lang":this.isQT=!0;break;default:break}e.seek(t)}this.isQT||this.parseFullHeader(e),Be.prototype.parse.call(this,e)}},pc=class extends B{constructor(){super(...arguments),this.box_name="MovieFragmentHeaderBox"}static{this.fourcc="mfhd"}parse(e){this.parseFullHeader(e),this.sequence_number=e.readUint32()}write(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.sequence_number)}},mc=class extends B{constructor(){super(...arguments),this.box_name="MovieHeaderBox"}static{this.fourcc="mvhd"}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.rate=e.readUint32(),this.volume=e.readUint16()>>8,e.readUint16(),e.readUint32Array(2),this.matrix=e.readInt32Array(9),e.readUint32Array(6),this.next_track_id=e.readUint32()}write(e){let t=this.modification_time>ot||this.creation_time>ot||this.duration>ot||this.version===1;this.version=t?1:0,this.size=4*4+20*4,this.size+=t?3*4:0,this.flags=0,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.timescale),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration)),e.writeUint32(this.rate),e.writeUint16(this.volume<<8),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeInt32Array(this.matrix),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(this.next_track_id)}print(e){super.printHeader(e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"timescale: "+this.timescale),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"rate: "+this.rate),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"next_track_id: "+this.next_track_id)}},wh=class extends Ms{static{this.fourcc="mett"}parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}},Sh=class extends Ms{static{this.fourcc="metx"}parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.parseFooter(e)}},kh=class extends O{constructor(){super(...arguments),this.box_name="AV1CodecConfigurationBox"}static{this.fourcc="av1C"}parse(e){let t=e.readUint8();if((t>>7&1)!==1){k.error("BoxParser","av1C marker problem",e.isofile);return}if(this.version=t&127,this.version!==1){k.error("BoxParser","av1C version "+this.version+" not supported",e.isofile);return}if(t=e.readUint8(),this.seq_profile=t>>5&7,this.seq_level_idx_0=t&31,t=e.readUint8(),this.seq_tier_0=t>>7&1,this.high_bitdepth=t>>6&1,this.twelve_bit=t>>5&1,this.monochrome=t>>4&1,this.chroma_subsampling_x=t>>3&1,this.chroma_subsampling_y=t>>2&1,this.chroma_sample_position=t&3,t=e.readUint8(),this.reserved_1=t>>5&7,this.reserved_1!==0){k.error("BoxParser","av1C reserved_1 parsing problem",e.isofile);return}if(this.initial_presentation_delay_present=t>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=t&15;else if(this.reserved_2=t&15,this.reserved_2!==0){k.error("BoxParser","av1C reserved_2 parsing problem",e.isofile);return}let i=this.size-this.hdr_size-4;this.configOBUs=e.readUint8Array(i)}},Th=class extends B{constructor(){super(...arguments),this.box_name="ElementaryStreamDescriptorBox"}static{this.fourcc="esds"}parse(e){this.parseFullHeader(e);let t=e.readUint8Array(this.size-this.hdr_size);if("MPEG4DescriptorParser"in an){let i=new an.MPEG4DescriptorParser;this.esd=i.parseOneDescriptor(new Dt(t.buffer,0,1))}}},Eh=class extends B{constructor(){super(...arguments),this.box_name="VPCodecConfigurationRecord"}static{this.fourcc="vpcC"}parse(e){if(this.parseFullHeader(e),this.version===1){this.profile=e.readUint8(),this.level=e.readUint8();let t=e.readUint8();this.bitDepth=t>>4,this.chromaSubsampling=t>>1&7,this.videoFullRangeFlag=t&1,this.colourPrimaries=e.readUint8(),this.transferCharacteristics=e.readUint8(),this.matrixCoefficients=e.readUint8(),this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)}else{this.profile=e.readUint8(),this.level=e.readUint8();let t=e.readUint8();this.bitDepth=t>>4&15,this.colorSpace=t&15,t=e.readUint8(),this.chromaSubsampling=t>>4&15,this.transferFunction=t>>1&7,this.videoFullRangeFlag=t&1,this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)}}},Uh=class extends B{constructor(){super(...arguments),this.box_name="VvcConfigurationBox"}static{this.fourcc="vvcC"}parse(e){this.parseFullHeader(e);let t={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(n){this.held_bits=n.readUint8(),this.num_held_bits=1*8},stream_read_2_bytes:function(n){this.held_bits=n.readUint16(),this.num_held_bits=2*8},extract_bits:function(n){let a=this.held_bits>>this.num_held_bits-n&(1<<n)-1;return this.num_held_bits-=n,a}};if(t.stream_read_1_bytes(e),t.extract_bits(5),this.lengthSizeMinusOne=t.extract_bits(2),this.ptl_present_flag=t.extract_bits(1),this.ptl_present_flag){t.stream_read_2_bytes(e),this.ols_idx=t.extract_bits(9),this.num_sublayers=t.extract_bits(3),this.constant_frame_rate=t.extract_bits(2),this.chroma_format_idc=t.extract_bits(2),t.stream_read_1_bytes(e),this.bit_depth_minus8=t.extract_bits(3),t.extract_bits(5);{if(t.stream_read_2_bytes(e),t.extract_bits(2),this.num_bytes_constraint_info=t.extract_bits(6),this.general_profile_idc=t.extract_bits(7),this.general_tier_flag=t.extract_bits(1),this.general_level_idc=e.readUint8(),t.stream_read_1_bytes(e),this.ptl_frame_only_constraint_flag=t.extract_bits(1),this.ptl_multilayer_enabled_flag=t.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(let n=0;n<this.num_bytes_constraint_info-1;n++){let a=t.extract_bits(6);t.stream_read_1_bytes(e);let o=t.extract_bits(2);this.general_constraint_info[n]=a<<2|o}this.general_constraint_info[this.num_bytes_constraint_info-1]=t.extract_bits(6)}else t.extract_bits(6);if(this.num_sublayers>1){t.stream_read_1_bytes(e),this.ptl_sublayer_present_mask=0;for(let n=this.num_sublayers-2;n>=0;--n){let a=t.extract_bits(1);this.ptl_sublayer_present_mask|=a<<n}for(let n=this.num_sublayers;n<=8&&this.num_sublayers>1;++n)t.extract_bits(1);this.sublayer_level_idc=[];for(let n=this.num_sublayers-2;n>=0;--n)this.ptl_sublayer_present_mask&1<<n&&(this.sublayer_level_idc[n]=e.readUint8())}if(this.ptl_num_sub_profiles=e.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(let n=0;n<this.ptl_num_sub_profiles;n++)this.general_sub_profile_idc.push(e.readUint32())}this.max_picture_width=e.readUint16(),this.max_picture_height=e.readUint16(),this.avg_frame_rate=e.readUint16()}let i=12,s=13;this.nalu_arrays=[];let r=e.readUint8();for(let n=0;n<r;n++){let a=[];this.nalu_arrays.push(a),t.stream_read_1_bytes(e),a.completeness=t.extract_bits(1),t.extract_bits(2),a.nalu_type=t.extract_bits(5);let o=1;a.nalu_type!==s&&a.nalu_type!==i&&(o=e.readUint16());for(let c=0;c<o;c++){let l=e.readUint16();a.push({data:e.readUint8Array(l),length:l})}}}},Bh=class extends O{constructor(){super(...arguments),this.box_name="ColourInformationBox"}static{this.fourcc="colr"}parse(e){if(this.colour_type=e.readString(4),this.colour_type==="nclx"){this.colour_primaries=e.readUint16(),this.transfer_characteristics=e.readUint16(),this.matrix_coefficients=e.readUint16();let t=e.readUint8();this.full_range_flag=t>>7}else this.colour_type==="rICC"?this.ICC_profile=e.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=e.readUint8Array(this.size-4))}};function Cs(e,t){let i=Number(e).toString(16);for(t=typeof t>"u"?2:t;i.length<t;)i="0"+i;return i}var cn=class extends $e{getCodec(){let e=super.getCodec();return this.avcC?\`\${e}.\${Cs(this.avcC.AVCProfileIndication)}\${Cs(this.avcC.profile_compatibility)}\${Cs(this.avcC.AVCLevelIndication)}\`:e}},Ah=class extends cn{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}static{this.fourcc="avc1"}},Ch=class extends cn{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}static{this.fourcc="avc2"}},Mh=class extends cn{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}static{this.fourcc="avc3"}},zh=class extends cn{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}static{this.fourcc="avc4"}},Ph=class extends $e{constructor(){super(...arguments),this.box_name="AV1SampleEntry"}static{this.fourcc="av01"}getCodec(){let e=super.getCodec(),t=this.av1C.seq_level_idx_0,i=t<10?"0"+t:t,s;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?s=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(s=this.av1C.high_bitdepth===1?"10":"08"),e+"."+this.av1C.seq_profile+"."+i+(this.av1C.seq_tier_0?"H":"M")+"."+s}},Ih=class extends $e{static{this.fourcc="dav1"}},ln=class extends $e{getCodec(){let e=super.getCodec();if(this.hvcC){switch(e+=".",this.hvcC.general_profile_space){case 0:e+="";break;case 1:e+="A";break;case 2:e+="B";break;case 3:e+="C";break}e+=this.hvcC.general_profile_idc,e+=".";let t=this.hvcC.general_profile_compatibility,i=0;for(let n=0;n<32&&(i|=t&1,n!==31);n++)i<<=1,t>>=1;e+=Cs(i,0),e+=".",this.hvcC.general_tier_flag===0?e+="L":e+="H",e+=this.hvcC.general_level_idc;let s=!1,r="";for(let n=5;n>=0;n--)(this.hvcC.general_constraint_indicator[n]||s)&&(r="."+Cs(this.hvcC.general_constraint_indicator[n],0)+r,s=!0);e+=r}return e}},Rh=class extends ln{constructor(){super(...arguments),this.box_name="HEVCSampleEntry"}static{this.fourcc="hvc1"}},Fh=class extends ln{static{this.fourcc="hvc2"}},Lh=class extends ln{constructor(){super(...arguments),this.box_name="HEVCSampleEntry",this.colrs=[],this.subBoxNames=["colr"]}static{this.fourcc="hev1"}},Oh=class extends ln{static{this.fourcc="hev2"}},Dh=class extends $e{constructor(){super(...arguments),this.box_name="HEVCTileSampleSampleEntry"}static{this.fourcc="hvt1"}},Nh=class extends $e{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}static{this.fourcc="lhe1"}},Hh=class extends $e{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}static{this.fourcc="lhv1"}},Gh=class extends $e{static{this.fourcc="dvh1"}},Vh=class extends $e{static{this.fourcc="dvhe"}},gc=class extends $e{getCodec(){let e=super.getCodec();if(this.vvcC){e+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?e+=".H":e+=".L",e+=this.vvcC.general_level_idc;let t="";if(this.vvcC.general_constraint_info){let i=[],s=0;s|=this.vvcC.ptl_frame_only_constraint_flag<<7,s|=this.vvcC.ptl_multilayer_enabled_flag<<6;let r;for(let n=0;n<this.vvcC.general_constraint_info.length;++n)s|=this.vvcC.general_constraint_info[n]>>2&63,i.push(s),s&&(r=n),s=this.vvcC.general_constraint_info[n]>>2&3;if(r===void 0)t=".CA";else{t=".C";let n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",a=0,o=0;for(let c=0;c<=r;++c)for(a=a<<8|i[c],o+=8;o>=5;){let l=a>>o-5&31;t+=n[l],o-=5,a&=(1<<o)-1}o&&(a<<=5-o,t+=n[a&31])}}e+=t}return e}},Wh=class extends gc{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}static{this.fourcc="vvc1"}},qh=class extends gc{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}static{this.fourcc="vvi1"}},jh=class extends $e{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}static{this.fourcc="vvs1"}},$h=class extends $e{constructor(){super(...arguments),this.box_name="VvcNonVCLSampleEntry"}static{this.fourcc="vvcN"}},_c=class extends $e{getCodec(){let e=super.getCodec(),t=this.vpcC.level;t===0&&(t="00");let i=this.vpcC.bitDepth;return i===8&&(i="08"),\`\${e}.0\${this.vpcC.profile}.\${t}.\${i}\`}},Yh=class extends _c{static{this.fourcc="vp08"}},Xh=class extends _c{static{this.fourcc="vp09"}},Zh=class extends $e{static{this.fourcc="avs3"}},Qh=class extends $e{constructor(){super(...arguments),this.box_name="J2KSampleEntry"}static{this.fourcc="j2ki"}},Kh=class extends $e{static{this.fourcc="mjp2"}},Jh=class extends $e{static{this.fourcc="mjpg"}},ef=class extends $e{constructor(){super(...arguments),this.box_name="UncompressedVideoSampleEntry"}static{this.fourcc="uncv"}},tf=class extends $e{constructor(){super(...arguments),this.box_name="MP4VisualSampleEntry"}static{this.fourcc="mp4v"}},sf=class extends Pt{constructor(){super(...arguments),this.box_name="MP4AudioSampleEntry"}static{this.fourcc="mp4a"}getCodec(){let e=super.getCodec();if(this.esds&&this.esds.esd){let t=this.esds.esd.getOTI(),i=this.esds.esd.getAudioConfig();return e+"."+Cs(t)+(i?"."+i:"")}else return e}},rf=class extends Pt{static{this.fourcc="m4ae"}},nf=class extends Pt{static{this.fourcc="ac-3"}},af=class extends Pt{static{this.fourcc="ac-4"}},of=class extends Pt{static{this.fourcc="ec-3"}},cf=class extends Pt{static{this.fourcc="Opus"}},lf=class extends Pt{static{this.fourcc="mha1"}},df=class extends Pt{static{this.fourcc="mha2"}},uf=class extends Pt{static{this.fourcc="mhm1"}},hf=class extends Pt{static{this.fourcc="mhm2"}},ff=class extends Pt{static{this.fourcc="fLaC"}},pf=class extends $e{static{this.fourcc="encv"}},mf=class extends Pt{static{this.fourcc="enca"}},gf=class extends Zi{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}static{this.fourcc="encu"}},_f=class extends ua{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}static{this.fourcc="encs"}},xf=class extends ua{static{this.fourcc="mp4s"}},yf=class extends Gu{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}static{this.fourcc="enct"}},bf=class extends Ms{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}static{this.fourcc="encm"}},vf=class extends $e{constructor(){super(...arguments),this.box_name="RestrictedVideoSampleEntry"}static{this.fourcc="resv"}},wf=class extends Zi{static{this.fourcc="sbtt"}parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}},xc=class extends Zi{static{this.fourcc="stpp"}parse(e){this.parseHeader(e),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.auxiliary_mime_types=e.readCString(),this.parseFooter(e)}write(e){this.writeHeader(e),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,e.writeCString(this.namespace),e.writeCString(this.schema_location),e.writeCString(this.auxiliary_mime_types),this.writeFooter(e)}},Sf=class extends Zi{static{this.fourcc="stxt"}parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}getCodec(){let e=super.getCodec();return this.mime_format?e+"."+this.mime_format:e}},kf=class extends Zi{static{this.fourcc="tx3g"}parse(e){this.parseHeader(e),this.displayFlags=e.readUint32(),this.horizontal_justification=e.readInt8(),this.vertical_justification=e.readInt8(),this.bg_color_rgba=e.readUint8Array(4),this.box_record=e.readInt16Array(4),this.style_record=e.readUint8Array(12),this.parseFooter(e)}},Tf=class extends Ms{static{this.fourcc="wvtt"}parse(e){this.parseHeader(e),this.parseFooter(e)}},Ef=class extends B{constructor(){super(...arguments),this.box_name="SampleToGroupBox"}static{this.fourcc="sbgp"}parse(e){this.parseFullHeader(e),this.grouping_type=e.readString(4),this.version===1?this.grouping_type_parameter=e.readUint32():this.grouping_type_parameter=0,this.entries=[];let t=e.readUint32();for(let i=0;i<t;i++)this.entries.push({sample_count:e.readInt32(),group_description_index:e.readInt32()})}write(e){this.grouping_type_parameter?this.version=1:this.version=0,this.flags=0,this.size=8+8*this.entries.length+(this.version===1?4:0),this.writeHeader(e),e.writeString(this.grouping_type,void 0,4),this.version===1&&e.writeUint32(this.grouping_type_parameter),e.writeUint32(this.entries.length);for(let t=0;t<this.entries.length;t++){let i=this.entries[t];e.writeInt32(i.sample_count),e.writeInt32(i.group_description_index)}}},Uf=class extends B{constructor(){super(...arguments),this.box_name="SampleDependencyTypeBox"}static{this.fourcc="sdtp"}parse(e){this.parseFullHeader(e);let t=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(let i=0;i<t;i++){let s=e.readUint8();this.is_leading[i]=s>>6,this.sample_depends_on[i]=s>>4&3,this.sample_is_depended_on[i]=s>>2&3,this.sample_has_redundancy[i]=s&3}}},Bf=class extends B{constructor(){super(...arguments),this.box_name="SampleGroupDescriptionBox"}static{this.fourcc="sgpd"}parse(e){this.parseFullHeader(e),this.grouping_type=e.readString(4),k.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=e.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=e.readUint32()),this.entries=[];let t=e.readUint32();for(let i=0;i<t;i++){let s;this.grouping_type in zt.sampleGroupEntry?s=new zt.sampleGroupEntry[this.grouping_type](this.grouping_type):s=new tt(this.grouping_type),this.entries.push(s),this.version===1?this.default_length===0?s.description_length=e.readUint32():s.description_length=this.default_length:s.description_length=this.default_length,s.write===tt.prototype.write&&(k.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),s.data=e.readUint8Array(s.description_length),e.seek(e.getPosition()-s.description_length)),s.parse(e)}}write(e){this.flags=0,this.size=12;for(let t=0;t<this.entries.length;t++){let i=this.entries[t];this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=i.data.length)}this.writeHeader(e),e.writeString(this.grouping_type,void 0,4),this.version===1&&e.writeUint32(this.default_length),this.version>=2&&e.writeUint32(this.default_sample_description_index),e.writeUint32(this.entries.length);for(let t=0;t<this.entries.length;t++){let i=this.entries[t];this.version===1&&this.default_length===0&&e.writeUint32(i.description_length),i.write(e)}}},Af=class extends B{constructor(){super(...arguments),this.box_name="CompressedSegmentIndexBox"}static{this.fourcc="sidx"}parse(e){this.parseFullHeader(e),this.reference_ID=e.readUint32(),this.timescale=e.readUint32(),this.version===0?(this.earliest_presentation_time=e.readUint32(),this.first_offset=e.readUint32()):(this.earliest_presentation_time=e.readUint64(),this.first_offset=e.readUint64()),e.readUint16(),this.references=[];let t=e.readUint16();for(let i=0;i<t;i++){let s=e.readUint32(),r=e.readUint32(),n=e.readUint32();this.references.push({reference_type:s>>31&1,referenced_size:s&2147483647,subsegment_duration:r,starts_with_SAP:n>>31&1,SAP_type:n>>28&7,SAP_delta_time:n&268435455})}}write(e){let t=this.earliest_presentation_time>ot||this.first_offset>ot||this.version===1;this.version=t?1:0,this.size=4*2+2+2+12*this.references.length,this.size+=t?16:8,this.flags=0,this.writeHeader(e),e.writeUint32(this.reference_ID),e.writeUint32(this.timescale),t?(e.writeUint64(this.earliest_presentation_time),e.writeUint64(this.first_offset)):(e.writeUint32(this.earliest_presentation_time),e.writeUint32(this.first_offset)),e.writeUint16(0),e.writeUint16(this.references.length);for(let i=0;i<this.references.length;i++){let s=this.references[i];e.writeUint32(s.reference_type<<31|s.referenced_size),e.writeUint32(s.subsegment_duration),e.writeUint32(s.starts_with_SAP<<31|s.SAP_type<<28|s.SAP_delta_time)}}},yc=class extends B{constructor(){super(...arguments),this.box_name="SoundMediaHeaderBox"}static{this.fourcc="smhd"}parse(e){this.parseFullHeader(e),this.balance=e.readUint16(),e.readUint16()}write(e){this.version=0,this.size=4,this.writeHeader(e),e.writeUint16(this.balance),e.writeUint16(0)}},bc=class extends B{constructor(){super(...arguments),this.box_name="ChunkOffsetBox"}static{this.fourcc="stco"}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.chunk_offsets=[],this.version===0)for(let i=0;i<t;i++)this.chunk_offsets.push(e.readUint32())}write(e){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),e.writeUint32Array(this.chunk_offsets)}unpack(e){for(let t=0;t<this.chunk_offsets.length;t++)e[t].offset=this.chunk_offsets[t]}},vc=class extends B{constructor(){super(...arguments),this.box_name="SubtitleMediaHeaderBox"}static{this.fourcc="sthd"}},wc=class extends B{constructor(){super(...arguments),this.box_name="SampleToChunkBox"}static{this.fourcc="stsc"}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(let i=0;i<t;i++)this.first_chunk.push(e.readUint32()),this.samples_per_chunk.push(e.readUint32()),this.sample_description_index.push(e.readUint32())}write(e){this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(e),e.writeUint32(this.first_chunk.length);for(let t=0;t<this.first_chunk.length;t++)e.writeUint32(this.first_chunk[t]),e.writeUint32(this.samples_per_chunk[t]),e.writeUint32(this.sample_description_index[t])}unpack(e){let t=0,i=0;for(let s=0;s<this.first_chunk.length;s++)for(let r=0;r<(s+1<this.first_chunk.length?this.first_chunk[s+1]:1/0);r++){i++;for(let n=0;n<this.samples_per_chunk[s];n++){if(e[t])e[t].description_index=this.sample_description_index[s],e[t].chunk_index=i;else return;t++}}}},Sc=class extends B{constructor(){super(...arguments),this.box_name="SampleDescriptionBox"}static{this.fourcc="stsd"}parse(e){this.parseFullHeader(e),this.entries=[];let t=e.readUint32();for(let i=1;i<=t;i++){let s=li(e,!0,this.size-(e.getPosition()-this.start));if(s.code===Nt){let r;s.type in zt.sampleEntry?(r=new zt.sampleEntry[s.type](s.size),r.hdr_size=s.hdr_size,r.start=s.start):(k.warn("BoxParser",\`Unknown sample entry type: '\${s.type}'\`),r=new Si(s.size,s.hdr_size,s.start),r.type=s.type),r.write===Si.prototype.write&&(k.info("BoxParser","SampleEntry "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(e)),r.parse(e),this.entries.push(r)}else return}}write(e){this.version=0,this.flags=0,this.size=0,this.writeHeader(e),e.writeUint32(this.entries.length),this.size+=4;for(let t=0;t<this.entries.length;t++)this.entries[t].write(e),this.size+=this.entries[t].size;k.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)}},kc=class extends B{constructor(){super(...arguments),this.box_name="SampleSizeBox"}static{this.fourcc="stsz"}parse(e){if(this.parseFullHeader(e),this.sample_sizes=[],this.version===0){this.sample_size=e.readUint32(),this.sample_count=e.readUint32();for(let t=0;t<this.sample_count;t++)this.sample_size===0?this.sample_sizes.push(e.readUint32()):this.sample_sizes[t]=this.sample_size}}write(e){let t=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0){let i=0;for(;i+1<this.sample_sizes.length;)if(this.sample_sizes[i+1]!==this.sample_sizes[0]){t=!1;break}else i++}else t=!1;this.size=8,t||(this.size+=4*this.sample_sizes.length),this.writeHeader(e),t?e.writeUint32(this.sample_sizes[0]):e.writeUint32(0),e.writeUint32(this.sample_sizes.length),t||e.writeUint32Array(this.sample_sizes)}unpack(e){for(let t=0;t<this.sample_sizes.length;t++)e[t].size=this.sample_sizes[t]}},Tc=class extends B{constructor(){super(...arguments),this.box_name="TimeToSampleBox",this.sample_counts=[],this.sample_deltas=[]}static{this.fourcc="stts"}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.sample_counts.length=0,this.sample_deltas.length=0,this.version===0)for(let i=0;i<t;i++){this.sample_counts.push(e.readUint32());let s=e.readInt32();s<0&&(k.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),s=1),this.sample_deltas.push(s)}}write(e){this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length);for(let t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),e.writeUint32(this.sample_deltas[t])}unpack(e){let t=0;for(let i=0;i<this.sample_counts.length;i++)for(let s=0;s<this.sample_counts[i];s++)t===0?e[t].dts=0:e[t].dts=e[t-1].dts+this.sample_deltas[i],t++}},Ec=class extends B{constructor(){super(...arguments),this.box_name="TrackFragmentBaseMediaDecodeTimeBox"}static{this.fourcc="tfdt"}parse(e){this.parseFullHeader(e),this.version===1?this.baseMediaDecodeTime=e.readUint64():this.baseMediaDecodeTime=e.readUint32()}write(e){let t=this.baseMediaDecodeTime>ot||this.version===1;this.version=t?1:0,this.size=4,this.size+=t?4:0,this.flags=0,this.writeHeader(e),t?e.writeUint64(this.baseMediaDecodeTime):e.writeUint32(this.baseMediaDecodeTime)}},Uc=class extends B{constructor(){super(...arguments),this.box_name="TrackFragmentHeaderBox"}static{this.fourcc="tfhd"}parse(e){this.parseFullHeader(e);let t=0;this.track_id=e.readUint32(),this.size-this.hdr_size>t&&this.flags&Yr?(this.base_data_offset=e.readUint64(),t+=8):this.base_data_offset=0,this.size-this.hdr_size>t&&this.flags&Xr?(this.default_sample_description_index=e.readUint32(),t+=4):this.default_sample_description_index=0,this.size-this.hdr_size>t&&this.flags&Zr?(this.default_sample_duration=e.readUint32(),t+=4):this.default_sample_duration=0,this.size-this.hdr_size>t&&this.flags&Qr?(this.default_sample_size=e.readUint32(),t+=4):this.default_sample_size=0,this.size-this.hdr_size>t&&this.flags&Kr?(this.default_sample_flags=e.readUint32(),t+=4):this.default_sample_flags=0}write(e){this.version=0,this.size=4,this.flags&Yr&&(this.size+=8),this.flags&Xr&&(this.size+=4),this.flags&Zr&&(this.size+=4),this.flags&Qr&&(this.size+=4),this.flags&Kr&&(this.size+=4),this.writeHeader(e),e.writeUint32(this.track_id),this.flags&Yr&&e.writeUint64(this.base_data_offset),this.flags&Xr&&e.writeUint32(this.default_sample_description_index),this.flags&Zr&&e.writeUint32(this.default_sample_duration),this.flags&Qr&&e.writeUint32(this.default_sample_size),this.flags&Kr&&e.writeUint32(this.default_sample_flags)}},Bc=class extends B{constructor(){super(...arguments),this.box_name="TrackHeaderBox",this.layer=0,this.alternate_group=0}static{this.fourcc="tkhd"}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint32()),e.readUint32Array(2),this.layer=e.readInt16(),this.alternate_group=e.readInt16(),this.volume=e.readInt16()>>8,e.readUint16(),this.matrix=e.readInt32Array(9),this.width=e.readUint32(),this.height=e.readUint32()}write(e){let t=this.modification_time>ot||this.creation_time>ot||this.duration>ot||this.version===1;this.version=t?1:0,this.size=5*4+15*4,this.size+=t?3*4:0,this.flags=this.flags??3,this.writeHeader(e),t?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint32(this.duration)),e.writeUint32Array([0,0]),e.writeInt16(this.layer),e.writeInt16(this.alternate_group),e.writeInt16(this.volume<<8),e.writeInt16(0),e.writeInt32Array(this.matrix),e.writeUint32(this.width),e.writeUint32(this.height)}print(e){super.printHeader(e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"track_id: "+this.track_id),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"layer: "+this.layer),e.log(e.indent+"alternate_group: "+this.alternate_group),e.log(e.indent+"width: "+this.width),e.log(e.indent+"height: "+this.height)}},ca=class extends B{constructor(){super(...arguments),this.box_name="TrackExtendsBox"}static{this.fourcc="trex"}parse(e){this.parseFullHeader(e),this.track_id=e.readUint32(),this.default_sample_description_index=e.readUint32(),this.default_sample_duration=e.readUint32(),this.default_sample_size=e.readUint32(),this.default_sample_flags=e.readUint32()}write(e){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(e),e.writeUint32(this.track_id),e.writeUint32(this.default_sample_description_index),e.writeUint32(this.default_sample_duration),e.writeUint32(this.default_sample_size),e.writeUint32(this.default_sample_flags)}},Ac=class extends B{constructor(){super(...arguments),this.box_name="TrackRunBox",this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[]}static{this.fourcc="trun"}parse(e){this.parseFullHeader(e);let t=0;if(this.sample_count=e.readUint32(),t+=4,this.size-this.hdr_size>t&&this.flags&hr?(this.data_offset=e.readInt32(),t+=4):this.data_offset=0,this.size-this.hdr_size>t&&this.flags&Jr?(this.first_sample_flags=e.readUint32(),t+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>t)for(let i=0;i<this.sample_count;i++)this.flags&fr&&(this.sample_duration[i]=e.readUint32()),this.flags&pr&&(this.sample_size[i]=e.readUint32()),this.flags&mr&&(this.sample_flags[i]=e.readUint32()),this.flags&gr&&(this.version===0?this.sample_composition_time_offset[i]=e.readUint32():this.sample_composition_time_offset[i]=e.readInt32())}write(e){this.size=4,this.flags&hr&&(this.size+=4),this.flags&Jr&&(this.size+=4),this.flags&fr&&(this.size+=4*this.sample_duration.length),this.flags&pr&&(this.size+=4*this.sample_size.length),this.flags&mr&&(this.size+=4*this.sample_flags.length),this.flags&gr&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(e),e.writeUint32(this.sample_count),this.flags&hr&&(this.data_offset_position=e.getPosition(),e.writeInt32(this.data_offset)),this.flags&Jr&&e.writeUint32(this.first_sample_flags);for(let t=0;t<this.sample_count;t++)this.flags&fr&&e.writeUint32(this.sample_duration[t]),this.flags&pr&&e.writeUint32(this.sample_size[t]),this.flags&mr&&e.writeUint32(this.sample_flags[t]),this.flags&gr&&(this.version===0?e.writeUint32(this.sample_composition_time_offset[t]):e.writeInt32(this.sample_composition_time_offset[t]))}},Cc=class extends B{constructor(){super(...arguments),this.box_name="DataEntryUrlBox"}static{this.fourcc="url "}parse(e){this.parseFullHeader(e),this.flags!==1&&(this.location=e.readCString())}write(e){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(e),this.location&&e.writeCString(this.location)}},Mc=class extends B{constructor(){super(...arguments),this.box_name="VideoMediaHeaderBox"}static{this.fourcc="vmhd"}parse(e){this.parseFullHeader(e),this.graphicsmode=e.readUint16(),this.opcolor=e.readUint16Array(3)}write(e){this.version=0,this.size=8,this.writeHeader(e),e.writeUint16(this.graphicsmode),e.writeUint16Array(this.opcolor)}},ra=class{constructor(e,t,i){this.grouping_type=e,this.grouping_type_parameter=t,this.sbgp=i,this.last_sample_in_run=-1,this.entry_index=-1}},Cf=class Pi{constructor(t,i=!0){this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.moovStartSent=!1,this.readySent=!1,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.sidxSent=!1,this.items=[],this.entity_groups=[],this.itemsDataSize=0,this.lastMoofIndex=0,this.samplesDataSize=0,this.lastBoxStartPosition=0,this.nextParsePosition=0,this.discardMdatData=!0,this.discardMdatData=i,t?(this.stream=t,this.parse()):this.stream=new tn,this.stream.isofile=this}setSegmentOptions(t,i,s){let{sizePerSegment:r=Number.MAX_SAFE_INTEGER,rapAlignement:n=!0}=s,a=s.nbSamples??s.nbSamplesPerFragment??1e3,o=s.nbSamplesPerFragment??a;if(a<=0||o<=0||r<=0){k.error("ISOFile",\`Invalid segment options: nbSamples=\${a}, nbSamplesPerFragment=\${o}, sizePerSegment=\${r}\`);return}if(a<o&&(k.warn("ISOFile",\`nbSamples (\${a}) is less than nbSamplesPerFragment (\${o}), setting nbSamples to nbSamplesPerFragment\`),a=o),this.fragmentedTracks.some(l=>l.nb_samples!==a)){k.error("ISOFile",\`Cannot set segment options for track \${t}: nbSamples (\${a}) does not match existing tracks\`);return}let c=this.getTrackById(t);if(c){let l={id:t,user:i,trak:c,segmentStream:void 0,nb_samples:a,nb_samples_per_fragment:o,size_per_segment:r,rapAlignement:n,state:{lastFragmentSampleNumber:0,lastSegmentSampleNumber:0,accumulatedSize:0}};this.fragmentedTracks.push(l),c.nextSample=0}this.discardMdatData&&k.warn("ISOFile","Segmentation options set but discardMdatData is true, samples will not be segmented")}unsetSegmentOptions(t){let i=-1;for(let s=0;s<this.fragmentedTracks.length;s++)this.fragmentedTracks[s].id===t&&(i=s);i>-1&&this.fragmentedTracks.splice(i,1)}setExtractionOptions(t,i,{nbSamples:s=1e3}={}){let r=this.getTrackById(t);r&&(this.extractedTracks.push({id:t,user:i,trak:r,nb_samples:s,samples:[]}),r.nextSample=0),this.discardMdatData&&k.warn("ISOFile","Extraction options set but discardMdatData is true, samples will not be extracted")}unsetExtractionOptions(t){let i=-1;for(let s=0;s<this.extractedTracks.length;s++)this.extractedTracks[s].id===t&&(i=s);i>-1&&this.extractedTracks.splice(i,1)}parse(){if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else{this.saveParsePosition&&this.saveParsePosition();let i=li(this.stream,!1);if(i.code===zi)if(this.processIncompleteBox){if(this.processIncompleteBox(i))continue;return}else return;else if(i.code===Nt){let s=i.box;if(this.boxes.push(s),s.type==="uuid")this[s.uuid]!==void 0&&k.warn("ISOFile","Duplicate Box of uuid: "+s.uuid+", overriding previous occurrence"),this[s.uuid]=s;else switch(s.type){case"mdat":this.mdats.push(s),this.transferMdatData(s);break;case"moof":this.moofs.push(s);break;case"free":case"skip":break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[s.type]!==void 0?Array.isArray(this[s.type+"s"])?(k.info("ISOFile",\`Found multiple boxes of type \${s.type} in ISOFile, adding to array\`),this[s.type+"s"].push(s)):(k.warn("ISOFile",\`Found multiple boxes of type \${s.type} but no array exists. Creating array dynamically.\`),this[s.type+"s"]=[this[s.type],s]):(this[s.type]=s,Array.isArray(this[s.type+"s"])&&this[s.type+"s"].push(s));break}this.updateUsedBytes&&this.updateUsedBytes(s,i)}else if(i.code===Yo){k.error("ISOFile",\`Invalid data found while parsing box of type '\${i.type}' at position \${i.start}. Aborting parsing.\`,this);break}}}checkBuffer(t){if(!t)throw new Error("Buffer must be defined and non empty");return t.byteLength===0?(k.warn("ISOFile","Ignoring empty buffer (fileStart: "+t.fileStart+")"),this.stream.logBufferLevel(),!1):(k.info("ISOFile","Processing buffer (fileStart: "+t.fileStart+")"),t.usedBytes=0,this.stream.insertBuffer(t),this.stream.logBufferLevel(),this.stream.initialized()?!0:(k.warn("ISOFile","Not ready to start parsing"),!1))}appendBuffer(t,i){let s;if(this.checkBuffer(t))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(i),this.nextSeekPosition?(s=this.nextSeekPosition,this.nextSeekPosition=void 0):s=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(s=this.stream.getEndFilePositionAfter(s))):this.nextParsePosition?s=this.nextParsePosition:s=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(k.info("ISOFile","Done processing buffer (fileStart: "+t.fileStart+") - next buffer to fetch should have a fileStart position of "+s),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),k.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),s}getFragmentDuration(){let t=this.getBox("mvex");if(!t)return;if(t.mehd)return{num:t.mehd.fragment_duration,den:this.moov.mvhd.timescale};let i=this.getBoxes("trak",!1),s={num:0,den:1};for(let r of i){let n=r.samples_duration,a=r.mdia.mdhd.timescale;n&&a&&n/a>s.num/s.den&&(s={num:n,den:a})}return s}getInfo(){if(!this.moov)return{hasMoov:!1,mime:""};let t=new Date("1904-01-01T00:00:00Z").getTime(),i=this.getBox("mvex")!==void 0,s={hasMoov:!0,duration:this.moov.mvhd.duration,timescale:this.moov.mvhd.timescale,isFragmented:i,fragment_duration:this.getFragmentDuration(),isProgressive:this.isProgressive,hasIOD:this.moov.iods!==void 0,brands:[this.ftyp.major_brand].concat(this.ftyp.compatible_brands),created:new Date(t+this.moov.mvhd.creation_time*1e3),modified:new Date(t+this.moov.mvhd.modification_time*1e3),tracks:[],audioTracks:[],videoTracks:[],subtitleTracks:[],metadataTracks:[],hintTracks:[],otherTracks:[],mime:""};for(let r=0;r<this.moov.traks.length;r++){let n=this.moov.traks[r],a=n.mdia.minf.stbl.stsd.entries[0],o=n.samples_size,c=n.mdia.mdhd.timescale,l=n.samples_duration,u=o*8*c/l,h={samples_duration:l,bitrate:u,size:o,timescale:c,alternate_group:n.tkhd.alternate_group,codec:a.getCodec(),created:new Date(t+n.tkhd.creation_time*1e3),cts_shift:n.mdia.minf.stbl.cslg,duration:n.mdia.mdhd.duration,id:n.tkhd.track_id,kind:n.udta&&n.udta.kinds.length?n.udta.kinds[0]:{schemeURI:"",value:""},language:n.mdia.elng?n.mdia.elng.extended_language:n.mdia.mdhd.languageString,layer:n.tkhd.layer,matrix:n.tkhd.matrix,modified:new Date(t+n.tkhd.modification_time*1e3),movie_duration:n.tkhd.duration,movie_timescale:s.timescale,name:n.mdia.hdlr.name,nb_samples:n.samples.length,references:[],track_height:n.tkhd.height/65536,track_width:n.tkhd.width/65536,volume:n.tkhd.volume};if(s.tracks.push(h),n.tref)for(let f=0;f<n.tref.references.length;f++)h.references.push({type:n.tref.references[f].type,track_ids:n.tref.references[f].track_ids});n.edts&&(h.edits=n.edts.elst.entries),a instanceof Pt?(h.type="audio",s.audioTracks.push(h),h.audio={sample_rate:a.getSampleRate(),channel_count:a.getChannelCount(),sample_size:a.getSampleSize()}):a instanceof $e?(h.type="video",s.videoTracks.push(h),h.video={width:a.getWidth(),height:a.getHeight()}):a instanceof Zi?(h.type="subtitles",s.subtitleTracks.push(h)):a instanceof qo?(h.type="metadata",s.hintTracks.push(h)):a instanceof Ms?(h.type="metadata",s.metadataTracks.push(h)):(h.type="metadata",s.otherTracks.push(h))}s.videoTracks&&s.videoTracks.length>0?s.mime+='video/mp4; codecs="':s.audioTracks&&s.audioTracks.length>0?s.mime+='audio/mp4; codecs="':s.mime+='application/mp4; codecs="';for(let r=0;r<s.tracks.length;r++)r!==0&&(s.mime+=","),s.mime+=s.tracks[r].codec;return s.mime+='"; profiles="',s.mime+=this.ftyp.compatible_brands.join(),s.mime+='"',s}setNextSeekPositionFromSample(t){t&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(t.offset+t.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=t.offset+t.alreadyRead)}processSamples(t){if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==void 0){let i=new Set;for(;i.size<this.fragmentedTracks.length&&this.fragmentedTracks.some(s=>s.trak.nextSample<s.trak.samples.length)&&this.sampleProcessingStarted;)for(let s of this.fragmentedTracks){let r=s.trak;if(!i.has(s.id)){let n=r.nextSample<r.samples.length?this.getSample(r,r.nextSample):void 0;if(!n){this.setNextSeekPositionFromSample(r.samples[r.nextSample]),i.add(s.id);continue}s.state.accumulatedSize+=n.size;let a=r.nextSample+1,o=a-s.state.lastFragmentSampleNumber>s.nb_samples_per_fragment,c=a-s.state.lastSegmentSampleNumber>s.nb_samples,l=o||a%s.nb_samples_per_fragment===0,u=c||a%s.nb_samples===0,h=s.state.accumulatedSize>=s.size_per_segment,f=!s.rapAlignement||n.is_sync,p=t||r.nextSample+1>=r.samples.length;if(p&&!f&&k.warn("ISOFile","Flushing track #"+s.id+" at sample #"+r.nextSample+" which is not a RAP, this may lead to playback issues"),l=l&&f,u=u&&f,h=h&&f,l||h||p){o?k.warn("ISOFile","Fragment on track #"+s.id+" is overdue, creating it with samples ["+s.state.lastFragmentSampleNumber+", "+r.nextSample+"]"):k.debug("ISOFile","Creating media fragment on track #"+s.id+" for samples ["+s.state.lastFragmentSampleNumber+", "+r.nextSample+"]");let m=this.createFragment(s.id,s.state.lastFragmentSampleNumber,r.nextSample,s.segmentStream);if(m)s.segmentStream=m,s.state.lastFragmentSampleNumber=r.nextSample+1;else{i.add(s.id);continue}}(u||h||p)&&(c?k.warn("ISOFile","Segment on track #"+s.id+" is overdue, sending it with samples ["+Math.max(0,r.nextSample-s.nb_samples)+", "+(r.nextSample-1)+"]"):k.info("ISOFile","Sending fragmented data on track #"+s.id+" for samples ["+Math.max(0,r.nextSample-s.nb_samples)+", "+(r.nextSample-1)+"]"),k.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(s.id,s.user,s.segmentStream.buffer,r.nextSample+1,t||r.nextSample+1>=r.samples.length),s.segmentStream=void 0,s.state.accumulatedSize=0,s.state.lastSegmentSampleNumber=r.nextSample+1),r.nextSample++}}}if(this.onSamples!==void 0)for(let i=0;i<this.extractedTracks.length;i++){let s=this.extractedTracks[i],r=s.trak;for(;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){k.debug("ISOFile","Exporting on track #"+s.id+" sample #"+r.nextSample);let n=this.getSample(r,r.nextSample);if(n)r.nextSample++,s.samples.push(n);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%s.nb_samples===0||r.nextSample>=r.samples.length)&&(k.debug("ISOFile","Sending samples on track #"+s.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(s.id,s.user,s.samples),s.samples=[],s!==this.extractedTracks[i]))break}}}}getBox(t){let i=this.getBoxes(t,!0);return i.length?i[0]:void 0}getBoxes(t,i){let s=[],r=n=>{n instanceof O&&n.type&&n.type===t&&s.push(n);let a=[];n.boxes&&a.push(...n.boxes),n.entries&&a.push(...n.entries),n.item_infos&&a.push(...n.item_infos),n.references&&a.push(...n.references);for(let o of a){if(s.length&&i)return;r(o)}};return r(this),s}getTrackSamplesInfo(t){let i=this.getTrackById(t);if(i)return i.samples}getTrackSample(t,i){let s=this.getTrackById(t);return this.getSample(s,i)}releaseUsedSamples(t,i){let s=0,r=this.getTrackById(t);r.lastValidSample||(r.lastValidSample=0);for(let n=r.lastValidSample;n<i;n++)s+=this.releaseSample(r,n);k.info("ISOFile","Track #"+t+" released samples up to "+i+" (released size: "+s+", remaining: "+this.samplesDataSize+")"),r.lastValidSample=i}start(){this.sampleProcessingStarted=!0,this.processSamples(!1)}stop(){this.sampleProcessingStarted=!1}flush(){k.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)}seekTrack(t,i,s){let r=0,n=0,a;if(s.samples.length===0)return k.info("ISOFile","No sample in track, cannot seek! Using time "+k.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(let c=0;c<s.samples.length;c++){let l=s.samples[c];if(c===0)n=0,a=l.timescale;else if(l.cts>t*l.timescale){n=c-1;break}i&&l.is_sync&&(r=c)}for(i&&(n=r),t=s.samples[n].cts,s.nextSample=n;s.samples[n].alreadyRead===s.samples[n].size&&s.samples[n+1];)n++;let o=s.samples[n].offset+s.samples[n].alreadyRead;return k.info("ISOFile","Seeking to "+(i?"RAP":"")+" sample #"+s.nextSample+" on track "+s.tkhd.track_id+", time "+k.getDurationString(t,a)+" and offset: "+o),{offset:o,time:t/a}}getTrackDuration(t){if(!t.samples)return 1/0;let i=t.samples[t.samples.length-1];return(i.cts+i.duration)/i.timescale}seek(t,i){let s=this.moov,r={offset:1/0,time:1/0};if(this.moov){for(let n=0;n<s.traks.length;n++){let a=s.traks[n];if(t>this.getTrackDuration(a))continue;let o=this.seekTrack(t,i,a);o.offset<r.offset&&(r.offset=o.offset),o.time<r.time&&(r.time=o.time)}return k.info("ISOFile","Seeking at time "+k.getDurationString(r.time,1)+" needs a buffer with a fileStart position of "+r.offset),r.offset===1/0?r={offset:this.nextParsePosition,time:0}:r.offset=this.stream.getEndFilePositionAfter(r.offset),k.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+r.offset),r}else throw new Error("Cannot seek: moov not received!")}equal(t){let i=0;for(;i<this.boxes.length&&i<t.boxes.length;){let s=this.boxes[i],r=t.boxes[i];if(!Zo(s,r))return!1;i++}return!0}write(t){for(let i=0;i<this.boxes.length;i++)this.boxes[i].write(t)}createFragment(t,i,s,r){let n=[];for(let u=i;u<=s;u++){let h=this.getTrackById(t),f=this.getSample(h,u);if(!f){this.setNextSeekPositionFromSample(h.samples[u]);return}n.push(f)}let a=r||new Dt;a.endianness=1;let o=this.createMoof(n);o.write(a),o.trafs[0].truns[0].data_offset=o.size+8,k.debug("MP4Box","Adjusting data_offset with new value "+o.trafs[0].truns[0].data_offset),a.adjustUint32(o.trafs[0].truns[0].data_offset_position,o.trafs[0].truns[0].data_offset);let c=new sn;c.stream=new tn;let l=0;for(let u of n)if(u.data){let h=Ii.fromArrayBuffer(u.data.buffer,l);c.stream.insertBuffer(h),l+=u.data.byteLength}return c.write(a),a}static writeInitializationSegment(t,i,s){k.debug("ISOFile","Generating initialization segment");let r=new Dt;r.endianness=1,t.write(r);let n=i.addBox(new oa);if(s){let a=n.addBox(new hc);a.fragment_duration=s}for(let a=0;a<i.traks.length;a++){let o=n.addBox(new ca);o.track_id=i.traks[a].tkhd.track_id,o.default_sample_description_index=1,o.default_sample_duration=i.traks[a].samples[0]?.duration??0,o.default_sample_size=0,o.default_sample_flags=65536}return i.write(r),r.buffer}save(t){let i=new Dt;return i.isofile=this,i.endianness=1,this.write(i),i.save(t)}getBuffer(){let t=new Dt;return t.isofile=this,t.endianness=1,this.write(t),t}initializeSegmentation(){this.onSegment||k.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.resetTables());let t=new aa;t.addBox(this.moov.mvhd);for(let i=0;i<this.fragmentedTracks.length;i++){let s=this.getTrackById(this.fragmentedTracks[i].id);if(!s){k.warn("ISOFile",\`Track with id \${this.fragmentedTracks[i].id} not found, skipping fragmentation initialization\`);continue}t.addBox(s)}return{tracks:t.traks.map((i,s)=>({id:i.tkhd.track_id,user:this.fragmentedTracks[s].user})),buffer:Pi.writeInitializationSegment(this.ftyp,t,this.moov?.mvex?.mehd.fragment_duration)}}resetTables(){this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0;for(let t=0;t<this.moov.traks.length;t++){let i=this.moov.traks[t];i.tkhd.duration=0,i.mdia.mdhd.duration=0;let s=i.mdia.minf.stbl.stco||i.mdia.minf.stbl.co64;s.chunk_offsets=[];let r=i.mdia.minf.stbl.stsc;r.first_chunk=[],r.samples_per_chunk=[],r.sample_description_index=[];let n=i.mdia.minf.stbl.stsz||i.mdia.minf.stbl.stz2;n.sample_sizes=[];let a=i.mdia.minf.stbl.stts;a.sample_counts=[],a.sample_deltas=[];let o=i.mdia.minf.stbl.ctts;o&&(o.sample_counts=[],o.sample_offsets=[]);let c=i.mdia.minf.stbl.stss,l=i.mdia.minf.stbl.boxes.indexOf(c);l!==-1&&(i.mdia.minf.stbl.boxes[l]=void 0)}}static initSampleGroups(t,i,s,r,n){i&&(i.sample_groups_info=[]),t.sample_groups_info||(t.sample_groups_info=[]);for(let a=0;a<s.length;a++){let o=s[a].grouping_type+"/"+s[a].grouping_type_parameter,c=new ra(s[a].grouping_type,s[a].grouping_type_parameter,s[a]);i&&(i.sample_groups_info[o]=c),t.sample_groups_info[o]||(t.sample_groups_info[o]=c);for(let l=0;l<r.length;l++)r[l].grouping_type===s[a].grouping_type&&(c.description=r[l],c.description.used=!0);if(n)for(let l=0;l<n.length;l++)n[l].grouping_type===s[a].grouping_type&&(c.fragment_description=n[l],c.fragment_description.used=!0,c.is_fragment=!0)}if(i){if(n){for(let a=0;a<n.length;a++)if(!n[a].used&&n[a].version>=2){let o=n[a].grouping_type+"/0",c=new ra(n[a].grouping_type,0);c.is_fragment=!0,i.sample_groups_info[o]||(i.sample_groups_info[o]=c)}}}else for(let a=0;a<r.length;a++)if(!r[a].used&&r[a].version>=2){let o=r[a].grouping_type+"/0",c=new ra(r[a].grouping_type,0);t.sample_groups_info[o]||(t.sample_groups_info[o]=c)}}static setSampleGroupProperties(t,i,s,r){i.sample_groups=[];for(let n in r)if(i.sample_groups[n]={grouping_type:r[n].grouping_type,grouping_type_parameter:r[n].grouping_type_parameter},s>=r[n].last_sample_in_run&&(r[n].last_sample_in_run<0&&(r[n].last_sample_in_run=0),r[n].entry_index++,r[n].entry_index<=r[n].sbgp.entries.length-1&&(r[n].last_sample_in_run+=r[n].sbgp.entries[r[n].entry_index].sample_count)),r[n].entry_index<=r[n].sbgp.entries.length-1?i.sample_groups[n].group_description_index=r[n].sbgp.entries[r[n].entry_index].group_description_index:i.sample_groups[n].group_description_index=-1,i.sample_groups[n].group_description_index!==0){let a;if(r[n].fragment_description?a=r[n].fragment_description:a=r[n].description,i.sample_groups[n].group_description_index>0){let o;i.sample_groups[n].group_description_index>65535?o=(i.sample_groups[n].group_description_index>>16)-1:o=i.sample_groups[n].group_description_index-1,a&&o>=0&&(i.sample_groups[n].description=a.entries[o])}else a&&a.version>=2&&a.default_group_description_index>0&&(i.sample_groups[n].description=a.entries[a.default_group_description_index-1])}}static process_sdtp(t,i,s){i&&(t?(i.is_leading=t.is_leading[s],i.depends_on=t.sample_depends_on[s],i.is_depended_on=t.sample_is_depended_on[s],i.has_redundancy=t.sample_has_redundancy[s]):(i.is_leading=0,i.depends_on=0,i.is_depended_on=0,i.has_redundancy=0))}buildSampleLists(){for(let t=0;t<this.moov.traks.length;t++)this.buildTrakSampleLists(this.moov.traks[t])}buildTrakSampleLists(t){let i,s,r,n,a,o;t.samples=[],t.samples_duration=0,t.samples_size=0;let c=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,l=t.mdia.minf.stbl.stsc,u=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,h=t.mdia.minf.stbl.stts,f=t.mdia.minf.stbl.ctts,p=t.mdia.minf.stbl.stss,m=t.mdia.minf.stbl.stsd,g=t.mdia.minf.stbl.subs,y=t.mdia.minf.stbl.stdp,w=t.mdia.minf.stbl.sbgps,x=t.mdia.minf.stbl.sgpds,b=-1,S=-1,v=-1,T=-1,C=0,P=0,E=0;if(Pi.initSampleGroups(t,void 0,w,x),!(typeof u>"u")){for(i=0;i<u.sample_sizes.length;i++){let U={number:i,track_id:t.tkhd.track_id,timescale:t.mdia.mdhd.timescale,alreadyRead:0,size:u.sample_sizes[i]};t.samples[i]=U,t.samples_size+=U.size,i===0?(r=1,s=0,U.chunk_index=r,U.chunk_run_index=s,o=l.samples_per_chunk[s],a=0,s+1<l.first_chunk.length?n=l.first_chunk[s+1]-1:n=1/0):i<o?(U.chunk_index=r,U.chunk_run_index=s):(r++,U.chunk_index=r,a=0,r<=n||(s++,s+1<l.first_chunk.length?n=l.first_chunk[s+1]-1:n=1/0),U.chunk_run_index=s,o+=l.samples_per_chunk[s]),U.description_index=l.sample_description_index[U.chunk_run_index]-1,U.description=m.entries[U.description_index],U.offset=c.chunk_offsets[U.chunk_index-1]+a,a+=U.size,i>b&&(S++,b<0&&(b=0),b+=h.sample_counts[S]),i>0?(t.samples[i-1].duration=h.sample_deltas[S],t.samples_duration+=t.samples[i-1].duration,U.dts=t.samples[i-1].dts+t.samples[i-1].duration):U.dts=0,f?(i>=v&&(T++,v<0&&(v=0),v+=f.sample_counts[T]),U.cts=t.samples[i].dts+f.sample_offsets[T]):U.cts=U.dts,p?(i===p.sample_numbers[C]-1?(U.is_sync=!0,C++):(U.is_sync=!1,U.degradation_priority=0),g&&g.entries[P].sample_delta+E===i+1&&(U.subsamples=g.entries[P].subsamples,E+=g.entries[P].sample_delta,P++)):U.is_sync=!0,Pi.process_sdtp(t.mdia.minf.stbl.sdtp,U,U.number),y?U.degradation_priority=y.priority[i]:U.degradation_priority=0,g&&g.entries[P].sample_delta+E===i&&(U.subsamples=g.entries[P].subsamples,E+=g.entries[P].sample_delta),(w.length>0||x.length>0)&&Pi.setSampleGroupProperties(t,U,i,t.sample_groups_info)}i>0&&(t.samples[i-1].duration=Math.max(t.mdia.mdhd.duration-t.samples[i-1].dts,0),t.samples_duration+=t.samples[i-1].duration)}}updateSampleLists(){let t,i,s,r,n;if(this.moov!==void 0)for(;this.lastMoofIndex<this.moofs.length;){let a=this.moofs[this.lastMoofIndex];if(this.lastMoofIndex++,a.type==="moof"){let o=a;for(let c=0;c<o.trafs.length;c++){let l=o.trafs[c],u=this.getTrackById(l.tfhd.track_id),h=this.getTrexById(l.tfhd.track_id);l.tfhd.flags&Xr?t=l.tfhd.default_sample_description_index:t=h?h.default_sample_description_index:1,l.tfhd.flags&Zr?i=l.tfhd.default_sample_duration:i=h?h.default_sample_duration:0,l.tfhd.flags&Qr?s=l.tfhd.default_sample_size:s=h?h.default_sample_size:0,l.tfhd.flags&Kr?r=l.tfhd.default_sample_flags:r=h?h.default_sample_flags:0,l.sample_number=0,l.sbgps.length>0&&Pi.initSampleGroups(u,l,l.sbgps,u.mdia.minf.stbl.sgpds,l.sgpds);for(let f=0;f<l.truns.length;f++){let p=l.truns[f];for(let m=0;m<p.sample_count;m++){let g=t-1,y=r;p.flags&mr?y=p.sample_flags[m]:m===0&&p.flags&Jr&&(y=p.first_sample_flags);let w=s;p.flags&pr&&(w=p.sample_size[m]),u.samples_size+=w;let x=i;p.flags&fr&&(x=p.sample_duration[m]),u.samples_duration+=x;let b;u.first_traf_merged||m>0?b=u.samples[u.samples.length-1].dts+u.samples[u.samples.length-1].duration:(l.tfdt?b=l.tfdt.baseMediaDecodeTime:b=0,u.first_traf_merged=!0);let S=b;p.flags&gr&&(S=b+p.sample_composition_time_offset[m]);let v=!!(l.tfhd.flags&Yr),T=!!(l.tfhd.flags&Do),C=!!(p.flags&hr),P=0;v?P=l.tfhd.base_data_offset:T||f===0?P=o.start:P=n;let E;f===0&&m===0?C?E=P+p.data_offset:E=P:E=n,n=E+w;let U=l.sample_number;l.sample_number++;let H={cts:S,description_index:g,description:u.mdia.minf.stbl.stsd.entries[g],dts:b,duration:x,moof_number:this.lastMoofIndex,number_in_traf:U,number:u.samples.length,offset:E,size:w,timescale:u.mdia.mdhd.timescale,track_id:u.tkhd.track_id,is_sync:!(y>>16&1),is_leading:y>>26&3,depends_on:y>>24&3,is_depended_on:y>>22&3,has_redundancy:y>>20&3,degradation_priority:y&65535};l.first_sample_index=u.samples.length,u.samples.push(H),(l.sbgps.length>0||l.sgpds.length>0||u.mdia.minf.stbl.sbgps.length>0||u.mdia.minf.stbl.sgpds.length>0)&&Pi.setSampleGroupProperties(u,H,H.number_in_traf,l.sample_groups_info)}}if(l.subs){u.has_fragment_subsamples=!0;let f=l.first_sample_index;for(let p=0;p<l.subs.entries.length;p++){f+=l.subs.entries[p].sample_delta;let m=u.samples[f-1];m.subsamples=l.subs.entries[p].subsamples}}}}}}getSample(t,i){let s=t.samples[i];if(this.moov){if(!s.data)s.data=new Uint8Array(s.size),s.alreadyRead=0,this.samplesDataSize+=s.size,k.debug("ISOFile","Allocating sample #"+i+" on track #"+t.tkhd.track_id+" of size "+s.size+" (total: "+this.samplesDataSize+")");else if(s.alreadyRead===s.size)return s;for(;;){let r=this.stream,n=r.findPosition(!0,s.offset+s.alreadyRead,!1),a,o;if(n>-1)a=r.buffers[n],o=a.fileStart;else for(let c of this.mdats){if(!c.stream){k.debug("ISOFile","mdat stream not yet fully read for #"+this.mdats.indexOf(c)+" mdat");continue}if(n=c.stream.findPosition(!0,s.offset+s.alreadyRead-c.start-c.hdr_size,!1),n>-1){r=c.stream,a=c.stream.buffers[n],o=c.start+c.hdr_size+a.fileStart;break}}if(a){let c=a.byteLength-(s.offset+s.alreadyRead-o);if(s.size-s.alreadyRead<=c)return k.debug("ISOFile","Getting sample #"+i+" data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-o)+" read size: "+(s.size-s.alreadyRead)+" full size: "+s.size+")"),Dt.memcpy(s.data.buffer,s.alreadyRead,a,s.offset+s.alreadyRead-o,s.size-s.alreadyRead),a.usedBytes+=s.size-s.alreadyRead,r.logBufferLevel(),s.alreadyRead=s.size,s;if(c===0)return;k.debug("ISOFile","Getting sample #"+i+" partial data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-o)+" read size: "+c+" full size: "+s.size+")"),Dt.memcpy(s.data.buffer,s.alreadyRead,a,s.offset+s.alreadyRead-o,c),s.alreadyRead+=c,a.usedBytes+=c,r.logBufferLevel()}else return}}}releaseSample(t,i){let s=t.samples[i];return s.data?(this.samplesDataSize-=s.size,s.data=void 0,s.alreadyRead=0,s.size):0}getAllocatedSampleDataSize(){return this.samplesDataSize}getCodecs(){let t="";for(let i=0;i<this.moov.traks.length;i++){let s=this.moov.traks[i];i>0&&(t+=","),t+=s.mdia.minf.stbl.stsd.entries[0].getCodec()}return t}getTrexById(t){if(!(!this.moov||!this.moov.mvex))for(let i=0;i<this.moov.mvex.trexs.length;i++){let s=this.moov.mvex.trexs[i];if(s.track_id===t)return s}}getTrackById(t){if(this.moov)for(let i=0;i<this.moov.traks.length;i++){let s=this.moov.traks[i];if(s.tkhd.track_id===t)return s}}flattenItemInfo(){let t=this.items,i=this.entity_groups,s=this.meta;if(!(!s||!s.hdlr||!s.iinf)){for(let r=0;r<s.iinf.item_infos.length;r++){let n=s.iinf.item_infos[r].item_ID;t[n]={id:n,name:s.iinf.item_infos[r].item_name,ref_to:[],content_type:s.iinf.item_infos[r].content_type,content_encoding:s.iinf.item_infos[r].content_encoding,item_uri_type:s.iinf.item_infos[r].item_uri_type,type:s.iinf.item_infos[r].item_type?s.iinf.item_infos[r].item_type:"mime",protection:s.iinf.item_infos[r].item_protection_index>0?s.ipro.protections[s.iinf.item_infos[r].item_protection_index-1]:void 0}}if(s.grpl)for(let r=0;r<s.grpl.boxes.length;r++){let n=s.grpl.boxes[r];i[n.group_id]={id:n.group_id,entity_ids:n.entity_ids,type:n.type}}if(s.iloc)for(let r=0;r<s.iloc.items.length;r++){let n=s.iloc.items[r],a=t[n.item_ID];n.data_reference_index!==0&&(k.warn("Item storage with reference to other files: not supported"),a.source=s.dinf.boxes[n.data_reference_index-1]),a.extents=[],a.size=0;for(let o=0;o<n.extents.length;o++)a.extents[o]={offset:n.extents[o].extent_offset+n.base_offset,length:n.extents[o].extent_length,alreadyRead:0},n.construction_method===1&&(a.extents[o].offset+=s.idat.start+s.idat.hdr_size),a.size+=a.extents[o].length}if(s.pitm&&(t[s.pitm.item_id].primary=!0),s.iref)for(let r=0;r<s.iref.references.length;r++){let n=s.iref.references[r];for(let a=0;a<n.references.length;a++)t[n.from_item_ID].ref_to.push({type:n.type,id:n.references[a]})}if(s.iprp)for(let r=0;r<s.iprp.ipmas.length;r++){let n=s.iprp.ipmas[r];for(let a=0;a<n.associations.length;a++){let o=n.associations[a],c=t[o.id]??i[o.id];if(c){c.properties===void 0&&(c.properties={boxes:[]});for(let l=0;l<o.props.length;l++){let u=o.props[l];if(u.property_index>0&&u.property_index-1<s.iprp.ipco.boxes.length){let h=s.iprp.ipco.boxes[u.property_index-1];c.properties[h.type]=h,c.properties.boxes.push(h)}}}}}}}getItem(t){if(!this.meta)return;let i=this.items[t];if(!i.data&&i.size)i.data=new Uint8Array(i.size),i.alreadyRead=0,this.itemsDataSize+=i.size,k.debug("ISOFile","Allocating item #"+t+" of size "+i.size+" (total: "+this.itemsDataSize+")");else if(i.alreadyRead===i.size)return i;for(let s=0;s<i.extents.length;s++){let r=i.extents[s];if(r.alreadyRead!==r.length){let n=this.stream.findPosition(!0,r.offset+r.alreadyRead,!1);if(n>-1){let a=this.stream.buffers[n],o=a.byteLength-(r.offset+r.alreadyRead-a.fileStart);if(r.length-r.alreadyRead<=o)k.debug("ISOFile","Getting item #"+t+" extent #"+s+" data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-a.fileStart)+" read size: "+(r.length-r.alreadyRead)+" full extent size: "+r.length+" full item size: "+i.size+")"),Dt.memcpy(i.data.buffer,i.alreadyRead,a,r.offset+r.alreadyRead-a.fileStart,r.length-r.alreadyRead),(!this.parsingMdat||this.discardMdatData)&&(a.usedBytes+=r.length-r.alreadyRead),this.stream.logBufferLevel(),i.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length;else{k.debug("ISOFile","Getting item #"+t+" extent #"+s+" partial data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-a.fileStart)+" read size: "+o+" full extent size: "+r.length+" full item size: "+i.size+")"),Dt.memcpy(i.data.buffer,i.alreadyRead,a,r.offset+r.alreadyRead-a.fileStart,o),r.alreadyRead+=o,i.alreadyRead+=o,(!this.parsingMdat||this.discardMdatData)&&(a.usedBytes+=o),this.stream.logBufferLevel();return}}else return}}if(i.alreadyRead===i.size)return i}releaseItem(t){let i=this.items[t];if(i.data){this.itemsDataSize-=i.size,i.data=void 0,i.alreadyRead=0;for(let s=0;s<i.extents.length;s++){let r=i.extents[s];r.alreadyRead=0}return i.size}else return 0}processItems(t){for(let i in this.items){let s=this.items[i];this.getItem(s.id),t&&!s.sent&&(t(s),s.sent=!0,s.data=void 0)}}hasItem(t){for(let i in this.items){let s=this.items[i];if(s.name===t)return s.id}return-1}getMetaHandler(){if(this.meta)return this.meta.hdlr.handler}getPrimaryItem(){if(this.meta&&this.meta.pitm)return this.getItem(this.meta.pitm.item_id)}itemToFragmentedTrackFile({itemId:t}={}){let i;if(t?i=this.getItem(t):i=this.getPrimaryItem(),!i)return;let s=new Pi;s.discardMdatData=!1;let r={type:i.type,description_boxes:i.properties.boxes};i.properties.ispe&&(r.width=i.properties.ispe.image_width,r.height=i.properties.ispe.image_height);let n=s.addTrack(r);if(n)return s.addSample(n,i.data),s}processIncompleteBox(t){if(t.type==="mdat"){let i=new sn(t.size);return this.parsingMdat=i,this.boxes.push(i),this.mdats.push(i),i.start=t.start,i.hdr_size=t.hdr_size,i.original_size=t.original_size,this.stream.addUsedBytes(i.hdr_size),this.lastBoxStartPosition=i.start+i.size,this.stream.seek(i.start+i.size,!1,this.discardMdatData)?(this.transferMdatData(),this.parsingMdat=void 0,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=i.start+i.size,!1)}else return t.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),(this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1)?(this.nextParsePosition=this.stream.getEndPosition(),!0):(t.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+t.size:this.nextParsePosition=this.stream.getEndPosition(),!1)}hasIncompleteMdat(){return this.parsingMdat!==void 0}transferMdatData(t){let i=t??this.parsingMdat;if(this.discardMdatData){k.debug("ISOFile","Discarding 'mdat' data, not transferring it to the mdat box stream");return}if(!i){k.warn("ISOFile","Cannot transfer 'mdat' data, no mdat box is being parsed");return}let s=this.stream.findPosition(!0,i.start+i.hdr_size,!1),r=this.stream.findPosition(!0,i.start+i.size,!1);if(s===-1||r===-1){console.trace(i,s,r),k.warn("ISOFile","Cannot transfer 'mdat' data, start or end buffer not found");return}i.stream=new tn;for(let n=s;n<=r;n++){let a=this.stream.buffers[n],o=n===s?i.start+i.hdr_size-a.fileStart:0,c=n===r?i.start+i.size-a.fileStart:a.byteLength;if(c>o){k.debug("ISOFile","Transferring 'mdat' data from buffer #"+n+" ("+o+" to "+c+")");let l=c-o,u=new Ii(l),h=i.stream.getAbsoluteEndPosition();Dt.memcpy(u,0,a,o,l),u.fileStart=h,i.stream.insertBuffer(u),a.usedBytes+=l}}}processIncompleteMdat(){let t=this.parsingMdat;return this.stream.seek(t.start+t.size,!1,this.discardMdatData)?(k.debug("ISOFile","Found 'mdat' end in buffered data"),this.transferMdatData(),this.parsingMdat=void 0,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)}restoreParsePosition(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)}saveParsePosition(){this.lastBoxStartPosition=this.stream.getPosition()}updateUsedBytes(t,i){this.stream.addUsedBytes&&(t.type==="mdat"?(this.stream.addUsedBytes(t.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(t.size-t.hdr_size)):this.stream.addUsedBytes(t.size))}addBox(t){return O.prototype.addBox.call(this,t)}init(t={}){let i=this.addBox(new cc);i.major_brand=t.brands&&t.brands[0]||"iso4",i.minor_version=0,i.compatible_brands=t.brands||["iso4"];let s=this.addBox(new aa);s.addBox(new oa);let r=s.addBox(new mc);return r.timescale=t.timescale||600,r.rate=t.rate||65536,r.creation_time=0,r.modification_time=0,r.duration=t.duration||0,r.volume=t.width?0:256,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.next_track_id=1,this}addTrack(t={}){this.moov||this.init(t);let i=t||{};i.width=i.width||320,i.height=i.height||320,i.id=i.id||this.moov.mvhd.next_track_id,i.type=i.type||"avc1";let s=this.moov.addBox(new Jo);this.moov.mvhd.next_track_id=i.id+1;let r=s.addBox(new Bc);r.flags=Eu|Uu|Bu,r.creation_time=0,r.modification_time=0,r.track_id=i.id,r.duration=i.duration||0,r.layer=i.layer||0,r.alternate_group=0,r.volume=1,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.width=i.width<<16,r.height=i.height<<16;let n=s.addBox(new ec),a=n.addBox(new uc);a.creation_time=0,a.modification_time=0,a.timescale=i.timescale||1,a.duration=i.media_duration||0,a.language=i.language||"und";let o=n.addBox(new lc);o.handler=i.hdlr||"vide",o.name=i.name||"Track created with MP4Box.js";let c=n.addBox(new oc);c.extended_language=i.language||"fr-FR";let l=n.addBox(new tc),u=zt.sampleEntry[i.type];if(!u)return;let h=new u;if(h.data_reference_index=1,h instanceof $e){let T=h,C=l.addBox(new Mc);C.graphicsmode=0,C.opcolor=[0,0,0],T.width=i.width,T.height=i.height,T.horizresolution=72<<16,T.vertresolution=72<<16,T.frame_count=1,T.compressorname=i.type+" Compressor",T.depth=24,i.avcDecoderConfigRecord?T.addBox(new Qo(i.avcDecoderConfigRecord.byteLength)).parse(new Wo(i.avcDecoderConfigRecord)):i.hevcDecoderConfigRecord&&T.addBox(new dc(i.hevcDecoderConfigRecord.byteLength)).parse(new Wo(i.hevcDecoderConfigRecord))}else if(h instanceof Pt){let T=h,C=l.addBox(new yc);C.balance=i.balance||0,T.channel_count=i.channel_count||2,T.samplesize=i.samplesize||16,T.samplerate=i.samplerate||65536}else h instanceof qo?l.addBox(new Ko):h instanceof Zi?(l.addBox(new vc),h instanceof xc&&(h.namespace=i.namespace||"nonamespace",h.schema_location=i.schema_location||"",h.auxiliary_mime_types=i.auxiliary_mime_types||"")):h instanceof Ms?l.addBox(new rn):h instanceof ua?l.addBox(new rn):l.addBox(new rn);i.description&&h.addBox.call(h,i.description),i.description_boxes&&i.description_boxes.forEach(function(T){h.addBox.call(h,T)});let p=l.addBox(new ic).addBox(new ac),m=new Cc;m.flags=1,p.addEntry(m);let g=l.addBox(new sc);g.addBox(new Sc).addEntry(h);let w=g.addBox(new Tc);w.sample_counts=[],w.sample_deltas=[];let x=g.addBox(new wc);x.first_chunk=[],x.samples_per_chunk=[],x.sample_description_index=[];let b=g.addBox(new bc);b.chunk_offsets=[];let S=g.addBox(new kc);S.sample_sizes=[];let v=this.moov.mvex.addBox(new ca);return v.track_id=i.id,v.default_sample_description_index=i.default_sample_description_index||1,v.default_sample_duration=i.default_sample_duration||0,v.default_sample_size=i.default_sample_size||0,v.default_sample_flags=i.default_sample_flags||0,this.buildTrakSampleLists(s),i.id}addSample(t,i,{sample_description_index:s,duration:r=1,cts:n=0,dts:a=0,is_sync:o=!1,is_leading:c=0,depends_on:l=0,is_depended_on:u=0,has_redundancy:h=0,degradation_priority:f=0,subsamples:p,offset:m=0}={}){let g=this.getTrackById(t);if(g===void 0)return;let y=s?s-1:0,w={number:g.samples.length,track_id:g.tkhd.track_id,timescale:g.mdia.mdhd.timescale,description_index:y,description:g.mdia.minf.stbl.stsd.entries[y],data:i,size:i.byteLength,alreadyRead:i.byteLength,duration:r,cts:n,dts:a,is_sync:o,is_leading:c,depends_on:l,is_depended_on:u,has_redundancy:h,degradation_priority:f,offset:m,subsamples:p};g.samples.push(w),g.samples_size+=w.size,g.samples_duration+=w.duration,g.first_dts===void 0&&(g.first_dts=a),this.processSamples();let x=this.addBox(this.createMoof([w]));x.computeSize(),x.trafs[0].truns[0].data_offset=x.size+8;let b=this.addBox(new sn);return b.data=new Uint8Array(i),w}createMoof(t){if(t.length===0)return;if(t.some(u=>u.track_id!==t[0].track_id))throw new Error("Cannot create moof for samples from different tracks: "+t.map(u=>u.track_id).join(", "));let i=t[0].track_id,s=this.getTrackById(i);if(!s)throw new Error("Cannot create moof for non-existing track: "+i);let r=new rc,n=r.addBox(new pc);n.sequence_number=++this.nextMoofNumber;let a=r.addBox(new nc),o=a.addBox(new Uc);o.track_id=i,o.flags=Do;let c=a.addBox(new Ec);c.baseMediaDecodeTime=t[0].dts-(s.first_dts||0);let l=a.addBox(new Ac);l.flags=hr|fr|pr|mr|gr,l.data_offset=0,l.first_sample_flags=0,l.sample_count=t.length;for(let u of t){let h=0;u.is_sync?h=1<<25:h=65536,l.sample_duration.push(u.duration),l.sample_size.push(u.size),l.sample_flags.push(h),l.sample_composition_time_offset.push(u.cts-u.dts)}return r}print(t){t.indent="";for(let i=0;i<this.boxes.length;i++)this.boxes[i]&&this.boxes[i].print(t)}};function zc(e=!1,t){return new Cf(t,!e)}var Pc={};$o(Pc,{Descriptor:()=>Qi,ES_Descriptor:()=>Lc,MPEG4DescriptorParser:()=>Rf});var Ic=3,on=4,ha=5,Rc=6,Qi=class Fc{constructor(t,i){this.tag=t,this.size=i,this.descs=[]}parse(t){this.data=t.readUint8Array(this.size)}findDescriptor(t){for(let i=0;i<this.descs.length;i++)if(this.descs[i].tag===t)return this.descs[i]}parseOneDescriptor(t){let i=0,s=t.readUint8(),r=t.readUint8();for(;r&128;)i=(i<<7)+(r&127),r=t.readUint8();i=(i<<7)+(r&127),k.debug("Descriptor","Found "+(nn[s]||"Descriptor "+s)+", size "+i+" at position "+t.getPosition());let n=nn[s]?new If[nn[s]](i):new Fc(i);return n.parse(t),n}parseRemainingDescriptors(t){let i=t.getPosition();for(;t.getPosition()<i+this.size;){let s=this.parseOneDescriptor?.(t);this.descs.push(s)}}},Lc=class extends Qi{constructor(e){super(Ic,e)}parse(e){if(this.ES_ID=e.readUint16(),this.flags=e.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=e.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){let t=e.readUint8();this.URL=e.readString(t),this.size-=t+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=e.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(e)}getOTI(){let e=this.findDescriptor(on);return e?e.oti:0}getAudioConfig(){let e=this.findDescriptor(on);if(!e)return;let t=e.findDescriptor(ha);if(t&&t.data){let i=(t.data[0]&248)>>3;return i===31&&t.data.length>=2&&(i=32+((t.data[0]&7)<<3)+((t.data[1]&224)>>5)),i}}},Mf=class extends Qi{constructor(e){super(on,e)}parse(e){this.oti=e.readUint8(),this.streamType=e.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=e.readUint24(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32(),this.size-=13,this.parseRemainingDescriptors(e)}},zf=class extends Qi{constructor(e){super(ha,e)}},Pf=class extends Qi{constructor(e){super(Rc,e)}},If={Descriptor:Qi,ES_Descriptor:Lc,DecoderConfigDescriptor:Mf,DecoderSpecificInfo:zf,SLConfigDescriptor:Pf},nn={[Ic]:"ES_Descriptor",[on]:"DecoderConfigDescriptor",[ha]:"DecoderSpecificInfo",[Rc]:"SLConfigDescriptor"},Rf=class{constructor(){this.parseOneDescriptor=Qi.prototype.parseOneDescriptor}getDescriptorName(e){return nn[e]}};var Oc={};$o(Oc,{CoLLBox:()=>Yf,ItemContentIDPropertyBox:()=>vg,OpusSampleEntry:()=>cf,SmDmBox:()=>ym,a1lxBox:()=>Ff,a1opBox:()=>Lf,ac_3SampleEntry:()=>nf,ac_4SampleEntry:()=>af,aebrBox:()=>hp,afbrBox:()=>fp,albcBox:()=>pp,alstSampleGroupEntry:()=>Zm,altrBox:()=>mp,auxCBox:()=>Of,av01SampleEntry:()=>Ph,av1CBox:()=>kh,avc1SampleEntry:()=>Ah,avc2SampleEntry:()=>Ch,avc3SampleEntry:()=>Mh,avc4SampleEntry:()=>zh,avcCBox:()=>Qo,avllSampleGroupEntry:()=>Qm,avs3SampleEntry:()=>Zh,avssSampleGroupEntry:()=>Km,brstBox:()=>gp,btrtBox:()=>Df,bxmlBox:()=>Yu,ccstBox:()=>Nf,cdefBox:()=>Hf,clapBox:()=>Gf,clefBox:()=>rm,clliBox:()=>Vf,cmexBox:()=>Wf,cminBox:()=>qf,cmpdBox:()=>jf,co64Box:()=>$f,colrBox:()=>Bh,coviBox:()=>Qf,cprtBox:()=>Kf,cschBox:()=>Jf,cslgBox:()=>ep,cttsBox:()=>tp,dOpsBox:()=>cp,dac3Box:()=>ip,dataBox:()=>ur,dav1SampleEntry:()=>Ih,dec3Box:()=>sp,dfLaBox:()=>rp,dimmBox:()=>np,dinfBox:()=>ic,dmax:()=>ap,dmedBox:()=>op,dobrBox:()=>_p,drefBox:()=>ac,drepBox:()=>lp,dtrtSampleGroupEntry:()=>Jm,dvh1SampleEntry:()=>Gh,dvheSampleEntry:()=>Vh,ec_3SampleEntry:()=>of,edtsBox:()=>Zu,elngBox:()=>oc,elstBox:()=>dp,emsgBox:()=>up,encaSampleEntry:()=>mf,encmSampleEntry:()=>bf,encsSampleEntry:()=>_f,enctSampleEntry:()=>yf,encuSampleEntry:()=>gf,encvSampleEntry:()=>pf,enofBox:()=>am,eqivBox:()=>xp,esdsBox:()=>Th,etypBox:()=>fh,fLaCSampleEntry:()=>ff,favcBox:()=>yp,fielBox:()=>Ap,fobrBox:()=>bp,freeBox:()=>Wu,frmaBox:()=>Cp,ftypBox:()=>cc,grplBox:()=>uh,hdlrBox:()=>lc,hev1SampleEntry:()=>Lh,hev2SampleEntry:()=>Oh,hinfBox:()=>th,hmhdBox:()=>Ko,hntiBox:()=>eh,hvc1SampleEntry:()=>Rh,hvc2SampleEntry:()=>Fh,hvcCBox:()=>dc,hvt1SampleEntry:()=>Dh,iaugBox:()=>vp,idatBox:()=>Vu,iinfBox:()=>gh,ilocBox:()=>_h,ilstBox:()=>om,imirBox:()=>Mp,infeBox:()=>mh,iodsBox:()=>ju,ipcoBox:()=>dh,ipmaBox:()=>zp,iproBox:()=>Xu,iprpBox:()=>lh,irefBox:()=>yh,irotBox:()=>Pp,ispeBox:()=>Ip,itaiBox:()=>Rp,j2kHBox:()=>hh,j2kiSampleEntry:()=>Qh,keysBox:()=>cm,kindBox:()=>Fp,levaBox:()=>Lp,lhe1SampleEntry:()=>Nh,lhv1SampleEntry:()=>Hh,lhvCBox:()=>Op,lselBox:()=>Dp,m4aeSampleEntry:()=>rf,maxrBox:()=>Np,mdatBox:()=>sn,mdcvBox:()=>Hp,mdhdBox:()=>uc,mdiaBox:()=>ec,mecoBox:()=>Ju,mehdBox:()=>hc,metaBox:()=>vh,mettSampleEntry:()=>wh,metxSampleEntry:()=>Sh,mfhdBox:()=>pc,mfraBox:()=>Ku,mfroBox:()=>Gp,mha1SampleEntry:()=>lf,mha2SampleEntry:()=>df,mhm1SampleEntry:()=>uf,mhm2SampleEntry:()=>hf,minfBox:()=>tc,mjp2SampleEntry:()=>Kh,mjpgSampleEntry:()=>Jh,moofBox:()=>rc,moovBox:()=>aa,mp4aSampleEntry:()=>sf,mp4sSampleEntry:()=>xf,mp4vSampleEntry:()=>tf,mskCBox:()=>Vp,msrcTrackGroupTypeBox:()=>Om,mvexBox:()=>oa,mvhdBox:()=>mc,mvifSampleGroupEntry:()=>eg,nmhdBox:()=>rn,npckBox:()=>Wp,numpBox:()=>qp,padbBox:()=>$p,panoBox:()=>wp,paspBox:()=>Yp,paylBox:()=>Xp,paytBox:()=>Zp,pdinBox:()=>Qp,piffLsmBox:()=>mg,piffPsshBox:()=>gg,piffSencBox:()=>_g,piffTencBox:()=>xg,piffTfrfBox:()=>yg,piffTfxdBox:()=>bg,pitmBox:()=>bh,pixiBox:()=>Kp,pmaxBox:()=>Jp,povdBox:()=>ph,prdiBox:()=>em,prfrBox:()=>tm,prftBox:()=>im,prgrBox:()=>Up,profBox:()=>lm,prolSampleGroupEntry:()=>tg,psshBox:()=>sm,pymdBox:()=>Bp,rapSampleGroupEntry:()=>ig,rashSampleGroupEntry:()=>sg,resvSampleEntry:()=>vf,rinfBox:()=>nh,rollSampleGroupEntry:()=>rg,rtp_Box:()=>um,saioBox:()=>hm,saizBox:()=>fm,sbgpBox:()=>Ef,sbpmBox:()=>mm,sbttSampleEntry:()=>wf,schiBox:()=>ah,schmBox:()=>gm,scifSampleGroupEntry:()=>ng,scnmSampleGroupEntry:()=>ag,sdp_Box:()=>_m,sdtpBox:()=>Uf,seigSampleGroupEntry:()=>og,sencBox:()=>xm,sgpdBox:()=>Bf,sidxBox:()=>Af,sinfBox:()=>rh,skipBox:()=>qu,slidBox:()=>Sp,smhdBox:()=>yc,ssixBox:()=>bm,stblBox:()=>sc,stcoBox:()=>bc,stdpBox:()=>vm,sterBox:()=>kp,sthdBox:()=>vc,stppSampleEntry:()=>xc,strdBox:()=>sh,striBox:()=>wm,strkBox:()=>ih,stsaSampleGroupEntry:()=>cg,stscBox:()=>wc,stsdBox:()=>Sc,stsgBox:()=>Sm,stshBox:()=>km,stssBox:()=>Tm,stszBox:()=>kc,sttsBox:()=>Tc,stviBox:()=>Em,stxtSampleEntry:()=>Sf,stypBox:()=>Um,stz2Box:()=>Bm,subsBox:()=>Am,syncSampleGroupEntry:()=>lg,taicBox:()=>Cm,taptBox:()=>dm,teleSampleGroupEntry:()=>dg,tencBox:()=>Mm,tfdtBox:()=>Ec,tfhdBox:()=>Uc,tfraBox:()=>zm,tkhdBox:()=>Bc,tmaxBox:()=>Pm,tminBox:()=>Im,totlBox:()=>Rm,tpayBox:()=>Fm,tpylBox:()=>Lm,trafBox:()=>nc,trakBox:()=>Jo,trefBox:()=>Dm,trepBox:()=>Nm,trexBox:()=>ca,trgrBox:()=>oh,trpyBox:()=>Hm,trunBox:()=>Ac,tsasSampleGroupEntry:()=>ug,tsclSampleGroupEntry:()=>hg,tselBox:()=>Gm,tsynBox:()=>Tp,tx3gSampleEntry:()=>kf,txtcBox:()=>Vm,tycoBox:()=>Wm,udesBox:()=>qm,udtaBox:()=>ch,uncCBox:()=>jm,uncvSampleEntry:()=>ef,urlBox:()=>Cc,urnBox:()=>$m,viprSampleGroupEntry:()=>fg,vmhdBox:()=>Mc,vp08SampleEntry:()=>Yh,vp09SampleEntry:()=>Xh,vpcCBox:()=>Eh,vttCBox:()=>Ym,vttcBox:()=>Qu,vvc1SampleEntry:()=>Wh,vvcCBox:()=>Uh,vvcNSampleEntry:()=>$h,vvi1SampleEntry:()=>qh,vvnCBox:()=>Xm,vvs1SampleEntry:()=>jh,wbbrBox:()=>Ep,wvttSampleEntry:()=>Tf,xmlBox:()=>$u});var Ff=class extends O{constructor(){super(...arguments),this.box_name="AV1LayeredImageIndexingProperty"}static{this.fourcc="a1lx"}parse(e){let i=((e.readUint8()&1&1)+1)*16;this.layer_size=[];for(let s=0;s<3;s++)i===16?this.layer_size[s]=e.readUint16():this.layer_size[s]=e.readUint32()}},Lf=class extends O{constructor(){super(...arguments),this.box_name="OperatingPointSelectorProperty"}static{this.fourcc="a1op"}parse(e){this.op_index=e.readUint8()}},Of=class extends B{constructor(){super(...arguments),this.box_name="AuxiliaryTypeProperty"}static{this.fourcc="auxC"}parse(e){this.parseFullHeader(e),this.aux_type=e.readCString();let t=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=e.readUint8Array(t)}},Df=class extends O{constructor(){super(...arguments),this.box_name="BitRateBox"}static{this.fourcc="btrt"}parse(e){this.bufferSizeDB=e.readUint32(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32()}},Nf=class extends B{constructor(){super(...arguments),this.box_name="CodingConstraintsBox"}static{this.fourcc="ccst"}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.all_ref_pics_intra=(t&128)===128,this.intra_pred_used=(t&64)===64,this.max_ref_per_pic=(t&63)>>2,e.readUint24()}},Hf=class extends O{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}static{this.fourcc="cdef"}parse(e){this.channel_count=e.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];for(let t=0;t<this.channel_count;t++)this.channel_indexes.push(e.readUint16()),this.channel_types.push(e.readUint16()),this.channel_associations.push(e.readUint16())}},Gf=class extends O{constructor(){super(...arguments),this.box_name="CleanApertureBox"}static{this.fourcc="clap"}parse(e){this.cleanApertureWidthN=e.readUint32(),this.cleanApertureWidthD=e.readUint32(),this.cleanApertureHeightN=e.readUint32(),this.cleanApertureHeightD=e.readUint32(),this.horizOffN=e.readUint32(),this.horizOffD=e.readUint32(),this.vertOffN=e.readUint32(),this.vertOffD=e.readUint32()}},Vf=class extends O{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}static{this.fourcc="clli"}parse(e){this.max_content_light_level=e.readUint16(),this.max_pic_average_light_level=e.readUint16()}},Wf=class extends O{constructor(){super(...arguments),this.box_name="CameraExtrinsicMatrixProperty"}static{this.fourcc="cmex"}parse(e){this.flags&1&&(this.pos_x=e.readInt32()),this.flags&2&&(this.pos_y=e.readInt32()),this.flags&4&&(this.pos_z=e.readInt32()),this.flags&8&&(this.version===0?this.flags&16?(this.quat_x=e.readInt32(),this.quat_y=e.readInt32(),this.quat_z=e.readInt32()):(this.quat_x=e.readInt16(),this.quat_y=e.readInt16(),this.quat_z=e.readInt16()):this.version),this.flags&32&&(this.id=e.readUint32())}},qf=class extends O{constructor(){super(...arguments),this.box_name="CameraIntrinsicMatrixProperty"}static{this.fourcc="cmin"}parse(e){this.focal_length_x=e.readInt32(),this.principal_point_x=e.readInt32(),this.principal_point_y=e.readInt32(),this.flags&1&&(this.focal_length_y=e.readInt32(),this.skew_factor=e.readInt32())}},jf=class extends O{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}static{this.fourcc="cmpd"}parse(e){this.component_count=e.readUint32(),this.component_types=[],this.component_type_urls=[];for(let t=0;t<this.component_count;t++){let i=e.readUint16();this.component_types.push(i),i>=32768&&this.component_type_urls.push(e.readCString())}}},$f=class extends B{constructor(){super(...arguments),this.box_name="ChunkLargeOffsetBox"}static{this.fourcc="co64"}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.chunk_offsets=[],this.version===0)for(let i=0;i<t;i++)this.chunk_offsets.push(e.readUint64())}write(e){this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length);for(let t=0;t<this.chunk_offsets.length;t++)e.writeUint64(this.chunk_offsets[t])}},Yf=class extends B{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}static{this.fourcc="CoLL"}parse(e){this.parseFullHeader(e),this.maxCLL=e.readUint16(),this.maxFALL=e.readUint16()}},Xf=class{toString(){let e="centre_azimuth: ";return e+=this.centre_azimuth,e+=" (",e+=this.centre_azimuth*2**-16,e+="\\xB0), centre_elevation: ",e+=this.centre_elevation,e+=" (",e+=this.centre_elevation*2**-16,e+="\\xB0), centre_tilt: ",e+=this.centre_tilt,e+=" (",e+=this.centre_tilt*2**-16,e+="\\xB0)",this.range_included_flag&&(e+=", azimuth_range: ",e+=this.azimuth_range,e+=" (",e+=this.azimuth_range*2**-16,e+="\\xB0), elevation_range: ",e+=this.elevation_range,e+=" (",e+=this.elevation_range*2**-16,e+="\\xB0)"),this.interpolate_included_flag&&(e+=", interpolate: ",e+=this.interpolate),e}},Zf=class{toString(){let e="";return this.view_idc&&(e+="view_idc: ",e+=this.view_idc,e+=", "),e+="sphere_region: {",e+=this.sphere_region,e+="}",e}},Qf=class extends B{constructor(){super(...arguments),this.box_name="CoverageInformationBox"}static{this.fourcc="covi"}parse(e){this.parseFullHeader(e),this.coverage_shape_type=e.readUint8();let t=e.readUint8(),i=e.readInt8(),s=i&128;s&&(this.default_view_idc=(i&96)>>5),this.coverage_regions=new Array;for(let r=0;r<t;r++){let n=new Zf;s&&(n.view_idc=e.readUint8()>>6),n.sphere_region=this.parseSphereRegion(e,!0,!0),this.coverage_regions.push(n)}}parseSphereRegion(e,t,i){let s=new Xf;return s.centre_azimuth=e.readInt32(),s.centre_elevation=e.readInt32(),s.centre_tilt=e.readInt32(),s.range_included_flag=t,t&&(s.azimuth_range=e.readUint32(),s.elevation_range=e.readUint32()),s.interpolate_included_flag=i,i&&(s.interpolate=(e.readUint8()&128)===128),s}},Kf=class extends B{constructor(){super(...arguments),this.box_name="CopyrightBox"}static{this.fourcc="cprt"}parse(e){this.parseFullHeader(e),this.parseLanguage(e),this.notice=e.readCString()}},Jf=class extends B{constructor(){super(...arguments),this.box_name="CompatibleSchemeTypeBox"}static{this.fourcc="csch"}parse(e){this.parseFullHeader(e),this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readCString())}},dr=2147483647,ep=class extends B{constructor(){super(...arguments),this.box_name="CompositionToDecodeBox"}static{this.fourcc="cslg"}parse(e){this.parseFullHeader(e),this.version===0?(this.compositionToDTSShift=e.readInt32(),this.leastDecodeToDisplayDelta=e.readInt32(),this.greatestDecodeToDisplayDelta=e.readInt32(),this.compositionStartTime=e.readInt32(),this.compositionEndTime=e.readInt32()):this.version===1&&(this.compositionToDTSShift=e.readInt64(),this.leastDecodeToDisplayDelta=e.readInt64(),this.greatestDecodeToDisplayDelta=e.readInt64(),this.compositionStartTime=e.readInt64(),this.compositionEndTime=e.readInt64())}write(e){this.version=0,(this.compositionToDTSShift>dr||this.leastDecodeToDisplayDelta>dr||this.greatestDecodeToDisplayDelta>dr||this.compositionStartTime>dr||this.compositionEndTime>dr)&&(this.version=1),this.flags=0,this.version===0?(this.size=4*5,this.writeHeader(e),e.writeInt32(this.compositionToDTSShift),e.writeInt32(this.leastDecodeToDisplayDelta),e.writeInt32(this.greatestDecodeToDisplayDelta),e.writeInt32(this.compositionStartTime),e.writeInt32(this.compositionEndTime)):this.version===1&&(this.size=8*5,this.writeHeader(e),e.writeInt64(this.compositionToDTSShift),e.writeInt64(this.leastDecodeToDisplayDelta),e.writeInt64(this.greatestDecodeToDisplayDelta),e.writeInt64(this.compositionStartTime),e.writeInt64(this.compositionEndTime))}},tp=class extends B{constructor(){super(...arguments),this.box_name="CompositionOffsetBox"}static{this.fourcc="ctts"}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(let i=0;i<t;i++){this.sample_counts.push(e.readUint32());let s=e.readInt32();s<0&&k.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(s)}else if(this.version===1)for(let i=0;i<t;i++)this.sample_counts.push(e.readUint32()),this.sample_offsets.push(e.readInt32())}write(e){this.version=this.sample_offsets.some(t=>t<0)?1:0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length);for(let t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),this.version===1?e.writeInt32(this.sample_offsets[t]):e.writeUint32(this.sample_offsets[t])}unpack(e){let t=0;for(let i=0;i<this.sample_counts.length;i++)for(let s=0;s<this.sample_counts[i];s++)e[t].pts=e[t].dts+this.sample_offsets[i],t++}},ip=class extends O{constructor(){super(...arguments),this.box_name="AC3SpecificBox"}static{this.fourcc="dac3"}parse(e){let t=e.readUint8(),i=e.readUint8(),s=e.readUint8();this.fscod=t>>6,this.bsid=t>>1&31,this.bsmod=(t&1)<<2|i>>6&3,this.acmod=i>>3&7,this.lfeon=i>>2&1,this.bit_rate_code=i&3|s>>5&7}},sp=class extends O{constructor(){super(...arguments),this.box_name="EC3SpecificBox"}static{this.fourcc="dec3"}parse(e){let t=e.readUint16();this.data_rate=t>>3,this.num_ind_sub=t&7,this.ind_subs=[];for(let i=0;i<this.num_ind_sub+1;i++){let s=e.readUint8(),r=e.readUint8(),n=e.readUint8(),a={fscod:s>>6,bsid:s>>1&31,bsmod:(s&1)<<4|r>>4&15,acmod:r>>1&7,lfeon:r&1,num_dep_sub:n>>1&15};this.ind_subs.push(a),a.num_dep_sub>0&&(a.chan_loc=(n&1)<<8|e.readUint8())}}},rp=class extends B{constructor(){super(...arguments),this.box_name="FLACSpecificBox"}static{this.fourcc="dfLa"}parse(e){this.parseFullHeader(e);let t=127,i=128,s=[],r=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"],n;do{n=e.readUint8();let a=Math.min(n&t,r.length-1);a?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),s.push(r[a])}while(n&i);this.numMetadataBlocks=s.length+" ("+s.join(", ")+")"}},np=class extends O{constructor(){super(...arguments),this.box_name="hintimmediateBytesSent"}static{this.fourcc="dimm"}parse(e){this.bytessent=e.readUint64()}},ap=class extends O{constructor(){super(...arguments),this.box_name="hintlongestpacket"}static{this.fourcc="dmax"}parse(e){this.time=e.readUint32()}},op=class extends O{constructor(){super(...arguments),this.box_name="hintmediaBytesSent"}static{this.fourcc="dmed"}parse(e){this.bytessent=e.readUint64()}},cp=class extends O{constructor(){super(...arguments),this.box_name="OpusSpecificBox"}static{this.fourcc="dOps"}parse(e){if(this.Version=e.readUint8(),this.OutputChannelCount=e.readUint8(),this.PreSkip=e.readUint16(),this.InputSampleRate=e.readUint32(),this.OutputGain=e.readInt16(),this.ChannelMappingFamily=e.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=e.readUint8(),this.CoupledCount=e.readUint8(),this.ChannelMapping=[];for(let t=0;t<this.OutputChannelCount;t++)this.ChannelMapping[t]=e.readUint8()}}write(e){if(this.size=11,this.ChannelMappingFamily!==0&&(this.size+=2+this.OutputChannelCount),this.writeHeader(e),e.writeUint8(this.Version),e.writeUint8(this.OutputChannelCount),e.writeUint16(this.PreSkip),e.writeUint32(this.InputSampleRate),e.writeInt16(this.OutputGain),e.writeUint8(this.ChannelMappingFamily),this.ChannelMappingFamily!==0){e.writeUint8(this.StreamCount),e.writeUint8(this.CoupledCount);for(let t=0;t<this.OutputChannelCount;t++)e.writeUint8(this.ChannelMapping[t])}}},lp=class extends O{constructor(){super(...arguments),this.box_name="hintrepeatedBytesSent"}static{this.fourcc="drep"}parse(e){this.bytessent=e.readUint64()}},dp=class extends B{constructor(){super(...arguments),this.box_name="EditListBox"}static{this.fourcc="elst"}parse(e){this.parseFullHeader(e),this.entries=[];let t=e.readUint32();for(let i=0;i<t;i++){let s={segment_duration:this.version===1?e.readUint64():e.readUint32(),media_time:this.version===1?e.readInt64():e.readInt32(),media_rate_integer:e.readInt16(),media_rate_fraction:e.readInt16()};this.entries.push(s)}}write(e){let t=this.entries.some(i=>i.segment_duration>ot||i.media_time>ot)||this.version===1;this.version=t?1:0,this.size=4+12*this.entries.length,this.size+=t?2*4*this.entries.length:0,this.writeHeader(e),e.writeUint32(this.entries.length);for(let i=0;i<this.entries.length;i++){let s=this.entries[i];t?(e.writeUint64(s.segment_duration),e.writeInt64(s.media_time)):(e.writeUint32(s.segment_duration),e.writeInt32(s.media_time)),e.writeInt16(s.media_rate_integer),e.writeInt16(s.media_rate_fraction)}}},up=class extends B{constructor(){super(...arguments),this.box_name="EventMessageBox"}static{this.fourcc="emsg"}parse(e){this.parseFullHeader(e),this.version===1?(this.timescale=e.readUint32(),this.presentation_time=e.readUint64(),this.event_duration=e.readUint32(),this.id=e.readUint32(),this.scheme_id_uri=e.readCString(),this.value=e.readCString()):(this.scheme_id_uri=e.readCString(),this.value=e.readCString(),this.timescale=e.readUint32(),this.presentation_time_delta=e.readUint32(),this.event_duration=e.readUint32(),this.id=e.readUint32());let t=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version===1&&(t-=4),this.message_data=e.readUint8Array(t)}write(e){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(e),e.writeCString(this.scheme_id_uri),e.writeCString(this.value),e.writeUint32(this.timescale),e.writeUint32(this.presentation_time_delta),e.writeUint32(this.event_duration),e.writeUint32(this.id),e.writeUint8Array(this.message_data)}},xt=class extends B{parse(e){this.parseFullHeader(e),this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[];for(let t=0;t<this.num_entities_in_group;t++){let i=e.readUint32();this.entity_ids.push(i)}}},hp=class extends xt{constructor(){super(...arguments),this.box_name="Auto exposure bracketing"}static{this.fourcc="aebr"}},fp=class extends xt{constructor(){super(...arguments),this.box_name="Flash exposure information"}static{this.fourcc="afbr"}},pp=class extends xt{constructor(){super(...arguments),this.box_name="Album collection"}static{this.fourcc="albc"}},mp=class extends xt{constructor(){super(...arguments),this.box_name="Alternative entity"}static{this.fourcc="altr"}},gp=class extends xt{constructor(){super(...arguments),this.box_name="Burst image"}static{this.fourcc="brst"}},_p=class extends xt{constructor(){super(...arguments),this.box_name="Depth of field bracketing"}static{this.fourcc="dobr"}},xp=class extends xt{constructor(){super(...arguments),this.box_name="Equivalent entity"}static{this.fourcc="eqiv"}},yp=class extends xt{constructor(){super(...arguments),this.box_name="Favorites collection"}static{this.fourcc="favc"}},bp=class extends xt{constructor(){super(...arguments),this.box_name="Focus bracketing"}static{this.fourcc="fobr"}},vp=class extends xt{constructor(){super(...arguments),this.box_name="Image item with an audio track"}static{this.fourcc="iaug"}},wp=class extends xt{constructor(){super(...arguments),this.box_name="Panorama"}static{this.fourcc="pano"}},Sp=class extends xt{constructor(){super(...arguments),this.box_name="Slideshow"}static{this.fourcc="slid"}},kp=class extends xt{constructor(){super(...arguments),this.box_name="Stereo"}static{this.fourcc="ster"}},Tp=class extends xt{constructor(){super(...arguments),this.box_name="Time-synchronized capture"}static{this.fourcc="tsyn"}},Ep=class extends xt{constructor(){super(...arguments),this.box_name="White balance bracketing"}static{this.fourcc="wbbr"}},Up=class extends xt{constructor(){super(...arguments),this.box_name="Progressive rendering"}static{this.fourcc="prgr"}},Bp=class extends xt{constructor(){super(...arguments),this.box_name="Image pyramid"}static{this.fourcc="pymd"}parse(e){this.parseFullHeader(e),this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[];for(let t=0;t<this.num_entities_in_group;t++){let i=e.readUint32();this.entity_ids.push(i)}this.tile_size_x=e.readUint16(),this.tile_size_y=e.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[];for(let t=0;t<this.num_entities_in_group;t++)this.layer_binning[t]=e.readUint16(),this.tiles_in_layer_row_minus1[t]=e.readUint16(),this.tiles_in_layer_column_minus1[t]=e.readUint16()}},Ap=class extends O{constructor(){super(...arguments),this.box_name="FieldHandlingBox"}static{this.fourcc="fiel"}parse(e){this.fieldCount=e.readUint8(),this.fieldOrdering=e.readUint8()}},Cp=class extends O{constructor(){super(...arguments),this.box_name="OriginalFormatBox"}static{this.fourcc="frma"}parse(e){this.data_format=e.readString(4)}},Mp=class extends O{constructor(){super(...arguments),this.box_name="ImageMirror"}static{this.fourcc="imir"}parse(e){let t=e.readUint8();this.reserved=t>>7,this.axis=t&1}},zp=class extends B{constructor(){super(...arguments),this.box_name="ItemPropertyAssociationBox"}static{this.fourcc="ipma"}parse(e){this.parseFullHeader(e);let t=e.readUint32();this.associations=[];for(let i=0;i<t;i++){let s=this.version<1?e.readUint16():e.readUint32(),r=[],n=e.readUint8();for(let a=0;a<n;a++){let o=e.readUint8();r.push({essential:(o&128)>>7===1,property_index:this.flags&1?(o&127)<<8|e.readUint8():o&127})}this.associations.push({id:s,props:r})}}},Pp=class extends O{constructor(){super(...arguments),this.box_name="ImageRotation"}static{this.fourcc="irot"}parse(e){this.angle=e.readUint8()&3}},Ip=class extends B{constructor(){super(...arguments),this.box_name="ImageSpatialExtentsProperty"}static{this.fourcc="ispe"}parse(e){this.parseFullHeader(e),this.image_width=e.readUint32(),this.image_height=e.readUint32()}},Rp=class extends B{constructor(){super(...arguments),this.box_name="TAITimestampBox"}static{this.fourcc="itai"}parse(e){this.TAI_timestamp=e.readUint64();let t=e.readUint8();this.sychronization_state=t>>7&1,this.timestamp_generation_failure=t>>6&1,this.timestamp_is_modified=t>>5&1}},Fp=class extends B{constructor(){super(...arguments),this.box_name="KindBox"}static{this.fourcc="kind"}parse(e){this.parseFullHeader(e),this.schemeURI=e.readCString(),this.isEndOfBox(e)||(this.value=e.readCString())}write(e){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value?this.value.length+1:0),this.writeHeader(e),e.writeCString(this.schemeURI),this.value&&e.writeCString(this.value)}},Lp=class extends B{constructor(){super(...arguments),this.box_name="LevelAssignmentBox"}static{this.fourcc="leva"}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.levels=[];for(let i=0;i<t;i++){let s={};this.levels[i]=s,s.track_ID=e.readUint32();let r=e.readUint8();switch(s.padding_flag=r>>7,s.assignment_type=r&127,s.assignment_type){case 0:s.grouping_type=e.readString(4);break;case 1:s.grouping_type=e.readString(4),s.grouping_type_parameter=e.readUint32();break;case 2:break;case 3:break;case 4:s.sub_track_id=e.readUint32();break;default:k.warn("BoxParser",\`Unknown level assignment type: \${s.assignment_type}\`)}}}},Op=class extends O{constructor(){super(...arguments),this.box_name="LHEVCConfigurationBox"}static{this.fourcc="lhvC"}parse(e){this.configurationVersion=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3;let t=e.readUint8();this.numTemporalLayers=(t&13)>>3,this.temporalIdNested=(t&4)>>2,this.lengthSizeMinusOne=t&3,this.nalu_arrays=[];let i=e.readUint8();for(let s=0;s<i;s++){let r=[];this.nalu_arrays.push(r),t=e.readUint8(),r.completeness=(t&128)>>7,r.nalu_type=t&63;let n=e.readUint16();for(let a=0;a<n;a++){let o=e.readUint16();r.push({data:e.readUint8Array(o)})}}}},Dp=class extends O{constructor(){super(...arguments),this.box_name="LayerSelectorProperty"}static{this.fourcc="lsel"}parse(e){this.layer_id=e.readUint16()}},Np=class extends O{constructor(){super(...arguments),this.box_name="hintmaxrate"}static{this.fourcc="maxr"}parse(e){this.period=e.readUint32(),this.bytes=e.readUint32()}},$r=class{constructor(e,t){this.x=e,this.y=t}toString(){return"("+this.x+","+this.y+")"}},Hp=class extends O{constructor(){super(...arguments),this.box_name="MasteringDisplayColourVolumeBox"}static{this.fourcc="mdcv"}parse(e){this.display_primaries=[],this.display_primaries[0]=new $r(e.readUint16(),e.readUint16()),this.display_primaries[1]=new $r(e.readUint16(),e.readUint16()),this.display_primaries[2]=new $r(e.readUint16(),e.readUint16()),this.white_point=new $r(e.readUint16(),e.readUint16()),this.max_display_mastering_luminance=e.readUint32(),this.min_display_mastering_luminance=e.readUint32()}},Gp=class extends B{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessOffsetBox"}static{this.fourcc="mfro"}parse(e){this.parseFullHeader(e),this._size=e.readUint32()}},Vp=class extends B{constructor(){super(...arguments),this.box_name="MaskConfigurationProperty"}static{this.fourcc="mskC"}parse(e){this.parseFullHeader(e),this.bits_per_pixel=e.readUint8()}},Wp=class extends O{constructor(){super(...arguments),this.box_name="hintPacketsSent"}static{this.fourcc="npck"}parse(e){this.packetssent=e.readUint32()}},qp=class extends O{constructor(){super(...arguments),this.box_name="hintPacketsSent"}static{this.fourcc="nump"}parse(e){this.packetssent=e.readUint64()}},jp=class{constructor(e,t){this.pad1=e,this.pad2=t}},$p=class extends B{constructor(){super(...arguments),this.box_name="PaddingBitsBox"}static{this.fourcc="padb"}parse(e){this.parseFullHeader(e);let t=e.readUint32();this.padbits=[];for(let i=0;i<Math.floor((t+1)/2);i++){let s=e.readUint8(),r=(s&112)>>4,n=s&7;this.padbits.push(new jp(r,n))}}},Yp=class extends O{constructor(){super(...arguments),this.box_name="PixelAspectRatioBox"}static{this.fourcc="pasp"}parse(e){this.hSpacing=e.readUint32(),this.vSpacing=e.readUint32()}},Xp=class extends O{constructor(){super(...arguments),this.box_name="CuePayloadBox"}static{this.fourcc="payl"}parse(e){this.text=e.readString(this.size-this.hdr_size)}},Zp=class extends O{constructor(){super(...arguments),this.box_name="hintpayloadID"}static{this.fourcc="payt"}parse(e){this.payloadID=e.readUint32();let t=e.readUint8();this.rtpmap_string=e.readString(t)}},Qp=class extends B{constructor(){super(...arguments),this.box_name="ProgressiveDownloadInfoBox",this.rate=[],this.initial_delay=[]}static{this.fourcc="pdin"}parse(e){this.parseFullHeader(e);let t=(this.size-this.hdr_size)/8;for(let i=0;i<t;i++)this.rate[i]=e.readUint32(),this.initial_delay[i]=e.readUint32()}},Kp=class extends B{constructor(){super(...arguments),this.box_name="PixelInformationProperty"}static{this.fourcc="pixi"}parse(e){this.parseFullHeader(e),this.num_channels=e.readUint8(),this.bits_per_channels=[];for(let t=0;t<this.num_channels;t++)this.bits_per_channels[t]=e.readUint8()}},Jp=class extends O{constructor(){super(...arguments),this.box_name="hintlargestpacket"}static{this.fourcc="pmax"}parse(e){this.bytes=e.readUint32()}},em=class extends B{constructor(){super(...arguments),this.box_name="ProgressiveDerivedImageItemInformationProperty"}static{this.fourcc="prdi"}parse(e){if(this.parseFullHeader(e),this.step_count=e.readUint16(),this.item_count=[],this.flags&2)for(let t=0;t<this.step_count;t++)this.item_count[t]=e.readUint16()}},tm=class extends B{constructor(){super(...arguments),this.box_name="ProjectionFormatBox"}static{this.fourcc="prfr"}parse(e){this.parseFullHeader(e),this.projection_type=e.readUint8()&31}},im=class extends B{constructor(){super(...arguments),this.box_name="ProducerReferenceTimeBox"}static{this.fourcc="prft"}parse(e){this.parseFullHeader(e),this.ref_track_id=e.readUint32(),this.ntp_timestamp=e.readUint64(),this.version===0?this.media_time=e.readUint32():this.media_time=e.readUint64()}},sm=class extends B{constructor(){super(...arguments),this.box_name="ProtectionSystemSpecificHeaderBox"}static{this.fourcc="pssh"}parse(e){if(this.parseFullHeader(e),this.system_id=Xi(e),this.version>0){let i=e.readUint32();this.kid=[];for(let s=0;s<i;s++)this.kid[s]=Xi(e)}let t=e.readUint32();t>0&&(this.protection_data=e.readUint8Array(t))}},rm=class extends B{constructor(){super(...arguments),this.box_name="TrackCleanApertureDimensionsBox"}static{this.fourcc="clef"}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}};function nm(e,t){if(e===ur.Types.UTF8)return new TextDecoder("utf-8").decode(t);let i=new DataView(t.buffer);if(e===ur.Types.BE_UNSIGNED_INT){if(t.length===1)return i.getUint8(0);if(t.length===2)return i.getUint16(0,!1);if(t.length===4)return i.getUint32(0,!1);if(t.length===8)return i.getBigUint64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_UNSIGNED_INT length "+t.length)}else if(e===ur.Types.BE_SIGNED_INT){if(t.length===1)return i.getInt8(0);if(t.length===2)return i.getInt16(0,!1);if(t.length===4)return i.getInt32(0,!1);if(t.length===8)return i.getBigInt64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_SIGNED_INT length "+t.length)}else if(e===ur.Types.BE_FLOAT32)return i.getFloat32(0,!1);k.warn("DataBox","Unsupported or unimplemented itif data type: "+e)}var ur=class extends O{constructor(){super(...arguments),this.box_name="DataBox"}static{this.fourcc="data"}static{this.Types={RESERVED:0,UTF8:1,UTF16:2,SJIS:3,UTF8_SORT:4,UTF16_SORT:5,JPEG:13,PNG:14,BE_SIGNED_INT:21,BE_UNSIGNED_INT:22,BE_FLOAT32:23,BE_FLOAT64:24,BMP:27,QT_ATOM:28,BE_SIGNED_INT8:65,BE_SIGNED_INT16:66,BE_SIGNED_INT32:67,BE_FLOAT32_POINT:70,BE_FLOAT32_DIMENSIONS:71,BE_FLOAT32_RECT:72,BE_SIGNED_INT64:74,BE_UNSIGNED_INT8:75,BE_UNSIGNED_INT16:76,BE_UNSIGNED_INT32:77,BE_UNSIGNED_INT64:78,BE_FLOAT64_AFFINE_TRANSFORM:79}}parse(e){this.valueType=e.readUint32(),this.country=e.readUint16(),this.country>255&&(e.seek(e.getPosition()-2),this.countryString=e.readString(2)),this.language=e.readUint16(),this.language>255&&(e.seek(e.getPosition()-2),this.parseLanguage(e)),this.raw=e.readUint8Array(this.size-this.hdr_size-8),this.value=nm(this.valueType,this.raw)}},am=class extends B{constructor(){super(...arguments),this.box_name="TrackEncodedPixelsDimensionsBox"}static{this.fourcc="enof"}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}},om=class extends O{constructor(){super(...arguments),this.box_name="IlstBox"}static{this.fourcc="ilst"}parse(e){this.list={};let t=this.size-this.hdr_size;for(;t>0;){let i=e.readUint32(),s=e.readUint32(),r=li(e,!1,i-8);r.code===Nt&&(this.list[s]=r.box),t-=i}}},cm=class extends B{constructor(){super(...arguments),this.box_name="KeysBox"}static{this.fourcc="keys"}parse(e){this.parseFullHeader(e),this.count=e.readUint32(),this.keys={};for(let t=0;t<this.count;t++){let i=e.readUint32();this.keys[t+1]=e.readString(i-4)}}},lm=class extends B{constructor(){super(...arguments),this.box_name="TrackProductionApertureDimensionsBox"}static{this.fourcc="prof"}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}},dm=class extends Be{constructor(){super(...arguments),this.box_name="TrackApertureModeDimensionsBox",this.clefs=[],this.profs=[],this.enofs=[],this.subBoxNames=["clef","prof","enof"]}static{this.fourcc="tapt"}},um=class extends O{constructor(){super(...arguments),this.box_name="rtpmoviehintinformation"}static{this.fourcc="rtp "}parse(e){this.descriptionformat=e.readString(4),this.sdptext=e.readString(this.size-this.hdr_size-4)}},hm=class extends B{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationOffsetsBox"}static{this.fourcc="saio"}parse(e){this.parseFullHeader(e),this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32());let t=e.readUint32();this.offset=[];for(let i=0;i<t;i++)this.version===0?this.offset[i]=e.readUint32():this.offset[i]=e.readUint64()}},fm=class extends B{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationSizesBox"}static{this.fourcc="saiz"}parse(e){if(this.parseFullHeader(e),this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32()),this.default_sample_info_size=e.readUint8(),this.sample_count=e.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(let t=0;t<this.sample_count;t++)this.sample_info_size[t]=e.readUint8()}},pm=class{constructor(e,t){this.bad_pixel_row=e,this.bad_pixel_column=t}toString(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"}},mm=class extends B{constructor(){super(...arguments),this.box_name="SensorBadPixelsMapBox"}static{this.fourcc="sbpm"}parse(e){this.parseFullHeader(e),this.component_count=e.readUint16(),this.component_index=[];for(let i=0;i<this.component_count;i++)this.component_index.push(e.readUint16());let t=e.readUint8();this.correction_applied=(t&128)===128,this.num_bad_rows=e.readUint32(),this.num_bad_cols=e.readUint32(),this.num_bad_pixels=e.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[];for(let i=0;i<this.num_bad_rows;i++)this.bad_rows.push(e.readUint32());for(let i=0;i<this.num_bad_cols;i++)this.bad_columns.push(e.readUint32());for(let i=0;i<this.num_bad_pixels;i++){let s=e.readUint32(),r=e.readUint32();this.bad_pixels.push(new pm(s,r))}}},gm=class extends B{constructor(){super(...arguments),this.box_name="SchemeTypeBox"}static{this.fourcc="schm"}parse(e){this.parseFullHeader(e),this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readString(this.size-this.hdr_size-8))}},_m=class extends O{constructor(){super(...arguments),this.box_name="rtptracksdphintinformation"}static{this.fourcc="sdp "}parse(e){this.sdptext=e.readString(this.size-this.hdr_size)}},xm=class extends B{constructor(){super(...arguments),this.box_name="SampleEncryptionBox"}static{this.fourcc="senc"}},ym=class extends B{constructor(){super(...arguments),this.box_name="SMPTE2086MasteringDisplayMetadataBox"}static{this.fourcc="SmDm"}parse(e){this.parseFullHeader(e),this.primaryRChromaticity_x=e.readUint16(),this.primaryRChromaticity_y=e.readUint16(),this.primaryGChromaticity_x=e.readUint16(),this.primaryGChromaticity_y=e.readUint16(),this.primaryBChromaticity_x=e.readUint16(),this.primaryBChromaticity_y=e.readUint16(),this.whitePointChromaticity_x=e.readUint16(),this.whitePointChromaticity_y=e.readUint16(),this.luminanceMax=e.readUint32(),this.luminanceMin=e.readUint32()}},bm=class extends B{constructor(){super(...arguments),this.box_name="CompressedSubsegmentIndexBox"}static{this.fourcc="ssix"}parse(e){this.parseFullHeader(e),this.subsegments=[];let t=e.readUint32();for(let i=0;i<t;i++){let s={};this.subsegments.push(s),s.ranges=[];let r=e.readUint32();for(let n=0;n<r;n++){let a={};s.ranges.push(a),a.level=e.readUint8(),a.range_size=e.readUint24()}}}},vm=class extends B{constructor(){super(...arguments),this.box_name="DegradationPriorityBox"}static{this.fourcc="stpd"}parse(e){this.parseFullHeader(e);let t=(this.size-this.hdr_size)/2;this.priority=[];for(let i=0;i<t;i++)this.priority[i]=e.readUint16()}},wm=class extends B{constructor(){super(...arguments),this.box_name="SubTrackInformationBox"}static{this.fourcc="stri"}parse(e){this.parseFullHeader(e),this.switch_group=e.readUint16(),this.alternate_group=e.readUint16(),this.sub_track_id=e.readUint32();let t=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(let i=0;i<t;i++)this.attribute_list[i]=e.readUint32()}},Sm=class extends B{constructor(){super(...arguments),this.box_name="SubTrackSampleGroupBox"}static{this.fourcc="stsg"}parse(e){this.parseFullHeader(e),this.grouping_type=e.readUint32();let t=e.readUint16();this.group_description_index=[];for(let i=0;i<t;i++)this.group_description_index[i]=e.readUint32()}},km=class extends B{constructor(){super(...arguments),this.box_name="ShadowSyncSampleBox"}static{this.fourcc="stsh"}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(let i=0;i<t;i++)this.shadowed_sample_numbers.push(e.readUint32()),this.sync_sample_numbers.push(e.readUint32())}write(e){this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(e),e.writeUint32(this.shadowed_sample_numbers.length);for(let t=0;t<this.shadowed_sample_numbers.length;t++)e.writeUint32(this.shadowed_sample_numbers[t]),e.writeUint32(this.sync_sample_numbers[t])}},Tm=class extends B{constructor(){super(...arguments),this.box_name="SyncSampleBox"}static{this.fourcc="stss"}parse(e){this.parseFullHeader(e);let t=e.readUint32();if(this.version===0){this.sample_numbers=[];for(let i=0;i<t;i++)this.sample_numbers.push(e.readUint32())}}write(e){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(e),e.writeUint32(this.sample_numbers.length),e.writeUint32Array(this.sample_numbers)}},Em=class extends B{constructor(){super(...arguments),this.box_name="StereoVideoBox"}static{this.fourcc="stvi"}parse(e){this.parseFullHeader(e);let t=e.readUint32();this.single_view_allowed=t&3,this.stereo_scheme=e.readUint32();let i=e.readUint32();for(this.stereo_indication_type=e.readString(i),this.boxes=[];e.getPosition()<this.start+this.size;){let s=li(e,!1,this.size-(e.getPosition()-this.start));if(s.code===Nt){let r=s.box;this.boxes.push(r),this[r.type]=r}else return}}},Um=class extends O{constructor(){super(...arguments),this.box_name="SegmentTypeBox"}static{this.fourcc="styp"}parse(e){let t=this.size-this.hdr_size;this.major_brand=e.readString(4),this.minor_version=e.readUint32(),t-=8,this.compatible_brands=[];let i=0;for(;t>=4;)this.compatible_brands[i]=e.readString(4),t-=4,i++}write(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,void 0,4),e.writeUint32(this.minor_version);for(let t=0;t<this.compatible_brands.length;t++)e.writeString(this.compatible_brands[t],void 0,4)}},Bm=class extends B{constructor(){super(...arguments),this.box_name="CompactSampleSizeBox"}static{this.fourcc="stz2"}parse(e){if(this.parseFullHeader(e),this.sample_sizes=[],this.version===0){this.reserved=e.readUint24(),this.field_size=e.readUint8();let t=e.readUint32();if(this.field_size===4)for(let i=0;i<t;i+=2){let s=e.readUint8();this.sample_sizes[i]=s>>4&15,this.sample_sizes[i+1]=s&15}else if(this.field_size===8)for(let i=0;i<t;i++)this.sample_sizes[i]=e.readUint8();else if(this.field_size===16)for(let i=0;i<t;i++)this.sample_sizes[i]=e.readUint16();else k.error("BoxParser","Error in length field in stz2 box",e.isofile)}}},Am=class extends B{constructor(){super(...arguments),this.box_name="SubSampleInformationBox"}static{this.fourcc="subs"}parse(e){this.parseFullHeader(e);let t=e.readUint32();this.entries=[];let i;for(let s=0;s<t;s++){let r={};if(this.entries[s]=r,r.sample_delta=e.readUint32(),r.subsamples=[],i=e.readUint16(),i>0)for(let n=0;n<i;n++){let a={};r.subsamples.push(a),this.version===1?a.size=e.readUint32():a.size=e.readUint16(),a.priority=e.readUint8(),a.discardable=e.readUint8(),a.codec_specific_parameters=e.readUint32()}}}},Cm=class extends B{constructor(){super(...arguments),this.box_name="TAIClockInfoBox"}static{this.fourcc="taic"}parse(e){this.time_uncertainty=e.readUint64(),this.clock_resolution=e.readUint32(),this.clock_drift_rate=e.readInt32();let t=e.readUint8();this.clock_type=(t&192)>>6}},Mm=class extends B{constructor(){super(...arguments),this.box_name="TrackEncryptionBox"}static{this.fourcc="tenc"}parse(e){if(this.parseFullHeader(e),e.readUint8(),this.version===0)e.readUint8();else{let t=e.readUint8();this.default_crypt_byte_block=t>>4&15,this.default_skip_byte_block=t&15}this.default_isProtected=e.readUint8(),this.default_Per_Sample_IV_Size=e.readUint8(),this.default_KID=Xi(e),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=e.readUint8(),this.default_constant_IV=e.readUint8Array(this.default_constant_IV_size))}},zm=class extends B{constructor(){super(...arguments),this.box_name="TrackFragmentRandomAccessBox"}static{this.fourcc="tfra"}parse(e){this.parseFullHeader(e),this.track_ID=e.readUint32(),e.readUint24();let t=e.readUint8();this.length_size_of_traf_num=t>>4&3,this.length_size_of_trun_num=t>>2&3,this.length_size_of_sample_num=t&3,this.entries=[];let i=e.readUint32();for(let s=0;s<i;s++)this.version===1?(this.time=e.readUint64(),this.moof_offset=e.readUint64()):(this.time=e.readUint32(),this.moof_offset=e.readUint32()),this.traf_number=e["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=e["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=e["readUint"+8*(this.length_size_of_sample_num+1)]()}},Pm=class extends O{constructor(){super(...arguments),this.box_name="hintmaxrelativetime"}static{this.fourcc="tmax"}parse(e){this.time=e.readUint32()}},Im=class extends O{constructor(){super(...arguments),this.box_name="hintminrelativetime"}static{this.fourcc="tmin"}parse(e){this.time=e.readUint32()}},Rm=class extends O{constructor(){super(...arguments),this.box_name="hintBytesSent"}static{this.fourcc="totl"}parse(e){this.bytessent=e.readUint32()}},Fm=class extends O{constructor(){super(...arguments),this.box_name="hintBytesSent"}static{this.fourcc="tpay"}parse(e){this.bytessent=e.readUint32()}},Lm=class extends O{constructor(){super(...arguments),this.box_name="hintBytesSent"}static{this.fourcc="tpyl"}parse(e){this.bytessent=e.readUint64()}},Om=class extends Cu{static{this.fourcc="msrc"}},Dm=class Dc extends O{constructor(){super(...arguments),this.box_name="TrackReferenceBox",this.references=[]}static{this.fourcc="tref"}static{this.allowed_types=["hint","cdsc","font","hind","vdep","vplx","subt","thmb","auxl","cdtg","shsc","aest"]}parse(t){for(;t.getPosition()<this.start+this.size;){let i=li(t,!0,this.size-(t.getPosition()-this.start));if(i.code===Nt){Dc.allowed_types.includes(i.type)||k.warn("BoxParser",\`Unknown track reference type: '\${i.type}'\`);let s=new Pu(i.type,i.size,i.hdr_size,i.start);s.write===O.prototype.write&&s.type!=="mdat"&&(k.info("BoxParser","TrackReference "+s.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(t)),s.parse(t),this.references.push(s)}else return}}},Nm=class extends B{constructor(){super(...arguments),this.box_name="TrackExtensionPropertiesBox"}static{this.fourcc="trep"}parse(e){for(this.parseFullHeader(e),this.track_ID=e.readUint32(),this.boxes=[];e.getPosition()<this.start+this.size;){let t=li(e,!1,this.size-(e.getPosition()-this.start));if(t.code===Nt){let i=t.box;this.boxes.push(i)}else return}}},Hm=class extends O{constructor(){super(...arguments),this.box_name="hintBytesSent"}static{this.fourcc="trpy"}parse(e){this.bytessent=e.readUint64()}},Gm=class extends B{constructor(){super(...arguments),this.box_name="TrackSelectionBox"}static{this.fourcc="tsel"}parse(e){this.parseFullHeader(e),this.switch_group=e.readUint32();let t=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(let i=0;i<t;i++)this.attribute_list[i]=e.readUint32()}},Vm=class extends B{constructor(){super(...arguments),this.box_name="TextConfigBox"}static{this.fourcc="txtc"}parse(e){this.parseFullHeader(e),this.config=e.readCString()}},Wm=class extends O{constructor(){super(...arguments),this.box_name="TypeCombinationBox"}static{this.fourcc="tyco"}parse(e){let t=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(let i=0;i<t;i++)this.compatible_brands[i]=e.readString(4)}},qm=class extends B{constructor(){super(...arguments),this.box_name="UserDescriptionProperty"}static{this.fourcc="udes"}parse(e){this.parseFullHeader(e),this.lang=e.readCString(),this.name=e.readCString(),this.description=e.readCString(),this.tags=e.readCString()}},jm=class extends B{constructor(){super(...arguments),this.box_name="UncompressedFrameConfigBox"}static{this.fourcc="uncC"}parse(e){if(this.parseFullHeader(e),this.profile=e.readString(4),this.version!==1){if(this.version===0){this.component_count=e.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[];for(let i=0;i<this.component_count;i++)this.component_index.push(e.readUint16()),this.component_bit_depth_minus_one.push(e.readUint8()),this.component_format.push(e.readUint8()),this.component_align_size.push(e.readUint8());this.sampling_type=e.readUint8(),this.interleave_type=e.readUint8(),this.block_size=e.readUint8();let t=e.readUint8();this.component_little_endian=t>>7&1,this.block_pad_lsb=t>>6&1,this.block_little_endian=t>>5&1,this.block_reversed=t>>4&1,this.pad_unknown=t>>3&1,this.pixel_size=e.readUint32(),this.row_align_size=e.readUint32(),this.tile_align_size=e.readUint32(),this.num_tile_cols_minus_one=e.readUint32(),this.num_tile_rows_minus_one=e.readUint32()}}}},$m=class extends B{constructor(){super(...arguments),this.box_name="DataEntryUrnBox"}static{this.fourcc="urn "}parse(e){this.parseFullHeader(e),this.name=e.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=e.readCString())}write(e){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(e),e.writeCString(this.name),this.location&&e.writeCString(this.location)}},Ym=class extends O{constructor(){super(...arguments),this.box_name="WebVTTConfigurationBox"}static{this.fourcc="vttC"}parse(e){this.text=e.readString(this.size-this.hdr_size)}},Xm=class extends B{constructor(){super(...arguments),this.box_name="VvcNALUConfigBox"}static{this.fourcc="vvnC"}parse(e){this.parseFullHeader(e);let t=e.readUint8();this.lengthSizeMinusOne=t&3}},Zm=class extends tt{static{this.grouping_type="alst"}parse(e){let t=e.readUint16();this.first_output_sample=e.readUint16(),this.sample_offset=[];for(let s=0;s<t;s++)this.sample_offset[s]=e.readUint32();let i=this.description_length-4-4*t;this.num_output_samples=[],this.num_total_samples=[];for(let s=0;s<i/4;s++)this.num_output_samples[s]=e.readUint16(),this.num_total_samples[s]=e.readUint16()}},Qm=class extends tt{static{this.grouping_type="avll"}parse(e){this.layerNumber=e.readUint8(),this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()}},Km=class extends tt{static{this.grouping_type="avss"}parse(e){this.subSequenceIdentifier=e.readUint16(),this.layerNumber=e.readUint8();let t=e.readUint8();this.durationFlag=t>>7,this.avgRateFlag=t>>6&1,this.durationFlag&&(this.duration=e.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()),this.dependency=[];let i=e.readUint8();for(let s=0;s<i;s++)this.dependency.push({subSeqDirectionFlag:e.readUint8(),layerNumber:e.readUint8(),subSequenceIdentifier:e.readUint16()})}},Jm=class extends tt{static{this.grouping_type="dtrt"}parse(e){k.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},eg=class extends tt{static{this.grouping_type="mvif"}parse(e){k.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},tg=class extends tt{static{this.grouping_type="prol"}parse(e){this.roll_distance=e.readInt16()}},ig=class extends tt{static{this.grouping_type="rap "}parse(e){let t=e.readUint8();this.num_leading_samples_known=t>>7,this.num_leading_samples=t&127}},sg=class extends tt{static{this.grouping_type="rash"}parse(e){if(this.operation_point_count=e.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)k.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=e.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=e.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(let t=0;t<this.operation_point_count;t++)this.available_bitrate[t]=e.readUint32(),this.target_rate_share[t]=e.readUint16()}this.maximum_bitrate=e.readUint32(),this.minimum_bitrate=e.readUint32(),this.discard_priority=e.readUint8()}}},rg=class extends tt{static{this.grouping_type="roll"}parse(e){this.roll_distance=e.readInt16()}},ng=class extends tt{static{this.grouping_type="scif"}parse(e){k.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},ag=class extends tt{static{this.grouping_type="scnm"}parse(e){k.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},og=class extends tt{static{this.grouping_type="seig"}parse(e){this.reserved=e.readUint8();let t=e.readUint8();this.crypt_byte_block=t>>4,this.skip_byte_block=t&15,this.isProtected=e.readUint8(),this.Per_Sample_IV_Size=e.readUint8(),this.KID=Xi(e),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=e.readUint8(),this.constant_IV=e.readUint8Array(this.constant_IV_size))}},cg=class extends tt{static{this.grouping_type="stsa"}parse(e){k.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},lg=class extends tt{static{this.grouping_type="sync"}parse(e){let t=e.readUint8();this.NAL_unit_type=t&63}},dg=class extends tt{static{this.grouping_type="tele"}parse(e){let t=e.readUint8();this.level_independently_decodable=t>>7}},ug=class extends tt{static{this.grouping_type="tsas"}parse(e){k.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},hg=class extends tt{static{this.grouping_type="tscl"}parse(e){k.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},fg=class extends tt{static{this.grouping_type="vipr"}parse(e){k.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},pg=class extends O{static{this.fourcc="uuid"}},zs=class extends B{static{this.fourcc="uuid"}},mg=class extends zs{constructor(){super(...arguments),this.box_name="LiveServerManifestBox"}static{this.uuid="a5d40b30e81411ddba2f0800200c9a66"}parse(e){this.parseFullHeader(e),this.LiveServerManifest=e.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},gg=class extends zs{constructor(){super(...arguments),this.box_name="PiffProtectionSystemSpecificHeaderBox"}static{this.uuid="d08a4f1810f34a82b6c832d8aba183d3"}parse(e){this.parseFullHeader(e),this.system_id=Xi(e);let t=e.readUint32();t>0&&(this.data=e.readUint8Array(t))}},_g=class extends zs{constructor(){super(...arguments),this.box_name="PiffSampleEncryptionBox"}static{this.uuid="a2394f525a9b4f14a2446c427c648df4"}},xg=class extends zs{constructor(){super(...arguments),this.box_name="PiffTrackEncryptionBox"}static{this.uuid="8974dbce7be74c5184f97148f9882554"}parse(e){this.parseFullHeader(e),this.default_AlgorithmID=e.readUint24(),this.default_IV_size=e.readUint8(),this.default_KID=Xi(e)}},yg=class extends zs{constructor(){super(...arguments),this.box_name="TfrfBox"}static{this.uuid="d4807ef2ca3946958e5426cb9e46a79f"}parse(e){this.parseFullHeader(e),this.fragment_count=e.readUint8(),this.entries=[];for(let t=0;t<this.fragment_count;t++){let i=0,s=0;this.version===1?(i=e.readUint64(),s=e.readUint64()):(i=e.readUint32(),s=e.readUint32()),this.entries.push({absolute_time:i,absolute_duration:s})}}},bg=class extends zs{constructor(){super(...arguments),this.box_name="TfxdBox"}static{this.uuid="6d1d9b0542d544e680e2141daff757b2"}parse(e){this.parseFullHeader(e),this.version===1?(this.absolute_time=e.readUint64(),this.duration=e.readUint64()):(this.absolute_time=e.readUint32(),this.duration=e.readUint32())}},vg=class extends pg{constructor(){super(...arguments),this.box_name="ItemContentIDProperty"}static{this.uuid="261ef3741d975bbaacbd9d2c8ea73522"}parse(e){this.content_id=e.readCString()}},Vb=Du(Oc);Nu(Pc);var Nc=12,wg=2,Sg=24,kg=90,Tg=2e3,dn=class e{width;height;duration;samples;keyIndices;tsToIndex=new Map;config;decoder=null;nextFeedIndex=Number.POSITIVE_INFINITY;flushed=!1;cache=new Map;windowLo=0;windowHi=Number.POSITIVE_INFINITY;lastTarget=-1;waiters=new Map;opChain=Promise.resolve();disposed=!1;static isSupported(){return typeof VideoDecoder<"u"}constructor(t,i,s,r,n){this.config=t,this.samples=i,this.width=s,this.height=r,this.duration=n,this.keyIndices=[];for(let a=0;a<i.length;a++)i[a].isKey&&this.keyIndices.push(a),this.tsToIndex.set(i[a].chunk.timestamp,a);(this.keyIndices.length===0||this.keyIndices[0]!==0)&&this.keyIndices.unshift(0)}static async load(t){if(!e.isSupported())throw new Error("WebCodecs VideoDecoder unavailable in this context");let i=new AbortController,s=setTimeout(()=>i.abort(),1e4),r;try{r=await fetch(t,{mode:"cors",signal:i.signal})}finally{clearTimeout(s)}if(!r.ok)throw new Error(\`fetch failed (\${r.status})\`);let n=await r.arrayBuffer();n.fileStart=0;let a=zc(),{info:o,rawSamples:c}=await new Promise((g,y)=>{let w=[],x=null;a.onError=b=>y(new Error(\`mp4box: \${b}\`)),a.onReady=b=>{if(b.videoTracks.length===0){y(new Error("no video track in container"));return}x=b;let S=b.videoTracks[0];a.setExtractionOptions(S.id,null,{nbSamples:S.nb_samples}),a.start()},a.onSamples=(b,S,v)=>{w.push(...v);let T=x?.videoTracks[0]?.nb_samples??1/0;w.length>=T&&g({info:x,rawSamples:w})},a.appendBuffer(n),a.flush()}),l=o.videoTracks[0],u=Eg(a,l.id),h={codec:l.codec,codedWidth:l.video?.width??l.track_width,codedHeight:l.video?.height??l.track_height,...u?{description:u}:{}};if(!(await VideoDecoder.isConfigSupported(h)).supported)throw new Error(\`codec \${l.codec} not decodable here\`);let p=c.map(g=>({time:g.cts/g.timescale,isKey:g.is_sync,chunk:new EncodedVideoChunk({type:g.is_sync?"key":"delta",timestamp:Math.round(g.cts/g.timescale*1e6),duration:Math.round(g.duration/g.timescale*1e6),data:g.data})}));if(p.length===0)throw new Error("container has zero video samples");let m=o.duration/o.timescale;return new e(h,p,h.codedWidth,h.codedHeight,m>0?m:p[p.length-1].time)}getFrame(t){let i=this.opChain.then(()=>this.#e(t));return this.opChain=i.catch(()=>{}),i}async#e(t){if(this.disposed)return null;let i=this.#n(t),s=this.lastTarget>=0&&i<this.lastTarget;this.lastTarget=i;let r=this.windowLo;this.windowLo=Math.max(0,i-(s?Sg:wg)),this.windowHi=Math.min(this.samples.length-1,i+Nc);for(let[c,l]of this.cache)(c<this.windowLo||c>this.windowHi)&&(l.close(),this.cache.delete(c));let n=this.windowHi,a=this.cache.get(i);return a?(this.#t(n,!1),a):(this.#s(i,r),await new Promise(c=>{let l=this.waiters.get(i)??[];l.push(c),this.waiters.set(i,l),this.#t(n,!0),setTimeout(()=>{let u=this.waiters.get(i);u&&u.includes(c)&&(this.waiters.set(i,u.filter(h=>h!==c)),c(this.cache.get(i)??null))},Tg)}))}#s(t,i){if(!(!this.decoder||this.decoder.state==="closed"||this.flushed||this.nextFeedIndex===Number.POSITIVE_INFINITY||t<i||this.nextFeedIndex>t+Nc||t-this.nextFeedIndex>kg))return;this.decoder&&this.decoder.state!=="closed"&&this.decoder.close();let r=new VideoDecoder({output:n=>this.#r(n),error:n=>{$().warn("VideoDecoder error:",n.message),this.#i()}});r.configure(this.config),this.decoder=r,this.flushed=!1,this.nextFeedIndex=this.#a(t)}#t(t,i){let s=this.decoder;if(!(!s||s.state==="closed"||this.flushed)){for(;this.nextFeedIndex<=t&&this.nextFeedIndex<this.samples.length;)s.decode(this.samples[this.nextFeedIndex].chunk),this.nextFeedIndex+=1;i&&this.nextFeedIndex>=this.samples.length&&(this.flushed=!0,s.flush().catch(()=>{}))}}#r(t){if(this.disposed){t.close();return}let i=this.tsToIndex.get(t.timestamp);if(i===void 0||i<this.windowLo||i>this.windowHi)t.close();else{let s=this.cache.get(i);s&&s.close(),this.cache.set(i,t)}if(i!==void 0){let s=this.waiters.get(i);if(s){this.waiters.delete(i);let r=this.cache.get(i)??null;for(let n of s)n(r)}}}#i(){for(let[,t]of this.waiters)for(let i of t)i(null);this.waiters.clear()}#n(t){let i=Math.max(0,Math.min(t,this.samples[this.samples.length-1].time)),s=0,r=-1/0;for(let n=0;n<this.samples.length;n++){let a=this.samples[n].time;a<=i&&a>r&&(r=a,s=n)}return s}#a(t){let i=this.keyIndices[0];for(let s of this.keyIndices)if(s<=t)i=s;else break;return i}dispose(){this.disposed=!0,this.#i();for(let t of this.cache.values())t.close();this.cache.clear(),this.decoder&&this.decoder.state!=="closed"&&this.decoder.close(),this.decoder=null,this.samples=[]}};function Eg(e,t){try{let i=e.getTrackById(t);for(let s of i.mdia.minf.stbl.stsd.entries){let r=s.avcC??s.hvcC??s.vpcC??s.av1C;if(r){let n=new Dt(void 0,0,la.BIG_ENDIAN);return r.write(n),new Uint8Array(n.buffer,8)}}}catch(i){$().debug("extractDescription failed:",i instanceof Error?i.message:String(i))}}var Vc=e=>e,Wc=e=>e*e,qc=e=>e*(2-e),fa=e=>e<.5?2*e*e:-1+(4-2*e)*e,Ug=e=>e*e*e,Bg=e=>1-Math.pow(1-e,3),Ag=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,Cg=Wc,Mg=qc,zg=fa,Pg=e=>e*e*e*e,Ig=e=>1-Math.pow(1-e,4),Rg=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2,Fg=e=>e*e*e*e*e,Lg=e=>1-Math.pow(1-e,5),Og=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2,Dg=e=>1-Math.cos(e*Math.PI/2),Ng=e=>Math.sin(e*Math.PI/2),Hg=e=>-(Math.cos(Math.PI*e)-1)/2,Gg=e=>e===0?0:Math.pow(2,10*e-10),Vg=e=>e===1?1:1-Math.pow(2,-10*e),Wg=e=>e===0?0:e===1?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2,qg=e=>1-Math.sqrt(1-Math.pow(e,2)),jg=e=>Math.sqrt(1-Math.pow(e-1,2)),$g=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2,fn=1.70158,un=fn*1.525,jc=fn+1,Yg=e=>jc*e*e*e-fn*e*e,Xg=e=>1+jc*Math.pow(e-1,3)+fn*Math.pow(e-1,2),Zg=e=>e<.5?Math.pow(2*e,2)*((un+1)*2*e-un)/2:(Math.pow(2*e-2,2)*((un+1)*(e*2-2)+un)+2)/2,Qg=e=>{let r=Math.sqrt(100),n=10/(2*Math.sqrt(100*1)),a=e;if(n<1){let o=r*Math.sqrt(1-n*n);return 1-Math.exp(-n*r*a)*(Math.cos(o*a)+n*r/o*Math.sin(o*a))}return 1-Math.exp(-r*a)*(1+r*a)},$c=2*Math.PI/3,Hc=2*Math.PI/4.5,Kg=e=>-Math.pow(2,10*e-10)*Math.sin((e*10-10.75)*$c),Jg=e=>Math.pow(2,-10*e)*Math.sin((e*10-.75)*$c)+1,e0=e=>e<.5?-(Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Hc))/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Hc)/2+1,hn=e=>e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375,t0=e=>1-hn(1-e),i0=e=>e<.5?(1-hn(1-2*e))/2:(1+hn(2*e-1))/2,s0={linear:Vc,ease:fa,"ease-in":Wc,"ease-out":qc,"ease-in-out":fa,"ease-in-cubic":Ug,"ease-out-cubic":Bg,"ease-in-out-cubic":Ag,"ease-in-quad":Cg,"ease-out-quad":Mg,"ease-in-out-quad":zg,"ease-in-quart":Pg,"ease-out-quart":Ig,"ease-in-out-quart":Rg,"ease-in-quint":Fg,"ease-out-quint":Lg,"ease-in-out-quint":Og,"ease-in-sine":Dg,"ease-out-sine":Ng,"ease-in-out-sine":Hg,"ease-in-expo":Gg,"ease-out-expo":Vg,"ease-in-out-expo":Wg,"ease-in-circ":qg,"ease-out-circ":jg,"ease-in-out-circ":$g,"ease-in-back":Yg,"ease-out-back":Xg,"ease-in-out-back":Zg,spring:Qg,"elastic-in":Kg,"elastic-out":Jg,"elastic-in-out":e0,"bounce-in":t0,"bounce-out":hn,"bounce-in-out":i0};function r0(e,t,i,s){let r=3*e,n=3*(i-e)-r,a=1-r-n,o=3*t,c=3*(s-t)-o,l=1-o-c,u=p=>((a*p+n)*p+r)*p,h=p=>((l*p+c)*p+o)*p,f=p=>(3*a*p+2*n)*p+r;return p=>{let m=p;for(let w=0;w<8;w++){let x=u(m)-p;if(Math.abs(x)<1e-6)return h(m);let b=f(m);if(Math.abs(b)<1e-6)break;m-=x/b}let g=0,y=1;for(m=p;g<y;){let w=u(m);if(Math.abs(w-p)<1e-6||(w<p?g=m:y=m,m=(g+y)/2,y-g<1e-6))break}return h(m)}}function n0(e){return t=>Math.floor(t*e)/e}var a0=/^cubic-bezier\\(\\s*(-?\\d*\\.?\\d+)\\s*,\\s*(-?\\d*\\.?\\d+)\\s*,\\s*(-?\\d*\\.?\\d+)\\s*,\\s*(-?\\d*\\.?\\d+)\\s*\\)$/,o0=/^steps\\(\\s*(\\d+)\\s*\\)$/,Gc=new Map;function c0(e){let t=Gc.get(e);if(t!==void 0)return t;let i=null,s=a0.exec(e);if(s){let r=Math.min(1,Math.max(0,parseFloat(s[1]))),n=Math.min(1,Math.max(0,parseFloat(s[3])));i=r0(r,parseFloat(s[2]),n,parseFloat(s[4]))}else{let r=o0.exec(e);if(r){let n=parseInt(r[1],10);n>0&&(i=n0(n))}}return Gc.set(e,i),i}function yt(e,t){return t<=0?0:t>=1?1:e?(s0[e]??c0(e)??Vc)(t):t}var Ps=[1,1,1,1],di=e=>Math.max(0,Math.min(1,e)),l0={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};function d0(e,t,i){let s=(e%360+360)%360/360;if(t===0)return[i,i,i];let r=i<.5?i*(1+t):i+t-i*t,n=2*i-r,a=o=>{let c=o;return c<0&&(c+=1),c>1&&(c-=1),c<1/6?n+(r-n)*6*c:c<1/2?r:c<2/3?n+(r-n)*(2/3-c)*6:n};return[a(s+1/3),a(s),a(s-1/3)]}function kt(e){if(!e)return Ps;let t=e.trim();if(t.startsWith("rgb")){let o=t.match(/^rgba?\\(\\s*([-\\d.]+)\\s*[,\\s]\\s*([-\\d.]+)\\s*[,\\s]\\s*([-\\d.]+)(?:\\s*[,/]\\s*([-\\d.]+%?))?\\s*\\)$/i);if(!o)return Ps;let c=(parseFloat(o[1])||0)/255,l=(parseFloat(o[2])||0)/255,u=(parseFloat(o[3])||0)/255,h=1;return o[4]&&(h=o[4].endsWith("%")?parseFloat(o[4])/100:parseFloat(o[4]),Number.isFinite(h)||(h=1)),[di(c),di(l),di(u),di(h)]}if(t.startsWith("hsl")){let o=t.match(/^hsla?\\(\\s*([-\\d.]+)(?:deg)?\\s*[,\\s]\\s*([-\\d.]+)%\\s*[,\\s]\\s*([-\\d.]+)%(?:\\s*[,/]\\s*([-\\d.]+%?))?\\s*\\)$/i);if(!o)return Ps;let[c,l,u]=d0(parseFloat(o[1])||0,di((parseFloat(o[2])||0)/100),di((parseFloat(o[3])||0)/100)),h=1;return o[4]&&(h=o[4].endsWith("%")?parseFloat(o[4])/100:parseFloat(o[4]),Number.isFinite(h)||(h=1)),[di(c),di(l),di(u),di(h)]}if(!t.startsWith("#")){let o=t.toLowerCase();if(o==="transparent")return[0,0,0,0];let c=l0[o];if(!c)return Ps;t=c}let i=t.slice(1),s=1,r=1,n=1,a=1;if(i.length===3)s=parseInt(i[0]+i[0],16)/255,r=parseInt(i[1]+i[1],16)/255,n=parseInt(i[2]+i[2],16)/255;else if(i.length===4)s=parseInt(i[0]+i[0],16)/255,r=parseInt(i[1]+i[1],16)/255,n=parseInt(i[2]+i[2],16)/255,a=parseInt(i[3]+i[3],16)/255;else if(i.length===6)s=parseInt(i.slice(0,2),16)/255,r=parseInt(i.slice(2,4),16)/255,n=parseInt(i.slice(4,6),16)/255;else if(i.length===8)s=parseInt(i.slice(0,2),16)/255,r=parseInt(i.slice(2,4),16)/255,n=parseInt(i.slice(4,6),16)/255,a=parseInt(i.slice(6,8),16)/255;else return Ps;return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(n)||!Number.isFinite(a)?Ps:[s,r,n,a]}function u0(e){let[t,i,s,r]=e;return[t*r,i*r,s*r,r]}function ft(e){return u0(kt(e))}function Yc(e){let t=Math.round(Math.max(0,Math.min(1,e[0]))*255),i=Math.round(Math.max(0,Math.min(1,e[1]))*255),s=Math.round(Math.max(0,Math.min(1,e[2]))*255),r=Math.max(0,Math.min(1,e[3]));return\`rgba(\${t}, \${i}, \${s}, \${r})\`}function pa(e,t,i){if(!t||e.length<2||i<=0)return i;let s=e[e.length-1].time,r=typeof s=="number"?s:parseFloat(String(s));if(!Number.isFinite(r)||r<=0)return i;if(t==="ping-pong"){let n=i%(2*r);return n<=r?n:2*r-n}return i%r}function Ze(e,t){if(e.length===0)return 0;if(e.length===1)return It(e[0].value);let i=e[0],s=e[e.length-1];if(t<=It(i.time))return It(i.value);if(t>=It(s.time))return It(s.value);for(let r=0;r<e.length-1;r++){let n=e[r],a=e[r+1],o=It(n.time),c=It(a.time);if(t>=o&&t<=c){let l=c-o,u=l>0?(t-o)/l:0,h=yt(a.easing,u),f=It(n.value),p=It(a.value);return f+(p-f)*h}}return It(s.value)}function Xc(e,t){if(e.length===0)return[1,1,1,1];if(e.length===1)return Is(e[0].value);let i=e[0],s=e[e.length-1];if(t<=It(i.time))return Is(i.value);if(t>=It(s.time))return Is(s.value);for(let r=0;r<e.length-1;r++){let n=e[r],a=e[r+1],o=It(n.time),c=It(a.time);if(t>=o&&t<=c){let l=c-o,u=l>0?(t-o)/l:0,h=yt(a.easing,u),f=Is(n.value),p=Is(a.value);return[f[0]+(p[0]-f[0])*h,f[1]+(p[1]-f[1])*h,f[2]+(p[2]-f[2])*h,f[3]+(p[3]-f[3])*h]}}return Is(s.value)}function Zc(e){return e.length>0&&e.every(t=>typeof t.value=="string"&&(t.value.startsWith("#")||t.value.trim().startsWith("rgb")))}function Is(e){return kt(typeof e=="string"?e:void 0)}function It(e){if(typeof e=="number")return Number.isFinite(e)?e:0;if(typeof e=="string"){let t=parseFloat(e);return Number.isFinite(t)?t:0}return 0}function pn(e,t){let i=Math.max(0,e.trimStart),s=Math.max(0,t-i),r=e.trimDuration!=null?Math.max(0,Math.min(e.trimDuration,s)):s;return{start:i,length:r}}function Rs(e,t,i){if(t.timeRemap&&t.timeRemap.length>0){let a=Math.max(0,e-t.elementStart),o=Ze(t.timeRemap,a);return Math.max(0,Math.min(o,Math.max(0,i-1e-4)))}let{start:s,length:r}=pn(t,i);if(r<=0)return s;let n=Math.max(0,e-t.elementStart)*t.rate;return t.loop?s+n%r:s+Math.min(n,r-1e-4)}function Ri(e){return Array.isArray(e)&&e.length>0?e:null}function Ki(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function Ji(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}var mn=null;function h0(){return mn||(mn=new AudioContext,mn.suspend()),mn}async function ma(e){let t=new AbortController,i=setTimeout(()=>t.abort(),1e4),s;try{s=await fetch(e,{mode:"cors",signal:t.signal})}finally{clearTimeout(i)}if(!s.ok)throw new Error(\`Failed to fetch audio \${e}: HTTP \${s.status}\`);let r=await s.arrayBuffer();return h0().decodeAudioData(r)}function Qc(e,t,i,s){let r=1;return i>0&&(r*=Math.min(1,Math.max(0,e/i))),s>0&&(r*=Math.min(1,Math.max(0,(t-e)/s))),r}function ga(e,t,i,s){let r=new Set([e,t]);return i>0&&r.add(Math.min(i,t)),s>0&&r.add(Math.max(0,t-s)),[...r].filter(n=>n>=e).sort((n,a)=>n-a).map(n=>({tau:n,gain:Qc(n,t,i,s)}))}function _a(e){let t=e.createDynamicsCompressor();return t.threshold.value=-1,t.knee.value=0,t.ratio.value=20,t.attack.value=.003,t.release.value=.1,t}function Jc(e,t,i){let s=[],r=null,n=null;for(let a=t;a<=i+1e-9;a+=.01){let o=e(a),c=n!==null&&o!==null?(o-n)/.01:null,l=c===null?null:c>.02?"forward":c<-.02?"backward":"freeze";l==="forward"||l==="backward"?r&&r.direction===l?(r.media.push(o),r.t1=a):(r&&r.media.length>1&&s.push(r),r={t0:a-.01,t1:a,media:[n,o],direction:l}):(r&&r.media.length>1&&s.push(r),r=null),n=o}return r&&r.media.length>1&&s.push(r),s}var Kc=new WeakMap;function f0(e,t){let i=Kc.get(t);if(i)return i;let s=e.createBuffer(t.numberOfChannels,t.length,t.sampleRate);for(let r=0;r<t.numberOfChannels;r++){let n=t.getChannelData(r),a=s.getChannelData(r);for(let o=0,c=n.length;o<c;o++)a[o]=n[c-1-o]}return Kc.set(t,s),s}function el(e,t,i,s,r,n){let a=e.createBufferSource(),o=i.t1-i.t0,c=i.media.length,l=new Float32Array(Math.max(2,c-1));for(let p=0;p<c-1;p++)l[p]=Math.max(.001,Math.abs(i.media[p+1]-i.media[p])/.01);c-1===1&&(l[1]=l[0]);let u=i.media[0],h=i.media[c-1],f=Math.abs(h-u);if(i.direction==="forward"){a.buffer=t,a.playbackRate.setValueCurveAtTime(l,r,o);let p=e.createGain();p.gain.value=n,a.connect(p).connect(s),a.start(r,Math.max(0,Math.min(u,t.duration)),f)}else{let p=f0(e,t);a.buffer=p,a.playbackRate.setValueCurveAtTime(l,r,o);let m=e.createGain();m.gain.value=n,a.connect(m).connect(s),a.start(r,Math.max(0,Math.min(t.duration-u,t.duration)),f)}return a}function tl(e,t,i,s){for(let r of e){let n=ui(r.time,0),a=ya(r.duration,i-n);if(r.type==="audio"||r.type==="video")s.push({el:r,chain:t});else if(r.type==="group"){let o=r.elements;Array.isArray(o)&&tl(o,[...t,{start:n,dur:a,remap:Ri(r.time_remap)}],a,s)}}}var p0=48e3,m0=2;async function il(e,t,i,s={}){let r=s.sampleRate??p0,n=s.numberOfChannels??m0,a=Math.ceil(i*r),o=[];if(tl(e.elements,[],i,o),o.length===0)return null;let c=new OfflineAudioContext({numberOfChannels:n,length:a,sampleRate:r}),l=c.createGain(),u=_a(c);l.connect(u).connect(c.destination);let h=0;for(let{el:f,chain:p}of o){let m=String(f.source??""),g=t.get(m);if(!g){f.type==="audio"&&$().warn(\`Audio element \${f.id??"(no id)"} skipped \\u2014 buffer not preloaded for \${m}\`);continue}let y=f.type==="video"?Ri(f.time_remap):null;if(y!==null||p.some(z=>z.remap!==null)){let z=ui(f.time,0),L=ya(f.duration,i),re=f.type==="video"?Ki(f.playback_rate):1,te=V=>{let ie=V;for(let Le of p){if(ie<Le.start||ie>Le.start+Le.dur)return null;ie-=Le.start,Le.remap&&(ie=Math.max(0,Ze(Le.remap,ie)))}if(ie<z||ie>z+L)return null;let pe=Rs(ie,{elementStart:z,trimStart:xa(ui(f.trim_start,0)),trimDuration:Ji(f.trim_duration),rate:re,loop:f.loop===!0,timeRemap:y},g.duration);return Math.max(0,Math.min(pe,g.duration))},K=ui(f.volume,100),q=Math.max(0,K/100);for(let V of Jc(te,0,i))el(c,g,V,l,V.t0,q),h++;continue}let x=p.reduce((z,L)=>z+L.start,0),b=xa(x+ui(f.time,0)),S=f.type==="video"?Ki(f.playback_rate):1,v=pn({trimStart:xa(ui(f.trim_start,0)),trimDuration:Ji(f.trim_duration)},g.duration);if(b>=i||v.length<=0)continue;let T=ya(f.duration,v.length/S),C=Math.min(T,i-b),P=Math.min(v.length,C*S);if(P<=0)continue;let E=c.createBufferSource();E.buffer=g,E.playbackRate.value=S;let U=c.createGain(),H=ui(f.volume,100),Q=Math.max(0,H/100);U.gain.value=Q;let J=Math.max(0,ui(f.audio_fade_in,0)),D=Math.max(0,ui(f.audio_fade_out,0));if(J>0||D>0){let z=ga(0,C,J,D);U.gain.setValueAtTime(Q*z[0].gain,b);for(let L of z.slice(1))U.gain.linearRampToValueAtTime(Q*L.gain,b+L.tau)}E.connect(U).connect(l),f.loop?(E.loop=!0,E.loopStart=v.start,E.loopEnd=v.start+v.length,E.start(b,v.start),E.stop(b+C)):E.start(b,v.start,P),h++}return h===0?null:c.startRendering()}function ui(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function ya(e,t){return e==="auto"||e==="end"||e==null?t:ui(e,t)}function xa(e){return e<0?0:e}function sl(e){let t=e.numberOfChannels,i=e.sampleRate,s=e.length,r=2,n=t*r,a=s*n,o=44+a,c=new ArrayBuffer(o),l=new DataView(c),u=(p,m)=>{for(let g=0;g<m.length;g++)l.setUint8(p+g,m.charCodeAt(g))};u(0,"RIFF"),l.setUint32(4,36+a,!0),u(8,"WAVE"),u(12,"fmt "),l.setUint32(16,16,!0),l.setUint16(20,1,!0),l.setUint16(22,t,!0),l.setUint32(24,i,!0),l.setUint32(28,i*n,!0),l.setUint16(32,n,!0),l.setUint16(34,r*8,!0),u(36,"data"),l.setUint32(40,a,!0);let h=[];for(let p=0;p<t;p++)h.push(e.getChannelData(p));let f=44;for(let p=0;p<s;p++)for(let m=0;m<t;m++){let g=h[m][p];g=g<-1?-1:g>1?1:g,l.setInt16(f,g<0?g*32768:g*32767,!0),f+=2}return c}var rl=[[0,0,0,0,0,0,0,0],[0,0,0,0,0,24,24,0],[0,0,0,126,0,0,0,0],[0,24,24,0,0,24,24,0],[0,0,126,0,126,0,0,0],[0,24,24,126,24,24,0,0],[0,198,204,24,48,102,198,0],[0,102,60,255,60,102,0,0],[124,198,222,222,222,192,120,0],[108,108,254,108,254,108,108,0]],ba=80,nl=8;function al(){let e=new OffscreenCanvas(ba,nl),t=e.getContext("2d"),i=t.createImageData(ba,nl);for(let s=0;s<rl.length;s++){let r=rl[s];for(let n=0;n<8;n++){let a=r[n];for(let o=0;o<8;o++){if(!(a&128>>o))continue;let c=(n*ba+s*8+o)*4;i.data[c]=255,i.data[c+1]=255,i.data[c+2]=255,i.data[c+3]=255}}}return t.putImageData(i,0,0),e}function va(){return{e:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],aff:!0}}function Qe(e,t){if(e.aff&&t.aff){let n=e.e[0],a=e.e[1],o=e.e[4],c=e.e[5],l=e.e[12],u=e.e[13],h=t.e[0],f=t.e[1],p=t.e[4],m=t.e[5],g=t.e[12],y=t.e[13];return{e:[n*h+o*f,a*h+c*f,0,0,n*p+o*m,a*p+c*m,0,0,0,0,1,0,n*g+o*y+l,a*g+c*y+u,0,1],aff:!0}}let i=e.e,s=t.e,r=new Array(16);for(let n=0;n<4;n++)for(let a=0;a<4;a++)r[n*4+a]=i[a]*s[n*4]+i[4+a]*s[n*4+1]+i[8+a]*s[n*4+2]+i[12+a]*s[n*4+3];return{e:r,aff:!1}}function Fi(e,t,i){if(e.aff)return[e.e[0]*t+e.e[4]*i+e.e[12],e.e[1]*t+e.e[5]*i+e.e[13]];let s=e.e,r=s[0]*t+s[4]*i+s[12],n=s[1]*t+s[5]*i+s[13],a=s[3]*t+s[7]*i+s[15];return a!==0&&a!==1?[r/a,n/a]:[r,n]}function Li(e){return Math.atan2(e.e[1],e.e[0])*(180/Math.PI)}function g0(e){return Math.sqrt(e.e[0]*e.e[0]+e.e[1]*e.e[1])}function _0(e){return Math.sqrt(e.e[4]*e.e[4]+e.e[5]*e.e[5])}function Xt(e,t,i,s,r,n,a,o){let[c,l]=Fi(e,i,s);return{cx:c,cy:l,rotation:r+Li(e),opacity01:n*t,width:a*g0(e),height:o*_0(e)}}function ze(e,t,i,s,r,n,a,o,c){let l={e:lr(t,i,s,r,n,a,o,c?.xRot??0,c?.yRot??0,c?.z??0),aff:!1};return Qe(e,l).e}function ki(e,t,i,s,r,n){let a=s*Math.PI/180,o=r*Math.PI/180,c=n*Math.PI/180,l=Math.cos(a),u=Math.sin(a),h=Math.cos(o),f=Math.sin(o),p=Math.cos(c),m=Math.sin(c),g=(b,S,v)=>{let T=S*p-v*m,C=S*m+v*p,P=b*h+C*f,E=-b*f+C*h;return[P*l-T*u,P*u+T*l,E]},y=g(1,0,0),w=g(0,1,0),x=g(0,0,1);return{e:[y[0],y[1],y[2],0,w[0],w[1],w[2],0,x[0],x[1],x[2],0,e-e*y[0]-t*w[0],t-e*y[1]-t*w[1],i-e*y[2]-t*w[2],1],aff:!1}}function ol(e,t,i,s,r,n,a,o,c,l,u,h=u){let f=s*n,p=r*a,m=o*Math.PI/180,g=c*Math.PI/180,y=l*Math.PI/180,w=Math.cos(m),x=Math.sin(m),b=Math.cos(g),S=Math.sin(g),v=Math.cos(y),T=Math.sin(y),C=(H,Q,J)=>{let D=Q*v-J*T,z=Q*T+J*v,L=H*b+z*S,re=-H*S+z*b;return[L*w-D*x,L*x+D*w,re]},P=C(u,0,0),E=C(0,h,0),U=C(0,0,1);return{e:[P[0],P[1],P[2],0,E[0],E[1],E[2],0,U[0],U[1],U[2],0,e-f*P[0]-p*E[0],t-f*P[1]-p*E[1],i-f*P[2]-p*E[2],1],aff:!1}}function cl(e,t,i,s,r,n,a,o,c=o){let l=i*r,u=s*n,h=a*Math.PI/180,f=Math.cos(h),p=Math.sin(h),m=f*o,g=p*o,y=-p*c,w=f*c;return{e:[m,g,0,0,y,w,0,0,0,0,1,0,e+m*-l+y*-u,t+g*-l+w*-u,0,1],aff:!0}}function R(e,t,i,s=0){if(e==null)return s;if(typeof e=="number")return Number.isFinite(e)?e:s;if(typeof e!="string")return s;let r=e.trim();if(r==="")return s;let n=r.match(/^(-?\\d*\\.?\\d+)\\s*(px|%|vw|vh|vmin|vmax)?$/i);if(!n)return s;let a=parseFloat(n[1]);if(!Number.isFinite(a))return s;switch((n[2]||"px").toLowerCase()){case"px":return a;case"%":return a/100*t;case"vw":return a/100*i.width;case"vh":return a/100*i.height;case"vmin":return a/100*Math.min(i.width,i.height);case"vmax":return a/100*Math.max(i.width,i.height);default:return s}}function Ie(e,t=0){if(e==null)return t;if(typeof e=="number")return Number.isFinite(e)?e:t;let i=e.trim();if(i.endsWith("%")){let r=parseFloat(i);return Number.isFinite(r)?r/100:t}let s=parseFloat(i);return Number.isFinite(s)?s:t}var ll=["mp4","gif"];var dl=["linear","ease","ease-in","ease-out","ease-in-out","ease-in-cubic","ease-out-cubic","ease-in-out-cubic","ease-in-quad","ease-out-quad","ease-in-out-quad","ease-in-quart","ease-out-quart","ease-in-out-quart","ease-in-quint","ease-out-quint","ease-in-out-quint","ease-in-sine","ease-out-sine","ease-in-out-sine","ease-in-expo","ease-out-expo","ease-in-out-expo","ease-in-circ","ease-out-circ","ease-in-out-circ","ease-in-back","ease-out-back","ease-in-out-back","spring","elastic-in","elastic-out","elastic-in-out","bounce-in","bounce-out","bounce-in-out"],ul=["fade-in","fade-out","slide-left-in","slide-right-in","slide-up-in","slide-down-in","slide-left-out","slide-right-out","slide-up-out","slide-down-out","scale-in","scale-out","rotate-in","rotate-out","bounce-in","bounce-out","spin","shake","wiggle","squash","pan","shift","drift","breathe","orbit","text-appear","text-slide","text-fly","text-typewriter","text-wave","text-flip"],hl=["tiktok_bounce","fade_reveal","kinetic_typewriter","word_pop"];var d={};jd(d,{BRAND:()=>V0,DIRTY:()=>es,EMPTY_PATH:()=>v0,INVALID:()=>Z,NEVER:()=>U_,OK:()=>Tt,ParseStatus:()=>bt,Schema:()=>he,ZodAny:()=>Ni,ZodArray:()=>Bi,ZodBigInt:()=>is,ZodBoolean:()=>ss,ZodBranded:()=>xr,ZodCatch:()=>ps,ZodDate:()=>rs,ZodDefault:()=>fs,ZodDiscriminatedUnion:()=>xn,ZodEffects:()=>Kt,ZodEnum:()=>us,ZodError:()=>Rt,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>bn,ZodIntersection:()=>cs,ZodIssueCode:()=>A,ZodLazy:()=>ls,ZodLiteral:()=>ds,ZodMap:()=>Hs,ZodNaN:()=>Vs,ZodNativeEnum:()=>hs,ZodNever:()=>ri,ZodNull:()=>as,ZodNullable:()=>pi,ZodNumber:()=>ts,ZodObject:()=>Ft,ZodOptional:()=>Zt,ZodParsedType:()=>F,ZodPipeline:()=>yr,ZodPromise:()=>Hi,ZodReadonly:()=>ms,ZodRecord:()=>yn,ZodSchema:()=>he,ZodSet:()=>Gs,ZodString:()=>Di,ZodSymbol:()=>Ds,ZodTransformer:()=>Kt,ZodTuple:()=>fi,ZodType:()=>he,ZodUndefined:()=>ns,ZodUnion:()=>os,ZodUnknown:()=>Ui,ZodVoid:()=>Ns,addIssueToContext:()=>I,any:()=>K0,array:()=>i_,bigint:()=>$0,boolean:()=>Sl,coerce:()=>E_,custom:()=>bl,date:()=>Y0,datetimeRegex:()=>xl,defaultErrorMap:()=>Ti,discriminatedUnion:()=>a_,effect:()=>x_,enum:()=>m_,function:()=>h_,getErrorMap:()=>Fs,getParsedType:()=>hi,instanceof:()=>q0,intersection:()=>o_,isAborted:()=>gn,isAsync:()=>Ls,isDirty:()=>_n,isValid:()=>Oi,late:()=>W0,lazy:()=>f_,literal:()=>p_,makeIssue:()=>_r,map:()=>d_,nan:()=>j0,nativeEnum:()=>g_,never:()=>e_,null:()=>Q0,nullable:()=>b_,number:()=>wl,object:()=>s_,objectUtil:()=>wa,oboolean:()=>T_,onumber:()=>k_,optional:()=>y_,ostring:()=>S_,pipeline:()=>w_,preprocess:()=>v_,promise:()=>__,quotelessJson:()=>x0,record:()=>l_,set:()=>u_,setErrorMap:()=>b0,strictObject:()=>r_,string:()=>vl,symbol:()=>X0,transformer:()=>x_,tuple:()=>c_,undefined:()=>Z0,union:()=>n_,unknown:()=>J0,util:()=>xe,void:()=>t_});var xe;(function(e){e.assertEqual=r=>{};function t(r){}e.assertIs=t;function i(r){throw new Error}e.assertNever=i,e.arrayToEnum=r=>{let n={};for(let a of r)n[a]=a;return n},e.getValidEnumValues=r=>{let n=e.objectKeys(r).filter(o=>typeof r[r[o]]!="number"),a={};for(let o of n)a[o]=r[o];return e.objectValues(a)},e.objectValues=r=>e.objectKeys(r).map(function(n){return r[n]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{let n=[];for(let a in r)Object.prototype.hasOwnProperty.call(r,a)&&n.push(a);return n},e.find=(r,n)=>{for(let a of r)if(n(a))return a},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,n=" | "){return r.map(a=>typeof a=="string"?\`'\${a}'\`:a).join(n)}e.joinValues=s,e.jsonStringifyReplacer=(r,n)=>typeof n=="bigint"?n.toString():n})(xe||(xe={}));var wa;(function(e){e.mergeShapes=(t,i)=>({...t,...i})})(wa||(wa={}));var F=xe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hi=e=>{switch(typeof e){case"undefined":return F.undefined;case"string":return F.string;case"number":return Number.isNaN(e)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":return Array.isArray(e)?F.array:e===null?F.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?F.promise:typeof Map<"u"&&e instanceof Map?F.map:typeof Set<"u"&&e instanceof Set?F.set:typeof Date<"u"&&e instanceof Date?F.date:F.object;default:return F.unknown}};var A=xe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),x0=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Rt=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let i=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,i):this.__proto__=i,this.name="ZodError",this.issues=t}format(t){let i=t||function(n){return n.message},s={_errors:[]},r=n=>{for(let a of n.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)s._errors.push(i(a));else{let o=s,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(i(a))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return r(this),s}static assert(t){if(!(t instanceof e))throw new Error(\`Not a ZodError: \${t}\`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,xe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=i=>i.message){let i={},s=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];i[n]=i[n]||[],i[n].push(t(r))}else s.push(t(r));return{formErrors:s,fieldErrors:i}}get formErrors(){return this.flatten()}};Rt.create=e=>new Rt(e);var y0=(e,t)=>{let i;switch(e.code){case A.invalid_type:e.received===F.undefined?i="Required":i=\`Expected \${e.expected}, received \${e.received}\`;break;case A.invalid_literal:i=\`Invalid literal value, expected \${JSON.stringify(e.expected,xe.jsonStringifyReplacer)}\`;break;case A.unrecognized_keys:i=\`Unrecognized key(s) in object: \${xe.joinValues(e.keys,", ")}\`;break;case A.invalid_union:i="Invalid input";break;case A.invalid_union_discriminator:i=\`Invalid discriminator value. Expected \${xe.joinValues(e.options)}\`;break;case A.invalid_enum_value:i=\`Invalid enum value. Expected \${xe.joinValues(e.options)}, received '\${e.received}'\`;break;case A.invalid_arguments:i="Invalid function arguments";break;case A.invalid_return_type:i="Invalid function return type";break;case A.invalid_date:i="Invalid date";break;case A.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(i=\`Invalid input: must include "\${e.validation.includes}"\`,typeof e.validation.position=="number"&&(i=\`\${i} at one or more positions greater than or equal to \${e.validation.position}\`)):"startsWith"in e.validation?i=\`Invalid input: must start with "\${e.validation.startsWith}"\`:"endsWith"in e.validation?i=\`Invalid input: must end with "\${e.validation.endsWith}"\`:xe.assertNever(e.validation):e.validation!=="regex"?i=\`Invalid \${e.validation}\`:i="Invalid";break;case A.too_small:e.type==="array"?i=\`Array must contain \${e.exact?"exactly":e.inclusive?"at least":"more than"} \${e.minimum} element(s)\`:e.type==="string"?i=\`String must contain \${e.exact?"exactly":e.inclusive?"at least":"over"} \${e.minimum} character(s)\`:e.type==="number"?i=\`Number must be \${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}\${e.minimum}\`:e.type==="bigint"?i=\`Number must be \${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}\${e.minimum}\`:e.type==="date"?i=\`Date must be \${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}\${new Date(Number(e.minimum))}\`:i="Invalid input";break;case A.too_big:e.type==="array"?i=\`Array must contain \${e.exact?"exactly":e.inclusive?"at most":"less than"} \${e.maximum} element(s)\`:e.type==="string"?i=\`String must contain \${e.exact?"exactly":e.inclusive?"at most":"under"} \${e.maximum} character(s)\`:e.type==="number"?i=\`Number must be \${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} \${e.maximum}\`:e.type==="bigint"?i=\`BigInt must be \${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} \${e.maximum}\`:e.type==="date"?i=\`Date must be \${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} \${new Date(Number(e.maximum))}\`:i="Invalid input";break;case A.custom:i="Invalid input";break;case A.invalid_intersection_types:i="Intersection results could not be merged";break;case A.not_multiple_of:i=\`Number must be a multiple of \${e.multipleOf}\`;break;case A.not_finite:i="Number must be finite";break;default:i=t.defaultError,xe.assertNever(e)}return{message:i}},Ti=y0;var fl=Ti;function b0(e){fl=e}function Fs(){return fl}var _r=e=>{let{data:t,path:i,errorMaps:s,issueData:r}=e,n=[...i,...r.path||[]],a={...r,path:n};if(r.message!==void 0)return{...r,path:n,message:r.message};let o="",c=s.filter(l=>!!l).slice().reverse();for(let l of c)o=l(a,{data:t,defaultError:o}).message;return{...r,path:n,message:o}},v0=[];function I(e,t){let i=Fs(),s=_r({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,i,i===Ti?void 0:Ti].filter(r=>!!r)});e.common.issues.push(s)}var bt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,i){let s=[];for(let r of i){if(r.status==="aborted")return Z;r.status==="dirty"&&t.dirty(),s.push(r.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,i){let s=[];for(let r of i){let n=await r.key,a=await r.value;s.push({key:n,value:a})}return e.mergeObjectSync(t,s)}static mergeObjectSync(t,i){let s={};for(let r of i){let{key:n,value:a}=r;if(n.status==="aborted"||a.status==="aborted")return Z;n.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),n.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(s[n.value]=a.value)}return{status:t.value,value:s}}},Z=Object.freeze({status:"aborted"}),es=e=>({status:"dirty",value:e}),Tt=e=>({status:"valid",value:e}),gn=e=>e.status==="aborted",_n=e=>e.status==="dirty",Oi=e=>e.status==="valid",Ls=e=>typeof Promise<"u"&&e instanceof Promise;var G;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(G||(G={}));var Qt=class{constructor(t,i,s,r){this._cachedPath=[],this.parent=t,this.data=i,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},pl=(e,t)=>{if(Oi(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let i=new Rt(e.common.issues);return this._error=i,this._error}}};function ce(e){if(!e)return{};let{errorMap:t,invalid_type_error:i,required_error:s,description:r}=e;if(t&&(i||s))throw new Error(\`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.\`);return t?{errorMap:t,description:r}:{errorMap:(a,o)=>{let{message:c}=e;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??s??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??i??o.defaultError}},description:r}}var he=class{get description(){return this._def.description}_getType(t){return hi(t.data)}_getOrReturnCtx(t,i){return i||{common:t.parent.common,data:t.data,parsedType:hi(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new bt,ctx:{common:t.parent.common,data:t.data,parsedType:hi(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let i=this._parse(t);if(Ls(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(t){let i=this._parse(t);return Promise.resolve(i)}parse(t,i){let s=this.safeParse(t,i);if(s.success)return s.data;throw s.error}safeParse(t,i){let s={common:{issues:[],async:i?.async??!1,contextualErrorMap:i?.errorMap},path:i?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:hi(t)},r=this._parseSync({data:t,path:s.path,parent:s});return pl(s,r)}"~validate"(t){let i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:hi(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:i});return Oi(s)?{value:s.value}:{issues:i.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:i}).then(s=>Oi(s)?{value:s.value}:{issues:i.common.issues})}async parseAsync(t,i){let s=await this.safeParseAsync(t,i);if(s.success)return s.data;throw s.error}async safeParseAsync(t,i){let s={common:{issues:[],contextualErrorMap:i?.errorMap,async:!0},path:i?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:hi(t)},r=this._parse({data:t,path:s.path,parent:s}),n=await(Ls(r)?r:Promise.resolve(r));return pl(s,n)}refine(t,i){let s=r=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(r):i;return this._refinement((r,n)=>{let a=t(r),o=()=>n.addIssue({code:A.custom,...s(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(t,i){return this._refinement((s,r)=>t(s)?!0:(r.addIssue(typeof i=="function"?i(s,r):i),!1))}_refinement(t){return new Kt({schema:this,typeName:ee.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:i=>this["~validate"](i)}}optional(){return Zt.create(this,this._def)}nullable(){return pi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Bi.create(this)}promise(){return Hi.create(this,this._def)}or(t){return os.create([this,t],this._def)}and(t){return cs.create(this,t,this._def)}transform(t){return new Kt({...ce(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let i=typeof t=="function"?t:()=>t;return new fs({...ce(this._def),innerType:this,defaultValue:i,typeName:ee.ZodDefault})}brand(){return new xr({typeName:ee.ZodBranded,type:this,...ce(this._def)})}catch(t){let i=typeof t=="function"?t:()=>t;return new ps({...ce(this._def),innerType:this,catchValue:i,typeName:ee.ZodCatch})}describe(t){let i=this.constructor;return new i({...this._def,description:t})}pipe(t){return yr.create(this,t)}readonly(){return ms.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},w0=/^c[^\\s-]{8,}$/i,S0=/^[0-9a-z]+$/,k0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,T0=/^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i,E0=/^[a-z0-9_-]{21}$/i,U0=/^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,B0=/^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/,A0=/^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i,C0="^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$",Sa,M0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,z0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,P0=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,I0=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,R0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,F0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gl="((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))",L0=new RegExp(\`^\${gl}$\`);function _l(e){let t="[0-5]\\\\d";e.precision?t=\`\${t}\\\\.\\\\d{\${e.precision}}\`:e.precision==null&&(t=\`\${t}(\\\\.\\\\d+)?\`);let i=e.precision?"+":"?";return\`([01]\\\\d|2[0-3]):[0-5]\\\\d(:\${t})\${i}\`}function O0(e){return new RegExp(\`^\${_l(e)}$\`)}function xl(e){let t=\`\${gl}T\${_l(e)}\`,i=[];return i.push(e.local?"Z?":"Z"),e.offset&&i.push("([+-]\\\\d{2}:?\\\\d{2})"),t=\`\${t}(\${i.join("|")})\`,new RegExp(\`^\${t}$\`)}function D0(e,t){return!!((t==="v4"||!t)&&M0.test(e)||(t==="v6"||!t)&&P0.test(e))}function N0(e,t){if(!U0.test(e))return!1;try{let[i]=e.split(".");if(!i)return!1;let s=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||t&&r.alg!==t)}catch{return!1}}function H0(e,t){return!!((t==="v4"||!t)&&z0.test(e)||(t==="v6"||!t)&&I0.test(e))}var Di=class e extends he{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==F.string){let n=this._getOrReturnCtx(t);return I(n,{code:A.invalid_type,expected:F.string,received:n.parsedType}),Z}let s=new bt,r;for(let n of this._def.checks)if(n.kind==="min")t.data.length<n.value&&(r=this._getOrReturnCtx(t,r),I(r,{code:A.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),s.dirty());else if(n.kind==="max")t.data.length>n.value&&(r=this._getOrReturnCtx(t,r),I(r,{code:A.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),s.dirty());else if(n.kind==="length"){let a=t.data.length>n.value,o=t.data.length<n.value;(a||o)&&(r=this._getOrReturnCtx(t,r),a?I(r,{code:A.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&I(r,{code:A.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),s.dirty())}else if(n.kind==="email")A0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"email",code:A.invalid_string,message:n.message}),s.dirty());else if(n.kind==="emoji")Sa||(Sa=new RegExp(C0,"u")),Sa.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"emoji",code:A.invalid_string,message:n.message}),s.dirty());else if(n.kind==="uuid")T0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"uuid",code:A.invalid_string,message:n.message}),s.dirty());else if(n.kind==="nanoid")E0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"nanoid",code:A.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid")w0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"cuid",code:A.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid2")S0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"cuid2",code:A.invalid_string,message:n.message}),s.dirty());else if(n.kind==="ulid")k0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"ulid",code:A.invalid_string,message:n.message}),s.dirty());else if(n.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),I(r,{validation:"url",code:A.invalid_string,message:n.message}),s.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"regex",code:A.invalid_string,message:n.message}),s.dirty())):n.kind==="trim"?t.data=t.data.trim():n.kind==="includes"?t.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(t,r),I(r,{code:A.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),s.dirty()):n.kind==="toLowerCase"?t.data=t.data.toLowerCase():n.kind==="toUpperCase"?t.data=t.data.toUpperCase():n.kind==="startsWith"?t.data.startsWith(n.value)||(r=this._getOrReturnCtx(t,r),I(r,{code:A.invalid_string,validation:{startsWith:n.value},message:n.message}),s.dirty()):n.kind==="endsWith"?t.data.endsWith(n.value)||(r=this._getOrReturnCtx(t,r),I(r,{code:A.invalid_string,validation:{endsWith:n.value},message:n.message}),s.dirty()):n.kind==="datetime"?xl(n).test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{code:A.invalid_string,validation:"datetime",message:n.message}),s.dirty()):n.kind==="date"?L0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{code:A.invalid_string,validation:"date",message:n.message}),s.dirty()):n.kind==="time"?O0(n).test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{code:A.invalid_string,validation:"time",message:n.message}),s.dirty()):n.kind==="duration"?B0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"duration",code:A.invalid_string,message:n.message}),s.dirty()):n.kind==="ip"?D0(t.data,n.version)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"ip",code:A.invalid_string,message:n.message}),s.dirty()):n.kind==="jwt"?N0(t.data,n.alg)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"jwt",code:A.invalid_string,message:n.message}),s.dirty()):n.kind==="cidr"?H0(t.data,n.version)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"cidr",code:A.invalid_string,message:n.message}),s.dirty()):n.kind==="base64"?R0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"base64",code:A.invalid_string,message:n.message}),s.dirty()):n.kind==="base64url"?F0.test(t.data)||(r=this._getOrReturnCtx(t,r),I(r,{validation:"base64url",code:A.invalid_string,message:n.message}),s.dirty()):xe.assertNever(n);return{status:s.value,value:t.data}}_regex(t,i,s){return this.refinement(r=>t.test(r),{validation:i,code:A.invalid_string,...G.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...G.errToObj(t)})}url(t){return this._addCheck({kind:"url",...G.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...G.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...G.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...G.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...G.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...G.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...G.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...G.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...G.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...G.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...G.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...G.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...G.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...G.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...G.errToObj(t)})}regex(t,i){return this._addCheck({kind:"regex",regex:t,...G.errToObj(i)})}includes(t,i){return this._addCheck({kind:"includes",value:t,position:i?.position,...G.errToObj(i?.message)})}startsWith(t,i){return this._addCheck({kind:"startsWith",value:t,...G.errToObj(i)})}endsWith(t,i){return this._addCheck({kind:"endsWith",value:t,...G.errToObj(i)})}min(t,i){return this._addCheck({kind:"min",value:t,...G.errToObj(i)})}max(t,i){return this._addCheck({kind:"max",value:t,...G.errToObj(i)})}length(t,i){return this._addCheck({kind:"length",value:t,...G.errToObj(i)})}nonempty(t){return this.min(1,G.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxLength(){let t=null;for(let i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}};Di.create=e=>new Di({checks:[],typeName:ee.ZodString,coerce:e?.coerce??!1,...ce(e)});function G0(e,t){let i=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=i>s?i:s,n=Number.parseInt(e.toFixed(r).replace(".","")),a=Number.parseInt(t.toFixed(r).replace(".",""));return n%a/10**r}var ts=class e extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==F.number){let n=this._getOrReturnCtx(t);return I(n,{code:A.invalid_type,expected:F.number,received:n.parsedType}),Z}let s,r=new bt;for(let n of this._def.checks)n.kind==="int"?xe.isInteger(t.data)||(s=this._getOrReturnCtx(t,s),I(s,{code:A.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(s=this._getOrReturnCtx(t,s),I(s,{code:A.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(s=this._getOrReturnCtx(t,s),I(s,{code:A.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):n.kind==="multipleOf"?G0(t.data,n.value)!==0&&(s=this._getOrReturnCtx(t,s),I(s,{code:A.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):n.kind==="finite"?Number.isFinite(t.data)||(s=this._getOrReturnCtx(t,s),I(s,{code:A.not_finite,message:n.message}),r.dirty()):xe.assertNever(n);return{status:r.value,value:t.data}}gte(t,i){return this.setLimit("min",t,!0,G.toString(i))}gt(t,i){return this.setLimit("min",t,!1,G.toString(i))}lte(t,i){return this.setLimit("max",t,!0,G.toString(i))}lt(t,i){return this.setLimit("max",t,!1,G.toString(i))}setLimit(t,i,s,r){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:i,inclusive:s,message:G.toString(r)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:G.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(t)})}multipleOf(t,i){return this._addCheck({kind:"multipleOf",value:t,message:G.toString(i)})}finite(t){return this._addCheck({kind:"finite",message:G.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(t)})}get minValue(){let t=null;for(let i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxValue(){let t=null;for(let i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&xe.isInteger(t.value))}get isFinite(){let t=null,i=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(i===null||s.value>i)&&(i=s.value):s.kind==="max"&&(t===null||s.value<t)&&(t=s.value)}return Number.isFinite(i)&&Number.isFinite(t)}};ts.create=e=>new ts({checks:[],typeName:ee.ZodNumber,coerce:e?.coerce||!1,...ce(e)});var is=class e extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==F.bigint)return this._getInvalidInput(t);let s,r=new bt;for(let n of this._def.checks)n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(s=this._getOrReturnCtx(t,s),I(s,{code:A.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(s=this._getOrReturnCtx(t,s),I(s,{code:A.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):n.kind==="multipleOf"?t.data%n.value!==BigInt(0)&&(s=this._getOrReturnCtx(t,s),I(s,{code:A.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):xe.assertNever(n);return{status:r.value,value:t.data}}_getInvalidInput(t){let i=this._getOrReturnCtx(t);return I(i,{code:A.invalid_type,expected:F.bigint,received:i.parsedType}),Z}gte(t,i){return this.setLimit("min",t,!0,G.toString(i))}gt(t,i){return this.setLimit("min",t,!1,G.toString(i))}lte(t,i){return this.setLimit("max",t,!0,G.toString(i))}lt(t,i){return this.setLimit("max",t,!1,G.toString(i))}setLimit(t,i,s,r){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:i,inclusive:s,message:G.toString(r)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(t)})}multipleOf(t,i){return this._addCheck({kind:"multipleOf",value:t,message:G.toString(i)})}get minValue(){let t=null;for(let i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxValue(){let t=null;for(let i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}};is.create=e=>new is({checks:[],typeName:ee.ZodBigInt,coerce:e?.coerce??!1,...ce(e)});var ss=class extends he{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==F.boolean){let s=this._getOrReturnCtx(t);return I(s,{code:A.invalid_type,expected:F.boolean,received:s.parsedType}),Z}return Tt(t.data)}};ss.create=e=>new ss({typeName:ee.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});var rs=class e extends he{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==F.date){let n=this._getOrReturnCtx(t);return I(n,{code:A.invalid_type,expected:F.date,received:n.parsedType}),Z}if(Number.isNaN(t.data.getTime())){let n=this._getOrReturnCtx(t);return I(n,{code:A.invalid_date}),Z}let s=new bt,r;for(let n of this._def.checks)n.kind==="min"?t.data.getTime()<n.value&&(r=this._getOrReturnCtx(t,r),I(r,{code:A.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),s.dirty()):n.kind==="max"?t.data.getTime()>n.value&&(r=this._getOrReturnCtx(t,r),I(r,{code:A.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),s.dirty()):xe.assertNever(n);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,i){return this._addCheck({kind:"min",value:t.getTime(),message:G.toString(i)})}max(t,i){return this._addCheck({kind:"max",value:t.getTime(),message:G.toString(i)})}get minDate(){let t=null;for(let i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t!=null?new Date(t):null}};rs.create=e=>new rs({checks:[],coerce:e?.coerce||!1,typeName:ee.ZodDate,...ce(e)});var Ds=class extends he{_parse(t){if(this._getType(t)!==F.symbol){let s=this._getOrReturnCtx(t);return I(s,{code:A.invalid_type,expected:F.symbol,received:s.parsedType}),Z}return Tt(t.data)}};Ds.create=e=>new Ds({typeName:ee.ZodSymbol,...ce(e)});var ns=class extends he{_parse(t){if(this._getType(t)!==F.undefined){let s=this._getOrReturnCtx(t);return I(s,{code:A.invalid_type,expected:F.undefined,received:s.parsedType}),Z}return Tt(t.data)}};ns.create=e=>new ns({typeName:ee.ZodUndefined,...ce(e)});var as=class extends he{_parse(t){if(this._getType(t)!==F.null){let s=this._getOrReturnCtx(t);return I(s,{code:A.invalid_type,expected:F.null,received:s.parsedType}),Z}return Tt(t.data)}};as.create=e=>new as({typeName:ee.ZodNull,...ce(e)});var Ni=class extends he{constructor(){super(...arguments),this._any=!0}_parse(t){return Tt(t.data)}};Ni.create=e=>new Ni({typeName:ee.ZodAny,...ce(e)});var Ui=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Tt(t.data)}};Ui.create=e=>new Ui({typeName:ee.ZodUnknown,...ce(e)});var ri=class extends he{_parse(t){let i=this._getOrReturnCtx(t);return I(i,{code:A.invalid_type,expected:F.never,received:i.parsedType}),Z}};ri.create=e=>new ri({typeName:ee.ZodNever,...ce(e)});var Ns=class extends he{_parse(t){if(this._getType(t)!==F.undefined){let s=this._getOrReturnCtx(t);return I(s,{code:A.invalid_type,expected:F.void,received:s.parsedType}),Z}return Tt(t.data)}};Ns.create=e=>new Ns({typeName:ee.ZodVoid,...ce(e)});var Bi=class e extends he{_parse(t){let{ctx:i,status:s}=this._processInputParams(t),r=this._def;if(i.parsedType!==F.array)return I(i,{code:A.invalid_type,expected:F.array,received:i.parsedType}),Z;if(r.exactLength!==null){let a=i.data.length>r.exactLength.value,o=i.data.length<r.exactLength.value;(a||o)&&(I(i,{code:a?A.too_big:A.too_small,minimum:o?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&i.data.length<r.minLength.value&&(I(i,{code:A.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&i.data.length>r.maxLength.value&&(I(i,{code:A.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),i.common.async)return Promise.all([...i.data].map((a,o)=>r.type._parseAsync(new Qt(i,a,i.path,o)))).then(a=>bt.mergeArray(s,a));let n=[...i.data].map((a,o)=>r.type._parseSync(new Qt(i,a,i.path,o)));return bt.mergeArray(s,n)}get element(){return this._def.type}min(t,i){return new e({...this._def,minLength:{value:t,message:G.toString(i)}})}max(t,i){return new e({...this._def,maxLength:{value:t,message:G.toString(i)}})}length(t,i){return new e({...this._def,exactLength:{value:t,message:G.toString(i)}})}nonempty(t){return this.min(1,t)}};Bi.create=(e,t)=>new Bi({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...ce(t)});function Os(e){if(e instanceof Ft){let t={};for(let i in e.shape){let s=e.shape[i];t[i]=Zt.create(Os(s))}return new Ft({...e._def,shape:()=>t})}else return e instanceof Bi?new Bi({...e._def,type:Os(e.element)}):e instanceof Zt?Zt.create(Os(e.unwrap())):e instanceof pi?pi.create(Os(e.unwrap())):e instanceof fi?fi.create(e.items.map(t=>Os(t))):e}var Ft=class e extends he{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),i=xe.objectKeys(t);return this._cached={shape:t,keys:i},this._cached}_parse(t){if(this._getType(t)!==F.object){let l=this._getOrReturnCtx(t);return I(l,{code:A.invalid_type,expected:F.object,received:l.parsedType}),Z}let{status:s,ctx:r}=this._processInputParams(t),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof ri&&this._def.unknownKeys==="strip"))for(let l in r.data)a.includes(l)||o.push(l);let c=[];for(let l of a){let u=n[l],h=r.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Qt(r,h,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof ri){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of o)c.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(l==="strict")o.length>0&&(I(r,{code:A.unrecognized_keys,keys:o}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of o){let h=r.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Qt(r,h,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let h=await u.key,f=await u.value;l.push({key:h,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>bt.mergeObjectSync(s,l)):bt.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(t){return G.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(i,s)=>{let r=this._def.errorMap?.(i,s).message??s.defaultError;return i.code==="unrecognized_keys"?{message:G.errToObj(t).message??r}:{message:r}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ee.ZodObject})}setKey(t,i){return this.augment({[t]:i})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let i={};for(let s of xe.objectKeys(t))t[s]&&this.shape[s]&&(i[s]=this.shape[s]);return new e({...this._def,shape:()=>i})}omit(t){let i={};for(let s of xe.objectKeys(this.shape))t[s]||(i[s]=this.shape[s]);return new e({...this._def,shape:()=>i})}deepPartial(){return Os(this)}partial(t){let i={};for(let s of xe.objectKeys(this.shape)){let r=this.shape[s];t&&!t[s]?i[s]=r:i[s]=r.optional()}return new e({...this._def,shape:()=>i})}required(t){let i={};for(let s of xe.objectKeys(this.shape))if(t&&!t[s])i[s]=this.shape[s];else{let n=this.shape[s];for(;n instanceof Zt;)n=n._def.innerType;i[s]=n}return new e({...this._def,shape:()=>i})}keyof(){return yl(xe.objectKeys(this.shape))}};Ft.create=(e,t)=>new Ft({shape:()=>e,unknownKeys:"strip",catchall:ri.create(),typeName:ee.ZodObject,...ce(t)});Ft.strictCreate=(e,t)=>new Ft({shape:()=>e,unknownKeys:"strict",catchall:ri.create(),typeName:ee.ZodObject,...ce(t)});Ft.lazycreate=(e,t)=>new Ft({shape:e,unknownKeys:"strip",catchall:ri.create(),typeName:ee.ZodObject,...ce(t)});var os=class extends he{_parse(t){let{ctx:i}=this._processInputParams(t),s=this._def.options;function r(n){for(let o of n)if(o.result.status==="valid")return o.result;for(let o of n)if(o.result.status==="dirty")return i.common.issues.push(...o.ctx.common.issues),o.result;let a=n.map(o=>new Rt(o.ctx.common.issues));return I(i,{code:A.invalid_union,unionErrors:a}),Z}if(i.common.async)return Promise.all(s.map(async n=>{let a={...i,common:{...i.common,issues:[]},parent:null};return{result:await n._parseAsync({data:i.data,path:i.path,parent:a}),ctx:a}})).then(r);{let n,a=[];for(let c of s){let l={...i,common:{...i.common,issues:[]},parent:null},u=c._parseSync({data:i.data,path:i.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!n&&(n={result:u,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(n)return i.common.issues.push(...n.ctx.common.issues),n.result;let o=a.map(c=>new Rt(c));return I(i,{code:A.invalid_union,unionErrors:o}),Z}}get options(){return this._def.options}};os.create=(e,t)=>new os({options:e,typeName:ee.ZodUnion,...ce(t)});var Ei=e=>e instanceof ls?Ei(e.schema):e instanceof Kt?Ei(e.innerType()):e instanceof ds?[e.value]:e instanceof us?e.options:e instanceof hs?xe.objectValues(e.enum):e instanceof fs?Ei(e._def.innerType):e instanceof ns?[void 0]:e instanceof as?[null]:e instanceof Zt?[void 0,...Ei(e.unwrap())]:e instanceof pi?[null,...Ei(e.unwrap())]:e instanceof xr||e instanceof ms?Ei(e.unwrap()):e instanceof ps?Ei(e._def.innerType):[],xn=class e extends he{_parse(t){let{ctx:i}=this._processInputParams(t);if(i.parsedType!==F.object)return I(i,{code:A.invalid_type,expected:F.object,received:i.parsedType}),Z;let s=this.discriminator,r=i.data[s],n=this.optionsMap.get(r);return n?i.common.async?n._parseAsync({data:i.data,path:i.path,parent:i}):n._parseSync({data:i.data,path:i.path,parent:i}):(I(i,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,i,s){let r=new Map;for(let n of i){let a=Ei(n.shape[t]);if(!a.length)throw new Error(\`A discriminator value for key \\\`\${t}\\\` could not be extracted from all schema options\`);for(let o of a){if(r.has(o))throw new Error(\`Discriminator property \${String(t)} has duplicate value \${String(o)}\`);r.set(o,n)}}return new e({typeName:ee.ZodDiscriminatedUnion,discriminator:t,options:i,optionsMap:r,...ce(s)})}};function ka(e,t){let i=hi(e),s=hi(t);if(e===t)return{valid:!0,data:e};if(i===F.object&&s===F.object){let r=xe.objectKeys(t),n=xe.objectKeys(e).filter(o=>r.indexOf(o)!==-1),a={...e,...t};for(let o of n){let c=ka(e[o],t[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(i===F.array&&s===F.array){if(e.length!==t.length)return{valid:!1};let r=[];for(let n=0;n<e.length;n++){let a=e[n],o=t[n],c=ka(a,o);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return i===F.date&&s===F.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var cs=class extends he{_parse(t){let{status:i,ctx:s}=this._processInputParams(t),r=(n,a)=>{if(gn(n)||gn(a))return Z;let o=ka(n.value,a.value);return o.valid?((_n(n)||_n(a))&&i.dirty(),{status:i.value,value:o.data}):(I(s,{code:A.invalid_intersection_types}),Z)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([n,a])=>r(n,a)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};cs.create=(e,t,i)=>new cs({left:e,right:t,typeName:ee.ZodIntersection,...ce(i)});var fi=class e extends he{_parse(t){let{status:i,ctx:s}=this._processInputParams(t);if(s.parsedType!==F.array)return I(s,{code:A.invalid_type,expected:F.array,received:s.parsedType}),Z;if(s.data.length<this._def.items.length)return I(s,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Z;!this._def.rest&&s.data.length>this._def.items.length&&(I(s,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());let n=[...s.data].map((a,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new Qt(s,a,s.path,o)):null}).filter(a=>!!a);return s.common.async?Promise.all(n).then(a=>bt.mergeArray(i,a)):bt.mergeArray(i,n)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};fi.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fi({items:e,typeName:ee.ZodTuple,rest:null,...ce(t)})};var yn=class e extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:i,ctx:s}=this._processInputParams(t);if(s.parsedType!==F.object)return I(s,{code:A.invalid_type,expected:F.object,received:s.parsedType}),Z;let r=[],n=this._def.keyType,a=this._def.valueType;for(let o in s.data)r.push({key:n._parse(new Qt(s,o,s.path,o)),value:a._parse(new Qt(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?bt.mergeObjectAsync(i,r):bt.mergeObjectSync(i,r)}get element(){return this._def.valueType}static create(t,i,s){return i instanceof he?new e({keyType:t,valueType:i,typeName:ee.ZodRecord,...ce(s)}):new e({keyType:Di.create(),valueType:t,typeName:ee.ZodRecord,...ce(i)})}},Hs=class extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:i,ctx:s}=this._processInputParams(t);if(s.parsedType!==F.map)return I(s,{code:A.invalid_type,expected:F.map,received:s.parsedType}),Z;let r=this._def.keyType,n=this._def.valueType,a=[...s.data.entries()].map(([o,c],l)=>({key:r._parse(new Qt(s,o,s.path,[l,"key"])),value:n._parse(new Qt(s,c,s.path,[l,"value"]))}));if(s.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of a){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return Z;(l.status==="dirty"||u.status==="dirty")&&i.dirty(),o.set(l.value,u.value)}return{status:i.value,value:o}})}else{let o=new Map;for(let c of a){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return Z;(l.status==="dirty"||u.status==="dirty")&&i.dirty(),o.set(l.value,u.value)}return{status:i.value,value:o}}}};Hs.create=(e,t,i)=>new Hs({valueType:t,keyType:e,typeName:ee.ZodMap,...ce(i)});var Gs=class e extends he{_parse(t){let{status:i,ctx:s}=this._processInputParams(t);if(s.parsedType!==F.set)return I(s,{code:A.invalid_type,expected:F.set,received:s.parsedType}),Z;let r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(I(s,{code:A.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),i.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(I(s,{code:A.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),i.dirty());let n=this._def.valueType;function a(c){let l=new Set;for(let u of c){if(u.status==="aborted")return Z;u.status==="dirty"&&i.dirty(),l.add(u.value)}return{status:i.value,value:l}}let o=[...s.data.values()].map((c,l)=>n._parse(new Qt(s,c,s.path,l)));return s.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(t,i){return new e({...this._def,minSize:{value:t,message:G.toString(i)}})}max(t,i){return new e({...this._def,maxSize:{value:t,message:G.toString(i)}})}size(t,i){return this.min(t,i).max(t,i)}nonempty(t){return this.min(1,t)}};Gs.create=(e,t)=>new Gs({valueType:e,minSize:null,maxSize:null,typeName:ee.ZodSet,...ce(t)});var bn=class e extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:i}=this._processInputParams(t);if(i.parsedType!==F.function)return I(i,{code:A.invalid_type,expected:F.function,received:i.parsedType}),Z;function s(o,c){return _r({data:o,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Fs(),Ti].filter(l=>!!l),issueData:{code:A.invalid_arguments,argumentsError:c}})}function r(o,c){return _r({data:o,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Fs(),Ti].filter(l=>!!l),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let n={errorMap:i.common.contextualErrorMap},a=i.data;if(this._def.returns instanceof Hi){let o=this;return Tt(async function(...c){let l=new Rt([]),u=await o._def.args.parseAsync(c,n).catch(p=>{throw l.addIssue(s(c,p)),l}),h=await Reflect.apply(a,this,u);return await o._def.returns._def.type.parseAsync(h,n).catch(p=>{throw l.addIssue(r(h,p)),l})})}else{let o=this;return Tt(function(...c){let l=o._def.args.safeParse(c,n);if(!l.success)throw new Rt([s(c,l.error)]);let u=Reflect.apply(a,this,l.data),h=o._def.returns.safeParse(u,n);if(!h.success)throw new Rt([r(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:fi.create(t).rest(Ui.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,i,s){return new e({args:t||fi.create([]).rest(Ui.create()),returns:i||Ui.create(),typeName:ee.ZodFunction,...ce(s)})}},ls=class extends he{get schema(){return this._def.getter()}_parse(t){let{ctx:i}=this._processInputParams(t);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}};ls.create=(e,t)=>new ls({getter:e,typeName:ee.ZodLazy,...ce(t)});var ds=class extends he{_parse(t){if(t.data!==this._def.value){let i=this._getOrReturnCtx(t);return I(i,{received:i.data,code:A.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:t.data}}get value(){return this._def.value}};ds.create=(e,t)=>new ds({value:e,typeName:ee.ZodLiteral,...ce(t)});function yl(e,t){return new us({values:e,typeName:ee.ZodEnum,...ce(t)})}var us=class e extends he{_parse(t){if(typeof t.data!="string"){let i=this._getOrReturnCtx(t),s=this._def.values;return I(i,{expected:xe.joinValues(s),received:i.parsedType,code:A.invalid_type}),Z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let i=this._getOrReturnCtx(t),s=this._def.values;return I(i,{received:i.data,code:A.invalid_enum_value,options:s}),Z}return Tt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let i of this._def.values)t[i]=i;return t}get Values(){let t={};for(let i of this._def.values)t[i]=i;return t}get Enum(){let t={};for(let i of this._def.values)t[i]=i;return t}extract(t,i=this._def){return e.create(t,{...this._def,...i})}exclude(t,i=this._def){return e.create(this.options.filter(s=>!t.includes(s)),{...this._def,...i})}};us.create=yl;var hs=class extends he{_parse(t){let i=xe.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==F.string&&s.parsedType!==F.number){let r=xe.objectValues(i);return I(s,{expected:xe.joinValues(r),received:s.parsedType,code:A.invalid_type}),Z}if(this._cache||(this._cache=new Set(xe.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let r=xe.objectValues(i);return I(s,{received:s.data,code:A.invalid_enum_value,options:r}),Z}return Tt(t.data)}get enum(){return this._def.values}};hs.create=(e,t)=>new hs({values:e,typeName:ee.ZodNativeEnum,...ce(t)});var Hi=class extends he{unwrap(){return this._def.type}_parse(t){let{ctx:i}=this._processInputParams(t);if(i.parsedType!==F.promise&&i.common.async===!1)return I(i,{code:A.invalid_type,expected:F.promise,received:i.parsedType}),Z;let s=i.parsedType===F.promise?i.data:Promise.resolve(i.data);return Tt(s.then(r=>this._def.type.parseAsync(r,{path:i.path,errorMap:i.common.contextualErrorMap})))}};Hi.create=(e,t)=>new Hi({type:e,typeName:ee.ZodPromise,...ce(t)});var Kt=class extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:i,ctx:s}=this._processInputParams(t),r=this._def.effect||null,n={addIssue:a=>{I(s,a),a.fatal?i.abort():i.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),r.type==="preprocess"){let a=r.transform(s.data,n);if(s.common.async)return Promise.resolve(a).then(async o=>{if(i.value==="aborted")return Z;let c=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return c.status==="aborted"?Z:c.status==="dirty"?es(c.value):i.value==="dirty"?es(c.value):c});{if(i.value==="aborted")return Z;let o=this._def.schema._parseSync({data:a,path:s.path,parent:s});return o.status==="aborted"?Z:o.status==="dirty"?es(o.value):i.value==="dirty"?es(o.value):o}}if(r.type==="refinement"){let a=o=>{let c=r.refinement(o,n);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?Z:(o.status==="dirty"&&i.dirty(),a(o.value),{status:i.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?Z:(o.status==="dirty"&&i.dirty(),a(o.value).then(()=>({status:i.value,value:o.value}))))}if(r.type==="transform")if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Oi(a))return Z;let o=r.transform(a.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>Oi(a)?Promise.resolve(r.transform(a.value,n)).then(o=>({status:i.value,value:o})):Z);xe.assertNever(r)}};Kt.create=(e,t,i)=>new Kt({schema:e,typeName:ee.ZodEffects,effect:t,...ce(i)});Kt.createWithPreprocess=(e,t,i)=>new Kt({schema:t,effect:{type:"preprocess",transform:e},typeName:ee.ZodEffects,...ce(i)});var Zt=class extends he{_parse(t){return this._getType(t)===F.undefined?Tt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Zt.create=(e,t)=>new Zt({innerType:e,typeName:ee.ZodOptional,...ce(t)});var pi=class extends he{_parse(t){return this._getType(t)===F.null?Tt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};pi.create=(e,t)=>new pi({innerType:e,typeName:ee.ZodNullable,...ce(t)});var fs=class extends he{_parse(t){let{ctx:i}=this._processInputParams(t),s=i.data;return i.parsedType===F.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:i.path,parent:i})}removeDefault(){return this._def.innerType}};fs.create=(e,t)=>new fs({innerType:e,typeName:ee.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});var ps=class extends he{_parse(t){let{ctx:i}=this._processInputParams(t),s={...i,common:{...i.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Ls(r)?r.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Rt(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Rt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ps.create=(e,t)=>new ps({innerType:e,typeName:ee.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});var Vs=class extends he{_parse(t){if(this._getType(t)!==F.nan){let s=this._getOrReturnCtx(t);return I(s,{code:A.invalid_type,expected:F.nan,received:s.parsedType}),Z}return{status:"valid",value:t.data}}};Vs.create=e=>new Vs({typeName:ee.ZodNaN,...ce(e)});var V0=Symbol("zod_brand"),xr=class extends he{_parse(t){let{ctx:i}=this._processInputParams(t),s=i.data;return this._def.type._parse({data:s,path:i.path,parent:i})}unwrap(){return this._def.type}},yr=class e extends he{_parse(t){let{status:i,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?Z:n.status==="dirty"?(i.dirty(),es(n.value)):this._def.out._parseAsync({data:n.value,path:s.path,parent:s})})();{let r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?Z:r.status==="dirty"?(i.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(t,i){return new e({in:t,out:i,typeName:ee.ZodPipeline})}},ms=class extends he{_parse(t){let i=this._def.innerType._parse(t),s=r=>(Oi(r)&&(r.value=Object.freeze(r.value)),r);return Ls(i)?i.then(r=>s(r)):s(i)}unwrap(){return this._def.innerType}};ms.create=(e,t)=>new ms({innerType:e,typeName:ee.ZodReadonly,...ce(t)});function ml(e,t){let i=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof i=="string"?{message:i}:i}function bl(e,t={},i){return e?Ni.create().superRefine((s,r)=>{let n=e(s);if(n instanceof Promise)return n.then(a=>{if(!a){let o=ml(t,s),c=o.fatal??i??!0;r.addIssue({code:"custom",...o,fatal:c})}});if(!n){let a=ml(t,s),o=a.fatal??i??!0;r.addIssue({code:"custom",...a,fatal:o})}}):Ni.create()}var W0={object:Ft.lazycreate},ee;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ee||(ee={}));var q0=(e,t={message:\`Input not instance of \${e.name}\`})=>bl(i=>i instanceof e,t),vl=Di.create,wl=ts.create,j0=Vs.create,$0=is.create,Sl=ss.create,Y0=rs.create,X0=Ds.create,Z0=ns.create,Q0=as.create,K0=Ni.create,J0=Ui.create,e_=ri.create,t_=Ns.create,i_=Bi.create,s_=Ft.create,r_=Ft.strictCreate,n_=os.create,a_=xn.create,o_=cs.create,c_=fi.create,l_=yn.create,d_=Hs.create,u_=Gs.create,h_=bn.create,f_=ls.create,p_=ds.create,m_=us.create,g_=hs.create,__=Hi.create,x_=Kt.create,y_=Zt.create,b_=pi.create,v_=Kt.createWithPreprocess,w_=yr.create,S_=()=>vl().optional(),k_=()=>wl().optional(),T_=()=>Sl().optional(),E_={string:e=>Di.create({...e,coerce:!0}),number:e=>ts.create({...e,coerce:!0}),boolean:e=>ss.create({...e,coerce:!0}),bigint:e=>is.create({...e,coerce:!0}),date:e=>rs.create({...e,coerce:!0})};var U_=Z;var Et=d.union([d.number(),d.string()]),B_=/^(?:cubic-bezier\\(\\s*-?\\d*\\.?\\d+\\s*(?:,\\s*-?\\d*\\.?\\d+\\s*){3}\\)|steps\\(\\s*[1-9]\\d*\\s*\\))$/,wn=d.union([d.enum(dl),d.string().regex(B_,"expected cubic-bezier(x1, y1, x2, y2) or steps(n)")]),Ta=d.tuple([d.number(),d.number()]),Ea=d.tuple([d.number(),d.number(),d.number()]),we=d.object({time:Et.describe("Keyframe time in seconds, relative to the element start."),value:d.union([d.number(),d.string(),Ta,Ea]).describe("Keyframe value: a number, a string (color/length), or a position [x,y] or [x,y,z]."),easing:wn.describe("Per-keyframe easing into the next keyframe (overrides the track easing).").optional(),in_tangent:d.union([Ta,Ea]).describe("Bezier in-handle [dx,dy] (or [dx,dy,dz]) for spatial paths.").optional(),out_tangent:d.union([Ta,Ea]).describe("Bezier out-handle [dx,dy] (or [dx,dy,dz]) for spatial paths.").optional()}),Ws={vars:["t","dur","i","n","value"],consts:["PI","TAU","E"],functions:["sin","cos","tan","asin","acos","atan","atan2","sinh","cosh","tanh","abs","sign","sqrt","cbrt","pow","exp","log","log2","floor","ceil","round","trunc","fract","hypot","min","max","mod","clamp","lerp","mix","step","smoothstep","linear","ease","noise","wiggle","random"],operators:["+","-","*","/","%","^","<",">","<=",">=","==","!=","&&","||","!","?:"]},kl=\`Tier-A expression: a numeric property given as { "expr": "<formula>" }. CLOSED grammar \\u2014 a pure, deterministic function of the element's own clock; it CANNOT reference other elements or read any runtime input (no ref(), no mouse/audio/valueAtTime \\u2014 those are Tier-B and are permanently unsupported). Variables: \${Ws.vars.join(", ")} (t = element-local seconds, dur = element duration, i = index in a generated set, n = sibling count, value = the property's base value). Constants: \${Ws.consts.join(", ")}. Functions (the only ones allowed): \${Ws.functions.join(", ")}. linear(x,x0,x1,y0,y1) and ease(x,x0,x1,y0,y1) map x\\u2208[x0,x1]\\u2192[y0,y1] clamped (ease = cubic in-out); noise(x[,seed]), wiggle(freq,amp[,seed]), random(seed) are deterministic. Operators: \${Ws.operators.join(" ")} (^ = power, right-assoc; ?: ternary). Any unknown identifier, function, assignment, member access, or string is a parse error, and the property silently falls back to its base value.\`,Ae=d.object({expr:d.string().min(1).describe(kl)}).strict().describe(kl),vn=d.union([d.number(),d.string(),d.array(we),Ae]),A_=d.object({type:d.enum(ul).describe("Named animation preset (e.g. fade-in, slide-left-in, bounce-in, spin, wiggle, text-appear)."),duration:d.number().nonnegative().describe("Tween length in seconds (default 0.5 for most presets).").optional(),easing:wn.describe("Easing curve for the tween (default ease-out for most presets).").optional(),split:d.enum(["letter","word"]).describe('For text presets: animate per "letter" or per "word".').optional(),stagger:d.number().nonnegative().describe("Delay between split units in seconds (default ~0.09 word, ~0.035 letter).").optional(),time:d.union([d.literal("start"),d.literal("end"),d.number()]).describe('When the tween runs: "start", "end", or a time in seconds (default "start").').optional(),frequency:d.number().positive().describe("Oscillation frequency in Hz, for oscillating presets like wiggle.").optional(),rotation:d.number().describe("Rotation magnitude in degrees (preset-specific, e.g. spin 360).").optional(),distance:d.number().describe("Travel distance in px (preset-specific, e.g. slide 40).").optional(),direction:d.enum(["left","right","up","down"]).describe("Travel direction for slide/fly-style presets.").optional(),scale:d.number().min(0).max(1).describe("Squash/scale depth, 0-1 (default 0.3).").optional(),seed:d.number().int().min(0).describe("Noise seed, integer (default 0).").optional(),axis:d.enum(["x","y","z"]).describe("For text-flip: the 3D rotation axis (default x).").optional()}),C_=d.object({property:d.string().min(1).describe('Property to animate: "x", "y", "rotation", "scale", "opacity", etc., or "position" for an [x,y]/[x,y,z] path.'),keyframes:d.array(we).min(1).describe("Keyframes in ascending time order (at least one)."),easing:wn.describe("Default easing for keyframes that do not set their own.").optional(),auto_orient:d.boolean().describe('On a "position" path, rotate the element to face its travel direction (default false).').optional(),loop:d.union([d.boolean(),d.literal("ping-pong")]).describe('Repeat the track: true (wrap), "ping-pong" (reflect), or omit to clamp.').optional()}).superRefine((e,t)=>{if(e.property!=="position")return;let i=null;e.keyframes.forEach((s,r)=>{if(!Array.isArray(s.value))return;let n=s.value.length;i===null?i=n:n!==i&&t.addIssue({code:d.ZodIssueCode.custom,path:["keyframes",r,"value"],message:"position path keyframes must agree in dimensionality \\u2014 all [x, y] or all [x, y, z] (\\xA76.7)"})}),i!==3&&e.keyframes.forEach((s,r)=>{for(let n of["in_tangent","out_tangent"])s[n]?.length===3&&t.addIssue({code:d.ZodIssueCode.custom,path:["keyframes",r,n],message:"3-component tangents require a 3D position path \\u2014 [x, y, z] keyframe values (\\xA76.7)"})})}),de=d.union([d.number(),d.array(we),Ae]),M_=d.discriminatedUnion("type",[d.object({type:d.literal("pixelate"),cell_size:de.describe("Cell size in canvas px (default 8, min 1). Each pixel takes its cell-center color.").optional()}),d.object({type:d.literal("dither"),levels:de.describe("Quantization levels per color channel (default 4, min 2).").optional(),pixel_size:de.describe("Bayer dither cell size in logical px, resolution-independent (default 2).").optional()}),d.object({type:d.literal("halftone"),cell_size:de.describe("Dot-grid cell size in canvas px (default 8, min 2).").optional(),angle:de.describe("Grid rotation in degrees (default 45).").optional()}),d.object({type:d.literal("ascii"),cell_size:de.describe("Glyph cell size in canvas px (default 12, min 4).").optional()}),d.object({type:d.literal("glass"),blur_radius:de.describe("Backdrop blur sigma in px (default 0 = clear glass; >0 = frosted).").optional(),refraction:de.describe("Lens bend strength, approx px of displacement (default 21).").optional(),edge_width:de.describe("Bevel z-radius; how deep the lens curvature reaches (default 40).").optional(),edge_highlight:de.describe("Light-rig strength; 0.35 reproduces the reference defaults (default 0.35).").optional(),shadow:de.describe("Drop-shadow opacity painted outside the pane (default 0.3).").optional(),dispersion:de.describe("Chromatic aberration along the surface normal (default 0.05).").optional(),backdrop_saturation:de.describe("Saturation of the sampled backdrop, 1 = unchanged (default 1).").optional(),tint:d.string().describe("Color drawn over the glass; its alpha is the tint strength. Static in v1.").optional(),mode:d.enum(["pill","dome"]).describe('Lens cross-section: "pill" biconvex (default) or "dome" flat-bottom magnifier.').optional()}),d.object({type:d.literal("glow"),radius:de.describe("Blur sigma of the glow, in px (default 20).").optional(),intensity:de.describe("Glow brightness multiplier (default 1).").optional(),color:d.string().describe('Glow color (default "#FFFFFF").').optional()}),d.object({type:d.literal("drop_shadow"),offset_x:de.describe("Shadow horizontal offset in px (default 0).").optional(),offset_y:de.describe("Shadow vertical offset in px (default 12).").optional(),blur:de.describe("Shadow blur sigma in px (default 18).").optional(),color:d.string().describe('Shadow color (default "#000000").').optional(),opacity:de.describe("Shadow opacity, 0..1 (default 0.6).").optional()}),d.object({type:d.literal("stroke"),width:de.describe("Outline width in px, drawn outside the silhouette (default 4).").optional(),color:d.string().describe('Stroke color (default "#FFFFFF").').optional()}),d.object({type:d.literal("chroma_key"),color:d.string().describe('Key color removed from the layer (default "#00FF00").').optional(),tolerance:de.describe("Chroma distance below which pixels are keyed out (default 0.18).").optional(),softness:de.describe("Soft-edge width past tolerance (default 0.1).").optional(),spill:de.describe("Spill suppression of the key color (default 0.5).").optional()}),d.object({type:d.literal("luma_key"),threshold:de.describe("Luma below which pixels are removed (default 0.5).").optional(),softness:de.describe("Soft-edge width past threshold (default 0.1).").optional(),invert:d.boolean().describe("Remove brighter pixels instead of darker (default false).").optional()}),d.object({type:d.literal("levels"),in_black:de.describe("Input black point, 0..1 (default 0).").optional(),in_white:de.describe("Input white point, 0..1 (default 1).").optional(),gamma:de.describe("Midtone gamma, >0; values >1 brighten midtones (default 1).").optional(),out_black:de.describe("Output black point, 0..1 (default 0).").optional(),out_white:de.describe("Output white point, 0..1 (default 1).").optional()}),d.object({type:d.literal("lut"),source:d.string().min(1).describe("URL of a .cube LUT file (http(s), relative, or data: URI)."),intensity:de.describe("Blend toward the graded color, 0..1 (default 1).").optional()}),d.object({type:d.literal("fractal_noise"),scale:de.describe("Canvas px per noise lattice cell (default 100).").optional(),evolution:de.describe("Third-axis position for animating noise churn (default 0).").optional(),offset_x:de.describe("Noise scroll offset x in canvas px (default 0).").optional(),offset_y:de.describe("Noise scroll offset y in canvas px (default 0).").optional(),octaves:d.number().int().min(1).max(8).describe("fBm octaves, integer 1-8, static (default 4).").optional(),seed:d.number().int().min(0).describe("Noise seed, integer, static; use values <2^24 (default 0).").optional()}),d.object({type:d.literal("turbulent_displace"),amount:de.describe("Max displacement in canvas px (default 16).").optional(),scale:de.describe("Canvas px per noise lattice cell (default 120).").optional(),evolution:de.describe("Third-axis position for animating noise churn (default 0).").optional(),octaves:d.number().int().min(1).max(8).describe("fBm octaves, integer 1-8, static (default 2).").optional(),seed:d.number().int().min(0).describe("Noise seed, integer, static (default 0).").optional()})]),Ht=d.union([d.number(),d.array(we),Ae]),z_=d.object({roughness:Ht.describe("Surface roughness, 0 (glossy) to 1 (matte); clamped to 0.02-1 (default 0.5).").optional(),metalness:Ht.describe("Metalness, 0 (dielectric) to 1 (metal) (default 0).").optional(),reflectivity:Ht.describe("Environment-reflection strength; needs scene lights + environment (default 1).").optional(),emissive:Ht.describe("Self-illumination strength, multiplied into the color (default 0).").optional(),normal_map:d.string().describe("URL of a tangent-space normal map for surface detail (flat texel = #8080ff).").optional(),normal_scale:Ht.describe("Normal-map strength, 0 = flat, higher = more relief (default 1).").optional()}).passthrough(),Gi={id:d.string().optional(),name:d.string().optional(),layer:d.number().int().min(1).max(1e3).describe("The element's layer in the stack (1-1000), like an After Effects layer: each element has its own unique layer and LOWER numbers draw in front (layer 1 is on top). Within equal z-depth, layer is the draw order."),visible:d.boolean().optional(),time:Et.describe("Element start time in seconds from composition start (default 0).").optional(),duration:d.union([d.number(),d.string(),d.literal("auto"),d.literal("end")]).describe('How long the element lasts: seconds, "auto" (its natural content/media length), or "end" (until the composition ends).').optional(),x:vn.describe('Horizontal position of the anchor point, in px or a string like "50%"/"100vw" (default 0). With the default anchor (left), this is the box left edge.').optional(),y:vn.describe('Vertical position of the anchor point, in px or a string like "50%" (default 0). With the default anchor (top), this is the box top edge.').optional(),x_anchor:Et.describe('Point in the box that x positions: 0 = left, "50%" = center, "100%" = right (default 0). Default 0 makes x/y the top-left corner (CSS/SVG/Canvas model); rotation and scale still pivot the box center regardless of anchor.').optional(),y_anchor:Et.describe('Point in the box that y positions: 0 = top, "50%" = center, "100%" = bottom (default 0).').optional(),width:vn.describe('Box width in px or a string like "50%"/"100vw".').optional(),height:vn.describe('Box height in px or a string like "50%"/"100vh".').optional(),aspect_ratio:d.number().positive().optional(),rotation:d.union([d.number(),d.array(we),Ae]).describe("In-plane rotation in degrees about the box center (default 0).").optional(),z_rotation:d.union([d.number(),d.array(we),Ae]).describe("Same slot as rotation (in-plane degrees); author one, not both (default 0).").optional(),x_rotation:d.union([d.number(),d.array(we),Ae]).describe("Rotation about the local x axis in degrees; tips the top edge away under a camera (default 0).").optional(),y_rotation:d.union([d.number(),d.array(we),Ae]).describe("Rotation about the local y axis in degrees; turns the right edge away under a camera (default 0).").optional(),z:d.union([d.number(),d.array(we),Ae]).describe("Depth in px toward (+) / away from (-) the viewer; orders elements and drives perspective under a camera (default 0).").optional(),scale:d.union([d.number(),d.array(we),Ae]).describe("Uniform scale factor, multiplied with x_scale/y_scale (default 1).").optional(),x_scale:d.union([d.number(),d.string(),d.array(we),Ae]).describe('Horizontal scale factor, number or "150%" (default 1).').optional(),y_scale:d.union([d.number(),d.string(),d.array(we),Ae]).describe('Vertical scale factor, number or "150%" (default 1).').optional(),x_skew:d.union([d.number(),d.array(we),Ae]).describe("Horizontal shear in degrees (CSS skewX); positive moves the bottom edge right (default 0).").optional(),y_skew:d.union([d.number(),d.array(we),Ae]).describe("Vertical shear in degrees (CSS skewY); positive moves the right edge down (default 0).").optional(),opacity:d.union([d.number(),d.array(we),Ae]).describe("Opacity from 0 (transparent) to 1 (opaque) (default 1).").optional(),blend_mode:d.enum(["normal","multiply","screen","add","overlay","hard-light","soft-light"]).optional(),blur_radius:d.union([d.number().nonnegative(),d.array(we),Ae]).describe("Gaussian blur sigma in px applied to the element (default 0 = none).").optional(),brightness:d.union([d.number().nonnegative(),d.array(we),Ae]).describe("Brightness multiplier, 1 = unchanged, >1 brightens (default 1).").optional(),contrast:d.union([d.number().nonnegative(),d.array(we),Ae]).describe("Contrast multiplier around mid-gray, 1 = unchanged (default 1).").optional(),saturation:d.union([d.number().nonnegative(),d.array(we),Ae]).describe("Saturation multiplier, 1 = unchanged, 0 = grayscale (default 1).").optional(),hue_rotate:d.union([d.number(),d.array(we),Ae]).describe("Hue rotation in degrees (default 0).").optional(),effects:d.array(M_).describe("Stylize/keying effects applied in array order (e.g. glass, drop_shadow, chroma_key, glow); they stack.").optional(),material:z_.describe("PBR material (roughness/metalness/etc.); only visible with scene lights.").optional(),animations:d.array(A_).describe("Named animation presets applied to this element (e.g. fade-in, slide-left-in); see the animation type list.").optional(),keyframe_animations:d.array(C_).describe("Explicit per-property keyframe tracks (property + keyframes[]); use for custom motion and position paths.").optional()},P_=d.object({...Gi,type:d.literal("video"),source:d.string().min(1),volume:d.union([d.number(),d.array(we),Ae]).describe("Volume in percent, 0..100 (default 100).").optional(),playback_rate:d.union([d.number(),d.array(we),Ae]).describe("Timeline seconds per media second (default 1); <1 = slow-mo, >1 = speed-up.").optional(),trim_start:d.number().nonnegative().describe("Media in-point in seconds (default 0).").optional(),trim_duration:d.number().nonnegative().describe("Length of the played window in seconds (default = remainder after trim_start).").optional(),loop:d.boolean().describe("Restart at the trim in-point when the window ends (default false).").optional(),time_remap:d.array(we).describe("Keyframes whose values are media times in seconds; replaces trim/playback_rate for warped playback.").optional(),audio_fade_in:d.number().nonnegative().describe("Audio fade-in length in seconds (default 0).").optional(),audio_fade_out:d.number().nonnegative().describe("Audio fade-out length in seconds (default 0).").optional(),fit:d.enum(["cover","contain","fill","none"]).describe("How the media fills the box (CSS object-fit): cover (default), contain, fill, or none.").optional(),crop_x:d.number().min(0).max(1).describe("Source crop origin x, normalized 0..1, applied before fit (default 0).").optional(),crop_y:d.number().min(0).max(1).describe("Source crop origin y, normalized 0..1 (default 0).").optional(),crop_width:d.number().min(0).max(1).describe("Source crop width, normalized 0..1 (default 1 = whole source).").optional(),crop_height:d.number().min(0).max(1).describe("Source crop height, normalized 0..1 (default 1).").optional()}).passthrough(),I_=d.object({...Gi,type:d.literal("image"),source:d.string().min(1),fit:d.enum(["cover","contain","fill","none"]).describe("How the image fills the box (CSS object-fit): cover (default), contain, fill, or none.").optional(),border_radius:d.number().nonnegative().describe("Corner radius in px (default 0).").optional(),crop_x:d.number().min(0).max(1).describe("Source crop origin x, normalized 0..1, applied before fit (default 0).").optional(),crop_y:d.number().min(0).max(1).describe("Source crop origin y, normalized 0..1 (default 0).").optional(),crop_width:d.number().min(0).max(1).describe("Source crop width, normalized 0..1 (default 1 = whole source).").optional(),crop_height:d.number().min(0).max(1).describe("Source crop height, normalized 0..1 (default 1).").optional()}).passthrough(),R_=d.object({type:d.literal("linear-wipe"),angle:d.number().describe("Wipe direction in degrees (default -45); 0 = left-to-right, 90 = top-to-bottom.").optional(),progress:d.union([d.number(),d.array(we),Ae]).describe("Reveal amount, 0 (hidden) to 1 (fully shown); animatable (default 1 = fully shown).").optional(),softness:d.number().min(0).max(1).describe("Softness of the wipe edge, 0..1 (default 0.3).").optional()}),Tl=d.object({color:d.string(),offset_x:d.number().describe("Shadow horizontal offset in px (default 0).").optional(),offset_y:d.number().describe("Shadow vertical offset in px, positive = down (default 0).").optional(),blur:d.number().nonnegative().describe("Shadow blur sigma in px (default 0 = crisp).").optional(),opacity:d.number().min(0).max(1).describe("Shadow opacity, 0..1 (default 1).").optional()}).passthrough(),El=d.union([Tl,d.array(Tl)]).describe("Per-glyph drop shadow: one object, or an array rendered back-to-front.").optional(),F_=d.object({color:d.string(),height_ratio:d.number().describe("Band height as a fraction of font size (default 1 = full line box).").optional(),inset_y_ratio:d.number().describe("Vertical offset of the band as a fraction of font size (default 0).").optional(),padding_x:d.number().describe("Horizontal padding around the span glyphs in px (default 0).").optional(),skew_x:d.number().describe("Horizontal skew of the band in degrees (default 0).").optional(),border_radius:d.number().nonnegative().describe("Band corner radius in px (default 0).").optional(),opacity:d.number().min(0).max(1).describe("Band opacity, 0..1 (default 1).").optional()}).passthrough(),L_=d.object({text:d.string(),font_weight:Et.optional(),font_style:d.enum(["normal","italic"]).optional(),font_family:d.string().optional(),font_size:Et.optional(),fill_color:d.string().optional(),letter_spacing:d.number().optional(),background_color:d.string().describe("Flat band behind this span; overridden by background.").optional(),background:F_.describe("Styled background band behind this span (height/inset/padding/skew/radius).").optional(),nowrap:d.boolean().describe("Prevent line-breaking inside this span (default false).").optional()}).passthrough(),O_=d.object({...Gi,type:d.literal("text"),text:d.string().describe("The text content; use this OR spans, not both.").optional(),spans:d.array(L_).describe("Rich-text runs with per-span styling; alternative to a single text string.").optional(),font_family:d.string().optional(),font_size:Et.describe('Font size in px, a string, or "auto" to fit the box.').optional(),font_size_minimum:Et.describe('Lower bound in px when font_size is "auto" (default 8).').optional(),font_size_maximum:Et.describe('Upper bound in px when font_size is "auto" (default 400).').optional(),font_weight:Et.optional(),font_style:d.enum(["normal","italic"]).optional(),fill_color:d.string().describe('Text color (default "#ffffff").').optional(),stroke_color:d.string().describe("Glyph outline color; pair with stroke_width.").optional(),stroke_width:d.number().describe("Glyph outline width in px (default 0).").optional(),text_transform:d.enum(["none","uppercase","lowercase","capitalize"]).optional(),text_wrap:d.boolean().describe("Soft-wrap within the box width (default true); false forces a single line.").optional(),text_align:d.enum(["left","center","right"]).describe('Horizontal text alignment (default "left").').optional(),vertical_align:d.enum(["top","middle","bottom"]).describe('Vertical alignment within the box (default "top").').optional(),x_padding:Et.describe("Horizontal inset in px around the text (default 0).").optional(),y_padding:Et.describe("Vertical inset in px around the text (default 0).").optional(),x_alignment:Et.describe("Fine horizontal alignment as a 0..1 fraction; overrides text_align.").optional(),y_alignment:Et.describe("Fine vertical alignment as a 0..1 fraction; overrides vertical_align.").optional(),line_height:d.number().describe("Line spacing as a multiple of font size (default 1).").optional(),letter_spacing:d.number().describe("Tracking in px added after each glyph (default 0).").optional(),background_color:d.string().describe("Background band behind the text, shrink-wrapped per line (default none).").optional(),background_border_radius:d.number().describe("Corner radius in px of the background band (default 0).").optional(),background_padding:d.union([d.number(),d.tuple([d.number(),d.number()])]).describe("Background band padding in px: a number, or [x, y] (default [0, 0]).").optional(),text_shadow:El,mask:R_.describe("Linear-wipe reveal of the text (angle/progress/softness).").optional()}).passthrough(),Sn=d.object({offset:d.number().min(0).max(1).describe("Position along the gradient, 0 (start) to 1 (end)."),color:d.string()}),D_=d.discriminatedUnion("type",[d.object({type:d.literal("ambient"),color:d.string().describe('Ambient light color (default "#FFFFFF").').optional(),intensity:Ht.describe("Ambient brightness multiplier (default 1).").optional()}).passthrough(),d.object({type:d.literal("directional"),azimuth:Ht.describe("Compass direction of the light in degrees (default 0).").optional(),elevation:Ht.describe("Height of the light above the screen plane in degrees (default 45).").optional(),color:d.string().describe('Directional light color (default "#FFFFFF").').optional(),intensity:Ht.describe("Directional brightness multiplier (default 1).").optional()}).passthrough()]),N_=d.union([d.object({type:d.literal("gradient"),stops:d.array(Sn).min(2).max(6).describe("Sky gradient stops (2-6), sampled by the reflection ray vertical component.")}).passthrough(),d.object({type:d.literal("image"),src:d.string().describe("Equirectangular environment image URL, used for material reflections.")}).passthrough()]),H_=d.object({threshold:Ht.describe("Luma above which pixels bloom, 0-1 (default 0.75).").optional(),knee:Ht.describe("Soft-knee width around the threshold (default 0.1).").optional(),intensity:Ht.describe("Bloom strength multiplier (default 1).").optional(),radius:Ht.describe("Bloom blur sigma in px (default 24).").optional()}).passthrough(),G_=d.object({type:d.literal("linear"),angle:d.number().describe("Gradient direction in degrees (CSS convention; default 180 = top-to-bottom).").optional(),stops:d.array(Sn).min(2).max(4).describe("Color stops, 2-4.")}),V_=d.object({type:d.literal("radial"),cx:d.number().describe("Center x as a fraction of the box, 0..1 (default 0.5).").optional(),cy:d.number().describe("Center y as a fraction of the box, 0..1 (default 0.5).").optional(),radius:d.number().positive().describe("Radius as a fraction of the box, 0..1 (default 0.5).").optional(),stops:d.array(Sn).min(2).max(4).describe("Color stops, 2-4.")}),W_=d.discriminatedUnion("type",[G_,V_]),q_=d.object({color:d.string(),offset_x:d.number().describe("Shadow horizontal offset in px (default 0).").optional(),offset_y:d.number().describe("Shadow vertical offset in px (default 12).").optional(),blur:d.number().nonnegative().describe("Shadow blur sigma in px (default 18).").optional()}).passthrough(),j_=d.object({id:d.string().min(1).describe("Identifier referenced from a path fill/stroke as url(#id)."),type:d.literal("linear"),x1:d.number().describe("Gradient line start x in viewBox coords; the line runs (x1,y1) to (x2,y2)."),y1:d.number(),x2:d.number(),y2:d.number(),stops:d.array(Sn).min(2).max(4).describe("Color stops, 2-4.")}),$_=d.object({d:d.union([d.string().min(1),d.array(we)]).describe("SVG path data; an array of keyframes morphs between path shapes."),fill:d.string().describe("Fill color, or url(#id) referencing a gradient (default none).").optional(),stroke:d.string().describe("Stroke color, or url(#id); needs stroke_width > 0.").optional(),stroke_width:d.number().positive().describe("Stroke width in px.").optional(),stroke_progress:d.union([d.number(),d.array(we),Ae]).describe("Reveal fraction of the stroke length, 0..1 (default 1); shorthand for a draw-on trim.").optional(),trim_start:de.describe("Stroke start as a fraction of path length, 0..1 (default 0).").optional(),trim_end:de.describe("Stroke end as a fraction of path length, 0..1 (default 1).").optional(),trim_offset:de.describe("Rotate the visible trim window around the path, 0..1 wrapping (default 0).").optional(),clip_path:d.string().describe("SVG path d-string that clips this path (intersection).").optional(),stroke_linecap:d.enum(["butt","round","square"]).describe('Line-end style (default "butt").').optional(),stroke_linejoin:d.enum(["miter","round","bevel"]).describe('Line-join style (default "miter").').optional(),opacity:d.number().min(0).max(1).describe("Path opacity, 0..1 (default 1).").optional()}),Y_=d.object({...Gi,type:d.literal("shape"),shape:d.enum(["rectangle","ellipse"]).describe('Primitive kind: "rectangle" (default) or "ellipse". Ignored when paths is present.').optional(),fill_color:d.string().describe('Solid fill color, hex or CSS name (default "#ffffff"); overridden by gradient.').optional(),gradient:W_.describe("Linear or radial gradient fill (overrides fill_color).").optional(),stroke_color:d.string().describe("Outline color, hex or CSS name; pair with stroke_width > 0.").optional(),stroke_width:d.number().describe("Outline width in px, drawn outside the shape (default 0 = no stroke).").optional(),border_radius:d.number().describe("Corner radius in px for a rectangle (default 0).").optional(),shadow:q_.describe("Drop shadow cast by the shape (color, offset, blur).").optional(),paths:d.array($_).min(1).describe("Vector path form: an array of SVG paths. Its presence switches the shape from primitive to vector and ignores shape/fill_color/etc.").optional(),view_box:d.tuple([d.number(),d.number(),d.number(),d.number()]).describe("SVG viewBox [x, y, width, height] for the paths coordinate space (default [0, 0, 100, 100]).").optional(),gradients:d.array(j_).describe("Named gradients referenced from path fill/stroke as url(#id).").optional()}).passthrough(),X_=d.object({...Gi,type:d.literal("audio"),source:d.string().min(1),volume:d.union([d.number(),d.array(we),Ae]).describe("Volume in percent, 0..100 (default 100).").optional(),trim_start:d.number().nonnegative().describe("Media in-point in seconds (default 0).").optional(),trim_duration:d.number().nonnegative().describe("Length of the played window in seconds (default = remainder after trim_start).").optional(),loop:d.boolean().describe("Restart at the trim in-point when the window ends (default false).").optional(),audio_fade_in:d.number().nonnegative().describe("Fade-in length in seconds (default 0).").optional(),audio_fade_out:d.number().nonnegative().describe("Fade-out length in seconds (default 0).").optional()}).passthrough(),Z_=d.object({...Gi,type:d.literal("group"),elements:d.array(d.unknown()).min(1).describe("Child elements; the group transform composes onto all of them (couple elements without duplicating motion onto each)."),time_remap:d.array(we).describe("Keyframes that warp the group subtree clock (values are warped seconds).").optional(),clip:d.boolean().describe("Clip children to the group box (default false).").optional(),border_radius:d.number().nonnegative().describe("Corner radius in px of the clipped group box (default 0).").optional(),mask:d.object({mode:d.enum(["alpha","alpha-inverted","luma","luma-inverted"]).describe("How the mask layer drives content opacity: alpha or luma, optionally inverted."),elements:d.array(d.unknown()).min(1).describe("Elements that compose the mask layer.")}).describe("Mask the group with another set of elements (alpha or luma).").optional()}).passthrough(),Q_=d.object({text:d.string(),start:d.number().nonnegative(),end:d.number().nonnegative()}),K_=d.object({...Gi,type:d.literal("caption"),words:d.array(Q_).min(1).describe("Word timings: array of { text, start, end } in seconds; drives the karaoke-style highlight."),style:d.enum(hl).describe("Kinetic caption preset (e.g. tiktok_bounce, fade_reveal, word_pop).").optional(),max_length:d.union([d.number().int().positive(),d.literal("auto")]).describe('On-screen chunking: max letters per chunk (number) or "auto" (a few words); omit to show all words at once.').optional(),font_family:d.string().optional(),font_size:Et.describe('Font size in px, a string, or "auto" to fit (default "auto").').optional(),font_weight:Et.optional(),font_style:d.enum(["normal","italic"]).optional(),fill_color:d.string().describe('Color of inactive (not-yet-spoken) words (default "#ffffff").').optional(),stroke_color:d.string().describe("Glyph outline color; pair with stroke_width.").optional(),stroke_width:d.number().describe("Glyph outline width in px (default 0).").optional(),text_align:d.enum(["left","center","right"]).describe('Horizontal alignment (default "left").').optional(),line_height:d.number().describe("Line spacing as a multiple of font size (default 1.2).").optional(),letter_spacing:d.number().describe("Tracking in px added after each glyph (default 0).").optional(),background_color:d.string().describe("Background band behind the caption (default none).").optional(),background_border_radius:d.number().describe("Corner radius in px of the background band (default 0).").optional(),background_padding:d.union([d.number(),d.tuple([d.number(),d.number()])]).describe("Background band padding in px: a number, or [x, y] (default [0, 0]).").optional(),text_shadow:El,highlight_color:d.string().describe('Color of the active (currently-spoken) word (default "#ffd60a").').optional(),highlight_background_color:d.string().describe("Background color behind the active word (default none).").optional()}).passthrough(),J_=d.object({...Gi,type:d.literal("particles"),rate:d.number().positive().describe("Particles emitted per second (default 60).").optional(),lifetime:d.number().positive().describe("Seconds each particle lives (default 1.5).").optional(),velocity:d.number().nonnegative().describe("Initial particle speed in px/s (default 300).").optional(),spread:d.number().min(0).max(360).describe("Emission cone width in degrees, 0-360 (default 360 = all directions).").optional(),direction:d.number().describe("Emission direction in degrees: 0 = right, 90 = down, -90 = up (default -90).").optional(),gravity:d.number().describe("Downward acceleration in px/s^2 (default 600).").optional(),color:d.union([d.string(),d.array(d.string()).min(1)]).describe("Particle color, or an array of colors picked per particle.").optional(),size:d.number().positive().describe("Particle size in px (default 12).").optional(),size_variation:d.number().min(0).max(1).describe("Random size variation, 0-1 (default 0.4).").optional(),particle_shape:d.enum(["square","circle"]).describe('Particle shape (default "square").').optional(),rotation_speed:d.number().describe("Spin rate in degrees/s (default 360).").optional(),burst:d.boolean().describe("Emit all particles at once instead of continuously (default false).").optional(),burst_count:d.number().int().min(1).max(2e3).describe("Particles emitted in burst mode (default 80).").optional(),fade_at:d.number().min(0).max(1).describe("Lifetime fraction where fade-out begins, 0-1 (default 0.7).").optional(),z_velocity:d.number().describe("Depth speed in px/s along the plane normal (default 0).").optional(),z_spread:d.number().nonnegative().describe("Random depth-speed range in px/s (default 0).").optional(),target_points:d.array(d.tuple([d.number(),d.number()])).describe("Canvas-space [x, y] targets the particles converge toward.").optional(),convergence_easing:wn.describe("Easing for convergence toward target_points.").optional(),scatter_radius:d.number().nonnegative().describe("Spawn-disk radius in px (default = the larger canvas dimension).").optional()}).passthrough(),ex=d.discriminatedUnion("type",[P_,I_,O_,Y_,X_,Z_,K_,J_]),tx=d.object({family:d.string().min(1).describe("Family name that text/caption elements reference via font_family."),weight:d.union([d.number(),d.string()]).describe('CSS font-weight this face covers, e.g. 400, "bold", or a range "100 900" (default "normal").').optional(),style:d.enum(["normal","italic"]).optional(),src:d.string().min(1).describe("Font file URL (http(s), relative, or data: URI)."),unicode_range:d.string().describe("CSS unicode-range this face covers, for subsetting.").optional()}).passthrough(),ix=d.object({perspective:d.union([d.number().positive(),d.array(we),Ae]).describe("Focal distance in px (>0); smaller = stronger perspective foreshortening."),origin_x:d.union([d.number(),d.string()]).describe("Vanishing-point x, px or string (default canvas center).").optional(),origin_y:d.union([d.number(),d.string()]).describe("Vanishing-point y, px or string (default canvas center).").optional(),x:d.union([d.number(),d.array(we),Ae]).describe("Camera dolly x in px (default 0).").optional(),y:d.union([d.number(),d.array(we),Ae]).describe("Camera dolly y in px (default 0).").optional(),z:d.union([d.number(),d.array(we),Ae]).describe("Camera dolly toward the scene in px; +z = closer (default 0).").optional(),x_rotation:d.union([d.number(),d.array(we),Ae]).describe("Camera pitch in degrees (default 0).").optional(),y_rotation:d.union([d.number(),d.array(we),Ae]).describe("Camera yaw in degrees (default 0).").optional(),z_rotation:d.union([d.number(),d.array(we),Ae]).describe("Camera roll in degrees (default 0).").optional(),sort:d.enum(["depth","paint"]).describe('Compositing order: "depth" (2.5D by z, default) or "paint" (fixed layer order, layer 1 on top).').optional()}).passthrough();function Ua(e,t,i){let s=new Map;e.forEach((r,n)=>{if(typeof r!="object"||r===null)return;let a=r.layer;if(typeof a=="number"){let o=s.get(a);o?o.push(n):s.set(a,[n])}});for(let[r,n]of s)if(!(n.length<2))for(let a of n)i.addIssue({code:d.ZodIssueCode.custom,path:[...t,a,"layer"],message:\`duplicate layer \${r} \\u2014 each element in a container needs a unique layer (layer 1 = top); renumber the colliding elements\`});e.forEach((r,n)=>{if(typeof r!="object"||r===null)return;let a=r,o=[...t,n];a.rotation!==void 0&&a.z_rotation!==void 0&&i.addIssue({code:d.ZodIssueCode.custom,path:[...o,"z_rotation"],message:"\`rotation\` and \`z_rotation\` are the same slot \\u2014 author one, not both (\\xA74.4)"}),a.type==="group"&&Array.isArray(a.elements)&&Ua(a.elements,[...o,"elements"],i);let c=a.mask;a.type==="group"&&c&&Array.isArray(c.elements)&&Ua(c.elements,[...o,"mask","elements"],i)})}var sx=d.object({clipkit_version:d.string().describe('Protocol version (default "1.0").').optional(),output_format:d.enum(ll).describe('Output format: "mp4" (default) or "gif".').optional(),width:d.number().int().positive().describe("Canvas width in px (default 1920).").optional(),height:d.number().int().positive().describe("Canvas height in px (default 1080).").optional(),duration:d.union([d.number().nonnegative(),d.literal("auto")]).describe('Total duration in seconds, or "auto" to fit the longest element (default "auto").').optional(),frame_rate:d.number().positive().describe("Frames per second (default 30).").optional(),background_color:d.string().describe('Canvas background color (default opaque black "#000000").').optional(),fonts:d.array(tx).describe("Custom font faces to register before rendering.").optional(),motion_blur:d.object({samples:d.number().int().min(1).max(32).describe("Sub-frame samples, 1-32 (default 8).").optional(),shutter:d.number().gt(0).max(1).describe("Shutter as a fraction of the frame interval, 0..1 (default 0.5).").optional()}).passthrough().optional(),camera:ix.describe("Scene camera (perspective + pose); omit for flat 2D.").optional(),lights:d.array(D_).describe("Scene lights for PBR materials; omit for unlit.").optional(),environment:N_.describe("Environment map for material reflections.").optional(),bloom:H_.describe("Post-process bloom (glow on bright areas).").optional(),elements:d.array(ex).min(1).describe("The scene content (at least one element); drawn by z-depth then layer order (layer 1 on top).")}).passthrough().superRefine((e,t)=>{Array.isArray(e.elements)&&Ua(e.elements,["elements"],t)});function Ba(e){let t=Math.imul(e>>>0,747796405)+2891336453>>>0,i=Math.imul((t>>>(t>>>28)+4^t)>>>0,277803737)>>>0;return(i>>>22^i)>>>0}function Ul(e,t){return Ba((e|0)>>>0^Ba(t>>>0))/4294967295}function Bl(e){return Ba(e>>>0)/4294967296}function br(e,t){let i=Math.floor(e),s=e-i,r=s*s*s*(s*(s*6-15)+10),n=Ul(i,t),a=Ul(i+1,t);return n+(a-n)*r}var Ml={PI:Math.PI,TAU:Math.PI*2,E:Math.E},rx=new Set(Ws.vars),zl={sin:e=>Math.sin(e[0]),cos:e=>Math.cos(e[0]),tan:e=>Math.tan(e[0]),asin:e=>Math.asin(e[0]),acos:e=>Math.acos(e[0]),atan:e=>Math.atan(e[0]),atan2:e=>Math.atan2(e[0],e[1]),sinh:e=>Math.sinh(e[0]),cosh:e=>Math.cosh(e[0]),tanh:e=>Math.tanh(e[0]),abs:e=>Math.abs(e[0]),sign:e=>Math.sign(e[0]),sqrt:e=>Math.sqrt(e[0]),cbrt:e=>Math.cbrt(e[0]),pow:e=>Math.pow(e[0],e[1]),exp:e=>Math.exp(e[0]),log:e=>Math.log(e[0]),log2:e=>Math.log2(e[0]),floor:e=>Math.floor(e[0]),ceil:e=>Math.ceil(e[0]),round:e=>Math.round(e[0]),trunc:e=>Math.trunc(e[0]),fract:e=>e[0]-Math.floor(e[0]),hypot:e=>Math.hypot(...e),min:e=>Math.min(...e),max:e=>Math.max(...e),mod:e=>(e[0]%e[1]+e[1])%e[1],clamp:e=>Math.min(Math.max(e[0],e[1]),e[2]),lerp:e=>e[0]+(e[1]-e[0])*e[2],mix:e=>e[0]+(e[1]-e[0])*e[2],step:e=>e[1]<e[0]?0:1,smoothstep:e=>{let t=Math.min(Math.max((e[2]-e[0])/(e[1]-e[0]),0),1);return t*t*(3-2*t)},linear:e=>{let t=Al((e[0]-e[1])/(e[2]-e[1]));return e[3]+(e[4]-e[3])*t},ease:e=>{let t=Al((e[0]-e[1])/(e[2]-e[1])),i=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;return e[3]+(e[4]-e[3])*i},noise:e=>2*br(e[0],e[1]??0)-1,wiggle:(e,t)=>(e[1]??0)*(2*br(t.t*(e[0]??0),e[2]??0)-1),random:e=>Bl(e[0]??0)},Al=e=>Math.min(Math.max(e,0),1);var nx=zl,Cl=Ml;function ax(e){let t=[],i=0;for(;i<e.length;){let s=e[i];if(s===" "||s===" "||s===\`
|
|
2007
|
+
\`||s==="\\r"){i++;continue}if(s>="0"&&s<="9"||s==="."&&/[0-9]/.test(e[i+1]??"")){let n=/^[0-9]*\\.?[0-9]+(?:[eE][+-]?[0-9]+)?/.exec(e.slice(i));if(!n)return null;t.push({t:"num",v:parseFloat(n[0])}),i+=n[0].length;continue}if(/[A-Za-z_]/.test(s)){let n=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(i));t.push({t:"id",v:n[0]}),i+=n[0].length;continue}let r=e.slice(i,i+2);if(["<=",">=","==","!=","&&","||"].includes(r)){t.push({t:"op",v:r}),i+=2;continue}if("+-*/%^()<>!?:,".includes(s)){t.push({t:"op",v:s}),i++;continue}return null}return t}var kn={"||":2,"&&":3,"==":4,"!=":4,"<":5,">":5,"<=":5,">=":5,"+":6,"-":6,"*":7,"/":7,"%":7,"^":9};function ox(e){let t=0,i=()=>e[t],s=()=>e[t++];function r(){let c=i();if(!c)return null;if(c.t==="num")return s(),{k:"num",v:c.v};if(c.t==="op"&&(c.v==="-"||c.v==="!")){s();let l=n();return l&&{k:"un",op:c.v,a:l}}if(c.t==="op"&&c.v==="("){s();let l=a(0);return!l||s()?.v!==")"?null:l}if(c.t==="id"){if(s(),i()?.t==="op"&&i()?.v==="("){s();let l=[];if(!(i()?.t==="op"&&i()?.v===")"))for(;;){let u=a(0);if(!u)return null;if(l.push(u),i()?.v===","){s();continue}break}return s()?.v!==")"||!(c.v in zl)?null:{k:"call",name:c.v,args:l}}return c.v in Ml||rx.has(c.v)?{k:"var",name:c.v}:null}return null}function n(){return r()}function a(c){let l=n();if(!l)return null;for(;;){let u=i();if(u?.t==="op"&&u.v==="?"){if(c>1)break;s();let p=a(0);if(!p||s()?.v!==":")return null;let m=a(1);if(!m)return null;l={k:"tern",c:l,a:p,b:m};continue}if(u?.t!=="op"||!(u.v in kn)||kn[u.v]<c)break;s();let h=u.v==="^"?kn[u.v]:kn[u.v]+1,f=a(h);if(!f)return null;l={k:"bin",op:u.v,a:l,b:f}}return l}let o=a(0);return o&&t===e.length?o:null}function ni(e,t){switch(e.k){case"num":return e.v;case"var":return e.name in Cl?Cl[e.name]:t[e.name];case"un":return e.op==="-"?-ni(e.a,t):ni(e.a,t)===0?1:0;case"tern":return ni(e.c,t)!==0?ni(e.a,t):ni(e.b,t);case"call":return nx[e.name](e.args.map(i=>ni(i,t)),t);case"bin":{let i=ni(e.a,t);if(e.op==="&&")return i!==0&&ni(e.b,t)!==0?1:0;if(e.op==="||")return i!==0||ni(e.b,t)!==0?1:0;let s=ni(e.b,t);switch(e.op){case"+":return i+s;case"-":return i-s;case"*":return i*s;case"/":return i/s;case"%":return i%s;case"^":return Math.pow(i,s);case"<":return i<s?1:0;case">":return i>s?1:0;case"<=":return i<=s?1:0;case">=":return i>=s?1:0;case"==":return i===s?1:0;case"!=":return i!==s?1:0}return NaN}}}var Aa=new Map;function Pl(e){if(Aa.has(e))return Aa.get(e);let t=ax(e),i=t?ox(t):null;return Aa.set(e,i),i}function ai(e){return typeof e=="object"&&e!==null&&typeof e.expr=="string"}function oi(e,t){let i=Pl(e.expr);if(!i)return t.value;let s=ni(i,t);return Number.isFinite(s)?s:t.value}var Jt=64;function cx(e){return Array.isArray(e)&&(e.length===2||e.length===3)&&e.every(t=>typeof t=="number")}function Vi(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);return Number.isFinite(i)?i:t}return t}function Il(e,t,i,s,r){let n=1-r,a=n*n*n,o=3*n*n*r,c=3*n*r*r,l=r*r*r;return[a*e[0]+o*t[0]+c*i[0]+l*s[0],a*e[1]+o*t[1]+c*i[1]+l*s[1]]}function lx(e,t,i,s,r){let n=1-r,a=3*n*n,o=6*n*r,c=3*r*r;return[a*(t[0]-e[0])+o*(i[0]-t[0])+c*(s[0]-i[0]),a*(t[1]-e[1])+o*(i[1]-t[1])+c*(s[1]-i[1])]}function dx(e,t){let i=e.value,s=t.value,r=e.out_tangent?[i[0]+e.out_tangent[0],i[1]+e.out_tangent[1]]:[i[0]+(s[0]-i[0])/3,i[1]+(s[1]-i[1])/3],n=t.in_tangent?[s[0]+t.in_tangent[0],s[1]+t.in_tangent[1]]:[s[0]-(s[0]-i[0])/3,s[1]-(s[1]-i[1])/3];return[i,r,n,s]}function Ca(e,t,i){let[s,r,n,a]=dx(e,t),o=new Float64Array(Jt+1),c=s;for(let g=1;g<=Jt;g++){let y=Il(s,r,n,a,g/Jt);o[g]=o[g-1]+Math.hypot(y[0]-c[0],y[1]-c[1]),c=y}let l=o[Jt],u;if(l<=0)u=i;else{let g=i*l,y=1;for(;y<Jt&&o[y]<g;)y++;let w=o[y-1],x=o[y],b=x>w?(g-w)/(x-w):0;u=(y-1+b)/Jt}let h=Il(s,r,n,a,u),[f,p]=lx(s,r,n,a,u);f===0&&p===0&&(f=a[0]-s[0],p=a[1]-s[1]);let m=Math.atan2(p,f)*180/Math.PI;return{point:h,angle:m}}function Tn(e){return[e[0],e[1],e.length===3?e[2]:0]}function Rl(e,t,i,s,r){let n=1-r,a=n*n*n,o=3*n*n*r,c=3*n*r*r,l=r*r*r;return[a*e[0]+o*t[0]+c*i[0]+l*s[0],a*e[1]+o*t[1]+c*i[1]+l*s[1],a*e[2]+o*t[2]+c*i[2]+l*s[2]]}function ux(e,t,i,s,r){let n=1-r,a=3*n*n,o=6*n*r,c=3*r*r;return[a*(t[0]-e[0])+o*(i[0]-t[0])+c*(s[0]-i[0]),a*(t[1]-e[1])+o*(i[1]-t[1])+c*(s[1]-i[1]),a*(t[2]-e[2])+o*(i[2]-t[2])+c*(s[2]-i[2])]}function hx(e,t){let i=Tn(e.value),s=Tn(t.value),r=e.out_tangent,n=r?[i[0]+r[0],i[1]+r[1],r.length===3?i[2]+r[2]:i[2]+(s[2]-i[2])/3]:[i[0]+(s[0]-i[0])/3,i[1]+(s[1]-i[1])/3,i[2]+(s[2]-i[2])/3],a=t.in_tangent,o=a?[s[0]+a[0],s[1]+a[1],a.length===3?s[2]+a[2]:s[2]-(s[2]-i[2])/3]:[s[0]-(s[0]-i[0])/3,s[1]-(s[1]-i[1])/3,s[2]-(s[2]-i[2])/3];return[i,n,o,s]}function Ma(e,t,i){let[s,r,n,a]=hx(e,t),o=new Float64Array(Jt+1),c=s;for(let g=1;g<=Jt;g++){let y=Rl(s,r,n,a,g/Jt);o[g]=o[g-1]+Math.hypot(y[0]-c[0],y[1]-c[1],y[2]-c[2]),c=y}let l=o[Jt],u;if(l<=0)u=i;else{let g=i*l,y=1;for(;y<Jt&&o[y]<g;)y++;let w=o[y-1],x=o[y],b=x>w?(g-w)/(x-w):0;u=(y-1+b)/Jt}let h=Rl(s,r,n,a,u),[f,p]=ux(s,r,n,a,u);f===0&&p===0&&(f=a[0]-s[0],p=a[1]-s[1]);let m=Math.atan2(p,f)*180/Math.PI;return{point:h,angle:m}}function Fl(e,t){let i=e.keyframe_animations;if(!i)return null;let s=i.find(l=>l.property==="position");if(!s)return null;let r=s.keyframes.filter(l=>cx(l.value));if(r.length===0)return null;let n=s.auto_orient===!0;if(r.some(l=>l.value.length===3))return fx(r,s,t,n);if(r.length===1){let l=r[0].value;return{x:l[0],y:l[1],z:null,angle:0,autoOrient:n}}let a=r[0],o=r[r.length-1];if(t<=Vi(a.time,0)){let{point:l,angle:u}=Ca(a,r[1],0);return{x:l[0],y:l[1],z:null,angle:u,autoOrient:n}}if(t>=Vi(o.time,0)){let{point:l,angle:u}=Ca(r[r.length-2],o,1);return{x:l[0],y:l[1],z:null,angle:u,autoOrient:n}}for(let l=0;l<r.length-1;l++){let u=r[l],h=r[l+1],f=Vi(u.time,0),p=Vi(h.time,0);if(t>=f&&t<=p){let m=p-f,g=m>0?(t-f)/m:0,y=yt(h.easing,g),{point:w,angle:x}=Ca(u,h,y);return{x:w[0],y:w[1],z:null,angle:x,autoOrient:n}}}let c=o.value;return{x:c[0],y:c[1],z:null,angle:0,autoOrient:n}}function fx(e,t,i,s){if(e.length===1){let o=Tn(e[0].value);return{x:o[0],y:o[1],z:o[2],angle:0,autoOrient:s}}let r=e[0],n=e[e.length-1];if(i<=Vi(r.time,0)){let{point:o,angle:c}=Ma(r,e[1],0);return{x:o[0],y:o[1],z:o[2],angle:c,autoOrient:s}}if(i>=Vi(n.time,0)){let{point:o,angle:c}=Ma(e[e.length-2],n,1);return{x:o[0],y:o[1],z:o[2],angle:c,autoOrient:s}}for(let o=0;o<e.length-1;o++){let c=e[o],l=e[o+1],u=Vi(c.time,0),h=Vi(l.time,0);if(i>=u&&i<=h){let f=h-u,p=f>0?(i-u)/f:0,m=yt(l.easing,p),{point:g,angle:y}=Ma(c,l,m);return{x:g[0],y:g[1],z:g[2],angle:y,autoOrient:s}}}let a=Tn(n.value);return{x:a[0],y:a[1],z:a[2],angle:0,autoOrient:s}}var Ol="ease-out",px={"fade-in":[{property:"opacity",fromDelta:0,toDelta:1,relative:!1}],"fade-out":[{property:"opacity",fromDelta:1,toDelta:0,relative:!1}],"slide-left-in":[{property:"x",fromDelta:-200,toDelta:0,relative:!0}],"slide-right-in":[{property:"x",fromDelta:200,toDelta:0,relative:!0}],"slide-up-in":[{property:"y",fromDelta:200,toDelta:0,relative:!0}],"slide-down-in":[{property:"y",fromDelta:-200,toDelta:0,relative:!0}],"slide-left-out":[{property:"x",fromDelta:0,toDelta:-200,relative:!0}],"slide-right-out":[{property:"x",fromDelta:0,toDelta:200,relative:!0}],"slide-up-out":[{property:"y",fromDelta:0,toDelta:-200,relative:!0}],"slide-down-out":[{property:"y",fromDelta:0,toDelta:200,relative:!0}],"scale-in":[{property:"scale",fromDelta:0,toDelta:1,relative:!1}],"scale-out":[{property:"scale",fromDelta:1,toDelta:0,relative:!1}],"rotate-in":[{property:"rotation",fromDelta:-90,toDelta:0,relative:!0}],"rotate-out":[{property:"rotation",fromDelta:0,toDelta:90,relative:!0}],"bounce-in":[{property:"scale",fromDelta:0,toDelta:1,relative:!1,defaultEasing:"ease-out-back"}],"bounce-out":[{property:"scale",fromDelta:1,toDelta:0,relative:!1,defaultEasing:"ease-in-back"}]},mx=new Set(["spin","shake","wiggle","pan","drift","breathe","orbit"]);function Dl(e,t){let s=mx.has(e.type)&&e.duration==null&&e.time==null?t:e.duration??.5,r=e.easing??Ol,n;e.time==="start"||e.time==null?n=0:e.time==="end"?n=Math.max(0,t-s):n=e.time;let a=gx(e,n,s);if(a)return a;let o=px[e.type];if(!o)return[];let c=e.type.endsWith("-in");return o.map(l=>({property:l.property,startTime:n,duration:s,from:l.fromDelta,to:l.toDelta,easing:l.defaultEasing??r,relative:l.relative,fillBackwards:c}))}function Ll(e){switch(e){case"left":return{property:"x",sign:-1};case"up":return{property:"y",sign:-1};case"down":return{property:"y",sign:1};case"right":default:return{property:"x",sign:1}}}function gx(e,t,i){let s=e.easing??"linear";switch(e.type){case"spin":{let r=e.rotation??360;return[{property:"rotation",startTime:t,duration:i,from:0,to:r,easing:s,relative:!0}]}case"shake":{let r=e.distance??24;return[{property:"x",startTime:t,duration:i,from:r,to:0,easing:s,relative:!0,oscillate:{frequency:e.frequency??8}}]}case"wiggle":{let r=e.rotation??8;return[{property:"rotation",startTime:t,duration:i,from:r,to:r,easing:s,relative:!0,oscillate:{frequency:e.frequency??2}}]}case"drift":{let r=e.distance??30,n=e.frequency??.5,a=Math.max(0,Math.round(e.seed??0));return[{property:"x",startTime:t,duration:i,from:r,to:r,easing:"linear",relative:!0,oscillate:{frequency:n,noise:{seed:a}}},{property:"y",startTime:t,duration:i,from:r,to:r,easing:"linear",relative:!0,oscillate:{frequency:n,noise:{seed:a+7919}}}]}case"breathe":{let r=e.scale??.05;return[{property:"scale",startTime:t,duration:i,from:r,to:r,easing:"linear",relative:!0,oscillate:{frequency:e.frequency??.4}}]}case"orbit":{let r=e.distance??40,n=e.frequency??.5,a=e.direction==="left";return[{property:"x",startTime:t,duration:i,from:r,to:r,easing:"linear",relative:!0,oscillate:{frequency:n,phase:Math.PI/2}},{property:"y",startTime:t,duration:i,from:a?-r:r,to:a?-r:r,easing:"linear",relative:!0,oscillate:{frequency:n}}]}case"squash":{let r=e.scale??.3,n=i/2,a=t+n,o=r*.6;return[{property:"y_scale",startTime:t,duration:n,from:1,to:1-r,easing:"ease-in-quad",relative:!1},{property:"y_scale",startTime:a,duration:n,from:1-r,to:1,easing:"ease-out-back",relative:!1},{property:"x_scale",startTime:t,duration:n,from:1,to:1+o,easing:"ease-in-quad",relative:!1},{property:"x_scale",startTime:a,duration:n,from:1+o,to:1,easing:"ease-out-back",relative:!1}]}case"pan":{let r=e.distance??200,{property:n,sign:a}=Ll(e.direction);return[{property:n,startTime:t,duration:i,from:-r/2*a,to:r/2*a,easing:s,relative:!0}]}case"shift":{let r=e.distance??200,{property:n,sign:a}=Ll(e.direction);return[{property:n,startTime:t,duration:i,from:0,to:r*a,easing:e.easing??Ol,relative:!0,hold:!0}]}default:return null}}function M(e,t,i,s){let r=s.timeOffset+En(e.time),n=xx(e.duration,s.sourceDuration-r),a=Math.min(s.time-r,n);if(t==="x"||t==="y"||t==="z"||t==="rotation"){let o=Fl(e,a);if(o){if(t==="x")return o.x;if(t==="y")return o.y;if(t==="z"&&o.z!==null)return o.z;if(t==="rotation"&&o.autoOrient)return Nl(e,"rotation",i,a,n)+o.angle}}return Nl(e,t,i,a,n)}function Nl(e,t,i,s,r){let n=e[t]??(t==="rotation"?e.z_rotation:void 0);if(ai(n))return oi(n,{t:s,dur:r,i:0,n:1,value:i});let a=e.keyframe_animations;if(a){for(let c of a)if(c.property===t||t==="rotation"&&c.property==="z_rotation")return Ze(c.keyframes,pa(c.keyframes,c.loop,s))}let o=e.animations;if(o&&o.length>0){let c=i,l=!1;for(let u of o){let h=Dl(u,r);for(let f of h){if(f.property!==t)continue;let p=f.startTime+f.duration;if(s<f.startTime){if(!f.fillBackwards)continue;c=f.relative?i+f.from:f.from,l=!0;continue}if(s>p&&!f.hold)continue;let m=f.duration>0?Math.min(1,(s-f.startTime)/f.duration):1,g=yt(f.easing,m),y=f.from+(f.to-f.from)*g;if(f.oscillate){let w=s-f.startTime;y*=f.oscillate.noise?(br(f.oscillate.frequency*w,f.oscillate.noise.seed)-.5)*2:Math.sin(2*Math.PI*f.oscillate.frequency*w+(f.oscillate.phase??0))}c=f.relative?i+y:y,l=!0}}if(l)return c}return i}function Xe(e,t){let i=e;return i.x_rotation!==void 0||i.y_rotation!==void 0||i.z!==void 0||e.keyframe_animations?.some(r=>r.property==="x_rotation"||r.property==="y_rotation"||r.property==="z"||r.property==="position"&&r.keyframes.some(n=>Array.isArray(n.value)&&n.value.length===3))?{xRot:M(e,"x_rotation",za(i.x_rotation),t),yRot:M(e,"y_rotation",za(i.y_rotation),t),z:M(e,"z",za(i.z),t)}:null}function za(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function _x(e,t){let i=t.modelMatrix.e,s=M(e,"x",R(e.x,t.canvas.width,t.canvas),t),r=M(e,"y",R(e.y,t.canvas.height,t.canvas),t),n=Xe(e,t)?.z??0;return i[2]*s+i[6]*r+i[10]*n+i[14]}function Un(e,t){return e.map((i,s)=>({el:i,i:s,z:_x(i,t)})).sort((i,s)=>i.z-s.z||i.i-s.i).map(i=>i.el)}function Ut(e,t){let i=M(e,"scale",Pa(e.scale,1),t),s=M(e,"x_scale",Pa(e.x_scale,1),t),r=M(e,"y_scale",Pa(e.y_scale,1),t);return{sx:i*s,sy:i*r}}function mi(e,t,i){let s=e.aspect_ratio;return typeof s!="number"||!(s>0)?{width:t,height:i}:e.width!==void 0&&e.height===void 0?{width:t,height:t/s}:e.height!==void 0&&e.width===void 0?{width:i*s,height:i}:{width:t,height:i}}function vr(e,t,i,s){let r=e.keyframe_animations;if(r){for(let n of r)if(n.property===t&&Zc(n.keyframes)){let a=s.timeOffset+En(e.time),o=pa(n.keyframes,n.loop,s.time-a);return Yc(Xc(n.keyframes,o))}}return i}function ei(e,t){return{skewX:M(e,"x_skew",En(e.x_skew),t),skewY:M(e,"y_skew",En(e.y_skew),t)}}function Pa(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return e.trim().endsWith("%")?i/100:i}return t}function En(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=parseFloat(e);return Number.isFinite(t)?t:0}return 0}function xx(e,t){if(e==="auto"||e==="end"||e==null)return t;if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);return Number.isFinite(i)?i:t}return t}var yx=new Set(["text-appear","text-slide","text-fly","text-typewriter","text-wave","text-flip"]);var bx={opacity:1,dx:0,dy:0};function Ia(e){return e.some(t=>t.type==="text-flip")}function Ra(e){let t=e.animations;if(!t||t.length===0)return null;let i=null;for(let s of t){if(!yx.has(s.type)||s.time==="end")continue;let r=s.split??vx(s.type);(i??=[]).push({type:s.type,split:r,stagger:s.stagger??(r==="word"?.09:.035),duration:s.duration??.5,startTime:typeof s.time=="number"?s.time:0,distance:s.distance??(s.type==="text-fly"?140:s.type==="text-wave"?12:40),direction:s.direction??"up",frequency:s.frequency??1.5,easing:s.easing,axis:s.axis??"x",angle:s.rotation??90})}return i}function vx(e){return e==="text-typewriter"||e==="text-wave"||e==="text-flip"?"letter":"word"}function Fa(e,t,i,s){let r=1,n=0,a=0,o;for(let c of e){let l=c.split==="word"?s:i;if(c.type==="text-wave"){let p=t-c.startTime;if(p<0)continue;a+=Math.sin(2*Math.PI*c.frequency*p-l*.6)*c.distance;continue}let u=c.startTime+l*c.stagger;if(c.type==="text-typewriter"){t<u&&(r=0);continue}let h=c.duration>0?Math.max(0,Math.min(1,(t-u)/c.duration)):t>=u?1:0,f=yt(c.easing??(c.type==="text-fly"?"ease-out-back":"ease-out-cubic"),h);if(r*=Math.max(0,Math.min(1,f)),c.type==="text-flip"){let p=c.angle*(1-f);if(p!==0){o??={};let m=o[c.split]??=[0,0,0];m[c.axis==="x"?0:c.axis==="y"?1:2]+=p}continue}if(c.type==="text-slide"||c.type==="text-fly"){let p=(1-f)*c.distance;switch(c.direction){case"up":a+=p;break;case"down":a-=p;break;case"left":n+=p;break;case"right":n-=p;break}}}return r===1&&n===0&&a===0&&!o?bx:{opacity:r,dx:n,dy:a,flips:o}}var qs=" !\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~\\xA0\\xA2\\xA3\\xA5\\xA6\\xA7\\xA9\\xAB\\xAE\\xB0\\xB1\\xB7\\xBB\\xBF\\xD7\\xF7\\u2013\\u2014\\u2018\\u2019\\u201C\\u201D\\u201E\\u2020\\u2021\\u2022\\u2026\\u2030\\u2032\\u2033\\u203A\\u2039\\u20AC\\u2122\\u2190\\u2191\\u2192\\u2193";function wr(e){return\`\${e.family}|\${e.size}|\${e.weight}\`}function Sr(e,t){let{family:i,size:s,weight:r}=e,n=typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas"),a=n.getContext("2d",{willReadFrequently:!1});if(!a)throw new Error("Failed to acquire 2D context for font atlas");let o=\`\${r} \${s}px \${i}\`;a.font=o,a.textBaseline="alphabetic",a.textAlign="left";let c=a.measureText("Mg"),l=Math.max(s*.6,c.actualBoundingBoxAscent||s*.8),u=Math.max(s*.15,c.actualBoundingBoxDescent||s*.2),h=Math.max(s*.6,c.fontBoundingBoxAscent||c.actualBoundingBoxAscent||s*.8),f=Math.max(s*.1,c.fontBoundingBoxDescent||c.actualBoundingBoxDescent||s*.2);if(typeof document<"u"&&document.body){let D=document.createElement("div");D.style.cssText=\`position:absolute;visibility:hidden;left:-9999px;top:0;white-space:nowrap;font:\${o};line-height:\${s}px;\`,D.textContent="Hg";let z=document.createElement("span");z.style.cssText="display:inline-block;width:0;height:0;",D.appendChild(z),document.body.appendChild(D);let L=z.offsetTop+z.offsetHeight;D.remove(),L>0&&L<s*2&&(h=L,f=s-L)}let p=new Map,m=0;for(let D of qs){let z=a.measureText(D),L=z.width,re=z.actualBoundingBoxLeft||0,te=z.actualBoundingBoxRight||L,K=z.actualBoundingBoxAscent||l,q=z.actualBoundingBoxDescent||u,V=Math.ceil(Math.max(L,re+te));p.set(D,{width:V,advance:L,aLeft:re,aRight:te,aAscent:K,aDescent:q}),V>m&&(m=V),K>l&&(l=K),q>u&&(u=q)}let g=4,y=Math.ceil(m+2*g),w=Math.ceil(l+u+2*g),x=Math.ceil(Math.sqrt(qs.length)),b=Math.ceil(qs.length/x),S=x*y,v=b*w,T=t.capabilities.maxTextureSize;if(S>T||v>T)throw new Error(\`Font atlas for \${i} \${s}px \${r} (\${S}\\xD7\${v}) exceeds backend max texture dimension \${T}.\`);n.width=S,n.height=v,a.font=o,a.textBaseline="alphabetic",a.textAlign="left",a.fillStyle="#ffffff",a.clearRect(0,0,S,v);let C=2,P=new Map;for(let D=0;D<qs.length;D++){let z=qs[D],L=D%x,re=Math.floor(D/x),te=L*y,K=re*w,q=K+g+l,V=te+g;a.fillText(z,V,q);let ie=p.get(z),pe=Math.floor(V-ie.aLeft)-C,Le=Math.ceil(V+ie.aRight)+C,Ke=Math.floor(q-ie.aAscent)-C,Se=Math.ceil(q+ie.aDescent)+C;pe=Math.max(te,pe),Le=Math.min(te+y,Le),Ke=Math.max(K,Ke),Se=Math.min(K+w,Se);let He=Math.max(0,Le-pe),me=Math.max(0,Se-Ke);P.set(z,{x:pe,y:Ke,width:He,height:me,advance:ie.advance,offsetX:pe-V,offsetY:Ke-q})}$().debug(\`Generated font atlas: \${i} \${s}px \${r} (\${S}\\xD7\${v}, \${qs.length} glyphs)\`);let E=t.createTexture(n),H=(typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")).getContext("2d");H.font=o;let Q=new Map;return{family:i,size:s,weight:r,texture:E,width:S,height:v,glyphs:P,ascent:h,descent:f,lineHeight:w,kern:(D,z)=>{if(D===""||z==="")return 0;let L=D+z,re=Q.get(L);if(re===void 0){let te=p.get(D),K=p.get(z);!te||!K?re=0:(H.font!==o&&(H.font=o),re=H.measureText(L).width-te.advance-K.advance),Q.set(L,re)}return re}}}var wx=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-sans-serif","ui-serif","ui-monospace","ui-rounded"]);function kr(e){let t=e.trim();return t.includes(",")||wx.has(t.toLowerCase())?t:\`\${t}, sans-serif\`}var js=null;function Sx(){if(js)return js;if(typeof OffscreenCanvas<"u")return js=new OffscreenCanvas(1,1).getContext("2d"),js;if(typeof document>"u")return null;let e=document.createElement("canvas");return e.width=1,e.height=1,js=e.getContext("2d"),js}var Bn=100,Hl=8,Gl=1e3;function kx(e,t,i){let s=Sx();return s?(s.font=\`\${i} \${Bn}px \${t}\`,s.measureText(e).width):Bn*.5}function La(e,t,i,s){let r=0;for(let n of e){let a=s.get(n);a===void 0&&(a=kx(n,t,i),s.set(n,a)),r+=a}return r}function Tr(e,t,i,s,r=48,n=Hl,a=Gl){if(!e||s<=0)return r;let o=La(e,t,i,new Map);if(o<=0)return r;let c=Bn*(s/o);return Math.max(n,Math.min(c,a))}function Vl(e,t,i,s,r,n,a=Hl,o=Gl){if(!e||s<=0||r<=0)return a;let c=new Map,l=La(" ",t,i,c),u=e.split(\`
|
|
2008
|
+
\`).map(m=>m.split(" ").map(g=>La(g,t,i,c))),h=m=>{let g=m/Bn,y=0;for(let w of u){let x=0,b=!1;for(let S of w){let v=S*g;if(v>s)return!1;let T=b?x+l*g+v:v;b&&T>s?(y+=1,x=v):(x=T,b=!0)}y+=1}return y*m*n<=r};if(!h(a))return a;let f=a,p=o;for(let m=0;m<24;m++){let g=(f+p)/2;h(g)?f=g:p=g}return Math.floor(f*10)/10}function Cn(e){let t=e[3];return t<=.001?1:1.6-.75*Math.min(1,Math.max(0,(.2126*e[0]+.7152*e[1]+.0722*e[2])/t))}function jl(e,t){if(e.mask){Cx(e,t);return}if(e.spans&&e.spans.length>0){Tx(e,t);return}let{canvas:i,backend:s}=t,r=t.timeOffset+Ge(e.time,0),n=t.time-r,a=Yl(e,n);if(a.length===0)return;let o=kr(String(e.font_family??"sans-serif")),c=e.font_weight??"normal",l;if(e.font_size==="auto"){let Ee=(e.width!==void 0?R(e.width,i.width,i,i.width):i.width)-2*R(e.x_padding,i.width,i,0),ge=R(e.font_size_minimum,i.height,i,8),Y=R(e.font_size_maximum,i.height,i,400);if(e.height!==void 0){let oe=R(e.height,i.height,i,0)-2*R(e.y_padding,i.height,i,0);l=Vl(a,o,c,Math.max(1,Ee),Math.max(1,oe),Ge(e.line_height,1),ge,Y)}else l=Tr(a,o,c,Math.max(1,Ee),48,ge,Y)}else typeof e.font_size=="number"?l=e.font_size:typeof e.font_size=="string"?l=R(e.font_size,i.height,i,48):l=48;let u=wr({family:o,size:l,weight:c}),h;t.fontAtlases.has(u)?h=t.fontAtlases.get(u):(h=Sr({family:o,size:l,weight:c},s),t.fontAtlases.set(u,h));let f=M(e,"x",R(e.x,i.width,i),t),p=M(e,"y",R(e.y,i.height,i),t),m=M(e,"rotation",Ge(e.rotation??e.z_rotation,0),t),g=M(e,"opacity",Ge(e.opacity,1),t),{sx:y,sy:w}=Ut(e,t),{skewX:x,skewY:b}=ei(e,t),S=Math.tan(x*Math.PI/180),v=Math.tan(b*Math.PI/180),T=Ie(e.x_anchor),C=Ie(e.y_anchor),P=Ra(e),E=P!==null&&Ia(P),U=Xe(e,t),H=U!==null||!t.modelMatrix.aff||E,Q,J,D,z=null;H?(z=Qe(t.modelMatrix,ki(f,p,U?.z??0,m,U?.yRot??0,U?.xRot??0)),Q=f,J=p,D=0):([Q,J]=Fi(t.modelMatrix,f,p),D=m+Li(t.modelMatrix));let L=g*t.opacityFactor,re=R(e.x_padding,i.width,i,0),te=R(e.y_padding,i.height,i,0),K=Ge(e.letter_spacing,0),q=Ee=>{let ge=0,Y="";for(let oe of Ee){let j=h.glyphs.get(oe);j&&(ge+=j.advance+K+h.kern(Y,oe),Y=oe)}return ge},V=typeof e.width=="number"?e.width:typeof e.width=="string"?R(e.width,i.width,i,Number.NaN):Number.NaN,ie=Number.isFinite(V)?Math.max(0,V-2*re):Number.POSITIVE_INFINITY,pe=e.font_size==="auto"&&e.height!==void 0,Le=e.text_wrap!==!1&&(e.font_size!=="auto"||pe)&&Number.isFinite(ie),Ke=.5,Se=[];for(let Ee of a.split(\`
|
|
2009
|
+
\`)){if(!Le||q(Ee)<=ie+Ke){Se.push(Ee);continue}let ge="";for(let Y of Ee.split(" ")){let oe=ge.length>0?\`\${ge} \${Y}\`:Y;ge.length>0&&q(oe)>ie+Ke?(Se.push(ge),ge=Y):ge=oe}ge.length>0&&Se.push(ge)}let He=Se.map(q),me=He.length>0?Math.max(...He):0,Ye=h.ascent+h.descent,dt=Ge(e.line_height,1),st=l*dt,Lt=(st-Ye)/2,Mi=Number.isFinite(V)?V:me+2*re,At=Math.max(0,Mi-2*re),Wt=e.text_align??"left",ii=Mn(e.x_alignment,Wt==="center"?.5:Wt==="right"?1:0),qt=st*Se.length,jt=qt+2*te;typeof e.height=="number"?jt=e.height:typeof e.height=="string"&&(jt=R(e.height,i.height,i,jt));let ae=e.vertical_align??"top",ye=Mn(e.y_alignment,ae==="middle"?.5:ae==="bottom"?1:0),We=Math.max(0,jt-2*te-qt),Oe=Q-Mi*T+re,Me=J-jt*C+te+We*ye,qe=ft(vr(e,"fill_color",typeof e.fill_color=="string"?e.fill_color:"#ffffff",t)),Te=Math.max(0,Math.min(1,L)),De=[qe[0]*Te,qe[1]*Te,qe[2]*Te,qe[3]*Te],Re=D*Math.PI/180,gt=Math.cos(Re),ci=Math.sin(Re),ne=D!==0,rt=(Ee,ge)=>{let Y=(Ee-Q)*y,oe=(ge-J)*w,j=Y+S*oe,ue=oe+v*Y;return ne?[Q+j*gt-ue*ci,J+j*ci+ue*gt]:[Q+j,J+ue]},Je=t.time-(t.timeOffset+Ge(e.time,0)),ut=null,nt=null;if(E){ut=[];let Ee=[],ge=0,Y=0,oe=!1;for(let j=0;j<Se.length;j++){let ue=Oe+Math.max(0,At-He[j])*ii,Ne=Me+j*st+Lt+h.ascent,X="";for(let _t of Se[j]){let _e=/\\s/.test(_t);_e&&oe?(Y+=1,oe=!1):_e||(oe=!0);let Fe=h.glyphs.get(_t);if(!Fe)continue;if(ue+=h.kern(X,_t),X=_t,Fe.width===0||Fe.height===0){ue+=Fe.advance+K;continue}let le=ue+Fe.offsetX,Ct=Ne+Fe.offsetY;ut[ge]=[le+Fe.width/2,Ct+Fe.height/2];let ve=Ee[Y]??={l:1/0,r:-1/0,t:1/0,b:-1/0};ve.l=Math.min(ve.l,le),ve.r=Math.max(ve.r,le+Fe.width),ve.t=Math.min(ve.t,Ct),ve.b=Math.max(ve.b,Ct+Fe.height),ge+=1,ue+=Fe.advance+K}oe&&(Y+=1,oe=!1)}nt=Ee.map(j=>[(j.l+j.r)/2,(j.t+j.b)/2])}if(typeof e.background_color=="string"&&me>0&&Se.length>0){let Ee=(()=>{let j=ft(e.background_color);return[j[0]*Te,j[1]*Te,j[2]*Te,j[3]*Te]})(),[ge,Y]=$l(e.background_padding),oe=Ge(e.background_border_radius,0);for(let j=0;j<Se.length;j++){let ue=He[j];if(ue<=0)continue;let X=Oe+Math.max(0,At-ue)*ii+ue/2,_t=Me+j*st+Lt+Ye/2,[_e,Fe]=rt(X,_t),le=(ue+2*ge)*y,Ct=(Ye+2*Y)*w;s.drawShape({cx:_e,cy:Fe,width:le,height:Ct,rotation:D,skewX:x,skewY:b,transform:z?ze(z,_e,Fe,le,Ct,0,x,b,null):void 0,color:Ee,cornerRadius:oe,shape:"rectangle",blend:e.blend_mode})}}let Pe=zn(e.text_shadow,Te),wt=Pe.length>0?2:1,ht=0,at=0,et=!1;for(let Ee=0;Ee<wt;Ee++){let ge=Pe.length>0&&Ee===0,Y=Pe.length===0||Ee===1;ht=0,at=0,et=!1;for(let oe=0;oe<Se.length;oe++){let j=Se[oe],ue=Math.max(0,At-He[oe]),Ne=Oe+ue*ii,X=Me+oe*st+Lt+h.ascent,_t="";for(let _e of j){let Fe=/\\s/.test(_e);Fe&&et?(at+=1,et=!1):Fe||(et=!0);let le=h.glyphs.get(_e);if(!le)continue;if(Ne+=h.kern(_t,_e),_t=_e,le.width===0||le.height===0){Ne+=le.advance+K;continue}let Ct=ht,ve=P?Fa(P,Je,ht,at):null;if(ht+=1,ve&&ve.opacity<=0){Ne+=le.advance+K;continue}let Ot=z;if(Ot&&ve?.flips){let cr=(Bs,As)=>{if(!Bs||!As)return;let[Jn,Nr]=rt(Bs[0]+ve.dx,Bs[1]+ve.dy);Ot=Qe(Ot,ki(Jn,Nr,0,As[2],As[1],As[0]))};cr(nt?.[at],ve.flips.word),cr(ut?.[Ct],ve.flips.letter)}let ir=Ne+le.offsetX+(ve?ve.dx:0),sr=X+le.offsetY+(ve?ve.dy:0),rr=(ir+le.width/2-Q)*y,nr=(sr+le.height/2-J)*w,Es=rr+S*nr,vi=nr+v*rr,$t=Q+Es,Yt=J+vi;ne&&($t=Q+Es*gt-vi*ci,Yt=J+Es*ci+vi*gt),!Ot&&D===0&&x===0&&b===0&&y===1&&w===1&&!ve&&($t=Math.round($t-le.width/2)+le.width/2,Yt=Math.round(Yt-le.height/2)+le.height/2);let Us=le.x/h.width,$i=le.y/h.height,ar=(le.x+le.width)/h.width,or=(le.y+le.height)/h.height,yo=ve&&ve.opacity<1?[De[0]*ve.opacity,De[1]*ve.opacity,De[2]*ve.opacity,De[3]*ve.opacity]:De;if(ge){let cr=le.width*y,Bs=le.height*w;Pn(Pe,ve&&ve.opacity<1?ve.opacity:1,(As,Jn,Nr)=>{let[bo,vo]=rt(ir+As+le.width/2,sr+Jn+le.height/2);s.drawTexturedQuad({cx:bo,cy:vo,width:cr,height:Bs,rotation:D,skewX:x,skewY:b,transform:Ot?ze(Ot,bo,vo,cr,Bs,0,x,b,null):void 0,texture:h.texture,uvRect:[Us,$i,ar,or],tint:Nr,blend:e.blend_mode,alphaGamma:Cn(Nr)})})}Y&&s.drawTexturedQuad({cx:$t,cy:Yt,width:le.width*y,height:le.height*w,rotation:D,skewX:x,skewY:b,transform:Ot?ze(Ot,$t,Yt,le.width*y,le.height*w,0,x,b,null):void 0,texture:h.texture,uvRect:[Us,$i,ar,or],tint:yo,blend:e.blend_mode,alphaGamma:Cn(yo)}),Ne+=le.advance+K}et&&(at+=1,et=!1)}}}function Tx(e,t){let{canvas:i,backend:s}=t,r=t.timeOffset+Ge(e.time,0),n=t.time-r,a=String(e.font_family??"sans-serif"),o=e.font_weight??"normal",c=Bx(e,t),l=typeof e.fill_color=="string"?e.fill_color:"#ffffff",u=e.text_align??"left",h=[],f={spans:[],width:0,ascent:0,descent:0},p=e.text_transform;for(let ne of e.spans){if(ne.text===\`
|
|
2010
|
+
\`){h.push(f),f={spans:[],width:0,ascent:0,descent:0};continue}let rt=p&&p!=="none"?{...ne,text:Xl(ne.text,p)}:ne,Je=Ux(rt,{family:a,size:c,weight:o,color:l,letterSpacing:Ge(e.letter_spacing,0)},t);f.spans.push(Je),f.width+=Je.width,f.ascent=Math.max(f.ascent,Je.atlas.ascent),f.descent=Math.max(f.descent,Je.atlas.descent)}h.push(f);let m=typeof e.width=="number"?e.width:typeof e.width=="string"?R(e.width,i.width,i,1/0):1/0,g=!0,y=[];for(let ne of h)g||ne.width<=m||!Number.isFinite(m)?y.push(ne):y.push(...Ex(ne,m));let w=Ge(e.line_height,1),x=0,b=0;for(let ne of y){x=Math.max(x,ne.width);let rt=c*w;b+=rt}let S=M(e,"x",R(e.x,i.width,i),t),v=M(e,"y",R(e.y,i.height,i),t),T=M(e,"rotation",Ge(e.rotation??e.z_rotation,0),t),C=M(e,"opacity",Ge(e.opacity,1),t),{sx:P,sy:E}=Ut(e,t),{skewX:U,skewY:H}=ei(e,t),Q=Math.tan(U*Math.PI/180),J=Math.tan(H*Math.PI/180),D=Ra(e),z=D!==null&&Ia(D),L=Xe(e,t),re=L!==null||!t.modelMatrix.aff||z,te,K,q,V=null;re?(V=Qe(t.modelMatrix,ki(S,v,L?.z??0,T,L?.yRot??0,L?.xRot??0)),te=S,K=v,q=0):([te,K]=Fi(t.modelMatrix,S,v),q=T+Li(t.modelMatrix));let ie=C*t.opacityFactor,pe=Math.max(0,Math.min(1,ie)),Le=Ie(e.x_anchor),Ke=Ie(e.y_anchor),Se=R(e.x_padding,i.width,i,0),He=R(e.y_padding,i.height,i,0),me=Number.isFinite(m)?m:x+2*Se,Ye=Math.max(0,me-2*Se),dt=Mn(e.x_alignment,u==="center"?.5:u==="right"?1:0),st=b+2*He;typeof e.height=="number"?st=e.height:typeof e.height=="string"&&(st=R(e.height,i.height,i,st));let Lt=e.vertical_align??"top",Mi=Mn(e.y_alignment,Lt==="middle"?.5:Lt==="bottom"?1:0),At=Math.max(0,st-2*He-b),Wt=te-me*Le+Se,ii=K-st*Ke+He+At*Mi,qt=q*Math.PI/180,jt=Math.cos(qt),ae=Math.sin(qt),ye=Math.abs(q)>.01;function We(ne,rt){let Je=(ne-te)*P,ut=(rt-K)*E,nt=Je+Q*ut,Pe=ut+J*Je;return ye?[te+nt*jt-Pe*ae,K+nt*ae+Pe*jt]:[te+nt,K+Pe]}let Oe=t.time-(t.timeOffset+Ge(e.time,0)),Me=null,qe=null;if(z){Me=[];let ne=[],rt=0,Je=0,ut=!1,nt=ii;for(let Pe of y){let wt=Pe.ascent+Pe.descent,ht=c*w,at=nt+(ht-wt)/2+Pe.ascent,et=Wt+Math.max(0,Ye-Pe.width)*dt;for(let Ee of Pe.spans){let ge="";for(let Y of Ee.text){let oe=/\\s/.test(Y);oe&&ut?(Je+=1,ut=!1):oe||(ut=!0);let j=Ee.atlas.glyphs.get(Y);if(!j)continue;if(et+=Ee.atlas.kern(ge,Y),ge=Y,j.width===0||j.height===0){et+=j.advance+Ee.letterSpacing;continue}let ue=et+j.offsetX,Ne=at+j.offsetY;Me[rt]=[ue+j.width/2,Ne+j.height/2];let X=ne[Je]??={l:1/0,r:-1/0,t:1/0,b:-1/0};X.l=Math.min(X.l,ue),X.r=Math.max(X.r,ue+j.width),X.t=Math.min(X.t,Ne),X.b=Math.max(X.b,Ne+j.height),rt+=1,et+=j.advance+Ee.letterSpacing}}nt+=ht}qe=ne.map(Pe=>[(Pe.l+Pe.r)/2,(Pe.t+Pe.b)/2])}let Te=0,De=0,Re=!1;if(typeof e.background_color=="string"&&x>0&&y.length>0){let ne=ft(e.background_color),rt=[ne[0]*pe,ne[1]*pe,ne[2]*pe,ne[3]*pe],[Je,ut]=$l(e.background_padding),nt=Ge(e.background_border_radius,0),Pe=c*w,wt=ii;for(let ht of y){let at=ht.width;if(at>0){let et=ht.ascent+ht.descent,ge=Wt+Math.max(0,Ye-at)*dt+at/2,Y=wt+(Pe-et)/2+et/2,[oe,j]=We(ge,Y),ue=(at+2*Je)*P,Ne=(et+2*ut)*E;s.drawShape({cx:oe,cy:j,width:ue,height:Ne,rotation:q,skewX:U,skewY:H,transform:V?ze(V,oe,j,ue,Ne,0,U,H,null):void 0,color:rt,cornerRadius:nt,shape:"rectangle",blend:e.blend_mode})}wt+=Pe}}let gt=zn(e.text_shadow,pe),ci=gt.length>0?2:1;for(let ne=0;ne<ci;ne++){let rt=gt.length>0&&ne===0,Je=gt.length===0||ne===1;Te=0,De=0,Re=!1;let ut=ii;for(let nt of y){let Pe=nt.ascent+nt.descent,wt=c*w,ht=(wt-Pe)/2,at=ut+ht+nt.ascent,et=Math.max(0,Ye-nt.width),ge=Wt+et*dt;for(let Y of nt.spans){if(Y.background&&Je){let ue=Y.background,Ne=Math.max(0,wt*ue.heightRatio),X=ut+wt*ue.insetYRatio,_t=Y.width+ue.paddingX*2,_e=ge+Y.width/2,Fe=X+Ne/2,[le,Ct]=We(_e,Fe);s.drawShape({cx:le,cy:Ct,width:_t*P,height:Ne*E,rotation:q,skewX:ue.skewX+U,skewY:H,transform:V?ze(V,le,Ct,_t*P,Ne*E,0,ue.skewX+U,H,null):void 0,color:[ue.color[0]*pe,ue.color[1]*pe,ue.color[2]*pe,ue.color[3]*pe],cornerRadius:ue.borderRadius,shape:"rectangle",blend:e.blend_mode})}let oe=[Y.tint[0]*pe,Y.tint[1]*pe,Y.tint[2]*pe,Y.tint[3]*pe],j="";for(let ue of Y.text){let Ne=/\\s/.test(ue);Ne&&Re?(De+=1,Re=!1):Ne||(Re=!0);let X=Y.atlas.glyphs.get(ue);if(!X)continue;if(ge+=Y.atlas.kern(j,ue),j=ue,X.width===0||X.height===0){ge+=X.advance+Y.letterSpacing;continue}let _t=Te,_e=D?Fa(D,Oe,Te,De):null;if(Te+=1,_e&&_e.opacity<=0){ge+=X.advance+Y.letterSpacing;continue}let Fe=V;if(Fe&&_e?.flips){let vi=($t,Yt)=>{if(!$t||!Yt)return;let[Us,$i]=We($t[0]+_e.dx,$t[1]+_e.dy);Fe=Qe(Fe,ki(Us,$i,0,Yt[2],Yt[1],Yt[0]))};vi(qe?.[De],_e.flips.word),vi(Me?.[_t],_e.flips.letter)}let le=ge+X.offsetX+(_e?_e.dx:0),Ct=at+X.offsetY+(_e?_e.dy:0),[ve,Ot]=We(le+X.width/2,Ct+X.height/2);!Fe&&q===0&&U===0&&H===0&&P===1&&E===1&&!_e&&(ve=Math.round(ve-X.width/2)+X.width/2,Ot=Math.round(Ot-X.height/2)+X.height/2);let ir=X.x/Y.atlas.width,sr=X.y/Y.atlas.height,rr=(X.x+X.width)/Y.atlas.width,nr=(X.y+X.height)/Y.atlas.height,Es=_e&&_e.opacity<1?[oe[0]*_e.opacity,oe[1]*_e.opacity,oe[2]*_e.opacity,oe[3]*_e.opacity]:oe;if(rt){let vi=X.width*P,$t=X.height*E;Pn(gt,_e&&_e.opacity<1?_e.opacity:1,(Yt,Us,$i)=>{let[ar,or]=We(le+Yt+X.width/2,Ct+Us+X.height/2);s.drawTexturedQuad({cx:ar,cy:or,width:vi,height:$t,rotation:q,skewX:U,skewY:H,transform:Fe?ze(Fe,ar,or,vi,$t,0,U,H,null):void 0,texture:Y.atlas.texture,uvRect:[ir,sr,rr,nr],tint:$i,blend:e.blend_mode,alphaGamma:Cn($i)})})}Je&&s.drawTexturedQuad({cx:ve,cy:Ot,width:X.width*P,height:X.height*E,rotation:q,skewX:U,skewY:H,transform:Fe?ze(Fe,ve,Ot,X.width*P,X.height*E,0,U,H,null):void 0,texture:Y.atlas.texture,uvRect:[ir,sr,rr,nr],tint:Es,blend:e.blend_mode,alphaGamma:Cn(Es)}),ge+=X.advance+Y.letterSpacing}}ut+=wt}}}function Ex(e,t){let i=[];for(let n of e.spans){if(n.nowrap){i.push({word:n.text,resolved:n,width:n.width});continue}let a=n.text.split(/(\\s+)/).filter(o=>o!=="");for(let o of a){let c=0,l="";for(let u of o){let h=n.atlas.glyphs.get(u);h&&(c+=h.advance+n.letterSpacing+n.atlas.kern(l,u),l=u)}i.push({word:o,resolved:n,width:c})}}let s=[],r={spans:[],width:0,ascent:0,descent:0};for(let n of i){let a=n.word.trim()==="";r.width+n.width>t&&r.spans.length>0&&(s.push(r),r={spans:[],width:0,ascent:0,descent:0},a)||(r.spans.push({...n.resolved,text:n.word,width:n.width}),r.width+=n.width,r.ascent=Math.max(r.ascent,n.resolved.atlas.ascent),r.descent=Math.max(r.descent,n.resolved.atlas.descent))}return r.spans.length>0&&s.push(r),s}function Ux(e,t,i){let s=e.font_family??t.family,r=e.font_weight??t.weight,n;typeof e.font_size=="number"?n=e.font_size:typeof e.font_size=="string"?n=R(e.font_size,i.canvas.height,i.canvas,t.size):n=t.size;let a=wr({family:s,size:n,weight:r}),o=i.fontAtlases.get(a);o||(o=Sr({family:s,size:n,weight:r},i.backend),i.fontAtlases.set(a,o));let c=Ge(e.letter_spacing,t.letterSpacing),l=0,u="";for(let m of e.text){let g=o.glyphs.get(m);g&&(l+=g.advance+c+o.kern(u,m),u=m)}let h=e.fill_color??t.color,f=ft(h),p;if(e.background){let m=e.background.opacity!==void 0?Math.max(0,Math.min(1,e.background.opacity)):1,g=ft(e.background.color);p={color:[g[0]*m,g[1]*m,g[2]*m,g[3]*m],heightRatio:e.background.height_ratio??1,insetYRatio:e.background.inset_y_ratio??0,paddingX:e.background.padding_x??0,skewX:e.background.skew_x??0,borderRadius:e.background.border_radius??0}}else e.background_color&&(p={color:ft(e.background_color),heightRatio:1,insetYRatio:0,paddingX:0,skewX:0,borderRadius:0});return{text:e.text,atlas:o,tint:f,background:p,width:l,letterSpacing:c,nowrap:e.nowrap===!0}}function Bx(e,t){return e.font_size==="auto"?48:typeof e.font_size=="number"?e.font_size:typeof e.font_size=="string"?R(e.font_size,t.canvas.height,t.canvas,48):48}function Ge(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function $l(e){if(Array.isArray(e))return[Ge(e[0],0),Ge(e[1],0)];let t=Ge(e,0);return[t,t]}function zn(e,t=1){if(!e)return[];let i=Array.isArray(e)?e:[e],s=[];for(let r of i){if(!r||typeof r!="object")continue;let n=r;if(typeof n.color!="string")continue;let a=ft(n.color),o=Math.max(0,Math.min(1,Ge(n.opacity,1)))*t;s.push({color:[a[0]*o,a[1]*o,a[2]*o,a[3]*o],dx:Ge(n.offset_x,0),dy:Ge(n.offset_y,0),blur:Math.max(0,Ge(n.blur,0))})}return s}var Ax=(()=>{let e=[[0,0,1]],t=[{r:.62,n:6},{r:1.18,n:8}];for(let s of t)for(let r=0;r<s.n;r++){let n=r/s.n*Math.PI*2+s.r;e.push([Math.cos(n)*s.r,Math.sin(n)*s.r,Math.exp(-(s.r*s.r)/.7)])}let i=e.reduce((s,r)=>s+r[2],0);return e.map(([s,r,n])=>[s,r,n/i])})(),Wl=(e,t)=>[e[0]*t,e[1]*t,e[2]*t,e[3]*t];function Pn(e,t,i){for(let s of e)if(s.blur<=.001)i(s.dx,s.dy,t<1?Wl(s.color,t):s.color);else for(let[r,n,a]of Ax)i(s.dx+r*s.blur,s.dy+n*s.blur,Wl(s.color,a*t))}var An=2;function Cx(e,t){let{canvas:i,backend:s,maskedTexts:r}=t,n=t.timeOffset+Ge(e.time,0),a=t.time-n,o=Yl(e,a);if(o.length===0)return;let c=kr(String(e.font_family??"sans-serif")),l=String(e.font_weight??"normal"),u=e.font_style==="italic"?"italic":"normal",h;if(e.font_size==="auto"){let Se=(e.width!==void 0?R(e.width,i.width,i,i.width):i.width)-2*R(e.x_padding,i.width,i,0),He=R(e.font_size_minimum,i.height,i,8),me=R(e.font_size_maximum,i.height,i,400);h=Tr(o,c,l,Math.max(1,Se),48,He,me)}else typeof e.font_size=="number"?h=e.font_size:typeof e.font_size=="string"?h=R(e.font_size,i.height,i,48):h=48;let f=Px(),p=\`\${u} \${l} \${h*An}px \${c}\`;f.font=p;let m=f.measureText(o),g=m.actualBoundingBoxAscent,y=m.actualBoundingBoxDescent,w=Math.max(1,Math.ceil(m.width)),x=Math.max(1,Math.ceil(g+y)),b=Math.max(4,Math.ceil(h*An*.1)),S=w+b*2,v=x+b*2,T=S/An,C=v/An,P=typeof e.id=="string"?e.id:\`__masked_text_\${o}\`,E=r.get(P);if(!E||E.canvas.width!==S||E.canvas.height!==v){let Se=new OffscreenCanvas(S,v),He=Se.getContext("2d");if(!He)return;let me=s.createTexture(Se);E={canvas:Se,ctx:He,texture:me},r.set(P,E)}let U=E.ctx;U.save(),U.setTransform(1,0,0,1,0,0),U.clearRect(0,0,S,v),U.font=p,U.fillStyle=typeof e.fill_color=="string"?e.fill_color:"#ffffff",U.textBaseline="alphabetic",U.textAlign="left",U.fillText(o,b,b+g),U.restore();let H=e.mask,Q=Er(Mx(H.progress,a));zx(U,S,v,H.angle??-45,Q,H.softness??.3),s.updateTexture(E.texture,E.canvas);let J=M(e,"x",R(e.x,i.width,i),t),D=M(e,"y",R(e.y,i.height,i),t),z=M(e,"rotation",Ge(e.rotation??e.z_rotation,0),t),L=M(e,"opacity",Ge(e.opacity,1),t),re=Ie(e.x_anchor),te=Ie(e.y_anchor),K=J-T*re,q=D-C*te,V=K+T/2,ie=q+C/2,pe=Er(L);if(pe<=0)return;let Le=Xe(e,t),Ke=Le!==null||!t.modelMatrix.aff;s.drawTexturedQuad({cx:V,cy:ie,width:T,height:C,rotation:z,transform:Ke?ze(t.modelMatrix,V,ie,T,C,z,0,0,Le):void 0,texture:E.texture,tint:[pe,pe,pe,pe],blend:e.blend_mode})}function Mx(e,t){return e===void 0?1:typeof e=="number"?e:ai(e)?oi(e,{t,dur:0,i:0,n:1,value:1}):Array.isArray(e)?Ze(e,t):1}function zx(e,t,i,s,r,n){let a=s*Math.PI/180,o=Math.sin(a),c=-Math.cos(a),l=Math.abs(t*o)+Math.abs(i*c);if(l===0)return;let u=t/2,h=i/2,f=u-l/2*o,p=h-l/2*c,m=u+l/2*o,g=h+l/2*c,y=Er(n),w=(1-r)*(1+y),x=Math.max(0,w-y),b=Er(x),S=Math.max(b,Er(w)),v=e.createLinearGradient(f,p,m,g);v.addColorStop(0,"rgba(0,0,0,0)"),v.addColorStop(b,"rgba(0,0,0,0)"),v.addColorStop(S,"rgba(0,0,0,1)"),v.addColorStop(1,"rgba(0,0,0,1)"),e.save(),e.setTransform(1,0,0,1,0,0),e.globalCompositeOperation="destination-in",e.fillStyle=v,e.fillRect(0,0,t,i),e.globalCompositeOperation="source-over",e.restore()}var ql=null,Oa=null;function Px(){return Oa||(ql=new OffscreenCanvas(1,1),Oa=ql.getContext("2d")),Oa}function Er(e){return e<0?0:e>1?1:e}function Yl(e,t){return Xl(String(e.text??""),e.text_transform)}function Xl(e,t){switch(t){case"uppercase":return e.toUpperCase();case"lowercase":return e.toLowerCase();case"capitalize":return e.replace(/(^|\\s)(\\S)/g,(i,s,r)=>s+r.toUpperCase());default:return e}}function Mn(e,t){if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.min(1,e));if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return Math.max(0,Math.min(1,e.trim().endsWith("%")?i/100:i))}return t}function Da(e,t){if(e.length===0)return[];let i=[];if(t===void 0)i.push([...e]);else if(t==="auto"){let n=[];for(let a of e){if(n.length>0){let o=n[n.length-1];(n.length>=6||a.start-o.end>=.6||a.end-n[0].start>3)&&(i.push(n),n=[])}n.push(a)}n.length>0&&i.push(n)}else{let n=[],a=0;for(let o of e){let c=o.text.trim().length,l=n.length>0?a+1+c:c;n.length>0&&l>t&&(i.push(n),n=[],a=0),a=n.length>0?a+1+c:c,n.push(o)}n.length>0&&i.push(n)}let s=[],r=0;for(let n of i)s.push({words:n,startIndex:r,start:n[0].start,end:n[n.length-1].end}),r+=n.length;return s}function Na(e,t){let i=null;for(let s of e)if(s.start<=t)i=s;else break;return i}function Zl(e,t){let{canvas:i,backend:s}=t,r=e.words;if(!r||r.length===0)return;let n=t.timeOffset+gi(e.time,0),a=t.time-n,o=Da(r,e.max_length),c=e.max_length===void 0?r:Na(o,a)?.words??[];if(c.length===0)return;let l=kr(String(e.font_family??"sans-serif")),u=e.font_weight??"bold",h;if(e.font_size==="auto"){let ae=e.width!==void 0?R(e.width,i.width,i,i.width*.9):i.width*.9,ye=c.map(We=>We.text).join(" ");h=Tr(ye,l,u,ae,64)}else typeof e.font_size=="number"?h=e.font_size:typeof e.font_size=="string"?h=R(e.font_size,i.height,i,64):h=64;let f=wr({family:l,size:h,weight:u}),p;t.fontAtlases.has(f)?p=t.fontAtlases.get(f):(p=Sr({family:l,size:h,weight:u},s),t.fontAtlases.set(f,p));let m=M(e,"x",R(e.x,i.width,i),t),g=M(e,"y",R(e.y,i.height,i),t),y=M(e,"rotation",gi(e.rotation??e.z_rotation,0),t),w=M(e,"opacity",gi(e.opacity,1),t),x=Xe(e,t),b=x!==null||!t.modelMatrix.aff,S,v,T,C=null;b?(C=Qe(t.modelMatrix,ki(m,g,x?.z??0,y,x?.yRot??0,x?.xRot??0)),S=m,v=g,T=0):([S,v]=Fi(t.modelMatrix,m,g),T=y+Li(t.modelMatrix));let P=w*t.opacityFactor,E=Ie(e.x_anchor),U=Ie(e.y_anchor),H=p.glyphs.get(" ")?.advance??h*.3,Q=e.width!==void 0?R(e.width,i.width,i,i.width*.9):i.width*.9,J=ae=>{let ye=0;for(let We of ae)ye+=p.glyphs.get(We)?.advance??0;return ye},D=[];{let ae=[],ye=0;for(let We of c){let Oe=J(We.text);ae.length>0&&ye+H+Oe>Q&&(D.push(ae),ae=[],ye=0),ae.length>0&&(ye+=H),ae.push(We),ye+=Oe}ae.length>0&&D.push(ae)}let z=[],L=[],re=[];for(let ae=0;ae<D.length;ae++){let ye=0,We=D[ae];for(let Oe=0;Oe<We.length;Oe++){let Me=We[Oe],qe=ye,Te=L.length;for(let De of Me.text){let Re=p.glyphs.get(De);Re&&(Re.width>0&&Re.height>0&&L.push({glyphX:Re.x,glyphY:Re.y,glyphW:Re.width,glyphH:Re.height,cursorX:ye,offsetX:Re.offsetX,offsetY:Re.offsetY,lineIndex:ae}),ye+=Re.advance)}z.push({word:Me,width:ye-qe,cursorStart:qe,charStart:Te,charCount:L.length-Te,lineIndex:ae}),Oe<We.length-1&&(ye+=H)}re.push(ye)}let te=re.length>0?Math.max(...re):0,K=(p.ascent+p.descent)*gi(e.line_height,1.2),q=Math.max(D.length,1)*K,V=S-Q*E,ie=v-q*U,pe=e.text_align==="left"?0:e.text_align==="right"?1:.5,Le=re.map(ae=>V+(Q-ae)*pe),Ke=D.map((ae,ye)=>ie+p.ascent+ye*K),Se=Ke.map(ae=>ae-p.ascent+(p.ascent+p.descent)/2),He=T*Math.PI/180,me=Math.cos(He),Ye=Math.sin(He),dt=T!==0,st=e.style??"tiktok_bounce",Lt=ft(typeof e.fill_color=="string"?e.fill_color:"#ffffff"),Mi=ft(typeof e.highlight_color=="string"?e.highlight_color:"#ffd60a"),At=Math.max(0,Math.min(1,P)),Wt=t.timeOffset+gi(e.time,0),ii=t.time-Wt;if(typeof e.background_color=="string"&&te>0){let ae=ft(e.background_color),ye=e.background_padding,We=Array.isArray(ye)?gi(ye[0],0):gi(ye,0),Oe=Array.isArray(ye)?gi(ye[1],0):gi(ye,0),Me=te+2*We,qe=q+2*Oe,Te=V+Q/2,De=ie+q/2;if(dt){let Re=Te-S,gt=De-v;Te=S+Re*me-gt*Ye,De=v+Re*Ye+gt*me}s.drawShape({cx:Te,cy:De,width:Me,height:qe,rotation:T,skewX:0,skewY:0,transform:C?ze(C,Te,De,Me,qe,0,0,0,null):void 0,color:[ae[0]*At,ae[1]*At,ae[2]*At,ae[3]*At],cornerRadius:gi(e.background_border_radius,0),shape:"rectangle",blend:e.blend_mode})}let qt=zn(e.text_shadow,At),jt=qt.length>0?2:1;for(let ae=0;ae<jt;ae++){let ye=qt.length>0&&ae===0,We=qt.length===0||ae===1;for(let Oe of z){let Me=Ix(st,Oe.word,ii);if(Me.opacity<=0)continue;let qe=Le[Oe.lineIndex]+Oe.cursorStart+Oe.width/2,Te=Se[Oe.lineIndex],De=Me.highlighted?Mi:Lt,Re=At*Me.opacity,gt=[De[0]*Re,De[1]*Re,De[2]*Re,De[3]*Re];for(let ci=0;ci<Oe.charCount;ci++){let ne=L[Oe.charStart+ci],rt=Le[ne.lineIndex]+ne.cursorX+ne.offsetX+ne.glyphW/2,Je=Ke[ne.lineIndex]+ne.offsetY+ne.glyphH/2,ut=rt-qe,nt=Je-Te,Pe=qe+ut*Me.scale,wt=Te+nt*Me.scale,ht=ne.glyphW*Me.scale,at=ne.glyphH*Me.scale;if(dt){let oe=Pe-S,j=wt-v;Pe=S+oe*me-j*Ye,wt=v+oe*Ye+j*me}let et=ne.glyphX/p.width,Ee=ne.glyphY/p.height,ge=(ne.glyphX+ne.glyphW)/p.width,Y=(ne.glyphY+ne.glyphH)/p.height;ye&&Pn(qt,Me.opacity,(oe,j,ue)=>{let Ne=qe+(rt+oe-qe)*Me.scale,X=Te+(Je+j-Te)*Me.scale;if(dt){let _t=Ne-S,_e=X-v;Ne=S+_t*me-_e*Ye,X=v+_t*Ye+_e*me}s.drawTexturedQuad({cx:Ne,cy:X,width:ht,height:at,rotation:T,transform:C?ze(C,Ne,X,ht,at,0,0,0,null):void 0,texture:p.texture,uvRect:[et,Ee,ge,Y],tint:ue,blend:e.blend_mode})}),We&&s.drawTexturedQuad({cx:Pe,cy:wt,width:ht,height:at,rotation:T,transform:C?ze(C,Pe,wt,ht,at,0,0,0,null):void 0,texture:p.texture,uvRect:[et,Ee,ge,Y],tint:gt,blend:e.blend_mode})}}}}function Ix(e,t,i){let s=i-t.start,r=Math.max(.01,t.end-t.start),n=s<0,a=s>=0&&s<=r,o=s>r;switch(e){case"tiktok_bounce":return Rx(s,r,n,a,o);case"fade_reveal":return Fx(s,r,n,a,o);case"kinetic_typewriter":return Lx(n,a,o);case"word_pop":return Ox(s,n,a,o)}}function Rx(e,t,i,s,r){return i?{opacity:0,scale:1,highlighted:!1}:s?e<.18?{opacity:1,scale:.6+.4*yt("ease-out-back",e/.18),highlighted:!0}:{opacity:1,scale:1,highlighted:!0}:{opacity:1,scale:1,highlighted:!1}}function Fx(e,t,i,s,r){if(i)return e>-.12?{opacity:(e+.12)/.12,scale:1,highlighted:!1}:{opacity:0,scale:1,highlighted:!1};if(s)return{opacity:1,scale:1,highlighted:!0};let a=e-t;return a<.12?{opacity:1-a/.12,scale:1,highlighted:!1}:{opacity:0,scale:1,highlighted:!1}}function Lx(e,t,i){return e?{opacity:0,scale:1,highlighted:!1}:{opacity:1,scale:1,highlighted:t}}function Ox(e,t,i,s){return t?{opacity:0,scale:1,highlighted:!1}:i?e<.15?{opacity:1,scale:1+.15*Math.sin(e/.15*Math.PI),highlighted:!0}:{opacity:1,scale:1,highlighted:!0}:{opacity:1,scale:1,highlighted:!1}}function gi(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}var Ur=Math.PI/180;function ct(e,t,i){return e===void 0?i:ai(e)?oi(e,{t,dur:0,i:0,n:1,value:i}):Array.isArray(e)?Ze(e,t):e}function Ql(e,t){let i=e.lights;if(!i||i.length===0)return[];let s=[];for(let r of i){let n=kt(r.color??"#ffffff"),a=ct(r.intensity,t,1),o=[n[0]*a,n[1]*a,n[2]*a];if(r.type==="ambient")s.push({ambient:!0,dir:[0,0,1],color:o});else{let c=ct(r.azimuth,t,0)*Ur,l=ct(r.elevation,t,45)*Ur,u=Math.cos(l);s.push({ambient:!1,dir:[u*Math.cos(c),u*Math.sin(c),Math.sin(l)],color:o})}}return s}function Wi(e,t){let i=e.material;return i?{roughness:Math.max(.02,Math.min(1,ct(i.roughness,t,.5))),metalness:Math.max(0,Math.min(1,ct(i.metalness,t,0))),reflectivity:Math.max(0,ct(i.reflectivity,t,1)),emissive:Math.max(0,ct(i.emissive,t,0)),normalMap:typeof i.normal_map=="string"&&i.normal_map?i.normal_map:null,normalScale:Math.max(0,ct(i.normal_scale,t,1))}:null}function Kl(e,t){let i=e.environment;if(!i)return null;if(i.type==="image")return i.src?{stops:[],avg:[.5,.5,.5],image:i.src}:null;if(i.type!=="gradient"||!i.stops||i.stops.length===0)return null;let s=i.stops.slice(0,4).map(n=>{let a=kt(n.color);return{offset:Math.max(0,Math.min(1,n.offset)),color:[a[0],a[1],a[2]]}}).sort((n,a)=>n.offset-a.offset),r=[0,0,0];for(let n of s)r[0]+=n.color[0],r[1]+=n.color[1],r[2]+=n.color[2];return r[0]/=s.length,r[1]/=s.length,r[2]/=s.length,{stops:s,avg:r,image:null}}function Ha(e,t){let i=e.bloom;if(!i)return null;let s=Math.max(0,ct(i.intensity,t,1)),r=Math.max(0,ct(i.radius,t,24));return s<=0||r<=0?null:{threshold:Math.max(0,Math.min(1,ct(i.threshold,t,.75))),knee:Math.max(.001,ct(i.knee,t,.1)),intensity:s,radius:r}}function Jl(e,t,i){let s=Math.max(.001,ct(e.perspective,t,1e3)),r=e.origin_x!==void 0&&typeof e.origin_x=="number"?e.origin_x:i.width/2,n=e.origin_y!==void 0&&typeof e.origin_y=="number"?e.origin_y:i.height/2,a=ct(e.x,t,0),o=ct(e.y,t,0),c=ct(e.z,t,0),l=ct(e.x_rotation,t,0)*Ur,u=ct(e.y_rotation,t,0)*Ur,h=ct(e.z_rotation,t,0)*Ur,f=Math.cos(l),p=Math.sin(l),m=Math.cos(u),g=Math.sin(u),y=Math.cos(h),w=Math.sin(h),x=f*g,b=-p,S=f*m,v=x*y-b*w,T=x*w+b*y,C=S;return[r+a+s*v,n+o+s*T,c+s*C]}function qi(e,t,i,s,r){if(!i||e.lights.length===0&&!e.environment)return null;let n=t,a=n[8],o=n[9],c=n[10],l=Math.hypot(a,o,c)||1;a/=l,o/=l,c/=l;let u;if(i.normalMap&&i.normalScale>0){let g=e.images.get(i.normalMap);if(g){let y=n[0],w=n[1],x=n[2],b=Math.hypot(y,w,x)||1;y/=b,w/=b,x/=b;let S=n[4],v=n[5],T=n[6],C=Math.hypot(S,v,T)||1;S/=C,v/=C,T/=C,u={texture:g.texture,scale:i.normalScale,tangent:[y,w,x],bitangent:[S,v,T]}}}let h=[0,0,0],f=[],p=[];for(let g of e.lights)g.ambient?(h[0]+=g.color[0],h[1]+=g.color[1],h[2]+=g.color[2]):f.length<4&&(f.push(g.dir),p.push(g.color));let m=e.environment?{stopColors:e.environment.stops.map(g=>g.color),stopOffsets:e.environment.stops.map(g=>g.offset),avg:e.environment.avg,image:e.environment.image?e.images.get(e.environment.image)?.texture:void 0}:void 0;return{albedo:s,strokeAlbedo:r,roughness:i.roughness,metalness:i.metalness,reflectivity:i.reflectivity,emissive:i.emissive,worldMatrix:t,normal:[a,o,c],eye:e.eye,ambient:h,lightDirs:f,lightColors:p,env:m,normalMap:u}}var Dx=[1,1,1,1];function td(e,t){let i=t.timeOffset+ji(e.time,0),s=id(e.duration,t.sourceDuration-i);if(t.time<i||t.time>i+s)return;let r=t.time,n=Array.isArray(e.time_remap)&&e.time_remap.length>0?i+Math.max(0,Ze(e.time_remap,t.time-i)):t.time,a=M(e,"opacity",ji(e.opacity,1),t),o=Math.max(0,Math.min(1,a));if(o===0)return;let{canvas:c}=t,l=R(e.x,c.width,c),u=R(e.y,c.height,c),h=e.width!==void 0?R(e.width,c.width,c):0,f=e.height!==void 0?R(e.height,c.height,c):0,p=Ie(e.x_anchor),m=Ie(e.y_anchor),g=M(e,"rotation",ji(e.rotation??e.z_rotation,0),t),{sx:y,sy:w}=Ut(e,t),x=Xe(e,t),b=[...e.elements].sort((z,L)=>ji(L.layer,Number.MAX_SAFE_INTEGER)-ji(z.layer,Number.MAX_SAFE_INTEGER)),S=t._dispatch,v=t.modelMatrix,T=t.worldMatrix,C=t.opacityFactor,P=t.timeOffset,E=t.surfaceWidth,U=t.surfaceHeight;if(e.clip===!0||e.mask)if(h<=0||f<=0)$().warn("group clip/mask requires explicit width and height \\u2014 skipping");else{let z=(Se,He)=>{let me=t.groupTargets.get(Se);me&&(me.width!==h||me.height!==f)&&(t.backend.destroyRenderTarget(me.target),me=void 0),me||(me={target:t.backend.createRenderTarget(h,f),width:h,height:f},t.groupTargets.set(Se,me)),me.lastTouched=t.frameIndex,t.backend.pushTarget(me.target,[0,0,0,0]);try{t.modelMatrix=va(),t.worldMatrix=va(),t.opacityFactor=1,t.timeOffset=i,t.time=n,t.surfaceWidth=h,t.surfaceHeight=f;let Ye=[...He].sort((dt,st)=>ji(st.layer,Number.MAX_SAFE_INTEGER)-ji(dt.layer,Number.MAX_SAFE_INTEGER));for(let dt of Ye)dt.visible!==!1&&ed(dt,t.time,i,s)&&S?.(dt,t)}finally{t.backend.popTarget()}return t.modelMatrix=v,t.worldMatrix=T,t.opacityFactor=C,t.timeOffset=P,t.time=r,t.surfaceWidth=E,t.surfaceHeight=U,me},L=e.id??"__group_layer__",re=z(L,b),te=e.mask?z(\`\${L}::mask\`,e.mask.elements):null,{cx:K,cy:q}=Mt(l,u,h,f,p,m),V=x!==null||!v.aff,ie=Xt(v,C,K,q,g,a,h*y,f*w),pe=V?ze(v,K,q,h*y,f*w,g,0,0,x):void 0,Le=Math.max(0,Math.min(1,ie.opacity01)),Ke=[Le,Le,Le,Le];if(te&&e.mask)t.backend.drawMaskedQuad({cx:ie.cx,cy:ie.cy,width:V?h*y:ie.width,height:V?f*w:ie.height,rotation:ie.rotation,transform:pe,content:re.target.texture,mask:te.target.texture,mode:e.mask.mode,tint:Ke,blend:e.blend_mode});else{let Se=typeof e.border_radius=="number"&&e.border_radius>0?e.border_radius*y:void 0,He=Wi(e,t.time),me=He?qi(t,ze(T,K,q,h*y,f*w,g,0,0,x),He,Dx):null;t.backend.drawTexturedQuad({cx:ie.cx,cy:ie.cy,width:V?h*y:ie.width,height:V?f*w:ie.height,rotation:ie.rotation,transform:pe,texture:re.target.texture,tint:Ke,cornerRadius:Se,blend:e.blend_mode,lit:me??void 0})}return}e.blend_mode&&e.blend_mode!=="normal"&&$().warn("group blend_mode requires clip: true or mask \\u2014 ignored; children composite with their own blend modes");let{cx:H,cy:Q}=Mt(l,u,h,f,p,m),J=x?ol(H,Q,x.z,h,f,.5,.5,g,x.yRot,x.xRot,y,w):cl(H,Q,h,f,.5,.5,g,y,w);t.modelMatrix=Qe(v,J),t.worldMatrix=Qe(T,J),t.opacityFactor=C*o,t.timeOffset=i,t.time=n;let D=t.depthSort?Un(b,t):b;for(let z of D)z.visible!==!1&&ed(z,t.time,i,s)&&S?.(z,t);t.modelMatrix=v,t.worldMatrix=T,t.opacityFactor=C,t.timeOffset=P,t.time=r}function ji(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function id(e,t){if(e==="auto"||e==="end"||e==null)return t;if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function ed(e,t,i,s){let r=ji(e.time,0),n=i+r,a=id(e.duration,s-r);return t>=n&&t<=n+a}var sd=[0,0,1,1],In=e=>e<0?0:e>1?1:e;function Nx(e){if(!e)return null;let{x:t,y:i,width:s,height:r}=e;if(![t,i,s,r].every(l=>Number.isFinite(l)))return null;let n=In(t),a=In(i),o=Math.min(In(s),1-n),c=Math.min(In(r),1-a);return o<=0||c<=0||n===0&&a===0&&o===1&&c===1?null:{x:n,y:a,width:o,height:c}}function Rn(e,t,i,s,r,n){let a=Nx(n),o=a?s*a.width:s,c=a?r*a.height:r,l=Hx(e,t,i,o,c);if(!a)return l;let[u,h,f,p]=l.uvRect;return{drawWidth:l.drawWidth,drawHeight:l.drawHeight,uvRect:[a.x+u*a.width,a.y+h*a.height,a.x+f*a.width,a.y+p*a.height]}}function Hx(e,t,i,s,r){if(t<=0||i<=0||s<=0||r<=0||e==="fill")return{drawWidth:t,drawHeight:i,uvRect:sd};switch(e){case"contain":{let n=Math.min(t/s,i/r);return{drawWidth:s*n,drawHeight:r*n,uvRect:sd}}case"none":{let n=Math.min(t,s),a=Math.min(i,r),o=(1-n/s)/2,c=(1-a/r)/2;return{drawWidth:n,drawHeight:a,uvRect:[o,c,1-o,1-c]}}case"cover":default:{let n=Math.max(t/s,i/r),a=(1-t/(s*n))/2,o=(1-i/(r*n))/2;return{drawWidth:t,drawHeight:i,uvRect:[a,o,1-a,1-o]}}}}var Gx=[1,1,1,1];function nd(e,t){let{canvas:i,backend:s,images:r}=t,n=String(e.source??"");if(!n)return;let a=r.get(n);if(!a)return;let o=M(e,"x",R(e.x,i.width,i),t),c=M(e,"y",R(e.y,i.height,i),t),{sx:l,sy:u}=Ut(e,t),h=mi(e,M(e,"width",R(e.width,i.width,i,a.bitmap.width),t),M(e,"height",R(e.height,i.height,i,a.bitmap.height),t)),f=l*h.width,p=u*h.height,m=M(e,"rotation",gs(e.rotation??e.z_rotation,0),t),g=M(e,"opacity",gs(e.opacity,1),t),y=Ie(e.x_anchor),w=Ie(e.y_anchor),{cx:x,cy:b}=Mt(o,c,f,p,y,w),S=Xt(t.modelMatrix,t.opacityFactor,x,b,m,g,f,p),v=Math.max(0,Math.min(1,S.opacity01)),T=[v,v,v,v],C=Xe(e,t),P=C!==null||!t.modelMatrix.aff,E=Rn(e.fit,P?f:S.width,P?p:S.height,a.bitmap.width,a.bitmap.height,Vx(e,t)),{skewX:U,skewY:H}=ei(e,t),Q=Wi(e,t.time),J=Q?qi(t,ze(t.worldMatrix,x,b,E.drawWidth,E.drawHeight,m,U,H,C),Q,Gx):null;s.drawTexturedQuad({cx:S.cx,cy:S.cy,width:E.drawWidth,height:E.drawHeight,rotation:S.rotation,skewX:U,skewY:H,transform:P?ze(t.modelMatrix,x,b,E.drawWidth,E.drawHeight,m,U,H,C):void 0,texture:a.texture,uvRect:E.uvRect,tint:T,cornerRadius:gs(e.border_radius,0),blend:e.blend_mode,lit:J??void 0})}var rd=["crop_x","crop_y","crop_width","crop_height"];function Vx(e,t){let i=rd.some(r=>e[r]!==void 0),s=(e.keyframe_animations??[]).some(r=>rd.includes(r.property));if(!(!i&&!s))return{x:M(e,"crop_x",gs(e.crop_x,0),t),y:M(e,"crop_y",gs(e.crop_y,0),t),width:M(e,"crop_width",gs(e.crop_width,1),t),height:M(e,"crop_height",gs(e.crop_height,1),t)}}function gs(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function ad(e,t){let{canvas:i,backend:s}=t,r=t.timeOffset+Bt(e.time,0),n=t.time-r;if(n<0)return;let a=M(e,"x",R(e.x,i.width,i),t),o=M(e,"y",R(e.y,i.height,i),t),c=Bt(e.z_velocity,0),l=Bt(e.z_spread,0),u=c!==0||l!==0,h=Xe(e,t),f=h!==null||!t.modelMatrix.aff||u?Qe(t.modelMatrix,ki(a,o,h?.z??0,0,h?.yRot??0,h?.xRot??0)):null,p=Math.max(1,Bt(e.rate,60)),m=Math.max(.01,Bt(e.lifetime,1.5)),g=Bt(e.velocity,300),y=Bt(e.spread,360),w=Bt(e.direction,-90),x=Bt(e.gravity,600),b=Math.max(1,Bt(e.size,12)),S=Fn(Bt(e.size_variation,.4)),v=Bt(e.rotation_speed,360),T=e.burst===!0,C=Math.max(1,Math.floor(Bt(e.burst_count,80))),P=Fn(Bt(e.fade_at,.7)),E=e.particle_shape==="circle",U=Array.isArray(e.target_points)?e.target_points:null,H=e.convergence_easing??"ease-out-quart",Q=Bt(e.scatter_radius,Math.max(i.width,i.height)),J=Wx(e.color),D=Fn(M(e,"opacity",Bt(e.opacity,1),t)*t.opacityFactor);if(D<=0)return;let z=qx(typeof e.id=="string"?e.id:"particles"),L,re;if(T){if(n>=m)return;L=0,re=C-1}else L=Math.max(0,Math.ceil((n-m)*p)),re=Math.floor(n*p);for(let te=L;te<=re;te++){let K=T?0:te/p,q=n-K;if(q<0||q>=m)continue;let V=jx(z+te*2654435769),ie=V(),pe=V(),Le=V(),Ke=V(),Se=V(),He=V(),me,Ye;if(U&&U.length>0){let Oe=ie*Math.PI*2,Me=Q*(.5+.5*pe),qe=a+Math.cos(Oe)*Me,Te=o+Math.sin(Oe)*Me,De=U[te%U.length],Re=Fn(q/m),gt=yt(H,Re);me=qe+(De[0]-qe)*gt,Ye=Te+(De[1]-Te)*gt}else{let Me=(w+(ie-.5)*y)*Math.PI/180,qe=g*(.7+.6*pe),Te=Math.cos(Me)*qe,De=Math.sin(Me)*qe;me=a+Te*q,Ye=o+De*q+.5*x*q*q}let dt=u?(c+(He-.5)*l)*q:0,st=v*q*(Le<.5?-1:1),Lt=b*(1-S+S*Ke),Mi=J[Math.floor(Se*J.length)%J.length],At=q/m,Wt=D;if(At>P&&(Wt*=(1-At)/(1-P)),Wt<=0)continue;let[ii,qt]=f?[me,Ye]:Fi(t.modelMatrix,me,Ye),jt=f?st:st+Li(t.modelMatrix),ae=kt(Mi),ye=ae[3]*Wt,We=[ae[0]*ye,ae[1]*ye,ae[2]*ye,ye];s.drawShape({cx:ii,cy:qt,width:Lt,height:Lt,rotation:jt,transform:f?ze(f,me,Ye,Lt,Lt,st,0,0,dt!==0?{xRot:0,yRot:0,z:dt}:null):void 0,color:We,shape:E?"ellipse":"rectangle",cornerRadius:0,blend:e.blend_mode})}}function Bt(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function Fn(e){return e<0?0:e>1?1:e}function Wx(e){return e?Array.isArray(e)?e.length>0?e:["#ffffff"]:[e]:["#ffffff"]}function qx(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t>>>0}function jx(e){let t=e>>>0;return()=>{t=t+1831565813|0;let i=t;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}function cd(e,t){let{canvas:i,backend:s}=t,r=M(e,"x",R(e.x,i.width,i),t),n=M(e,"y",R(e.y,i.height,i),t),{sx:a,sy:o}=Ut(e,t),c=mi(e,M(e,"width",R(e.width,i.width,i,100),t),M(e,"height",R(e.height,i.height,i,100),t)),l=a*c.width,u=o*c.height,h=M(e,"rotation",_s(e.rotation??e.z_rotation,0),t),{skewX:f,skewY:p}=ei(e,t),m=M(e,"opacity",_s(e.opacity,1),t),g=Ie(e.x_anchor),y=Ie(e.y_anchor),{cx:w,cy:x}=Mt(r,n,l,u,g,y),b=Xe(e,t),S=b!==null||!t.modelMatrix.aff,v=Xt(t.modelMatrix,t.opacityFactor,w,x,h,m,l,u),T=S?ze(t.modelMatrix,w,x,l,u,h,f,p,b):void 0,C=vr(e,"fill_color",typeof e.fill_color=="string"?e.fill_color:void 0,t),P=Ga(C,v.opacity01),E=M(e,"border_radius",_s(e.border_radius,0),t),H=(typeof e.shape=="string"&&e.shape||"rectangle").toLowerCase()==="ellipse",Q=e.gradient?$x(e.gradient,v.opacity01):void 0,J=vr(e,"stroke_color",typeof e.stroke_color=="string"?e.stroke_color:void 0,t)??null,D=M(e,"stroke_width",_s(e.stroke_width,0),t),z=J&&D>0?Ga(J,v.opacity01):void 0;if(e.shadow&&typeof e.shadow.color=="string"){let K=Ga(e.shadow.color,v.opacity01),q=_s(e.shadow.offset_x,0),V=_s(e.shadow.offset_y,0),ie=Math.max(0,_s(e.shadow.blur,0));s.drawShapeShadow({cx:v.cx,cy:v.cy,width:S?l:v.width,height:S?u:v.height,rotation:v.rotation,skewX:f,skewY:p,transform:S?ze(t.modelMatrix,w+q,x+V,l+ie*2,u+ie*2,h,f,p,b):void 0,cornerRadius:E,shape:H?"ellipse":"rectangle",offsetX:q,offsetY:V,blur:ie,color:K})}let L=Q?null:Wi(e,t.time),re=Math.max(0,Math.min(1,v.opacity01)),te=L?qi(t,ze(t.worldMatrix,w,x,l,u,h,f,p,b),L,od(C,re),J&&D>0?od(J,re):void 0):null;s.drawShape({cx:v.cx,cy:v.cy,width:S?l:v.width,height:S?u:v.height,rotation:v.rotation,skewX:f,skewY:p,transform:T,color:P,gradient:Q,cornerRadius:E,shape:H?"ellipse":"rectangle",strokeColor:z,strokeWidth:z?D:0,blend:e.blend_mode,lit:te??void 0})}function od(e,t){let i=kt(typeof e=="string"?e:"#ffffff");return[i[0],i[1],i[2],i[3]*t]}function $x(e,t){let i=Math.max(0,Math.min(1,t)),s=e.stops.slice(0,4).map(r=>{let n=ft(r.color);return{offset:Math.max(0,Math.min(1,r.offset)),color:[n[0]*i,n[1]*i,n[2]*i,n[3]*i]}});return e.type==="linear"?{type:"linear",angle:((typeof e.angle=="number"?e.angle:180)-90)*Math.PI/180,stops:s}:{type:"radial",cx:typeof e.cx=="number"?e.cx:.5,cy:typeof e.cy=="number"?e.cy:.5,radius:typeof e.radius=="number"?e.radius:.5,stops:s}}function _s(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function Ga(e,t){let i=ft(typeof e=="string"?e:"#ffffff"),s=Math.max(0,Math.min(1,t));return[i[0]*s,i[1]*s,i[2]*s,i[3]*s]}var ld=/([MLHVCSQTZmlhvcsqtz])|(-?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?)/g,Br=new Map;function dd(e){let t=Br.get(e);if(t!==void 0)return t;if(Br.size>256&&Br.clear(),/[Aa]/.test(e))return Br.set(e,null),null;let i=[],s=[],r=[],n;for(ld.lastIndex=0;(n=ld.exec(e))!==null;)n[1]?(i.push(n[1]),r.push(n[1])):(r.push(s.length),s.push(parseFloat(n[2])));let a={skeleton:i.join(""),numbers:s,layout:r};return Br.set(e,a),a}function ud(e,t,i){let s=dd(e),r=dd(t);if(!s||!r||s.skeleton!==r.skeleton||s.numbers.length!==r.numbers.length)return null;let n=[];for(let a of s.layout)if(typeof a=="string")n.push(a);else{let o=s.numbers[a]+(r.numbers[a]-s.numbers[a])*i;n.push(String(Math.round(o*1e3)/1e3))}return n.join(" ")}var Ln=new Map;function Yx(e){Ln.size>256&&Ln.clear();let t=Ln.get(e);if(t!==void 0)return t;let i=0;try{let s=document.createElementNS("http://www.w3.org/2000/svg","path");s.setAttribute("d",e),i=s.getTotalLength()}catch{i=0}return(!Number.isFinite(i)||i<=0)&&(i=1e3),Ln.set(e,i),i}function fd(e,t,i,s){let{canvas:r,ctx:n}=s,a=e.view_box??[0,0,100,100],[o,c,l,u]=a;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,r.width,r.height),n.restore(),n.save(),n.scale(r.width/l,r.height/u),n.translate(-o,-c);let h=new Map;for(let p of e.gradients??[])h.set(p.id,p);let f=e.paths??[];for(let p=0;p<f.length;p++){let m=f[p],g=t[p*3]??0,y=t[p*3+1]??1,w=t[p*3+2]??0,x=i[p]??(typeof m.d=="string"?m.d:"");x&&Xx(n,m,x,g,y,w,h)}n.restore()}function Xx(e,t,i,s,r,n,a){let o=t.fill&&t.fill!=="none",c=t.stroke&&t.stroke!=="none"&&(t.stroke_width??0)>0;if(!o&&!c)return;let l=t.opacity??1;if(l<=0)return;let u=l<1;(u||t.clip_path)&&(e.save(),u&&(e.globalAlpha=l),t.clip_path&&e.clip(new Path2D(t.clip_path)));let h=new Path2D(i);if(o&&(e.fillStyle=hd(e,t.fill,a),e.fill(h)),c){let f=Math.max(0,Math.min(1,r)-Math.max(0,s));if(f>0)if(e.strokeStyle=hd(e,t.stroke,a),e.lineWidth=t.stroke_width,e.lineCap=t.stroke_linecap??"butt",e.lineJoin=t.stroke_linejoin??"miter",f>=1)e.stroke(h);else{let p=Yx(i),m=((Math.max(0,s)+n)%1+1)%1;e.setLineDash([f*p,p-f*p]),e.lineDashOffset=-m*p,e.stroke(h),e.setLineDash([]),e.lineDashOffset=0}}(u||t.clip_path)&&e.restore()}function hd(e,t,i){let s=t.match(/^url\\(#([^)]+)\\)$/);if(s){let r=s[1],n=i.get(r);if(!n)return"#ffffff";let a=e.createLinearGradient(n.x1,n.y1,n.x2,n.y2);for(let o of n.stops)a.addColorStop(Zx(o.offset),o.color);return a}return t}function Zx(e){return e<0?0:e>1?1:e}var pd=2,md=2048;function gd(e,t){let{canvas:i,backend:s,svgRasters:r}=t,n=e.paths;if(!n||n.length===0)return;let a=e.view_box??[0,0,100,100],[,,o,c]=a,l=M(e,"x",R(e.x,i.width,i),t),u=M(e,"y",R(e.y,i.height,i),t),{sx:h,sy:f}=Ut(e,t),p=mi(e,M(e,"width",R(e.width,i.width,i,o),t),M(e,"height",R(e.height,i.height,i,c),t)),m=h*p.width,g=f*p.height,y=M(e,"rotation",Wa(e.rotation??e.z_rotation,0),t),w=M(e,"opacity",Wa(e.opacity,1),t),x=Ie(e.x_anchor),b=Ie(e.y_anchor),{cx:S,cy:v}=Mt(l,u,m,g,x,b),T=Xt(t.modelMatrix,t.opacityFactor,S,v,y,w,m,g),C=Jx(T.opacity01);if(C<=0||T.width<=0||T.height<=0)return;let P=t.timeOffset+Wa(e.time,0),E=t.time-P,U=n.flatMap(V=>Qx(V,E)),H=n.map(V=>Kx(V.d,E)),Q=Math.min(md,Math.max(1,Math.ceil(Math.max(o,m)*pd))),J=Math.min(md,Math.max(1,Math.ceil(Math.max(c,g)*pd))),D=typeof e.id=="string"?e.id:\`__svg_\${JSON.stringify(a)}\`,z=r.get(D);if(!z||z.canvas.width!==Q||z.canvas.height!==J){let V=new OffscreenCanvas(Q,J),ie=V.getContext("2d");if(!ie)return;let pe=s.createTexture(V);z={canvas:V,ctx:ie,texture:pe},r.set(D,z)}let L={trims:U,ds:H,pathsRef:n,gradientsRef:e.gradients,rasterW:Q,rasterH:J};ey(z.lastSignature,L)||(fd(e,U,H,z),s.updateTexture(z.texture,z.canvas),z.lastSignature=L);let re=Xe(e,t),te=re!==null||!t.modelMatrix.aff,{skewX:K,skewY:q}=ei(e,t);s.drawTexturedQuad({cx:T.cx,cy:T.cy,width:te?m:T.width,height:te?g:T.height,rotation:T.rotation,skewX:K,skewY:q,transform:te?ze(t.modelMatrix,S,v,m,g,y,K,q,re):void 0,texture:z.texture,tint:[C,C,C,C],blend:e.blend_mode})}function Qx(e,t){let i=r=>{if(r!==void 0){if(typeof r=="number")return r;if(ai(r))return oi(r,{t,dur:0,i:0,n:1,value:0});if(Array.isArray(r))return Ze(r,t)}};return e.trim_start!==void 0||e.trim_end!==void 0||e.trim_offset!==void 0?[Va(i(e.trim_start)??0),Va(i(e.trim_end)??1),i(e.trim_offset)??0]:[0,Va(i(e.stroke_progress)??1),0]}function Va(e){return Math.max(0,Math.min(1,e))}function Kx(e,t){if(typeof e=="string")return e;if(!Array.isArray(e)||e.length===0)return"";let i=n=>typeof n.time=="number"?n.time:parseFloat(String(n.time))||0,s=e[0],r=e[e.length-1];if(t<=i(s))return String(s.value);if(t>=i(r))return String(r.value);for(let n=0;n<e.length-1;n++){let a=e[n],o=e[n+1],c=i(a),l=i(o);if(t>=c&&t<=l){let u=l-c,h=yt(o.easing,u>0?(t-c)/u:1);return ud(String(a.value),String(o.value),h)??String(a.value)}}return String(r.value)}function Wa(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function Jx(e){return e<0?0:e>1?1:e}function ey(e,t){if(!e||e.pathsRef!==t.pathsRef||e.gradientsRef!==t.gradientsRef||e.rasterW!==t.rasterW||e.rasterH!==t.rasterH||e.trims.length!==t.trims.length)return!1;for(let i=0;i<e.trims.length;i++)if(e.trims[i]!==t.trims[i])return!1;if(e.ds.length!==t.ds.length)return!1;for(let i=0;i<e.ds.length;i++)if(e.ds[i]!==t.ds[i])return!1;return!0}var ty=[1,1,1,1];function xd(e,t){let{canvas:i,backend:s,videos:r}=t,n=String(e.source??"");if(!n)return;let a=r.get(n);if(!a)return;a.video&&a.video.readyState>=2&&a.video.currentTime!==a.lastUploadedTime&&(s.updateTexture(a.texture,a.video),a.lastUploadedTime=a.video.currentTime);let o=M(e,"x",R(e.x,i.width,i),t),c=M(e,"y",R(e.y,i.height,i),t),{sx:l,sy:u}=Ut(e,t),h=mi(e,M(e,"width",R(e.width,i.width,i,a.width),t),M(e,"height",R(e.height,i.height,i,a.height),t)),f=l*h.width,p=u*h.height,m=M(e,"rotation",$s(e.rotation??e.z_rotation,0),t),g=M(e,"opacity",$s(e.opacity,1),t),y=Ie(e.x_anchor),w=Ie(e.y_anchor),{cx:x,cy:b}=Mt(o,c,f,p,y,w),S=Xt(t.modelMatrix,t.opacityFactor,x,b,m,g,f,p),v=Math.max(0,Math.min(1,S.opacity01)),T=[v,v,v,v],C=Xe(e,t),P=C!==null||!t.modelMatrix.aff,E=Rn(e.fit,P?f:S.width,P?p:S.height,a.width,a.height,iy(e,t)),{skewX:U,skewY:H}=ei(e,t),Q=Wi(e,t.time),J=Q?qi(t,ze(t.worldMatrix,x,b,E.drawWidth,E.drawHeight,m,U,H,C),Q,ty):null;s.drawTexturedQuad({cx:S.cx,cy:S.cy,width:E.drawWidth,height:E.drawHeight,rotation:S.rotation,skewX:U,skewY:H,transform:P?ze(t.modelMatrix,x,b,E.drawWidth,E.drawHeight,m,U,H,C):void 0,texture:a.texture,uvRect:E.uvRect,tint:T,blend:e.blend_mode,lit:J??void 0})}var _d=["crop_x","crop_y","crop_width","crop_height"];function iy(e,t){let i=_d.some(r=>e[r]!==void 0),s=(e.keyframe_animations??[]).some(r=>_d.includes(r.property));if(!(!i&&!s))return{x:M(e,"crop_x",$s(e.crop_x,0),t),y:M(e,"crop_y",$s(e.crop_y,0),t),width:M(e,"crop_width",$s(e.crop_width,1),t),height:M(e,"crop_height",$s(e.crop_height,1),t)}}function $s(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);if(Number.isFinite(i))return i}return t}function On(e,t){let i=typeof e.duration=="number"?e.duration:1/0;t._dispatch=bd;let s=[...e.elements].sort((r,n)=>yd(n)-yd(r));t.depthSort&&(s=Un(s,t));for(let r of s)if(r.visible!==!1&&ly(r,t.time,i))try{bd(r,t)}catch(n){console.error("[clipkit] Element render failed:",r.type,r.id,n)}}function yd(e){return typeof e.layer=="number"&&Number.isFinite(e.layer)?e.layer:Number.MAX_SAFE_INTEGER}function bd(e,t){let i=ea(e.blend_mode);if(sy(e)||e.effects&&e.effects.length>0||i){let s=ry(e,t),r=ny(e,t);if(s||r.length>0||i){oy(e,t,s,r);return}}Sd(e,t)}var vd=["blur_radius","brightness","contrast","saturation","hue_rotate"];function sy(e){for(let i of vd)if(e[i]!==void 0)return!0;let t=e.keyframe_animations;if(t){for(let i of t)if(vd.includes(i.property))return!0}return!1}function ry(e,t){let i=Math.max(0,Ar(e,"blur_radius",0,t)),s=Math.max(0,Ar(e,"brightness",1,t)),r=Math.max(0,Ar(e,"contrast",1,t)),n=Math.max(0,Ar(e,"saturation",1,t)),a=Ar(e,"hue_rotate",0,t);return i===0&&s===1&&r===1&&n===1&&a===0?null:{blur:i,brightness:s,contrast:r,saturation:n,hueRotate:a}}function Ar(e,t,i,s){let r=e[t],n=i;if(typeof r=="number"&&Number.isFinite(r))n=r;else if(Array.isArray(r)){let a=s.timeOffset+Ys(e.time);n=Ze(r,s.time-a)}return M(e,t,n,s)}function ny(e,t){let i=e.effects;if(!i||i.length===0)return[];let s=t.timeOffset+Ys(e.time),r=t.time-s,n=(o,c)=>typeof o=="number"&&Number.isFinite(o)?o:Array.isArray(o)?Ze(o,r):c,a=[];for(let o of i)switch(o.type){case"pixelate":a.push({kind:"stylize",mode:"pixelate",p0:Math.max(1,n(o.cell_size,8))});break;case"dither":a.push({kind:"stylize",mode:"dither",p0:Math.max(2,n(o.levels,4)),p1:Math.max(1,n(o.pixel_size,2))});break;case"halftone":a.push({kind:"stylize",mode:"halftone",p0:Math.max(2,n(o.cell_size,8)),p1:n(o.angle,45)});break;case"ascii":a.push({kind:"stylize",mode:"ascii",p0:Math.max(4,n(o.cell_size,12))});break;case"glow":{let c=kt(typeof o.color=="string"?o.color:"#FFFFFF");a.push({kind:"stylize",mode:"glow",p0:Math.max(0,n(o.intensity,1)),auxBlur:Math.max(1,n(o.radius,20)),tint:[c[0]*c[3],c[1]*c[3],c[2]*c[3],c[3]]});break}case"drop_shadow":{let c=kt(typeof o.color=="string"?o.color:"#000000"),l=Math.max(0,Math.min(1,n(o.opacity,.6)))*c[3];a.push({kind:"stylize",mode:"drop_shadow",p0:n(o.offset_x,0),p1:n(o.offset_y,12),auxBlur:Math.max(.5,n(o.blur,18)),tint:[c[0]*l,c[1]*l,c[2]*l,l]});break}case"stroke":{let c=kt(typeof o.color=="string"?o.color:"#FFFFFF");a.push({kind:"stylize",mode:"stroke",p0:Math.max(1,n(o.width,4)),tint:[c[0]*c[3],c[1]*c[3],c[2]*c[3],c[3]]});break}case"chroma_key":{let c=kt(typeof o.color=="string"?o.color:"#00FF00");a.push({kind:"stylize",mode:"chroma_key",p0:Math.max(0,n(o.tolerance,.18)),p1:Math.max(0,n(o.softness,.1)),tint:[c[0],c[1],c[2],Math.max(0,Math.min(1,n(o.spill,.5)))]});break}case"luma_key":a.push({kind:"stylize",mode:"luma_key",p0:Math.max(0,Math.min(1,n(o.threshold,.5))),p1:Math.max(0,n(o.softness,.1)),tint:[o.invert===!0?1:0,0,0,0]});break;case"levels":{let c=l=>Math.max(0,Math.min(1,l));a.push({kind:"stylize",mode:"levels",p0:Math.max(.01,n(o.gamma,1)),tint:[c(n(o.in_black,0)),c(n(o.in_white,1)),c(n(o.out_black,0)),c(n(o.out_white,1))]});break}case"lut":{let c=typeof o.source=="string"?o.source:"",l=c?t.luts.get(c):void 0;if(!l){$().warn(\`lut not loaded \\u2014 pass skipped: \${c}\`);break}a.push({kind:"stylize",mode:"lut",p0:l.size,p1:Math.max(0,Math.min(1,n(o.intensity,1))),lutTex:l.texture});break}case"fractal_noise":{let c=Math.max(.001,n(o.scale,100));a.push({kind:"stylize",mode:"fractal_noise",p0:c,p1:n(o.evolution,0),tint:[n(o.offset_x,0)/c,n(o.offset_y,0)/c,Math.max(1,Math.min(8,Math.round(typeof o.octaves=="number"?o.octaves:4))),Math.max(0,Math.round(typeof o.seed=="number"?o.seed:0))]});break}case"turbulent_displace":a.push({kind:"stylize",mode:"turbulent_displace",p0:Math.max(0,n(o.amount,16)),p1:Math.max(1,n(o.scale,120)),tint:[n(o.evolution,0),Math.max(1,Math.min(8,Math.round(typeof o.octaves=="number"?o.octaves:2))),Math.max(0,Math.round(typeof o.seed=="number"?o.seed:0)),0]});break;case"glass":{let c=Math.max(0,n(o.edge_highlight,.35));a.push({kind:"glass",blur:Math.max(0,n(o.blur_radius,0)),refract:Math.abs(n(o.refraction,21))/30,chroma:Math.max(0,n(o.dispersion,.05)),edgeHL:c*(.05/.35),specular:0,fresnel:c*(1/.35),saturation:Math.max(0,n(o.backdrop_saturation,1))-1,zRadius:Math.max(1,n(o.edge_width,40)),bevelMode:o.mode==="dome"?1:0,shadowAlpha:Math.max(0,n(o.shadow,.3)),tint:typeof o.tint=="string"?kt(o.tint):[0,0,0,0]});break}default:$().warn(\`unknown effect type \\u2014 skipped: \${String(o.type)}\`)}return a}var wd=new WeakMap;function ay(e){let t=wd.get(e);return t||(t=e.createTexture(al()),wd.set(e,t)),t}function oy(e,t,i,s){let{backend:r}=t,n=t.surfaceWidth,a=t.surfaceHeight,o=e.id??"__fx__",c={...e,blur_radius:void 0,brightness:void 0,contrast:void 0,saturation:void 0,effects:void 0,blend_mode:void 0},l=ea(e.blend_mode)?e.blend_mode:void 0,u=null,h=!1;(l||s.some(x=>x.kind==="glass"))&&(u=xs(t,\`\${o}::bd\`,n,a),h=r.copySurfaceTo(u.target).flippedY);let f=xs(t,\`\${o}::fx\`,n,a);r.pushTarget(f.target,[0,0,0,0]);try{Sd(c,t)}finally{r.popTarget()}let p=n/2,m=a/2,g=[];i&&g.push((x,b)=>{let S=i.blur>0?qa(t,\`\${o}::blur\`,x,i.blur,n,a):x;r.drawFilteredQuad({cx:p,cy:m,width:n,height:a,texture:S,blurRadius:0,blurDir:[0,1],brightness:i.brightness,contrast:i.contrast,saturation:i.saturation,hueRotate:i.hueRotate,blend:b})});for(let x of s)x.kind==="stylize"?g.push((b,S)=>r.drawStylizedQuad({cx:p,cy:m,width:n,height:a,texture:b,mode:x.mode,p0:x.p0,p1:x.p1,aux:x.mode==="ascii"?ay(r):x.lutTex?x.lutTex:x.auxBlur?qa(t,\`\${o}::style\`,b,x.auxBlur,n,a):void 0,tint:x.tint,blend:S})):g.push((b,S)=>{if(e.type!=="shape"){$().warn("glass applies to shape elements \\u2014 effect skipped"),r.drawTexturedQuad({cx:p,cy:m,width:n,height:a,rotation:0,texture:b,blend:S});return}let v=u,T=x.blur>0?qa(t,\`\${o}::gfrost\`,v.target.texture,x.blur,n,a):v.target.texture,C=cy(e,t);r.drawGlassQuad({cx:p,cy:m,width:n,height:a,backdrop:T,backdropSharp:v.target.texture,backdropFlipY:h,paneCx:C.cx,paneCy:C.cy,paneHalfW:C.width/2,paneHalfH:C.height/2,cornerRadius:C.radius,rotation:C.rotation,paneHomography:C.paneH,zRadius:x.zRadius,refract:x.refract,chroma:x.chroma,edgeHighlight:x.edgeHL,specular:x.specular,fresnel:x.fresnel,saturation:x.saturation,tint:x.tint,alpha:C.alpha,bevelMode:x.bevelMode,shadowAlpha:x.shadowAlpha,shadowSpread:10,shadowOffY:1,blend:S})});let y=f.target.texture,w=!1;if(l){for(let x=0;x<g.length;x++){let b=w?f:xs(t,\`\${o}::fx-scratch\`,n,a);r.pushTarget(b.target,[0,0,0,0]);try{g[x](y,void 0)}finally{r.popTarget()}y=b.target.texture,w=!w}r.drawBackdropBlend({src:y,backdrop:u.target.texture,mode:l,width:n,height:a,backdropFlipY:h});return}for(let x=0;x<g.length;x++)if(x===g.length-1)g[x](y,e.blend_mode);else{let S=w?f:xs(t,\`\${o}::fx-scratch\`,n,a);r.pushTarget(S.target,[0,0,0,0]);try{g[x](y,void 0)}finally{r.popTarget()}y=S.target.texture,w=!w}}function qa(e,t,i,s,r,n){let{backend:a}=e;if(s<=0)return i;let o=1;for(;s/o>4&&o<16;)o*=2;let c=i,l=r,u=n;for(let m=1;m<o;m*=2){let g=Math.max(1,Math.round(l/2)),y=Math.max(1,Math.round(u/2)),w=xs(e,\`\${t}::ds\${m}\`,g,y);a.pushTarget(w.target,[0,0,0,0]);try{a.drawTexturedQuad({cx:g/2,cy:y/2,width:g,height:y,rotation:0,texture:c})}finally{a.popTarget()}c=w.target.texture,l=g,u=y}let h=s/o,f=xs(e,\`\${t}::bh\`,l,u);a.pushTarget(f.target,[0,0,0,0]);try{a.drawFilteredQuad({cx:l/2,cy:u/2,width:l,height:u,texture:c,blurRadius:h,blurDir:[1,0],brightness:1,contrast:1,saturation:1})}finally{a.popTarget()}let p=xs(e,\`\${t}::bv\`,l,u);a.pushTarget(p.target,[0,0,0,0]);try{a.drawFilteredQuad({cx:l/2,cy:u/2,width:l,height:u,texture:f.target.texture,blurRadius:h,blurDir:[0,1],brightness:1,contrast:1,saturation:1})}finally{a.popTarget()}return p.target.texture}function cy(e,t){let{canvas:i}=t,s=M(e,"x",R(e.x,i.width,i),t),r=M(e,"y",R(e.y,i.height,i),t),{sx:n,sy:a}=Ut(e,t),o=mi(e,M(e,"width",R(e.width,i.width,i,100),t),M(e,"height",R(e.height,i.height,i,100),t)),c=n*o.width,l=a*o.height,u=M(e,"rotation",Ys(e.rotation??e.z_rotation),t),h=M(e,"opacity",typeof e.opacity=="number"?e.opacity:1,t),f=Ie(e.x_anchor),p=Ie(e.y_anchor),{cx:m,cy:g}=Mt(s,r,c,l,f,p),y=String(e.shape??"rectangle").toLowerCase()==="ellipse",w=Xe(e,t);if(w!==null||!t.modelMatrix.aff){let S=Qe(t.modelMatrix,{e:lr(m,g,2,2,u,0,0,w?.xRot??0,w?.yRot??0,w?.z??0),aff:!1}).e,v=[S[0],S[1],S[3],-S[4],-S[5],-S[7],S[12],S[13],S[15]],T=y?Math.min(c,l)/2:Ys(e.border_radius);return{cx:0,cy:0,width:c,height:l,rotation:0,radius:T,paneH:v,alpha:Math.max(0,Math.min(1,h*t.opacityFactor))}}let x=Xt(t.modelMatrix,t.opacityFactor,m,g,u,h,c,l),b=y?Math.min(x.width,x.height)/2:Ys(e.border_radius);return{cx:x.cx,cy:x.cy,width:x.width,height:x.height,rotation:x.rotation,radius:b,alpha:Math.max(0,Math.min(1,x.opacity01))}}function xs(e,t,i,s){let r=e.groupTargets.get(t);return r&&(r.width!==i||r.height!==s)&&(e.backend.destroyRenderTarget(r.target),r=void 0),r||(r={target:e.backend.createRenderTarget(i,s),width:i,height:s},e.groupTargets.set(t,r)),r.lastTouched=e.frameIndex,r}function Sd(e,t){switch(e.type){case"shape":e.paths?gd(e,t):cd(e,t);return;case"text":jl(e,t);return;case"image":nd(e,t);return;case"video":xd(e,t);return;case"audio":return;case"caption":Zl(e,t);return;case"particles":ad(e,t);return;case"group":td(e,t);return}}function ly(e,t,i){let s=Ys(e.time),r=dy(e.duration,i-s),n=s+r;return t>=s&&t<=n}function Ys(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=parseFloat(e);return Number.isFinite(t)?t:0}return 0}function dy(e,t){if(e==="auto"||e==="end"||e==null)return t;if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);return Number.isFinite(i)?i:t}return t}var Dn={e:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],aff:!0};function ys(e,t,i=0){return e===void 0?i:ai(e)?oi(e,{t,dur:0,i:0,n:1,value:i}):Array.isArray(e)?Ze(e,t):e}function ja(e,t,i){return{e:[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1],aff:!1}}function uy(e,t,i){let s=e*Math.PI/180,r=t*Math.PI/180,n=i*Math.PI/180,a=Math.cos(s),o=Math.sin(s),c=Math.cos(r),l=Math.sin(r),u=Math.cos(n),h=Math.sin(n),f=(y,w,x)=>{let b=w*u-x*h,S=w*h+x*u,v=y*c+S*l,T=-y*l+S*c;return[v*a-b*o,v*o+b*a,T]},p=f(1,0,0),m=f(0,1,0),g=f(0,0,1);return{e:[p[0],m[0],g[0],0,p[1],m[1],g[1],0,p[2],m[2],g[2],0,0,0,0,1],aff:!1}}function $a(e,t,i){let s=ys(e.perspective,t,.001);(!Number.isFinite(s)||s<.001)&&(s=.001);let r=e.origin_x!==void 0?R(e.origin_x,i.width,i):i.width/2,n=e.origin_y!==void 0?R(e.origin_y,i.height,i):i.height/2,a={e:[1,0,0,0,0,1,0,0,-r/s,-n/s,1,-1/s,0,0,0,1],aff:!1},o=ys(e.x,t),c=ys(e.y,t),l=ys(e.z,t),u=ys(e.x_rotation,t),h=ys(e.y_rotation,t),f=ys(e.z_rotation,t);if(o===0&&c===0&&l===0&&u===0&&h===0&&f===0)return a;let p=Qe(Qe(Qe(ja(r,n,0),uy(f,h,u)),ja(-o,-c,-l)),ja(-r,-n,0));return Qe(a,p)}var ro=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},_=(e,t,i)=>(ro(e,t,"read from private field"),i?i.call(e):t.get(e)),fe=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},mt=(e,t,i,s)=>(ro(e,t,"write to private field"),s?s.call(e,i):t.set(e,i),i),hy=(e,t,i,s)=>({set _(r){mt(e,t,r,i)},get _(){return _(e,t,s)}}),be=(e,t,i)=>(ro(e,t,"access private method"),i),ke=new Uint8Array(8),bi=new DataView(ke.buffer),lt=e=>[(e%256+256)%256],Ce=e=>(bi.setUint16(0,e,!1),[ke[0],ke[1]]),fy=e=>(bi.setInt16(0,e,!1),[ke[0],ke[1]]),Td=e=>(bi.setUint32(0,e,!1),[ke[1],ke[2],ke[3]]),N=e=>(bi.setUint32(0,e,!1),[ke[0],ke[1],ke[2],ke[3]]),py=e=>(bi.setInt32(0,e,!1),[ke[0],ke[1],ke[2],ke[3]]),Ts=e=>(bi.setUint32(0,Math.floor(e/2**32),!1),bi.setUint32(4,e,!1),[ke[0],ke[1],ke[2],ke[3],ke[4],ke[5],ke[6],ke[7]]),no=e=>(bi.setInt16(0,2**8*e,!1),[ke[0],ke[1]]),xi=e=>(bi.setInt32(0,2**16*e,!1),[ke[0],ke[1],ke[2],ke[3]]),Ya=e=>(bi.setInt32(0,2**30*e,!1),[ke[0],ke[1],ke[2],ke[3]]),ti=(e,t=!1)=>{let i=Array(e.length).fill(null).map((s,r)=>e.charCodeAt(r));return t&&i.push(0),i},qn=e=>e&&e[e.length-1],ao=e=>{let t;for(let i of e)(!t||i.presentationTimestamp>t.presentationTimestamp)&&(t=i);return t},yi=(e,t,i=!0)=>{let s=e*t;return i?Math.round(s):s},Ed=e=>{let t=e*(Math.PI/180),i=Math.cos(t),s=Math.sin(t);return[i,s,0,-s,i,0,0,0,1]},Ud=Ed(0),Bd=e=>[xi(e[0]),xi(e[1]),Ya(e[2]),xi(e[3]),xi(e[4]),Ya(e[5]),xi(e[6]),xi(e[7]),Ya(e[8])],zr=e=>!e||typeof e!="object"?e:Array.isArray(e)?e.map(zr):Object.fromEntries(Object.entries(e).map(([t,i])=>[t,zr(i)])),Ks=e=>e>=0&&e<2**32,it=(e,t,i)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:i}),Ve=(e,t,i,s,r)=>it(e,[lt(t),Td(i),s??[]],r),my=e=>{let t=512;return e.fragmented?it("ftyp",[ti("iso5"),N(t),ti("iso5"),ti("iso6"),ti("mp41")]):it("ftyp",[ti("isom"),N(t),ti("isom"),e.holdsAvc?ti("avc1"):[],ti("mp41")])},Xa=e=>({type:"mdat",largeSize:e}),gy=e=>({type:"free",size:e}),Nn=(e,t,i=!1)=>it("moov",null,[_y(t,e),...e.map(s=>xy(s,t)),i?Xy(e):null]),_y=(e,t)=>{let i=yi(Math.max(0,...t.filter(a=>a.samples.length>0).map(a=>{let o=ao(a.samples);return o.presentationTimestamp+o.duration})),Ka),s=Math.max(...t.map(a=>a.id))+1,r=!Ks(e)||!Ks(i),n=r?Ts:N;return Ve("mvhd",+r,0,[n(e),n(e),N(Ka),n(i),xi(1),no(1),Array(10).fill(0),Bd(Ud),Array(24).fill(0),N(s)])},xy=(e,t)=>it("trak",null,[yy(e,t),by(e,t)]),yy=(e,t)=>{let i=ao(e.samples),s=yi(i?i.presentationTimestamp+i.duration:0,Ka),r=!Ks(t)||!Ks(s),n=r?Ts:N,a;return e.info.type==="video"?a=typeof e.info.rotation=="number"?Ed(e.info.rotation):e.info.rotation:a=Ud,Ve("tkhd",+r,3,[n(t),n(t),N(e.id),N(0),n(s),Array(8).fill(0),Ce(0),Ce(0),no(e.info.type==="audio"?1:0),Ce(0),Bd(a),xi(e.info.type==="video"?e.info.width:0),xi(e.info.type==="video"?e.info.height:0)])},by=(e,t)=>it("mdia",null,[vy(e,t),wy(e.info.type==="video"?"vide":"soun"),Sy(e)]),vy=(e,t)=>{let i=ao(e.samples),s=yi(i?i.presentationTimestamp+i.duration:0,e.timescale),r=!Ks(t)||!Ks(s),n=r?Ts:N;return Ve("mdhd",+r,0,[n(t),n(t),N(e.timescale),n(s),Ce(21956),Ce(0)])},wy=e=>Ve("hdlr",0,0,[ti("mhlr"),ti(e),N(0),N(0),N(0),ti("mp4-muxer-hdlr",!0)]),Sy=e=>it("minf",null,[e.info.type==="video"?ky():Ty(),Ey(),Ay(e)]),ky=()=>Ve("vmhd",0,1,[Ce(0),Ce(0),Ce(0),Ce(0)]),Ty=()=>Ve("smhd",0,0,[Ce(0),Ce(0)]),Ey=()=>it("dinf",null,[Uy()]),Uy=()=>Ve("dref",0,0,[N(1)],[By()]),By=()=>Ve("url ",0,1),Ay=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(i=>i.sampleCompositionTimeOffset!==0);return it("stbl",null,[Cy(e),Vy(e),Wy(e),qy(e),jy(e),$y(e),t?Yy(e):null])},Cy=e=>Ve("stsd",0,0,[N(1)],[e.info.type==="video"?My(nb[e.info.codec],e):Ny(ob[e.info.codec],e)]),My=(e,t)=>it(e,[Array(6).fill(0),Ce(1),Ce(0),Ce(0),Array(12).fill(0),Ce(t.info.width),Ce(t.info.height),N(4718592),N(4718592),N(0),Ce(1),Array(32).fill(0),Ce(24),fy(65535)],[ab[t.info.codec](t),t.info.decoderConfig.colorSpace?Ry(t):null]),zy={bt709:1,bt470bg:5,smpte170m:6},Py={bt709:1,smpte170m:6,"iec61966-2-1":13},Iy={rgb:0,bt709:1,bt470bg:5,smpte170m:6},Ry=e=>it("colr",[ti("nclx"),Ce(zy[e.info.decoderConfig.colorSpace.primaries]),Ce(Py[e.info.decoderConfig.colorSpace.transfer]),Ce(Iy[e.info.decoderConfig.colorSpace.matrix]),lt((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Fy=e=>e.info.decoderConfig&&it("avcC",[...new Uint8Array(e.info.decoderConfig.description)]),Ly=e=>e.info.decoderConfig&&it("hvcC",[...new Uint8Array(e.info.decoderConfig.description)]),Oy=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig;if(!t.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let i=t.codec.split("."),s=Number(i[1]),r=Number(i[2]),o=(Number(i[3])<<4)+(0<<1)+Number(t.colorSpace.fullRange);return Ve("vpcC",1,0,[lt(s),lt(r),lt(o),lt(2),lt(2),lt(2),Ce(0)])},Dy=()=>{let i=(1<<7)+1;return it("av1C",[i,0,0,0])},Ny=(e,t)=>it(e,[Array(6).fill(0),Ce(1),Ce(0),Ce(0),N(0),Ce(t.info.numberOfChannels),Ce(16),Ce(0),Ce(0),xi(t.info.sampleRate)],[cb[t.info.codec](t)]),Hy=e=>{let t=new Uint8Array(e.info.decoderConfig.description);return Ve("esds",0,0,[N(58753152),lt(32+t.byteLength),Ce(1),lt(0),N(75530368),lt(18+t.byteLength),lt(64),lt(21),Td(0),N(130071),N(130071),N(92307584),lt(t.byteLength),...t,N(109084800),lt(1),lt(2)])},Gy=e=>{let t=3840,i=0,s=e.info.decoderConfig?.description;if(s){if(s.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");let r=ArrayBuffer.isView(s)?new DataView(s.buffer,s.byteOffset,s.byteLength):new DataView(s);t=r.getUint16(10,!0),i=r.getInt16(14,!0)}return it("dOps",[lt(0),lt(e.info.numberOfChannels),Ce(t),N(e.info.sampleRate),no(i),lt(0)])},Vy=e=>Ve("stts",0,0,[N(e.timeToSampleTable.length),e.timeToSampleTable.map(t=>[N(t.sampleCount),N(t.sampleDelta)])]),Wy=e=>{if(e.samples.every(i=>i.type==="key"))return null;let t=[...e.samples.entries()].filter(([,i])=>i.type==="key");return Ve("stss",0,0,[N(t.length),t.map(([i])=>N(i+1))])},qy=e=>Ve("stsc",0,0,[N(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(t=>[N(t.firstChunk),N(t.samplesPerChunk),N(1)])]),jy=e=>Ve("stsz",0,0,[N(0),N(e.samples.length),e.samples.map(t=>N(t.size))]),$y=e=>e.finalizedChunks.length>0&&qn(e.finalizedChunks).offset>=2**32?Ve("co64",0,0,[N(e.finalizedChunks.length),e.finalizedChunks.map(t=>Ts(t.offset))]):Ve("stco",0,0,[N(e.finalizedChunks.length),e.finalizedChunks.map(t=>N(t.offset))]),Yy=e=>Ve("ctts",0,0,[N(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(t=>[N(t.sampleCount),N(t.sampleCompositionTimeOffset)])]),Xy=e=>it("mvex",null,e.map(Zy)),Zy=e=>Ve("trex",0,0,[N(e.id),N(1),N(0),N(0),N(0)]),kd=(e,t)=>it("moof",null,[Qy(e),...t.map(Ky)]),Qy=e=>Ve("mfhd",0,0,[N(e)]),Ad=e=>{let t=0,i=0,s=0,r=0,n=e.type==="delta";return i|=+n,n?t|=1:t|=2,t<<24|i<<16|s<<8|r},Ky=e=>it("traf",null,[Jy(e),eb(e),tb(e)]),Jy=e=>{let t=0;t|=8,t|=16,t|=32,t|=131072;let i=e.currentChunk.samples[1]??e.currentChunk.samples[0],s={duration:i.timescaleUnitsToNextSample,size:i.size,flags:Ad(i)};return Ve("tfhd",0,t,[N(e.id),N(s.duration),N(s.size),N(s.flags)])},eb=e=>Ve("tfdt",1,0,[Ts(yi(e.currentChunk.startTimestamp,e.timescale))]),tb=e=>{let t=e.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),i=e.currentChunk.samples.map(g=>g.size),s=e.currentChunk.samples.map(Ad),r=e.currentChunk.samples.map(g=>yi(g.presentationTimestamp-g.decodeTimestamp,e.timescale)),n=new Set(t),a=new Set(i),o=new Set(s),c=new Set(r),l=o.size===2&&s[0]!==s[1],u=n.size>1,h=a.size>1,f=!l&&o.size>1,p=c.size>1||[...c].some(g=>g!==0),m=0;return m|=1,m|=4*+l,m|=256*+u,m|=512*+h,m|=1024*+f,m|=2048*+p,Ve("trun",1,m,[N(e.currentChunk.samples.length),N(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?N(s[0]):[],e.currentChunk.samples.map((g,y)=>[u?N(t[y]):[],h?N(i[y]):[],f?N(s[y]):[],p?py(r[y]):[]])])},ib=e=>it("mfra",null,[...e.map(sb),rb()]),sb=(e,t)=>Ve("tfra",1,0,[N(e.id),N(63),N(e.finalizedChunks.length),e.finalizedChunks.map(s=>[Ts(yi(s.startTimestamp,e.timescale)),Ts(s.moofOffset),N(t+1),N(1),N(1)])]),rb=()=>Ve("mfro",0,0,[N(0)]),nb={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},ab={avc:Fy,hevc:Ly,vp9:Oy,av1:Dy},ob={aac:"mp4a",opus:"Opus"},cb={aac:Hy,opus:Gy},KE=Symbol("isTarget"),Qn=class{},oo=class extends Qn{constructor(){super(...arguments),this.buffer=null}},Cd=class extends Qn{constructor(e){if(super(),this.options=e,typeof e!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(e.onData){if(typeof e.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(e.onData.length<2)throw new TypeError("options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs.")}if(e.chunked!==void 0&&typeof e.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.")}},lb=class extends Qn{constructor(e,t){if(super(),this.stream=e,this.options=t,!(e instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(t!==void 0&&typeof t!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(t&&t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},bs,Xs,Md=class{constructor(){this.pos=0,fe(this,bs,new Uint8Array(8)),fe(this,Xs,new DataView(_(this,bs).buffer)),this.offsets=new WeakMap}seek(e){this.pos=e}writeU32(e){_(this,Xs).setUint32(0,e,!1),this.write(_(this,bs).subarray(0,4))}writeU64(e){_(this,Xs).setUint32(0,Math.floor(e/2**32),!1),_(this,Xs).setUint32(4,e,!1),this.write(_(this,bs).subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)_(this,Xs).setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.write(_(this,bs));e.length%8!==0&&this.write(_(this,bs).subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.pos),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.write(e.contents);else{let t=this.pos;if(this.writeBoxHeader(e,0),e.contents&&this.write(e.contents),e.children)for(let r of e.children)r&&this.writeBox(r);let i=this.pos,s=e.size??i-t;this.seek(t),this.writeBoxHeader(e,s),this.seek(i)}}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.pos;this.seek(this.offsets.get(e)),this.writeBox(e),this.seek(t)}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 i of e.children)i&&(t+=this.measureBox(i));return t}}};bs=new WeakMap;Xs=new WeakMap;var Hn,ks,Lr,Cr,Gn,Za,db=class extends Md{constructor(e){super(),fe(this,Gn),fe(this,Hn,void 0),fe(this,ks,new ArrayBuffer(2**16)),fe(this,Lr,new Uint8Array(_(this,ks))),fe(this,Cr,0),mt(this,Hn,e)}write(e){be(this,Gn,Za).call(this,this.pos+e.byteLength),_(this,Lr).set(e,this.pos),this.pos+=e.byteLength,mt(this,Cr,Math.max(_(this,Cr),this.pos))}finalize(){be(this,Gn,Za).call(this,this.pos),_(this,Hn).buffer=_(this,ks).slice(0,Math.max(_(this,Cr),this.pos))}};Hn=new WeakMap;ks=new WeakMap;Lr=new WeakMap;Cr=new WeakMap;Gn=new WeakSet;Za=function(e){let t=_(this,ks).byteLength;for(;t<e;)t*=2;if(t===_(this,ks).byteLength)return;let i=new ArrayBuffer(t),s=new Uint8Array(i);s.set(_(this,Lr),0),mt(this,ks,i),mt(this,Lr,s)};var ub=2**24,hb=2,Pr,vs,Mr,Ci,Vt,jn,Qa,co,zd,lo,Pd,Ir,$n,uo=class extends Md{constructor(e){super(),fe(this,jn),fe(this,co),fe(this,lo),fe(this,Ir),fe(this,Pr,void 0),fe(this,vs,[]),fe(this,Mr,void 0),fe(this,Ci,void 0),fe(this,Vt,[]),mt(this,Pr,e),mt(this,Mr,e.options?.chunked??!1),mt(this,Ci,e.options?.chunkSize??ub)}write(e){_(this,vs).push({data:e.slice(),start:this.pos}),this.pos+=e.byteLength}flush(){if(_(this,vs).length===0)return;let e=[],t=[..._(this,vs)].sort((i,s)=>i.start-s.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let i=1;i<t.length;i++){let s=e[e.length-1],r=t[i];r.start<=s.start+s.size?s.size=Math.max(s.size,r.start+r.data.byteLength-s.start):e.push({start:r.start,size:r.data.byteLength})}for(let i of e){i.data=new Uint8Array(i.size);for(let s of _(this,vs))i.start<=s.start&&s.start<i.start+i.size&&i.data.set(s.data,s.start-i.start);_(this,Mr)?(be(this,jn,Qa).call(this,i.data,i.start),be(this,Ir,$n).call(this)):_(this,Pr).options.onData?.(i.data,i.start)}_(this,vs).length=0}finalize(){_(this,Mr)&&be(this,Ir,$n).call(this,!0)}};Pr=new WeakMap;vs=new WeakMap;Mr=new WeakMap;Ci=new WeakMap;Vt=new WeakMap;jn=new WeakSet;Qa=function(e,t){let i=_(this,Vt).findIndex(o=>o.start<=t&&t<o.start+_(this,Ci));i===-1&&(i=be(this,lo,Pd).call(this,t));let s=_(this,Vt)[i],r=t-s.start,n=e.subarray(0,Math.min(_(this,Ci)-r,e.byteLength));s.data.set(n,r);let a={start:r,end:r+n.byteLength};if(be(this,co,zd).call(this,s,a),s.written[0].start===0&&s.written[0].end===_(this,Ci)&&(s.shouldFlush=!0),_(this,Vt).length>hb){for(let o=0;o<_(this,Vt).length-1;o++)_(this,Vt)[o].shouldFlush=!0;be(this,Ir,$n).call(this)}n.byteLength<e.byteLength&&be(this,jn,Qa).call(this,e.subarray(n.byteLength),t+n.byteLength)};co=new WeakSet;zd=function(e,t){let i=0,s=e.written.length-1,r=-1;for(;i<=s;){let n=Math.floor(i+(s-i+1)/2);e.written[n].start<=t.start?(i=n+1,r=n):s=n-1}for(e.written.splice(r+1,0,t),(r===-1||e.written[r].end<t.start)&&r++;r<e.written.length-1&&e.written[r].end>=e.written[r+1].start;)e.written[r].end=Math.max(e.written[r].end,e.written[r+1].end),e.written.splice(r+1,1)};lo=new WeakSet;Pd=function(e){let i={start:Math.floor(e/_(this,Ci))*_(this,Ci),data:new Uint8Array(_(this,Ci)),written:[],shouldFlush:!1};return _(this,Vt).push(i),_(this,Vt).sort((s,r)=>s.start-r.start),_(this,Vt).indexOf(i)};Ir=new WeakSet;$n=function(e=!1){for(let t=0;t<_(this,Vt).length;t++){let i=_(this,Vt)[t];if(!(!i.shouldFlush&&!e)){for(let s of i.written)_(this,Pr).options.onData?.(i.data.subarray(s.start,s.end),i.start+s.start);_(this,Vt).splice(t--,1)}}};var fb=class extends uo{constructor(e){super(new Cd({onData:(t,i)=>e.stream.write({type:"write",data:t,position:i}),chunked:!0,chunkSize:e.options?.chunkSize}))}},Ka=1e3,pb=["avc","hevc","vp9","av1"],mb=["aac","opus"],gb=2082844800,_b=["strict","offset","cross-track-offset"],W,se,Yn,Gt,vt,pt,Zs,Qs,ho,ws,Ss,Rr,Ja,Id,eo,Rd,fo,Fd,to,Ld,po,Od,Vn,io,_i,Ai,mo,Dd,Fr,Xn,Zn,go,Js,Or,Wn,so,Nd=class{constructor(e){if(fe(this,Ja),fe(this,eo),fe(this,fo),fe(this,to),fe(this,po),fe(this,Vn),fe(this,_i),fe(this,mo),fe(this,Fr),fe(this,Zn),fe(this,Js),fe(this,Wn),fe(this,W,void 0),fe(this,se,void 0),fe(this,Yn,void 0),fe(this,Gt,void 0),fe(this,vt,null),fe(this,pt,null),fe(this,Zs,Math.floor(Date.now()/1e3)+gb),fe(this,Qs,[]),fe(this,ho,1),fe(this,ws,[]),fe(this,Ss,[]),fe(this,Rr,!1),be(this,Ja,Id).call(this,e),e.video=zr(e.video),e.audio=zr(e.audio),e.fastStart=zr(e.fastStart),this.target=e.target,mt(this,W,{firstTimestampBehavior:"strict",...e}),e.target instanceof oo)mt(this,se,new db(e.target));else if(e.target instanceof Cd)mt(this,se,new uo(e.target));else if(e.target instanceof lb)mt(this,se,new fb(e.target));else throw new Error(\`Invalid target: \${e.target}\`);be(this,to,Ld).call(this),be(this,eo,Rd).call(this)}addVideoChunk(e,t,i,s){if(!(e instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");if(t&&typeof t!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(i!==void 0&&(!Number.isFinite(i)||i<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");if(s!==void 0&&!Number.isFinite(s))throw new TypeError("addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number.");let r=new Uint8Array(e.byteLength);e.copyTo(r),this.addVideoChunkRaw(r,e.type,i??e.timestamp,e.duration,t,s)}addVideoChunkRaw(e,t,i,s,r,n){if(!(e instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(i)||i<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(s)||s<0)throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");if(r&&typeof r!="object")throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");if(n!==void 0&&!Number.isFinite(n))throw new TypeError("addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number.");if(be(this,Wn,so).call(this),!_(this,W).video)throw new Error("No video track declared.");if(typeof _(this,W).fastStart=="object"&&_(this,vt).samples.length===_(this,W).fastStart.expectedVideoChunks)throw new Error(\`Cannot add more video chunks than specified in 'fastStart' (\${_(this,W).fastStart.expectedVideoChunks}).\`);let a=be(this,Vn,io).call(this,_(this,vt),e,t,i,s,r,n);if(_(this,W).fastStart==="fragmented"&&_(this,pt)){for(;_(this,Ss).length>0&&_(this,Ss)[0].decodeTimestamp<=a.decodeTimestamp;){let o=_(this,Ss).shift();be(this,_i,Ai).call(this,_(this,pt),o)}a.decodeTimestamp<=_(this,pt).lastDecodeTimestamp?be(this,_i,Ai).call(this,_(this,vt),a):_(this,ws).push(a)}else be(this,_i,Ai).call(this,_(this,vt),a)}addAudioChunk(e,t,i){if(!(e instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");if(t&&typeof t!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(i!==void 0&&(!Number.isFinite(i)||i<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let s=new Uint8Array(e.byteLength);e.copyTo(s),this.addAudioChunkRaw(s,e.type,i??e.timestamp,e.duration,t)}addAudioChunkRaw(e,t,i,s,r){if(!(e instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(i)||i<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(s)||s<0)throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");if(r&&typeof r!="object")throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");if(be(this,Wn,so).call(this),!_(this,W).audio)throw new Error("No audio track declared.");if(typeof _(this,W).fastStart=="object"&&_(this,pt).samples.length===_(this,W).fastStart.expectedAudioChunks)throw new Error(\`Cannot add more audio chunks than specified in 'fastStart' (\${_(this,W).fastStart.expectedAudioChunks}).\`);let n=be(this,Vn,io).call(this,_(this,pt),e,t,i,s,r);if(_(this,W).fastStart==="fragmented"&&_(this,vt)){for(;_(this,ws).length>0&&_(this,ws)[0].decodeTimestamp<=n.decodeTimestamp;){let a=_(this,ws).shift();be(this,_i,Ai).call(this,_(this,vt),a)}n.decodeTimestamp<=_(this,vt).lastDecodeTimestamp?be(this,_i,Ai).call(this,_(this,pt),n):_(this,Ss).push(n)}else be(this,_i,Ai).call(this,_(this,pt),n)}finalize(){if(_(this,Rr))throw new Error("Cannot finalize a muxer more than once.");if(_(this,W).fastStart==="fragmented"){for(let t of _(this,ws))be(this,_i,Ai).call(this,_(this,vt),t);for(let t of _(this,Ss))be(this,_i,Ai).call(this,_(this,pt),t);be(this,Zn,go).call(this,!1)}else _(this,vt)&&be(this,Fr,Xn).call(this,_(this,vt)),_(this,pt)&&be(this,Fr,Xn).call(this,_(this,pt));let e=[_(this,vt),_(this,pt)].filter(Boolean);if(_(this,W).fastStart==="in-memory"){let t;for(let s=0;s<2;s++){let r=Nn(e,_(this,Zs)),n=_(this,se).measureBox(r);t=_(this,se).measureBox(_(this,Gt));let a=_(this,se).pos+n+t;for(let o of _(this,Qs)){o.offset=a;for(let{data:c}of o.samples)a+=c.byteLength,t+=c.byteLength}if(a<2**32)break;t>=2**32&&(_(this,Gt).largeSize=!0)}let i=Nn(e,_(this,Zs));_(this,se).writeBox(i),_(this,Gt).size=t,_(this,se).writeBox(_(this,Gt));for(let s of _(this,Qs))for(let r of s.samples)_(this,se).write(r.data),r.data=null}else if(_(this,W).fastStart==="fragmented"){let t=_(this,se).pos,i=ib(e);_(this,se).writeBox(i);let s=_(this,se).pos-t;_(this,se).seek(_(this,se).pos-4),_(this,se).writeU32(s)}else{let t=_(this,se).offsets.get(_(this,Gt)),i=_(this,se).pos-t;_(this,Gt).size=i,_(this,Gt).largeSize=i>=2**32,_(this,se).patchBox(_(this,Gt));let s=Nn(e,_(this,Zs));if(typeof _(this,W).fastStart=="object"){_(this,se).seek(_(this,Yn)),_(this,se).writeBox(s);let r=t-_(this,se).pos;_(this,se).writeBox(gy(r))}else _(this,se).writeBox(s)}be(this,Js,Or).call(this),_(this,se).finalize(),mt(this,Rr,!0)}};W=new WeakMap;se=new WeakMap;Yn=new WeakMap;Gt=new WeakMap;vt=new WeakMap;pt=new WeakMap;Zs=new WeakMap;Qs=new WeakMap;ho=new WeakMap;ws=new WeakMap;Ss=new WeakMap;Rr=new WeakMap;Ja=new WeakSet;Id=function(e){if(typeof e!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(e.target instanceof Qn))throw new TypeError("The target must be provided and an instance of Target.");if(e.video){if(!pb.includes(e.video.codec))throw new TypeError(\`Unsupported video codec: \${e.video.codec}\`);if(!Number.isInteger(e.video.width)||e.video.width<=0)throw new TypeError(\`Invalid video width: \${e.video.width}. Must be a positive integer.\`);if(!Number.isInteger(e.video.height)||e.video.height<=0)throw new TypeError(\`Invalid video height: \${e.video.height}. Must be a positive integer.\`);let t=e.video.rotation;if(typeof t=="number"&&![0,90,180,270].includes(t))throw new TypeError(\`Invalid video rotation: \${t}. Has to be 0, 90, 180 or 270.\`);if(Array.isArray(t)&&(t.length!==9||t.some(i=>typeof i!="number")))throw new TypeError(\`Invalid video transformation matrix: \${t.join()}\`);if(e.video.frameRate!==void 0&&(!Number.isInteger(e.video.frameRate)||e.video.frameRate<=0))throw new TypeError(\`Invalid video frame rate: \${e.video.frameRate}. Must be a positive integer.\`)}if(e.audio){if(!mb.includes(e.audio.codec))throw new TypeError(\`Unsupported audio codec: \${e.audio.codec}\`);if(!Number.isInteger(e.audio.numberOfChannels)||e.audio.numberOfChannels<=0)throw new TypeError(\`Invalid number of audio channels: \${e.audio.numberOfChannels}. Must be a positive integer.\`);if(!Number.isInteger(e.audio.sampleRate)||e.audio.sampleRate<=0)throw new TypeError(\`Invalid audio sample rate: \${e.audio.sampleRate}. Must be a positive integer.\`)}if(e.firstTimestampBehavior&&!_b.includes(e.firstTimestampBehavior))throw new TypeError(\`Invalid first timestamp behavior: \${e.firstTimestampBehavior}\`);if(typeof e.fastStart=="object"){if(e.video){if(e.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(e.fastStart.expectedVideoChunks)||e.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(e.audio){if(e.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(e.fastStart.expectedAudioChunks)||e.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(e.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");if(e.minFragmentDuration!==void 0&&(!Number.isFinite(e.minFragmentDuration)||e.minFragmentDuration<0))throw new TypeError("'minFragmentDuration' must be a non-negative number.")};eo=new WeakSet;Rd=function(){if(_(this,se).writeBox(my({holdsAvc:_(this,W).video?.codec==="avc",fragmented:_(this,W).fastStart==="fragmented"})),mt(this,Yn,_(this,se).pos),_(this,W).fastStart==="in-memory")mt(this,Gt,Xa(!1));else if(_(this,W).fastStart!=="fragmented"){if(typeof _(this,W).fastStart=="object"){let e=be(this,fo,Fd).call(this);_(this,se).seek(_(this,se).pos+e)}mt(this,Gt,Xa(!0)),_(this,se).writeBox(_(this,Gt))}be(this,Js,Or).call(this)};fo=new WeakSet;Fd=function(){if(typeof _(this,W).fastStart!="object")return;let e=0,t=[_(this,W).fastStart.expectedVideoChunks,_(this,W).fastStart.expectedAudioChunks];for(let i of t)i&&(e+=8*Math.ceil(2/3*i),e+=4*i,e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i);return e+=4096,e};to=new WeakSet;Ld=function(){if(_(this,W).video&&mt(this,vt,{id:1,info:{type:"video",codec:_(this,W).video.codec,width:_(this,W).video.width,height:_(this,W).video.height,rotation:_(this,W).video.rotation??0,decoderConfig:null},timescale:_(this,W).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),_(this,W).audio&&(mt(this,pt,{id:_(this,W).video?2:1,info:{type:"audio",codec:_(this,W).audio.codec,numberOfChannels:_(this,W).audio.numberOfChannels,sampleRate:_(this,W).audio.sampleRate,decoderConfig:null},timescale:_(this,W).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),_(this,W).audio.codec==="aac")){let e=be(this,po,Od).call(this,2,_(this,W).audio.sampleRate,_(this,W).audio.numberOfChannels);_(this,pt).info.decoderConfig={codec:_(this,W).audio.codec,description:e,numberOfChannels:_(this,W).audio.numberOfChannels,sampleRate:_(this,W).audio.sampleRate}}};po=new WeakSet;Od=function(e,t,i){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(t),n=i,a="";a+=e.toString(2).padStart(5,"0"),a+=r.toString(2).padStart(4,"0"),r===15&&(a+=t.toString(2).padStart(24,"0")),a+=n.toString(2).padStart(4,"0");let o=Math.ceil(a.length/8)*8;a=a.padEnd(o,"0");let c=new Uint8Array(a.length/8);for(let l=0;l<a.length;l+=8)c[l/8]=parseInt(a.slice(l,l+8),2);return c};Vn=new WeakSet;io=function(e,t,i,s,r,n,a){let o=s/1e6,c=(s-(a??0))/1e6,l=r/1e6,u=be(this,mo,Dd).call(this,o,c,e);return o=u.presentationTimestamp,c=u.decodeTimestamp,n?.decoderConfig&&(e.info.decoderConfig===null?e.info.decoderConfig=n.decoderConfig:Object.assign(e.info.decoderConfig,n.decoderConfig)),{presentationTimestamp:o,decodeTimestamp:c,duration:l,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:yi(l,e.timescale)}};_i=new WeakSet;Ai=function(e,t){_(this,W).fastStart!=="fragmented"&&e.samples.push(t);let i=yi(t.presentationTimestamp-t.decodeTimestamp,e.timescale);if(e.lastTimescaleUnits!==null){let r=yi(t.decodeTimestamp,e.timescale,!1),n=Math.round(r-e.lastTimescaleUnits);if(e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,_(this,W).fastStart!=="fragmented"){let a=qn(e.timeToSampleTable);a.sampleCount===1?(a.sampleDelta=n,a.sampleCount++):a.sampleDelta===n?a.sampleCount++:(a.sampleCount--,e.timeToSampleTable.push({sampleCount:2,sampleDelta:n}));let o=qn(e.compositionTimeOffsetTable);o.sampleCompositionTimeOffset===i?o.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=0,_(this,W).fastStart!=="fragmented"&&(e.timeToSampleTable.push({sampleCount:1,sampleDelta:yi(t.duration,e.timescale)}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=t;let s=!1;if(!e.currentChunk)s=!0;else{let r=t.presentationTimestamp-e.currentChunk.startTimestamp;if(_(this,W).fastStart==="fragmented"){let n=_(this,vt)??_(this,pt),a=_(this,W).minFragmentDuration??1;e===n&&t.type==="key"&&r>=a&&(s=!0,be(this,Zn,go).call(this))}else s=r>=.5}s&&(e.currentChunk&&be(this,Fr,Xn).call(this,e),e.currentChunk={startTimestamp:t.presentationTimestamp,samples:[]}),e.currentChunk.samples.push(t)};mo=new WeakSet;Dd=function(e,t,i){let s=_(this,W).firstTimestampBehavior==="strict",r=i.lastDecodeTimestamp===-1;if(s&&r&&t!==0)throw new Error(\`The first chunk for your media track must have a timestamp of 0 (received DTS=\${t}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want.
|
|
2011
|
+
|
|
2012
|
+
If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
|
|
2013
|
+
\`);if(_(this,W).firstTimestampBehavior==="offset"||_(this,W).firstTimestampBehavior==="cross-track-offset"){i.firstDecodeTimestamp===void 0&&(i.firstDecodeTimestamp=t);let a;_(this,W).firstTimestampBehavior==="offset"?a=i.firstDecodeTimestamp:a=Math.min(_(this,vt)?.firstDecodeTimestamp??1/0,_(this,pt)?.firstDecodeTimestamp??1/0),t-=a,e-=a}if(t<i.lastDecodeTimestamp)throw new Error(\`Timestamps must be monotonically increasing (DTS went from \${i.lastDecodeTimestamp*1e6} to \${t*1e6}).\`);return i.lastDecodeTimestamp=t,{presentationTimestamp:e,decodeTimestamp:t}};Fr=new WeakSet;Xn=function(e){if(_(this,W).fastStart==="fragmented")throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");if(e.currentChunk){if(e.finalizedChunks.push(e.currentChunk),_(this,Qs).push(e.currentChunk),(e.compactlyCodedChunkTable.length===0||qn(e.compactlyCodedChunkTable).samplesPerChunk!==e.currentChunk.samples.length)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:e.currentChunk.samples.length}),_(this,W).fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=_(this,se).pos;for(let t of e.currentChunk.samples)_(this,se).write(t.data),t.data=null;be(this,Js,Or).call(this)}};Zn=new WeakSet;go=function(e=!0){if(_(this,W).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let t=[_(this,vt),_(this,pt)].filter(o=>o&&o.currentChunk);if(t.length===0)return;let i=hy(this,ho)._++;if(i===1){let o=Nn(t,_(this,Zs),!0);_(this,se).writeBox(o)}let s=_(this,se).pos,r=kd(i,t);_(this,se).writeBox(r);{let o=Xa(!1),c=0;for(let u of t)for(let h of u.currentChunk.samples)c+=h.size;let l=_(this,se).measureBox(o)+c;l>=2**32&&(o.largeSize=!0,l=_(this,se).measureBox(o)+c),o.size=l,_(this,se).writeBox(o)}for(let o of t){o.currentChunk.offset=_(this,se).pos,o.currentChunk.moofOffset=s;for(let c of o.currentChunk.samples)_(this,se).write(c.data),c.data=null}let n=_(this,se).pos;_(this,se).seek(_(this,se).offsets.get(r));let a=kd(i,t);_(this,se).writeBox(a),_(this,se).seek(n);for(let o of t)o.finalizedChunks.push(o.currentChunk),_(this,Qs).push(o.currentChunk),o.currentChunk=null;e&&be(this,Js,Or).call(this)};Js=new WeakSet;Or=function(){_(this,se)instanceof uo&&_(this,se).flush()};Wn=new WeakSet;so=function(){if(_(this,Rr))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};var Hd=128e3,xb="mp4a.40.2",yb=1024;async function Gd(e,t,i=Hd){if(typeof AudioEncoder>"u")return null;let s=[{muxer:"aac",encoder:"mp4a.40.2"},{muxer:"opus",encoder:"opus"}];for(let r of s)try{let{supported:n}=await AudioEncoder.isConfigSupported({codec:r.encoder,sampleRate:e,numberOfChannels:t,bitrate:i});if(n)return r}catch{}return null}async function Vd(e,t,i={}){if(typeof AudioEncoder>"u")throw new Error("WebCodecs AudioEncoder is not available in this environment");let s=i.bitrate??Hd,r=i.codec??xb,n=i.chunkSize??yb,a=e.sampleRate,o=e.numberOfChannels,c=new AudioEncoder({output:(h,f)=>{t.addAudioChunk(h,f)},error:h=>{$().error("AudioEncoder error:",h.message)}});c.configure({codec:r,sampleRate:a,numberOfChannels:o,bitrate:s});let l=e.length,u=[];for(let h=0;h<o;h++)u.push(e.getChannelData(h));for(let h=0;h<l;h+=n){let f=Math.min(n,l-h),p=new Float32Array(f*o);for(let g=0;g<f;g++)for(let y=0;y<o;y++)p[g*o+y]=u[y][h+g];let m=new AudioData({format:"f32",sampleRate:a,numberOfFrames:f,numberOfChannels:o,timestamp:Math.round(h/a*1e6),data:p});c.encode(m),m.close()}await c.flush(),c.close()}var bb={"480p":480,"720p":720,"1080p":1080,"1440p":1440,"4k":2160},vb={"480p":15e5,"720p":4e6,"1080p":8e6,"1440p":16e6,"4k":35e6},wb={"480p":"avc1.42E01F","720p":"avc1.42E01F","1080p":"avc1.42002A","1440p":"avc1.640033","4k":"avc1.640033"},Sb=8,Wd=12e4;function _o(e,t,i){if(e==="source"){let n=i>1080?"avc1.640033":"avc1.42002A";return{physicalWidth:t,physicalHeight:i,pixelRatio:1,defaultBitrate:5e6,defaultCodec:n}}let s=bb[e],r=s/i;return{physicalWidth:Math.round(t*r),physicalHeight:s,pixelRatio:r,defaultBitrate:vb[e],defaultCodec:wb[e]}}function Kn(e){let t=Math.max(2,Math.floor(e));return t%2===0?t:t-1}var er=class{canvas;renderer;encoder=null;muxer=null;tempCanvas;tempCtx;constructor(t,i){this.canvas=t,this.renderer=i,this.tempCanvas=document.createElement("canvas"),this.tempCtx=this.tempCanvas.getContext("2d")}async export(t,i={}){let{codec:s="avc1.42002A",bitrate:r=5e6,framerate:n=t.frame_rate||30,onProgress:a}=i,o=t.width??1920,c=t.height??1080,l=typeof t.duration=="number"?t.duration:10,u=Kn(this.canvas.width||o),h=Kn(this.canvas.height||c);console.log("[clipkit] Starting export:",{codec:s,bitrate:r,framerate:n,sourceWidth:o,sourceHeight:c,width:u,height:h,duration:l,hasAudio:!!i.audio}),this.tempCanvas.width=u,this.tempCanvas.height=h;let f=Math.ceil(l*n),p=t.motion_blur,m=p?Math.max(1,Math.min(32,Math.round(typeof p.samples=="number"?p.samples:8))):1,g=p&&typeof p.shutter=="number"?Math.min(1,Math.max(0,p.shutter)):.5,y=m>1&&g>0,w=y?new Float32Array(u*h*4):null;console.log("[clipkit] Encoding",f,"frames at",n,"fps",y?\`(motion blur: \${m} samples, shutter \${g})\`:"");let x=new oo,b=null;i.audio&&(b=await Gd(i.audio.buffer.sampleRate,i.audio.buffer.numberOfChannels,i.audio.bitrate),b||console.warn("[clipkit] No supported audio encoder \\u2014 rendering without audio."));let S={target:x,video:{codec:"avc",width:u,height:h},fastStart:"in-memory"};if(i.audio&&b&&(S.audio={codec:b.muxer,sampleRate:i.audio.buffer.sampleRate,numberOfChannels:i.audio.buffer.numberOfChannels}),this.muxer=new Nd(S),i.audio&&b){console.log("[clipkit] Encoding audio:",{codec:b.muxer,sampleRate:i.audio.buffer.sampleRate,channels:i.audio.buffer.numberOfChannels,duration:i.audio.buffer.duration.toFixed(2)+"s"});try{await Vd(i.audio.buffer,this.muxer,{bitrate:i.audio.bitrate,codec:b.encoder}),console.log("[clipkit] Audio encoded")}catch(E){console.warn("[clipkit] Audio encode failed \\u2014 continuing without audio:",E instanceof Error?E.message:String(E))}}let v=0,T=null;this.encoder=new VideoEncoder({output:(E,U)=>{this.muxer?.addVideoChunk(E,U),v++,a&&a(Math.min(1,v/f)),(v%30===0||v===f)&&console.log(\`[clipkit] Encoded \${v}/\${f}\`)},error:E=>{T=E instanceof Error?E:new Error(String(E)),console.error("[clipkit] VideoEncoder error:",T.message)}}),this.encoder.configure({codec:s,width:u,height:h,bitrate:r});for(let E=0;E<f;E++){let U=E*(1/n);if(y&&w){w.fill(0);for(let L=0;L<m;L++){let re=Math.min(Math.max(U+((L+.5)/m-.5)*(g/n),0),l);await this.renderer.renderAsync(t,re),await this.renderer.gpuFinish(),this.tempCtx.drawImage(this.canvas,0,0,u,h);let te=this.tempCtx.getImageData(0,0,u,h).data;for(let K=0;K<te.length;K++)w[K]+=te[K]}let J=this.tempCtx.createImageData(u,h),D=J.data,z=1/m;for(let L=0;L<D.length;L++)D[L]=Math.round(w[L]*z);this.tempCtx.putImageData(J,0,0)}else await this.renderer.renderAsync(t,U),await this.renderer.gpuFinish(),this.tempCtx.drawImage(this.canvas,0,0,u,h);let H=new VideoFrame(this.tempCanvas,{timestamp:E*1e6/n,duration:1e6/n});for(;this.encoder.encodeQueueSize>Sb;){if(T)throw T;await new Promise(J=>{let D=this.encoder,z=!1,L=()=>{z||(z=!0,D.removeEventListener("dequeue",L),J())};D.addEventListener("dequeue",L,{once:!0}),setTimeout(L,50)})}if(T)throw T;let Q=E%30===0;this.encoder.encode(H,{keyFrame:Q}),H.close()}if(T||(await Promise.race([this.encoder.flush(),new Promise((E,U)=>setTimeout(()=>U(new Error(\`Export stalled: encoder.flush did not resolve within \${Wd/1e3}s\`)),Wd))]),T))throw T;console.log("[clipkit] Encoding complete"),this.muxer.finalize();let{buffer:C}=x;if(!C||C.byteLength===0)throw new Error("Muxer produced no output");console.log("[clipkit] Muxer finalized, size:",(C.byteLength/1024/1024).toFixed(2),"MB");let P=new Blob([C],{type:"video/mp4"});return this.encoder.close(),this.encoder=null,this.muxer=null,console.log("[clipkit] Export complete, size:",(P.size/1024/1024).toFixed(2),"MB"),P}async exportFrames(t,i){let s=i.framerate??t.frame_rate??30,r=typeof t.duration=="number"?t.duration:10,n=Kn(this.canvas.width||(t.width??1920)),a=Kn(this.canvas.height||(t.height??1080));this.tempCanvas.width=n,this.tempCanvas.height=a;let o=Math.ceil(r*s);for(let c=0;c<o;c++){await this.renderer.renderAsync(t,c/s),await this.renderer.gpuFinish(),i.alpha&&this.tempCtx.clearRect(0,0,n,a),this.tempCtx.drawImage(this.canvas,0,0,n,a);let l=this.tempCanvas.toDataURL("image/png");await i.onFrame(c,l.slice(l.indexOf(",")+1)),i.onProgress?.((c+1)/o)}return o}};var tr=class{canvas;backend;currentSource=null;transparentBackground=!1;images=new si;videos=new si;audioBuffers=new si;fontAtlases=new si;svgRasters=new si;maskedTexts=new si;groupTargets=new si;frameIndex=0;groupTargetPoolCapBytes=512*1024*1024;luts=new si;blurTargets=[];initialized=!1;disposed=!1;constructor(t){this.canvas=t}async init(t={}){if(this.initialized)return!0;let i=t.backend??"auto";if(i==="webgpu"||i==="auto"){let s=new Wr(this.canvas);if(await s.init())return this.backend=s,this.initialized=!0,$().info("Runtime initialized with WebGPU backend"),!0;if(i==="webgpu")return!1}if(i==="webgl2"||i==="auto"){let s=new qr(this.canvas);if(await s.init())return this.backend=s,this.initialized=!0,$().info("Runtime initialized with WebGL2 backend"),!0}return!1}get api(){return this.initialized?this.backend.capabilities.api:null}load(t){this.currentSource=t;let i=t.width??1920,s=t.height??1080;this.backend.resize(i,s)}async preload(t){if(!this.initialized)throw new Error("ClipkitRuntime.preload() called before init()");let i=t??this.currentSource;if(!i)throw new Error("No source loaded");i.fonts&&i.fonts.length>0&&await Io(i.fonts);let s=[],r=[],n=[],a=[],o=[],c=new Set,l=x=>{for(let b of x){let S=b.effects;if(Array.isArray(S))for(let T of S)T.type==="lut"&&typeof T.source=="string"&&T.source&&c.add(T.source);let v=b.elements;Array.isArray(v)&&l(v)}};l(i.elements);for(let x of c)o.push(this.preloadLut(x));let u=new Map,h=x=>{for(let b of x){if(b.type==="video"&&typeof b.source=="string"&&b.source){let v=b,T=JSON.stringify([v.time,v.trim_start,v.trim_duration,v.playback_rate,v.loop,v.time_remap]),C=u.get(v.source);C||u.set(v.source,C=new Set),C.add(T)}let S=b.elements;Array.isArray(S)&&h(S)}};h(i.elements);for(let[x,b]of u)b.size>1&&$().warn(\`\${b.size} video elements share \${x} with different timings \\u2014 they share ONE decoder, so all will show the same frames and seeking will thrash. Give each element its own URL (append e.g. ?copy=2).\`);let f=x=>{for(let b of x){if(b.type==="image")r.push(this.preloadImage(b));else if(b.type==="video")n.push(this.preloadVideo(b)),a.push(this.preloadVideoAudio(b));else if(b.type==="audio")a.push(this.preloadAudio(b));else if(b.type==="text"||b.type==="caption"){let v=b;s.push(zo(v.font_family??"sans-serif",v.font_weight??"normal"))}else if(b.type==="group"){let v=b.elements;Array.isArray(v)&&f(v)}let S=b.material?.normal_map;typeof S=="string"&&S&&r.push(this.preloadImageUrl(S))}};f(i.elements);let p=i.environment;p&&p.type==="image"&&typeof p.src=="string"&&p.src&&r.push(this.preloadEnvImage(p.src));let m=1e4,g=(x,b)=>b.map(S=>Promise.race([S,new Promise(v=>setTimeout(()=>{$().warn(\`Preload: a \${x} asset exceeded \${m}ms \\u2014 proceeding without waiting for it.\`),v()},m))])),y=Promise.all([...g("font",s),...g("image",r),...g("video",n),...g("audio",a),...g("lut",o)]),w=new Promise(x=>setTimeout(()=>{$().warn("Preload global timeout \\u2014 proceeding with whatever loaded."),x()},3e4));await Promise.race([y,w]),await Promise.race([Po(),new Promise(x=>setTimeout(x,2e3))])}async preloadAudio(t){let i=String(t.source??"");if(i&&!this.audioBuffers.has(i))try{await this.audioBuffers.getOrLoad(i,async()=>ma(i))}catch(s){$().warn(\`Failed to preload audio \${i}:\`,s instanceof Error?s.message:String(s))}}async preloadVideoAudio(t){if(typeof AudioContext>"u")return;let i=String(t.source??"");if(i&&!this.audioBuffers.has(i))try{await this.audioBuffers.getOrLoad(i,async()=>ma(i))}catch(s){$().debug(\`Video \${i} has no decodable audio track:\`,s instanceof Error?s.message:String(s))}}async preloadLut(t){if(!this.luts.has(t))try{await this.luts.getOrLoad(t,async()=>{let{bitmap:i,size:s}=await Oo(t);return{texture:this.backend.createTexture(i),size:s}})}catch(i){$().warn(\`Failed to load LUT \${t}:\`,i instanceof Error?i.message:String(i))}}async preloadImage(t){return this.preloadImageUrl(String(t.source??""))}envAvg=new Map;async preloadEnvImage(t){if(await this.preloadImageUrl(t),this.envAvg.has(t))return;let i=this.images.get(t);if(i)try{let r=new OffscreenCanvas(1,1).getContext("2d");if(!r)return;r.drawImage(i.bitmap,0,0,1,1);let n=r.getImageData(0,0,1,1).data;this.envAvg.set(t,[n[0]/255,n[1]/255,n[2]/255])}catch{this.envAvg.set(t,[.5,.5,.5])}}async preloadImageUrl(t){if(t&&!this.images.has(t))try{await this.images.getOrLoad(t,async()=>{let i=await Ro(t),s=this.backend.createTexture(i);return{bitmap:i,texture:s}})}catch(i){$().warn(\`Failed to preload image \${t}:\`,i instanceof Error?i.message:String(i))}}async preloadVideo(t){let i=String(t.source??"");if(i&&!this.videos.has(i)){try{await this.videos.getOrLoad(i,async()=>{let s=await dn.load(i),r=await s.getFrame(0);if(!r)throw new Error("decoder produced no first frame");let n=this.backend.createTexture(r);return{video:null,frameSource:s,texture:n,lastUploadedTime:r.timestamp,width:s.width,height:s.height}});return}catch(s){let r=s instanceof Error?s.message:String(s);if(typeof document>"u"){$().warn(\`WebCodecs decode unavailable for \${i} (\${r}); host frame-pump fallback required.\`);return}$().warn(\`WebCodecs decode unavailable for \${i} (\${r}); falling back to HTMLVideoElement.\`)}try{await this.videos.getOrLoad(i,async()=>{let s=await Fo(i),r=this.backend.createTexture(s);return{video:s,frameSource:null,texture:r,lastUploadedTime:s.currentTime,width:s.videoWidth,height:s.videoHeight}})}catch(s){$().warn(\`Failed to preload video \${i}:\`,s instanceof Error?s.message:String(s))}}}hasVideoAsset(t){return this.videos.has(t)}collectActiveVideos(t,i,s,r){for(let n of t){let a=Dr(n.time),o=kb(n.duration,s-a);if(!(i<a||i>a+o)){if(n.type==="video")r.push({el:n,clock:i});else if(n.type==="group"){let c=n,l=i-a,u=Ri(c.time_remap),h=u?Math.max(0,Ze(u,l)):l;Array.isArray(c.elements)&&this.collectActiveVideos(c.elements,h,o,r)}}}}async prepareVideoFrames(t){let i=this.currentSource;if(!i)return;let s=typeof i.duration=="number"?i.duration:0,r=[];this.collectActiveVideos(i.elements,t,s,r);let n=[];for(let{el:a,clock:o}of r){let c=String(a.source??""),l=this.videos.get(c);if(!l?.frameSource)continue;let u=Rs(o,{elementStart:Dr(a.time),trimStart:Dr(a.trim_start),trimDuration:Ji(a.trim_duration),rate:Ki(a.playback_rate),loop:a.loop===!0,timeRemap:Ri(a.time_remap)},l.frameSource.duration),h=l.frameSource;n.push(h.getFrame(u).then(f=>{f&&l.lastUploadedTime!==f.timestamp&&(this.backend.updateTexture(l.texture,f),l.lastUploadedTime=f.timestamp)}))}n.length>0&&await Promise.all(n)}pushExternalVideoFrame(t,i){if(!this.initialized){i.close();return}let s=this.videos.get(t);if(s&&s.width===i.width&&s.height===i.height){this.backend.updateTexture(s.texture,i),i.close();return}s&&this.backend.destroyTexture(s.texture);let r=this.backend.createTexture(i);this.videos.set(t,{video:null,frameSource:null,texture:r,lastUploadedTime:0,width:i.width,height:i.height}),i.close()}frame(t){if(!this.initialized)return;let i=this.currentSource;if(!i)return;this.frameIndex++;let s=typeof i.background_color=="string"?ft(i.background_color):this.transparentBackground?[0,0,0,0]:void 0,r=Ha(i,t);if(this.backend.beginFrame(s),r){let n=this.backend.width,a=this.backend.height,o=this.acquireBlurTarget(6,n,a);this.backend.pushTarget(o,s??[0,0,0,0]),On(i,this.makeContext(t)),this.backend.popTarget(),this.applyBloom(o,n,a,r)}else On(i,this.makeContext(t));this.backend.endFrame(),this.evictGroupTargets()}applyBloom(t,i,s,r){let n=this.acquireBlurTarget(3,i,s),a=this.acquireBlurTarget(4,i,s),o={cx:i/2,cy:s/2,width:i,height:s};this.backend.pushTarget(n,[0,0,0,0]),this.backend.drawStylizedQuad({...o,texture:t.texture,mode:"bloom_bright",p0:r.threshold,p1:r.knee}),this.backend.popTarget(),this.backend.pushTarget(a,[0,0,0,0]),this.backend.drawFilteredQuad({...o,texture:n.texture,blurRadius:r.radius,blurDir:[1,0],brightness:1,contrast:1,saturation:1}),this.backend.popTarget(),this.backend.pushTarget(n,[0,0,0,0]),this.backend.drawFilteredQuad({...o,texture:a.texture,blurRadius:r.radius,blurDir:[0,1],brightness:1,contrast:1,saturation:1}),this.backend.popTarget();let c=r.intensity;this.backend.drawTexturedQuad({...o,rotation:0,texture:t.texture}),this.backend.drawTexturedQuad({...o,rotation:0,texture:n.texture,tint:[c,c,c,c],blend:"add"})}renderFinalFrame(t,i){if(!this.initialized)return;let s=this.currentSource;if(!s)return;this.frameIndex++;let r=s.motion_blur,n=r?Math.max(1,Math.min(32,Math.round(typeof r.samples=="number"?r.samples:8))):1;i!==void 0&&(n=Math.max(1,Math.min(n,Math.round(i))));let a=r&&typeof r.shutter=="number"?Math.min(1,Math.max(0,r.shutter)):.5;if(n<=1||a<=0){this.frame(t);return}let o=s.frame_rate??30,c=typeof s.duration=="number"?s.duration:Number.POSITIVE_INFINITY,l=typeof s.background_color=="string"?ft(s.background_color):[0,0,0,1],u=this.backend.width,h=this.backend.height,f=this.acquireBlurTarget(0,u,h),p=this.acquireBlurTarget(1,u,h),m=this.acquireBlurTarget(2,u,h),g={cx:u/2,cy:h/2,width:u,height:h,rotation:0};this.backend.beginFrame(l);for(let w=0;w<n;w++){let x=Math.min(Math.max(t+((w+.5)/n-.5)*(a/o),0),c);if(this.backend.pushTarget(f,l),On(s,this.makeContext(x)),this.backend.popTarget(),w===0)this.backend.pushTarget(p,[0,0,0,0]),this.backend.drawTexturedQuad({...g,texture:f.texture}),this.backend.popTarget();else{let b=1/(w+1),S=1-b;this.backend.pushTarget(m,[0,0,0,0]),this.backend.drawTexturedQuad({...g,texture:p.texture,tint:[S,S,S,S]}),this.backend.drawTexturedQuad({...g,texture:f.texture,tint:[b,b,b,b],blend:"add"}),this.backend.popTarget(),[p,m]=[m,p]}}let y=Ha(s,t);y?this.applyBloom(p,u,h,y):this.backend.drawTexturedQuad({...g,texture:p.texture}),this.backend.endFrame(),this.evictGroupTargets()}async gpuFinish(){this.initialized&&await this.backend.finish()}setGroupTargetPoolCap(t){this.groupTargetPoolCapBytes=t}evictGroupTargets(){let t=this.groupTargetPoolCapBytes;if(t<=0)return;let i=0,s=[];for(let[r,n]of this.groupTargets.entries()){let a=n.width*n.height*4;i+=a,n.lastTouched!==this.frameIndex&&s.push({key:r,entry:n,bytes:a})}if(!(i<=t)){s.sort((r,n)=>(r.entry.lastTouched??-1)-(n.entry.lastTouched??-1));for(let r of s){if(i<=t)break;this.backend.destroyRenderTarget(r.entry.target),this.groupTargets.delete(r.key),i-=r.bytes}}}acquireBlurTarget(t,i,s){let r=this.blurTargets[t];if(r&&r.width===i&&r.height===s)return r.target;r&&this.backend.destroyRenderTarget(r.target);let n=this.backend.createRenderTarget(i,s);return this.blurTargets[t]={target:n,width:i,height:s},n}async renderAsync(t,i){if(!this.initialized)return;t!==this.currentSource&&this.load(t);let s=typeof t.duration=="number"?t.duration:0,r=[],n=[];this.collectActiveVideos(t.elements,i,s,n);for(let{el:a,clock:o}of n){let c=String(a.source??""),l=this.videos.get(c);if(!l||!l.video)continue;let u=Rs(o,{elementStart:Dr(a.time),trimStart:Dr(a.trim_start),trimDuration:Ji(a.trim_duration),rate:Ki(a.playback_rate),loop:a.loop===!0,timeRemap:Ri(a.time_remap)},Number.isFinite(l.video.duration)?l.video.duration:0);r.push(Lo(l.video,u))}r.length>0&&await Promise.all(r),await this.prepareVideoFrames(i),this.frame(i)}async mixExportAudio(t){let i=typeof t.duration=="number"?t.duration:10,s=new Map;for(let[r,n]of this.audioBuffers.entries())s.set(r,n);try{return await il(t,s,i)}catch(r){return $().warn("Audio mix failed; exporting video only:",r instanceof Error?r.message:r),null}}async exportFrames(t){if(!this.initialized)throw new Error("ClipkitRuntime.exportFrames() called before init()");let i=this.currentSource;if(!i)throw new Error("No source loaded");if(t.onAudio){let s=await this.mixExportAudio(i);s&&await t.onAudio(sl(s))}this.transparentBackground=t.alpha===!0;try{return await new er(this.canvas,this).exportFrames(i,t)}finally{this.transparentBackground=!1}}async export(t={}){if(!this.initialized)throw new Error("ClipkitRuntime.export() called before init()");let i=this.currentSource;if(!i)throw new Error("No source loaded");let s=t.audio;if(!s){let f=await this.mixExportAudio(i);f&&(s={buffer:f})}let r=i.width??1920,n=i.height??1080,a=t.renderResolution??"source",{pixelRatio:o,defaultBitrate:c,defaultCodec:l}=_o(a,r,n),u=this.backend.width*1,h=this.backend.height*1;o!==1&&($().info(\`Export at \${a}: scaling backend to \${Math.round(r*o)}\\xD7\${Math.round(n*o)} (pixelRatio=\${o.toFixed(3)})\`),this.backend.resize(r,n,o));try{return await new er(this.canvas,this).export(i,{codec:l,bitrate:c,...t,audio:s})}finally{o!==1&&this.backend.resize(u,h)}}dispose(){if(!this.disposed){this.disposed=!0,this.images.clear();for(let[,t]of this.videos.entries())t.frameSource?.dispose();this.videos.clear(),this.fontAtlases.clear(),this.svgRasters.clear(),this.maskedTexts.clear();for(let[,t]of this.groupTargets.entries())this.backend.destroyRenderTarget(t.target);this.groupTargets.clear();for(let t of this.blurTargets)t&&this.backend.destroyRenderTarget(t.target);this.blurTargets=[],this.luts.clear(),this.backend.dispose()}}makeContext(t){let i=this.currentSource,s=i&&typeof i.duration=="number"?i.duration:0,r={width:this.backend.width,height:this.backend.height},n=i?.camera?$a(i.camera,t,r):Dn,a=i?.camera?i.camera.sort!=="paint":!!i&&xo(i.elements),o=i?Ql(i,t):[],c=i?Kl(i,t):null;if(c?.image){let u=this.envAvg.get(c.image);u&&(c.avg=[u[0],u[1],u[2]])}let l=i?.camera?Jl(i.camera,t,r):[r.width/2,r.height/2,1e3];return{backend:this.backend,canvas:r,time:t,sourceDuration:s,frameIndex:this.frameIndex,images:this.images,videos:this.videos,fontAtlases:this.fontAtlases,svgRasters:this.svgRasters,maskedTexts:this.maskedTexts,groupTargets:this.groupTargets,luts:this.luts,modelMatrix:n,worldMatrix:Dn,lights:o,eye:l,environment:c,depthSort:a,opacityFactor:1,timeOffset:0,surfaceWidth:this.backend.width,surfaceHeight:this.backend.height}}};function xo(e){for(let t of e){let i=t;if(i.z!==void 0||i.x_rotation!==void 0||i.y_rotation!==void 0||i.keyframe_animations?.some(s=>s.property==="z"||s.property==="x_rotation"||s.property==="y_rotation"||s.property==="position"&&s.keyframes.some(r=>Array.isArray(r.value)&&r.value.length===3))||i.type==="group"&&Array.isArray(i.elements)&&xo(i.elements)||i.mask?.elements&&xo(i.mask.elements))return!0}return!1}function Dr(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=parseFloat(e);return Number.isFinite(t)?t:0}return 0}function kb(e,t){if(e==="auto"||e==="end"||e==null)return t;if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=parseFloat(e);return Number.isFinite(i)?i:t}return t}window.runHarness=async function(t,i={}){try{let s=t.width??1920,r=t.height??1080,n=document.createElement("canvas");n.width=s,n.height=r,n.style.cssText="position:fixed; top:0; left:0;",document.body.appendChild(n);let a=new tr(n);if(!await a.init({backend:i.backend??"auto"}))throw new Error(\`runtime.init() failed (backend preference: \${i.backend??"auto"}). Try forcing backend 'webgl2'.\`);a.load(t),await a.preload();let c=t.frame_rate??30,l=typeof t.duration=="number"?t.duration:10,u=Math.max(1,Math.ceil(l*c)),h=await a.export({framerate:c,renderResolution:i.resolution,...i.bitrate?{bitrate:i.bitrate}:{},onProgress:p=>{let m=Math.round(p*u);window.__clipkitReportProgress?.(m,u).catch(()=>{})}}),f=Tb(await h.arrayBuffer());await window.__clipkitReportResult?.(f)}catch(s){let r=s instanceof Error?s.stack??s.message:String(s);await window.__clipkitReportError?.(r)}};window.renderStill=async function(t,i={}){try{let s=t.width??1920,r=t.height??1080,n=document.createElement("canvas");n.id="__clipkit_still",n.width=s,n.height=r,n.style.cssText=\`position:fixed; top:0; left:0; width:\${s}px; height:\${r}px;\`,document.body.appendChild(n);let a=new tr(n);if(!await a.init({backend:i.backend??"auto"}))throw new Error(\`runtime.init() failed (backend preference: \${i.backend??"auto"}).\`);a.load(t),await a.preload(),await a.renderAsync(t,i.time??0),await a.gpuFinish(),await window.__clipkitStillReady?.()}catch(s){let r=s instanceof Error?s.stack??s.message:String(s);await window.__clipkitReportError?.(r)}};function Tb(e){let t=new Uint8Array(e),i=32768,s="";for(let r=0;r<t.length;r+=i){let n=t.subarray(r,Math.min(r+i,t.length));s+=String.fromCharCode.apply(null,Array.from(n))}return btoa(s)}})();
|
|
2014
|
+
`;
|
|
2015
|
+
//# sourceMappingURL=embedded.js.map
|