cozyclay 3.1.5 → 3.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/app/index.html +1 -1
- package/dist/assets/{app-CTKcyPM-.js → app-BLS1Zaru.js} +1 -1
- package/dist/cozyclay-package.json +1 -1
- package/dist/index.html +1 -1
- package/mcp/project-camera.mjs +43 -0
- package/package.json +2 -1
- package/tools/verify-package-tarball.mjs +29 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 3.1.6 - 2026-10-25
|
|
6
|
+
|
|
7
|
+
The npm package ships the MCP module the live tools need, so the Studio's live tools and `cozyclay mcp` work on a fresh install.
|
|
8
|
+
|
|
9
|
+
Studio
|
|
10
|
+
|
|
11
|
+
- A 3.1.5 global install shows the **Update** chip in the top bar for the
|
|
12
|
+
first time, since this is the first release after the chip shipped.
|
|
13
|
+
**Update now**, or the command it offers to copy, installs 3.1.6; then
|
|
14
|
+
restart `cclay`.
|
|
15
|
+
|
|
16
|
+
MCP
|
|
17
|
+
|
|
18
|
+
- The npm package now ships `mcp/project-camera.mjs`, so the Studio's live
|
|
19
|
+
tools and `cozyclay mcp` start on an npm install instead of failing with
|
|
20
|
+
"Cannot find module" (broken since 3.1.2). The package check now fails a
|
|
21
|
+
release whose `bin/` or `mcp/` code imports a file the package leaves out.
|
|
22
|
+
|
|
5
23
|
## 3.1.5 - 2026-10-25
|
|
6
24
|
|
|
7
25
|
The Studio tells you when a new release is out and installs it in one click, Claude models work in the agent panel again, IK edits stay on their own character, turns and walks look more natural, and anonymous analytics show where the Studio gets in the way.
|
package/dist/app/index.html
CHANGED
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
<title>CozyClay Studio — 3D staging and previs in your browser</title>
|
|
35
35
|
|
|
36
36
|
<script defer src="https://static.cloudflareinsights.com/beacon.min.js" data-cf-beacon='{"token": "6a4384d1375d4ffc8a30a6346a8ad1a0"}'></script>
|
|
37
|
-
<script type="module" crossorigin src="/assets/app-
|
|
37
|
+
<script type="module" crossorigin src="/assets/app-BLS1Zaru.js"></script>
|
|
38
38
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
|
|
39
39
|
<link rel="modulepreload" crossorigin href="/assets/task-board-CkLZGPkv.js">
|
|
40
40
|
<link rel="modulepreload" crossorigin href="/assets/fflate.module-KbGj5-H6.js">
|
|
@@ -5117,7 +5117,7 @@ void main() {
|
|
|
5117
5117
|
float alpha = vAlpha * pow(sin(PI * vAcross), 0.6) * globalOpacity;
|
|
5118
5118
|
if (alpha < 0.002) discard;
|
|
5119
5119
|
gl_FragColor = effectOut(vAdd > 0.5 ? vColor : effectLight(vColor, vViewPos), alpha, vAdd);
|
|
5120
|
-
}`;function pfe(){let e=new Uint8Array(65536),t=(e,t,n)=>{let r=Math.sin(e*127.1+t*311.7+n*74.7)*43758.5453;return r-Math.floor(r)},n=(e,n,r)=>{let i=Math.floor(e),a=Math.floor(n),o=e-i,s=n-a,c=o*o*(3-2*o),l=s*s*(3-2*s),u=t(i,a,r)+(t(i+1,a,r)-t(i,a,r))*c;return u+(t(i,a+1,r)+(t(i+1,a+1,r)-t(i,a+1,r))*c-u)*l};for(let t=0;t<4;t+=1)for(let r=0;r<64;r+=1)for(let i=0;i<64;i+=1){let a=(i+.5)/64*2-1,o=(r+.5)/64*2-1,s=Math.hypot(a,o),c=Math.exp(-s*s*4.2)*(1-Math.min(1,Math.max(0,(s-.82)/.18)));if(t>0){let e=.55*n(a*3+5,o*3,t)+.3*n(a*6,o*6+3,t)+.15*n(a*12+1,o*12,t);c*=Math.min(1,Math.max(0,1.6*e-.25))}let l=(((t>>1)*64+r)*128+(t&1)*64+i)*4;e[l]=e[l+1]=e[l+2]=e[l+3]=Math.round(255*Math.min(1,c))}let r=new mp(e,128,128,ac);return r.minFilter=tl,r.magFilter=cu,r.generateMipmaps=!0,r.needsUpdate=!0,r}function d8(e,t,n={}){return new Hd({uniforms:{...qc.merge([Rm.lights,Rm.fog]),globalOpacity:{value:1},...n},vertexShader:e,fragmentShader:t,lights:!0,fog:!0,transparent:!0,depthWrite:!1,side:2,blending:5,blendEquation:100,blendSrc:201,blendDst:205,blendSrcAlpha:201,blendDstAlpha:205})}function f8(e,t,n){let r=new Ef(1,1),i={};for(let[e,a]of Object.entries(n))i[e]=new _d(new Float32Array(t*a),a).setUsage(Kl),r.setAttribute(e,i[e]);let a=new jd(r,e,t);return a.instanceMatrix.array.fill(0),a.count=0,a.frustumCulled=!1,a.renderOrder=5,a.raycast=()=>{},a.userData.noInk=!0,{mesh:a,attributes:i}}var p8=(e,t)=>{for(let n of Object.values(e))n.clearUpdateRanges(),n.addUpdateRange(0,t*n.itemSize),n.needsUpdate=!0};function mfe(){let e=pfe(),t=f8(d8(lfe,ufe,{map:{value:e}}),j$,{iPos:3,iParams:4,iColor:4,iStreak:4}),n=f8(d8(dfe,ffe),512,{rA0:3,rB0:3,rA1:3,rB1:3,rAlpha:2,rColor:4}),r=t.attributes,i=n.attributes;return{particles:t.mesh,ribbons:n.mesh,update(e,a,o=1){let s=0,c=0;Z$(e.records,e,a,{particle(e){s>=2e3||(r.iPos.array.set([e.x,e.y,e.z],s*3),r.iParams.array.set([e.size,e.angle,e.variant,+!e.additive],s*4),r.iColor.array.set([e.r,e.g,e.b,e.alpha],s*4),r.iStreak.array.set([e.sx,e.sy,e.sz,+!!e.additive],s*4),s+=1)},segment(e,t){c>=512||(i.rA0.array.set(e.a0,c*3),i.rB0.array.set(e.b0,c*3),i.rA1.array.set(e.a1,c*3),i.rB1.array.set(e.b1,c*3),i.rAlpha.array.set([e.alpha0,e.alpha1],c*2),i.rColor.array.set([...t.rgb,+!!t.effect.additive],c*4),c+=1)}}),t.mesh.count=s,n.mesh.count=c,p8(r,s),p8(i,c);for(let e of[t.mesh,n.mesh])e.material.uniforms.globalOpacity.value=o},dispose(){e.dispose();for(let e of[t.mesh,n.mesh])e.geometry.dispose(),e.material.dispose(),e.dispose?.()}}}var m8=Symbol(`effects`),hfe=`#7fd4f0`,h8=e=>{e&&e.layers.set(5)};function gfe({object:e}){let t=e.effect?.preset===`trail`,n=t?Math.max(.05,(e.effect?.width??.5)/2):.06,r=(0,Z.useMemo)(()=>{let e=.05,r=[[e,0,0],[0,e,0],[0,e,0],[-.05,0,0],[-.05,0,0],[0,-.05,0],[0,-.05,0],[e,0,0],[0,0,e],[0,e,0],[0,e,0],[0,0,-.05],[0,0,-.05],[0,-.05,0],[0,-.05,0],[0,0,e]],i=t?[[0,-n,0],[0,n,0],[-.03,-n,0],[.03,-n,0],[-.03,n,0],[.03,n,0]]:[[0,e,0],[0,.16,0],[0,.16,0],[.025,.12,0],[0,.16,0],[-.025,.12,0]],a=new Ol;return a.setAttribute(`position`,new uu([...r,...i].flat(),3)),a},[t,n]);return(0,Z.useEffect)(()=>()=>r.dispose(),[r]),(0,Q.jsxs)(`group`,{userData:{effectMarker:!0},children:[(0,Q.jsx)(`lineSegments`,{ref:h8,geometry:r,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{color:hfe,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),(0,Q.jsxs)(`mesh`,{ref:h8,visible:!1,userData:{emptyPick:!0},children:[(0,Q.jsx)(`sphereGeometry`,{args:[.08,12,8]}),(0,Q.jsx)(`meshBasicMaterial`,{})]})]})}var _fe=e=>(t,n)=>{let r=e?.current?.get(t);return r?(r.place(),r.world(n)):null};function vfe({objects:e,frameRef:t=null,take:n=null,registryRef:r=null,fadeOpacity:i=null}){let a=(0,Z.useMemo)(()=>e1(e),[e]),o=a.records.length>0,s=(0,Z.useMemo)(()=>o?mfe():null,[o]);(0,Z.useEffect)(()=>()=>s?.dispose(),[s]);let c=(0,Z.useMemo)(()=>_fe(r),[r]),l=(0,Z.useMemo)(()=>({...a,take:n??{},live:c}),[a,n,c]),u=(0,Z.useRef)(null),d=()=>{if(!s)return;let e=t?.current??0,n=i??1,r=[e,l,n];!l.records.some(e=>e.attach)&&u.current?.every((e,t)=>e===r[t])||(u.current=r,s.update(l,e,n))};return ty(d),(0,Z.useEffect)(()=>($$(()=>l),()=>$$(null)),[l]),(0,Z.useEffect)(()=>{let e=r?.current;if(!(!e||!s))return e.set(m8,{place:d,world:()=>null}),()=>{e.delete(m8)}}),s?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`primitive`,{object:s.particles}),(0,Q.jsx)(`primitive`,{object:s.ribbons})]}):null}var yfe=.2,g8=`cozyclay.poseObjectOpacity`;function bfe(e=globalThis.localStorage){let t=Number(e?.getItem?.(g8));return e?.getItem?.(`cozyclay.poseObjectOpacity`)==null||!Number.isFinite(t)?yfe:Math.min(1,Math.max(0,t))}function xfe(e,t=globalThis.localStorage){try{t?.setItem?.(g8,String(e))}catch{return}}var _8=new WeakMap,v8=()=>{};function Sfe(e){return Array.isArray(e.material)?e.material:e.material?[e.material]:[]}var y8=!1;function b8(e){y8=e}function Cfe(e,t){b8(!0),e?.();try{return t()}finally{b8(!1),e?.()}}function wfe(e,t,n=1){let r=y8||t==null||t>=1?1:t,i=r*n,a=i<1,o=r<1;e.traverse(e=>{if(e.isMesh){for(let t of Sfe(e))if(a){_8.has(t)||_8.set(t,{transparent:t.transparent,opacity:t.opacity,depthWrite:t.depthWrite});let e=_8.get(t).opacity*i;(t.opacity!==e||!t.transparent||t.depthWrite)&&(t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.needsUpdate=!0)}else _8.has(t)&&(Object.assign(t,_8.get(t)),_8.delete(t),t.needsUpdate=!0);o&&e.raycast!==v8?(e.userData.poseFadeRaycast=e.raycast,e.raycast=v8):!o&&e.raycast===v8&&(e.raycast=e.userData.poseFadeRaycast,delete e.userData.poseFadeRaycast)}})}var Tfe=.2,Efe=.02,Dfe=()=>{},x8=new WeakMap;function Ofe(e){return x8.has(e)}var S8=null;function kfe(){if(S8)return S8;let e=new Uint8Array(16384);for(let t=0;t<64;t+=1)for(let n=0;n<64;n+=1){let r=Math.hypot(n+.5-64/2,t+.5-64/2)/(64/2),i=r>=1?0:(1-r)**1.6,a=Math.min(1,.7*Math.exp(-((r/.25)**2))+.5*i);e.set([255,255,255,Math.round(a*255)],(t*64+n)*4)}return S8=new mp(e,64,64),S8.magFilter=cu,S8.minFilter=cu,S8.needsUpdate=!0,S8}function Afe(){let e=new om({map:kfe(),blending:2,transparent:!0,depthWrite:!1,fog:!1}),t=new Gp(e);return t.userData.glowHalo=!0,t.userData.beautyOnly=!0,t.raycast=Dfe,t.castShadow=!1,t.receiveShadow=!1,t.renderOrder=2,t}function jfe(e,t,n){e.traverse(e=>{if(!(!e.isMesh||!e.layers.isEnabled(0))){t(e);for(let t of Array.isArray(e.material)?e.material:[e.material])t?.emissive?.isColor&&n(t)}})}function Mfe(e,t){for(let[e,n]of t.bases)e.emissive.copy(n.emissive),e.emissiveIntensity=n.intensity;for(let e of t.shadowless)e.castShadow=!0;t.halo.removeFromParent(),t.halo.material.dispose(),x8.delete(e)}function Nfe(e,t){let n=(e.footprint?.width??0)*Math.abs(t.x),r=(e.height??0)*Math.abs(t.y),i=(e.footprint?.depth??0)*Math.abs(t.z),a=Math.max(n,r,i)/2;return{centreY:(e.height??0)/2,radius:a>0?a:Efe}}function Pfe(e,t,n){let r=t.glow,i=x8.get(e);if(!r){i&&Mfe(e,i);return}i||(i={halo:Afe(),bases:new Map,shadowless:new Set},x8.set(e,i)),i.halo.parent!==e&&e.add(i.halo);let a=r.intensity*n;jfe(e,e=>{e.castShadow&&(e.castShadow=!1,i.shadowless.add(e))},e=>{i.bases.has(e)||i.bases.set(e,{emissive:e.emissive.clone(),intensity:e.emissiveIntensity}),e.emissive.set(r.color),e.emissiveIntensity=a});let{centreY:o,radius:s}=Nfe(t,e.scale),c=2*s*r.halo*n,l=i.halo;l.visible=c>0&&a>0,l.position.set(0,o,0),l.scale.set(c/(Math.abs(e.scale.x)||1),c/(Math.abs(e.scale.y)||1),1),l.material.color.set(r.color).multiplyScalar(Tfe*a)}var Ffe=Math.PI/180,C8=new X(0,-1,0),w8=new X,T8=new X,E8=new Vu,Ife=new X;function D8(e,t){for(let n of e.children)if(n.userData?.[t])return n;return null}function Lfe(e,t,n){let r=D8(e,`sceneLight`);if(!r)return;let{color:i,intensity:a,range:o,angle:s,softness:c,aim:l}=t.light;if(r.color.set(i),r.intensity=a*qt*n,r.distance=o,r.castShadow&&r.isPointLight){let e=o>0?o:40;r.shadow.camera.far!==e&&(r.shadow.camera.far=e,r.shadow.camera.updateProjectionMatrix())}if(!r.isSpotLight)return;r.angle=s*Ffe,r.penumbra=c,e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(T8,E8,Ife),l?w8.set(l.x-T8.x,l.y-T8.y,l.z-T8.z):w8.copy(C8).applyQuaternion(E8),w8.lengthSq()<1e-10&&w8.copy(C8).applyQuaternion(E8),w8.normalize(),r.target.position.copy(T8).add(w8),r.target.updateMatrixWorld();let u=D8(e,`lightMarker`)?.children.find(e=>e.userData?.lightCone);u&&u.quaternion.setFromUnitVectors(C8,w8.applyQuaternion(E8.invert()))}function Rfe(e,t,n,r){if(!t.light&&!t.glow&&!Ofe(e))return;let i=tZ(t.id,n,r)*(t.light?Vn(t.id,n,t.light.flicker,r?.fps):1);t.light&&Lfe(e,t,i),Pfe(e,t,i)}var zfe=Math.PI/180,O8=.07,Bfe=.7;function Vfe(e,t){let n=e===`spot`?new nf:new Rl;if(n.position.set(0,0,0),n.decay=2,n.castShadow=t,n.userData.sceneLight=!0,t){let t=e===`spot`?1024:512;n.shadow.mapSize.set(t,t),n.shadow.bias=-4e-4,n.shadow.normalBias=.02,n.shadow.camera.near=.03,n.shadow.camera.far=40,n.shadow.camera.updateProjectionMatrix()}return n}function k8(e,t,n,r,i=0,a=24){for(let o=0;o<a;o+=1)for(let s of[o,o+1]){let o=s/a*Math.PI*2,c=[0,i,0];c[n]+=Math.cos(o)*t,c[r]+=Math.sin(o)*t,e.push(...c)}return e}function A8(e){let t=new Ol;return t.setAttribute(`position`,new uu(e,3)),t}function Hfe(){let e=[];k8(e,O8,0,2),k8(e,O8,0,1),k8(e,O8,1,2);for(let t=0;t<8;t+=1){let n=t/8*Math.PI*2;e.push(Math.cos(n)*O8*1.3,0,Math.sin(n)*O8*1.3,Math.cos(n)*O8*2,0,Math.sin(n)*O8*2)}return A8(e)}function Ufe(e){let t=Bfe*Math.tan(e*zfe),n=k8([],t,0,2,-.7,32);for(let e=0;e<4;e+=1){let r=e/4*Math.PI*2;n.push(0,0,0,Math.cos(r)*t,-.7,Math.sin(r)*t)}return A8(n)}var j8=e=>{e&&e.layers.set(5)};function Wfe({type:e,angle:t,color:n}){let r=(0,Z.useMemo)(()=>Hfe(),[]),i=(0,Z.useMemo)(()=>e===`spot`?Ufe(t):null,[e,t]);return(0,Z.useEffect)(()=>()=>r.dispose(),[r]),(0,Z.useEffect)(()=>()=>i?.dispose(),[i]),(0,Q.jsxs)(`group`,{userData:{lightMarker:!0},children:[(0,Q.jsx)(`lineSegments`,{ref:j8,geometry:r,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{color:n,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),i&&(0,Q.jsx)(`group`,{userData:{lightCone:!0},children:(0,Q.jsx)(`lineSegments`,{ref:j8,geometry:i,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{color:n,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.55})})}),(0,Q.jsxs)(`mesh`,{ref:j8,visible:!1,userData:{emptyPick:!0},children:[(0,Q.jsx)(`sphereGeometry`,{args:[u*.45,12,8]}),(0,Q.jsx)(`meshBasicMaterial`,{})]})]})}function Gfe({object:e}){let{type:t,shadow:n,angle:r,color:i}=e.light,a=(0,Z.useMemo)(()=>Vfe(t,n),[t,n]);return(0,Z.useEffect)(()=>()=>a.dispose(),[a]),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`primitive`,{object:a}),(0,Q.jsx)(Wfe,{type:t,angle:r,color:i})]})}function Kfe(e){let t=ey(e=>e.invalidate);(0,Z.useEffect)(()=>{t()},[t,e.light,e.glow])}function qfe({kind:e,object:t,color:n,autoColor:r,depthRank:i=0}){let a=e===`plane`?2:0,o=Zde(t,e,a,i),s=!(o?.transmission>0),c=o?(0,Q.jsx)(`primitive`,{object:o,attach:`material`}):r?(0,Q.jsx)(`meshStandardMaterial`,{...j0(r),side:a,...s8(i)}):(0,Q.jsx)(`meshStandardMaterial`,{color:n,roughness:.82,side:a,...s8(i)});return e===`sphere`?(0,Q.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`sphereGeometry`,{args:[.5,28,18]}),c]}):e===`capsule`?(0,Q.jsxs)(`mesh`,{position:[0,.7,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`capsuleGeometry`,{args:[.35,.7,6,18]}),c]}):e===`cylinder`?(0,Q.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`cylinderGeometry`,{args:[.5,.5,1,26]}),c]}):e===`cone`?(0,Q.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`coneGeometry`,{args:[.5,1,26]}),c]}):e===`plane`?(0,Q.jsxs)(`mesh`,{position:[0,.004,0],rotation:[-Math.PI/2,0,0],receiveShadow:!0,children:[(0,Q.jsx)(`planeGeometry`,{args:[2,2]}),c]}):(0,Q.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`boxGeometry`,{args:[1,1,1]}),c]})}function Jfe(e){let[t,n]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{if(n(null),e)return tr(e,n)},[e]),t}var Yfe=`#c2c6c8`;function Xfe({object:e}){let t=Jfe(e.assetId),n=e.footprint?.width??1,r=e.height??1;return(0,Q.jsxs)(`mesh`,{position:[0,r/2,0],castShadow:!0,receiveShadow:!0,userData:{cutoutTexture:t??null},children:[(0,Q.jsx)(`planeGeometry`,{args:[n,r]}),(0,Q.jsx)(`meshStandardMaterial`,{map:t??null,color:t?e.color:Yfe,side:2,alphaTest:t?.15:0,alphaToCoverage:!!t,roughness:.92,metalness:0})]})}function Zfe({object:e,depthRank:t=0}){let{recipe:n,autoColor:r}=e,i=(0,Z.useMemo)(()=>{let e=Jde(n,r?{materialFor:()=>new Kf(j0(r))}:{});return e.traverse(e=>e.material&&Object.assign(e.material,s8(t))),e},[n,r,t]);return(0,Z.useEffect)(()=>()=>Yde(i),[i]),(0,Q.jsx)(`primitive`,{object:i})}var Qfe=new Set([`cube`,`sphere`,`capsule`,`cylinder`,`cone`,`plane`]),$fe=[{to:[1,0,0],color:`#e5594f`},{to:[0,1,0],color:`#5fb95f`},{to:[0,0,1],color:`#4f86e5`}];function epe(){let e=u/2,t=(0,Z.useMemo)(()=>{let t=[],n=[],r=new Lu;for(let i of $fe)t.push(-i.to[0]*e,-i.to[1]*e,-i.to[2]*e,i.to[0]*e,i.to[1]*e,i.to[2]*e),r.set(i.color),n.push(r.r,r.g,r.b,r.r,r.g,r.b);let i=new Ol;return i.setAttribute(`position`,new uu(t,3)),i.setAttribute(`color`,new uu(n,3)),i},[e]);(0,Z.useEffect)(()=>()=>t.dispose(),[t]);let n=e=>e?.layers.set(5);return(0,Q.jsxs)(`group`,{userData:{emptyMarker:!0},children:[(0,Q.jsx)(`lineSegments`,{ref:n,geometry:t,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{vertexColors:!0,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),(0,Q.jsxs)(`mesh`,{ref:n,visible:!1,userData:{emptyPick:!0},children:[(0,Q.jsx)(`sphereGeometry`,{args:[e*1.25,12,8]}),(0,Q.jsx)(`meshBasicMaterial`,{})]})]})}function tpe({object:e,depthRank:t=0}){let{renderer:n,color:r,autoColor:i}=e;return n===`empty`?(0,Q.jsx)(epe,{}):n===`light`?(0,Q.jsx)(Gfe,{object:e}):n===`effect`?(0,Q.jsx)(gfe,{object:e}):n===`cutout`?(0,Q.jsx)(Xfe,{object:e}):n===`mesh`?(0,Q.jsx)(cfe,{object:e}):n===`sculpt`?(0,Q.jsx)(Zfe,{object:e,depthRank:t}):n===`text`?(0,Q.jsx)(Uce,{object:e}):Qfe.has(n)?(0,Q.jsx)(qfe,{kind:n,object:e,color:r,autoColor:i,depthRank:t}):null}function npe({object:e}){let t=e.renderer===`empty`||e.renderer===`light`||e.renderer===`effect`,n=t?u:Math.max(e.height??1,.08),r=t?u:e.footprint?.width??1,i=t?u:e.footprint?.depth??1,a=(0,Z.useMemo)(()=>new fc(new Of(r*1.04,n*1.04,i*1.04)),[r,n,i]);return(0,Z.useEffect)(()=>()=>a.dispose(),[a]),(0,Q.jsx)(`lineSegments`,{ref:e=>{e&&e.layers.set(5)},geometry:a,position:[0,t?0:n/2,0],renderOrder:998,children:(0,Q.jsx)(`lineBasicMaterial`,{color:`#e7b557`,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1})})}var M8=Math.PI/180,N8=new X,P8=new Vu,F8=new X,I8=new Nl,L8=new Y,R8=new Y,rpe=new Y;function ipe({object:e,selected:t,frameRef:n=null,take:r=null,attachFrameRef:i=null,registryRef:a=null,travelLookupRef:o=null,fadeOpacity:s=null,depthRank:c=0}){let l=(0,Z.useRef)(null),u=e.attach??null,d=()=>{let t=l.current;if(!t)return;let a=n?.current??0,c=n&&!u&&o?.current?cZ(o.current,e.id,a,r??{},R8):null;if((t.visible=eZ(e.id,a,r,o?.current))&&c)c.decompose(t.position,t.quaternion,t.scale);else if(u||e.path){if(N8.set(e.x,e.y??0,e.z),I8.set((e.rotX??0)*M8,e.rot*M8,(e.rotZ??0)*M8,`XYZ`),F8.set(e.scaleX??1,e.scaleY??1,e.scaleZ??1),n&&e.path){let t=ze(e,a,r??{});if(t){N8.set(t.x,t.y,t.z);let n=XX(e,t);I8.set(n.rotX*M8,n.rot*M8,n.rotZ*M8,`YXZ`)}}let o=u?i?.current?.(u.characterId,u.bone??null,rpe)??null:null;o?(L8.compose(N8,P8.setFromEuler(I8),F8),R8.multiplyMatrices(o,L8).decompose(N8,P8,F8),t.position.copy(N8),t.quaternion.copy(P8),t.scale.copy(F8)):(t.position.copy(N8),t.rotation.copy(I8),t.scale.copy(F8))}typeof window<`u`&&((window.__cclayPropWorld??={})[e.id]={x:t.position.x,y:t.position.y,z:t.position.z,quat:{x:t.quaternion.x,y:t.quaternion.y,z:t.quaternion.z,w:t.quaternion.w},frame:a}),wfe(t,s,e.opacity??1),Rfe(t,e,a,r)};ty(d),Kfe(e);let f=(0,Z.useRef)(d);f.current=d;let p=(0,Z.useRef)(null);return p.current||={place:()=>f.current(),world:e=>{let t=l.current;return t?(t.updateWorldMatrix(!0,!1),e?e.copy(t.matrixWorld):t.matrixWorld):null}},(0,Z.useEffect)(()=>{if(!a)return;let t=a.current;return t.set(e.id,p.current),()=>{t.delete(e.id)}},[a,e.id]),(0,Q.jsxs)(`group`,{ref:l,position:[e.x,e.y??0,e.z],rotation:[(e.rotX??0)*M8,e.rot*M8,(e.rotZ??0)*M8],scale:[e.scaleX??1,e.scaleY??1,e.scaleZ??1],userData:{sceneObjectId:e.id},children:[(0,Q.jsx)(tpe,{object:e,depthRank:c}),t&&(0,Q.jsx)(npe,{object:e})]})}function ape({objects:e=[],authoredObjects:t=null,selectedId:n=null,frameRef:r=null,take:i=null,attachFrameRef:a=null,syncRef:o=null,worldRef:s=null,fadeOpacity:c=null}){let l=(0,Z.useRef)(null),u=(0,Z.useRef)(null);u.current=(0,Z.useMemo)(()=>t?new Map(t.map(e=>[e.id,e])):null,[t]);let d=(0,Z.useMemo)(()=>cA(t??e),[t,e]);return l.current||=new Map,o&&(o.current=()=>{for(let e of l.current.values())e.place()}),s&&(s.current=(e,t)=>l.current.get(e)?.world(t)??null),(0,Q.jsxs)(`group`,{children:[rr(e).map(e=>(0,Q.jsx)(ipe,{object:e,selected:e.id===n,frameRef:r,take:i,attachFrameRef:a,registryRef:l,travelLookupRef:u,fadeOpacity:c,depthRank:d.get(e.id)??0},e.id)),(0,Q.jsx)(vfe,{objects:t??e,frameRef:r,take:i,registryRef:l,fadeOpacity:c})]})}var ope=new Y;function spe({objectId:e=null,objectsRef:t,frameRef:n=null,take:r=null,registryRef:i=null,children:a}){let o=(0,Z.useRef)(null),s=()=>{let i=o.current;if(!i)return;let a=e&&t?.current?uZ(t.current,e,n?.current??0,r??{},ope):null;a?a.decompose(i.position,i.quaternion,i.scale):(i.position.set(0,0,0),i.quaternion.identity(),i.scale.set(1,1,1))};ty(s,-1);let c=(0,Z.useRef)(s);return c.current=s,(0,Z.useEffect)(()=>{if(!i)return;let e=i.current,t=()=>c.current();return e.add(t),()=>{e.delete(t)}},[i]),(0,Q.jsx)(`group`,{ref:o,children:a})}var cpe=[139,92,246],z8=.62,lpe=`#141819`,upe=512,B8=1,V8=(e,t,n)=>Math.min(n,Math.max(t,e));function dpe(e,{onChange:t=()=>{},createBitmap:n=globalThis.createImageBitmap,makeCanvas:r=(e,t)=>new OffscreenCanvas(e,t)}={}){let i=e.getContext(`2d`,{willReadFrequently:!0}),a={full:null,preview:null,paint:null,tolerance:.18,brush:18,mode:`paint`,painting:!1,panning:null,last:null,seeds:[],before:null,view:{zoom:1,x:0,y:0},buffer:null,history:[],at:-1};function o(){if(a.paint){for(a.history.length=a.at+1,a.history.push(Uint8Array.from(a.paint));a.history.length>8;)a.history.shift();a.at=a.history.length-1}}function s(e){let t=a.at+e;return!a.paint||t<0||t>=a.history.length?!1:(a.at=t,a.paint.set(a.history[t]),p(),!0)}let c=()=>a.full&&a.preview?a.full.width/a.preview.width:1;function l(){if(!a.paint)return t({painted:0,coverage:0,zoom:1,canUndo:!1,canRedo:!1});let e=0;for(let t=0;t<a.paint.length;t++)e+=a.paint[t];t({painted:e,coverage:e/a.paint.length,zoom:a.view.zoom,canUndo:a.at>0,canRedo:a.at>=0&&a.at<a.history.length-1})}function u(){let t=e.getBoundingClientRect(),n=Math.min(3,Math.max(1,globalThis.devicePixelRatio||1));return{width:Math.max(1,Math.round((t.width||e.width||1)*n)),height:Math.max(1,Math.round((t.height||e.height||1)*n)),left:t.left,top:t.top,dpr:n}}function d(e){return a.preview?Math.min(e.width/a.preview.width,e.height/a.preview.height)*V8(a.view.zoom,B8,16):1}function f(){let e=u(),t=d(e),n=a.preview?a.preview.width*t:0,r=a.preview?a.preview.height*t:0,i=e.width/2/t,o=e.height/2/t,s={x:a.view.x,y:a.view.y};return s.x=n>=e.width?V8(s.x,i,a.preview.width-i):a.preview.width/2,s.y=r>=e.height?V8(s.y,o,a.preview.height-o):a.preview.height/2,{stage:e,scale:t,center:s,width:n,height:r,left:e.width/2-s.x*t,top:e.height/2-s.y*t}}function p(){if(!a.preview)return;let{width:t,height:n,data:o}=a.preview,s=c(),d=a.full.width,p=new Uint8ClampedArray(o.length),[m,h,g]=cpe;for(let e=0;e<n;e++){let n=Math.min(a.full.height-1,Math.floor(e*s));for(let r=0;r<t;r++){let i=e*t+r<<2,c=o[i+3]/255,l=o[i]*c+26*(1-c),u=o[i+1]*c+30*(1-c),f=o[i+2]*c+32*(1-c);a.paint[n*d+Math.min(d-1,Math.floor(r*s))]&&(l=l*.38+m*z8,u=u*.38+h*z8,f=f*.38+g*z8),p[i]=l,p[i+1]=u,p[i+2]=f,p[i+3]=255}}(!a.buffer||a.buffer.width!==t||a.buffer.height!==n)&&(a.buffer=r(t,n),a.buffer.width=t,a.buffer.height=n),a.buffer.getContext(`2d`).putImageData(new ImageData(p,t,n),0,0);let _=u();e.width=_.width,e.height=_.height;let v=f();a.view.x=v.center.x,a.view.y=v.center.y,i.fillStyle=lpe,i.fillRect(0,0,_.width,_.height),i.imageSmoothingEnabled=a.view.zoom<2,i.drawImage(a.buffer,0,0,t,n,v.left,v.top,v.width,v.height),l()}function m(e){let t=f(),n=t.stage.dpr,r=((e.clientX-t.stage.left)*n-t.left)/t.scale,i=((e.clientY-t.stage.top)*n-t.top)/t.scale;return{x:r*c(),y:i*c()}}function h(e){let t=f(),n=t.stage.dpr,r=(e.clientX-t.stage.left)*n-t.left,i=(e.clientY-t.stage.top)*n-t.top;return r>=0&&i>=0&&r<=t.width&&i<=t.height}function g(){let e=f();return Math.max(1,a.brush*e.stage.dpr/2/e.scale*c())}function _(e,t){let n=a.mode===`erase`?0:1,r=g(),i=Math.max(1,Math.ceil(Math.hypot(t.x-e.x,t.y-e.y)/Math.max(1,r*.4))),o=0;for(let s=1;s<=i;s++){let c=e.x+(t.x-e.x)*s/i,l=e.y+(t.y-e.y)*s/i;o+=$re(a.paint,a.full,{x:c,y:l,radius:r,value:n}),a.seeds.push({x:c,y:l})}o&&p()}function v(){let e=a.seeds,t=a.before;if(a.seeds=[],a.before=null,!e.length||!a.full)return;let n=a.mode===`erase`,r=HN(a.full,{points:e,tolerance:a.tolerance,within:n?t:null}),i=+!n,s=0;for(let e=0;e<r.length;e++)!r[e]||a.paint[e]===i||(a.paint[e]=i,s+=1);s&&(o(),p())}let y=t=>{if(!(!a.preview||!h(t))){if(t.preventDefault(),e.setPointerCapture?.(t.pointerId),t.button===1||w){a.panning={x:t.clientX,y:t.clientY};return}a.painting=!0,a.before=Uint8Array.from(a.paint),a.last=m(t),_(a.last,a.last)}},b=e=>{if(a.panning){let t=f(),n=t.stage.dpr;a.view.x=t.center.x-(e.clientX-a.panning.x)*n/t.scale,a.view.y=t.center.y-(e.clientY-a.panning.y)*n/t.scale,a.panning={x:e.clientX,y:e.clientY},p();return}if(!a.painting)return;let t=m(e);_(a.last,t),a.last=t},x=t=>{if(a.panning){a.panning=null,e.hasPointerCapture?.(t.pointerId)&&e.releasePointerCapture(t.pointerId);return}a.painting&&(a.painting=!1,v(),e.hasPointerCapture?.(t.pointerId)&&e.releasePointerCapture(t.pointerId))};function S(e,t,n){if(!a.preview)return;let r=f(),i=r.stage.dpr,o=((e-r.stage.left)*i-r.left)/r.scale,s=((t-r.stage.top)*i-r.top)/r.scale;a.view.zoom=V8(a.view.zoom*n,B8,16);let c=f(),l=(e-c.stage.left)*c.stage.dpr-c.stage.width/2,u=(t-c.stage.top)*c.stage.dpr-c.stage.height/2;a.view.x=o-l/c.scale,a.view.y=s-u/c.scale,p()}let C=e=>{a.preview&&(e.preventDefault(),S(e.clientX,e.clientY,e.deltaY<0?1.15:1/1.15))},w=!1,T=e=>{e.key===` `&&(w=!0)},E=e=>{e.key===` `&&(w=!1)};return e.addEventListener(`pointerdown`,y),e.addEventListener(`pointermove`,b),e.addEventListener(`pointerup`,x),e.addEventListener(`pointercancel`,x),e.addEventListener(`pointerleave`,x),e.addEventListener(`wheel`,C,{passive:!1}),e.addEventListener(`keydown`,T),e.addEventListener(`keyup`,E),{async load(e){let t=await n(new Blob([e.bytes],{type:e.type}));try{let e=(e,n)=>{let i=r(e,n).getContext(`2d`,{willReadFrequently:!0});return i.drawImage(t,0,0,e,n),{data:i.getImageData(0,0,e,n).data,width:e,height:n}};a.full=e(t.width,t.height);let n=Math.min(1,upe/Math.max(t.width,t.height));a.preview=n===1?{data:Uint8ClampedArray.from(a.full.data),width:a.full.width,height:a.full.height}:e(Math.max(1,Math.round(t.width*n)),Math.max(1,Math.round(t.height*n))),a.paint=new Uint8Array(a.full.width*a.full.height),a.view={zoom:1,x:a.preview.width/2,y:a.preview.height/2},a.buffer=null,a.history=[],a.at=-1,o(),p()}finally{t?.close?.()}},setMask(e,t,n){return!a.paint||!e||t!==a.full.width||n!==a.full.height?!1:(a.paint.set(e),o(),p(),!0)},autoDetect(e=a.tolerance){if(!a.full)return 0;a.tolerance=V8(Number(e)||0,.01,.9);let t=HN(a.full,{tolerance:a.tolerance}),n=0;for(let e=0;e<t.length;e++)!t[e]||a.paint[e]||(a.paint[e]=1,n+=1);return n&&o(),p(),n},zoomBy(e){let t=u();S(t.left+t.width/2/t.dpr,t.top+t.height/2/t.dpr,e)},fit(){a.view={zoom:1,x:(a.preview?.width??0)/2,y:(a.preview?.height??0)/2},p()},zoom:()=>a.view.zoom,setTolerance(e){a.tolerance=V8(Number(e)||0,.01,.9)},setBrush(e){a.brush=V8(Number(e)||1,2,200)},setMode(e){a.mode=e===`erase`?`erase`:`paint`},mode:()=>a.mode,tolerance:()=>a.tolerance,clear(){a.paint&&(a.paint.fill(0),o(),p())},undo:()=>s(-1),redo:()=>s(1),canUndo:()=>a.at>0,canRedo:()=>a.at>=0&&a.at<a.history.length-1,hasPaint:()=>!!a.paint?.some(e=>e===1),options(){return a.paint&&this.hasPaint()?{mask:a.paint,maskWidth:a.full.width,maskHeight:a.full.height}:null},dispose(){e.removeEventListener(`pointerdown`,y),e.removeEventListener(`pointermove`,b),e.removeEventListener(`pointerup`,x),e.removeEventListener(`pointercancel`,x),e.removeEventListener(`pointerleave`,x),e.removeEventListener(`wheel`,C),e.removeEventListener(`keydown`,T),e.removeEventListener(`keyup`,E)}}}var fpe={name:`cozyclay`,version:`3.1.5`,description:`Open source previs software in the browser: block a scene, pose characters, author camera moves and cuts, then take the same shots to an AI video model.`,scripts:{dev:`node tools/dev-full.mjs --host 127.0.0.1 --port 5180`,"dev:ui":`vite`,build:`vite build && node tools/sitemap.mjs`,lint:`node tools/check-knip.mjs && node tools/check-loc.mjs && node tools/check-eslint.mjs`,"lint:update":`node tools/check-knip.mjs --update && node tools/check-loc.mjs --update && node tools/check-eslint.mjs --update`,test:`npm run build && node tools/run-tests.mjs`,"test:manifest":`node tools/run-tests.mjs --list`,"test:analytics":`node test/verify-analytics.mjs`,"test:lifecycle":`npm run build && node test/process/verify-lifecycle.mjs`,"test:mcp-package":`node test/process/verify-mcp-package-isolation.mjs`,"test:hierarchy":`node test/verify-hierarchy.mjs`,"test:history":`node test/verify-history.mjs`,"test:scene-objects":`node test/verify-scene-objects.mjs`,"test:scene-assets":`node test/verify-scene-assets.mjs`,"test:scene-mesh":`node test/verify-scene-mesh.mjs`,"test:mesh-browser":`node tools/qa-browser.mjs -- node test/verify-mesh-browser.mjs`,"test:asset-shelf":`node test/verify-asset-shelf.mjs`,"test:matte":`node test/verify-matte.mjs`,"test:matte-editor":`node test/verify-matte-editor.mjs`,"test:scenes":`node test/verify-scenes.mjs`,"test:camera-move":`node test/verify-camera-move.mjs`,"test:cuts":`node test/verify-cuts.mjs`,"test:project-menu":`node tools/qa-browser.mjs -- node test/verify-project-menu-browser.mjs`,"test:first-success-guide":`QA_STARTUP_CHOOSER=1 node tools/qa-browser.mjs -- node test/verify-first-success-guide-browser.mjs`,"test:objects":`node tools/qa-browser.mjs -- node test/verify-object-gizmo.mjs`,"test:theme":`node test/verify-theme.mjs`,"test:appearance":`node test/verify-appearance.mjs`,"test:auto-color":`node test/verify-auto-color.mjs`,"test:shot-guides":`node test/verify-shot-guides.mjs`,"test:layout":`node test/verify-layout.mjs`,"test:timeline-camera":`node test/verify-timeline-camera.mjs`,"test:timeline-shots":`node test/verify-timeline-shots.mjs`,preview:`vite preview`,"test:ardy":`node tools/run-tests.mjs --scope ardy`,"test:ik-browser":`node tools/qa-browser.mjs -- node test/verify-ik-browser.mjs`,"demo:api":`npm --prefix workers/api run dev`,"demo:api:install":`npm --prefix workers/api ci`,"qa:browser":`node tools/qa-browser.mjs --`,"test:shot-authoring":`node test/verify-shot-authoring.mjs`,"test:camera-follow":`node test/verify-camera-follow.mjs`,"test:sample-at":`node test/verify-sample-at.mjs`,"test:offscreen-export":`node test/verify-offscreen-export.mjs`,"test:offscreen-export-browser":`node tools/qa-browser.mjs -- node test/verify-offscreen-export-browser.mjs`,"test:otio":`node test/verify-otio.mjs`,"test:usd-camera":`node test/verify-usd-camera.mjs`,"test:camera-rail-browser":`node tools/qa-browser.mjs -- node test/verify-camera-rail-browser.mjs`,"test:blocking-depth":`node test/verify-blocking-depth.mjs`,"test:pwa":`node test/verify-pwa.mjs`,"test:update-check":`node test/verify-update-check.mjs`,"test:korean-ui":`node test/verify-korean-ui.mjs`,prepack:`npm run build && node tools/prepare-package.mjs`,postpack:`node tools/prepare-package.mjs --clean`,prepublishOnly:`npm run build && node tools/prepare-package.mjs --check-key && node tools/prepare-package.mjs && node tools/verify-package-tarball.mjs`,"metrics:snapshot":`node tools/metrics-snapshot.mjs`},license:`AGPL-3.0-or-later`,type:`module`,dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.3.306`,"@earendil-works/pi-agent-core":`1.4.0`,"@earendil-works/pi-ai":`1.4.0`,"@earendil-works/pi-codemode":`1.4.0`,zod:`^4.6.7`},devDependencies:{"@eslint/js":`^10.0.1`,"@react-three/drei":`^10.7.7`,"@react-three/fiber":`^9.7.0`,"@vitejs/plugin-react":`^6.0.5`,eslint:`^10.12.0`,"eslint-plugin-react-hooks":`^7.1.1`,globals:`^17.13.0`,knip:`^6.41.0`,mediabunny:`^1.55.2`,"posthog-js":`^1.418.12`,react:`^19.2.8`,"react-dom":`^19.2.8`,"react-hot-toast":`^2.6.0`,"react-icons":`^5.7.0`,reactflow:`^11.11.4`,three:`^0.185.1`,"three-bvh-csg":`^0.0.18`,"three-mesh-bvh":`^0.9.16`,vite:`^8.2.0`},bin:{cozyclay:`bin/cozyclay.mjs`,cclay:`bin/cozyclay.mjs`},files:[`bin`,`dist`,`!dist/media/*.mp4`,`src`,`tools`,`!tools/qa-*.mjs`,`mcp/server.mjs`,`mcp/tool-handlers.mjs`,`mcp/live-hub.mjs`,`mcp/mesh-file.mjs`,`mcp/image-file.mjs`,`mcp/runtime`,`mcp/package.json`,`mcp/README.md`,`mcp/LIVE-PROTOCOL.md`,`README.md`,`INSTALL_FOR_AGENTS.md`,`CHANGELOG.md`,`LICENSE`,`LICENSES`,`LICENSING.md`,`THIRD_PARTY_NOTICES.md`],exports:{"./package.json":`./package.json`,"./src/*":`./src/*`,"./mcp/*":`./mcp/*`},peerDependencies:{three:`>=0.180`},peerDependenciesMeta:{three:{optional:!0}},engines:{node:`>=22.19.0`},keywords:[`3d`,`previs`,`animation`,`blocking`,`threejs`,`react-three-fiber`,`webgl`,`motion`,`ardy`,`storyboard`,`previz`],repository:{type:`git`,url:`git+https://github.com/NomaDamas/CozyClay.git`},homepage:`https://cozyclay.org/`,bugs:{url:`https://github.com/NomaDamas/CozyClay/issues`},publishConfig:{access:`public`}};function H8({id:e}){let t=`/thumbs/${e}-${Em()}.webp`,[n,r]=(0,Z.useState)(null);return n===t?null:(0,Q.jsx)(`img`,{className:`v2-start-art`,src:t,alt:``,"aria-hidden":`true`,draggable:`false`,decoding:`async`,onError:()=>r(t)})}function ppe(){return(0,Q.jsx)(`img`,{className:`v2-start-brand-mark`,src:`/icons/icon-192.png`,alt:``,"aria-hidden":`true`,draggable:`false`,width:`26`,height:`26`})}var mpe=fpe.version,U8=Object.freeze({id:`new-project`,thumbId:`blank-stage`,kind:`blank`,defaultName:`Untitled Project`,get name(){return J(`New project`,`새 프로젝트`)},get description(){return J(`Start from an empty stage.`,`빈 무대에서 시작합니다.`)}}),hpe=[{id:`storyboard`,label:()=>J(`Storyboard`,`스토리보드`),blurb:()=>J(`Describe scenes in words and direct one panel at a time. Output: image references.`,`말로 장면을 설명하면 한 장씩 패널을 연출합니다. 결과물: 이미지 레퍼런스.`)},{id:`animation`,label:()=>J(`Animation`,`애니메이션`),blurb:()=>J(`Block and shoot continuous motion. Output: clip references.`,`연속 동작을 블로킹하고 촬영합니다. 결과물: 클립 레퍼런스.`)}],W8=null;function G8(e){W8=e}function gpe(e){let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`,year:`numeric`}):J(`Recently`,`최근`)}function _pe(e){return{id:`sample-${e.id}`,starterId:e.id,name:e.name,description:e.blurb,kind:`sample`}}function vpe({open:e,initialName:t=`My Project`,onCancel:n,onSubmit:r}){let[i,a]=(0,Z.useState)(t);return(0,Z.useEffect)(()=>{if(e){if(W8!==null){let e=W8;W8=null,a(e),r(e);return}a(t)}},[e,t]),e?(0,Q.jsx)(`div`,{className:`v2-project-name-dialog-backdrop project-name-dialog-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`form`,{className:`v2-project-name-dialog project-name-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`project-name-dialog-title`,onSubmit:e=>{e.preventDefault(),r(i.trim()||`My Project`)},children:[(0,Q.jsx)(`strong`,{id:`project-name-dialog-title`,children:J(`Project name`,`프로젝트 이름`)}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{children:J(`Name`,`이름`)}),(0,Q.jsx)(`input`,{autoFocus:!0,value:i,onChange:e=>a(e.target.value),"aria-label":J(`Project name`,`프로젝트 이름`)})]}),(0,Q.jsxs)(`div`,{className:`v2-project-name-dialog-actions project-name-dialog-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`v2-dialog-secondary btn ghost`,onClick:n,children:J(`Cancel`,`취소`)}),(0,Q.jsx)(`button`,{type:`submit`,className:`v2-dialog-primary btn primary`,children:J(`Create`,`생성`)})]})]})}):null}function ype({currentName:e,onOpen:t,onOpenFile:n,onNew:r,onClose:i,startup:a=!1,starters:o=[],onStarter:s}){let c=(0,Z.useMemo)(()=>o.map(_pe),[o]),[l,u]=(0,Z.useState)(q),d=l===`storyboard`?[]:c,f=c[0]??U8,[p,m]=(0,Z.useState)(a?`new`:`recent`),[h,g]=(0,Z.useState)(f.id),[_,v]=(0,Z.useState)(e||f.defaultName||f.name||`My Project`),[y,b]=(0,Z.useState)(`24`),[x,S]=(0,Z.useState)(`Meters`),[C,w]=(0,Z.useState)([]),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)([]),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=!0;return bt().then(t=>{e&&w(Array.isArray(t)?t:[])}),ut().then(async t=>{if(!e||!t)return;let n=await $n(t);if(e){if(n!==`granted`){A(!0),n===`prompt`&&M(t);return}E(t),O(await ne(t))}}).catch(()=>{e&&A(!0)}),()=>{e=!1}},[]),(0,Z.useEffect)(()=>{a&&N.current?.focus()},[a]),(0,Z.useEffect)(()=>()=>{queueMicrotask(()=>G8(null))},[]);let P=d.find(e=>e.id===h)??U8,F=_.trim().length>0,I=J(`Enter a project name to create a project`,`프로젝트를 만들려면 이름을 입력하세요`),L=T?.name||J(`Browser project store`,`브라우저 프로젝트 저장소`),R=dr()&&se(),z=async()=>{if(!j||await Jt(j)!==`granted`)return;let e=j;M(null),A(!1),E(e),O(await ne(e))},B=async()=>{if(R)try{let e=await At();await ir(e),E(e),A(!1),M(null),O(await ne(e))}catch(e){e?.name!==`AbortError`&&A(!0)}},V=async()=>{T&&O(await ne(T))},ee=t=>{g(t.id),v(n=>!n.trim()||[P?.name,P?.defaultName,e].includes(n.trim())?t.defaultName??t.name:n)},H=e=>{u(e),!(e!==`storyboard`||!P?.starterId)&&(g(U8.id),v(e=>e.trim()===P?.name?U8.defaultName:e))},U=e=>{e.preventDefault();let t=_.trim();if(t){if(P?.starterId){s?.(P.starterId,t,{previsMode:`animation`});return}G8(t),r(t,{previsMode:l})}},W=[...C.map(e=>({...e,key:`recent-${e.name}`,removable:!0,date:e.openedAt})),...D.map(e=>({...e,key:`folder-${e.name}`,removable:!1,date:e.lastModified}))],G=[{id:`recent`,label:J(`Recent`,`최근`)},{id:`new`,label:J(`New Project`,`새 프로젝트`)},{id:`learn`,label:J(`Learn`,`배우기`)}];return(0,Q.jsx)(`div`,{className:`v2-start-screen project-browser-backdrop${a?` startup`:``}`,onPointerDown:e=>{!a&&e.target===e.currentTarget&&i?.()},children:(0,Q.jsxs)(`div`,{className:`v2-start-window project-browser${a?` startup`:``}`,role:`dialog`,"aria-modal":`true`,"aria-label":J(`Choose project`,`프로젝트 선택`),children:[(0,Q.jsxs)(`nav`,{className:`v2-start-nav`,"aria-label":J(`Project navigation`,`프로젝트 탐색`),children:[(0,Q.jsxs)(`div`,{className:`v2-start-brand`,children:[(0,Q.jsx)(ppe,{}),(0,Q.jsx)(`strong`,{children:`CozyClay`})]}),(0,Q.jsx)(`div`,{className:`v2-start-nav-list`,children:G.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-nav-item${p===e.id?` active`:``}`,"aria-current":p===e.id?`page`:void 0,onClick:()=>m(e.id),children:e.label},e.id))}),(0,Q.jsxs)(`div`,{className:`v2-start-version`,children:[`v`,mpe]})]}),(0,Q.jsxs)(`main`,{className:`v2-start-main`,children:[(0,Q.jsxs)(`div`,{className:`v2-start-main-head`,children:[(0,Q.jsxs)(`div`,{className:`v2-start-title-row`,children:[(0,Q.jsx)(`h1`,{children:p===`recent`?J(`Recent`,`최근`):p===`learn`?J(`Learn`,`배우기`):J(`New Project`,`새 프로젝트`)}),p!==`new`&&(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-close x`,onClick:i,"aria-label":J(`Close`,`닫기`),children:`×`})]}),p===`new`&&(0,Q.jsx)(`div`,{className:`v2-start-mode`,role:`radiogroup`,"aria-label":J(`Project mode`,`프로젝트 모드`),"data-testid":`start-previs-mode`,children:hpe.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e.id,className:`v2-start-mode-option${l===e.id?` active`:``}`,"data-previs-mode":e.id,onClick:()=>H(e.id),children:[(0,Q.jsx)(`strong`,{children:e.label()}),(0,Q.jsx)(`span`,{children:e.blurb()})]},e.id))})]}),p===`learn`?(0,Q.jsxs)(`div`,{className:`v2-start-learn`,children:[(0,Q.jsx)(`strong`,{children:J(`Block a shot in three moves`,`세 단계로 샷을 블로킹하세요`)}),(0,Q.jsx)(`p`,{children:J(`Choose a template, name the project, then place a character and frame the camera in the editor.`,`템플릿을 고르고 프로젝트 이름을 정한 다음 편집기에서 인물을 배치하고 카메라를 잡아 보세요.`)}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-learn-action`,onClick:()=>m(`new`),children:J(`Start a new project`,`새 프로젝트 시작`)})]}):p===`recent`?(0,Q.jsxs)(`div`,{className:`v2-start-recent-page`,children:[(0,Q.jsxs)(`div`,{className:`v2-start-recent-heading`,children:[(0,Q.jsx)(`span`,{children:J(`Recent projects`,`최근 프로젝트`)}),(0,Q.jsxs)(`div`,{className:`v2-start-recent-actions`,children:[T&&(0,Q.jsx)(`button`,{type:`button`,onClick:V,children:J(`Refresh`,`새로고침`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:n,children:J(`Open project file…`,`프로젝트 파일 열기…`)})]})]}),(0,Q.jsx)(K8,{entries:W,currentName:e,onOpen:t,onOpenFile:n,onRemove:async e=>{await jr(e.name),w(await bt())}})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`v2-start-template-grid`,role:`list`,"aria-label":J(`Project templates`,`프로젝트 템플릿`),children:[d.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-template${P?.id===e.id?` selected`:``}`,"data-template-id":e.id,onClick:()=>ee(e),onDoubleClick:()=>e.starterId&&s?.(e.starterId),children:[(0,Q.jsx)(`span`,{className:`v2-start-template-art ${e.kind}`,children:(0,Q.jsx)(H8,{id:e.starterId??e.id})}),(0,Q.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`span`,{children:e.description})]})]},e.id)),(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-add-card${P?.id===U8.id?` selected`:``}`,"data-testid":`start-new-project-card`,onClick:()=>{ee(U8),requestAnimationFrame(()=>N.current?.select())},children:[(0,Q.jsx)(`span`,{className:`v2-start-add-art`,"aria-hidden":`true`,children:(0,Q.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`20`,height:`20`,children:(0,Q.jsx)(`path`,{d:`M10 3.5v13M3.5 10h13`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})})}),(0,Q.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,Q.jsx)(`strong`,{children:J(`New project`,`새 프로젝트`)}),(0,Q.jsx)(`span`,{children:J(`Start from an empty stage`,`빈 무대에서 시작`)})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-add-card v2-start-open-card`,"data-testid":`start-open-project-card`,onClick:n,children:[(0,Q.jsx)(`span`,{className:`v2-start-add-art`,"aria-hidden":`true`,children:(0,Q.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`20`,height:`20`,children:(0,Q.jsx)(`path`,{d:`M2.5 6.5V15a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V8a1 1 0 0 0-1-1H10L8.5 5H3.5a1 1 0 0 0-1 1.5Z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinejoin:`round`})})}),(0,Q.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,Q.jsx)(`strong`,{children:J(`Open project`,`프로젝트 열기`)}),(0,Q.jsx)(`span`,{children:J(`A saved .cclayproject file`,`저장한 .cclayproject 파일`)})]})]})]}),(0,Q.jsxs)(`div`,{className:`v2-start-recent-block`,children:[(0,Q.jsx)(`div`,{className:`v2-start-recent-heading`,children:(0,Q.jsx)(`span`,{children:J(`Recent`,`최근`)})}),(0,Q.jsx)(K8,{entries:C.map(e=>({...e,key:`recent-${e.name}`,removable:!0,date:e.openedAt})),currentName:e,onOpen:t,onOpenFile:n,onRemove:async e=>{await jr(e.name),w(await bt())},compact:!0})]})]})]}),(0,Q.jsxs)(`aside`,{className:`v2-start-preview`,"data-testid":`start-project-preview`,"aria-label":J(`Project preview`,`프로젝트 미리보기`),children:[(0,Q.jsx)(`div`,{className:`v2-start-preview-art ${P?.kind||`blank`}`,children:(0,Q.jsx)(H8,{id:P.starterId??P.thumbId})}),(0,Q.jsxs)(`div`,{className:`v2-start-preview-copy`,children:[(0,Q.jsx)(`strong`,{children:P?.name}),(0,Q.jsx)(`span`,{children:P?.description})]}),(0,Q.jsxs)(`form`,{className:`v2-start-project-form`,onSubmit:U,children:[(0,Q.jsxs)(`label`,{className:`v2-start-field`,children:[(0,Q.jsx)(`span`,{children:J(`Name`,`이름`)}),(0,Q.jsx)(`input`,{ref:N,"data-testid":`start-project-name`,"aria-label":J(`Name`,`이름`),value:_,onChange:e=>v(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`v2-start-field`,children:[(0,Q.jsx)(`span`,{children:J(`Location`,`위치`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`v2-start-location`,onClick:B,disabled:!R,title:R?J(`Choose the project storage folder`,`프로젝트 저장 폴더 선택`):J(`Projects are stored in this browser`,`프로젝트는 이 브라우저에 저장됩니다`),children:[(0,Q.jsx)(`span`,{children:L}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⌄`})]})]}),(0,Q.jsxs)(`label`,{className:`v2-start-field`,children:[(0,Q.jsx)(`span`,{children:J(`Frame rate`,`프레임 레이트`)}),(0,Q.jsx)(`span`,{className:`v2-start-select-wrap`,children:(0,Q.jsxs)(`select`,{"aria-label":J(`Frame rate`,`프레임 레이트`),value:y,onChange:e=>b(e.target.value),children:[(0,Q.jsx)(`option`,{value:`24`,children:`24 fps`}),(0,Q.jsx)(`option`,{value:`30`,children:`30 fps`})]})})]}),(0,Q.jsxs)(`label`,{className:`v2-start-field`,children:[(0,Q.jsx)(`span`,{children:J(`Units`,`단위`)}),(0,Q.jsx)(`span`,{className:`v2-start-select-wrap`,children:(0,Q.jsxs)(`select`,{"aria-label":J(`Units`,`단위`),value:x,onChange:e=>S(e.target.value),children:[(0,Q.jsx)(`option`,{value:`Meters`,children:`Meters`}),(0,Q.jsx)(`option`,{value:`Feet`,children:`Feet`})]})})]}),k&&(0,Q.jsxs)(`p`,{className:`v2-start-location-status`,role:`status`,children:[j?J(`Folder access needs to be re-allowed.`,`폴더 접근을 다시 허용해야 해요.`):J(`Using the browser project store.`,`브라우저 프로젝트 저장소를 사용합니다.`),j&&(0,Q.jsx)(`button`,{type:`button`,onClick:z,children:J(`Re-allow`,`다시 허용`)})]}),(0,Q.jsxs)(`div`,{className:`v2-start-preview-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-cancel`,onClick:i,children:J(`Cancel`,`취소`)}),(0,Q.jsx)(`button`,{type:`submit`,className:`v2-start-create btn primary`,"data-testid":`start-create`,disabled:!F,title:F?J(`Create project`,`프로젝트 만들기`):I,children:J(`Create`,`생성`)})]})]})]})]})})}function K8({entries:e,currentName:t,onOpen:n,onOpenFile:r,onRemove:i,compact:a=!1}){return e.length===0?(0,Q.jsxs)(`p`,{className:`v2-start-empty${a?` compact`:``}`,children:[J(`No recent projects in this browser yet. `,`이 브라우저에 최근 프로젝트가 없습니다. `),(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-empty-open`,onClick:r,children:J(`Open a project file…`,`프로젝트 파일 열기…`)})]}):(0,Q.jsx)(`div`,{className:`v2-start-recent-list${a?` compact`:``}`,role:`list`,children:e.map(e=>(0,Q.jsxs)(`div`,{className:`v2-start-recent-row${e.name===t?` active`:``}`,role:`listitem`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`v2-start-recent-open`,onClick:()=>n(e),children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`span`,{children:gpe(e.date)}),(0,Q.jsxs)(`small`,{children:[e.shots??`—`,J(` shots`,` 샷`)]})]}),e.removable&&(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-recent-remove`,"aria-label":J(`Remove ${e.name} from recent projects`,`최근 프로젝트에서 ${e.name} 제거`,`从最近项目中移除 ${e.name}`),title:J(`Remove from list`,`목록에서 제거`),onClick:()=>i(e),children:`×`})]},e.key))})}var q8=Object.freeze([`animation`,`storyboard`]),bpe=Object.freeze([`1`,`2`,`3`,`4`]),J8=(e,t)=>{ea().then(()=>ba(e,t),()=>{})},Y8=()=>Date.now(),X8=null,Z8=e=>bpe.includes(String(e))?String(e):null,Q8=e=>{try{e()}catch{}};function xpe(e){Q8(()=>{q8.includes(e)&&(X8=Y8(),Es(`guide:opened`,1)&&J8(`guide:opened`,{mode:e}))})}function Spe(e,t,n){Q8(()=>{let r=Z8(t);if(!q8.includes(e)||!r)return;let i=Y8(),a=X8===null?NaN:i-X8;X8=i,Es(`guide:step:${r}`,1)&&J8(`guide:step`,{mode:e,step:r,step_ms:ls(a)}),t===n&&Es(`guide:completed`,1)&&J8(`guide:completed`,{mode:e})})}function Cpe(e,t){Q8(()=>{let n=Z8(t);!q8.includes(e)||!n||(X8=null,Es(`guide:dismissed`,1)&&J8(`guide:dismissed`,{mode:e,reached:n}))})}var wpe={animation:[{en:`Select a character in the Outliner.`,ko:`아웃라이너에서 캐릭터를 선택하세요.`,zh:`在大纲视图中选择一个角色。`,hintEn:`Click Character 1 (or its row) to make it active.`,hintKo:`캐릭터 1(또는 캐릭터 행)을 클릭하면 활성화됩니다.`,hintZh:`点击角色 1(或其所在行)使其成为当前角色。`},{en:`Move it in the Scene view.`,ko:`장면 보기에서 캐릭터를 움직이세요.`,zh:`在场景视图中移动它。`,hintEn:`Drag the character marker on the floor to place it.`,hintKo:`바닥의 캐릭터 마커를 드래그해 배치하세요.`,hintZh:`拖动地面上的角色标记来摆放位置。`},{en:`Ask the Agent for a motion.`,ko:`에이전트에게 동작을 요청하세요.`,zh:`让智能体生成一个动作。`,hintEn:`Open it with Cmd/Ctrl+B and say what the character does; the take lands on the Body lane.`,hintKo:`Cmd/Ctrl+B로 열고 캐릭터가 할 동작을 말하면 테이크가 바디 레인에 올라갑니다.`,hintZh:`按 Cmd/Ctrl+B 打开,说出角色要做的动作;动作片段会落在身体轨道上。`},{en:`Scrub the timeline or press Space to play.`,ko:`타임라인을 문지르거나 Space를 눌러 재생하세요.`,zh:`拖动时间线或按空格播放。`,hintEn:`Seeing the playhead move is your first visible result.`,hintKo:`재생 헤드가 움직이면 첫 결과를 확인한 것입니다.`,hintZh:`看到播放头移动,就是你的第一个可见结果。`}],storyboard:[{en:`Open the Agent panel (Cmd/Ctrl+B).`,ko:`에이전트 패널을 여세요 (Cmd/Ctrl+B).`,zh:`打开智能体面板(Cmd/Ctrl+B)。`,hintEn:`The Agent panel is where you describe each panel.`,hintKo:`에이전트 패널에서 각 패널을 설명합니다.`,hintZh:`在智能体面板中逐个描述每个面板。`},{en:`Describe one scene in a sentence.`,ko:`장면 하나를 한 문장으로 설명하세요.`,zh:`用一句话描述一个场景。`,hintEn:`One sentence per turn is enough for one panel.`,hintKo:`패널 하나에는 한 문장이면 충분합니다.`,hintZh:`每个面板一轮只说一句话就够了。`},{en:`Your panel appears on the Board.`,ko:`패널이 보드에 나타납니다.`,zh:`你的面板会出现在看板上。`,hintEn:`Open the Board tab to see the new panel card.`,hintKo:`보드 탭에서 새 패널 카드를 확인하세요.`,hintZh:`打开看板标签页查看新的面板卡片。`},{en:`Stylize it, or export the panel pack.`,ko:`스타일을 입히거나 패널 팩으로 내보내세요.`,zh:`对它进行风格化,或导出面板包。`,hintEn:`Use Stylize on the card, or export the panel pack.`,hintKo:`카드에서 스타일을 입히거나 패널 팩으로 내보내세요.`,hintZh:`在卡片上使用风格化,或导出面板包。`}]};function Tpe({open:e,onDismiss:t,previsMode:n=`animation`}){let r=n===`storyboard`,i=r?`storyboard`:`animation`,a=wpe[i],[o,s]=(0,Z.useState)(0);if((0,Z.useEffect)(()=>{e&&(s(0),xpe(i))},[e]),!e)return null;let c=o>=a.length,l=()=>{c||Cpe(i,o+1),t()};return(0,Q.jsxs)(`aside`,{className:`v2-first-success-guide first-success-guide`,role:`dialog`,"aria-labelledby":`first-success-guide-title`,"aria-describedby":`first-success-guide-description`,children:[(0,Q.jsxs)(`div`,{className:`v2-first-success-guide-head first-success-guide-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{id:`first-success-guide-title`,children:J(`Your first 60 seconds`,`첫 60초`)}),(0,Q.jsx)(`span`,{children:c?J(`Core loop complete`,`핵심 흐름 완료`,`核心流程完成`):J(`Step ${o+1} of ${a.length}`,`${o+1} / ${a.length} 단계`,`第 ${o+1} / ${a.length} 步`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-close first-success-guide-close`,onClick:l,"aria-label":J(`Dismiss guide`,`가이드 닫기`),children:`×`})]}),c?(0,Q.jsxs)(`div`,{className:`v2-first-success-guide-complete first-success-guide-complete`,id:`first-success-guide-description`,role:`status`,children:[(0,Q.jsx)(`div`,{className:`v2-first-success-guide-check first-success-guide-check`,children:`✓`}),(0,Q.jsx)(`strong`,{children:r?J(`You made your first panel.`,`첫 패널을 만들었어요.`):J(`You made your first shot.`,`첫 샷을 만들었어요.`)}),(0,Q.jsx)(`p`,{children:r?J(`Describe, review on the Board, then stylize or export. You can close this guide and keep adding panels.`,`설명하고, 보드에서 확인한 뒤 스타일을 입히거나 내보내세요. 가이드를 닫고 패널을 계속 추가하세요.`):J(`Select, move, ask, and play are the core CozyClay loop. You can close this guide and keep blocking.`,`선택하고, 움직이고, 요청하고, 재생하는 것이 CozyClay의 핵심 흐름입니다. 가이드를 닫고 계속 블로킹하세요.`)}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-next first-success-guide-next btn primary`,onClick:l,children:J(`Continue editing`,`편집 계속하기`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{id:`first-success-guide-description`,className:`v2-first-success-guide-intro first-success-guide-intro`,children:J(`Follow these four actions to see a result quickly.`,`네 가지 동작으로 빠르게 결과를 확인해 보세요.`)}),(0,Q.jsx)(`ol`,{className:`v2-first-success-guide-steps first-success-guide-steps`,children:a.map((e,t)=>(0,Q.jsxs)(`li`,{className:t<o?`done`:t===o?`current`:``,children:[(0,Q.jsx)(`span`,{className:`v2-first-success-guide-step-mark first-success-guide-step-mark`,children:t<o?`✓`:t+1}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:J(e.en,e.ko,e.zh)}),t===o&&(0,Q.jsx)(`span`,{children:J(e.hintEn,e.hintKo,e.hintZh)})]})]},e.en))}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-next first-success-guide-next btn primary`,onClick:()=>{Spe(i,o+1,a.length),s(o+1)},children:J(o===a.length-1?`Mark complete`:`I did this`,o===a.length-1?`완료로 표시`:`했어요`,o===a.length-1?`标记完成`:`我做了这一步`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-skip first-success-guide-skip`,onClick:l,children:J(`Skip guide`,`가이드 건너뛰기`)})]})}var Epe=Object.freeze([[`animation`,`Animation`,`애니메이션`,`动画`],[`film`,`Film / drama`,`영화·드라마`,`影视剧`],[`game`,`Game`,`게임`,`游戏`],[`ad_mv`,`Ad / music video`,`광고·뮤비`,`广告 / MV`],[`personal`,`Personal project`,`개인 작업`,`个人项目`],[`other`,`Something else`,`기타`,`其他`]]),Dpe=Object.freeze([[`team`,`With a team or company`,`팀·회사에서`,`与团队或公司`],[`solo`,`On my own`,`혼자`,`我自己`]]);function Ope({open:e,isKo:t,isZh:n,onAnswer:r}){let[i,a]=(0,Z.useState)(null),o=(e,r,i)=>t?r:n?i:e;if((0,Z.useEffect)(()=>{e||a(null)},[e]),!e)return null;let s=()=>r(i??`skip`,`skip`);return(0,Q.jsxs)(`section`,{className:`use-case-ask`,role:`dialog`,"aria-modal":`false`,"aria-labelledby":`use-case-ask-title`,onKeyDown:e=>{e.key===`Escape`&&s()},children:[(0,Q.jsxs)(`div`,{className:`use-case-ask-head`,children:[(0,Q.jsx)(`strong`,{id:`use-case-ask-title`,children:o(`Quick question (optional)`,`짧은 질문 (선택)`,`快速提问(可选)`)}),(0,Q.jsx)(`button`,{type:`button`,className:`use-case-ask-close`,"aria-label":o(`Close`,`닫기`,`关闭`),onClick:s,children:`×`})]}),(0,Q.jsx)(`p`,{className:`use-case-ask-prompt`,children:i?o(`Who are you making it with?`,`누구와 작업하나요?`,`你和谁一起做?`):o(`What are you making with CozyClay?`,`CozyClay로 뭘 만들고 있나요?`,`你在用 CozyClay 做什么?`)}),(0,Q.jsx)(`div`,{className:`use-case-ask-choices`,role:`group`,"aria-label":i?o(`Team or solo`,`팀 또는 혼자`,`团队或个人`):o(`Use case`,`용도`,`用途`),children:(i?Dpe:Epe).map(([e,t,n,s])=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>i?r(i,e):a(e),children:o(t,n,s)},e))}),(0,Q.jsx)(`p`,{className:`use-case-ask-note`,children:o(`Anonymous. Only the choice is sent.`,`익명이에요. 고른 항목만 전송돼요.`,`匿名。只发送所选项目。`)})]})}var $8=`gizmoHandleProxy`,kpe=[$8,`keyLightPick`,`pathAxis`,`pathIndex`,`pathRing`,`pathLine`,`craneAxis`,`craneIndex`];function Ape(e){for(let t=e;t;t=t.parent){let e=t.userData;if(e){for(let t of kpe)if(e[t]!==void 0)return!0}}return!1}function jpe(e){return e.some(e=>Ape(e.object))}var e5=(e,t)=>Math.max(0,Math.min(e.frameCount-1,Math.round(t)||0)),Mpe=(e,t)=>typeof t.parent==`string`?e.get(t.parent):null;function Npe(e,t,n){let r=new Set;for(let i=e.get(n);i&&!r.has(i.id);i=Mpe(e,i)){if(r.add(i.id),i.attach)return null;let e=t?.get?.(i.id);if(e)return{id:i.id,track:e}}return null}function Ppe(e,t){return e?.hold?e.hold[e5(e,t)]===1?`held`:null:e?`hinge`:null}function Fpe(e,t){return t.set(0,e.renderer===`empty`?0:(e.height??1)/2,0)}function Ipe(e,t,n,r){let i=e.get(t),a=i?cZ(e,t,n,r,new Y):null;if(!a)return null;let o=new Vu;return a.decompose(new X,o,new X),{centre:Fpe(i,new X).applyMatrix4(a).toArray(),quat:o.toArray()}}function Lpe(e,t){let n=e5(e,t);return{pos:new X().fromArray(e.pos,n*3),quat:new Vu().fromArray(e.quat,n*4)}}function t5(e,t,{travel:n=null,axis:r=null,degrees:i=0}={}){let a=e.pos.clone(),o=e.quat.clone();if(r&&i){let e=new Vu().setFromAxisAngle(r.clone().normalize(),i*Math.PI/180),n=new X().fromArray(t);a.sub(n).applyQuaternion(e).add(n),o.premultiply(e).normalize()}return n&&a.add(n),{pos:a,quat:o}}function Rpe(e,t,n,r,i){let a=new X().fromArray(n?.axis??[0,1,0]).normalize();return t5(e,n?.pivot??t,{axis:a,degrees:i*r.clone().normalize().dot(a)})}var n5=(e,t)=>t?Math.round(e/t)*t:e;function zpe(e,t,n=0){let r=new X;for(let i of t)r.addScaledVector(i,n5(e.dot(i),n));return r}var Bpe=(e,t=0)=>n5(e,t);function Vpe(e,t){let n=t&&e?.get?.(t.id);if(!n)return e;let r=e5(n,t.frame),i=Float32Array.from(n.pos),a=Float32Array.from(n.quat);return i.set(t.pos.toArray(),r*3),a.set(t.quat.toArray(),r*4),new Map(e).set(t.id,{...n,pos:i,quat:a})}var r5=e=>Math.round(e*1e4)/1e4;function Hpe(e,t,n,r,{hinge:i=!1}={}){return{characterId:e,objectId:t,frame:Math.max(0,Math.round(n)),...i?{}:{pos:r.pos.toArray().map(r5)},rot:r.quat.clone().normalize().toArray().map(r5)}}function Upe(e,t,n,r,i=[]){let a=e.get(t),o=n?.track?.hold;if(!a||!o)return null;let s=new X(0,a.renderer===`empty`?0:a.height??1,0),c=new Y,l=n=>cZ(e,t,n,r,c)?s.clone().applyMatrix4(c).toArray():null,u=[];for(let e=0;e<n.track.frameCount;e+=1){if(o[e]!==1)continue;let t=l(e);t&&u.push(t)}let d=i.filter(e=>o[e5(n.track,e)]===1).map(l).filter(Boolean);return u.length>1?{points:u,keys:d}:null}function Wpe({selected:e,objects:t,tracks:n,frame:r,frameCount:i,fps:a,motion:o,run:s}){let[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(null),d=(0,Z.useMemo)(()=>new Map(t.map(e=>[e.id,e])),[t]),f=Vpe(n,c),p=e?.id??null,m=p?Npe(d,f,p):null,h=m?Ipe(d,p,r,{frameCount:i,fps:a,objectTracks:f}):null,g=m?n.get(m.id):null,_=g?.characterId??null,v=m?Ppe(m.track,r):null,y=_?o?.motionFor?.(_)?.spec?.objects?.[m.id]??null:null,b=y?.keys,x=Array.isArray(b)?b.map(e=>e?.f).filter(Number.isFinite).join(`,`):``,S=m?.id??null,C=g?.pos,w=g?.quat,T=g?.hold,E=g?.frameCount,D=(0,Z.useMemo)(()=>{if(!S||!T)return null;let e={frameCount:E,pos:C,quat:w,hold:T},t=x?x.split(`,`).map(Number):[];return Upe(d,p,{track:e},{frameCount:i,fps:a,objectTracks:new Map([[S,e]])},t)},[d,p,S,C,w,T,E,i,a,x]);(0,Z.useEffect)(()=>{window.__heldGizmo=h?{id:p,mover:S,kind:v,characterId:_,pose:h}:null});let O=e=>{let t=u.current;t&&(t.last=e(t),l({id:t.id,frame:t.frame,...t.last}))};return{tracks:f,gizmo:h&&{pose:h,trail:D,editable:(v===`held`||v===`hinge`)&&!!_,hinge:v===`hinge`,begin(){return u.current={id:S,frame:Math.round(r),root:Lpe(g,r),pivot:h.centre,characterId:_,hinge:v===`hinge`?y??{}:null,last:null},!0},move:e=>O(t=>t5(t.root,t.pivot,{travel:e})),rotate:(e,t)=>O(n=>n.hinge?Rpe(n.root,n.pivot,n.hinge,e,t):t5(n.root,n.pivot,{axis:e,degrees:t})),end(e){let t=u.current;if(u.current=null,!e||!t?.last)return l(null);let n=null;try{n=s(`motion.keyObject`,Hpe(t.characterId,t.id,t.frame,t.last,{hinge:!!t.hinge}))}catch(e){console.warn(`motion.keyObject failed`,e)}Promise.resolve(n).finally(()=>l(null))}}}}var i5=`#ffd23d`;function Gpe({trail:e}){let t=(0,Z.useMemo)(()=>e?new Ol().setFromPoints(e.points.map(e=>new X(...e))):null,[e]);(0,Z.useEffect)(()=>()=>t?.dispose(),[t]);let n=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{n.current?.traverse(e=>e.layers.set(5))}),e?(0,Q.jsxs)(`group`,{ref:n,children:[(0,Q.jsx)(`line`,{geometry:t,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{color:i5,transparent:!0,opacity:.8,depthTest:!1,depthWrite:!1})}),e.keys.map((e,t)=>(0,Q.jsxs)(`mesh`,{position:e,renderOrder:997,children:[(0,Q.jsx)(`sphereGeometry`,{args:[.025,10,8]}),(0,Q.jsx)(`meshBasicMaterial`,{color:i5,depthTest:!1,depthWrite:!1,transparent:!0})]},t))]}):null}var a5=[{axis:`x`,dir:new X(1,0,0),color:`#ff5340`},{axis:`y`,dir:new X(0,1,0),color:`#54e05c`},{axis:`z`,dir:new X(0,0,1),color:`#3d8bff`}],o5={x:a5[0].dir,y:a5[1].dir,z:a5[2].dir},Kpe=[{id:`xz`,axes:[`x`,`z`],normal:`y`,color:`#54e05c`},{id:`xy`,axes:[`x`,`y`],normal:`z`,color:`#3d8bff`},{id:`yz`,axes:[`y`,`z`],normal:`x`,color:`#ff5340`}],s5=.62,c5=.016,qpe=.05,l5=.14,u5=.52,Jpe=.28,Ype=`#ffd23d`,d5=.022,f5=.09,p5=.09,Xpe=.07,Zpe=.16;function Qpe(e){return(e.y??0)+Math.max(As(e).height/2,.25)}function m5(e){return e.corner?`corner:${e.corner.id}`:e.axis??(e.plane?`plane:${e.plane.id}`:`centre`)}var $pe=[{id:`tr`,sx:1,sy:1},{id:`tl`,sx:-1,sy:1},{id:`br`,sx:1,sy:-1},{id:`bl`,sx:-1,sy:-1}],eme=new dc(new X(0,1,0),0);function h5(e,t,n){return t?.pose?n.fromArray(t.pose.centre):n.set(e.x,Qpe(e),e.z)}function g5(e,t){return t===`rotate`&&e?.editable?e.pose.quat:null}function _5({object:e,objects:t=[],mode:n=`move`,snap:r=!0,enabled:i,pickOnly:a=!1,paneRef:o,camRef:s,shotAspect:c=dE,onChange:l,onSelect:u,onGroundClick:d,onDragStart:f,onDragEnd:p,claimPointer:m,held:h=null}){let{gl:g,scene:_}=ey(),v=e=>{let t={x:e.left,y:e.top,w:e.width,h:e.height};return c?cE(t,c):t},y=e=>{if(c)e.aspect=c;else{let t=o?.current?.getBoundingClientRect();t&&t.height>=1&&(e.aspect=t.width/t.height)}},b=(0,Z.useRef)(null),x=(0,Z.useRef)(new Map),S=(0,Z.useRef)(null),C=(0,Z.useRef)({}),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),O=(0,Z.useRef)(null),k=(0,Z.useRef)(null),A=(0,Z.useRef)(null);A.current={object:e,objects:t,mode:n,snap:r,onChange:l,onSelect:u,onGroundClick:d,onDragStart:f,onDragEnd:p,claimPointer:m,held:h};let j=(0,Z.useMemo)(()=>({raycaster:new wl,ndc:new Gd,hit:new X,delta:new X,eye:new X,origin:new X,camPos:new X}),[]),M=(0,Z.useMemo)(()=>a5.map(({axis:e,dir:t})=>{let n=new Vu().setFromUnitVectors(new X(0,1,0),t);return{axis:e,u:new X(1,0,0).applyQuaternion(n),v:new X(0,0,1).applyQuaternion(n)}}),[]),N=(0,Z.useRef)(null);N.current&&(N.current.id!==e?.id||N.current.mode!==n)&&(T(null),O.current!==null&&(O.current=null,D(null))),N.current={id:e?.id,mode:n},(0,Z.useEffect)(()=>{b.current?.traverse(e=>e.layers?.set(5))});let P=()=>{let e=j.raycaster.intersectObjects(_.children,!0).find(e=>e.object.isMesh);j.raycaster.layers.set(5);let t=null,n=!1,r=j.raycaster.intersectObjects(_.children,!0).find(e=>{if(!e.object.isMesh)return!1;for(let r=e.object;r;r=r.parent){if(e.object.userData?.emptyPick&&r.userData?.sceneObjectId)return t=r.userData.sceneObjectId,n=!0,!0;if(r.userData?.shotCameraPick)return t=`__shotcam__`,!0;if(r.userData?.keyLightPick)return t=`__keylight__`,!0}return!1});if(j.raycaster.layers.set(0),r&&(n||!e||r.distance<e.distance))return{id:t,point:r.point.clone()};if(!e)return null;for(let t=e.object;t;t=t.parent){if(t.userData?.sceneObjectId)return{id:t.userData.sceneObjectId,point:e.point.clone()};if(t.userData?.characterPick)return{id:`char:${t.userData.characterPick}`,point:e.point.clone()}}return null},F=e=>{let t=o?.current,n=s?.current;if(!t||!n)return null;let r=t.getBoundingClientRect();if(r.width<2||r.height<2)return null;let i=v(r);return j.ndc.set((e.clientX-i.x)/i.w*2-1,-((e.clientY-i.y)/i.h)*2+1),Math.abs(j.ndc.x)<=1&&Math.abs(j.ndc.y)<=1?j.ndc:null};(0,Z.useEffect)(()=>{if(!i)return;let e=e=>{let t=s?.current,n=t?F(e):null;return n?(y(t),t.updateProjectionMatrix(),t.updateMatrixWorld(),t.matrixWorldInverse.copy(t.matrixWorld).invert(),b.current?.updateMatrixWorld(!0),_.updateMatrixWorld(),j.raycaster.setFromCamera(n,t),{ndc:n,camera:t}):null},t=t=>{let n=k.current;if(!n||!e(t)||!j.raycaster.ray.intersectPlane(n.plane,j.hit))return;let{objects:r,onChange:i,snap:a}=A.current;if(!(r.find(e=>e.id===n.id)??(A.current.object?.id===n.id?A.current.object:null)))return;let o=a!==(t.ctrlKey||t.metaKey);if(n.mode===`rotate`){j.delta.subVectors(j.hit,n.origin);let e=Math.atan2(j.delta.dot(n.binormal),j.delta.dot(n.tangent));if(n.turned+=Ar((e-n.lastAngle)*180/Math.PI),n.lastAngle=e,n.held)return void A.current.held?.rotate(n.dir,Bpe(n.turned,o?5:0));if(n.axis===`screen`){let e=pr(n.start,n.dir,n.turned,o?void 0:0);e&&i?.(n.id,e,n.token);return}let t=Qt(n.start,n.axis,n.turned,o?void 0:0);t&&i?.(n.id,t,n.token);return}if(n.mode===`corner`){let e=j.delta.subVectors(j.hit,n.origin),t=e.dot(n.right)*n.corner.sx+e.dot(n.up)*n.corner.sy,r=Math.max(.02,1+(t-n.startAlong)/n.reference),a=Math.max(.05,n.startHeight*r),s=Math.max(.05,n.startWidth*r);i?.(n.id,o?{height:Math.round(a*20)/20,width:Math.round(s*20)/20}:{height:a,width:s},n.token);return}if(n.mode===`scale`){j.delta.subVectors(j.hit,n.origin);let e=1+(j.delta.dot(n.dir)-n.startAlong)/n.reference,t=n.start?.renderer===`cutout`?n.start.footprint?.width??0:0;if(n.axis===`x`&&t>0){let r=Math.max(.05,t*Math.max(e,.01));i?.(n.id,{width:o?Math.round(r*20)/20:r},n.token);return}let r=wr(n.start,n.axis,e,o?void 0:0);r&&i?.(n.id,r,n.token);return}if(j.delta.subVectors(j.hit,n.hitStart),n.held)return void A.current.held?.move(zpe(j.delta,n.planeAxes?n.planeAxes.map(e=>o5[e]):[n.dir],o?.05:0));if(n.planeAxes){let e={};for(let t of n.planeAxes)Object.assign(e,Vt(n.start,t,j.delta.dot(o5[t]),o?void 0:0));i?.(n.id,e,n.token);return}let s=Vt(n.start,n.axis,j.delta.dot(n.dir),o?void 0:0);s&&i?.(n.id,s,n.token)},n=()=>{k.current&&(k.current=null,g.domElement.style.cursor=``,window.removeEventListener(`pointermove`,t),window.removeEventListener(`pointerup`,o),window.removeEventListener(`pointercancel`,c),window.removeEventListener(`blur`,l),window.removeEventListener(`keydown`,u,!0))},r=e=>{let t=k.current;if(!t)return;let r=A.current.onDragEnd,i=t.token;n(),t.held?A.current.held?.end(e):i!=null&&r&&r(i,{commit:e})},o=()=>r(!0),c=()=>r(!0),l=()=>r(!0),u=e=>{if(k.current){if((e.ctrlKey||e.metaKey)&&(e.code===`KeyZ`||e.code===`KeyY`)){r(!0);return}(e.code===`Escape`||e.key===`Escape`)&&(r(!1),e.preventDefault(),e.stopPropagation())}},d=(e,r,i,a)=>{let s=A.current.object;if(!s)return!1;let d=A.current.objects.find(e=>e.id===s.id)??s,f=A.current.held;h5(s,f,j.origin),a.getWorldDirection(j.eye);let p,m;if(e===`rotate`){let t=g5(f,e),n=r===`screen`?j.eye:t?i.clone().applyQuaternion(new Vu(...t)):i;p=new dc().setFromNormalAndCoplanarPoint(n,j.origin.clone());let a=new X;if(!j.raycaster.ray.intersectPlane(p,a))return!1;let o=new X(n.y,n.z,n.x).cross(n).normalize(),s=n.clone().cross(o).normalize(),c=a.clone().sub(j.origin);if(c.lengthSq()<1e-8)return!1;m={mode:`rotate`,tangent:o,binormal:s,lastAngle:Math.atan2(c.dot(s),c.dot(o)),turned:0,origin:j.origin.clone(),dir:n.clone()}}else if(e===`scale`){let e=r?i.clone():new X().crossVectors(j.eye,new X(0,1,0)).normalize(),t=e.clone().cross(j.eye).cross(e).normalize();p=new dc().setFromNormalAndCoplanarPoint(t,j.origin.clone());let n=new X;if(!j.raycaster.ray.intersectPlane(p,n))return!1;let a=n.clone().sub(j.origin).dot(e);m={mode:`scale`,dir:e,startAlong:a,reference:Math.abs(a)<.05?(b.current?.scale.x??1)*s5:a,origin:j.origin.clone()}}else if(e===`corner`){let e=(s.rot??0)*Math.PI/180,t=new X(Math.cos(e),0,-Math.sin(e)),n=new X(0,1,0),r=new X().crossVectors(t,n).normalize();p=new dc().setFromNormalAndCoplanarPoint(r,j.origin.clone());let a=new X;if(!j.raycaster.ray.intersectPlane(p,a))return!1;let o=d.footprint?.width??0,c=d.height??0;if(!(o>0)||!(c>0))return!1;let l=a.clone().sub(j.origin),u=l.dot(t)*i.sx+l.dot(n)*i.sy,f=(o+c)/4;m={mode:`corner`,corner:i,right:t,up:n,startAlong:u,reference:Math.abs(u)<.05?f:u,startWidth:o,startHeight:c,origin:j.origin.clone()}}else if(e===`plane`){let e=o5[i.normal];p=new dc().setFromNormalAndCoplanarPoint(e,j.origin.clone());let t=new X;if(!j.raycaster.ray.intersectPlane(p,t))return!1;m={mode:`move`,planeAxes:i.axes,hitStart:t}}else{let e=i.clone().cross(j.eye).cross(i).normalize();p=new dc().setFromNormalAndCoplanarPoint(e,j.origin.clone());let t=new X;if(!j.raycaster.ray.intersectPlane(p,t))return!1;m={mode:`move`,dir:i.clone(),hitStart:t}}let h=!!(f?.editable&&(e===`rotate`||!f.hinge&&(e===`move`||e===`plane`))&&f.begin()),_=h?void 0:A.current.onDragStart?.({owner:`gizmo`,cancel:n}),v=e===`corner`?i:null;return k.current={...m,id:d.id,axis:r,plane:p,corner:v,start:{...d},token:_,held:h},T(m5({axis:r,plane:p,corner:v})),g.domElement.style.cursor=`grabbing`,window.addEventListener(`pointermove`,t),window.addEventListener(`pointerup`,o),window.addEventListener(`pointercancel`,c),(_!=null||h)&&(window.addEventListener(`blur`,l),window.addEventListener(`keydown`,u,!0)),!0},f=t=>{let n=e(t);if(!n)return null;let r=[...x.current.values()].filter(e=>e.mesh?.parent);if(!r.length)return null;j.raycaster.layers.set(5);let i=j.raycaster.intersectObjects(r.map(e=>e.mesh),!1);if(!i.length)return null;let a=e=>r.find(t=>t.mesh===e.object),o=i.map(a).find(e=>e?.corner)??a(i[0]);return o?{...o,aim:n}:null},p=t=>{if(t.button!==0||t.altKey||t.target!==g.domElement||A.current.claimPointer?.(t))return;let n=f(t);if(n&&e(t)){j.raycaster.layers.set(5);let e=j.raycaster.intersectObjects(_.children,!0).some(e=>{for(let t=e.object;t;t=t.parent){let e=t.userData;if(e?.keyLightPick||e?.pathIndex!==void 0||e?.pathRing||e?.craneIndex!==void 0)return!0}return!1});if(j.raycaster.layers.set(0),e)return}if(n&&d(n.corner?`corner`:n.plane?`plane`:A.current.mode,n.axis,n.corner??n.plane??n.dir,n.aim.camera)){t.preventDefault(),t.stopPropagation();return}if(a||!e(t)||(j.raycaster.layers.set(5),jpe(j.raycaster.intersectObjects(_.children,!0))))return;j.raycaster.layers.set(0);let r=P();if(t.preventDefault(),t.stopPropagation(),!r&&A.current.onGroundClick&&j.raycaster.ray.intersectPlane(eme,j.hit)){A.current.onGroundClick({x:j.hit.x,z:j.hit.z});return}A.current.onSelect?.(r?r.id:null)},m=e=>{if(k.current||e.buttons!==0||e.target!==g.domElement)return;let t=f(e),n=t?m5(t):null;if(n!==O.current&&(O.current=n,D(n)),t){g.domElement.style.cursor=`grab`;return}a||(j.raycaster.layers.set(0),g.domElement.style.cursor=P()?`pointer`:``)};return a||(window.__gizmoPick=(e,t)=>{let n=f({clientX:e,clientY:t,button:0});return n?m5(n):null}),a||(window.__objectPick=(t,n)=>e({clientX:t,clientY:n})?(j.raycaster.layers.set(0),P()?.id??null):null),window.addEventListener(`pointerdown`,p,!0),g.domElement.addEventListener(`pointermove`,m),()=>{window.removeEventListener(`pointerdown`,p,!0),g.domElement.removeEventListener(`pointermove`,m),r(!0)}},[i,a,g,_,s,o,j]),ty(()=>{let t=b.current,r=s?.current;if(!t||!r||!e||(r.getWorldPosition(j.camPos),h5(e,h,j.origin),t.scale.setScalar(Math.max(.35,j.camPos.distanceTo(j.origin)*Zpe)),n!==`rotate`))return;r.getWorldDirection(j.eye);let i=S.current;i&&i.quaternion.copy(r.quaternion);let a=g5(h,n);if(a){let e=new Vu(...a).invert();j.eye.applyQuaternion(e),i?.quaternion.premultiply(e)}for(let{axis:e,u:t,v:n}of M){let r=C.current[e];r&&(r.rotation.z=Math.atan2(-j.eye.dot(n),-j.eye.dot(t)))}});let I=(0,Z.useCallback)(()=>{let e=s?.current,t=o?.current;if(!e||!t)return[];y(e),e.updateProjectionMatrix(),e.updateMatrixWorld(),e.matrixWorldInverse.copy(e.matrixWorld).invert(),b.current?.updateMatrixWorld(!0);let n=t.getBoundingClientRect(),r=v(n);return[...x.current.values()].filter(e=>e.mesh?.parent).map(t=>{let n=t.mesh.getWorldPosition(new X).project(e);return{axis:m5(t),x:r.x+(n.x+1)/2*r.w,y:r.y+(1-n.y)/2*r.h}})},[s,o,c]);if(typeof window<`u`&&!a&&(window.__gizmoHandles=I),(0,Z.useEffect)(()=>{if(!(typeof window>`u`||!a))return window.__characterGizmoHandles=I,()=>{window.__characterGizmoHandles===I&&delete window.__characterGizmoHandles}},[I,a]),!i||!e)return x.current.clear(),null;let L=(e,t)=>n=>{n&&(n.layers.set(5),n.userData[$8]=!0,x.current.set(e??`centre`,{mesh:n,axis:e,dir:t}))},R=e=>t=>{C.current[e]=t},z=e=>t=>{t&&(t.layers.set(5),t.userData[$8]=!0,x.current.set(`plane:${e.id}`,{mesh:t,axis:null,plane:e}))},B=e=>t=>{t&&(t.layers.set(5),t.userData[$8]=!0,x.current.set(`corner:${e.id}`,{mesh:t,axis:null,corner:e}))},V=(0,Q.jsx)(`meshBasicMaterial`,{visible:!1}),ee=w===`screen`,H=E===`screen`,U=w===`centre`,W=E===`centre`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Gpe,{trail:h?.trail??null}),(0,Q.jsxs)(`group`,{ref:b,position:h5(e,h,new X).toArray(),quaternion:g5(h,n)??[0,0,0,1],renderOrder:999,children:[a5.map(({axis:e,dir:t,color:r})=>{let i=new Vu().setFromUnitVectors(new X(0,1,0),t),a=w===e,o=E===e,s=a?Ype:r,c=a?2.2:o?3.6:2.2,l=(e=.95)=>(0,Q.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:s,emissiveIntensity:c,toneMapped:!1,depthTest:!1,depthWrite:!1,transparent:!0,opacity:e});return(0,Q.jsx)(`group`,{quaternion:i,children:n===`rotate`?(0,Q.jsxs)(`group`,{ref:R(e),rotation:[Math.PI/2,0,0],children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`torusGeometry`,{args:[u5,d5,8,24,Math.PI]}),l()]}),(0,Q.jsxs)(`mesh`,{rotation:[0,0,Math.PI],renderOrder:999,children:[(0,Q.jsx)(`torusGeometry`,{args:[u5,d5,8,24,Math.PI]}),l(Jpe)]}),(0,Q.jsxs)(`mesh`,{ref:L(e,t),children:[(0,Q.jsx)(`torusGeometry`,{args:[u5,Xpe,6,32]}),V]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`mesh`,{position:[0,s5/2,0],renderOrder:999,children:[(0,Q.jsx)(`cylinderGeometry`,{args:[c5,c5,s5,8]}),l()]}),(0,Q.jsxs)(`mesh`,{position:[0,s5+(n===`scale`?f5/2:l5/2),0],renderOrder:999,children:[n===`scale`?(0,Q.jsx)(`boxGeometry`,{args:[f5,f5,f5]}):(0,Q.jsx)(`coneGeometry`,{args:[qpe,l5,14]}),l()]}),(0,Q.jsxs)(`mesh`,{ref:L(e,t),position:[0,(s5+l5)/2,0],children:[(0,Q.jsx)(`cylinderGeometry`,{args:[p5,p5,s5+l5,8]}),V]})]})},e)}),n===`rotate`&&(0,Q.jsxs)(`group`,{ref:S,children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`torusGeometry`,{args:[.68,.022,8,64]}),(0,Q.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:ee?`#ffd23d`:`#f2f2f2`,emissiveIntensity:ee?2.2:H?3.6:2.2,toneMapped:!1,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})]}),(0,Q.jsxs)(`mesh`,{ref:L(`screen`,null),children:[(0,Q.jsx)(`torusGeometry`,{args:[.68,.07,6,48]}),V]})]}),n===`move`&&Kpe.map(e=>{let t=[0,0,0],n={x:0,y:1,z:2};for(let r of e.axes)t[n[r]]=.26;let r=e.normal===`y`?[-Math.PI/2,0,0]:e.normal===`x`?[0,Math.PI/2,0]:[0,0,0],i=w===`plane:${e.id}`,a=E===`plane:${e.id}`;return(0,Q.jsxs)(`group`,{position:t,rotation:r,children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`planeGeometry`,{args:[.2,.2]}),(0,Q.jsx)(`meshBasicMaterial`,{color:i?`#ffd23d`:e.color,transparent:!0,opacity:i?.6:a?.55:.34,side:2,depthTest:!1,depthWrite:!1})]}),(0,Q.jsxs)(`mesh`,{ref:z(e),children:[(0,Q.jsx)(`planeGeometry`,{args:[.2*1.5,.2*1.5]}),(0,Q.jsx)(`meshBasicMaterial`,{visible:!1,side:2})]})]},e.id)}),n===`scale`&&e?.renderer===`cutout`&&$pe.map(t=>{let n=(e.footprint?.width??0)/2,r=(e.height??0)/2;if(!(n>0)||!(r>0))return null;let i=b.current?.scale.x||1,a=`corner:${t.id}`,o=w===a,s=E===a,c=(e.rot??0)*Math.PI/180,l=t.sx*n/i,u=[l*Math.cos(c),t.sy*r/i,-l*Math.sin(c)];return(0,Q.jsxs)(`group`,{position:u,children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`boxGeometry`,{args:[.085,.085,.085]}),(0,Q.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:o?`#ffd23d`:`#f2f2f2`,emissiveIntensity:o?2:s?3.4:2,toneMapped:!1,depthTest:!1,depthWrite:!1})]}),(0,Q.jsxs)(`mesh`,{ref:B(t),children:[(0,Q.jsx)(`sphereGeometry`,{args:[.13,8,6]}),V]})]},a)}),n===`scale`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`boxGeometry`,{args:[.11,.11,.11]}),(0,Q.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:U?`#ffd23d`:`#f2f2f2`,emissiveIntensity:U?2:W?3.4:2,toneMapped:!1,depthTest:!1,depthWrite:!1})]}),(0,Q.jsxs)(`mesh`,{ref:L(null,null),children:[(0,Q.jsx)(`sphereGeometry`,{args:[.16,8,6]}),V]})]})]})]})}function tme({result:e,copied:t,recordedVideoName:n,onClose:r,onCopy:i,onDownload:a,downloadDisabled:o=!1,exportFeedback:s=null}){let c=e.mode===`video`,l=e.modelLabel??(c?J(`your AI video tool`,`AI 영상 도구`):J(`your selected image model`,`선택한 이미지 모델`)),u=!!e.frame,d;return d=c&&e.frameB?(0,Q.jsxs)(`p`,{children:[J(`Paste the prompt into ${l}, set `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},设置 `),(0,Q.jsx)(`code`,{children:`blocking-frame-A-start.png`}),J(` as the start frame, and `,`를 시작 프레임으로, `,` 作为起始帧,并将 `),(0,Q.jsx)(`code`,{children:`blocking-frame-B-end.png`}),J(` as the end frame.`,`를 끝 프레임으로 설정하세요.`)]}):c&&u?(0,Q.jsxs)(`p`,{children:[J(`Paste the prompt into ${l} and attach `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},并附加 `),(0,Q.jsx)(`code`,{children:`blocking-frame.png`}),J(` as the reference frame.`,`를 참고 프레임으로 첨부하세요.`,` 作为参考帧。`)]}):u?(0,Q.jsxs)(`p`,{children:[J(`Paste the prompt into ${l} and attach `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},并附加 `),(0,Q.jsx)(`code`,{children:`blocking-frame.png`}),J(` as the reference image.`,`를 참고 이미지로 첨부하세요.`,` 作为参考图像。`)]}):(0,Q.jsx)(`p`,{children:J(`Paste the copied prompt into ${l} to create the scene.`,`복사한 프롬프트를 ${l}에 붙여 넣어 장면을 만드세요.`,`将复制的提示词粘贴到 ${l} 以创建场景。`)}),(0,Q.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,Q.jsxs)(`div`,{className:`modal result-modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`result-title`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`result-title`,children:J(`Your shot is ready`,`장면이 준비됐어요`)}),(0,Q.jsx)(`button`,{type:`button`,className:`x`,onClick:r,"aria-label":J(`Close the result`,`결과 닫기`),children:`✕`})]}),e.frameB?(0,Q.jsxs)(`div`,{className:`move-frames`,children:[(0,Q.jsxs)(`figure`,{children:[(0,Q.jsx)(`img`,{className:`preview`,src:e.frame,alt:J(`Camera move start frame`,`카메라 움직임 시작 프레임`)}),(0,Q.jsxs)(`figcaption`,{children:[`A · `,J(`Start`,`시작`)]})]}),(0,Q.jsxs)(`figure`,{children:[(0,Q.jsx)(`img`,{className:`preview`,src:e.frameB,alt:J(`Camera move end frame`,`카메라 움직임 끝 프레임`)}),(0,Q.jsxs)(`figcaption`,{children:[`B · `,J(`End`,`끝`)]})]})]}):e.frame&&(0,Q.jsx)(`img`,{className:`preview`,src:e.frame,alt:J(`Finished scene frame`,`완성된 장면 프레임`)}),e.move&&(0,Q.jsxs)(`div`,{className:`move-slate result-move-slate`,children:[(0,Q.jsxs)(`span`,{children:[e.move.displaySlate??e.move.slate,` · `,e.move.spanS,J(`s`,`초`,`秒`)]}),(0,Q.jsx)(`small`,{children:J(`Camera move made from timeline keyframes`,`타임라인 키프레임으로 만든 카메라 움직임`)})]}),(0,Q.jsxs)(`label`,{className:`modal-label`,children:[J(`Prompt`,`프롬프트`),` `,t&&(0,Q.jsxs)(`em`,{children:[`· `,J(`copied`,`복사됨`)]})]}),(0,Q.jsx)(`div`,{className:`promptbox`,children:e.prompt}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn`,onClick:i,children:t?J(`Copied ✓`,`복사됨 ✓`):J(`Copy prompt`,`프롬프트 복사`)}),e.frame&&(0,Q.jsx)(`button`,{type:`button`,className:`btn`,onClick:a,disabled:o,children:e.downloaded?J(`Exported`,`내보냄`):e.frameB?J(`Export start and end frames`,`시작·끝 프레임 내보내기`):J(`Export frame`,`프레임 내보내기`)})]}),s,(0,Q.jsxs)(`section`,{className:`result-next`,"aria-labelledby":`result-next-title`,children:[(0,Q.jsx)(`span`,{className:`result-next-kicker`,children:J(`Next · ${l}`,`다음 · ${l}`,`下一步 · ${l}`)}),(0,Q.jsx)(`h4`,{id:`result-next-title`,children:J(`Handing off to your AI`,`AI에 넣는 순서`)}),(0,Q.jsx)(`div`,{className:`result-next-intro`,children:d}),(0,Q.jsxs)(`ol`,{className:`result-handoff-steps`,children:[(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`strong`,{children:J(`Copy the prompt`,`프롬프트 복사`)}),(0,Q.jsx)(`span`,{children:t?J(`Copied. Paste it into your AI service's prompt box.`,`복사됐어요. AI 서비스의 입력창에 붙여 넣으세요.`):J(`Press “Copy prompt” above, then paste it into your AI service.`,`위의 ‘프롬프트 복사’를 누른 뒤 AI 서비스 입력창에 붙여 넣으세요.`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`strong`,{children:J(`Export the frame`,`프레임 내보내기`)}),(0,Q.jsx)(`span`,{children:e.frameB?J(`Press “Export start and end frames” to save both PNGs.`,`‘시작·끝 프레임 내보내기’를 눌러 두 PNG를 저장하세요.`):u?J(`Press “Export frame” to save the PNG.`,`‘프레임 내보내기’를 눌러 PNG를 저장하세요.`):J(`This result has no frame to export.`,`이 결과에는 내보낼 프레임이 없어요.`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`strong`,{children:J(`Attach the image to your AI`,`AI에 이미지 첨부`)}),(0,Q.jsx)(`span`,{children:e.frameB?J(`Use your AI service's image attach button to upload the start and end frames together.`,`AI 서비스의 이미지 첨부 버튼에서 시작 프레임과 끝 프레임을 함께 올리세요.`):J(`Use your AI service's image attach button to upload blocking-frame.png.`,`AI 서비스의 이미지 첨부 버튼에서 blocking-frame.png를 올리세요.`)})]})]}),(0,Q.jsx)(`p`,{className:`result-handoff-note`,children:J(`The prompt describes the scene's content and mood; the frame shows the camera framing. Use both to reproduce this scene as closely as possible.`,`프롬프트는 장면의 내용과 분위기를 설명하고, 프레임은 카메라 구도를 보여줘요. 둘을 함께 넣어야 이 장면을 가장 가깝게 재현할 수 있어요.`)}),n&&(0,Q.jsxs)(`p`,{className:`result-reference-video`,children:[(0,Q.jsx)(`strong`,{children:J(`Optional · Reference video`,`선택 사항 · 참고 영상`)}),J(`A video recorded with the recording feature: `,`녹화 기능으로 만든 `),(0,Q.jsx)(`code`,{children:n}),J(` file. Use it separately from the reference frame in the prompt above.`,` 파일이에요. 위의 프롬프트 참고 프레임과는 별도로 활용하세요.`)]})]})]})})}var v5=`cozyclay:pwa-update-ready`;function y5(e){window.dispatchEvent(new CustomEvent(v5,{detail:e}))}function nme(){if(!(`serviceWorker`in navigator))return;if(globalThis.__COZYCLAY_RUNTIME__?.distribution===`npm`){navigator.serviceWorker.getRegistrations().then(e=>Promise.all(e.map(e=>e.unregister())));return}let e=!!navigator.serviceWorker.controller,t=!1;navigator.serviceWorker.addEventListener(`controllerchange`,()=>{if(!e){e=!0;return}t||(t=!0,window.location.reload())}),window.addEventListener(`load`,async()=>{try{let e=await navigator.serviceWorker.register(`/sw.js`,{scope:`/`});e.waiting&&y5(e),e.addEventListener(`updatefound`,()=>{let t=e.installing;t?.addEventListener(`statechange`,()=>{t.state===`installed`&&navigator.serviceWorker.controller&&y5(e)})})}catch{return}},{once:!0})}var rme=3;function ime({rig:e,take:t,objects:n,propTake:r}){let i=sn(Wt),a=DV(),o=ey(e=>e.scene),s=ey(e=>e.gl),c=ey(e=>e.invalidate),l=(0,Z.useMemo)(()=>new XQ({layer:5}),[]),u=a.mode!==`off`&&!!e&&Un(t),d=(0,Z.useMemo)(()=>u&&a.mode===`keys`?MV(t,n):[],[u,a.mode,t,n]),f=(0,Z.useMemo)(()=>u?kV({frame:i,last:t.frameCount-1,...a,keyFrames:d}):[],[u,i,t,a,d]);return(0,Z.useEffect)(()=>{if(u)return o.add(l.object),()=>{o.remove(l.object)}},[u,o,l]),(0,Z.useEffect)(()=>()=>l.dispose(),[l]),(0,Z.useEffect)(()=>{c()},[c,u,f]),(0,Z.useEffect)(()=>{typeof window<`u`&&(window.__cozyclayGhosts={set:l,gl:s,scene:o,entries:f})},[l,s,o,f]),ty(()=>{l.show(u&&!!e.parent)&&(l.setRig(e),l.syncSources(o,n,t,rme),e.parent.updateWorldMatrix(!0,!1),l.update({entries:f,take:t,placement:e.parent.matrixWorld,propTake:r,objects:n,count:a.count}))}),null}var ame=3,ome=.3,b5=.042,x5={w:512,h:96},sme=()=>{},S5=new WeakMap;function cme(e){if(!S5.has(e)){let t=null;e.traverse(e=>{!t&&e.isBone&&/Head$/.test(e.name)&&(t=e)}),S5.set(e,t)}return S5.get(e)}function lme(){let e=document.createElement(`canvas`);Object.assign(e,{width:x5.w,height:x5.h});let t=new au(e);t.colorSpace=rd;let n=new Gp(new om({map:t,transparent:!0,depthTest:!1,depthWrite:!1,sizeAttenuation:!1,toneMapped:!1}));return n.center.set(.5,0),n.renderOrder=1e3,n.layers.set(5),n.raycast=sme,n.userData={canvas:e,texture:t,text:null},n}function ume(e,t,n){let{canvas:r,texture:i}=e.userData;if(e.userData.text===`${t}|${n}`)return;e.userData.text=`${t}|${n}`;let a=r.getContext(`2d`),o=`600 44px system-ui, -apple-system, 'Apple SD Gothic Neo', 'Noto Sans KR', sans-serif`;a.font=o;let s=Math.min(x5.w-4,Math.ceil(a.measureText(t).width)+52+34);a.clearRect(0,0,r.width,r.height),a.fillStyle=`rgba(16, 24, 28, 0.82)`,a.strokeStyle=nn,a.lineWidth=4,a.beginPath(),a.roundRect((x5.w-s)/2,8,s,x5.h-16,30),a.fill(),a.stroke(),a.fillStyle=n?`#46d36f`:nn,a.beginPath(),a.arc((x5.w-s)/2+26+8,x5.h/2,9,0,Math.PI*2),a.fill(),a.fillStyle=`#eef6f3`,a.font=o,a.textBaseline=`middle`,a.fillText(t,(x5.w-s)/2+26+34,x5.h/2+2),i.needsUpdate=!0,e.scale.set(b5*(x5.w/x5.h),b5,1)}function dme({set:e,label:t,draft:n,rig:r,scene:i,objects:a,propTake:o}){let s=n?zn(n,Date.now()):null,c=!!s?.shown&&!!r?.parent;if(t.visible=c,typeof window<`u`&&(window.__cozyclayDraftGhost={set:e,label:t,draft:n,state:s,on:c}),!e.show(c))return;e.setRig(r),e.syncSources(i,a,n.take,ame),r.parent.updateWorldMatrix(!0,!1),e.update({entries:[{f:s.frame,side:`after`,rank:1}],take:n.take,placement:r.parent.matrixWorld,propTake:o,objects:a,count:1});let l=e.slots[0];l.material.color.set(nn).multiplyScalar(1.15),l.material.opacity=s.opacity;let u=cme(l.rig);u&&(e.object.updateMatrixWorld(!0),u.getWorldPosition(t.position),t.position.y+=ome,t.material.opacity=Math.min(1,s.opacity/nr))}function fme({rigs:e,objects:t}){let n=(0,Z.useSyncExternalStore)(Le,Zr,Zr),r=(0,Z.useMemo)(()=>Pr(),[n]),i=xt(),a=ey(e=>e.scene),o=ey(e=>e.invalidate),s=(0,Z.useMemo)(()=>new XQ({layer:5}),[]),c=(0,Z.useMemo)(()=>lme(),[]),l=r?e?.[r.characterId]??null:null,u=i&&!!l&&!!r?.take,d=(0,Z.useMemo)(()=>r?.take?{frameCount:r.take.frameCount,fps:r.take.fps,objectTracks:KQ(r.take)}:null,[r]);return(0,Z.useEffect)(()=>{if(u)return a.add(s.object),s.object.add(c),()=>{s.object.remove(c),a.remove(s.object)}},[u,a,s,c]),(0,Z.useEffect)(()=>()=>{s.dispose(),c.material.dispose(),c.userData.texture.dispose()},[s,c]),(0,Z.useEffect)(()=>{r&&ume(c,mn(r),r.qa?.total===0)},[r,c]),(0,Z.useEffect)(()=>{if(o(),!u)return;let e=setInterval(()=>{(zn(r,Date.now()).shown||s.object.visible)&&o()},1e3/(r.take.fps||24));return()=>clearInterval(e)},[u,r,s,o]),ty(()=>dme({set:s,label:c,draft:u?r:null,rig:l,scene:a,objects:t,propTake:d})),null}var pme=.42,mme=.2,hme=420,gme=Math.PI/180,_me=44,vme=()=>{},yme=e=>1-(1-e)**3;function bme(e,t){let n=e.target?t?.find(t=>t.id===e.target):null,r={x:n?.x??0,y:n?.y??0,z:n?.z??0,rot:n?.rot??0,...e.placement};return new Y().compose(new X(r.x,r.y,r.z),new Vu().setFromAxisAngle(new X(0,1,0),r.rot*gme),new X(1,1,1))}function xme(e,t){let n=[];for(let r of e){let e=bme(r,t);for(let t of ss(r.parts)){let{id:r,parent:i,matrix:a,...o}=t;n.push({identity:JSON.stringify([o,a.map(e=>Math.round(e*1e4))]),part:t,matrix:e.clone().multiply(new Y().fromArray(a))})}}return n}var Sme=class{root=new hl;meshes=new Map;constructor(){this.root.name=`sculpt-sketch`,this.root.userData.sculptSketch=!0}make(e,t){let n=o8(e.shape===`scatter`?{...e,shape:`blob`,roundness:.5,taper:0}:e),r=new Kf({color:e.color,emissive:e.color,emissiveIntensity:.18,roughness:.85,metalness:0,transparent:!0,opacity:0,depthWrite:!1}),i=new yd(n,r);return Object.assign(i,{raycast:vme,castShadow:!1,receiveShadow:!1,matrixAutoUpdate:!1,renderOrder:_me,frustumCulled:!1}),i.layers.set(5),i.userData.sculptSketch=!0,this.root.add(i),{mesh:i,base:new Y,born:t,opacity:e.shape===`scatter`?mme:pme}}drop({mesh:e}){this.root.remove(e),e.geometry.dispose(),e.material.dispose()}update(e,t){let n=new Map,r=new Map;for(let i of e){let e=(r.get(i.identity)??0)+1;r.set(i.identity,e);let a=`${i.identity}#${e}`,o=this.meshes.get(a);if(o)this.meshes.delete(a);else try{o=this.make(i.part,t)}catch{continue}o.base.copy(i.matrix),n.set(a,o)}for(let e of this.meshes.values())this.drop(e);this.meshes=n,this.frame(t)}frame(e){let t=!1,n=new Y;for(let r of this.meshes.values()){let i=Math.min(1,Math.max(0,(e-r.born)/hme)),a=yme(i);t||=i<1;let o=.55+.45*a;r.mesh.matrix.copy(r.base).multiply(n.makeScale(o,o,o)),r.mesh.material.opacity=r.opacity*a}return t}dispose(){for(let e of this.meshes.values())this.drop(e);this.meshes.clear()}};function Cme({objects:e}){let t=(0,Z.useSyncExternalStore)(Cs,Ns,Ns),n=ey(e=>e.scene),r=ey(e=>e.invalidate),i=(0,Z.useMemo)(()=>new Sme,[]),a=(0,Z.useMemo)(()=>xme(t,e),[t,e]);return(0,Z.useEffect)(()=>(n.add(i.root),typeof window<`u`&&(window.__cozyclaySculptSketch={frame:To,clear:si,meshes:()=>i.meshes.size,root:i.root}),()=>{n.remove(i.root),i.dispose()}),[n,i]),(0,Z.useEffect)(()=>{i.update(a,performance.now()),r()},[i,a,r]),ty(()=>{i.frame(performance.now())&&r()}),null}var C5=null;function wme(){if(C5!==null)return C5;try{let e=document.createElement(`canvas`);C5=!!(e.getContext(`webgl`)||e.getContext(`experimental-webgl`))}catch{C5=!1}return C5}function Tme(){let[e,t]=(0,Z.useState)(C5??!0);return(0,Z.useEffect)(()=>{if(typeof document>`u`)return;let e=setTimeout(()=>{let e=wme();t(e),e||QT(`unavailable`)},0);return()=>clearTimeout(e)},[]),e}function w5(e){if(!e)throw Error(`Assertion failed.`)}var T5=e=>e&&e[e.length-1],E5=e=>e>=0&&e<2**32,D5=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},O5=e=>{let t=D5(e);return t&1?t+1>>1:-(t>>1)},k5=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),A5=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),j5=new TextEncoder,M5={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},N5={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},P5={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Eme=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,F5=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),I5=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},Dme=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},L5=e=>{throw Error(`Unexpected value: ${e}`)},Ome=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},kme=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Ame=/^[a-z]{3}$/,jme=e=>Ame.test(e),R5=1e6*(1+2**-52),Mme=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{num:n*a,den:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{num:n*a,den:o}},z5=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Nme=e=>{w5(Number.isInteger(e.num)),w5(Number.isInteger(e.den)),w5(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},B5=e=>Array.isArray(e)?e:[e],V5=class{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},Pme=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),H5;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(H5||={});var U5=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==H5.Silent&&t!==H5.Errors&&t!==H5.Warnings&&t!==H5.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new V5}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=H5.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=H5.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=H5.Info&&console.info(...t)}};U5._level=H5.Info,U5._emitterInstance=null;var W5=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},Fme=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},Ime=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(t instanceof Uint8Array)&&!(t instanceof W5)&&!(t instanceof Fme)&&!Pme(t))throw TypeError(`Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},Lme=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.primary!==void 0&&typeof e.primary!=`boolean`)throw TypeError(`disposition.primary must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},G5=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},K5=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],q5=[-1,1,2,3,4,5,6,8],Rme=e=>{let t=K5.indexOf(e.sampleRate),n=null;t===-1&&(t=15,n=e.sampleRate);let r=q5.indexOf(e.numberOfChannels);if(r===-1)throw TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let i=13;e.objectType>=32&&(i+=6),t===15&&(i+=24);let a=Math.ceil(i/8),o=new Uint8Array(a),s=new G5(o);return e.objectType<32?s.writeBits(5,e.objectType):(s.writeBits(5,31),s.writeBits(6,e.objectType-32)),s.writeBits(4,t),t===15&&s.writeBits(24,n),s.writeBits(4,r),o},J5=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Y5=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],X5=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],Z5=[...X5,...Y5],Q5=[`webvtt`],$5=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],e7=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],t7=[`dtsc`,`dtsh`,`dtsl`,`dtse`],zme=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=+(r.slice(-1)===`H`),s=Number(t[3])===8?0:1,c=t[4]?Number(t[4]):0,l=t[5]?Number(t[5][0]):1,u=t[5]?Number(t[5][1]):1,d=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(s<<6)+0+(c<<4)+(l<<3)+(u<<2)+d,0]},n7=/^pcm-([usf])(\d+)(be)?$/,r7=e=>{if(w5(Y5.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=n7.exec(e);w5(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?2**7:0}},i7=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:e7.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:t7.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:n7.test(e)?e:e===`webvtt`?`webvtt`:null,Bme=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...e7],Vme=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Hme=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ume=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Wme=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,a7=(e,t)=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!Bme.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectWidth!==void 0!=(e.decoderConfig.displayAspectHeight!==void 0))throw TypeError(`Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.`);if(e.decoderConfig.description!==void 0&&!F5(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(M5);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(N5);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(P5);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!Vme.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!Hme.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!Ume.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)){if(!Wme.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)}else if(e7.some(t=>e.decoderConfig.codec.startsWith(t))&&!e7.some(t=>e.decoderConfig.codec===t))throw TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${e7.join(`, `)}.`);if(t!==null&&i7(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},Gme=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],o7=(e,t)=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!Gme.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!F5(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if(e.decoderConfig.codec.startsWith(`dts`)){if(!t7.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${t7.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!Y5.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Y5.join(`, `)}).`);if(t!==null&&i7(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},Kme=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},qme=[48e3,44100,32e3],Jme=[24e3,22050,16e3],s7;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(s7||={});var c7;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(c7||={});var l7=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},Yme=e=>e&31,u7=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)};new Uint8Array([0,0,0,1]);var Xme=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:Ome(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},Zme=e=>{try{let t=[],n=[],r=[];for(let i of l7(e)){let a=e.subarray(i.offset,i.offset+i.length),o=Yme(a[0]);o===s7.SPS?t.push(a):o===s7.PPS?n.push(a):o===s7.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=$me(i);w5(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return U5._error(`Error building AVC Decoder Configuration Record:`,e),null}},Qme=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if(e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144){w5(e.chromaFormat!==null),w5(e.bitDepthLumaMinus8!==null),w5(e.bitDepthChromaMinus8!==null),w5(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},d7={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},$me=e=>{try{let t=new G5(u7(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let n=t.readAlignedByte(),r=t.readAlignedByte(),i=t.readAlignedByte();D5(t);let a=1,o=0,s=0,c=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=D5(t),a===3&&(c=t.readBits(1)),o=D5(t),s=D5(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(a===3?12:8);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(i!==0){let e=O5(t);i=(r+e+256)%256}r=i===0?r:i}}}D5(t);let l=D5(t);if(l===0)D5(t);else if(l===1){t.skipBits(1),O5(t),O5(t);let e=D5(t);for(let n=0;n<e;n++)O5(t)}D5(t),t.skipBits(1);let u=D5(t),d=D5(t),f=16*(u+1),p=16*(d+1),m=f,h=p,g=t.readBits(1);if(g||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e=D5(t),n=D5(t),r=D5(t),i=D5(t),o,s;if((c===0?a:0)===0)o=1,s=2-g;else{let e=a===3?1:2,t=a===1?2:1;o=e,s=t*(2-g)}m-=o*(e+n),h-=s*(r+i)}let _=2,v=2,y=2,b=0,x={num:1,den:1},S=null,C=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);if(e===255)x={num:t.readBits(16),den:t.readBits(16)};else{let t=d7[e];t&&(x=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),b=t.readBits(1),t.readBits(1)&&(_=t.readBits(8),v=t.readBits(8),y=t.readBits(8))),t.readBits(1)&&(D5(t),D5(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&f7(t);let n=t.readBits(1);n&&f7(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),D5(t),D5(t),D5(t),D5(t),S=D5(t),C=D5(t))}if(S===null){w5(C===null);let e=r&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&e)S=0,C=0;else{let e=u+1,t=d+1,n=(2-g)*t,r=$5.find(e=>e.level>=i)??T5($5),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);S=a,C=a}}return w5(C!==null),{profileIdc:n,constraintFlags:r,levelIdc:i,frameMbsOnlyFlag:g,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:s,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:h,pixelAspectRatio:x,colourPrimaries:_,matrixCoefficients:y,transferCharacteristics:v,fullRangeFlag:b,numReorderFrames:S,maxDecFrameBuffering:C}}catch(e){return U5._error(`Error parsing AVC SPS:`,e),null}},f7=e=>{let t=D5(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)D5(e),D5(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},p7=e=>e>>1&63,ehe=e=>{try{let t=new G5(u7(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=nhe(t,n);D5(t);let u=D5(t),d=0;u===3&&(d=t.readBits(1));let f=D5(t),p=D5(t),m=f,h=p;if(t.readBits(1)){let e=D5(t),n=D5(t),r=D5(t),i=D5(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=D5(t),_=D5(t);D5(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)D5(t),y=D5(t),D5(t);if(D5(t),D5(t),D5(t),D5(t),D5(t),D5(t),t.readBits(1)&&t.readBits(1)&&rhe(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),D5(t),D5(t),t.skipBits(1)),ihe(t,D5(t)),t.readBits(1)){let e=D5(t);for(let n=0;n<e;n++)D5(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,w=0,T={num:1,den:1};if(t.readBits(1)){let e=ohe(t,n);T=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,w=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:T,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:w}}catch(e){return U5._error(`Error parsing HEVC SPS:`,e),null}},the=e=>{try{let t=[],n=[],r=[],i=[];for(let a of l7(e)){let o=e.subarray(a.offset,a.offset+a.length),s=p7(o[0]);s===c7.VPS_NUT?t.push(o):s===c7.SPS_NUT?n.push(o):s===c7.PPS_NUT?r.push(o):(s===c7.PREFIX_SEI_NUT||s===c7.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=ehe(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new G5(u7(e));t.skipBits(16),D5(t),D5(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),D5(t),D5(t),O5(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&D5(t),O5(t),O5(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:c7.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:c7.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:c7.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:p7(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return U5._error(`Error building HEVC Decoder Configuration Record:`,e),null}},nhe=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},rhe=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))D5(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&O5(e);for(let t=0;t<n;t++)O5(e)}},ihe=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=ahe(e,r,t,n)},ahe=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(D5(e)+1):t-1,e.readBits(1),D5(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=D5(e),n=D5(e);for(let n=0;n<t;n++)D5(e),e.readBits(1);for(let t=0;t<n;t++)D5(e),e.readBits(1);i=t+n}return i},ohe=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=d7[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(D5(e),D5(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(D5(e),D5(e),D5(e),D5(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&D5(e),e.readBits(1)&&she(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=D5(e),D5(e),D5(e),D5(e),D5(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},she=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?D5(e):o=e.readBits(1)===1;let s=1;o||(s=D5(e)+1),r&&m7(e,s,a),i&&m7(e,s,a)}},m7=(e,t,n)=>{for(let r=0;r<t;r++)D5(e),D5(e),n&&(D5(e),D5(e)),e.readBits(1)},che=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},lhe;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(lhe||={});var uhe=e=>{let t=A5(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},dhe;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(dhe||={});var fhe=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new G5(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}};new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var phe=[1,2,3,6],mhe=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new G5(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=phe[o],d;return d=i<3?qme[i]/1e3:Jme[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},hhe=8,ghe=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],_he=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],vhe=[16,16,20,20,0,24,24,0],h7=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],yhe=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],bhe=8,g7=[32e3,44100,48e3,0],xhe=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],She=[512,1024,2048,4096],Che=e=>{let t=whe(e),n=A5(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=The(e.subarray(r));if(!t)break;i??=t,r+=t.frameSize}if(t)return{frameSize:i?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:i!==null};if(!i?.asset)return null;let{asset:a}=i;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},whe=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new G5(e);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==31)return null;let n=t.readBits(1),r=t.readBits(7)+1;if(r%hhe!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=h7.length)return null;let o=ghe[t.readBits(4)];if(o===0)return null;let s=_he[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),n&&t.skipBits(16),t.skipBits(7);let l=vhe[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:h7[a]+ +!!u,sampleCount:r*32,channelLayout:yhe[a]|(u?bhe:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},The=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new G5(e);t.skipBits(32),t.skipBits(8);let n=t.readBits(2),r=t.readBits(1),i=8+4*r,a=16+4*r;t.skipBits(i);let o=t.readBits(a)+1,s={frameSize:o,asset:null};if(!t.readBits(1))return s;let c=g7[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,f=[];for(let e=0;e<u;e++)f.push(t.readBits(n+1));for(let e of f)t.skipBits(8*kme(e));if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,n=t.readBits(2)+1;t.skipBits(n*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let p=t.readBits(5)+1,m=xhe[t.readBits(4)],h=t.readBits(8)+1,g=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;g=t.readBits(e)}return c===0||t.getBitsLeft()<0?s:{frameSize:o,asset:{sampleRate:m,numberOfChannels:h,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:p}}},Ehe=e=>{let t=new Uint8Array(20),n=A5(t);n.setUint32(0,e.sampleRate),n.setUint32(4,e.bitRate),n.setUint32(8,e.bitRate),t[12]=e.pcmResolution;let r=e.core&&!e.hasExtensions?1:0,i=new G5(t);return i.seekToByte(13),i.writeBits(2,Math.max(She.indexOf(e.sampleCount),0)),i.writeBits(5,r),i.writeBits(1,+!!e.core?.lfePresent),i.writeBits(6,e.core?.amode??0),i.writeBits(14,e.core?e.core.frameSize-1:0),i.writeBits(1,0),i.writeBits(3,0),i.writeBits(16,e.channelLayout),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(5,0),t},_7=new Uint8Array,v7=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===_7&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===_7}get microsecondTimestamp(){return Math.trunc(R5*this.timestamp)}get microsecondDuration(){return Math.trunc(R5*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`EncodedAudioChunk is not available in this environment.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},Dhe=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},y7=e=>{let t=e.filePos,n=new G5(Ahe(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},Ohe=n(((e,t)=>{t.exports={}})),b7=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,A5(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},khe=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},Ahe=(e,t)=>{khe(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},jhe=class{constructor(e){this.mutex=new I5,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},x7=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Mhe=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},S7=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);w5(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},C7=new Uint8Array(8),w7=new DataView(C7.buffer),T7=e=>[(e%256+256)%256],E7=e=>(w7.setUint16(0,e,!1),[C7[0],C7[1]]),D7=e=>(w7.setInt16(0,e,!1),[C7[0],C7[1]]),O7=e=>(w7.setUint32(0,e,!1),[C7[1],C7[2],C7[3]]),$=e=>(w7.setUint32(0,e,!1),[C7[0],C7[1],C7[2],C7[3]]),k7=e=>(w7.setInt32(0,e,!1),[C7[0],C7[1],C7[2],C7[3]]),A7=e=>(w7.setUint32(0,Math.floor(e/2**32),!1),w7.setUint32(4,e,!1),[C7[0],C7[1],C7[2],C7[3],C7[4],C7[5],C7[6],C7[7]]),Nhe=e=>(w7.setInt32(0,Math.floor(e/2**32),!1),w7.setUint32(4,e,!1),[C7[0],C7[1],C7[2],C7[3],C7[4],C7[5],C7[6],C7[7]]),j7=e=>(w7.setInt16(0,2**8*e,!1),[C7[0],C7[1]]),M7=e=>(w7.setInt32(0,2**16*e,!1),[C7[0],C7[1],C7[2],C7[3]]),N7=e=>(w7.setInt32(0,2**30*e,!1),[C7[0],C7[1],C7[2],C7[3]]),P7=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},F7=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},I7=e=>{let t=Math.PI/180*e,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},L7=I7(0),R7=e=>[M7(e[0]),M7(e[1]),N7(e[2]),M7(e[3]),M7(e[4]),N7(e[5]),M7(e[6]),M7(e[7]),N7(e[8])],z7=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),B7=(e,t,n,r,i)=>z7(e,[T7(t),O7(n),r??[]],i),Phe=e=>e.isQuickTime?z7(`ftyp`,[F7(`qt `),$(512),F7(`qt `)]):e.fragmented?e.cmaf?z7(`ftyp`,[F7(`iso5`),$(512),F7(`iso5`),F7(`iso6`),F7(`mp41`),F7(`cmfc`),F7(`dash`)]):z7(`ftyp`,[F7(`iso5`),$(512),F7(`iso5`),F7(`iso6`),F7(`mp41`)]):z7(`ftyp`,[F7(`isom`),$(512),F7(`isom`),e.holdsAvc?F7(`avc1`):[],F7(`mp41`)]),V7=()=>z7(`styp`,[F7(`iso5`),$(0),F7(`iso5`),F7(`iso6`),F7(`mp41`),F7(`cmfc`),F7(`dash`)]),H7=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),B7(`sidx`,1,0,[$(1),$(d9),A7(f9(e.minWrittenTimestamp,d9)),A7(0),E7(0),E7(1),$(t&2147483647),$(f9(n,d9)),$(0)])},U7=e=>({type:`mdat`,largeSize:e}),Fhe=e=>({type:`free`,size:e}),W7=e=>z7(`moov`,void 0,[Ihe(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Lhe(t,e.creationTime)),e.isFragmented?bge(e.trackDatas):null,Nge(e)]),Ihe=(e,t)=>{let n=Math.max(0,...t.map(e=>f9(G7(e),d9)+f9(e.startTimestampOffset??0,d9))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!E5(e)||!E5(n),a=i?A7:$;return B7(`mvhd`,+i,0,[a(e),a(e),$(d9),a(n),M7(1),j7(1),Array(10).fill(0),R7(L7),Array(24).fill(0),$(r)])},G7=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},Lhe=(e,t)=>{let n=Wge(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return z7(`trak`,void 0,[Rhe(e,t),r?zhe(e,e.startTimestampOffset):null,Bhe(e,t),n.name===void 0?null:z7(`udta`,void 0,[z7(`name`,[...j5.encode(n.name)])])])},Rhe=(e,t)=>{let n=f9(G7(e),d9)+f9(e.startTimestampOffset??0,d9),r=!E5(t)||!E5(n),i=r?A7:$,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=I7(t??0)}else a=L7;let o=2;e.track.metadata.disposition?.default!==!1&&(o|=1);let s=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:L5(e);return B7(`tkhd`,+r,o,[i(t),i(t),$(e.track.id),$(0),i(n),Array(8).fill(0),E7(0),E7(s),j7(+(e.type===`audio`)),E7(0),R7(a),M7(e.type===`video`?e.info.width:0),M7(e.type===`video`?e.info.height:0)])},zhe=(e,t)=>{let n=f9(t,d9),r=f9(G7(e),d9),i=!E5(n)||!E5(r),a=i?A7:$,o=i?Nhe:k7;return z7(`edts`,void 0,[B7(`elst`,+!!i,0,[$(2),a(n),o(-1),M7(1),a(r),o(0),M7(1)])])},Bhe=(e,t)=>z7(`mdia`,void 0,[Vhe(e,t),K7(!0,Hhe[e.type],Uhe[e.type]),Whe(e)]),Vhe=(e,t)=>{let n=f9(G7(e),e.timescale),r=!E5(t)||!E5(n),i=r?A7:$;return B7(`mdhd`,+r,0,[i(t),i(t),$(e.timescale),i(n),E7(i9(e.track.metadata.languageCode??`und`)),E7(0)])},Hhe={video:`vide`,audio:`soun`,subtitle:`text`},Uhe={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},K7=(e,t,n,r=`\0\0\0\0`)=>B7(`hdlr`,0,0,[e?F7(`mhlr`):$(0),F7(t),F7(r),$(0),$(0),F7(n,!0)]),Whe=e=>z7(`minf`,void 0,[Ghe[e.type](),Khe(),Yhe(e)]),Ghe={video:()=>B7(`vmhd`,0,1,[E7(0),E7(0),E7(0),E7(0)]),audio:()=>B7(`smhd`,0,0,[E7(0),E7(0)]),subtitle:()=>B7(`nmhd`,0,0)},Khe=()=>z7(`dinf`,void 0,[qhe()]),qhe=()=>B7(`dref`,0,0,[$(1)],[Jhe()]),Jhe=()=>B7(`url `,0,1),Yhe=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return z7(`stbl`,void 0,[Xhe(e),pge(e),t?vge(e):null,t?yge(e):null,hge(e),gge(e),_ge(e),mge(e)])},Xhe=e=>{let t;if(e.type===`video`)t=Zhe(Lge(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=r9(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);w5(n),t=rge(n,e)}else e.type===`subtitle`&&(t=dge(Bge[e.track.source._codec],e));return w5(t),B7(`stsd`,0,0,[$(1)],[t])},Zhe=(e,t)=>z7(e,[[,,,,,,].fill(0),E7(1),E7(0),E7(0),Array(12).fill(0),E7(t.info.width),E7(t.info.height),$(4718592),$(4718592),$(0),E7(1),T7(10),F7(`Mediabunny`),Array(21).fill(0),E7(t.info.hasAlphaChannel?32:24),D7(65535)],[Rge[t.track.source._codec]?.(t)??null,Qhe(t),Eme(t.info.decoderConfig.colorSpace)?$he(t):null]),Qhe=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:z7(`pasp`,[$(e.info.pixelAspectRatio.num),$(e.info.pixelAspectRatio.den)]),$he=e=>z7(`colr`,[F7(e.muxer.isQuickTime?`nclc`:`nclx`),E7(M5[e.info.decoderConfig.colorSpace.primaries]),E7(N5[e.info.decoderConfig.colorSpace.transfer]),E7(P5[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:T7(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),ege=e=>e.info.decoderConfig&&z7(`avcC`,[...k5(e.info.decoderConfig.description)]),tge=e=>e.info.decoderConfig&&z7(`hvcC`,[...k5(e.info.decoderConfig.description)]),q7=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?M5[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?N5[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?P5[t.colorSpace.matrix]:2;return B7(`vpcC`,1,0,[T7(r),T7(i),T7(c),T7(l),T7(u),T7(d),E7(0)])},nge=e=>z7(`av1C`,zme(e.info.decoderConfig.codec)),rge=(e,t)=>{let n=0,r,i=16,a=Y5.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=r7(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),E7(1),E7(n),E7(0),$(0),E7(t.info.numberOfChannels),E7(i),E7(0),E7(0),E7(t.info.sampleRate<2**16?t.info.sampleRate:0),E7(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),E7(1),E7(n),E7(0),$(0),E7(t.info.numberOfChannels),E7(Math.min(i,16)),D7(e),E7(0),E7(t.info.sampleRate<2**16?t.info.sampleRate:0),E7(0),a?[$(1),$(i/8),$(t.info.numberOfChannels*i/8)]:[$(0),$(0),$(0)],$(2)]}return z7(e,r,[zge(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},J7=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...T7(t),...T7(21),...O7(0),...$(0),...$(0)];if(e.info.decoderConfig.description){let t=k5(e.info.decoderConfig.description);n=[...n,...T7(5),...P7(t.byteLength),...t]}return n=[...E7(1),...T7(0),...T7(4),...P7(n.length),...n,...T7(6),...T7(1),...T7(2)],n=[...T7(3),...P7(n.length),...n],B7(`esds`,0,0,n)},Y7=e=>z7(`wave`,void 0,[ige(e),age(e),z7(`\0\0\0\0`)]),ige=e=>z7(`frma`,[F7(r9(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),age=e=>{let{littleEndian:t}=r7(e.track.source._codec);return z7(`enda`,[E7(+t)])},oge=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){w5(s.byteLength>=18);let e=uhe(k5(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return z7(`dOps`,[T7(0),T7(t),E7(n),$(r),D7(i),T7(a),...o])},sge=e=>{let t=e.info.decoderConfig?.description;return w5(t),B7(`dfLa`,0,0,[...k5(t).subarray(4)])},X7=e=>{let{littleEndian:t,sampleSize:n}=r7(e.track.source._codec);return B7(`pcmC`,0,0,[T7(+t),T7(8*n)])},cge=e=>{w5(e.info.primingPacket);let t=fhe(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=new Uint8Array(3),r=new G5(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),z7(`dac3`,[...n])},lge=e=>{w5(e.info.primingPacket);let t=mhe(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new G5(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return z7(`dec3`,[...i])},uge=e=>{w5(e.info.primingPacket);let t=Che(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return z7(`ddts`,[...Ehe(t)])},dge=(e,t)=>z7(e,[[,,,,,,].fill(0),E7(1)],[Vge[t.track.source._codec](t)]),fge=e=>z7(`vttC`,[...j5.encode(e.info.config.description)]),pge=e=>B7(`stts`,0,0,[$(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[$(e.sampleCount),$(e.sampleDelta)])]),mge=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return B7(`stss`,0,0,[$(t.length),t.map(([e])=>$(e+1))])},hge=e=>B7(`stsc`,0,0,[$(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[$(e.firstChunk),$(e.samplesPerChunk),$(1)])]),gge=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=r7(e.track.source._codec);return B7(`stsz`,0,0,[$(t*e.info.numberOfChannels),$(e.samples.reduce((t,n)=>t+f9(n.duration,e.timescale),0))])}return B7(`stsz`,0,0,[$(0),$(e.samples.length),e.samples.map(e=>$(e.size))])},_ge=e=>e.finalizedChunks.length>0&&T5(e.finalizedChunks).offset>=2**32?B7(`co64`,0,0,[$(e.finalizedChunks.length),e.finalizedChunks.map(e=>A7(e.offset))]):B7(`stco`,0,0,[$(e.finalizedChunks.length),e.finalizedChunks.map(e=>$(e.offset))]),vge=e=>B7(`ctts`,1,0,[$(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[$(e.sampleCount),k7(e.sampleCompositionTimeOffset)])]),yge=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;w5(e.compositionTimeOffsetTable.length>0),w5(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,f9(n.timestamp,e.timescale)),i=Math.max(i,f9(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:B7(`cslg`,0,0,[k7(a),k7(t),k7(n),k7(r),k7(i)])},bge=e=>z7(`mvex`,void 0,e.map(xge)),xge=e=>B7(`trex`,0,0,[$(e.track.id),$(1),$(0),$(0),$(0)]),Z7=(e,t)=>z7(`moof`,void 0,[Sge(e),...t.map(Cge)]),Sge=e=>B7(`mfhd`,0,0,[$(e)]),Q7=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Cge=e=>z7(`traf`,void 0,[wge(e),Tge(e),Ege(e)]),wge=e=>{w5(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:Q7(n)};return B7(`tfhd`,0,t,[$(e.track.id),$(r.duration),$(r.size),$(r.flags)])},Tge=e=>(w5(e.currentChunk),B7(`tfdt`,1,0,[A7(f9(e.currentChunk.startTimestamp,e.timescale))])),Ege=e=>{w5(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Q7),i=e.currentChunk.samples.map(t=>f9(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,B7(`trun`,1,m,[$(e.currentChunk.samples.length),$(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?$(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?$(t[a]):[],d?$(n[a]):[],f?$(r[a]):[],p?k7(i[a]):[]])])},Dge=e=>z7(`mfra`,void 0,[...e.map(Oge),kge()]),Oge=e=>B7(`tfra`,1,0,[$(e.track.id),$(63),$(e.finalizedChunks.length),e.finalizedChunks.map(t=>[A7(f9(t.samples[0].timestamp,e.timescale)),A7(t.moofOffset),$(t.trafIndex+1),$(1),$(1)])]),kge=()=>B7(`mfro`,0,0,[$(0)]),Age=()=>z7(`vtte`),jge=(e,t,n,r,i)=>z7(`vttc`,void 0,[i===null?null:z7(`vsid`,[k7(i)]),n===null?null:z7(`iden`,[...j5.encode(n)]),t===null?null:z7(`ctim`,[...j5.encode(Mhe(t))]),r===null?null:z7(`sttg`,[...j5.encode(r)]),z7(`payl`,[...j5.encode(e)])]),Mge=e=>z7(`vtta`,[...j5.encode(e)]),Nge=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Fge(r);e&&t.push(e)}else if(n===`mdta`){let e=Ige(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&Pge(t,e.output._metadataTags);return t.length===0?null:z7(`udta`,void 0,t)},Pge=(e,t)=>{for(let{key:n,value:r}of z5(t))switch(n){case`title`:e.push($7(`©nam`,r));break;case`description`:e.push($7(`©des`,r));break;case`artist`:e.push($7(`©ART`,r));break;case`album`:e.push($7(`©alb`,r));break;case`albumArtist`:e.push($7(`albr`,r));break;case`genre`:e.push($7(`©gen`,r));break;case`date`:e.push($7(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push($7(`©cmt`,r));break;case`lyrics`:e.push($7(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:L5(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push($7(n,r)):r instanceof Uint8Array&&e.push(z7(n,Array.from(r))))}},$7=(e,t)=>{let n=j5.encode(t);return z7(e,[E7(n.length),E7(i9(`und`)),Array.from(n)])},e9={"image/jpeg":13,"image/png":14,"image/bmp":27},t9=(e,t)=>{let n=[];for(let{key:r,value:i}of z5(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:n9(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:n9(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:n9(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:n9(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:n9(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:n9(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:n9(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:n9(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:n9(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:z7(`data`,[$(e9[e.mimeType]??0),$(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:n9(t)})}else n.push({key:`trkn`,value:z7(`data`,[$(0),$(0),E7(0),E7(i),E7(e.tracksTotal??0),E7(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:z7(`data`,[$(0),$(0),E7(0),E7(i),E7(e.discsTotal??0),E7(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:L5(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:n9(i)}):i instanceof Uint8Array?n.push({key:r,value:z7(`data`,[$(0),$(0),Array.from(i)])}):i instanceof W5&&n.push({key:r,value:z7(`data`,[$(e9[i.mimeType]??0),$(0),Array.from(i.data)])}))}return n},Fge=e=>{let t=t9(e,!1);return t.length===0?null:B7(`meta`,0,0,void 0,[K7(!1,`mdir`,``,`appl`),z7(`ilst`,void 0,t.map(e=>z7(e.key,void 0,[e.value])))])},Ige=e=>{let t=t9(e,!0);return t.length===0?null:z7(`meta`,void 0,[K7(!1,`mdta`,``),B7(`keys`,0,0,[$(t.length)],t.map(e=>z7(`mdta`,[...j5.encode(e.key)]))),z7(`ilst`,void 0,t.map((e,t)=>z7(String.fromCharCode(...$(t+1)),void 0,[e.value])))])},n9=e=>z7(`data`,[$(1),$(0),...j5.encode(e)]),Lge=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},Rge={avc:ege,hevc:tge,vp8:q7,vp9:q7,av1:nge,prores:null},r9=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},zge=(e,t)=>{switch(e){case`aac`:return J7;case`mp3`:return J7;case`opus`:return oge;case`vorbis`:return J7;case`flac`:return sge;case`ac3`:return cge;case`eac3`:return lge;case`dts`:return uge}if(t)switch(e){case`pcm-s24`:return Y7;case`pcm-s24be`:return Y7;case`pcm-s32`:return Y7;case`pcm-s32be`:return Y7;case`pcm-f32`:return Y7;case`pcm-f32be`:return Y7;case`pcm-f64`:return Y7;case`pcm-f64be`:return Y7}else switch(e){case`pcm-s16`:return X7;case`pcm-s16be`:return X7;case`pcm-s24`:return X7;case`pcm-s24be`:return X7;case`pcm-s32`:return X7;case`pcm-s32be`:return X7;case`pcm-f32`:return X7;case`pcm-f32be`:return X7;case`pcm-f64`:return X7;case`pcm-f64be`:return X7}return null},Bge={webvtt:`wvtt`},Vge={webvtt:fge},i9=e=>{w5(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},a9=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){w5(!this.started),this.target._start(),this.started=!0}write(e){w5(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return w5(this.started&&!this.finalized),this.target._flush()}async finalize(){w5(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};Ohe();var o9=class extends V5{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new Hge(this,e)}},s9=2**16,c9=2**32,l9=class extends o9{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(s9,{maxByteLength:c9})}catch{this._buffer=new ArrayBuffer(s9),this._supportsResize=!1}else this._buffer=new ArrayBuffer(s9);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>c9)throw Error(`ArrayBuffer exceeded maximum size of ${c9} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},Hge=class extends o9{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},u9=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},d9=57600,Uge=2082844800,Wge=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},f9=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Gge=class extends jhe{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new l9,this.auxWriter=new a9(this.auxTarget,!1),this.auxBoxWriter=new S7(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Dme(),this.creationTime=Math.floor(Date.now()/1e3)+Uge,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof y9,this.isCmaf=t instanceof v9,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof v9?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof l9:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new S7(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof l9&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new a9(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new S7(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(w5(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Phe({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(w5(this.writer),w5(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=U7(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return Dhe({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;a7(n,e.source._codec),w5(n),w5(n.decoderConfig);let i={...n.decoderConfig};w5(i.codedWidth!==void 0),w5(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=Zme(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Qme(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=the(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=che(e),a=!0}let o=Mme(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:Nme({num:s*i.codedHeight,den:c*i.codedWidth}),u=i.codec===`ap4h`||i.codec===`ap4x`,d={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a,hasAlphaChannel:u},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;o7(n,e.source._codec),w5(n),w5(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=y7(b7.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=K5[e.samplingFrequencyIndex],r=q5[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=Rme({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),a=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Y5.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,primingPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;Kme(t),w5(t),w5(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...l7(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=Xme(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=y7(b7.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=r7(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=f9(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=r7(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let r of e.cueQueue)w5(r.timestamp<=t),w5(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=Age();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;x7.lastIndex=0;let r=x7.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=Mge(n.notes);this.auxBoxWriter.writeBox(e)}let c=jge(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:f9(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=f9(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=T5(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=f9(r.timestamp-r.decodeTimestamp,e.timescale),a=f9(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){w5(e.lastSample);let t=f9(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(w5(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=T5(e.timeToSampleTable);if(w5(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=T5(e.compositionTimeOffsetTable);w5(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=f9(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,w5(e.lastSample),w5(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){w5(t.type===`key`);let n=f9(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(w5(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),w5(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(w5(!this.isFragmented),w5(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+f9(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||T5(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)w5(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(w5(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(w5(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;w5(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=W7(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){w5(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new S7(this.writer);let e=this.boxWriter.measureBox(V7()),t=this.boxWriter.measureBox(H7(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}w5(this.writer),w5(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=Z7(n,t),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e=0;e<t.length;e++){let n=t[e];n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e;for(let e of n.currentChunk.samples)o+=e.size;s=Math.min(s,n.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=Z7(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}w5(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=U7(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){w5(this.writer),w5(this.boxWriter),this.ensureOneEnabledTrack();let e=W7(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;w5(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=U7(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){w5(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;w5(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){w5(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas)if(await this.finalizeCurrentChunk(e),e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}if(w5(this.writer),w5(this.boxWriter),this.fastStart===`in-memory`){this.mdat=U7(!1);let e;for(let t=0;t<2;t++){let t=W7(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)w5(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=W7(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)w5(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented)if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(V7()),this.boxWriter.writeBox(H7(this,e))}else{let e=this.writer.getPos(),t=Dge(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{w5(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);w5(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=W7(this);if(this.fastStart===`reserve`){w5(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Fhe(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}},p9=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},m9=class extends p9{constructor(e){if(super(),this._connectedTrack=null,!J5.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${J5.join(`, `)}.`);this._codec=e}},Kge=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},qge=class extends m9{constructor(e){super(e)}add(e,t){if(!(e instanceof v7))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),Kge(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},Jge=class extends p9{constructor(e){if(super(),this._connectedTrack=null,!Z5.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${Z5.join(`, `)}.`);this._codec=e}},Yge=class extends p9{constructor(e){if(super(),this._connectedTrack=null,!Q5.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Q5.join(`, `)}.`);this._codec=e}},h9=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>J5.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Z5.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Q5.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},g9=class extends h9{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Gge(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},_9=class extends g9{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...J5,...X5,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Q5]}_codecUnsupportedHint(e){return new y9().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},v9=class extends g9{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...J5,...X5,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Q5]}},y9=class extends g9{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...J5,...Z5]}_codecUnsupportedHint(e){return new _9().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},b9=[`video`,`audio`,`subtitle`],x9=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=B5(this.metadata.group),r=B5(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},Xge=class extends x9{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Zge=class extends x9{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Qge=class extends x9{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},S9=class e{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},C9=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!jme(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&Lme(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.group!==void 0&&!(e.group instanceof S9)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof S9))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},$ge=class extends V5{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new S9,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new I5,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof h9))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof o9||e.target instanceof u9))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof o9&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof o9)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof o9&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){w5(this._target instanceof u9);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof o9))throw TypeError(`getTarget must return a Target.`);return e};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){w5(this._target instanceof u9);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(w5(this._initTarget!==null),this._initTarget instanceof o9)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof o9)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new a9(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof m9))throw TypeError(`source must be a VideoSource.`);if(C9(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.decoderConfig!==void 0&&a7({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof v7))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Xge(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Jge))throw TypeError(`source must be an AudioSource.`);if(C9(t),t.decoderConfig!==void 0&&o7({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof v7))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Zge(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Yge))throw TypeError(`source must be a SubtitleSource.`);C9(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Qge(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Ime(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of b9)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of b9){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(U5._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return U5._warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&U5._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(U5._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}},e_e=e=>{if(e.startsWith(`avc1`))return`avc`;throw RangeError(`unsupported MP4 video codec: ${e}`)};async function t_e({chunks:e,codec:t,decoderConfig:n,signal:r=null}){if(!Array.isArray(e)||e.length<1)throw RangeError(`MP4 needs at least one encoded frame`);if(!n||typeof n!=`object`)throw TypeError(`MP4 needs a decoder config`);if(t.startsWith(`avc1`)&&!n.description)throw Error(`H.264 MP4 needs the encoder's AVC decoder configuration`);let i=new l9,a=new $ge({format:new _9({fastStart:`in-memory`}),target:i}),o=new qge(e_e(t));a.addVideoTrack(o);try{r?.throwIfAborted(),await a.start();for(let t=0;t<e.length;t+=1){r?.throwIfAborted();let i=e[t],a=new v7(i.data,i.type,i.timestamp/1e6,i.duration/1e6,t);await o.add(a,t===0?{decoderConfig:n}:void 0)}if(r?.throwIfAborted(),await a.finalize(),!i.buffer)throw Error(`MP4 muxer finalized without output`);return new Blob([i.buffer],{type:`video/mp4`})}catch(e){throw a.state!==`finalized`&&a.state!==`canceled`&&await a.cancel(),e}}var n_e=Object.freeze([Object.freeze({codec:`avc1.640032`,avc:Object.freeze({format:`avc`})}),Object.freeze({codec:`avc1.4d0032`,avc:Object.freeze({format:`avc`})}),Object.freeze({codec:`avc1.420032`,avc:Object.freeze({format:`avc`})})]);function r_e(e,t){let n=Math.round(e),r=Math.round(t);if(!Number.isFinite(e)||!Number.isFinite(t)||n<0||r<n)throw RangeError(`export frame range must be an inclusive non-negative range`);return{startFrame:n,endFrame:r,frameCount:r-n+1}}async function i_e(e,t=globalThis.crypto?.subtle){if(!t)throw Error(`Web Crypto is unavailable; pixel hashes cannot be computed`);return[...new Uint8Array(await t.digest(`SHA-256`,e))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function a_e(e,t,n,r){let i=n*4;for(let n=0;n<r;n+=1){let a=(r-1-n)*i;t.set(e.subarray(a,a+i),n*i)}}function w9(e,t){try{Object.defineProperty(e,"exportFailureCode",{value:e?.name===`AbortError`?`aborted`:t,configurable:!0})}catch{}return e}function T9(e,t){return t?new Promise((n,r)=>{let i=()=>{a(),r(E9())},a=()=>t.removeEventListener(`abort`,i);t.aborted?i():t.addEventListener(`abort`,i,{once:!0}),Promise.resolve(e).then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}async function o_e(e,t,n,r,i){for(let a of n_e){if(i?.aborted)throw E9();let o={...a,width:e,height:t,framerate:n,bitrate:Math.max(2e6,Math.round(e*t*n*.24)),latencyMode:`quality`};try{let e=await T9(r.isConfigSupported(o),i);if(e.supported)return e.config}catch(e){if(e?.name===`AbortError`)throw e}}throw i?.aborted?E9():w9(Error(`This browser has no H.264 WebCodecs encoder for MP4 export`),`unsupported_codec`)}function E9(){return new DOMException(`Offscreen export was cancelled`,`AbortError`)}async function s_e({startFrame:e,endFrame:t,fps:n,width:r,height:i,capture:a,signal:o,passKind:s=null,onFrame:c,onPhase:l,VideoEncoderClass:u=globalThis.VideoEncoder,VideoFrameClass:d=globalThis.VideoFrame}){if(o?.aborted)throw E9();let f=r_e(e,t);if(!Number.isFinite(n)||n<=0)throw RangeError(`export fps must be positive`);if(!Number.isInteger(r)||r<1||!Number.isInteger(i)||i<1)throw RangeError(`invalid export dimensions`);if(typeof a!=`function`)throw TypeError(`export capture must be a function`);if(!u||!d)throw w9(Error(`This browser does not support WebCodecs video export`),`unsupported_codec`);let p=await o_e(r,i,n,u,o);if(o?.aborted)throw E9();let m=[],h=null,g=[],_=null,v=null,y=`encode_failed`,b=()=>{try{v&&v.state!==`closed`&&v.close()}catch{}};try{if(v=new u({output(e,t){try{let r=new Uint8Array(e.byteLength);e.copyTo(r),m.push({timestamp:e.timestamp,duration:e.duration??Math.round(1e6/n),type:e.type,data:r}),!h&&t?.decoderConfig&&(h=t.decoderConfig)}catch(e){_=e}},error(e){_=e}}),o?.addEventListener(`abort`,b,{once:!0}),o?.aborted||(l?.({phase:`encoding`,cancellable:!0}),o?.aborted))throw E9();let e=new Uint8ClampedArray(r*i*4),t=1e6/n,x=Math.max(1,Math.round(n*2));v.configure(p);for(let n=0;n<f.frameCount;n+=1){if(o?.aborted)throw E9();let l=f.startFrame+n;y=`render_failed`;let u=a(l,s);if(!(u instanceof Uint8Array)||u.byteLength!==e.byteLength)throw Error(`frame ${l} returned ${u?.byteLength??0} RGBA bytes; expected ${e.byteLength}`);let p=await T9(i_e(u),o);if(g.push(p),a_e(u,e,r,i),y=`encode_failed`,o?.aborted)throw E9();let m=new d(e,{format:`RGBA`,codedWidth:r,codedHeight:i,timestamp:Math.round(n*t),duration:Math.round(t)});try{v.encode(m,{keyFrame:n%x===0})}finally{m.close()}if(_)throw _;v.encodeQueueSize>4&&await T9(v.flush(),o),c?.({frame:l,index:n,frameCount:f.frameCount,hash:p})}if(o?.aborted||(l?.({phase:`finalizing`,stage:`flush`,cancellable:!0}),o?.aborted)||(await T9(v.flush(),o),o?.aborted))throw E9();if(_)throw _;if(v.close(),m.length!==f.frameCount)throw Error(`WebCodecs emitted ${m.length} frames for ${f.frameCount} inputs`);l?.({phase:`finalizing`,stage:`mux`,cancellable:!1});let S=await t_e({chunks:m,codec:p.codec,decoderConfig:h??{codec:p.codec,codedWidth:r,codedHeight:i},signal:o});if(o?.aborted)throw E9();return{...f,fps:n,width:r,height:i,codec:p.codec,mimeType:S.type,encodedFrameCount:m.length,hashes:g,blob:S}}catch(e){throw w9(e,y)}finally{o?.removeEventListener(`abort`,b),b()}}var D9=e=>Number.isFinite(e)?e:null;function O9({shot:e=null,stage:t=null,cast:n=[],fps:r=null,aspectKey:i=null,size:a=null,frame:o=null,shotIndex:s=null,lens:c=null}={}){let l=e?.camera??null;return{focalMm:D9(l?.focalMm)??D9(c?.focalMm),fovDeg:D9(l?.fovDeg)??D9(c?.fovDeg),aspect:typeof i==`string`&&i?i:null,size:{width:D9(a?.width),height:D9(a?.height)},cameraMove:{dolly:!!l?.dollyTiming,crane:!!l?.craneHeight,rail:!!l?.railFollow&&l.railFollow.mode!==`off`},keyLight:t?.keyLight??null,cast:(Array.isArray(n)?n:[]).map(e=>({name:e?.name??e?.subject??null,model:e?.model??null})),frameRange:{start:D9(e?.startFrame),end:D9(e?.endFrame)},fps:D9(r),shotIndex:Number.isInteger(s)&&s>=0?s:null,shotTitle:typeof e?.name==`string`&&e.name?e.name:null,targetModel:e?.targetModel??null,frame:D9(o)}}var c_e=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function l_e(e){let t=4294967295;for(let n=0;n<e.length;n++)t=c_e[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}var k9=new TextEncoder,A9=0,j9=23585,M9=2048,N9=0,P9=20;function F9(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function I9(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function L9(e){if(!Array.isArray(e))throw TypeError(`buildZip expects an array of { name, data } entries`);let t=e.map(e=>{let t=k9.encode(e.name),n=typeof e.data==`string`?k9.encode(e.data):e.data;if(!(n instanceof Uint8Array))throw TypeError(`entry "${e.name}" data must be a Uint8Array or string`);return{nameBytes:t,data:n,crc:l_e(n)}}),n=t.reduce((e,t)=>e+30+t.nameBytes.length+t.data.length,0),r=t.reduce((e,t)=>e+46+t.nameBytes.length,0),i=new Uint8Array(n+r+22),a=0,o=[];for(let{nameBytes:e,data:n,crc:r}of t)o.push(a),I9(i,a,67324752),F9(i,a+4,P9),F9(i,a+6,M9),F9(i,a+8,N9),F9(i,a+10,A9),F9(i,a+12,j9),I9(i,a+14,r),I9(i,a+18,n.length),I9(i,a+22,n.length),F9(i,a+26,e.length),F9(i,a+28,0),i.set(e,a+30),a+=30+e.length,i.set(n,a),a+=n.length;let s=a;for(let e=0;e<t.length;e++){let{nameBytes:n,data:r,crc:s}=t[e];I9(i,a,33639248),F9(i,a+4,P9),F9(i,a+6,P9),F9(i,a+8,M9),F9(i,a+10,N9),F9(i,a+12,A9),F9(i,a+14,j9),I9(i,a+16,s),I9(i,a+20,r.length),I9(i,a+24,r.length),F9(i,a+28,n.length),F9(i,a+30,0),F9(i,a+32,0),F9(i,a+34,0),F9(i,a+36,0),I9(i,a+38,0),I9(i,a+42,o[e]),i.set(n,a+46),a+=46+n.length}let c=a-s;return I9(i,a,101010256),F9(i,a+4,0),F9(i,a+6,0),F9(i,a+8,t.length),F9(i,a+10,t.length),I9(i,a+12,c),I9(i,a+16,s),F9(i,a+20,0),i}function R9(e){return String(e??``).toLowerCase().normalize(`NFKD`).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`shot`}function u_e(e){return`cozyclay-shot-${e.index}-${R9(e.title)}.zip`}function d_e({shot:e,fps:t,hasLast:n,hasClip:r,ext:i,hasStylized:a}){let o=[`CozyClay keyframe pack - shot ${e.index}: ${e.title}`,`Frame range ${e.startFrame}-${e.endFrame} at ${t} fps.`,``,`This pack is a multi-reference bundle for Seedance-style tools.`,`Each file plays a distinct reference role:`,``,`- first.png: identity reference. The first frame defines what the`,` subject and scene must look like when the shot begins.`];return n?o.push(`- last.png: motion endpoint reference. The final frame pins where`,` the motion should land, constraining the generated trajectory.`):o.push(`- last.png: not included. Without an endpoint the tool is free to`,` choose how the motion resolves.`),r?o.push(`- clip.${i}: motion reference. The source clip carries the movement`,` the generated video should follow.`):o.push(`- clip.${i}: not included. Without a motion clip the tool must`,` invent the movement from the frames and prompt alone.`),o.push(`- camera.json: camera reference. The recorded camera move, fps, and`,` frame range to reproduce the framing over time.`,`- prompt.txt: the text prompt describing the intended action.`),a&&o.push(`- stylized.png: the stylized picture of this panel; first.png is its greybox.`),o.push(``,`Not in this pack: the shot-wide depth video (blocking-depth.mp4) is a`,`separate export - use Depth (mp4) in the export menu.`),o.join(`
|
|
5120
|
+
}`;function pfe(){let e=new Uint8Array(65536),t=(e,t,n)=>{let r=Math.sin(e*127.1+t*311.7+n*74.7)*43758.5453;return r-Math.floor(r)},n=(e,n,r)=>{let i=Math.floor(e),a=Math.floor(n),o=e-i,s=n-a,c=o*o*(3-2*o),l=s*s*(3-2*s),u=t(i,a,r)+(t(i+1,a,r)-t(i,a,r))*c;return u+(t(i,a+1,r)+(t(i+1,a+1,r)-t(i,a+1,r))*c-u)*l};for(let t=0;t<4;t+=1)for(let r=0;r<64;r+=1)for(let i=0;i<64;i+=1){let a=(i+.5)/64*2-1,o=(r+.5)/64*2-1,s=Math.hypot(a,o),c=Math.exp(-s*s*4.2)*(1-Math.min(1,Math.max(0,(s-.82)/.18)));if(t>0){let e=.55*n(a*3+5,o*3,t)+.3*n(a*6,o*6+3,t)+.15*n(a*12+1,o*12,t);c*=Math.min(1,Math.max(0,1.6*e-.25))}let l=(((t>>1)*64+r)*128+(t&1)*64+i)*4;e[l]=e[l+1]=e[l+2]=e[l+3]=Math.round(255*Math.min(1,c))}let r=new mp(e,128,128,ac);return r.minFilter=tl,r.magFilter=cu,r.generateMipmaps=!0,r.needsUpdate=!0,r}function d8(e,t,n={}){return new Hd({uniforms:{...qc.merge([Rm.lights,Rm.fog]),globalOpacity:{value:1},...n},vertexShader:e,fragmentShader:t,lights:!0,fog:!0,transparent:!0,depthWrite:!1,side:2,blending:5,blendEquation:100,blendSrc:201,blendDst:205,blendSrcAlpha:201,blendDstAlpha:205})}function f8(e,t,n){let r=new Ef(1,1),i={};for(let[e,a]of Object.entries(n))i[e]=new _d(new Float32Array(t*a),a).setUsage(Kl),r.setAttribute(e,i[e]);let a=new jd(r,e,t);return a.instanceMatrix.array.fill(0),a.count=0,a.frustumCulled=!1,a.renderOrder=5,a.raycast=()=>{},a.userData.noInk=!0,{mesh:a,attributes:i}}var p8=(e,t)=>{for(let n of Object.values(e))n.clearUpdateRanges(),n.addUpdateRange(0,t*n.itemSize),n.needsUpdate=!0};function mfe(){let e=pfe(),t=f8(d8(lfe,ufe,{map:{value:e}}),j$,{iPos:3,iParams:4,iColor:4,iStreak:4}),n=f8(d8(dfe,ffe),512,{rA0:3,rB0:3,rA1:3,rB1:3,rAlpha:2,rColor:4}),r=t.attributes,i=n.attributes;return{particles:t.mesh,ribbons:n.mesh,update(e,a,o=1){let s=0,c=0;Z$(e.records,e,a,{particle(e){s>=2e3||(r.iPos.array.set([e.x,e.y,e.z],s*3),r.iParams.array.set([e.size,e.angle,e.variant,+!e.additive],s*4),r.iColor.array.set([e.r,e.g,e.b,e.alpha],s*4),r.iStreak.array.set([e.sx,e.sy,e.sz,+!!e.additive],s*4),s+=1)},segment(e,t){c>=512||(i.rA0.array.set(e.a0,c*3),i.rB0.array.set(e.b0,c*3),i.rA1.array.set(e.a1,c*3),i.rB1.array.set(e.b1,c*3),i.rAlpha.array.set([e.alpha0,e.alpha1],c*2),i.rColor.array.set([...t.rgb,+!!t.effect.additive],c*4),c+=1)}}),t.mesh.count=s,n.mesh.count=c,p8(r,s),p8(i,c);for(let e of[t.mesh,n.mesh])e.material.uniforms.globalOpacity.value=o},dispose(){e.dispose();for(let e of[t.mesh,n.mesh])e.geometry.dispose(),e.material.dispose(),e.dispose?.()}}}var m8=Symbol(`effects`),hfe=`#7fd4f0`,h8=e=>{e&&e.layers.set(5)};function gfe({object:e}){let t=e.effect?.preset===`trail`,n=t?Math.max(.05,(e.effect?.width??.5)/2):.06,r=(0,Z.useMemo)(()=>{let e=.05,r=[[e,0,0],[0,e,0],[0,e,0],[-.05,0,0],[-.05,0,0],[0,-.05,0],[0,-.05,0],[e,0,0],[0,0,e],[0,e,0],[0,e,0],[0,0,-.05],[0,0,-.05],[0,-.05,0],[0,-.05,0],[0,0,e]],i=t?[[0,-n,0],[0,n,0],[-.03,-n,0],[.03,-n,0],[-.03,n,0],[.03,n,0]]:[[0,e,0],[0,.16,0],[0,.16,0],[.025,.12,0],[0,.16,0],[-.025,.12,0]],a=new Ol;return a.setAttribute(`position`,new uu([...r,...i].flat(),3)),a},[t,n]);return(0,Z.useEffect)(()=>()=>r.dispose(),[r]),(0,Q.jsxs)(`group`,{userData:{effectMarker:!0},children:[(0,Q.jsx)(`lineSegments`,{ref:h8,geometry:r,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{color:hfe,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),(0,Q.jsxs)(`mesh`,{ref:h8,visible:!1,userData:{emptyPick:!0},children:[(0,Q.jsx)(`sphereGeometry`,{args:[.08,12,8]}),(0,Q.jsx)(`meshBasicMaterial`,{})]})]})}var _fe=e=>(t,n)=>{let r=e?.current?.get(t);return r?(r.place(),r.world(n)):null};function vfe({objects:e,frameRef:t=null,take:n=null,registryRef:r=null,fadeOpacity:i=null}){let a=(0,Z.useMemo)(()=>e1(e),[e]),o=a.records.length>0,s=(0,Z.useMemo)(()=>o?mfe():null,[o]);(0,Z.useEffect)(()=>()=>s?.dispose(),[s]);let c=(0,Z.useMemo)(()=>_fe(r),[r]),l=(0,Z.useMemo)(()=>({...a,take:n??{},live:c}),[a,n,c]),u=(0,Z.useRef)(null),d=()=>{if(!s)return;let e=t?.current??0,n=i??1,r=[e,l,n];!l.records.some(e=>e.attach)&&u.current?.every((e,t)=>e===r[t])||(u.current=r,s.update(l,e,n))};return ty(d),(0,Z.useEffect)(()=>($$(()=>l),()=>$$(null)),[l]),(0,Z.useEffect)(()=>{let e=r?.current;if(!(!e||!s))return e.set(m8,{place:d,world:()=>null}),()=>{e.delete(m8)}}),s?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`primitive`,{object:s.particles}),(0,Q.jsx)(`primitive`,{object:s.ribbons})]}):null}var yfe=.2,g8=`cozyclay.poseObjectOpacity`;function bfe(e=globalThis.localStorage){let t=Number(e?.getItem?.(g8));return e?.getItem?.(`cozyclay.poseObjectOpacity`)==null||!Number.isFinite(t)?yfe:Math.min(1,Math.max(0,t))}function xfe(e,t=globalThis.localStorage){try{t?.setItem?.(g8,String(e))}catch{return}}var _8=new WeakMap,v8=()=>{};function Sfe(e){return Array.isArray(e.material)?e.material:e.material?[e.material]:[]}var y8=!1;function b8(e){y8=e}function Cfe(e,t){b8(!0),e?.();try{return t()}finally{b8(!1),e?.()}}function wfe(e,t,n=1){let r=y8||t==null||t>=1?1:t,i=r*n,a=i<1,o=r<1;e.traverse(e=>{if(e.isMesh){for(let t of Sfe(e))if(a){_8.has(t)||_8.set(t,{transparent:t.transparent,opacity:t.opacity,depthWrite:t.depthWrite});let e=_8.get(t).opacity*i;(t.opacity!==e||!t.transparent||t.depthWrite)&&(t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.needsUpdate=!0)}else _8.has(t)&&(Object.assign(t,_8.get(t)),_8.delete(t),t.needsUpdate=!0);o&&e.raycast!==v8?(e.userData.poseFadeRaycast=e.raycast,e.raycast=v8):!o&&e.raycast===v8&&(e.raycast=e.userData.poseFadeRaycast,delete e.userData.poseFadeRaycast)}})}var Tfe=.2,Efe=.02,Dfe=()=>{},x8=new WeakMap;function Ofe(e){return x8.has(e)}var S8=null;function kfe(){if(S8)return S8;let e=new Uint8Array(16384);for(let t=0;t<64;t+=1)for(let n=0;n<64;n+=1){let r=Math.hypot(n+.5-64/2,t+.5-64/2)/(64/2),i=r>=1?0:(1-r)**1.6,a=Math.min(1,.7*Math.exp(-((r/.25)**2))+.5*i);e.set([255,255,255,Math.round(a*255)],(t*64+n)*4)}return S8=new mp(e,64,64),S8.magFilter=cu,S8.minFilter=cu,S8.needsUpdate=!0,S8}function Afe(){let e=new om({map:kfe(),blending:2,transparent:!0,depthWrite:!1,fog:!1}),t=new Gp(e);return t.userData.glowHalo=!0,t.userData.beautyOnly=!0,t.raycast=Dfe,t.castShadow=!1,t.receiveShadow=!1,t.renderOrder=2,t}function jfe(e,t,n){e.traverse(e=>{if(!(!e.isMesh||!e.layers.isEnabled(0))){t(e);for(let t of Array.isArray(e.material)?e.material:[e.material])t?.emissive?.isColor&&n(t)}})}function Mfe(e,t){for(let[e,n]of t.bases)e.emissive.copy(n.emissive),e.emissiveIntensity=n.intensity;for(let e of t.shadowless)e.castShadow=!0;t.halo.removeFromParent(),t.halo.material.dispose(),x8.delete(e)}function Nfe(e,t){let n=(e.footprint?.width??0)*Math.abs(t.x),r=(e.height??0)*Math.abs(t.y),i=(e.footprint?.depth??0)*Math.abs(t.z),a=Math.max(n,r,i)/2;return{centreY:(e.height??0)/2,radius:a>0?a:Efe}}function Pfe(e,t,n){let r=t.glow,i=x8.get(e);if(!r){i&&Mfe(e,i);return}i||(i={halo:Afe(),bases:new Map,shadowless:new Set},x8.set(e,i)),i.halo.parent!==e&&e.add(i.halo);let a=r.intensity*n;jfe(e,e=>{e.castShadow&&(e.castShadow=!1,i.shadowless.add(e))},e=>{i.bases.has(e)||i.bases.set(e,{emissive:e.emissive.clone(),intensity:e.emissiveIntensity}),e.emissive.set(r.color),e.emissiveIntensity=a});let{centreY:o,radius:s}=Nfe(t,e.scale),c=2*s*r.halo*n,l=i.halo;l.visible=c>0&&a>0,l.position.set(0,o,0),l.scale.set(c/(Math.abs(e.scale.x)||1),c/(Math.abs(e.scale.y)||1),1),l.material.color.set(r.color).multiplyScalar(Tfe*a)}var Ffe=Math.PI/180,C8=new X(0,-1,0),w8=new X,T8=new X,E8=new Vu,Ife=new X;function D8(e,t){for(let n of e.children)if(n.userData?.[t])return n;return null}function Lfe(e,t,n){let r=D8(e,`sceneLight`);if(!r)return;let{color:i,intensity:a,range:o,angle:s,softness:c,aim:l}=t.light;if(r.color.set(i),r.intensity=a*qt*n,r.distance=o,r.castShadow&&r.isPointLight){let e=o>0?o:40;r.shadow.camera.far!==e&&(r.shadow.camera.far=e,r.shadow.camera.updateProjectionMatrix())}if(!r.isSpotLight)return;r.angle=s*Ffe,r.penumbra=c,e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(T8,E8,Ife),l?w8.set(l.x-T8.x,l.y-T8.y,l.z-T8.z):w8.copy(C8).applyQuaternion(E8),w8.lengthSq()<1e-10&&w8.copy(C8).applyQuaternion(E8),w8.normalize(),r.target.position.copy(T8).add(w8),r.target.updateMatrixWorld();let u=D8(e,`lightMarker`)?.children.find(e=>e.userData?.lightCone);u&&u.quaternion.setFromUnitVectors(C8,w8.applyQuaternion(E8.invert()))}function Rfe(e,t,n,r){if(!t.light&&!t.glow&&!Ofe(e))return;let i=tZ(t.id,n,r)*(t.light?Vn(t.id,n,t.light.flicker,r?.fps):1);t.light&&Lfe(e,t,i),Pfe(e,t,i)}var zfe=Math.PI/180,O8=.07,Bfe=.7;function Vfe(e,t){let n=e===`spot`?new nf:new Rl;if(n.position.set(0,0,0),n.decay=2,n.castShadow=t,n.userData.sceneLight=!0,t){let t=e===`spot`?1024:512;n.shadow.mapSize.set(t,t),n.shadow.bias=-4e-4,n.shadow.normalBias=.02,n.shadow.camera.near=.03,n.shadow.camera.far=40,n.shadow.camera.updateProjectionMatrix()}return n}function k8(e,t,n,r,i=0,a=24){for(let o=0;o<a;o+=1)for(let s of[o,o+1]){let o=s/a*Math.PI*2,c=[0,i,0];c[n]+=Math.cos(o)*t,c[r]+=Math.sin(o)*t,e.push(...c)}return e}function A8(e){let t=new Ol;return t.setAttribute(`position`,new uu(e,3)),t}function Hfe(){let e=[];k8(e,O8,0,2),k8(e,O8,0,1),k8(e,O8,1,2);for(let t=0;t<8;t+=1){let n=t/8*Math.PI*2;e.push(Math.cos(n)*O8*1.3,0,Math.sin(n)*O8*1.3,Math.cos(n)*O8*2,0,Math.sin(n)*O8*2)}return A8(e)}function Ufe(e){let t=Bfe*Math.tan(e*zfe),n=k8([],t,0,2,-.7,32);for(let e=0;e<4;e+=1){let r=e/4*Math.PI*2;n.push(0,0,0,Math.cos(r)*t,-.7,Math.sin(r)*t)}return A8(n)}var j8=e=>{e&&e.layers.set(5)};function Wfe({type:e,angle:t,color:n}){let r=(0,Z.useMemo)(()=>Hfe(),[]),i=(0,Z.useMemo)(()=>e===`spot`?Ufe(t):null,[e,t]);return(0,Z.useEffect)(()=>()=>r.dispose(),[r]),(0,Z.useEffect)(()=>()=>i?.dispose(),[i]),(0,Q.jsxs)(`group`,{userData:{lightMarker:!0},children:[(0,Q.jsx)(`lineSegments`,{ref:j8,geometry:r,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{color:n,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),i&&(0,Q.jsx)(`group`,{userData:{lightCone:!0},children:(0,Q.jsx)(`lineSegments`,{ref:j8,geometry:i,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{color:n,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.55})})}),(0,Q.jsxs)(`mesh`,{ref:j8,visible:!1,userData:{emptyPick:!0},children:[(0,Q.jsx)(`sphereGeometry`,{args:[u*.45,12,8]}),(0,Q.jsx)(`meshBasicMaterial`,{})]})]})}function Gfe({object:e}){let{type:t,shadow:n,angle:r,color:i}=e.light,a=(0,Z.useMemo)(()=>Vfe(t,n),[t,n]);return(0,Z.useEffect)(()=>()=>a.dispose(),[a]),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`primitive`,{object:a}),(0,Q.jsx)(Wfe,{type:t,angle:r,color:i})]})}function Kfe(e){let t=ey(e=>e.invalidate);(0,Z.useEffect)(()=>{t()},[t,e.light,e.glow])}function qfe({kind:e,object:t,color:n,autoColor:r,depthRank:i=0}){let a=e===`plane`?2:0,o=Zde(t,e,a,i),s=!(o?.transmission>0),c=o?(0,Q.jsx)(`primitive`,{object:o,attach:`material`}):r?(0,Q.jsx)(`meshStandardMaterial`,{...j0(r),side:a,...s8(i)}):(0,Q.jsx)(`meshStandardMaterial`,{color:n,roughness:.82,side:a,...s8(i)});return e===`sphere`?(0,Q.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`sphereGeometry`,{args:[.5,28,18]}),c]}):e===`capsule`?(0,Q.jsxs)(`mesh`,{position:[0,.7,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`capsuleGeometry`,{args:[.35,.7,6,18]}),c]}):e===`cylinder`?(0,Q.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`cylinderGeometry`,{args:[.5,.5,1,26]}),c]}):e===`cone`?(0,Q.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`coneGeometry`,{args:[.5,1,26]}),c]}):e===`plane`?(0,Q.jsxs)(`mesh`,{position:[0,.004,0],rotation:[-Math.PI/2,0,0],receiveShadow:!0,children:[(0,Q.jsx)(`planeGeometry`,{args:[2,2]}),c]}):(0,Q.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,Q.jsx)(`boxGeometry`,{args:[1,1,1]}),c]})}function Jfe(e){let[t,n]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{if(n(null),e)return tr(e,n)},[e]),t}var Yfe=`#c2c6c8`;function Xfe({object:e}){let t=Jfe(e.assetId),n=e.footprint?.width??1,r=e.height??1;return(0,Q.jsxs)(`mesh`,{position:[0,r/2,0],castShadow:!0,receiveShadow:!0,userData:{cutoutTexture:t??null},children:[(0,Q.jsx)(`planeGeometry`,{args:[n,r]}),(0,Q.jsx)(`meshStandardMaterial`,{map:t??null,color:t?e.color:Yfe,side:2,alphaTest:t?.15:0,alphaToCoverage:!!t,roughness:.92,metalness:0})]})}function Zfe({object:e,depthRank:t=0}){let{recipe:n,autoColor:r}=e,i=(0,Z.useMemo)(()=>{let e=Jde(n,r?{materialFor:()=>new Kf(j0(r))}:{});return e.traverse(e=>e.material&&Object.assign(e.material,s8(t))),e},[n,r,t]);return(0,Z.useEffect)(()=>()=>Yde(i),[i]),(0,Q.jsx)(`primitive`,{object:i})}var Qfe=new Set([`cube`,`sphere`,`capsule`,`cylinder`,`cone`,`plane`]),$fe=[{to:[1,0,0],color:`#e5594f`},{to:[0,1,0],color:`#5fb95f`},{to:[0,0,1],color:`#4f86e5`}];function epe(){let e=u/2,t=(0,Z.useMemo)(()=>{let t=[],n=[],r=new Lu;for(let i of $fe)t.push(-i.to[0]*e,-i.to[1]*e,-i.to[2]*e,i.to[0]*e,i.to[1]*e,i.to[2]*e),r.set(i.color),n.push(r.r,r.g,r.b,r.r,r.g,r.b);let i=new Ol;return i.setAttribute(`position`,new uu(t,3)),i.setAttribute(`color`,new uu(n,3)),i},[e]);(0,Z.useEffect)(()=>()=>t.dispose(),[t]);let n=e=>e?.layers.set(5);return(0,Q.jsxs)(`group`,{userData:{emptyMarker:!0},children:[(0,Q.jsx)(`lineSegments`,{ref:n,geometry:t,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{vertexColors:!0,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),(0,Q.jsxs)(`mesh`,{ref:n,visible:!1,userData:{emptyPick:!0},children:[(0,Q.jsx)(`sphereGeometry`,{args:[e*1.25,12,8]}),(0,Q.jsx)(`meshBasicMaterial`,{})]})]})}function tpe({object:e,depthRank:t=0}){let{renderer:n,color:r,autoColor:i}=e;return n===`empty`?(0,Q.jsx)(epe,{}):n===`light`?(0,Q.jsx)(Gfe,{object:e}):n===`effect`?(0,Q.jsx)(gfe,{object:e}):n===`cutout`?(0,Q.jsx)(Xfe,{object:e}):n===`mesh`?(0,Q.jsx)(cfe,{object:e}):n===`sculpt`?(0,Q.jsx)(Zfe,{object:e,depthRank:t}):n===`text`?(0,Q.jsx)(Uce,{object:e}):Qfe.has(n)?(0,Q.jsx)(qfe,{kind:n,object:e,color:r,autoColor:i,depthRank:t}):null}function npe({object:e}){let t=e.renderer===`empty`||e.renderer===`light`||e.renderer===`effect`,n=t?u:Math.max(e.height??1,.08),r=t?u:e.footprint?.width??1,i=t?u:e.footprint?.depth??1,a=(0,Z.useMemo)(()=>new fc(new Of(r*1.04,n*1.04,i*1.04)),[r,n,i]);return(0,Z.useEffect)(()=>()=>a.dispose(),[a]),(0,Q.jsx)(`lineSegments`,{ref:e=>{e&&e.layers.set(5)},geometry:a,position:[0,t?0:n/2,0],renderOrder:998,children:(0,Q.jsx)(`lineBasicMaterial`,{color:`#e7b557`,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1})})}var M8=Math.PI/180,N8=new X,P8=new Vu,F8=new X,I8=new Nl,L8=new Y,R8=new Y,rpe=new Y;function ipe({object:e,selected:t,frameRef:n=null,take:r=null,attachFrameRef:i=null,registryRef:a=null,travelLookupRef:o=null,fadeOpacity:s=null,depthRank:c=0}){let l=(0,Z.useRef)(null),u=e.attach??null,d=()=>{let t=l.current;if(!t)return;let a=n?.current??0,c=n&&!u&&o?.current?cZ(o.current,e.id,a,r??{},R8):null;if((t.visible=eZ(e.id,a,r,o?.current))&&c)c.decompose(t.position,t.quaternion,t.scale);else if(u||e.path){if(N8.set(e.x,e.y??0,e.z),I8.set((e.rotX??0)*M8,e.rot*M8,(e.rotZ??0)*M8,`XYZ`),F8.set(e.scaleX??1,e.scaleY??1,e.scaleZ??1),n&&e.path){let t=ze(e,a,r??{});if(t){N8.set(t.x,t.y,t.z);let n=XX(e,t);I8.set(n.rotX*M8,n.rot*M8,n.rotZ*M8,`YXZ`)}}let o=u?i?.current?.(u.characterId,u.bone??null,rpe)??null:null;o?(L8.compose(N8,P8.setFromEuler(I8),F8),R8.multiplyMatrices(o,L8).decompose(N8,P8,F8),t.position.copy(N8),t.quaternion.copy(P8),t.scale.copy(F8)):(t.position.copy(N8),t.rotation.copy(I8),t.scale.copy(F8))}typeof window<`u`&&((window.__cclayPropWorld??={})[e.id]={x:t.position.x,y:t.position.y,z:t.position.z,quat:{x:t.quaternion.x,y:t.quaternion.y,z:t.quaternion.z,w:t.quaternion.w},frame:a}),wfe(t,s,e.opacity??1),Rfe(t,e,a,r)};ty(d),Kfe(e);let f=(0,Z.useRef)(d);f.current=d;let p=(0,Z.useRef)(null);return p.current||={place:()=>f.current(),world:e=>{let t=l.current;return t?(t.updateWorldMatrix(!0,!1),e?e.copy(t.matrixWorld):t.matrixWorld):null}},(0,Z.useEffect)(()=>{if(!a)return;let t=a.current;return t.set(e.id,p.current),()=>{t.delete(e.id)}},[a,e.id]),(0,Q.jsxs)(`group`,{ref:l,position:[e.x,e.y??0,e.z],rotation:[(e.rotX??0)*M8,e.rot*M8,(e.rotZ??0)*M8],scale:[e.scaleX??1,e.scaleY??1,e.scaleZ??1],userData:{sceneObjectId:e.id},children:[(0,Q.jsx)(tpe,{object:e,depthRank:c}),t&&(0,Q.jsx)(npe,{object:e})]})}function ape({objects:e=[],authoredObjects:t=null,selectedId:n=null,frameRef:r=null,take:i=null,attachFrameRef:a=null,syncRef:o=null,worldRef:s=null,fadeOpacity:c=null}){let l=(0,Z.useRef)(null),u=(0,Z.useRef)(null);u.current=(0,Z.useMemo)(()=>t?new Map(t.map(e=>[e.id,e])):null,[t]);let d=(0,Z.useMemo)(()=>cA(t??e),[t,e]);return l.current||=new Map,o&&(o.current=()=>{for(let e of l.current.values())e.place()}),s&&(s.current=(e,t)=>l.current.get(e)?.world(t)??null),(0,Q.jsxs)(`group`,{children:[rr(e).map(e=>(0,Q.jsx)(ipe,{object:e,selected:e.id===n,frameRef:r,take:i,attachFrameRef:a,registryRef:l,travelLookupRef:u,fadeOpacity:c,depthRank:d.get(e.id)??0},e.id)),(0,Q.jsx)(vfe,{objects:t??e,frameRef:r,take:i,registryRef:l,fadeOpacity:c})]})}var ope=new Y;function spe({objectId:e=null,objectsRef:t,frameRef:n=null,take:r=null,registryRef:i=null,children:a}){let o=(0,Z.useRef)(null),s=()=>{let i=o.current;if(!i)return;let a=e&&t?.current?uZ(t.current,e,n?.current??0,r??{},ope):null;a?a.decompose(i.position,i.quaternion,i.scale):(i.position.set(0,0,0),i.quaternion.identity(),i.scale.set(1,1,1))};ty(s,-1);let c=(0,Z.useRef)(s);return c.current=s,(0,Z.useEffect)(()=>{if(!i)return;let e=i.current,t=()=>c.current();return e.add(t),()=>{e.delete(t)}},[i]),(0,Q.jsx)(`group`,{ref:o,children:a})}var cpe=[139,92,246],z8=.62,lpe=`#141819`,upe=512,B8=1,V8=(e,t,n)=>Math.min(n,Math.max(t,e));function dpe(e,{onChange:t=()=>{},createBitmap:n=globalThis.createImageBitmap,makeCanvas:r=(e,t)=>new OffscreenCanvas(e,t)}={}){let i=e.getContext(`2d`,{willReadFrequently:!0}),a={full:null,preview:null,paint:null,tolerance:.18,brush:18,mode:`paint`,painting:!1,panning:null,last:null,seeds:[],before:null,view:{zoom:1,x:0,y:0},buffer:null,history:[],at:-1};function o(){if(a.paint){for(a.history.length=a.at+1,a.history.push(Uint8Array.from(a.paint));a.history.length>8;)a.history.shift();a.at=a.history.length-1}}function s(e){let t=a.at+e;return!a.paint||t<0||t>=a.history.length?!1:(a.at=t,a.paint.set(a.history[t]),p(),!0)}let c=()=>a.full&&a.preview?a.full.width/a.preview.width:1;function l(){if(!a.paint)return t({painted:0,coverage:0,zoom:1,canUndo:!1,canRedo:!1});let e=0;for(let t=0;t<a.paint.length;t++)e+=a.paint[t];t({painted:e,coverage:e/a.paint.length,zoom:a.view.zoom,canUndo:a.at>0,canRedo:a.at>=0&&a.at<a.history.length-1})}function u(){let t=e.getBoundingClientRect(),n=Math.min(3,Math.max(1,globalThis.devicePixelRatio||1));return{width:Math.max(1,Math.round((t.width||e.width||1)*n)),height:Math.max(1,Math.round((t.height||e.height||1)*n)),left:t.left,top:t.top,dpr:n}}function d(e){return a.preview?Math.min(e.width/a.preview.width,e.height/a.preview.height)*V8(a.view.zoom,B8,16):1}function f(){let e=u(),t=d(e),n=a.preview?a.preview.width*t:0,r=a.preview?a.preview.height*t:0,i=e.width/2/t,o=e.height/2/t,s={x:a.view.x,y:a.view.y};return s.x=n>=e.width?V8(s.x,i,a.preview.width-i):a.preview.width/2,s.y=r>=e.height?V8(s.y,o,a.preview.height-o):a.preview.height/2,{stage:e,scale:t,center:s,width:n,height:r,left:e.width/2-s.x*t,top:e.height/2-s.y*t}}function p(){if(!a.preview)return;let{width:t,height:n,data:o}=a.preview,s=c(),d=a.full.width,p=new Uint8ClampedArray(o.length),[m,h,g]=cpe;for(let e=0;e<n;e++){let n=Math.min(a.full.height-1,Math.floor(e*s));for(let r=0;r<t;r++){let i=e*t+r<<2,c=o[i+3]/255,l=o[i]*c+26*(1-c),u=o[i+1]*c+30*(1-c),f=o[i+2]*c+32*(1-c);a.paint[n*d+Math.min(d-1,Math.floor(r*s))]&&(l=l*.38+m*z8,u=u*.38+h*z8,f=f*.38+g*z8),p[i]=l,p[i+1]=u,p[i+2]=f,p[i+3]=255}}(!a.buffer||a.buffer.width!==t||a.buffer.height!==n)&&(a.buffer=r(t,n),a.buffer.width=t,a.buffer.height=n),a.buffer.getContext(`2d`).putImageData(new ImageData(p,t,n),0,0);let _=u();e.width=_.width,e.height=_.height;let v=f();a.view.x=v.center.x,a.view.y=v.center.y,i.fillStyle=lpe,i.fillRect(0,0,_.width,_.height),i.imageSmoothingEnabled=a.view.zoom<2,i.drawImage(a.buffer,0,0,t,n,v.left,v.top,v.width,v.height),l()}function m(e){let t=f(),n=t.stage.dpr,r=((e.clientX-t.stage.left)*n-t.left)/t.scale,i=((e.clientY-t.stage.top)*n-t.top)/t.scale;return{x:r*c(),y:i*c()}}function h(e){let t=f(),n=t.stage.dpr,r=(e.clientX-t.stage.left)*n-t.left,i=(e.clientY-t.stage.top)*n-t.top;return r>=0&&i>=0&&r<=t.width&&i<=t.height}function g(){let e=f();return Math.max(1,a.brush*e.stage.dpr/2/e.scale*c())}function _(e,t){let n=a.mode===`erase`?0:1,r=g(),i=Math.max(1,Math.ceil(Math.hypot(t.x-e.x,t.y-e.y)/Math.max(1,r*.4))),o=0;for(let s=1;s<=i;s++){let c=e.x+(t.x-e.x)*s/i,l=e.y+(t.y-e.y)*s/i;o+=$re(a.paint,a.full,{x:c,y:l,radius:r,value:n}),a.seeds.push({x:c,y:l})}o&&p()}function v(){let e=a.seeds,t=a.before;if(a.seeds=[],a.before=null,!e.length||!a.full)return;let n=a.mode===`erase`,r=HN(a.full,{points:e,tolerance:a.tolerance,within:n?t:null}),i=+!n,s=0;for(let e=0;e<r.length;e++)!r[e]||a.paint[e]===i||(a.paint[e]=i,s+=1);s&&(o(),p())}let y=t=>{if(!(!a.preview||!h(t))){if(t.preventDefault(),e.setPointerCapture?.(t.pointerId),t.button===1||w){a.panning={x:t.clientX,y:t.clientY};return}a.painting=!0,a.before=Uint8Array.from(a.paint),a.last=m(t),_(a.last,a.last)}},b=e=>{if(a.panning){let t=f(),n=t.stage.dpr;a.view.x=t.center.x-(e.clientX-a.panning.x)*n/t.scale,a.view.y=t.center.y-(e.clientY-a.panning.y)*n/t.scale,a.panning={x:e.clientX,y:e.clientY},p();return}if(!a.painting)return;let t=m(e);_(a.last,t),a.last=t},x=t=>{if(a.panning){a.panning=null,e.hasPointerCapture?.(t.pointerId)&&e.releasePointerCapture(t.pointerId);return}a.painting&&(a.painting=!1,v(),e.hasPointerCapture?.(t.pointerId)&&e.releasePointerCapture(t.pointerId))};function S(e,t,n){if(!a.preview)return;let r=f(),i=r.stage.dpr,o=((e-r.stage.left)*i-r.left)/r.scale,s=((t-r.stage.top)*i-r.top)/r.scale;a.view.zoom=V8(a.view.zoom*n,B8,16);let c=f(),l=(e-c.stage.left)*c.stage.dpr-c.stage.width/2,u=(t-c.stage.top)*c.stage.dpr-c.stage.height/2;a.view.x=o-l/c.scale,a.view.y=s-u/c.scale,p()}let C=e=>{a.preview&&(e.preventDefault(),S(e.clientX,e.clientY,e.deltaY<0?1.15:1/1.15))},w=!1,T=e=>{e.key===` `&&(w=!0)},E=e=>{e.key===` `&&(w=!1)};return e.addEventListener(`pointerdown`,y),e.addEventListener(`pointermove`,b),e.addEventListener(`pointerup`,x),e.addEventListener(`pointercancel`,x),e.addEventListener(`pointerleave`,x),e.addEventListener(`wheel`,C,{passive:!1}),e.addEventListener(`keydown`,T),e.addEventListener(`keyup`,E),{async load(e){let t=await n(new Blob([e.bytes],{type:e.type}));try{let e=(e,n)=>{let i=r(e,n).getContext(`2d`,{willReadFrequently:!0});return i.drawImage(t,0,0,e,n),{data:i.getImageData(0,0,e,n).data,width:e,height:n}};a.full=e(t.width,t.height);let n=Math.min(1,upe/Math.max(t.width,t.height));a.preview=n===1?{data:Uint8ClampedArray.from(a.full.data),width:a.full.width,height:a.full.height}:e(Math.max(1,Math.round(t.width*n)),Math.max(1,Math.round(t.height*n))),a.paint=new Uint8Array(a.full.width*a.full.height),a.view={zoom:1,x:a.preview.width/2,y:a.preview.height/2},a.buffer=null,a.history=[],a.at=-1,o(),p()}finally{t?.close?.()}},setMask(e,t,n){return!a.paint||!e||t!==a.full.width||n!==a.full.height?!1:(a.paint.set(e),o(),p(),!0)},autoDetect(e=a.tolerance){if(!a.full)return 0;a.tolerance=V8(Number(e)||0,.01,.9);let t=HN(a.full,{tolerance:a.tolerance}),n=0;for(let e=0;e<t.length;e++)!t[e]||a.paint[e]||(a.paint[e]=1,n+=1);return n&&o(),p(),n},zoomBy(e){let t=u();S(t.left+t.width/2/t.dpr,t.top+t.height/2/t.dpr,e)},fit(){a.view={zoom:1,x:(a.preview?.width??0)/2,y:(a.preview?.height??0)/2},p()},zoom:()=>a.view.zoom,setTolerance(e){a.tolerance=V8(Number(e)||0,.01,.9)},setBrush(e){a.brush=V8(Number(e)||1,2,200)},setMode(e){a.mode=e===`erase`?`erase`:`paint`},mode:()=>a.mode,tolerance:()=>a.tolerance,clear(){a.paint&&(a.paint.fill(0),o(),p())},undo:()=>s(-1),redo:()=>s(1),canUndo:()=>a.at>0,canRedo:()=>a.at>=0&&a.at<a.history.length-1,hasPaint:()=>!!a.paint?.some(e=>e===1),options(){return a.paint&&this.hasPaint()?{mask:a.paint,maskWidth:a.full.width,maskHeight:a.full.height}:null},dispose(){e.removeEventListener(`pointerdown`,y),e.removeEventListener(`pointermove`,b),e.removeEventListener(`pointerup`,x),e.removeEventListener(`pointercancel`,x),e.removeEventListener(`pointerleave`,x),e.removeEventListener(`wheel`,C),e.removeEventListener(`keydown`,T),e.removeEventListener(`keyup`,E)}}}var fpe={name:`cozyclay`,version:`3.1.6`,description:`Open source previs software in the browser: block a scene, pose characters, author camera moves and cuts, then take the same shots to an AI video model.`,scripts:{dev:`node tools/dev-full.mjs --host 127.0.0.1 --port 5180`,"dev:ui":`vite`,build:`vite build && node tools/sitemap.mjs`,lint:`node tools/check-knip.mjs && node tools/check-loc.mjs && node tools/check-eslint.mjs`,"lint:update":`node tools/check-knip.mjs --update && node tools/check-loc.mjs --update && node tools/check-eslint.mjs --update`,test:`npm run build && node tools/run-tests.mjs`,"test:manifest":`node tools/run-tests.mjs --list`,"test:analytics":`node test/verify-analytics.mjs`,"test:lifecycle":`npm run build && node test/process/verify-lifecycle.mjs`,"test:mcp-package":`node test/process/verify-mcp-package-isolation.mjs`,"test:hierarchy":`node test/verify-hierarchy.mjs`,"test:history":`node test/verify-history.mjs`,"test:scene-objects":`node test/verify-scene-objects.mjs`,"test:scene-assets":`node test/verify-scene-assets.mjs`,"test:scene-mesh":`node test/verify-scene-mesh.mjs`,"test:mesh-browser":`node tools/qa-browser.mjs -- node test/verify-mesh-browser.mjs`,"test:asset-shelf":`node test/verify-asset-shelf.mjs`,"test:matte":`node test/verify-matte.mjs`,"test:matte-editor":`node test/verify-matte-editor.mjs`,"test:scenes":`node test/verify-scenes.mjs`,"test:camera-move":`node test/verify-camera-move.mjs`,"test:cuts":`node test/verify-cuts.mjs`,"test:project-menu":`node tools/qa-browser.mjs -- node test/verify-project-menu-browser.mjs`,"test:first-success-guide":`QA_STARTUP_CHOOSER=1 node tools/qa-browser.mjs -- node test/verify-first-success-guide-browser.mjs`,"test:objects":`node tools/qa-browser.mjs -- node test/verify-object-gizmo.mjs`,"test:theme":`node test/verify-theme.mjs`,"test:appearance":`node test/verify-appearance.mjs`,"test:auto-color":`node test/verify-auto-color.mjs`,"test:shot-guides":`node test/verify-shot-guides.mjs`,"test:layout":`node test/verify-layout.mjs`,"test:timeline-camera":`node test/verify-timeline-camera.mjs`,"test:timeline-shots":`node test/verify-timeline-shots.mjs`,preview:`vite preview`,"test:ardy":`node tools/run-tests.mjs --scope ardy`,"test:ik-browser":`node tools/qa-browser.mjs -- node test/verify-ik-browser.mjs`,"demo:api":`npm --prefix workers/api run dev`,"demo:api:install":`npm --prefix workers/api ci`,"qa:browser":`node tools/qa-browser.mjs --`,"test:shot-authoring":`node test/verify-shot-authoring.mjs`,"test:camera-follow":`node test/verify-camera-follow.mjs`,"test:sample-at":`node test/verify-sample-at.mjs`,"test:offscreen-export":`node test/verify-offscreen-export.mjs`,"test:offscreen-export-browser":`node tools/qa-browser.mjs -- node test/verify-offscreen-export-browser.mjs`,"test:otio":`node test/verify-otio.mjs`,"test:usd-camera":`node test/verify-usd-camera.mjs`,"test:camera-rail-browser":`node tools/qa-browser.mjs -- node test/verify-camera-rail-browser.mjs`,"test:blocking-depth":`node test/verify-blocking-depth.mjs`,"test:pwa":`node test/verify-pwa.mjs`,"test:update-check":`node test/verify-update-check.mjs`,"test:korean-ui":`node test/verify-korean-ui.mjs`,prepack:`npm run build && node tools/prepare-package.mjs`,postpack:`node tools/prepare-package.mjs --clean`,prepublishOnly:`npm run build && node tools/prepare-package.mjs --check-key && node tools/prepare-package.mjs && node tools/verify-package-tarball.mjs`,"metrics:snapshot":`node tools/metrics-snapshot.mjs`},license:`AGPL-3.0-or-later`,type:`module`,dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.3.306`,"@earendil-works/pi-agent-core":`1.4.0`,"@earendil-works/pi-ai":`1.4.0`,"@earendil-works/pi-codemode":`1.4.0`,zod:`^4.6.7`},devDependencies:{"@eslint/js":`^10.0.1`,"@react-three/drei":`^10.7.7`,"@react-three/fiber":`^9.7.0`,"@vitejs/plugin-react":`^6.0.5`,eslint:`^10.12.0`,"eslint-plugin-react-hooks":`^7.1.1`,globals:`^17.13.0`,knip:`^6.41.0`,mediabunny:`^1.55.2`,"posthog-js":`^1.418.12`,react:`^19.2.8`,"react-dom":`^19.2.8`,"react-hot-toast":`^2.6.0`,"react-icons":`^5.7.0`,reactflow:`^11.11.4`,three:`^0.185.1`,"three-bvh-csg":`^0.0.18`,"three-mesh-bvh":`^0.9.16`,vite:`^8.2.0`},bin:{cozyclay:`bin/cozyclay.mjs`,cclay:`bin/cozyclay.mjs`},files:[`bin`,`dist`,`!dist/media/*.mp4`,`src`,`tools`,`!tools/qa-*.mjs`,`mcp/server.mjs`,`mcp/tool-handlers.mjs`,`mcp/live-hub.mjs`,`mcp/mesh-file.mjs`,`mcp/image-file.mjs`,`mcp/project-camera.mjs`,`mcp/runtime`,`mcp/package.json`,`mcp/README.md`,`mcp/LIVE-PROTOCOL.md`,`README.md`,`INSTALL_FOR_AGENTS.md`,`CHANGELOG.md`,`LICENSE`,`LICENSES`,`LICENSING.md`,`THIRD_PARTY_NOTICES.md`],exports:{"./package.json":`./package.json`,"./src/*":`./src/*`,"./mcp/*":`./mcp/*`},peerDependencies:{three:`>=0.180`},peerDependenciesMeta:{three:{optional:!0}},engines:{node:`>=22.19.0`},keywords:[`3d`,`previs`,`animation`,`blocking`,`threejs`,`react-three-fiber`,`webgl`,`motion`,`ardy`,`storyboard`,`previz`],repository:{type:`git`,url:`git+https://github.com/NomaDamas/CozyClay.git`},homepage:`https://cozyclay.org/`,bugs:{url:`https://github.com/NomaDamas/CozyClay/issues`},publishConfig:{access:`public`}};function H8({id:e}){let t=`/thumbs/${e}-${Em()}.webp`,[n,r]=(0,Z.useState)(null);return n===t?null:(0,Q.jsx)(`img`,{className:`v2-start-art`,src:t,alt:``,"aria-hidden":`true`,draggable:`false`,decoding:`async`,onError:()=>r(t)})}function ppe(){return(0,Q.jsx)(`img`,{className:`v2-start-brand-mark`,src:`/icons/icon-192.png`,alt:``,"aria-hidden":`true`,draggable:`false`,width:`26`,height:`26`})}var mpe=fpe.version,U8=Object.freeze({id:`new-project`,thumbId:`blank-stage`,kind:`blank`,defaultName:`Untitled Project`,get name(){return J(`New project`,`새 프로젝트`)},get description(){return J(`Start from an empty stage.`,`빈 무대에서 시작합니다.`)}}),hpe=[{id:`storyboard`,label:()=>J(`Storyboard`,`스토리보드`),blurb:()=>J(`Describe scenes in words and direct one panel at a time. Output: image references.`,`말로 장면을 설명하면 한 장씩 패널을 연출합니다. 결과물: 이미지 레퍼런스.`)},{id:`animation`,label:()=>J(`Animation`,`애니메이션`),blurb:()=>J(`Block and shoot continuous motion. Output: clip references.`,`연속 동작을 블로킹하고 촬영합니다. 결과물: 클립 레퍼런스.`)}],W8=null;function G8(e){W8=e}function gpe(e){let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`,year:`numeric`}):J(`Recently`,`최근`)}function _pe(e){return{id:`sample-${e.id}`,starterId:e.id,name:e.name,description:e.blurb,kind:`sample`}}function vpe({open:e,initialName:t=`My Project`,onCancel:n,onSubmit:r}){let[i,a]=(0,Z.useState)(t);return(0,Z.useEffect)(()=>{if(e){if(W8!==null){let e=W8;W8=null,a(e),r(e);return}a(t)}},[e,t]),e?(0,Q.jsx)(`div`,{className:`v2-project-name-dialog-backdrop project-name-dialog-backdrop`,role:`presentation`,children:(0,Q.jsxs)(`form`,{className:`v2-project-name-dialog project-name-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`project-name-dialog-title`,onSubmit:e=>{e.preventDefault(),r(i.trim()||`My Project`)},children:[(0,Q.jsx)(`strong`,{id:`project-name-dialog-title`,children:J(`Project name`,`프로젝트 이름`)}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{children:J(`Name`,`이름`)}),(0,Q.jsx)(`input`,{autoFocus:!0,value:i,onChange:e=>a(e.target.value),"aria-label":J(`Project name`,`프로젝트 이름`)})]}),(0,Q.jsxs)(`div`,{className:`v2-project-name-dialog-actions project-name-dialog-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`v2-dialog-secondary btn ghost`,onClick:n,children:J(`Cancel`,`취소`)}),(0,Q.jsx)(`button`,{type:`submit`,className:`v2-dialog-primary btn primary`,children:J(`Create`,`생성`)})]})]})}):null}function ype({currentName:e,onOpen:t,onOpenFile:n,onNew:r,onClose:i,startup:a=!1,starters:o=[],onStarter:s}){let c=(0,Z.useMemo)(()=>o.map(_pe),[o]),[l,u]=(0,Z.useState)(q),d=l===`storyboard`?[]:c,f=c[0]??U8,[p,m]=(0,Z.useState)(a?`new`:`recent`),[h,g]=(0,Z.useState)(f.id),[_,v]=(0,Z.useState)(e||f.defaultName||f.name||`My Project`),[y,b]=(0,Z.useState)(`24`),[x,S]=(0,Z.useState)(`Meters`),[C,w]=(0,Z.useState)([]),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)([]),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=!0;return bt().then(t=>{e&&w(Array.isArray(t)?t:[])}),ut().then(async t=>{if(!e||!t)return;let n=await $n(t);if(e){if(n!==`granted`){A(!0),n===`prompt`&&M(t);return}E(t),O(await ne(t))}}).catch(()=>{e&&A(!0)}),()=>{e=!1}},[]),(0,Z.useEffect)(()=>{a&&N.current?.focus()},[a]),(0,Z.useEffect)(()=>()=>{queueMicrotask(()=>G8(null))},[]);let P=d.find(e=>e.id===h)??U8,F=_.trim().length>0,I=J(`Enter a project name to create a project`,`프로젝트를 만들려면 이름을 입력하세요`),L=T?.name||J(`Browser project store`,`브라우저 프로젝트 저장소`),R=dr()&&se(),z=async()=>{if(!j||await Jt(j)!==`granted`)return;let e=j;M(null),A(!1),E(e),O(await ne(e))},B=async()=>{if(R)try{let e=await At();await ir(e),E(e),A(!1),M(null),O(await ne(e))}catch(e){e?.name!==`AbortError`&&A(!0)}},V=async()=>{T&&O(await ne(T))},ee=t=>{g(t.id),v(n=>!n.trim()||[P?.name,P?.defaultName,e].includes(n.trim())?t.defaultName??t.name:n)},H=e=>{u(e),!(e!==`storyboard`||!P?.starterId)&&(g(U8.id),v(e=>e.trim()===P?.name?U8.defaultName:e))},U=e=>{e.preventDefault();let t=_.trim();if(t){if(P?.starterId){s?.(P.starterId,t,{previsMode:`animation`});return}G8(t),r(t,{previsMode:l})}},W=[...C.map(e=>({...e,key:`recent-${e.name}`,removable:!0,date:e.openedAt})),...D.map(e=>({...e,key:`folder-${e.name}`,removable:!1,date:e.lastModified}))],G=[{id:`recent`,label:J(`Recent`,`최근`)},{id:`new`,label:J(`New Project`,`새 프로젝트`)},{id:`learn`,label:J(`Learn`,`배우기`)}];return(0,Q.jsx)(`div`,{className:`v2-start-screen project-browser-backdrop${a?` startup`:``}`,onPointerDown:e=>{!a&&e.target===e.currentTarget&&i?.()},children:(0,Q.jsxs)(`div`,{className:`v2-start-window project-browser${a?` startup`:``}`,role:`dialog`,"aria-modal":`true`,"aria-label":J(`Choose project`,`프로젝트 선택`),children:[(0,Q.jsxs)(`nav`,{className:`v2-start-nav`,"aria-label":J(`Project navigation`,`프로젝트 탐색`),children:[(0,Q.jsxs)(`div`,{className:`v2-start-brand`,children:[(0,Q.jsx)(ppe,{}),(0,Q.jsx)(`strong`,{children:`CozyClay`})]}),(0,Q.jsx)(`div`,{className:`v2-start-nav-list`,children:G.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-nav-item${p===e.id?` active`:``}`,"aria-current":p===e.id?`page`:void 0,onClick:()=>m(e.id),children:e.label},e.id))}),(0,Q.jsxs)(`div`,{className:`v2-start-version`,children:[`v`,mpe]})]}),(0,Q.jsxs)(`main`,{className:`v2-start-main`,children:[(0,Q.jsxs)(`div`,{className:`v2-start-main-head`,children:[(0,Q.jsxs)(`div`,{className:`v2-start-title-row`,children:[(0,Q.jsx)(`h1`,{children:p===`recent`?J(`Recent`,`최근`):p===`learn`?J(`Learn`,`배우기`):J(`New Project`,`새 프로젝트`)}),p!==`new`&&(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-close x`,onClick:i,"aria-label":J(`Close`,`닫기`),children:`×`})]}),p===`new`&&(0,Q.jsx)(`div`,{className:`v2-start-mode`,role:`radiogroup`,"aria-label":J(`Project mode`,`프로젝트 모드`),"data-testid":`start-previs-mode`,children:hpe.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e.id,className:`v2-start-mode-option${l===e.id?` active`:``}`,"data-previs-mode":e.id,onClick:()=>H(e.id),children:[(0,Q.jsx)(`strong`,{children:e.label()}),(0,Q.jsx)(`span`,{children:e.blurb()})]},e.id))})]}),p===`learn`?(0,Q.jsxs)(`div`,{className:`v2-start-learn`,children:[(0,Q.jsx)(`strong`,{children:J(`Block a shot in three moves`,`세 단계로 샷을 블로킹하세요`)}),(0,Q.jsx)(`p`,{children:J(`Choose a template, name the project, then place a character and frame the camera in the editor.`,`템플릿을 고르고 프로젝트 이름을 정한 다음 편집기에서 인물을 배치하고 카메라를 잡아 보세요.`)}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-learn-action`,onClick:()=>m(`new`),children:J(`Start a new project`,`새 프로젝트 시작`)})]}):p===`recent`?(0,Q.jsxs)(`div`,{className:`v2-start-recent-page`,children:[(0,Q.jsxs)(`div`,{className:`v2-start-recent-heading`,children:[(0,Q.jsx)(`span`,{children:J(`Recent projects`,`최근 프로젝트`)}),(0,Q.jsxs)(`div`,{className:`v2-start-recent-actions`,children:[T&&(0,Q.jsx)(`button`,{type:`button`,onClick:V,children:J(`Refresh`,`새로고침`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:n,children:J(`Open project file…`,`프로젝트 파일 열기…`)})]})]}),(0,Q.jsx)(K8,{entries:W,currentName:e,onOpen:t,onOpenFile:n,onRemove:async e=>{await jr(e.name),w(await bt())}})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`v2-start-template-grid`,role:`list`,"aria-label":J(`Project templates`,`프로젝트 템플릿`),children:[d.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-template${P?.id===e.id?` selected`:``}`,"data-template-id":e.id,onClick:()=>ee(e),onDoubleClick:()=>e.starterId&&s?.(e.starterId),children:[(0,Q.jsx)(`span`,{className:`v2-start-template-art ${e.kind}`,children:(0,Q.jsx)(H8,{id:e.starterId??e.id})}),(0,Q.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`span`,{children:e.description})]})]},e.id)),(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-add-card${P?.id===U8.id?` selected`:``}`,"data-testid":`start-new-project-card`,onClick:()=>{ee(U8),requestAnimationFrame(()=>N.current?.select())},children:[(0,Q.jsx)(`span`,{className:`v2-start-add-art`,"aria-hidden":`true`,children:(0,Q.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`20`,height:`20`,children:(0,Q.jsx)(`path`,{d:`M10 3.5v13M3.5 10h13`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})})}),(0,Q.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,Q.jsx)(`strong`,{children:J(`New project`,`새 프로젝트`)}),(0,Q.jsx)(`span`,{children:J(`Start from an empty stage`,`빈 무대에서 시작`)})]})]}),(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-add-card v2-start-open-card`,"data-testid":`start-open-project-card`,onClick:n,children:[(0,Q.jsx)(`span`,{className:`v2-start-add-art`,"aria-hidden":`true`,children:(0,Q.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`20`,height:`20`,children:(0,Q.jsx)(`path`,{d:`M2.5 6.5V15a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V8a1 1 0 0 0-1-1H10L8.5 5H3.5a1 1 0 0 0-1 1.5Z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinejoin:`round`})})}),(0,Q.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,Q.jsx)(`strong`,{children:J(`Open project`,`프로젝트 열기`)}),(0,Q.jsx)(`span`,{children:J(`A saved .cclayproject file`,`저장한 .cclayproject 파일`)})]})]})]}),(0,Q.jsxs)(`div`,{className:`v2-start-recent-block`,children:[(0,Q.jsx)(`div`,{className:`v2-start-recent-heading`,children:(0,Q.jsx)(`span`,{children:J(`Recent`,`최근`)})}),(0,Q.jsx)(K8,{entries:C.map(e=>({...e,key:`recent-${e.name}`,removable:!0,date:e.openedAt})),currentName:e,onOpen:t,onOpenFile:n,onRemove:async e=>{await jr(e.name),w(await bt())},compact:!0})]})]})]}),(0,Q.jsxs)(`aside`,{className:`v2-start-preview`,"data-testid":`start-project-preview`,"aria-label":J(`Project preview`,`프로젝트 미리보기`),children:[(0,Q.jsx)(`div`,{className:`v2-start-preview-art ${P?.kind||`blank`}`,children:(0,Q.jsx)(H8,{id:P.starterId??P.thumbId})}),(0,Q.jsxs)(`div`,{className:`v2-start-preview-copy`,children:[(0,Q.jsx)(`strong`,{children:P?.name}),(0,Q.jsx)(`span`,{children:P?.description})]}),(0,Q.jsxs)(`form`,{className:`v2-start-project-form`,onSubmit:U,children:[(0,Q.jsxs)(`label`,{className:`v2-start-field`,children:[(0,Q.jsx)(`span`,{children:J(`Name`,`이름`)}),(0,Q.jsx)(`input`,{ref:N,"data-testid":`start-project-name`,"aria-label":J(`Name`,`이름`),value:_,onChange:e=>v(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`v2-start-field`,children:[(0,Q.jsx)(`span`,{children:J(`Location`,`위치`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`v2-start-location`,onClick:B,disabled:!R,title:R?J(`Choose the project storage folder`,`프로젝트 저장 폴더 선택`):J(`Projects are stored in this browser`,`프로젝트는 이 브라우저에 저장됩니다`),children:[(0,Q.jsx)(`span`,{children:L}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⌄`})]})]}),(0,Q.jsxs)(`label`,{className:`v2-start-field`,children:[(0,Q.jsx)(`span`,{children:J(`Frame rate`,`프레임 레이트`)}),(0,Q.jsx)(`span`,{className:`v2-start-select-wrap`,children:(0,Q.jsxs)(`select`,{"aria-label":J(`Frame rate`,`프레임 레이트`),value:y,onChange:e=>b(e.target.value),children:[(0,Q.jsx)(`option`,{value:`24`,children:`24 fps`}),(0,Q.jsx)(`option`,{value:`30`,children:`30 fps`})]})})]}),(0,Q.jsxs)(`label`,{className:`v2-start-field`,children:[(0,Q.jsx)(`span`,{children:J(`Units`,`단위`)}),(0,Q.jsx)(`span`,{className:`v2-start-select-wrap`,children:(0,Q.jsxs)(`select`,{"aria-label":J(`Units`,`단위`),value:x,onChange:e=>S(e.target.value),children:[(0,Q.jsx)(`option`,{value:`Meters`,children:`Meters`}),(0,Q.jsx)(`option`,{value:`Feet`,children:`Feet`})]})})]}),k&&(0,Q.jsxs)(`p`,{className:`v2-start-location-status`,role:`status`,children:[j?J(`Folder access needs to be re-allowed.`,`폴더 접근을 다시 허용해야 해요.`):J(`Using the browser project store.`,`브라우저 프로젝트 저장소를 사용합니다.`),j&&(0,Q.jsx)(`button`,{type:`button`,onClick:z,children:J(`Re-allow`,`다시 허용`)})]}),(0,Q.jsxs)(`div`,{className:`v2-start-preview-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-cancel`,onClick:i,children:J(`Cancel`,`취소`)}),(0,Q.jsx)(`button`,{type:`submit`,className:`v2-start-create btn primary`,"data-testid":`start-create`,disabled:!F,title:F?J(`Create project`,`프로젝트 만들기`):I,children:J(`Create`,`생성`)})]})]})]})]})})}function K8({entries:e,currentName:t,onOpen:n,onOpenFile:r,onRemove:i,compact:a=!1}){return e.length===0?(0,Q.jsxs)(`p`,{className:`v2-start-empty${a?` compact`:``}`,children:[J(`No recent projects in this browser yet. `,`이 브라우저에 최근 프로젝트가 없습니다. `),(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-empty-open`,onClick:r,children:J(`Open a project file…`,`프로젝트 파일 열기…`)})]}):(0,Q.jsx)(`div`,{className:`v2-start-recent-list${a?` compact`:``}`,role:`list`,children:e.map(e=>(0,Q.jsxs)(`div`,{className:`v2-start-recent-row${e.name===t?` active`:``}`,role:`listitem`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`v2-start-recent-open`,onClick:()=>n(e),children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`span`,{children:gpe(e.date)}),(0,Q.jsxs)(`small`,{children:[e.shots??`—`,J(` shots`,` 샷`)]})]}),e.removable&&(0,Q.jsx)(`button`,{type:`button`,className:`v2-start-recent-remove`,"aria-label":J(`Remove ${e.name} from recent projects`,`최근 프로젝트에서 ${e.name} 제거`,`从最近项目中移除 ${e.name}`),title:J(`Remove from list`,`목록에서 제거`),onClick:()=>i(e),children:`×`})]},e.key))})}var q8=Object.freeze([`animation`,`storyboard`]),bpe=Object.freeze([`1`,`2`,`3`,`4`]),J8=(e,t)=>{ea().then(()=>ba(e,t),()=>{})},Y8=()=>Date.now(),X8=null,Z8=e=>bpe.includes(String(e))?String(e):null,Q8=e=>{try{e()}catch{}};function xpe(e){Q8(()=>{q8.includes(e)&&(X8=Y8(),Es(`guide:opened`,1)&&J8(`guide:opened`,{mode:e}))})}function Spe(e,t,n){Q8(()=>{let r=Z8(t);if(!q8.includes(e)||!r)return;let i=Y8(),a=X8===null?NaN:i-X8;X8=i,Es(`guide:step:${r}`,1)&&J8(`guide:step`,{mode:e,step:r,step_ms:ls(a)}),t===n&&Es(`guide:completed`,1)&&J8(`guide:completed`,{mode:e})})}function Cpe(e,t){Q8(()=>{let n=Z8(t);!q8.includes(e)||!n||(X8=null,Es(`guide:dismissed`,1)&&J8(`guide:dismissed`,{mode:e,reached:n}))})}var wpe={animation:[{en:`Select a character in the Outliner.`,ko:`아웃라이너에서 캐릭터를 선택하세요.`,zh:`在大纲视图中选择一个角色。`,hintEn:`Click Character 1 (or its row) to make it active.`,hintKo:`캐릭터 1(또는 캐릭터 행)을 클릭하면 활성화됩니다.`,hintZh:`点击角色 1(或其所在行)使其成为当前角色。`},{en:`Move it in the Scene view.`,ko:`장면 보기에서 캐릭터를 움직이세요.`,zh:`在场景视图中移动它。`,hintEn:`Drag the character marker on the floor to place it.`,hintKo:`바닥의 캐릭터 마커를 드래그해 배치하세요.`,hintZh:`拖动地面上的角色标记来摆放位置。`},{en:`Ask the Agent for a motion.`,ko:`에이전트에게 동작을 요청하세요.`,zh:`让智能体生成一个动作。`,hintEn:`Open it with Cmd/Ctrl+B and say what the character does; the take lands on the Body lane.`,hintKo:`Cmd/Ctrl+B로 열고 캐릭터가 할 동작을 말하면 테이크가 바디 레인에 올라갑니다.`,hintZh:`按 Cmd/Ctrl+B 打开,说出角色要做的动作;动作片段会落在身体轨道上。`},{en:`Scrub the timeline or press Space to play.`,ko:`타임라인을 문지르거나 Space를 눌러 재생하세요.`,zh:`拖动时间线或按空格播放。`,hintEn:`Seeing the playhead move is your first visible result.`,hintKo:`재생 헤드가 움직이면 첫 결과를 확인한 것입니다.`,hintZh:`看到播放头移动,就是你的第一个可见结果。`}],storyboard:[{en:`Open the Agent panel (Cmd/Ctrl+B).`,ko:`에이전트 패널을 여세요 (Cmd/Ctrl+B).`,zh:`打开智能体面板(Cmd/Ctrl+B)。`,hintEn:`The Agent panel is where you describe each panel.`,hintKo:`에이전트 패널에서 각 패널을 설명합니다.`,hintZh:`在智能体面板中逐个描述每个面板。`},{en:`Describe one scene in a sentence.`,ko:`장면 하나를 한 문장으로 설명하세요.`,zh:`用一句话描述一个场景。`,hintEn:`One sentence per turn is enough for one panel.`,hintKo:`패널 하나에는 한 문장이면 충분합니다.`,hintZh:`每个面板一轮只说一句话就够了。`},{en:`Your panel appears on the Board.`,ko:`패널이 보드에 나타납니다.`,zh:`你的面板会出现在看板上。`,hintEn:`Open the Board tab to see the new panel card.`,hintKo:`보드 탭에서 새 패널 카드를 확인하세요.`,hintZh:`打开看板标签页查看新的面板卡片。`},{en:`Stylize it, or export the panel pack.`,ko:`스타일을 입히거나 패널 팩으로 내보내세요.`,zh:`对它进行风格化,或导出面板包。`,hintEn:`Use Stylize on the card, or export the panel pack.`,hintKo:`카드에서 스타일을 입히거나 패널 팩으로 내보내세요.`,hintZh:`在卡片上使用风格化,或导出面板包。`}]};function Tpe({open:e,onDismiss:t,previsMode:n=`animation`}){let r=n===`storyboard`,i=r?`storyboard`:`animation`,a=wpe[i],[o,s]=(0,Z.useState)(0);if((0,Z.useEffect)(()=>{e&&(s(0),xpe(i))},[e]),!e)return null;let c=o>=a.length,l=()=>{c||Cpe(i,o+1),t()};return(0,Q.jsxs)(`aside`,{className:`v2-first-success-guide first-success-guide`,role:`dialog`,"aria-labelledby":`first-success-guide-title`,"aria-describedby":`first-success-guide-description`,children:[(0,Q.jsxs)(`div`,{className:`v2-first-success-guide-head first-success-guide-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{id:`first-success-guide-title`,children:J(`Your first 60 seconds`,`첫 60초`)}),(0,Q.jsx)(`span`,{children:c?J(`Core loop complete`,`핵심 흐름 완료`,`核心流程完成`):J(`Step ${o+1} of ${a.length}`,`${o+1} / ${a.length} 단계`,`第 ${o+1} / ${a.length} 步`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-close first-success-guide-close`,onClick:l,"aria-label":J(`Dismiss guide`,`가이드 닫기`),children:`×`})]}),c?(0,Q.jsxs)(`div`,{className:`v2-first-success-guide-complete first-success-guide-complete`,id:`first-success-guide-description`,role:`status`,children:[(0,Q.jsx)(`div`,{className:`v2-first-success-guide-check first-success-guide-check`,children:`✓`}),(0,Q.jsx)(`strong`,{children:r?J(`You made your first panel.`,`첫 패널을 만들었어요.`):J(`You made your first shot.`,`첫 샷을 만들었어요.`)}),(0,Q.jsx)(`p`,{children:r?J(`Describe, review on the Board, then stylize or export. You can close this guide and keep adding panels.`,`설명하고, 보드에서 확인한 뒤 스타일을 입히거나 내보내세요. 가이드를 닫고 패널을 계속 추가하세요.`):J(`Select, move, ask, and play are the core CozyClay loop. You can close this guide and keep blocking.`,`선택하고, 움직이고, 요청하고, 재생하는 것이 CozyClay의 핵심 흐름입니다. 가이드를 닫고 계속 블로킹하세요.`)}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-next first-success-guide-next btn primary`,onClick:l,children:J(`Continue editing`,`편집 계속하기`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{id:`first-success-guide-description`,className:`v2-first-success-guide-intro first-success-guide-intro`,children:J(`Follow these four actions to see a result quickly.`,`네 가지 동작으로 빠르게 결과를 확인해 보세요.`)}),(0,Q.jsx)(`ol`,{className:`v2-first-success-guide-steps first-success-guide-steps`,children:a.map((e,t)=>(0,Q.jsxs)(`li`,{className:t<o?`done`:t===o?`current`:``,children:[(0,Q.jsx)(`span`,{className:`v2-first-success-guide-step-mark first-success-guide-step-mark`,children:t<o?`✓`:t+1}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:J(e.en,e.ko,e.zh)}),t===o&&(0,Q.jsx)(`span`,{children:J(e.hintEn,e.hintKo,e.hintZh)})]})]},e.en))}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-next first-success-guide-next btn primary`,onClick:()=>{Spe(i,o+1,a.length),s(o+1)},children:J(o===a.length-1?`Mark complete`:`I did this`,o===a.length-1?`완료로 표시`:`했어요`,o===a.length-1?`标记完成`:`我做了这一步`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-skip first-success-guide-skip`,onClick:l,children:J(`Skip guide`,`가이드 건너뛰기`)})]})}var Epe=Object.freeze([[`animation`,`Animation`,`애니메이션`,`动画`],[`film`,`Film / drama`,`영화·드라마`,`影视剧`],[`game`,`Game`,`게임`,`游戏`],[`ad_mv`,`Ad / music video`,`광고·뮤비`,`广告 / MV`],[`personal`,`Personal project`,`개인 작업`,`个人项目`],[`other`,`Something else`,`기타`,`其他`]]),Dpe=Object.freeze([[`team`,`With a team or company`,`팀·회사에서`,`与团队或公司`],[`solo`,`On my own`,`혼자`,`我自己`]]);function Ope({open:e,isKo:t,isZh:n,onAnswer:r}){let[i,a]=(0,Z.useState)(null),o=(e,r,i)=>t?r:n?i:e;if((0,Z.useEffect)(()=>{e||a(null)},[e]),!e)return null;let s=()=>r(i??`skip`,`skip`);return(0,Q.jsxs)(`section`,{className:`use-case-ask`,role:`dialog`,"aria-modal":`false`,"aria-labelledby":`use-case-ask-title`,onKeyDown:e=>{e.key===`Escape`&&s()},children:[(0,Q.jsxs)(`div`,{className:`use-case-ask-head`,children:[(0,Q.jsx)(`strong`,{id:`use-case-ask-title`,children:o(`Quick question (optional)`,`짧은 질문 (선택)`,`快速提问(可选)`)}),(0,Q.jsx)(`button`,{type:`button`,className:`use-case-ask-close`,"aria-label":o(`Close`,`닫기`,`关闭`),onClick:s,children:`×`})]}),(0,Q.jsx)(`p`,{className:`use-case-ask-prompt`,children:i?o(`Who are you making it with?`,`누구와 작업하나요?`,`你和谁一起做?`):o(`What are you making with CozyClay?`,`CozyClay로 뭘 만들고 있나요?`,`你在用 CozyClay 做什么?`)}),(0,Q.jsx)(`div`,{className:`use-case-ask-choices`,role:`group`,"aria-label":i?o(`Team or solo`,`팀 또는 혼자`,`团队或个人`):o(`Use case`,`용도`,`用途`),children:(i?Dpe:Epe).map(([e,t,n,s])=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>i?r(i,e):a(e),children:o(t,n,s)},e))}),(0,Q.jsx)(`p`,{className:`use-case-ask-note`,children:o(`Anonymous. Only the choice is sent.`,`익명이에요. 고른 항목만 전송돼요.`,`匿名。只发送所选项目。`)})]})}var $8=`gizmoHandleProxy`,kpe=[$8,`keyLightPick`,`pathAxis`,`pathIndex`,`pathRing`,`pathLine`,`craneAxis`,`craneIndex`];function Ape(e){for(let t=e;t;t=t.parent){let e=t.userData;if(e){for(let t of kpe)if(e[t]!==void 0)return!0}}return!1}function jpe(e){return e.some(e=>Ape(e.object))}var e5=(e,t)=>Math.max(0,Math.min(e.frameCount-1,Math.round(t)||0)),Mpe=(e,t)=>typeof t.parent==`string`?e.get(t.parent):null;function Npe(e,t,n){let r=new Set;for(let i=e.get(n);i&&!r.has(i.id);i=Mpe(e,i)){if(r.add(i.id),i.attach)return null;let e=t?.get?.(i.id);if(e)return{id:i.id,track:e}}return null}function Ppe(e,t){return e?.hold?e.hold[e5(e,t)]===1?`held`:null:e?`hinge`:null}function Fpe(e,t){return t.set(0,e.renderer===`empty`?0:(e.height??1)/2,0)}function Ipe(e,t,n,r){let i=e.get(t),a=i?cZ(e,t,n,r,new Y):null;if(!a)return null;let o=new Vu;return a.decompose(new X,o,new X),{centre:Fpe(i,new X).applyMatrix4(a).toArray(),quat:o.toArray()}}function Lpe(e,t){let n=e5(e,t);return{pos:new X().fromArray(e.pos,n*3),quat:new Vu().fromArray(e.quat,n*4)}}function t5(e,t,{travel:n=null,axis:r=null,degrees:i=0}={}){let a=e.pos.clone(),o=e.quat.clone();if(r&&i){let e=new Vu().setFromAxisAngle(r.clone().normalize(),i*Math.PI/180),n=new X().fromArray(t);a.sub(n).applyQuaternion(e).add(n),o.premultiply(e).normalize()}return n&&a.add(n),{pos:a,quat:o}}function Rpe(e,t,n,r,i){let a=new X().fromArray(n?.axis??[0,1,0]).normalize();return t5(e,n?.pivot??t,{axis:a,degrees:i*r.clone().normalize().dot(a)})}var n5=(e,t)=>t?Math.round(e/t)*t:e;function zpe(e,t,n=0){let r=new X;for(let i of t)r.addScaledVector(i,n5(e.dot(i),n));return r}var Bpe=(e,t=0)=>n5(e,t);function Vpe(e,t){let n=t&&e?.get?.(t.id);if(!n)return e;let r=e5(n,t.frame),i=Float32Array.from(n.pos),a=Float32Array.from(n.quat);return i.set(t.pos.toArray(),r*3),a.set(t.quat.toArray(),r*4),new Map(e).set(t.id,{...n,pos:i,quat:a})}var r5=e=>Math.round(e*1e4)/1e4;function Hpe(e,t,n,r,{hinge:i=!1}={}){return{characterId:e,objectId:t,frame:Math.max(0,Math.round(n)),...i?{}:{pos:r.pos.toArray().map(r5)},rot:r.quat.clone().normalize().toArray().map(r5)}}function Upe(e,t,n,r,i=[]){let a=e.get(t),o=n?.track?.hold;if(!a||!o)return null;let s=new X(0,a.renderer===`empty`?0:a.height??1,0),c=new Y,l=n=>cZ(e,t,n,r,c)?s.clone().applyMatrix4(c).toArray():null,u=[];for(let e=0;e<n.track.frameCount;e+=1){if(o[e]!==1)continue;let t=l(e);t&&u.push(t)}let d=i.filter(e=>o[e5(n.track,e)]===1).map(l).filter(Boolean);return u.length>1?{points:u,keys:d}:null}function Wpe({selected:e,objects:t,tracks:n,frame:r,frameCount:i,fps:a,motion:o,run:s}){let[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(null),d=(0,Z.useMemo)(()=>new Map(t.map(e=>[e.id,e])),[t]),f=Vpe(n,c),p=e?.id??null,m=p?Npe(d,f,p):null,h=m?Ipe(d,p,r,{frameCount:i,fps:a,objectTracks:f}):null,g=m?n.get(m.id):null,_=g?.characterId??null,v=m?Ppe(m.track,r):null,y=_?o?.motionFor?.(_)?.spec?.objects?.[m.id]??null:null,b=y?.keys,x=Array.isArray(b)?b.map(e=>e?.f).filter(Number.isFinite).join(`,`):``,S=m?.id??null,C=g?.pos,w=g?.quat,T=g?.hold,E=g?.frameCount,D=(0,Z.useMemo)(()=>{if(!S||!T)return null;let e={frameCount:E,pos:C,quat:w,hold:T},t=x?x.split(`,`).map(Number):[];return Upe(d,p,{track:e},{frameCount:i,fps:a,objectTracks:new Map([[S,e]])},t)},[d,p,S,C,w,T,E,i,a,x]);(0,Z.useEffect)(()=>{window.__heldGizmo=h?{id:p,mover:S,kind:v,characterId:_,pose:h}:null});let O=e=>{let t=u.current;t&&(t.last=e(t),l({id:t.id,frame:t.frame,...t.last}))};return{tracks:f,gizmo:h&&{pose:h,trail:D,editable:(v===`held`||v===`hinge`)&&!!_,hinge:v===`hinge`,begin(){return u.current={id:S,frame:Math.round(r),root:Lpe(g,r),pivot:h.centre,characterId:_,hinge:v===`hinge`?y??{}:null,last:null},!0},move:e=>O(t=>t5(t.root,t.pivot,{travel:e})),rotate:(e,t)=>O(n=>n.hinge?Rpe(n.root,n.pivot,n.hinge,e,t):t5(n.root,n.pivot,{axis:e,degrees:t})),end(e){let t=u.current;if(u.current=null,!e||!t?.last)return l(null);let n=null;try{n=s(`motion.keyObject`,Hpe(t.characterId,t.id,t.frame,t.last,{hinge:!!t.hinge}))}catch(e){console.warn(`motion.keyObject failed`,e)}Promise.resolve(n).finally(()=>l(null))}}}}var i5=`#ffd23d`;function Gpe({trail:e}){let t=(0,Z.useMemo)(()=>e?new Ol().setFromPoints(e.points.map(e=>new X(...e))):null,[e]);(0,Z.useEffect)(()=>()=>t?.dispose(),[t]);let n=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{n.current?.traverse(e=>e.layers.set(5))}),e?(0,Q.jsxs)(`group`,{ref:n,children:[(0,Q.jsx)(`line`,{geometry:t,renderOrder:997,frustumCulled:!1,children:(0,Q.jsx)(`lineBasicMaterial`,{color:i5,transparent:!0,opacity:.8,depthTest:!1,depthWrite:!1})}),e.keys.map((e,t)=>(0,Q.jsxs)(`mesh`,{position:e,renderOrder:997,children:[(0,Q.jsx)(`sphereGeometry`,{args:[.025,10,8]}),(0,Q.jsx)(`meshBasicMaterial`,{color:i5,depthTest:!1,depthWrite:!1,transparent:!0})]},t))]}):null}var a5=[{axis:`x`,dir:new X(1,0,0),color:`#ff5340`},{axis:`y`,dir:new X(0,1,0),color:`#54e05c`},{axis:`z`,dir:new X(0,0,1),color:`#3d8bff`}],o5={x:a5[0].dir,y:a5[1].dir,z:a5[2].dir},Kpe=[{id:`xz`,axes:[`x`,`z`],normal:`y`,color:`#54e05c`},{id:`xy`,axes:[`x`,`y`],normal:`z`,color:`#3d8bff`},{id:`yz`,axes:[`y`,`z`],normal:`x`,color:`#ff5340`}],s5=.62,c5=.016,qpe=.05,l5=.14,u5=.52,Jpe=.28,Ype=`#ffd23d`,d5=.022,f5=.09,p5=.09,Xpe=.07,Zpe=.16;function Qpe(e){return(e.y??0)+Math.max(As(e).height/2,.25)}function m5(e){return e.corner?`corner:${e.corner.id}`:e.axis??(e.plane?`plane:${e.plane.id}`:`centre`)}var $pe=[{id:`tr`,sx:1,sy:1},{id:`tl`,sx:-1,sy:1},{id:`br`,sx:1,sy:-1},{id:`bl`,sx:-1,sy:-1}],eme=new dc(new X(0,1,0),0);function h5(e,t,n){return t?.pose?n.fromArray(t.pose.centre):n.set(e.x,Qpe(e),e.z)}function g5(e,t){return t===`rotate`&&e?.editable?e.pose.quat:null}function _5({object:e,objects:t=[],mode:n=`move`,snap:r=!0,enabled:i,pickOnly:a=!1,paneRef:o,camRef:s,shotAspect:c=dE,onChange:l,onSelect:u,onGroundClick:d,onDragStart:f,onDragEnd:p,claimPointer:m,held:h=null}){let{gl:g,scene:_}=ey(),v=e=>{let t={x:e.left,y:e.top,w:e.width,h:e.height};return c?cE(t,c):t},y=e=>{if(c)e.aspect=c;else{let t=o?.current?.getBoundingClientRect();t&&t.height>=1&&(e.aspect=t.width/t.height)}},b=(0,Z.useRef)(null),x=(0,Z.useRef)(new Map),S=(0,Z.useRef)(null),C=(0,Z.useRef)({}),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),O=(0,Z.useRef)(null),k=(0,Z.useRef)(null),A=(0,Z.useRef)(null);A.current={object:e,objects:t,mode:n,snap:r,onChange:l,onSelect:u,onGroundClick:d,onDragStart:f,onDragEnd:p,claimPointer:m,held:h};let j=(0,Z.useMemo)(()=>({raycaster:new wl,ndc:new Gd,hit:new X,delta:new X,eye:new X,origin:new X,camPos:new X}),[]),M=(0,Z.useMemo)(()=>a5.map(({axis:e,dir:t})=>{let n=new Vu().setFromUnitVectors(new X(0,1,0),t);return{axis:e,u:new X(1,0,0).applyQuaternion(n),v:new X(0,0,1).applyQuaternion(n)}}),[]),N=(0,Z.useRef)(null);N.current&&(N.current.id!==e?.id||N.current.mode!==n)&&(T(null),O.current!==null&&(O.current=null,D(null))),N.current={id:e?.id,mode:n},(0,Z.useEffect)(()=>{b.current?.traverse(e=>e.layers?.set(5))});let P=()=>{let e=j.raycaster.intersectObjects(_.children,!0).find(e=>e.object.isMesh);j.raycaster.layers.set(5);let t=null,n=!1,r=j.raycaster.intersectObjects(_.children,!0).find(e=>{if(!e.object.isMesh)return!1;for(let r=e.object;r;r=r.parent){if(e.object.userData?.emptyPick&&r.userData?.sceneObjectId)return t=r.userData.sceneObjectId,n=!0,!0;if(r.userData?.shotCameraPick)return t=`__shotcam__`,!0;if(r.userData?.keyLightPick)return t=`__keylight__`,!0}return!1});if(j.raycaster.layers.set(0),r&&(n||!e||r.distance<e.distance))return{id:t,point:r.point.clone()};if(!e)return null;for(let t=e.object;t;t=t.parent){if(t.userData?.sceneObjectId)return{id:t.userData.sceneObjectId,point:e.point.clone()};if(t.userData?.characterPick)return{id:`char:${t.userData.characterPick}`,point:e.point.clone()}}return null},F=e=>{let t=o?.current,n=s?.current;if(!t||!n)return null;let r=t.getBoundingClientRect();if(r.width<2||r.height<2)return null;let i=v(r);return j.ndc.set((e.clientX-i.x)/i.w*2-1,-((e.clientY-i.y)/i.h)*2+1),Math.abs(j.ndc.x)<=1&&Math.abs(j.ndc.y)<=1?j.ndc:null};(0,Z.useEffect)(()=>{if(!i)return;let e=e=>{let t=s?.current,n=t?F(e):null;return n?(y(t),t.updateProjectionMatrix(),t.updateMatrixWorld(),t.matrixWorldInverse.copy(t.matrixWorld).invert(),b.current?.updateMatrixWorld(!0),_.updateMatrixWorld(),j.raycaster.setFromCamera(n,t),{ndc:n,camera:t}):null},t=t=>{let n=k.current;if(!n||!e(t)||!j.raycaster.ray.intersectPlane(n.plane,j.hit))return;let{objects:r,onChange:i,snap:a}=A.current;if(!(r.find(e=>e.id===n.id)??(A.current.object?.id===n.id?A.current.object:null)))return;let o=a!==(t.ctrlKey||t.metaKey);if(n.mode===`rotate`){j.delta.subVectors(j.hit,n.origin);let e=Math.atan2(j.delta.dot(n.binormal),j.delta.dot(n.tangent));if(n.turned+=Ar((e-n.lastAngle)*180/Math.PI),n.lastAngle=e,n.held)return void A.current.held?.rotate(n.dir,Bpe(n.turned,o?5:0));if(n.axis===`screen`){let e=pr(n.start,n.dir,n.turned,o?void 0:0);e&&i?.(n.id,e,n.token);return}let t=Qt(n.start,n.axis,n.turned,o?void 0:0);t&&i?.(n.id,t,n.token);return}if(n.mode===`corner`){let e=j.delta.subVectors(j.hit,n.origin),t=e.dot(n.right)*n.corner.sx+e.dot(n.up)*n.corner.sy,r=Math.max(.02,1+(t-n.startAlong)/n.reference),a=Math.max(.05,n.startHeight*r),s=Math.max(.05,n.startWidth*r);i?.(n.id,o?{height:Math.round(a*20)/20,width:Math.round(s*20)/20}:{height:a,width:s},n.token);return}if(n.mode===`scale`){j.delta.subVectors(j.hit,n.origin);let e=1+(j.delta.dot(n.dir)-n.startAlong)/n.reference,t=n.start?.renderer===`cutout`?n.start.footprint?.width??0:0;if(n.axis===`x`&&t>0){let r=Math.max(.05,t*Math.max(e,.01));i?.(n.id,{width:o?Math.round(r*20)/20:r},n.token);return}let r=wr(n.start,n.axis,e,o?void 0:0);r&&i?.(n.id,r,n.token);return}if(j.delta.subVectors(j.hit,n.hitStart),n.held)return void A.current.held?.move(zpe(j.delta,n.planeAxes?n.planeAxes.map(e=>o5[e]):[n.dir],o?.05:0));if(n.planeAxes){let e={};for(let t of n.planeAxes)Object.assign(e,Vt(n.start,t,j.delta.dot(o5[t]),o?void 0:0));i?.(n.id,e,n.token);return}let s=Vt(n.start,n.axis,j.delta.dot(n.dir),o?void 0:0);s&&i?.(n.id,s,n.token)},n=()=>{k.current&&(k.current=null,g.domElement.style.cursor=``,window.removeEventListener(`pointermove`,t),window.removeEventListener(`pointerup`,o),window.removeEventListener(`pointercancel`,c),window.removeEventListener(`blur`,l),window.removeEventListener(`keydown`,u,!0))},r=e=>{let t=k.current;if(!t)return;let r=A.current.onDragEnd,i=t.token;n(),t.held?A.current.held?.end(e):i!=null&&r&&r(i,{commit:e})},o=()=>r(!0),c=()=>r(!0),l=()=>r(!0),u=e=>{if(k.current){if((e.ctrlKey||e.metaKey)&&(e.code===`KeyZ`||e.code===`KeyY`)){r(!0);return}(e.code===`Escape`||e.key===`Escape`)&&(r(!1),e.preventDefault(),e.stopPropagation())}},d=(e,r,i,a)=>{let s=A.current.object;if(!s)return!1;let d=A.current.objects.find(e=>e.id===s.id)??s,f=A.current.held;h5(s,f,j.origin),a.getWorldDirection(j.eye);let p,m;if(e===`rotate`){let t=g5(f,e),n=r===`screen`?j.eye:t?i.clone().applyQuaternion(new Vu(...t)):i;p=new dc().setFromNormalAndCoplanarPoint(n,j.origin.clone());let a=new X;if(!j.raycaster.ray.intersectPlane(p,a))return!1;let o=new X(n.y,n.z,n.x).cross(n).normalize(),s=n.clone().cross(o).normalize(),c=a.clone().sub(j.origin);if(c.lengthSq()<1e-8)return!1;m={mode:`rotate`,tangent:o,binormal:s,lastAngle:Math.atan2(c.dot(s),c.dot(o)),turned:0,origin:j.origin.clone(),dir:n.clone()}}else if(e===`scale`){let e=r?i.clone():new X().crossVectors(j.eye,new X(0,1,0)).normalize(),t=e.clone().cross(j.eye).cross(e).normalize();p=new dc().setFromNormalAndCoplanarPoint(t,j.origin.clone());let n=new X;if(!j.raycaster.ray.intersectPlane(p,n))return!1;let a=n.clone().sub(j.origin).dot(e);m={mode:`scale`,dir:e,startAlong:a,reference:Math.abs(a)<.05?(b.current?.scale.x??1)*s5:a,origin:j.origin.clone()}}else if(e===`corner`){let e=(s.rot??0)*Math.PI/180,t=new X(Math.cos(e),0,-Math.sin(e)),n=new X(0,1,0),r=new X().crossVectors(t,n).normalize();p=new dc().setFromNormalAndCoplanarPoint(r,j.origin.clone());let a=new X;if(!j.raycaster.ray.intersectPlane(p,a))return!1;let o=d.footprint?.width??0,c=d.height??0;if(!(o>0)||!(c>0))return!1;let l=a.clone().sub(j.origin),u=l.dot(t)*i.sx+l.dot(n)*i.sy,f=(o+c)/4;m={mode:`corner`,corner:i,right:t,up:n,startAlong:u,reference:Math.abs(u)<.05?f:u,startWidth:o,startHeight:c,origin:j.origin.clone()}}else if(e===`plane`){let e=o5[i.normal];p=new dc().setFromNormalAndCoplanarPoint(e,j.origin.clone());let t=new X;if(!j.raycaster.ray.intersectPlane(p,t))return!1;m={mode:`move`,planeAxes:i.axes,hitStart:t}}else{let e=i.clone().cross(j.eye).cross(i).normalize();p=new dc().setFromNormalAndCoplanarPoint(e,j.origin.clone());let t=new X;if(!j.raycaster.ray.intersectPlane(p,t))return!1;m={mode:`move`,dir:i.clone(),hitStart:t}}let h=!!(f?.editable&&(e===`rotate`||!f.hinge&&(e===`move`||e===`plane`))&&f.begin()),_=h?void 0:A.current.onDragStart?.({owner:`gizmo`,cancel:n}),v=e===`corner`?i:null;return k.current={...m,id:d.id,axis:r,plane:p,corner:v,start:{...d},token:_,held:h},T(m5({axis:r,plane:p,corner:v})),g.domElement.style.cursor=`grabbing`,window.addEventListener(`pointermove`,t),window.addEventListener(`pointerup`,o),window.addEventListener(`pointercancel`,c),(_!=null||h)&&(window.addEventListener(`blur`,l),window.addEventListener(`keydown`,u,!0)),!0},f=t=>{let n=e(t);if(!n)return null;let r=[...x.current.values()].filter(e=>e.mesh?.parent);if(!r.length)return null;j.raycaster.layers.set(5);let i=j.raycaster.intersectObjects(r.map(e=>e.mesh),!1);if(!i.length)return null;let a=e=>r.find(t=>t.mesh===e.object),o=i.map(a).find(e=>e?.corner)??a(i[0]);return o?{...o,aim:n}:null},p=t=>{if(t.button!==0||t.altKey||t.target!==g.domElement||A.current.claimPointer?.(t))return;let n=f(t);if(n&&e(t)){j.raycaster.layers.set(5);let e=j.raycaster.intersectObjects(_.children,!0).some(e=>{for(let t=e.object;t;t=t.parent){let e=t.userData;if(e?.keyLightPick||e?.pathIndex!==void 0||e?.pathRing||e?.craneIndex!==void 0)return!0}return!1});if(j.raycaster.layers.set(0),e)return}if(n&&d(n.corner?`corner`:n.plane?`plane`:A.current.mode,n.axis,n.corner??n.plane??n.dir,n.aim.camera)){t.preventDefault(),t.stopPropagation();return}if(a||!e(t)||(j.raycaster.layers.set(5),jpe(j.raycaster.intersectObjects(_.children,!0))))return;j.raycaster.layers.set(0);let r=P();if(t.preventDefault(),t.stopPropagation(),!r&&A.current.onGroundClick&&j.raycaster.ray.intersectPlane(eme,j.hit)){A.current.onGroundClick({x:j.hit.x,z:j.hit.z});return}A.current.onSelect?.(r?r.id:null)},m=e=>{if(k.current||e.buttons!==0||e.target!==g.domElement)return;let t=f(e),n=t?m5(t):null;if(n!==O.current&&(O.current=n,D(n)),t){g.domElement.style.cursor=`grab`;return}a||(j.raycaster.layers.set(0),g.domElement.style.cursor=P()?`pointer`:``)};return a||(window.__gizmoPick=(e,t)=>{let n=f({clientX:e,clientY:t,button:0});return n?m5(n):null}),a||(window.__objectPick=(t,n)=>e({clientX:t,clientY:n})?(j.raycaster.layers.set(0),P()?.id??null):null),window.addEventListener(`pointerdown`,p,!0),g.domElement.addEventListener(`pointermove`,m),()=>{window.removeEventListener(`pointerdown`,p,!0),g.domElement.removeEventListener(`pointermove`,m),r(!0)}},[i,a,g,_,s,o,j]),ty(()=>{let t=b.current,r=s?.current;if(!t||!r||!e||(r.getWorldPosition(j.camPos),h5(e,h,j.origin),t.scale.setScalar(Math.max(.35,j.camPos.distanceTo(j.origin)*Zpe)),n!==`rotate`))return;r.getWorldDirection(j.eye);let i=S.current;i&&i.quaternion.copy(r.quaternion);let a=g5(h,n);if(a){let e=new Vu(...a).invert();j.eye.applyQuaternion(e),i?.quaternion.premultiply(e)}for(let{axis:e,u:t,v:n}of M){let r=C.current[e];r&&(r.rotation.z=Math.atan2(-j.eye.dot(n),-j.eye.dot(t)))}});let I=(0,Z.useCallback)(()=>{let e=s?.current,t=o?.current;if(!e||!t)return[];y(e),e.updateProjectionMatrix(),e.updateMatrixWorld(),e.matrixWorldInverse.copy(e.matrixWorld).invert(),b.current?.updateMatrixWorld(!0);let n=t.getBoundingClientRect(),r=v(n);return[...x.current.values()].filter(e=>e.mesh?.parent).map(t=>{let n=t.mesh.getWorldPosition(new X).project(e);return{axis:m5(t),x:r.x+(n.x+1)/2*r.w,y:r.y+(1-n.y)/2*r.h}})},[s,o,c]);if(typeof window<`u`&&!a&&(window.__gizmoHandles=I),(0,Z.useEffect)(()=>{if(!(typeof window>`u`||!a))return window.__characterGizmoHandles=I,()=>{window.__characterGizmoHandles===I&&delete window.__characterGizmoHandles}},[I,a]),!i||!e)return x.current.clear(),null;let L=(e,t)=>n=>{n&&(n.layers.set(5),n.userData[$8]=!0,x.current.set(e??`centre`,{mesh:n,axis:e,dir:t}))},R=e=>t=>{C.current[e]=t},z=e=>t=>{t&&(t.layers.set(5),t.userData[$8]=!0,x.current.set(`plane:${e.id}`,{mesh:t,axis:null,plane:e}))},B=e=>t=>{t&&(t.layers.set(5),t.userData[$8]=!0,x.current.set(`corner:${e.id}`,{mesh:t,axis:null,corner:e}))},V=(0,Q.jsx)(`meshBasicMaterial`,{visible:!1}),ee=w===`screen`,H=E===`screen`,U=w===`centre`,W=E===`centre`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Gpe,{trail:h?.trail??null}),(0,Q.jsxs)(`group`,{ref:b,position:h5(e,h,new X).toArray(),quaternion:g5(h,n)??[0,0,0,1],renderOrder:999,children:[a5.map(({axis:e,dir:t,color:r})=>{let i=new Vu().setFromUnitVectors(new X(0,1,0),t),a=w===e,o=E===e,s=a?Ype:r,c=a?2.2:o?3.6:2.2,l=(e=.95)=>(0,Q.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:s,emissiveIntensity:c,toneMapped:!1,depthTest:!1,depthWrite:!1,transparent:!0,opacity:e});return(0,Q.jsx)(`group`,{quaternion:i,children:n===`rotate`?(0,Q.jsxs)(`group`,{ref:R(e),rotation:[Math.PI/2,0,0],children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`torusGeometry`,{args:[u5,d5,8,24,Math.PI]}),l()]}),(0,Q.jsxs)(`mesh`,{rotation:[0,0,Math.PI],renderOrder:999,children:[(0,Q.jsx)(`torusGeometry`,{args:[u5,d5,8,24,Math.PI]}),l(Jpe)]}),(0,Q.jsxs)(`mesh`,{ref:L(e,t),children:[(0,Q.jsx)(`torusGeometry`,{args:[u5,Xpe,6,32]}),V]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`mesh`,{position:[0,s5/2,0],renderOrder:999,children:[(0,Q.jsx)(`cylinderGeometry`,{args:[c5,c5,s5,8]}),l()]}),(0,Q.jsxs)(`mesh`,{position:[0,s5+(n===`scale`?f5/2:l5/2),0],renderOrder:999,children:[n===`scale`?(0,Q.jsx)(`boxGeometry`,{args:[f5,f5,f5]}):(0,Q.jsx)(`coneGeometry`,{args:[qpe,l5,14]}),l()]}),(0,Q.jsxs)(`mesh`,{ref:L(e,t),position:[0,(s5+l5)/2,0],children:[(0,Q.jsx)(`cylinderGeometry`,{args:[p5,p5,s5+l5,8]}),V]})]})},e)}),n===`rotate`&&(0,Q.jsxs)(`group`,{ref:S,children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`torusGeometry`,{args:[.68,.022,8,64]}),(0,Q.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:ee?`#ffd23d`:`#f2f2f2`,emissiveIntensity:ee?2.2:H?3.6:2.2,toneMapped:!1,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})]}),(0,Q.jsxs)(`mesh`,{ref:L(`screen`,null),children:[(0,Q.jsx)(`torusGeometry`,{args:[.68,.07,6,48]}),V]})]}),n===`move`&&Kpe.map(e=>{let t=[0,0,0],n={x:0,y:1,z:2};for(let r of e.axes)t[n[r]]=.26;let r=e.normal===`y`?[-Math.PI/2,0,0]:e.normal===`x`?[0,Math.PI/2,0]:[0,0,0],i=w===`plane:${e.id}`,a=E===`plane:${e.id}`;return(0,Q.jsxs)(`group`,{position:t,rotation:r,children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`planeGeometry`,{args:[.2,.2]}),(0,Q.jsx)(`meshBasicMaterial`,{color:i?`#ffd23d`:e.color,transparent:!0,opacity:i?.6:a?.55:.34,side:2,depthTest:!1,depthWrite:!1})]}),(0,Q.jsxs)(`mesh`,{ref:z(e),children:[(0,Q.jsx)(`planeGeometry`,{args:[.2*1.5,.2*1.5]}),(0,Q.jsx)(`meshBasicMaterial`,{visible:!1,side:2})]})]},e.id)}),n===`scale`&&e?.renderer===`cutout`&&$pe.map(t=>{let n=(e.footprint?.width??0)/2,r=(e.height??0)/2;if(!(n>0)||!(r>0))return null;let i=b.current?.scale.x||1,a=`corner:${t.id}`,o=w===a,s=E===a,c=(e.rot??0)*Math.PI/180,l=t.sx*n/i,u=[l*Math.cos(c),t.sy*r/i,-l*Math.sin(c)];return(0,Q.jsxs)(`group`,{position:u,children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`boxGeometry`,{args:[.085,.085,.085]}),(0,Q.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:o?`#ffd23d`:`#f2f2f2`,emissiveIntensity:o?2:s?3.4:2,toneMapped:!1,depthTest:!1,depthWrite:!1})]}),(0,Q.jsxs)(`mesh`,{ref:B(t),children:[(0,Q.jsx)(`sphereGeometry`,{args:[.13,8,6]}),V]})]},a)}),n===`scale`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`mesh`,{renderOrder:999,children:[(0,Q.jsx)(`boxGeometry`,{args:[.11,.11,.11]}),(0,Q.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:U?`#ffd23d`:`#f2f2f2`,emissiveIntensity:U?2:W?3.4:2,toneMapped:!1,depthTest:!1,depthWrite:!1})]}),(0,Q.jsxs)(`mesh`,{ref:L(null,null),children:[(0,Q.jsx)(`sphereGeometry`,{args:[.16,8,6]}),V]})]})]})]})}function tme({result:e,copied:t,recordedVideoName:n,onClose:r,onCopy:i,onDownload:a,downloadDisabled:o=!1,exportFeedback:s=null}){let c=e.mode===`video`,l=e.modelLabel??(c?J(`your AI video tool`,`AI 영상 도구`):J(`your selected image model`,`선택한 이미지 모델`)),u=!!e.frame,d;return d=c&&e.frameB?(0,Q.jsxs)(`p`,{children:[J(`Paste the prompt into ${l}, set `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},设置 `),(0,Q.jsx)(`code`,{children:`blocking-frame-A-start.png`}),J(` as the start frame, and `,`를 시작 프레임으로, `,` 作为起始帧,并将 `),(0,Q.jsx)(`code`,{children:`blocking-frame-B-end.png`}),J(` as the end frame.`,`를 끝 프레임으로 설정하세요.`)]}):c&&u?(0,Q.jsxs)(`p`,{children:[J(`Paste the prompt into ${l} and attach `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},并附加 `),(0,Q.jsx)(`code`,{children:`blocking-frame.png`}),J(` as the reference frame.`,`를 참고 프레임으로 첨부하세요.`,` 作为参考帧。`)]}):u?(0,Q.jsxs)(`p`,{children:[J(`Paste the prompt into ${l} and attach `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},并附加 `),(0,Q.jsx)(`code`,{children:`blocking-frame.png`}),J(` as the reference image.`,`를 참고 이미지로 첨부하세요.`,` 作为参考图像。`)]}):(0,Q.jsx)(`p`,{children:J(`Paste the copied prompt into ${l} to create the scene.`,`복사한 프롬프트를 ${l}에 붙여 넣어 장면을 만드세요.`,`将复制的提示词粘贴到 ${l} 以创建场景。`)}),(0,Q.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,Q.jsxs)(`div`,{className:`modal result-modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`result-title`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`result-title`,children:J(`Your shot is ready`,`장면이 준비됐어요`)}),(0,Q.jsx)(`button`,{type:`button`,className:`x`,onClick:r,"aria-label":J(`Close the result`,`결과 닫기`),children:`✕`})]}),e.frameB?(0,Q.jsxs)(`div`,{className:`move-frames`,children:[(0,Q.jsxs)(`figure`,{children:[(0,Q.jsx)(`img`,{className:`preview`,src:e.frame,alt:J(`Camera move start frame`,`카메라 움직임 시작 프레임`)}),(0,Q.jsxs)(`figcaption`,{children:[`A · `,J(`Start`,`시작`)]})]}),(0,Q.jsxs)(`figure`,{children:[(0,Q.jsx)(`img`,{className:`preview`,src:e.frameB,alt:J(`Camera move end frame`,`카메라 움직임 끝 프레임`)}),(0,Q.jsxs)(`figcaption`,{children:[`B · `,J(`End`,`끝`)]})]})]}):e.frame&&(0,Q.jsx)(`img`,{className:`preview`,src:e.frame,alt:J(`Finished scene frame`,`완성된 장면 프레임`)}),e.move&&(0,Q.jsxs)(`div`,{className:`move-slate result-move-slate`,children:[(0,Q.jsxs)(`span`,{children:[e.move.displaySlate??e.move.slate,` · `,e.move.spanS,J(`s`,`초`,`秒`)]}),(0,Q.jsx)(`small`,{children:J(`Camera move made from timeline keyframes`,`타임라인 키프레임으로 만든 카메라 움직임`)})]}),(0,Q.jsxs)(`label`,{className:`modal-label`,children:[J(`Prompt`,`프롬프트`),` `,t&&(0,Q.jsxs)(`em`,{children:[`· `,J(`copied`,`복사됨`)]})]}),(0,Q.jsx)(`div`,{className:`promptbox`,children:e.prompt}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn`,onClick:i,children:t?J(`Copied ✓`,`복사됨 ✓`):J(`Copy prompt`,`프롬프트 복사`)}),e.frame&&(0,Q.jsx)(`button`,{type:`button`,className:`btn`,onClick:a,disabled:o,children:e.downloaded?J(`Exported`,`내보냄`):e.frameB?J(`Export start and end frames`,`시작·끝 프레임 내보내기`):J(`Export frame`,`프레임 내보내기`)})]}),s,(0,Q.jsxs)(`section`,{className:`result-next`,"aria-labelledby":`result-next-title`,children:[(0,Q.jsx)(`span`,{className:`result-next-kicker`,children:J(`Next · ${l}`,`다음 · ${l}`,`下一步 · ${l}`)}),(0,Q.jsx)(`h4`,{id:`result-next-title`,children:J(`Handing off to your AI`,`AI에 넣는 순서`)}),(0,Q.jsx)(`div`,{className:`result-next-intro`,children:d}),(0,Q.jsxs)(`ol`,{className:`result-handoff-steps`,children:[(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`strong`,{children:J(`Copy the prompt`,`프롬프트 복사`)}),(0,Q.jsx)(`span`,{children:t?J(`Copied. Paste it into your AI service's prompt box.`,`복사됐어요. AI 서비스의 입력창에 붙여 넣으세요.`):J(`Press “Copy prompt” above, then paste it into your AI service.`,`위의 ‘프롬프트 복사’를 누른 뒤 AI 서비스 입력창에 붙여 넣으세요.`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`strong`,{children:J(`Export the frame`,`프레임 내보내기`)}),(0,Q.jsx)(`span`,{children:e.frameB?J(`Press “Export start and end frames” to save both PNGs.`,`‘시작·끝 프레임 내보내기’를 눌러 두 PNG를 저장하세요.`):u?J(`Press “Export frame” to save the PNG.`,`‘프레임 내보내기’를 눌러 PNG를 저장하세요.`):J(`This result has no frame to export.`,`이 결과에는 내보낼 프레임이 없어요.`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`strong`,{children:J(`Attach the image to your AI`,`AI에 이미지 첨부`)}),(0,Q.jsx)(`span`,{children:e.frameB?J(`Use your AI service's image attach button to upload the start and end frames together.`,`AI 서비스의 이미지 첨부 버튼에서 시작 프레임과 끝 프레임을 함께 올리세요.`):J(`Use your AI service's image attach button to upload blocking-frame.png.`,`AI 서비스의 이미지 첨부 버튼에서 blocking-frame.png를 올리세요.`)})]})]}),(0,Q.jsx)(`p`,{className:`result-handoff-note`,children:J(`The prompt describes the scene's content and mood; the frame shows the camera framing. Use both to reproduce this scene as closely as possible.`,`프롬프트는 장면의 내용과 분위기를 설명하고, 프레임은 카메라 구도를 보여줘요. 둘을 함께 넣어야 이 장면을 가장 가깝게 재현할 수 있어요.`)}),n&&(0,Q.jsxs)(`p`,{className:`result-reference-video`,children:[(0,Q.jsx)(`strong`,{children:J(`Optional · Reference video`,`선택 사항 · 참고 영상`)}),J(`A video recorded with the recording feature: `,`녹화 기능으로 만든 `),(0,Q.jsx)(`code`,{children:n}),J(` file. Use it separately from the reference frame in the prompt above.`,` 파일이에요. 위의 프롬프트 참고 프레임과는 별도로 활용하세요.`)]})]})]})})}var v5=`cozyclay:pwa-update-ready`;function y5(e){window.dispatchEvent(new CustomEvent(v5,{detail:e}))}function nme(){if(!(`serviceWorker`in navigator))return;if(globalThis.__COZYCLAY_RUNTIME__?.distribution===`npm`){navigator.serviceWorker.getRegistrations().then(e=>Promise.all(e.map(e=>e.unregister())));return}let e=!!navigator.serviceWorker.controller,t=!1;navigator.serviceWorker.addEventListener(`controllerchange`,()=>{if(!e){e=!0;return}t||(t=!0,window.location.reload())}),window.addEventListener(`load`,async()=>{try{let e=await navigator.serviceWorker.register(`/sw.js`,{scope:`/`});e.waiting&&y5(e),e.addEventListener(`updatefound`,()=>{let t=e.installing;t?.addEventListener(`statechange`,()=>{t.state===`installed`&&navigator.serviceWorker.controller&&y5(e)})})}catch{return}},{once:!0})}var rme=3;function ime({rig:e,take:t,objects:n,propTake:r}){let i=sn(Wt),a=DV(),o=ey(e=>e.scene),s=ey(e=>e.gl),c=ey(e=>e.invalidate),l=(0,Z.useMemo)(()=>new XQ({layer:5}),[]),u=a.mode!==`off`&&!!e&&Un(t),d=(0,Z.useMemo)(()=>u&&a.mode===`keys`?MV(t,n):[],[u,a.mode,t,n]),f=(0,Z.useMemo)(()=>u?kV({frame:i,last:t.frameCount-1,...a,keyFrames:d}):[],[u,i,t,a,d]);return(0,Z.useEffect)(()=>{if(u)return o.add(l.object),()=>{o.remove(l.object)}},[u,o,l]),(0,Z.useEffect)(()=>()=>l.dispose(),[l]),(0,Z.useEffect)(()=>{c()},[c,u,f]),(0,Z.useEffect)(()=>{typeof window<`u`&&(window.__cozyclayGhosts={set:l,gl:s,scene:o,entries:f})},[l,s,o,f]),ty(()=>{l.show(u&&!!e.parent)&&(l.setRig(e),l.syncSources(o,n,t,rme),e.parent.updateWorldMatrix(!0,!1),l.update({entries:f,take:t,placement:e.parent.matrixWorld,propTake:r,objects:n,count:a.count}))}),null}var ame=3,ome=.3,b5=.042,x5={w:512,h:96},sme=()=>{},S5=new WeakMap;function cme(e){if(!S5.has(e)){let t=null;e.traverse(e=>{!t&&e.isBone&&/Head$/.test(e.name)&&(t=e)}),S5.set(e,t)}return S5.get(e)}function lme(){let e=document.createElement(`canvas`);Object.assign(e,{width:x5.w,height:x5.h});let t=new au(e);t.colorSpace=rd;let n=new Gp(new om({map:t,transparent:!0,depthTest:!1,depthWrite:!1,sizeAttenuation:!1,toneMapped:!1}));return n.center.set(.5,0),n.renderOrder=1e3,n.layers.set(5),n.raycast=sme,n.userData={canvas:e,texture:t,text:null},n}function ume(e,t,n){let{canvas:r,texture:i}=e.userData;if(e.userData.text===`${t}|${n}`)return;e.userData.text=`${t}|${n}`;let a=r.getContext(`2d`),o=`600 44px system-ui, -apple-system, 'Apple SD Gothic Neo', 'Noto Sans KR', sans-serif`;a.font=o;let s=Math.min(x5.w-4,Math.ceil(a.measureText(t).width)+52+34);a.clearRect(0,0,r.width,r.height),a.fillStyle=`rgba(16, 24, 28, 0.82)`,a.strokeStyle=nn,a.lineWidth=4,a.beginPath(),a.roundRect((x5.w-s)/2,8,s,x5.h-16,30),a.fill(),a.stroke(),a.fillStyle=n?`#46d36f`:nn,a.beginPath(),a.arc((x5.w-s)/2+26+8,x5.h/2,9,0,Math.PI*2),a.fill(),a.fillStyle=`#eef6f3`,a.font=o,a.textBaseline=`middle`,a.fillText(t,(x5.w-s)/2+26+34,x5.h/2+2),i.needsUpdate=!0,e.scale.set(b5*(x5.w/x5.h),b5,1)}function dme({set:e,label:t,draft:n,rig:r,scene:i,objects:a,propTake:o}){let s=n?zn(n,Date.now()):null,c=!!s?.shown&&!!r?.parent;if(t.visible=c,typeof window<`u`&&(window.__cozyclayDraftGhost={set:e,label:t,draft:n,state:s,on:c}),!e.show(c))return;e.setRig(r),e.syncSources(i,a,n.take,ame),r.parent.updateWorldMatrix(!0,!1),e.update({entries:[{f:s.frame,side:`after`,rank:1}],take:n.take,placement:r.parent.matrixWorld,propTake:o,objects:a,count:1});let l=e.slots[0];l.material.color.set(nn).multiplyScalar(1.15),l.material.opacity=s.opacity;let u=cme(l.rig);u&&(e.object.updateMatrixWorld(!0),u.getWorldPosition(t.position),t.position.y+=ome,t.material.opacity=Math.min(1,s.opacity/nr))}function fme({rigs:e,objects:t}){let n=(0,Z.useSyncExternalStore)(Le,Zr,Zr),r=(0,Z.useMemo)(()=>Pr(),[n]),i=xt(),a=ey(e=>e.scene),o=ey(e=>e.invalidate),s=(0,Z.useMemo)(()=>new XQ({layer:5}),[]),c=(0,Z.useMemo)(()=>lme(),[]),l=r?e?.[r.characterId]??null:null,u=i&&!!l&&!!r?.take,d=(0,Z.useMemo)(()=>r?.take?{frameCount:r.take.frameCount,fps:r.take.fps,objectTracks:KQ(r.take)}:null,[r]);return(0,Z.useEffect)(()=>{if(u)return a.add(s.object),s.object.add(c),()=>{s.object.remove(c),a.remove(s.object)}},[u,a,s,c]),(0,Z.useEffect)(()=>()=>{s.dispose(),c.material.dispose(),c.userData.texture.dispose()},[s,c]),(0,Z.useEffect)(()=>{r&&ume(c,mn(r),r.qa?.total===0)},[r,c]),(0,Z.useEffect)(()=>{if(o(),!u)return;let e=setInterval(()=>{(zn(r,Date.now()).shown||s.object.visible)&&o()},1e3/(r.take.fps||24));return()=>clearInterval(e)},[u,r,s,o]),ty(()=>dme({set:s,label:c,draft:u?r:null,rig:l,scene:a,objects:t,propTake:d})),null}var pme=.42,mme=.2,hme=420,gme=Math.PI/180,_me=44,vme=()=>{},yme=e=>1-(1-e)**3;function bme(e,t){let n=e.target?t?.find(t=>t.id===e.target):null,r={x:n?.x??0,y:n?.y??0,z:n?.z??0,rot:n?.rot??0,...e.placement};return new Y().compose(new X(r.x,r.y,r.z),new Vu().setFromAxisAngle(new X(0,1,0),r.rot*gme),new X(1,1,1))}function xme(e,t){let n=[];for(let r of e){let e=bme(r,t);for(let t of ss(r.parts)){let{id:r,parent:i,matrix:a,...o}=t;n.push({identity:JSON.stringify([o,a.map(e=>Math.round(e*1e4))]),part:t,matrix:e.clone().multiply(new Y().fromArray(a))})}}return n}var Sme=class{root=new hl;meshes=new Map;constructor(){this.root.name=`sculpt-sketch`,this.root.userData.sculptSketch=!0}make(e,t){let n=o8(e.shape===`scatter`?{...e,shape:`blob`,roundness:.5,taper:0}:e),r=new Kf({color:e.color,emissive:e.color,emissiveIntensity:.18,roughness:.85,metalness:0,transparent:!0,opacity:0,depthWrite:!1}),i=new yd(n,r);return Object.assign(i,{raycast:vme,castShadow:!1,receiveShadow:!1,matrixAutoUpdate:!1,renderOrder:_me,frustumCulled:!1}),i.layers.set(5),i.userData.sculptSketch=!0,this.root.add(i),{mesh:i,base:new Y,born:t,opacity:e.shape===`scatter`?mme:pme}}drop({mesh:e}){this.root.remove(e),e.geometry.dispose(),e.material.dispose()}update(e,t){let n=new Map,r=new Map;for(let i of e){let e=(r.get(i.identity)??0)+1;r.set(i.identity,e);let a=`${i.identity}#${e}`,o=this.meshes.get(a);if(o)this.meshes.delete(a);else try{o=this.make(i.part,t)}catch{continue}o.base.copy(i.matrix),n.set(a,o)}for(let e of this.meshes.values())this.drop(e);this.meshes=n,this.frame(t)}frame(e){let t=!1,n=new Y;for(let r of this.meshes.values()){let i=Math.min(1,Math.max(0,(e-r.born)/hme)),a=yme(i);t||=i<1;let o=.55+.45*a;r.mesh.matrix.copy(r.base).multiply(n.makeScale(o,o,o)),r.mesh.material.opacity=r.opacity*a}return t}dispose(){for(let e of this.meshes.values())this.drop(e);this.meshes.clear()}};function Cme({objects:e}){let t=(0,Z.useSyncExternalStore)(Cs,Ns,Ns),n=ey(e=>e.scene),r=ey(e=>e.invalidate),i=(0,Z.useMemo)(()=>new Sme,[]),a=(0,Z.useMemo)(()=>xme(t,e),[t,e]);return(0,Z.useEffect)(()=>(n.add(i.root),typeof window<`u`&&(window.__cozyclaySculptSketch={frame:To,clear:si,meshes:()=>i.meshes.size,root:i.root}),()=>{n.remove(i.root),i.dispose()}),[n,i]),(0,Z.useEffect)(()=>{i.update(a,performance.now()),r()},[i,a,r]),ty(()=>{i.frame(performance.now())&&r()}),null}var C5=null;function wme(){if(C5!==null)return C5;try{let e=document.createElement(`canvas`);C5=!!(e.getContext(`webgl`)||e.getContext(`experimental-webgl`))}catch{C5=!1}return C5}function Tme(){let[e,t]=(0,Z.useState)(C5??!0);return(0,Z.useEffect)(()=>{if(typeof document>`u`)return;let e=setTimeout(()=>{let e=wme();t(e),e||QT(`unavailable`)},0);return()=>clearTimeout(e)},[]),e}function w5(e){if(!e)throw Error(`Assertion failed.`)}var T5=e=>e&&e[e.length-1],E5=e=>e>=0&&e<2**32,D5=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},O5=e=>{let t=D5(e);return t&1?t+1>>1:-(t>>1)},k5=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),A5=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),j5=new TextEncoder,M5={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},N5={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},P5={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Eme=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,F5=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),I5=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},Dme=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},L5=e=>{throw Error(`Unexpected value: ${e}`)},Ome=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},kme=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Ame=/^[a-z]{3}$/,jme=e=>Ame.test(e),R5=1e6*(1+2**-52),Mme=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{num:n*a,den:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{num:n*a,den:o}},z5=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Nme=e=>{w5(Number.isInteger(e.num)),w5(Number.isInteger(e.den)),w5(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},B5=e=>Array.isArray(e)?e:[e],V5=class{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},Pme=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),H5;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(H5||={});var U5=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==H5.Silent&&t!==H5.Errors&&t!==H5.Warnings&&t!==H5.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new V5}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=H5.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=H5.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=H5.Info&&console.info(...t)}};U5._level=H5.Info,U5._emitterInstance=null;var W5=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},Fme=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},Ime=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(t instanceof Uint8Array)&&!(t instanceof W5)&&!(t instanceof Fme)&&!Pme(t))throw TypeError(`Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},Lme=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.primary!==void 0&&typeof e.primary!=`boolean`)throw TypeError(`disposition.primary must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},G5=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},K5=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],q5=[-1,1,2,3,4,5,6,8],Rme=e=>{let t=K5.indexOf(e.sampleRate),n=null;t===-1&&(t=15,n=e.sampleRate);let r=q5.indexOf(e.numberOfChannels);if(r===-1)throw TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let i=13;e.objectType>=32&&(i+=6),t===15&&(i+=24);let a=Math.ceil(i/8),o=new Uint8Array(a),s=new G5(o);return e.objectType<32?s.writeBits(5,e.objectType):(s.writeBits(5,31),s.writeBits(6,e.objectType-32)),s.writeBits(4,t),t===15&&s.writeBits(24,n),s.writeBits(4,r),o},J5=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Y5=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],X5=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],Z5=[...X5,...Y5],Q5=[`webvtt`],$5=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],e7=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],t7=[`dtsc`,`dtsh`,`dtsl`,`dtse`],zme=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=+(r.slice(-1)===`H`),s=Number(t[3])===8?0:1,c=t[4]?Number(t[4]):0,l=t[5]?Number(t[5][0]):1,u=t[5]?Number(t[5][1]):1,d=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(s<<6)+0+(c<<4)+(l<<3)+(u<<2)+d,0]},n7=/^pcm-([usf])(\d+)(be)?$/,r7=e=>{if(w5(Y5.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=n7.exec(e);w5(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?2**7:0}},i7=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:e7.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:t7.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:n7.test(e)?e:e===`webvtt`?`webvtt`:null,Bme=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...e7],Vme=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Hme=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ume=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Wme=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,a7=(e,t)=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!Bme.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectWidth!==void 0!=(e.decoderConfig.displayAspectHeight!==void 0))throw TypeError(`Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.`);if(e.decoderConfig.description!==void 0&&!F5(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(M5);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(N5);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(P5);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!Vme.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!Hme.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!Ume.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)){if(!Wme.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)}else if(e7.some(t=>e.decoderConfig.codec.startsWith(t))&&!e7.some(t=>e.decoderConfig.codec===t))throw TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${e7.join(`, `)}.`);if(t!==null&&i7(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},Gme=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],o7=(e,t)=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!Gme.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!F5(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if(e.decoderConfig.codec.startsWith(`dts`)){if(!t7.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${t7.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!Y5.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Y5.join(`, `)}).`);if(t!==null&&i7(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},Kme=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},qme=[48e3,44100,32e3],Jme=[24e3,22050,16e3],s7;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(s7||={});var c7;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(c7||={});var l7=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},Yme=e=>e&31,u7=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)};new Uint8Array([0,0,0,1]);var Xme=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:Ome(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},Zme=e=>{try{let t=[],n=[],r=[];for(let i of l7(e)){let a=e.subarray(i.offset,i.offset+i.length),o=Yme(a[0]);o===s7.SPS?t.push(a):o===s7.PPS?n.push(a):o===s7.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=$me(i);w5(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return U5._error(`Error building AVC Decoder Configuration Record:`,e),null}},Qme=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if(e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144){w5(e.chromaFormat!==null),w5(e.bitDepthLumaMinus8!==null),w5(e.bitDepthChromaMinus8!==null),w5(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},d7={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},$me=e=>{try{let t=new G5(u7(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let n=t.readAlignedByte(),r=t.readAlignedByte(),i=t.readAlignedByte();D5(t);let a=1,o=0,s=0,c=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=D5(t),a===3&&(c=t.readBits(1)),o=D5(t),s=D5(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(a===3?12:8);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(i!==0){let e=O5(t);i=(r+e+256)%256}r=i===0?r:i}}}D5(t);let l=D5(t);if(l===0)D5(t);else if(l===1){t.skipBits(1),O5(t),O5(t);let e=D5(t);for(let n=0;n<e;n++)O5(t)}D5(t),t.skipBits(1);let u=D5(t),d=D5(t),f=16*(u+1),p=16*(d+1),m=f,h=p,g=t.readBits(1);if(g||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e=D5(t),n=D5(t),r=D5(t),i=D5(t),o,s;if((c===0?a:0)===0)o=1,s=2-g;else{let e=a===3?1:2,t=a===1?2:1;o=e,s=t*(2-g)}m-=o*(e+n),h-=s*(r+i)}let _=2,v=2,y=2,b=0,x={num:1,den:1},S=null,C=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);if(e===255)x={num:t.readBits(16),den:t.readBits(16)};else{let t=d7[e];t&&(x=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),b=t.readBits(1),t.readBits(1)&&(_=t.readBits(8),v=t.readBits(8),y=t.readBits(8))),t.readBits(1)&&(D5(t),D5(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&f7(t);let n=t.readBits(1);n&&f7(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),D5(t),D5(t),D5(t),D5(t),S=D5(t),C=D5(t))}if(S===null){w5(C===null);let e=r&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&e)S=0,C=0;else{let e=u+1,t=d+1,n=(2-g)*t,r=$5.find(e=>e.level>=i)??T5($5),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);S=a,C=a}}return w5(C!==null),{profileIdc:n,constraintFlags:r,levelIdc:i,frameMbsOnlyFlag:g,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:s,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:h,pixelAspectRatio:x,colourPrimaries:_,matrixCoefficients:y,transferCharacteristics:v,fullRangeFlag:b,numReorderFrames:S,maxDecFrameBuffering:C}}catch(e){return U5._error(`Error parsing AVC SPS:`,e),null}},f7=e=>{let t=D5(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)D5(e),D5(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},p7=e=>e>>1&63,ehe=e=>{try{let t=new G5(u7(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=nhe(t,n);D5(t);let u=D5(t),d=0;u===3&&(d=t.readBits(1));let f=D5(t),p=D5(t),m=f,h=p;if(t.readBits(1)){let e=D5(t),n=D5(t),r=D5(t),i=D5(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=D5(t),_=D5(t);D5(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)D5(t),y=D5(t),D5(t);if(D5(t),D5(t),D5(t),D5(t),D5(t),D5(t),t.readBits(1)&&t.readBits(1)&&rhe(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),D5(t),D5(t),t.skipBits(1)),ihe(t,D5(t)),t.readBits(1)){let e=D5(t);for(let n=0;n<e;n++)D5(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,w=0,T={num:1,den:1};if(t.readBits(1)){let e=ohe(t,n);T=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,w=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:T,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:w}}catch(e){return U5._error(`Error parsing HEVC SPS:`,e),null}},the=e=>{try{let t=[],n=[],r=[],i=[];for(let a of l7(e)){let o=e.subarray(a.offset,a.offset+a.length),s=p7(o[0]);s===c7.VPS_NUT?t.push(o):s===c7.SPS_NUT?n.push(o):s===c7.PPS_NUT?r.push(o):(s===c7.PREFIX_SEI_NUT||s===c7.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=ehe(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new G5(u7(e));t.skipBits(16),D5(t),D5(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),D5(t),D5(t),O5(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&D5(t),O5(t),O5(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:c7.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:c7.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:c7.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:p7(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return U5._error(`Error building HEVC Decoder Configuration Record:`,e),null}},nhe=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},rhe=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))D5(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&O5(e);for(let t=0;t<n;t++)O5(e)}},ihe=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=ahe(e,r,t,n)},ahe=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(D5(e)+1):t-1,e.readBits(1),D5(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=D5(e),n=D5(e);for(let n=0;n<t;n++)D5(e),e.readBits(1);for(let t=0;t<n;t++)D5(e),e.readBits(1);i=t+n}return i},ohe=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=d7[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(D5(e),D5(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(D5(e),D5(e),D5(e),D5(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&D5(e),e.readBits(1)&&she(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=D5(e),D5(e),D5(e),D5(e),D5(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},she=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?D5(e):o=e.readBits(1)===1;let s=1;o||(s=D5(e)+1),r&&m7(e,s,a),i&&m7(e,s,a)}},m7=(e,t,n)=>{for(let r=0;r<t;r++)D5(e),D5(e),n&&(D5(e),D5(e)),e.readBits(1)},che=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},lhe;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(lhe||={});var uhe=e=>{let t=A5(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},dhe;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(dhe||={});var fhe=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new G5(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}};new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var phe=[1,2,3,6],mhe=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new G5(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=phe[o],d;return d=i<3?qme[i]/1e3:Jme[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},hhe=8,ghe=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],_he=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],vhe=[16,16,20,20,0,24,24,0],h7=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],yhe=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],bhe=8,g7=[32e3,44100,48e3,0],xhe=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],She=[512,1024,2048,4096],Che=e=>{let t=whe(e),n=A5(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=The(e.subarray(r));if(!t)break;i??=t,r+=t.frameSize}if(t)return{frameSize:i?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:i!==null};if(!i?.asset)return null;let{asset:a}=i;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},whe=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new G5(e);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==31)return null;let n=t.readBits(1),r=t.readBits(7)+1;if(r%hhe!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=h7.length)return null;let o=ghe[t.readBits(4)];if(o===0)return null;let s=_he[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),n&&t.skipBits(16),t.skipBits(7);let l=vhe[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:h7[a]+ +!!u,sampleCount:r*32,channelLayout:yhe[a]|(u?bhe:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},The=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new G5(e);t.skipBits(32),t.skipBits(8);let n=t.readBits(2),r=t.readBits(1),i=8+4*r,a=16+4*r;t.skipBits(i);let o=t.readBits(a)+1,s={frameSize:o,asset:null};if(!t.readBits(1))return s;let c=g7[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,f=[];for(let e=0;e<u;e++)f.push(t.readBits(n+1));for(let e of f)t.skipBits(8*kme(e));if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,n=t.readBits(2)+1;t.skipBits(n*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let p=t.readBits(5)+1,m=xhe[t.readBits(4)],h=t.readBits(8)+1,g=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;g=t.readBits(e)}return c===0||t.getBitsLeft()<0?s:{frameSize:o,asset:{sampleRate:m,numberOfChannels:h,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:p}}},Ehe=e=>{let t=new Uint8Array(20),n=A5(t);n.setUint32(0,e.sampleRate),n.setUint32(4,e.bitRate),n.setUint32(8,e.bitRate),t[12]=e.pcmResolution;let r=e.core&&!e.hasExtensions?1:0,i=new G5(t);return i.seekToByte(13),i.writeBits(2,Math.max(She.indexOf(e.sampleCount),0)),i.writeBits(5,r),i.writeBits(1,+!!e.core?.lfePresent),i.writeBits(6,e.core?.amode??0),i.writeBits(14,e.core?e.core.frameSize-1:0),i.writeBits(1,0),i.writeBits(3,0),i.writeBits(16,e.channelLayout),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(5,0),t},_7=new Uint8Array,v7=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===_7&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===_7}get microsecondTimestamp(){return Math.trunc(R5*this.timestamp)}get microsecondDuration(){return Math.trunc(R5*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`EncodedAudioChunk is not available in this environment.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},Dhe=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},y7=e=>{let t=e.filePos,n=new G5(Ahe(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},Ohe=n(((e,t)=>{t.exports={}})),b7=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,A5(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},khe=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},Ahe=(e,t)=>{khe(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},jhe=class{constructor(e){this.mutex=new I5,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},x7=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Mhe=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},S7=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);w5(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},C7=new Uint8Array(8),w7=new DataView(C7.buffer),T7=e=>[(e%256+256)%256],E7=e=>(w7.setUint16(0,e,!1),[C7[0],C7[1]]),D7=e=>(w7.setInt16(0,e,!1),[C7[0],C7[1]]),O7=e=>(w7.setUint32(0,e,!1),[C7[1],C7[2],C7[3]]),$=e=>(w7.setUint32(0,e,!1),[C7[0],C7[1],C7[2],C7[3]]),k7=e=>(w7.setInt32(0,e,!1),[C7[0],C7[1],C7[2],C7[3]]),A7=e=>(w7.setUint32(0,Math.floor(e/2**32),!1),w7.setUint32(4,e,!1),[C7[0],C7[1],C7[2],C7[3],C7[4],C7[5],C7[6],C7[7]]),Nhe=e=>(w7.setInt32(0,Math.floor(e/2**32),!1),w7.setUint32(4,e,!1),[C7[0],C7[1],C7[2],C7[3],C7[4],C7[5],C7[6],C7[7]]),j7=e=>(w7.setInt16(0,2**8*e,!1),[C7[0],C7[1]]),M7=e=>(w7.setInt32(0,2**16*e,!1),[C7[0],C7[1],C7[2],C7[3]]),N7=e=>(w7.setInt32(0,2**30*e,!1),[C7[0],C7[1],C7[2],C7[3]]),P7=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},F7=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},I7=e=>{let t=Math.PI/180*e,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},L7=I7(0),R7=e=>[M7(e[0]),M7(e[1]),N7(e[2]),M7(e[3]),M7(e[4]),N7(e[5]),M7(e[6]),M7(e[7]),N7(e[8])],z7=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),B7=(e,t,n,r,i)=>z7(e,[T7(t),O7(n),r??[]],i),Phe=e=>e.isQuickTime?z7(`ftyp`,[F7(`qt `),$(512),F7(`qt `)]):e.fragmented?e.cmaf?z7(`ftyp`,[F7(`iso5`),$(512),F7(`iso5`),F7(`iso6`),F7(`mp41`),F7(`cmfc`),F7(`dash`)]):z7(`ftyp`,[F7(`iso5`),$(512),F7(`iso5`),F7(`iso6`),F7(`mp41`)]):z7(`ftyp`,[F7(`isom`),$(512),F7(`isom`),e.holdsAvc?F7(`avc1`):[],F7(`mp41`)]),V7=()=>z7(`styp`,[F7(`iso5`),$(0),F7(`iso5`),F7(`iso6`),F7(`mp41`),F7(`cmfc`),F7(`dash`)]),H7=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),B7(`sidx`,1,0,[$(1),$(d9),A7(f9(e.minWrittenTimestamp,d9)),A7(0),E7(0),E7(1),$(t&2147483647),$(f9(n,d9)),$(0)])},U7=e=>({type:`mdat`,largeSize:e}),Fhe=e=>({type:`free`,size:e}),W7=e=>z7(`moov`,void 0,[Ihe(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Lhe(t,e.creationTime)),e.isFragmented?bge(e.trackDatas):null,Nge(e)]),Ihe=(e,t)=>{let n=Math.max(0,...t.map(e=>f9(G7(e),d9)+f9(e.startTimestampOffset??0,d9))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!E5(e)||!E5(n),a=i?A7:$;return B7(`mvhd`,+i,0,[a(e),a(e),$(d9),a(n),M7(1),j7(1),Array(10).fill(0),R7(L7),Array(24).fill(0),$(r)])},G7=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},Lhe=(e,t)=>{let n=Wge(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return z7(`trak`,void 0,[Rhe(e,t),r?zhe(e,e.startTimestampOffset):null,Bhe(e,t),n.name===void 0?null:z7(`udta`,void 0,[z7(`name`,[...j5.encode(n.name)])])])},Rhe=(e,t)=>{let n=f9(G7(e),d9)+f9(e.startTimestampOffset??0,d9),r=!E5(t)||!E5(n),i=r?A7:$,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=I7(t??0)}else a=L7;let o=2;e.track.metadata.disposition?.default!==!1&&(o|=1);let s=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:L5(e);return B7(`tkhd`,+r,o,[i(t),i(t),$(e.track.id),$(0),i(n),Array(8).fill(0),E7(0),E7(s),j7(+(e.type===`audio`)),E7(0),R7(a),M7(e.type===`video`?e.info.width:0),M7(e.type===`video`?e.info.height:0)])},zhe=(e,t)=>{let n=f9(t,d9),r=f9(G7(e),d9),i=!E5(n)||!E5(r),a=i?A7:$,o=i?Nhe:k7;return z7(`edts`,void 0,[B7(`elst`,+!!i,0,[$(2),a(n),o(-1),M7(1),a(r),o(0),M7(1)])])},Bhe=(e,t)=>z7(`mdia`,void 0,[Vhe(e,t),K7(!0,Hhe[e.type],Uhe[e.type]),Whe(e)]),Vhe=(e,t)=>{let n=f9(G7(e),e.timescale),r=!E5(t)||!E5(n),i=r?A7:$;return B7(`mdhd`,+r,0,[i(t),i(t),$(e.timescale),i(n),E7(i9(e.track.metadata.languageCode??`und`)),E7(0)])},Hhe={video:`vide`,audio:`soun`,subtitle:`text`},Uhe={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},K7=(e,t,n,r=`\0\0\0\0`)=>B7(`hdlr`,0,0,[e?F7(`mhlr`):$(0),F7(t),F7(r),$(0),$(0),F7(n,!0)]),Whe=e=>z7(`minf`,void 0,[Ghe[e.type](),Khe(),Yhe(e)]),Ghe={video:()=>B7(`vmhd`,0,1,[E7(0),E7(0),E7(0),E7(0)]),audio:()=>B7(`smhd`,0,0,[E7(0),E7(0)]),subtitle:()=>B7(`nmhd`,0,0)},Khe=()=>z7(`dinf`,void 0,[qhe()]),qhe=()=>B7(`dref`,0,0,[$(1)],[Jhe()]),Jhe=()=>B7(`url `,0,1),Yhe=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return z7(`stbl`,void 0,[Xhe(e),pge(e),t?vge(e):null,t?yge(e):null,hge(e),gge(e),_ge(e),mge(e)])},Xhe=e=>{let t;if(e.type===`video`)t=Zhe(Lge(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=r9(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);w5(n),t=rge(n,e)}else e.type===`subtitle`&&(t=dge(Bge[e.track.source._codec],e));return w5(t),B7(`stsd`,0,0,[$(1)],[t])},Zhe=(e,t)=>z7(e,[[,,,,,,].fill(0),E7(1),E7(0),E7(0),Array(12).fill(0),E7(t.info.width),E7(t.info.height),$(4718592),$(4718592),$(0),E7(1),T7(10),F7(`Mediabunny`),Array(21).fill(0),E7(t.info.hasAlphaChannel?32:24),D7(65535)],[Rge[t.track.source._codec]?.(t)??null,Qhe(t),Eme(t.info.decoderConfig.colorSpace)?$he(t):null]),Qhe=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:z7(`pasp`,[$(e.info.pixelAspectRatio.num),$(e.info.pixelAspectRatio.den)]),$he=e=>z7(`colr`,[F7(e.muxer.isQuickTime?`nclc`:`nclx`),E7(M5[e.info.decoderConfig.colorSpace.primaries]),E7(N5[e.info.decoderConfig.colorSpace.transfer]),E7(P5[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:T7(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),ege=e=>e.info.decoderConfig&&z7(`avcC`,[...k5(e.info.decoderConfig.description)]),tge=e=>e.info.decoderConfig&&z7(`hvcC`,[...k5(e.info.decoderConfig.description)]),q7=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?M5[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?N5[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?P5[t.colorSpace.matrix]:2;return B7(`vpcC`,1,0,[T7(r),T7(i),T7(c),T7(l),T7(u),T7(d),E7(0)])},nge=e=>z7(`av1C`,zme(e.info.decoderConfig.codec)),rge=(e,t)=>{let n=0,r,i=16,a=Y5.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=r7(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),E7(1),E7(n),E7(0),$(0),E7(t.info.numberOfChannels),E7(i),E7(0),E7(0),E7(t.info.sampleRate<2**16?t.info.sampleRate:0),E7(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),E7(1),E7(n),E7(0),$(0),E7(t.info.numberOfChannels),E7(Math.min(i,16)),D7(e),E7(0),E7(t.info.sampleRate<2**16?t.info.sampleRate:0),E7(0),a?[$(1),$(i/8),$(t.info.numberOfChannels*i/8)]:[$(0),$(0),$(0)],$(2)]}return z7(e,r,[zge(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},J7=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...T7(t),...T7(21),...O7(0),...$(0),...$(0)];if(e.info.decoderConfig.description){let t=k5(e.info.decoderConfig.description);n=[...n,...T7(5),...P7(t.byteLength),...t]}return n=[...E7(1),...T7(0),...T7(4),...P7(n.length),...n,...T7(6),...T7(1),...T7(2)],n=[...T7(3),...P7(n.length),...n],B7(`esds`,0,0,n)},Y7=e=>z7(`wave`,void 0,[ige(e),age(e),z7(`\0\0\0\0`)]),ige=e=>z7(`frma`,[F7(r9(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),age=e=>{let{littleEndian:t}=r7(e.track.source._codec);return z7(`enda`,[E7(+t)])},oge=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){w5(s.byteLength>=18);let e=uhe(k5(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return z7(`dOps`,[T7(0),T7(t),E7(n),$(r),D7(i),T7(a),...o])},sge=e=>{let t=e.info.decoderConfig?.description;return w5(t),B7(`dfLa`,0,0,[...k5(t).subarray(4)])},X7=e=>{let{littleEndian:t,sampleSize:n}=r7(e.track.source._codec);return B7(`pcmC`,0,0,[T7(+t),T7(8*n)])},cge=e=>{w5(e.info.primingPacket);let t=fhe(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=new Uint8Array(3),r=new G5(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),z7(`dac3`,[...n])},lge=e=>{w5(e.info.primingPacket);let t=mhe(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new G5(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return z7(`dec3`,[...i])},uge=e=>{w5(e.info.primingPacket);let t=Che(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return z7(`ddts`,[...Ehe(t)])},dge=(e,t)=>z7(e,[[,,,,,,].fill(0),E7(1)],[Vge[t.track.source._codec](t)]),fge=e=>z7(`vttC`,[...j5.encode(e.info.config.description)]),pge=e=>B7(`stts`,0,0,[$(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[$(e.sampleCount),$(e.sampleDelta)])]),mge=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return B7(`stss`,0,0,[$(t.length),t.map(([e])=>$(e+1))])},hge=e=>B7(`stsc`,0,0,[$(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[$(e.firstChunk),$(e.samplesPerChunk),$(1)])]),gge=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=r7(e.track.source._codec);return B7(`stsz`,0,0,[$(t*e.info.numberOfChannels),$(e.samples.reduce((t,n)=>t+f9(n.duration,e.timescale),0))])}return B7(`stsz`,0,0,[$(0),$(e.samples.length),e.samples.map(e=>$(e.size))])},_ge=e=>e.finalizedChunks.length>0&&T5(e.finalizedChunks).offset>=2**32?B7(`co64`,0,0,[$(e.finalizedChunks.length),e.finalizedChunks.map(e=>A7(e.offset))]):B7(`stco`,0,0,[$(e.finalizedChunks.length),e.finalizedChunks.map(e=>$(e.offset))]),vge=e=>B7(`ctts`,1,0,[$(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[$(e.sampleCount),k7(e.sampleCompositionTimeOffset)])]),yge=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;w5(e.compositionTimeOffsetTable.length>0),w5(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,f9(n.timestamp,e.timescale)),i=Math.max(i,f9(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:B7(`cslg`,0,0,[k7(a),k7(t),k7(n),k7(r),k7(i)])},bge=e=>z7(`mvex`,void 0,e.map(xge)),xge=e=>B7(`trex`,0,0,[$(e.track.id),$(1),$(0),$(0),$(0)]),Z7=(e,t)=>z7(`moof`,void 0,[Sge(e),...t.map(Cge)]),Sge=e=>B7(`mfhd`,0,0,[$(e)]),Q7=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Cge=e=>z7(`traf`,void 0,[wge(e),Tge(e),Ege(e)]),wge=e=>{w5(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:Q7(n)};return B7(`tfhd`,0,t,[$(e.track.id),$(r.duration),$(r.size),$(r.flags)])},Tge=e=>(w5(e.currentChunk),B7(`tfdt`,1,0,[A7(f9(e.currentChunk.startTimestamp,e.timescale))])),Ege=e=>{w5(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Q7),i=e.currentChunk.samples.map(t=>f9(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,B7(`trun`,1,m,[$(e.currentChunk.samples.length),$(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?$(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?$(t[a]):[],d?$(n[a]):[],f?$(r[a]):[],p?k7(i[a]):[]])])},Dge=e=>z7(`mfra`,void 0,[...e.map(Oge),kge()]),Oge=e=>B7(`tfra`,1,0,[$(e.track.id),$(63),$(e.finalizedChunks.length),e.finalizedChunks.map(t=>[A7(f9(t.samples[0].timestamp,e.timescale)),A7(t.moofOffset),$(t.trafIndex+1),$(1),$(1)])]),kge=()=>B7(`mfro`,0,0,[$(0)]),Age=()=>z7(`vtte`),jge=(e,t,n,r,i)=>z7(`vttc`,void 0,[i===null?null:z7(`vsid`,[k7(i)]),n===null?null:z7(`iden`,[...j5.encode(n)]),t===null?null:z7(`ctim`,[...j5.encode(Mhe(t))]),r===null?null:z7(`sttg`,[...j5.encode(r)]),z7(`payl`,[...j5.encode(e)])]),Mge=e=>z7(`vtta`,[...j5.encode(e)]),Nge=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Fge(r);e&&t.push(e)}else if(n===`mdta`){let e=Ige(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&Pge(t,e.output._metadataTags);return t.length===0?null:z7(`udta`,void 0,t)},Pge=(e,t)=>{for(let{key:n,value:r}of z5(t))switch(n){case`title`:e.push($7(`©nam`,r));break;case`description`:e.push($7(`©des`,r));break;case`artist`:e.push($7(`©ART`,r));break;case`album`:e.push($7(`©alb`,r));break;case`albumArtist`:e.push($7(`albr`,r));break;case`genre`:e.push($7(`©gen`,r));break;case`date`:e.push($7(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push($7(`©cmt`,r));break;case`lyrics`:e.push($7(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:L5(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push($7(n,r)):r instanceof Uint8Array&&e.push(z7(n,Array.from(r))))}},$7=(e,t)=>{let n=j5.encode(t);return z7(e,[E7(n.length),E7(i9(`und`)),Array.from(n)])},e9={"image/jpeg":13,"image/png":14,"image/bmp":27},t9=(e,t)=>{let n=[];for(let{key:r,value:i}of z5(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:n9(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:n9(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:n9(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:n9(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:n9(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:n9(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:n9(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:n9(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:n9(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:z7(`data`,[$(e9[e.mimeType]??0),$(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:n9(t)})}else n.push({key:`trkn`,value:z7(`data`,[$(0),$(0),E7(0),E7(i),E7(e.tracksTotal??0),E7(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:z7(`data`,[$(0),$(0),E7(0),E7(i),E7(e.discsTotal??0),E7(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:L5(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:n9(i)}):i instanceof Uint8Array?n.push({key:r,value:z7(`data`,[$(0),$(0),Array.from(i)])}):i instanceof W5&&n.push({key:r,value:z7(`data`,[$(e9[i.mimeType]??0),$(0),Array.from(i.data)])}))}return n},Fge=e=>{let t=t9(e,!1);return t.length===0?null:B7(`meta`,0,0,void 0,[K7(!1,`mdir`,``,`appl`),z7(`ilst`,void 0,t.map(e=>z7(e.key,void 0,[e.value])))])},Ige=e=>{let t=t9(e,!0);return t.length===0?null:z7(`meta`,void 0,[K7(!1,`mdta`,``),B7(`keys`,0,0,[$(t.length)],t.map(e=>z7(`mdta`,[...j5.encode(e.key)]))),z7(`ilst`,void 0,t.map((e,t)=>z7(String.fromCharCode(...$(t+1)),void 0,[e.value])))])},n9=e=>z7(`data`,[$(1),$(0),...j5.encode(e)]),Lge=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},Rge={avc:ege,hevc:tge,vp8:q7,vp9:q7,av1:nge,prores:null},r9=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},zge=(e,t)=>{switch(e){case`aac`:return J7;case`mp3`:return J7;case`opus`:return oge;case`vorbis`:return J7;case`flac`:return sge;case`ac3`:return cge;case`eac3`:return lge;case`dts`:return uge}if(t)switch(e){case`pcm-s24`:return Y7;case`pcm-s24be`:return Y7;case`pcm-s32`:return Y7;case`pcm-s32be`:return Y7;case`pcm-f32`:return Y7;case`pcm-f32be`:return Y7;case`pcm-f64`:return Y7;case`pcm-f64be`:return Y7}else switch(e){case`pcm-s16`:return X7;case`pcm-s16be`:return X7;case`pcm-s24`:return X7;case`pcm-s24be`:return X7;case`pcm-s32`:return X7;case`pcm-s32be`:return X7;case`pcm-f32`:return X7;case`pcm-f32be`:return X7;case`pcm-f64`:return X7;case`pcm-f64be`:return X7}return null},Bge={webvtt:`wvtt`},Vge={webvtt:fge},i9=e=>{w5(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},a9=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){w5(!this.started),this.target._start(),this.started=!0}write(e){w5(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return w5(this.started&&!this.finalized),this.target._flush()}async finalize(){w5(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};Ohe();var o9=class extends V5{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new Hge(this,e)}},s9=2**16,c9=2**32,l9=class extends o9{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(s9,{maxByteLength:c9})}catch{this._buffer=new ArrayBuffer(s9),this._supportsResize=!1}else this._buffer=new ArrayBuffer(s9);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>c9)throw Error(`ArrayBuffer exceeded maximum size of ${c9} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},Hge=class extends o9{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},u9=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},d9=57600,Uge=2082844800,Wge=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},f9=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Gge=class extends jhe{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new l9,this.auxWriter=new a9(this.auxTarget,!1),this.auxBoxWriter=new S7(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Dme(),this.creationTime=Math.floor(Date.now()/1e3)+Uge,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof y9,this.isCmaf=t instanceof v9,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof v9?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof l9:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new S7(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof l9&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new a9(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new S7(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(w5(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Phe({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(w5(this.writer),w5(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=U7(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return Dhe({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;a7(n,e.source._codec),w5(n),w5(n.decoderConfig);let i={...n.decoderConfig};w5(i.codedWidth!==void 0),w5(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=Zme(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Qme(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=the(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=che(e),a=!0}let o=Mme(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:Nme({num:s*i.codedHeight,den:c*i.codedWidth}),u=i.codec===`ap4h`||i.codec===`ap4x`,d={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a,hasAlphaChannel:u},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;o7(n,e.source._codec),w5(n),w5(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=y7(b7.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=K5[e.samplingFrequencyIndex],r=q5[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=Rme({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),a=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Y5.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,primingPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;Kme(t),w5(t),w5(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...l7(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=Xme(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=y7(b7.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=r7(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=f9(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=r7(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let r of e.cueQueue)w5(r.timestamp<=t),w5(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=Age();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;x7.lastIndex=0;let r=x7.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=Mge(n.notes);this.auxBoxWriter.writeBox(e)}let c=jge(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:f9(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=f9(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=T5(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=f9(r.timestamp-r.decodeTimestamp,e.timescale),a=f9(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){w5(e.lastSample);let t=f9(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(w5(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=T5(e.timeToSampleTable);if(w5(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=T5(e.compositionTimeOffsetTable);w5(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=f9(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,w5(e.lastSample),w5(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){w5(t.type===`key`);let n=f9(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(w5(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),w5(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(w5(!this.isFragmented),w5(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+f9(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||T5(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)w5(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(w5(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(w5(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;w5(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=W7(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){w5(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new S7(this.writer);let e=this.boxWriter.measureBox(V7()),t=this.boxWriter.measureBox(H7(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}w5(this.writer),w5(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=Z7(n,t),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e=0;e<t.length;e++){let n=t[e];n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e;for(let e of n.currentChunk.samples)o+=e.size;s=Math.min(s,n.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=Z7(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}w5(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=U7(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){w5(this.writer),w5(this.boxWriter),this.ensureOneEnabledTrack();let e=W7(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;w5(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=U7(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){w5(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;w5(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){w5(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas)if(await this.finalizeCurrentChunk(e),e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}if(w5(this.writer),w5(this.boxWriter),this.fastStart===`in-memory`){this.mdat=U7(!1);let e;for(let t=0;t<2;t++){let t=W7(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)w5(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=W7(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)w5(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented)if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(V7()),this.boxWriter.writeBox(H7(this,e))}else{let e=this.writer.getPos(),t=Dge(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{w5(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);w5(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=W7(this);if(this.fastStart===`reserve`){w5(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Fhe(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}},p9=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},m9=class extends p9{constructor(e){if(super(),this._connectedTrack=null,!J5.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${J5.join(`, `)}.`);this._codec=e}},Kge=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},qge=class extends m9{constructor(e){super(e)}add(e,t){if(!(e instanceof v7))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),Kge(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},Jge=class extends p9{constructor(e){if(super(),this._connectedTrack=null,!Z5.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${Z5.join(`, `)}.`);this._codec=e}},Yge=class extends p9{constructor(e){if(super(),this._connectedTrack=null,!Q5.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Q5.join(`, `)}.`);this._codec=e}},h9=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>J5.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Z5.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Q5.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},g9=class extends h9{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Gge(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},_9=class extends g9{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...J5,...X5,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Q5]}_codecUnsupportedHint(e){return new y9().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},v9=class extends g9{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...J5,...X5,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Q5]}},y9=class extends g9{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...J5,...Z5]}_codecUnsupportedHint(e){return new _9().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},b9=[`video`,`audio`,`subtitle`],x9=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=B5(this.metadata.group),r=B5(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},Xge=class extends x9{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Zge=class extends x9{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Qge=class extends x9{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},S9=class e{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},C9=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!jme(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&Lme(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.group!==void 0&&!(e.group instanceof S9)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof S9))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},$ge=class extends V5{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new S9,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new I5,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof h9))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof o9||e.target instanceof u9))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof o9&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof o9)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof o9&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){w5(this._target instanceof u9);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof o9))throw TypeError(`getTarget must return a Target.`);return e};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){w5(this._target instanceof u9);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(w5(this._initTarget!==null),this._initTarget instanceof o9)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof o9)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new a9(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof m9))throw TypeError(`source must be a VideoSource.`);if(C9(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.decoderConfig!==void 0&&a7({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof v7))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Xge(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Jge))throw TypeError(`source must be an AudioSource.`);if(C9(t),t.decoderConfig!==void 0&&o7({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof v7))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Zge(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Yge))throw TypeError(`source must be a SubtitleSource.`);C9(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Qge(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Ime(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of b9)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of b9){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(U5._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return U5._warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&U5._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(U5._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}},e_e=e=>{if(e.startsWith(`avc1`))return`avc`;throw RangeError(`unsupported MP4 video codec: ${e}`)};async function t_e({chunks:e,codec:t,decoderConfig:n,signal:r=null}){if(!Array.isArray(e)||e.length<1)throw RangeError(`MP4 needs at least one encoded frame`);if(!n||typeof n!=`object`)throw TypeError(`MP4 needs a decoder config`);if(t.startsWith(`avc1`)&&!n.description)throw Error(`H.264 MP4 needs the encoder's AVC decoder configuration`);let i=new l9,a=new $ge({format:new _9({fastStart:`in-memory`}),target:i}),o=new qge(e_e(t));a.addVideoTrack(o);try{r?.throwIfAborted(),await a.start();for(let t=0;t<e.length;t+=1){r?.throwIfAborted();let i=e[t],a=new v7(i.data,i.type,i.timestamp/1e6,i.duration/1e6,t);await o.add(a,t===0?{decoderConfig:n}:void 0)}if(r?.throwIfAborted(),await a.finalize(),!i.buffer)throw Error(`MP4 muxer finalized without output`);return new Blob([i.buffer],{type:`video/mp4`})}catch(e){throw a.state!==`finalized`&&a.state!==`canceled`&&await a.cancel(),e}}var n_e=Object.freeze([Object.freeze({codec:`avc1.640032`,avc:Object.freeze({format:`avc`})}),Object.freeze({codec:`avc1.4d0032`,avc:Object.freeze({format:`avc`})}),Object.freeze({codec:`avc1.420032`,avc:Object.freeze({format:`avc`})})]);function r_e(e,t){let n=Math.round(e),r=Math.round(t);if(!Number.isFinite(e)||!Number.isFinite(t)||n<0||r<n)throw RangeError(`export frame range must be an inclusive non-negative range`);return{startFrame:n,endFrame:r,frameCount:r-n+1}}async function i_e(e,t=globalThis.crypto?.subtle){if(!t)throw Error(`Web Crypto is unavailable; pixel hashes cannot be computed`);return[...new Uint8Array(await t.digest(`SHA-256`,e))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function a_e(e,t,n,r){let i=n*4;for(let n=0;n<r;n+=1){let a=(r-1-n)*i;t.set(e.subarray(a,a+i),n*i)}}function w9(e,t){try{Object.defineProperty(e,"exportFailureCode",{value:e?.name===`AbortError`?`aborted`:t,configurable:!0})}catch{}return e}function T9(e,t){return t?new Promise((n,r)=>{let i=()=>{a(),r(E9())},a=()=>t.removeEventListener(`abort`,i);t.aborted?i():t.addEventListener(`abort`,i,{once:!0}),Promise.resolve(e).then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}async function o_e(e,t,n,r,i){for(let a of n_e){if(i?.aborted)throw E9();let o={...a,width:e,height:t,framerate:n,bitrate:Math.max(2e6,Math.round(e*t*n*.24)),latencyMode:`quality`};try{let e=await T9(r.isConfigSupported(o),i);if(e.supported)return e.config}catch(e){if(e?.name===`AbortError`)throw e}}throw i?.aborted?E9():w9(Error(`This browser has no H.264 WebCodecs encoder for MP4 export`),`unsupported_codec`)}function E9(){return new DOMException(`Offscreen export was cancelled`,`AbortError`)}async function s_e({startFrame:e,endFrame:t,fps:n,width:r,height:i,capture:a,signal:o,passKind:s=null,onFrame:c,onPhase:l,VideoEncoderClass:u=globalThis.VideoEncoder,VideoFrameClass:d=globalThis.VideoFrame}){if(o?.aborted)throw E9();let f=r_e(e,t);if(!Number.isFinite(n)||n<=0)throw RangeError(`export fps must be positive`);if(!Number.isInteger(r)||r<1||!Number.isInteger(i)||i<1)throw RangeError(`invalid export dimensions`);if(typeof a!=`function`)throw TypeError(`export capture must be a function`);if(!u||!d)throw w9(Error(`This browser does not support WebCodecs video export`),`unsupported_codec`);let p=await o_e(r,i,n,u,o);if(o?.aborted)throw E9();let m=[],h=null,g=[],_=null,v=null,y=`encode_failed`,b=()=>{try{v&&v.state!==`closed`&&v.close()}catch{}};try{if(v=new u({output(e,t){try{let r=new Uint8Array(e.byteLength);e.copyTo(r),m.push({timestamp:e.timestamp,duration:e.duration??Math.round(1e6/n),type:e.type,data:r}),!h&&t?.decoderConfig&&(h=t.decoderConfig)}catch(e){_=e}},error(e){_=e}}),o?.addEventListener(`abort`,b,{once:!0}),o?.aborted||(l?.({phase:`encoding`,cancellable:!0}),o?.aborted))throw E9();let e=new Uint8ClampedArray(r*i*4),t=1e6/n,x=Math.max(1,Math.round(n*2));v.configure(p);for(let n=0;n<f.frameCount;n+=1){if(o?.aborted)throw E9();let l=f.startFrame+n;y=`render_failed`;let u=a(l,s);if(!(u instanceof Uint8Array)||u.byteLength!==e.byteLength)throw Error(`frame ${l} returned ${u?.byteLength??0} RGBA bytes; expected ${e.byteLength}`);let p=await T9(i_e(u),o);if(g.push(p),a_e(u,e,r,i),y=`encode_failed`,o?.aborted)throw E9();let m=new d(e,{format:`RGBA`,codedWidth:r,codedHeight:i,timestamp:Math.round(n*t),duration:Math.round(t)});try{v.encode(m,{keyFrame:n%x===0})}finally{m.close()}if(_)throw _;v.encodeQueueSize>4&&await T9(v.flush(),o),c?.({frame:l,index:n,frameCount:f.frameCount,hash:p})}if(o?.aborted||(l?.({phase:`finalizing`,stage:`flush`,cancellable:!0}),o?.aborted)||(await T9(v.flush(),o),o?.aborted))throw E9();if(_)throw _;if(v.close(),m.length!==f.frameCount)throw Error(`WebCodecs emitted ${m.length} frames for ${f.frameCount} inputs`);l?.({phase:`finalizing`,stage:`mux`,cancellable:!1});let S=await t_e({chunks:m,codec:p.codec,decoderConfig:h??{codec:p.codec,codedWidth:r,codedHeight:i},signal:o});if(o?.aborted)throw E9();return{...f,fps:n,width:r,height:i,codec:p.codec,mimeType:S.type,encodedFrameCount:m.length,hashes:g,blob:S}}catch(e){throw w9(e,y)}finally{o?.removeEventListener(`abort`,b),b()}}var D9=e=>Number.isFinite(e)?e:null;function O9({shot:e=null,stage:t=null,cast:n=[],fps:r=null,aspectKey:i=null,size:a=null,frame:o=null,shotIndex:s=null,lens:c=null}={}){let l=e?.camera??null;return{focalMm:D9(l?.focalMm)??D9(c?.focalMm),fovDeg:D9(l?.fovDeg)??D9(c?.fovDeg),aspect:typeof i==`string`&&i?i:null,size:{width:D9(a?.width),height:D9(a?.height)},cameraMove:{dolly:!!l?.dollyTiming,crane:!!l?.craneHeight,rail:!!l?.railFollow&&l.railFollow.mode!==`off`},keyLight:t?.keyLight??null,cast:(Array.isArray(n)?n:[]).map(e=>({name:e?.name??e?.subject??null,model:e?.model??null})),frameRange:{start:D9(e?.startFrame),end:D9(e?.endFrame)},fps:D9(r),shotIndex:Number.isInteger(s)&&s>=0?s:null,shotTitle:typeof e?.name==`string`&&e.name?e.name:null,targetModel:e?.targetModel??null,frame:D9(o)}}var c_e=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function l_e(e){let t=4294967295;for(let n=0;n<e.length;n++)t=c_e[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}var k9=new TextEncoder,A9=0,j9=23585,M9=2048,N9=0,P9=20;function F9(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function I9(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function L9(e){if(!Array.isArray(e))throw TypeError(`buildZip expects an array of { name, data } entries`);let t=e.map(e=>{let t=k9.encode(e.name),n=typeof e.data==`string`?k9.encode(e.data):e.data;if(!(n instanceof Uint8Array))throw TypeError(`entry "${e.name}" data must be a Uint8Array or string`);return{nameBytes:t,data:n,crc:l_e(n)}}),n=t.reduce((e,t)=>e+30+t.nameBytes.length+t.data.length,0),r=t.reduce((e,t)=>e+46+t.nameBytes.length,0),i=new Uint8Array(n+r+22),a=0,o=[];for(let{nameBytes:e,data:n,crc:r}of t)o.push(a),I9(i,a,67324752),F9(i,a+4,P9),F9(i,a+6,M9),F9(i,a+8,N9),F9(i,a+10,A9),F9(i,a+12,j9),I9(i,a+14,r),I9(i,a+18,n.length),I9(i,a+22,n.length),F9(i,a+26,e.length),F9(i,a+28,0),i.set(e,a+30),a+=30+e.length,i.set(n,a),a+=n.length;let s=a;for(let e=0;e<t.length;e++){let{nameBytes:n,data:r,crc:s}=t[e];I9(i,a,33639248),F9(i,a+4,P9),F9(i,a+6,P9),F9(i,a+8,M9),F9(i,a+10,N9),F9(i,a+12,A9),F9(i,a+14,j9),I9(i,a+16,s),I9(i,a+20,r.length),I9(i,a+24,r.length),F9(i,a+28,n.length),F9(i,a+30,0),F9(i,a+32,0),F9(i,a+34,0),F9(i,a+36,0),I9(i,a+38,0),I9(i,a+42,o[e]),i.set(n,a+46),a+=46+n.length}let c=a-s;return I9(i,a,101010256),F9(i,a+4,0),F9(i,a+6,0),F9(i,a+8,t.length),F9(i,a+10,t.length),I9(i,a+12,c),I9(i,a+16,s),F9(i,a+20,0),i}function R9(e){return String(e??``).toLowerCase().normalize(`NFKD`).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`shot`}function u_e(e){return`cozyclay-shot-${e.index}-${R9(e.title)}.zip`}function d_e({shot:e,fps:t,hasLast:n,hasClip:r,ext:i,hasStylized:a}){let o=[`CozyClay keyframe pack - shot ${e.index}: ${e.title}`,`Frame range ${e.startFrame}-${e.endFrame} at ${t} fps.`,``,`This pack is a multi-reference bundle for Seedance-style tools.`,`Each file plays a distinct reference role:`,``,`- first.png: identity reference. The first frame defines what the`,` subject and scene must look like when the shot begins.`];return n?o.push(`- last.png: motion endpoint reference. The final frame pins where`,` the motion should land, constraining the generated trajectory.`):o.push(`- last.png: not included. Without an endpoint the tool is free to`,` choose how the motion resolves.`),r?o.push(`- clip.${i}: motion reference. The source clip carries the movement`,` the generated video should follow.`):o.push(`- clip.${i}: not included. Without a motion clip the tool must`,` invent the movement from the frames and prompt alone.`),o.push(`- camera.json: camera reference. The recorded camera move, fps, and`,` frame range to reproduce the framing over time.`,`- prompt.txt: the text prompt describing the intended action.`),a&&o.push(`- stylized.png: the stylized picture of this panel; first.png is its greybox.`),o.push(``,`Not in this pack: the shot-wide depth video (blocking-depth.mp4) is a`,`separate export - use Depth (mp4) in the export menu.`),o.join(`
|
|
5121
5121
|
`)+`
|
|
5122
5122
|
`}function z9({shot:e,fps:t,firstFramePng:n,lastFramePng:r,clip:i,camera:a,prompt:o,stylizedPng:s=null,folder:c=`${e.index}-${R9(e.title)}`}){let l=[{name:`${c}/first.png`,data:n}];r!=null&&l.push({name:`${c}/last.png`,data:r}),i!=null&&l.push({name:`${c}/clip.${i.ext}`,data:i.data}),s!=null&&l.push({name:`${c}/stylized.png`,data:s});let u=e.kind===`still`?{startFrame:e.startFrame,endFrame:e.startFrame,hold:e.endFrame-e.startFrame+1,kind:`still`}:{startFrame:e.startFrame,endFrame:e.endFrame};return l.push({name:`${c}/camera.json`,data:JSON.stringify({...a,fps:t,...u},null,2)+`
|
|
5123
5123
|
`},{name:`${c}/prompt.txt`,data:`${o}\n`},{name:`${c}/README.txt`,data:d_e({shot:e,fps:t,hasLast:r!=null,hasClip:i!=null,ext:i?i.ext:`mp4`,hasStylized:s!=null})}),l}function f_e(e){return L9(z9(e))}var p_e=90,B9=.5;function m_e(e){return((typeof e.caption==`string`?e.caption.trim():``)||String(e.prompt??``)).slice(0,p_e)}function V9({shots:e,columns:t=3,cell:n={width:320,height:180},createCanvas:r}){let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(e.length/i)),o=i*n.width,s=a*n.height,c=r(o,s),l=c.getContext(`2d`),u=Math.round(n.height*.6);return l.fillStyle=`#101014`,l.fillRect(0,0,o,s),e.forEach((e,t)=>{let r=t%i*n.width,a=Math.floor(t/i)*n.height,o=e.stylized||e.image;if(o){let t=o.width||o.videoWidth||1,i=o.height||o.videoHeight||1,s=n.width-16,c=u-8,d=Math.min(s/t,c/i),f=t*d,p=i*d,m=r+8+(s-f)/2,h=a+8+(c-p)/2;if(l.drawImage(o,m,h,f,p),e.stylized&&e.image){let t=f*B9,n=p*B9;l.drawImage(e.image,m+f-t,h+p-n,t,n)}}else l.fillStyle=`#2a2a32`,l.fillRect(r+8,a+8,n.width-16,u-8);let s=r+8,c=a+u+16;l.fillStyle=`#f2f2f5`,l.fillText(String(e.title??``),s,c),c+=14,l.fillStyle=`#9a9aa5`,l.fillText(`${e.durationSeconds}s`,s,c),c+=14,l.fillText(m_e(e),s,c)}),c}var h_e=Object.freeze([`depth`,`normal`]);function g_e(e,t=.1,n=40){let r=1/0,i=-1/0;for(let t of e??[])Number.isFinite(t?.min)&&t.min>0&&(r=Math.min(r,t.min)),Number.isFinite(t?.max)&&t.max>0&&(i=Math.max(i,t.max));return!Number.isFinite(r)||!Number.isFinite(i)?{near:t,far:n}:{near:r,far:Math.max(i,r+1e-4)}}function __e(e){if(!h_e.includes(e))throw Error(`Unknown render pass: ${e}`);return`blocking-frame-${e}.png`}var v_e=`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"payload":"{\"distribution\":\"npm\",\"package\":\"cozyclay\",\"version\":\"3.1.
|
|
1
|
+
{"payload":"{\"distribution\":\"npm\",\"package\":\"cozyclay\",\"version\":\"3.1.6\",\"repository\":\"NomaDamas/CozyClay\",\"content_sha256\":\"d7b44cfa152ddb449c4e1445adeb8e3ae0a176e8eab6d431c7d9103ee12c25fc\"}","signature":"ruWnt+cS82Ajp7uv+w9ZiHLcqY5lCSNKER2sVtiLV+jnhGAzpPw1/KuZazg9lwFucoycs99uTwY8s+e5A3WQDw=="}
|
package/dist/index.html
CHANGED
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"applicationCategory": "DesignApplication",
|
|
47
47
|
"applicationSubCategory": "3D previsualization",
|
|
48
48
|
"operatingSystem": "Any (Chromium-based browser)",
|
|
49
|
-
"softwareVersion": "3.1.
|
|
49
|
+
"softwareVersion": "3.1.6",
|
|
50
50
|
"description": "CozyClay is an open-source, browser-based 3D staging studio. Block a scene, pose characters, sequence motion prompts on a timeline, and preview generated motion in one local workspace that handles like the Unity Editor.",
|
|
51
51
|
"image": "https://cozyclay.org/media/cozyclay-truck-demo-poster.jpg",
|
|
52
52
|
"screenshot": "https://cozyclay.org/media/cozyclay-truck-demo-poster.jpg",
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The memory-only camera inside a saved project (#861).
|
|
3
|
+
*
|
|
4
|
+
* Without an editor the shot camera lives only in the MCP state, which the
|
|
5
|
+
* scene document does not carry. It rides the active scene's stage as one
|
|
6
|
+
* extra key: createSceneStage keeps unknown stage keys losslessly, so the
|
|
7
|
+
* studio passes it through untouched and `open_project` reads it back here.
|
|
8
|
+
*/
|
|
9
|
+
const STAGE_KEY = "authoringCamera";
|
|
10
|
+
const FIELDS = ["x", "y", "z", "focalMm"];
|
|
11
|
+
|
|
12
|
+
/** A copy of `document` whose active scene's stage records `camera`. */
|
|
13
|
+
export function documentWithCamera(document, camera) {
|
|
14
|
+
const record = Object.fromEntries(FIELDS.map((key) => [key, camera[key]]));
|
|
15
|
+
if (!FIELDS.every((key) => Number.isFinite(record[key]))) return document;
|
|
16
|
+
return {
|
|
17
|
+
...document,
|
|
18
|
+
scenes: document.scenes.map((scene) => scene.id === document.activeSceneId
|
|
19
|
+
? { ...scene, stage: { ...scene.stage, [STAGE_KEY]: record } }
|
|
20
|
+
: scene),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Split a loaded document into the camera saved with its active scene (null
|
|
25
|
+
* when it has none) and the document without that key, so the open scene is
|
|
26
|
+
* exactly the one that was saved and the camera lives only in the MCP state. */
|
|
27
|
+
export function splitSavedCamera(document) {
|
|
28
|
+
const scene = document.scenes.find((entry) => entry.id === document.activeSceneId) ?? document.scenes[0];
|
|
29
|
+
const record = scene?.stage?.[STAGE_KEY];
|
|
30
|
+
const valid = !!record && typeof record === "object"
|
|
31
|
+
&& FIELDS.every((key) => Number.isFinite(record[key])) && record.focalMm > 0;
|
|
32
|
+
return {
|
|
33
|
+
camera: valid ? Object.fromEntries(FIELDS.map((key) => [key, record[key]])) : null,
|
|
34
|
+
document: {
|
|
35
|
+
...document,
|
|
36
|
+
scenes: document.scenes.map((entry) => {
|
|
37
|
+
if (!entry?.stage || !Object.hasOwn(entry.stage, STAGE_KEY)) return entry;
|
|
38
|
+
const { [STAGE_KEY]: _saved, ...stage } = entry.stage;
|
|
39
|
+
return { ...entry, stage };
|
|
40
|
+
}),
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cozyclay",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.6",
|
|
4
4
|
"description": "Open source previs software in the browser: block a scene, pose characters, author camera moves and cuts, then take the same shots to an AI video model.",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"dev": "node tools/dev-full.mjs --host 127.0.0.1 --port 5180",
|
|
@@ -104,6 +104,7 @@
|
|
|
104
104
|
"mcp/live-hub.mjs",
|
|
105
105
|
"mcp/mesh-file.mjs",
|
|
106
106
|
"mcp/image-file.mjs",
|
|
107
|
+
"mcp/project-camera.mjs",
|
|
107
108
|
"mcp/runtime",
|
|
108
109
|
"mcp/package.json",
|
|
109
110
|
"mcp/README.md",
|
|
@@ -2,12 +2,37 @@
|
|
|
2
2
|
import { execFileSync } from "node:child_process";
|
|
3
3
|
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
|
-
import { join } from "node:path";
|
|
5
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
6
6
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
7
|
|
|
8
8
|
const packageRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
9
9
|
const temporaryRoot = mkdtempSync(join(tmpdir(), "cozyclay-package-check-"));
|
|
10
10
|
const extractionRoot = join(temporaryRoot, "extracted");
|
|
11
|
+
// Static, side-effect and dynamic imports with a relative specifier.
|
|
12
|
+
const RELATIVE_IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)["'](\.\.?\/[^"']+)["']/g;
|
|
13
|
+
|
|
14
|
+
function* modulesUnder(dir) {
|
|
15
|
+
if (!existsSync(dir)) return;
|
|
16
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
17
|
+
if (entry.name === "node_modules") continue;
|
|
18
|
+
const path = join(dir, entry.name);
|
|
19
|
+
if (entry.isDirectory()) yield* modulesUnder(path);
|
|
20
|
+
else if (entry.name.endsWith(".mjs")) yield path;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Every relative import of a shipped bin/ or mcp/ module must resolve inside the
|
|
25
|
+
// tarball: a dev checkout has every file, an npm install only what `files` lists.
|
|
26
|
+
function missingImports(packedRoot) {
|
|
27
|
+
const missing = [];
|
|
28
|
+
for (const file of [...modulesUnder(join(packedRoot, "bin")), ...modulesUnder(join(packedRoot, "mcp"))]) {
|
|
29
|
+
for (const [, specifier] of readFileSync(file, "utf8").matchAll(RELATIVE_IMPORT)) {
|
|
30
|
+
const target = resolve(dirname(file), specifier);
|
|
31
|
+
if (!existsSync(target)) missing.push(`${relative(packedRoot, file)} imports ${specifier} (${relative(packedRoot, target)} is not in the tarball)`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return missing;
|
|
35
|
+
}
|
|
11
36
|
|
|
12
37
|
try {
|
|
13
38
|
mkdirSync(extractionRoot);
|
|
@@ -24,6 +49,9 @@ try {
|
|
|
24
49
|
execFileSync("tar", ["-xzf", tarball, "-C", extractionRoot]);
|
|
25
50
|
|
|
26
51
|
const packedRoot = join(extractionRoot, "package");
|
|
52
|
+
const missing = missingImports(packedRoot);
|
|
53
|
+
if (missing.length > 0) throw new Error(`npm tarball is missing modules its bin/ and mcp/ code imports:\n ${missing.join("\n ")}`);
|
|
54
|
+
console.log("package tarball imports PASS (every relative import in bin/ and mcp/ resolves inside the tarball)");
|
|
27
55
|
const metadataPath = join(packedRoot, "package.json");
|
|
28
56
|
const markerPath = join(packedRoot, "dist", "cozyclay-package.json");
|
|
29
57
|
const signatureModulePath = join(packedRoot, "bin", "package-signature.mjs");
|