cozyclay 3.1.3 → 3.1.4
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 +12 -0
- package/bin/cozyclay.mjs +2 -48
- package/bin/star-prompt.mjs +123 -0
- package/dist/app/index.html +1 -1
- package/dist/assets/{app-DwETmoQZ.js → app-KXdgBC-S.js} +1 -1
- package/dist/cozyclay-package.json +1 -1
- package/package.json +1 -1
- package/tools/loc-baseline.json +1 -1
- package/tools/run-tests.mjs +1 -1
|
@@ -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 jle(){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 $f(e,128,128,Ws);return r.minFilter=Bc,r.magFilter=ql,r.generateMipmaps=!0,r.needsUpdate=!0,r}function _8(e,t,n={}){return new Ed({uniforms:{...Mc.merge([Pm.lights,Pm.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 v8(e,t,n){let r=new df(1,1),i={};for(let[e,a]of Object.entries(n))i[e]=new td(new Float32Array(t*a),a).setUsage(jl),r.setAttribute(e,i[e]);let a=new hd(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 y8=(e,t)=>{for(let n of Object.values(e))n.clearUpdateRanges(),n.addUpdateRange(0,t*n.itemSize),n.needsUpdate=!0};function Mle(){let e=jle(),t=v8(_8(Dle,Ole,{map:{value:e}}),zQ,{iPos:3,iParams:4,iColor:4,iStreak:4}),n=v8(_8(kle,Ale),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;a$(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,y8(r,s),y8(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 b8=Symbol(`effects`),Nle=`#7fd4f0`,x8=e=>{e&&e.layers.set(5)};function Ple({object:e}){let t=e.effect?.preset===`trail`,n=t?Math.max(.05,(e.effect?.width??.5)/2):.06,r=(0,Q.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 pl;return a.setAttribute(`position`,new Yl([...r,...i].flat(),3)),a},[t,n]);return(0,Q.useEffect)(()=>()=>r.dispose(),[r]),(0,$.jsxs)(`group`,{userData:{effectMarker:!0},children:[(0,$.jsx)(`lineSegments`,{ref:x8,geometry:r,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{color:Nle,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),(0,$.jsxs)(`mesh`,{ref:x8,visible:!1,userData:{emptyPick:!0},children:[(0,$.jsx)(`sphereGeometry`,{args:[.08,12,8]}),(0,$.jsx)(`meshBasicMaterial`,{})]})]})}var Fle=e=>(t,n)=>{let r=e?.current?.get(t);return r?(r.place(),r.world(n)):null};function Ile({objects:e,frameRef:t=null,take:n=null,registryRef:r=null,fadeOpacity:i=null}){let a=(0,Q.useMemo)(()=>c$(e),[e]),o=a.records.length>0,s=(0,Q.useMemo)(()=>o?Mle():null,[o]);(0,Q.useEffect)(()=>()=>s?.dispose(),[s]);let c=(0,Q.useMemo)(()=>Fle(r),[r]),l=(0,Q.useMemo)(()=>({...a,take:n??{},live:c}),[a,n,c]),u=(0,Q.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 iy(d),(0,Q.useEffect)(()=>(s$(()=>l),()=>s$(null)),[l]),(0,Q.useEffect)(()=>{let e=r?.current;if(!(!e||!s))return e.set(b8,{place:d,world:()=>null}),()=>{e.delete(b8)}}),s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`primitive`,{object:s.particles}),(0,$.jsx)(`primitive`,{object:s.ribbons})]}):null}var Lle=.2,S8=`cozyclay.poseObjectOpacity`;function Rle(e=globalThis.localStorage){let t=Number(e?.getItem?.(S8));return e?.getItem?.(`cozyclay.poseObjectOpacity`)==null||!Number.isFinite(t)?Lle:Math.min(1,Math.max(0,t))}function zle(e,t=globalThis.localStorage){try{t?.setItem?.(S8,String(e))}catch{return}}var C8=new WeakMap,w8=()=>{};function Ble(e){return Array.isArray(e.material)?e.material:e.material?[e.material]:[]}var T8=!1;function E8(e){T8=e}function Vle(e,t){E8(!0),e?.();try{return t()}finally{E8(!1),e?.()}}function Hle(e,t,n=1){let r=T8||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 Ble(e))if(a){C8.has(t)||C8.set(t,{transparent:t.transparent,opacity:t.opacity,depthWrite:t.depthWrite});let e=C8.get(t).opacity*i;(t.opacity!==e||!t.transparent||t.depthWrite)&&(t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.needsUpdate=!0)}else C8.has(t)&&(Object.assign(t,C8.get(t)),C8.delete(t),t.needsUpdate=!0);o&&e.raycast!==w8?(e.userData.poseFadeRaycast=e.raycast,e.raycast=w8):!o&&e.raycast===w8&&(e.raycast=e.userData.poseFadeRaycast,delete e.userData.poseFadeRaycast)}})}var Ule=.2,Wle=.02,Gle=()=>{},D8=new WeakMap;function Kle(e){return D8.has(e)}var O8=null;function qle(){if(O8)return O8;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 O8=new $f(e,64,64),O8.magFilter=ql,O8.minFilter=ql,O8.needsUpdate=!0,O8}function Jle(){let e=new Qp({map:qle(),blending:2,transparent:!0,depthWrite:!1,fog:!1}),t=new Mp(e);return t.userData.glowHalo=!0,t.userData.beautyOnly=!0,t.raycast=Gle,t.castShadow=!1,t.receiveShadow=!1,t.renderOrder=2,t}function Yle(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 Xle(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(),D8.delete(e)}function Zle(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:Wle}}function Qle(e,t,n){let r=t.glow,i=D8.get(e);if(!r){i&&Xle(e,i);return}i||(i={halo:Jle(),bases:new Map,shadowless:new Set},D8.set(e,i)),i.halo.parent!==e&&e.add(i.halo);let a=r.intensity*n;Yle(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}=Zle(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(Ule*a)}var $le=Math.PI/180,k8=new Z(0,-1,0),A8=new Z,j8=new Z,M8=new Tu,eue=new Z;function N8(e,t){for(let n of e.children)if(n.userData?.[t])return n;return null}function tue(e,t,n){let r=N8(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*go*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*$le,r.penumbra=c,e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(j8,M8,eue),l?A8.set(l.x-j8.x,l.y-j8.y,l.z-j8.z):A8.copy(k8).applyQuaternion(M8),A8.lengthSq()<1e-10&&A8.copy(k8).applyQuaternion(M8),A8.normalize(),r.target.position.copy(j8).add(A8),r.target.updateMatrixWorld();let u=N8(e,`lightMarker`)?.children.find(e=>e.userData?.lightCone);u&&u.quaternion.setFromUnitVectors(k8,A8.applyQuaternion(M8.invert()))}function nue(e,t,n,r){if(!t.light&&!t.glow&&!Kle(e))return;let i=lX(t.id,n,r)*(t.light?Ra(t.id,n,t.light.flicker,r?.fps):1);t.light&&tue(e,t,i),Qle(e,t,i)}var rue=Math.PI/180,P8=.07,iue=.7;function aue(e,t){let n=e===`spot`?new Bd:new Cl;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 F8(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 I8(e){let t=new pl;return t.setAttribute(`position`,new Yl(e,3)),t}function oue(){let e=[];F8(e,P8,0,2),F8(e,P8,0,1),F8(e,P8,1,2);for(let t=0;t<8;t+=1){let n=t/8*Math.PI*2;e.push(Math.cos(n)*P8*1.3,0,Math.sin(n)*P8*1.3,Math.cos(n)*P8*2,0,Math.sin(n)*P8*2)}return I8(e)}function sue(e){let t=iue*Math.tan(e*rue),n=F8([],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 I8(n)}var L8=e=>{e&&e.layers.set(5)};function cue({type:e,angle:t,color:n}){let r=(0,Q.useMemo)(()=>oue(),[]),i=(0,Q.useMemo)(()=>e===`spot`?sue(t):null,[e,t]);return(0,Q.useEffect)(()=>()=>r.dispose(),[r]),(0,Q.useEffect)(()=>()=>i?.dispose(),[i]),(0,$.jsxs)(`group`,{userData:{lightMarker:!0},children:[(0,$.jsx)(`lineSegments`,{ref:L8,geometry:r,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{color:n,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),i&&(0,$.jsx)(`group`,{userData:{lightCone:!0},children:(0,$.jsx)(`lineSegments`,{ref:L8,geometry:i,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{color:n,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.55})})}),(0,$.jsxs)(`mesh`,{ref:L8,visible:!1,userData:{emptyPick:!0},children:[(0,$.jsx)(`sphereGeometry`,{args:[ri*.45,12,8]}),(0,$.jsx)(`meshBasicMaterial`,{})]})]})}function lue({object:e}){let{type:t,shadow:n,angle:r,color:i}=e.light,a=(0,Q.useMemo)(()=>aue(t,n),[t,n]);return(0,Q.useEffect)(()=>()=>a.dispose(),[a]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`primitive`,{object:a}),(0,$.jsx)(cue,{type:t,angle:r,color:i})]})}function uue(e){let t=ry(e=>e.invalidate);(0,Q.useEffect)(()=>{t()},[t,e.light,e.glow])}function due({kind:e,object:t,color:n,autoColor:r,depthRank:i=0}){let a=e===`plane`?2:0,o=hle(t,e,a,i),s=!(o?.transmission>0),c=o?(0,$.jsx)(`primitive`,{object:o,attach:`material`}):r?(0,$.jsx)(`meshStandardMaterial`,{...q1(r),side:a,...p8(i)}):(0,$.jsx)(`meshStandardMaterial`,{color:n,roughness:.82,side:a,...p8(i)});return e===`sphere`?(0,$.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`sphereGeometry`,{args:[.5,28,18]}),c]}):e===`capsule`?(0,$.jsxs)(`mesh`,{position:[0,.7,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`capsuleGeometry`,{args:[.35,.7,6,18]}),c]}):e===`cylinder`?(0,$.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`cylinderGeometry`,{args:[.5,.5,1,26]}),c]}):e===`cone`?(0,$.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`coneGeometry`,{args:[.5,1,26]}),c]}):e===`plane`?(0,$.jsxs)(`mesh`,{position:[0,.004,0],rotation:[-Math.PI/2,0,0],receiveShadow:!0,children:[(0,$.jsx)(`planeGeometry`,{args:[2,2]}),c]}):(0,$.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`boxGeometry`,{args:[1,1,1]}),c]})}function fue(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(n(null),e)return io(e,n)},[e]),t}var pue=`#c2c6c8`;function mue({object:e}){let t=fue(e.assetId),n=e.footprint?.width??1,r=e.height??1;return(0,$.jsxs)(`mesh`,{position:[0,r/2,0],castShadow:!0,receiveShadow:!0,userData:{cutoutTexture:t??null},children:[(0,$.jsx)(`planeGeometry`,{args:[n,r]}),(0,$.jsx)(`meshStandardMaterial`,{map:t??null,color:t?e.color:pue,side:2,alphaTest:t?.15:0,alphaToCoverage:!!t,roughness:.92,metalness:0})]})}function hue({object:e,depthRank:t=0}){let{recipe:n,autoColor:r}=e,i=(0,Q.useMemo)(()=>{let e=fle(n,r?{materialFor:()=>new jf(q1(r))}:{});return e.traverse(e=>e.material&&Object.assign(e.material,p8(t))),e},[n,r,t]);return(0,Q.useEffect)(()=>()=>ple(i),[i]),(0,$.jsx)(`primitive`,{object:i})}var gue=new Set([`cube`,`sphere`,`capsule`,`cylinder`,`cone`,`plane`]),_ue=[{to:[1,0,0],color:`#e5594f`},{to:[0,1,0],color:`#5fb95f`},{to:[0,0,1],color:`#4f86e5`}];function vue(){let e=ri/2,t=(0,Q.useMemo)(()=>{let t=[],n=[],r=new X;for(let i of _ue)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 pl;return i.setAttribute(`position`,new Yl(t,3)),i.setAttribute(`color`,new Yl(n,3)),i},[e]);(0,Q.useEffect)(()=>()=>t.dispose(),[t]);let n=e=>e?.layers.set(5);return(0,$.jsxs)(`group`,{userData:{emptyMarker:!0},children:[(0,$.jsx)(`lineSegments`,{ref:n,geometry:t,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{vertexColors:!0,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),(0,$.jsxs)(`mesh`,{ref:n,visible:!1,userData:{emptyPick:!0},children:[(0,$.jsx)(`sphereGeometry`,{args:[e*1.25,12,8]}),(0,$.jsx)(`meshBasicMaterial`,{})]})]})}function yue({object:e,depthRank:t=0}){let{renderer:n,color:r,autoColor:i}=e;return n===`empty`?(0,$.jsx)(vue,{}):n===`light`?(0,$.jsx)(lue,{object:e}):n===`effect`?(0,$.jsx)(Ple,{object:e}):n===`cutout`?(0,$.jsx)(mue,{object:e}):n===`mesh`?(0,$.jsx)(Ele,{object:e}):n===`sculpt`?(0,$.jsx)(hue,{object:e,depthRank:t}):n===`text`?(0,$.jsx)(o0,{object:e}):gue.has(n)?(0,$.jsx)(due,{kind:n,object:e,color:r,autoColor:i,depthRank:t}):null}function bue({object:e}){let t=e.renderer===`empty`||e.renderer===`light`||e.renderer===`effect`,n=t?ri:Math.max(e.height??1,.08),r=t?ri:e.footprint?.width??1,i=t?ri:e.footprint?.depth??1,a=(0,Q.useMemo)(()=>new Zs(new pf(r*1.04,n*1.04,i*1.04)),[r,n,i]);return(0,Q.useEffect)(()=>()=>a.dispose(),[a]),(0,$.jsx)(`lineSegments`,{ref:e=>{e&&e.layers.set(5)},geometry:a,position:[0,t?0:n/2,0],renderOrder:998,children:(0,$.jsx)(`lineBasicMaterial`,{color:`#e7b557`,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1})})}var R8=Math.PI/180,z8=new Z,B8=new Tu,V8=new Z,H8=new vl,U8=new af,W8=new af,xue=new af;function Sue({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,Q.useRef)(null),u=e.attach??null,d=()=>{let t=l.current;if(!t)return;let a=n?.current??0,c=n&&!u&&o?.current?gX(o.current,e.id,a,r??{},W8):null;if((t.visible=cX(e.id,a,r,o?.current))&&c)c.decompose(t.position,t.quaternion,t.scale);else if(u||e.path){if(z8.set(e.x,e.y??0,e.z),H8.set((e.rotX??0)*R8,e.rot*R8,(e.rotZ??0)*R8,`XYZ`),V8.set(e.scaleX??1,e.scaleY??1,e.scaleZ??1),n&&e.path){let t=ga(e,a,r??{});if(t){z8.set(t.x,t.y,t.z);let n=iX(e,t);H8.set(n.rotX*R8,n.rot*R8,n.rotZ*R8,`YXZ`)}}let o=u?i?.current?.(u.characterId,u.bone??null,xue)??null:null;o?(U8.compose(z8,B8.setFromEuler(H8),V8),W8.multiplyMatrices(o,U8).decompose(z8,B8,V8),t.position.copy(z8),t.quaternion.copy(B8),t.scale.copy(V8)):(t.position.copy(z8),t.rotation.copy(H8),t.scale.copy(V8))}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}),Hle(t,s,e.opacity??1),nue(t,e,a,r)};iy(d),uue(e);let f=(0,Q.useRef)(d);f.current=d;let p=(0,Q.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,Q.useEffect)(()=>{if(!a)return;let t=a.current;return t.set(e.id,p.current),()=>{t.delete(e.id)}},[a,e.id]),(0,$.jsxs)(`group`,{ref:l,position:[e.x,e.y??0,e.z],rotation:[(e.rotX??0)*R8,e.rot*R8,(e.rotZ??0)*R8],scale:[e.scaleX??1,e.scaleY??1,e.scaleZ??1],userData:{sceneObjectId:e.id},children:[(0,$.jsx)(yue,{object:e,depthRank:c}),t&&(0,$.jsx)(bue,{object:e})]})}function Cue({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,Q.useRef)(null),u=(0,Q.useRef)(null);u.current=(0,Q.useMemo)(()=>t?new Map(t.map(e=>[e.id,e])):null,[t]);let d=(0,Q.useMemo)(()=>Qk(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,$.jsxs)(`group`,{children:[Da(e).map(e=>(0,$.jsx)(Sue,{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,$.jsx)(Ile,{objects:t??e,frameRef:r,take:i,registryRef:l,fadeOpacity:c})]})}var wue=new af;function Tue({objectId:e=null,objectsRef:t,frameRef:n=null,take:r=null,registryRef:i=null,children:a}){let o=(0,Q.useRef)(null),s=()=>{let i=o.current;if(!i)return;let a=e&&t?.current?vX(t.current,e,n?.current??0,r??{},wue):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))};iy(s,-1);let c=(0,Q.useRef)(s);return c.current=s,(0,Q.useEffect)(()=>{if(!i)return;let e=i.current,t=()=>c.current();return e.add(t),()=>{e.delete(t)}},[i]),(0,$.jsx)(`group`,{ref:o,children:a})}var Eue=[139,92,246],G8=.62,Due=`#141819`,Oue=512,K8=1,q8=(e,t,n)=>Math.min(n,Math.max(t,e));function kue(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)*q8(a.view.zoom,K8,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?q8(s.x,i,a.preview.width-i):a.preview.width/2,s.y=r>=e.height?q8(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]=Eue;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*G8,u=u*.38+h*G8,f=f*.38+g*G8),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=Due,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+=jN(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=AN(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=q8(a.view.zoom*n,K8,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,Oue/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=q8(Number(e)||0,.01,.9);let t=AN(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=q8(Number(e)||0,.01,.9)},setBrush(e){a.brush=q8(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 Aue={name:`cozyclay`,version:`3.1.3`,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 J8({id:e}){let t=`/thumbs/${e}-${_m()}.webp`,[n,r]=(0,Q.useState)(null);return n===t?null:(0,$.jsx)(`img`,{className:`v2-start-art`,src:t,alt:``,"aria-hidden":`true`,draggable:`false`,decoding:`async`,onError:()=>r(t)})}function jue(){return(0,$.jsx)(`img`,{className:`v2-start-brand-mark`,src:`/icons/icon-192.png`,alt:``,"aria-hidden":`true`,draggable:`false`,width:`26`,height:`26`})}var Mue=Aue.version,Y8=Object.freeze({id:`new-project`,thumbId:`blank-stage`,kind:`blank`,defaultName:`Untitled Project`,get name(){return Y(`New project`,`새 프로젝트`)},get description(){return Y(`Start from an empty stage.`,`빈 무대에서 시작합니다.`)}}),Nue=[{id:`storyboard`,label:()=>Y(`Storyboard`,`스토리보드`),blurb:()=>Y(`Describe scenes in words and direct one panel at a time. Output: image references.`,`말로 장면을 설명하면 한 장씩 패널을 연출합니다. 결과물: 이미지 레퍼런스.`)},{id:`animation`,label:()=>Y(`Animation`,`애니메이션`),blurb:()=>Y(`Block and shoot continuous motion. Output: clip references.`,`연속 동작을 블로킹하고 촬영합니다. 결과물: 클립 레퍼런스.`)}],X8=null;function Z8(e){X8=e}function Pue(e){let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`,year:`numeric`}):Y(`Recently`,`최근`)}function Fue(e){return{id:`sample-${e.id}`,starterId:e.id,name:e.name,description:e.blurb,kind:`sample`}}function Iue({open:e,initialName:t=`My Project`,onCancel:n,onSubmit:r}){let[i,a]=(0,Q.useState)(t);return(0,Q.useEffect)(()=>{if(e){if(X8!==null){let e=X8;X8=null,a(e),r(e);return}a(t)}},[e,t]),e?(0,$.jsx)(`div`,{className:`v2-project-name-dialog-backdrop project-name-dialog-backdrop`,role:`presentation`,children:(0,$.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,$.jsx)(`strong`,{id:`project-name-dialog-title`,children:Y(`Project name`,`프로젝트 이름`)}),(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`span`,{children:Y(`Name`,`이름`)}),(0,$.jsx)(`input`,{autoFocus:!0,value:i,onChange:e=>a(e.target.value),"aria-label":Y(`Project name`,`프로젝트 이름`)})]}),(0,$.jsxs)(`div`,{className:`v2-project-name-dialog-actions project-name-dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`v2-dialog-secondary btn ghost`,onClick:n,children:Y(`Cancel`,`취소`)}),(0,$.jsx)(`button`,{type:`submit`,className:`v2-dialog-primary btn primary`,children:Y(`Create`,`생성`)})]})]})}):null}function Lue({currentName:e,onOpen:t,onOpenFile:n,onNew:r,onClose:i,startup:a=!1,starters:o=[],onStarter:s}){let c=(0,Q.useMemo)(()=>o.map(Fue),[o]),[l,u]=(0,Q.useState)(Sr),d=l===`storyboard`?[]:c,f=c[0]??Y8,[p,m]=(0,Q.useState)(a?`new`:`recent`),[h,g]=(0,Q.useState)(f.id),[_,v]=(0,Q.useState)(e||f.defaultName||f.name||`My Project`),[y,b]=(0,Q.useState)(`24`),[x,S]=(0,Q.useState)(`Meters`),[C,w]=(0,Q.useState)([]),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)([]),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(null),N=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=!0;return Xi().then(t=>{e&&w(Array.isArray(t)?t:[])}),Br().then(async t=>{if(!e||!t)return;let n=await no(t);if(e){if(n!==`granted`){A(!0),n===`prompt`&&M(t);return}E(t),O(await Wr(t))}}).catch(()=>{e&&A(!0)}),()=>{e=!1}},[]),(0,Q.useEffect)(()=>{a&&N.current?.focus()},[a]),(0,Q.useEffect)(()=>()=>{queueMicrotask(()=>Z8(null))},[]);let P=d.find(e=>e.id===h)??Y8,F=_.trim().length>0,I=Y(`Enter a project name to create a project`,`프로젝트를 만들려면 이름을 입력하세요`),L=T?.name||Y(`Browser project store`,`브라우저 프로젝트 저장소`),R=Dr()&&Bi(),z=async()=>{if(!j||await _o(j)!==`granted`)return;let e=j;M(null),A(!1),E(e),O(await Wr(e))},ee=async()=>{if(R)try{let e=await Xo();await Oa(e),E(e),A(!1),M(null),O(await Wr(e))}catch(e){e?.name!==`AbortError`&&A(!0)}},B=async()=>{T&&O(await Wr(T))},V=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(Y8.id),v(e=>e.trim()===P?.name?Y8.defaultName:e))},U=e=>{e.preventDefault();let t=_.trim();if(t){if(P?.starterId){s?.(P.starterId,t,{previsMode:`animation`});return}Z8(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:Y(`Recent`,`최근`)},{id:`new`,label:Y(`New Project`,`새 프로젝트`)},{id:`learn`,label:Y(`Learn`,`배우기`)}];return(0,$.jsx)(`div`,{className:`v2-start-screen project-browser-backdrop${a?` startup`:``}`,onPointerDown:e=>{!a&&e.target===e.currentTarget&&i?.()},children:(0,$.jsxs)(`div`,{className:`v2-start-window project-browser${a?` startup`:``}`,role:`dialog`,"aria-modal":`true`,"aria-label":Y(`Choose project`,`프로젝트 선택`),children:[(0,$.jsxs)(`nav`,{className:`v2-start-nav`,"aria-label":Y(`Project navigation`,`프로젝트 탐색`),children:[(0,$.jsxs)(`div`,{className:`v2-start-brand`,children:[(0,$.jsx)(jue,{}),(0,$.jsx)(`strong`,{children:`CozyClay`})]}),(0,$.jsx)(`div`,{className:`v2-start-nav-list`,children:G.map(e=>(0,$.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,$.jsxs)(`div`,{className:`v2-start-version`,children:[`v`,Mue]})]}),(0,$.jsxs)(`main`,{className:`v2-start-main`,children:[(0,$.jsxs)(`div`,{className:`v2-start-main-head`,children:[(0,$.jsxs)(`div`,{className:`v2-start-title-row`,children:[(0,$.jsx)(`h1`,{children:p===`recent`?Y(`Recent`,`최근`):p===`learn`?Y(`Learn`,`배우기`):Y(`New Project`,`새 프로젝트`)}),p!==`new`&&(0,$.jsx)(`button`,{type:`button`,className:`v2-start-close x`,onClick:i,"aria-label":Y(`Close`,`닫기`),children:`×`})]}),p===`new`&&(0,$.jsx)(`div`,{className:`v2-start-mode`,role:`radiogroup`,"aria-label":Y(`Project mode`,`프로젝트 모드`),"data-testid":`start-previs-mode`,children:Nue.map(e=>(0,$.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,$.jsx)(`strong`,{children:e.label()}),(0,$.jsx)(`span`,{children:e.blurb()})]},e.id))})]}),p===`learn`?(0,$.jsxs)(`div`,{className:`v2-start-learn`,children:[(0,$.jsx)(`strong`,{children:Y(`Block a shot in three moves`,`세 단계로 샷을 블로킹하세요`)}),(0,$.jsx)(`p`,{children:Y(`Choose a template, name the project, then place a character and frame the camera in the editor.`,`템플릿을 고르고 프로젝트 이름을 정한 다음 편집기에서 인물을 배치하고 카메라를 잡아 보세요.`)}),(0,$.jsx)(`button`,{type:`button`,className:`v2-start-learn-action`,onClick:()=>m(`new`),children:Y(`Start a new project`,`새 프로젝트 시작`)})]}):p===`recent`?(0,$.jsxs)(`div`,{className:`v2-start-recent-page`,children:[(0,$.jsxs)(`div`,{className:`v2-start-recent-heading`,children:[(0,$.jsx)(`span`,{children:Y(`Recent projects`,`최근 프로젝트`)}),(0,$.jsxs)(`div`,{className:`v2-start-recent-actions`,children:[T&&(0,$.jsx)(`button`,{type:`button`,onClick:B,children:Y(`Refresh`,`새로고침`)}),(0,$.jsx)(`button`,{type:`button`,onClick:n,children:Y(`Open project file…`,`프로젝트 파일 열기…`)})]})]}),(0,$.jsx)(Q8,{entries:W,currentName:e,onOpen:t,onOpenFile:n,onRemove:async e=>{await Ca(e.name),w(await Xi())}})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`v2-start-template-grid`,role:`list`,"aria-label":Y(`Project templates`,`프로젝트 템플릿`),children:[d.map(e=>(0,$.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-template${P?.id===e.id?` selected`:``}`,"data-template-id":e.id,onClick:()=>V(e),onDoubleClick:()=>e.starterId&&s?.(e.starterId),children:[(0,$.jsx)(`span`,{className:`v2-start-template-art ${e.kind}`,children:(0,$.jsx)(J8,{id:e.starterId??e.id})}),(0,$.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`span`,{children:e.description})]})]},e.id)),(0,$.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-add-card${P?.id===Y8.id?` selected`:``}`,"data-testid":`start-new-project-card`,onClick:()=>{V(Y8),requestAnimationFrame(()=>N.current?.select())},children:[(0,$.jsx)(`span`,{className:`v2-start-add-art`,"aria-hidden":`true`,children:(0,$.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`20`,height:`20`,children:(0,$.jsx)(`path`,{d:`M10 3.5v13M3.5 10h13`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})})}),(0,$.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,$.jsx)(`strong`,{children:Y(`New project`,`새 프로젝트`)}),(0,$.jsx)(`span`,{children:Y(`Start from an empty stage`,`빈 무대에서 시작`)})]})]}),(0,$.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,$.jsx)(`span`,{className:`v2-start-add-art`,"aria-hidden":`true`,children:(0,$.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`20`,height:`20`,children:(0,$.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,$.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,$.jsx)(`strong`,{children:Y(`Open project`,`프로젝트 열기`)}),(0,$.jsx)(`span`,{children:Y(`A saved .cclayproject file`,`저장한 .cclayproject 파일`)})]})]})]}),(0,$.jsxs)(`div`,{className:`v2-start-recent-block`,children:[(0,$.jsx)(`div`,{className:`v2-start-recent-heading`,children:(0,$.jsx)(`span`,{children:Y(`Recent`,`최근`)})}),(0,$.jsx)(Q8,{entries:C.map(e=>({...e,key:`recent-${e.name}`,removable:!0,date:e.openedAt})),currentName:e,onOpen:t,onOpenFile:n,onRemove:async e=>{await Ca(e.name),w(await Xi())},compact:!0})]})]})]}),(0,$.jsxs)(`aside`,{className:`v2-start-preview`,"data-testid":`start-project-preview`,"aria-label":Y(`Project preview`,`프로젝트 미리보기`),children:[(0,$.jsx)(`div`,{className:`v2-start-preview-art ${P?.kind||`blank`}`,children:(0,$.jsx)(J8,{id:P.starterId??P.thumbId})}),(0,$.jsxs)(`div`,{className:`v2-start-preview-copy`,children:[(0,$.jsx)(`strong`,{children:P?.name}),(0,$.jsx)(`span`,{children:P?.description})]}),(0,$.jsxs)(`form`,{className:`v2-start-project-form`,onSubmit:U,children:[(0,$.jsxs)(`label`,{className:`v2-start-field`,children:[(0,$.jsx)(`span`,{children:Y(`Name`,`이름`)}),(0,$.jsx)(`input`,{ref:N,"data-testid":`start-project-name`,"aria-label":Y(`Name`,`이름`),value:_,onChange:e=>v(e.target.value)})]}),(0,$.jsxs)(`label`,{className:`v2-start-field`,children:[(0,$.jsx)(`span`,{children:Y(`Location`,`위치`)}),(0,$.jsxs)(`button`,{type:`button`,className:`v2-start-location`,onClick:ee,disabled:!R,title:R?Y(`Choose the project storage folder`,`프로젝트 저장 폴더 선택`):Y(`Projects are stored in this browser`,`프로젝트는 이 브라우저에 저장됩니다`),children:[(0,$.jsx)(`span`,{children:L}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`⌄`})]})]}),(0,$.jsxs)(`label`,{className:`v2-start-field`,children:[(0,$.jsx)(`span`,{children:Y(`Frame rate`,`프레임 레이트`)}),(0,$.jsx)(`span`,{className:`v2-start-select-wrap`,children:(0,$.jsxs)(`select`,{"aria-label":Y(`Frame rate`,`프레임 레이트`),value:y,onChange:e=>b(e.target.value),children:[(0,$.jsx)(`option`,{value:`24`,children:`24 fps`}),(0,$.jsx)(`option`,{value:`30`,children:`30 fps`})]})})]}),(0,$.jsxs)(`label`,{className:`v2-start-field`,children:[(0,$.jsx)(`span`,{children:Y(`Units`,`단위`)}),(0,$.jsx)(`span`,{className:`v2-start-select-wrap`,children:(0,$.jsxs)(`select`,{"aria-label":Y(`Units`,`단위`),value:x,onChange:e=>S(e.target.value),children:[(0,$.jsx)(`option`,{value:`Meters`,children:`Meters`}),(0,$.jsx)(`option`,{value:`Feet`,children:`Feet`})]})})]}),k&&(0,$.jsxs)(`p`,{className:`v2-start-location-status`,role:`status`,children:[j?Y(`Folder access needs to be re-allowed.`,`폴더 접근을 다시 허용해야 해요.`):Y(`Using the browser project store.`,`브라우저 프로젝트 저장소를 사용합니다.`),j&&(0,$.jsx)(`button`,{type:`button`,onClick:z,children:Y(`Re-allow`,`다시 허용`)})]}),(0,$.jsxs)(`div`,{className:`v2-start-preview-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`v2-start-cancel`,onClick:i,children:Y(`Cancel`,`취소`)}),(0,$.jsx)(`button`,{type:`submit`,className:`v2-start-create btn primary`,"data-testid":`start-create`,disabled:!F,title:F?Y(`Create project`,`프로젝트 만들기`):I,children:Y(`Create`,`생성`)})]})]})]})]})})}function Q8({entries:e,currentName:t,onOpen:n,onOpenFile:r,onRemove:i,compact:a=!1}){return e.length===0?(0,$.jsxs)(`p`,{className:`v2-start-empty${a?` compact`:``}`,children:[Y(`No recent projects in this browser yet. `,`이 브라우저에 최근 프로젝트가 없습니다. `),(0,$.jsx)(`button`,{type:`button`,className:`v2-start-empty-open`,onClick:r,children:Y(`Open a project file…`,`프로젝트 파일 열기…`)})]}):(0,$.jsx)(`div`,{className:`v2-start-recent-list${a?` compact`:``}`,role:`list`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`v2-start-recent-row${e.name===t?` active`:``}`,role:`listitem`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`v2-start-recent-open`,onClick:()=>n(e),children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`span`,{children:Pue(e.date)}),(0,$.jsxs)(`small`,{children:[e.shots??`—`,Y(` shots`,` 샷`)]})]}),e.removable&&(0,$.jsx)(`button`,{type:`button`,className:`v2-start-recent-remove`,"aria-label":Y(`Remove ${e.name} from recent projects`,`최근 프로젝트에서 ${e.name} 제거`,`从最近项目中移除 ${e.name}`),title:Y(`Remove from list`,`목록에서 제거`),onClick:()=>i(e),children:`×`})]},e.key))})}var Rue={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 zue({open:e,onDismiss:t,previsMode:n=`animation`}){let r=n===`storyboard`,i=Rue[r?`storyboard`:`animation`],[a,o]=(0,Q.useState)(0);if((0,Q.useEffect)(()=>{e&&o(0)},[e]),!e)return null;let s=a>=i.length;return(0,$.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,$.jsxs)(`div`,{className:`v2-first-success-guide-head first-success-guide-head`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{id:`first-success-guide-title`,children:Y(`Your first 60 seconds`,`첫 60초`)}),(0,$.jsx)(`span`,{children:s?Y(`Core loop complete`,`핵심 흐름 완료`,`核心流程完成`):Y(`Step ${a+1} of ${i.length}`,`${a+1} / ${i.length} 단계`,`第 ${a+1} / ${i.length} 步`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-close first-success-guide-close`,onClick:t,"aria-label":Y(`Dismiss guide`,`가이드 닫기`),children:`×`})]}),s?(0,$.jsxs)(`div`,{className:`v2-first-success-guide-complete first-success-guide-complete`,id:`first-success-guide-description`,role:`status`,children:[(0,$.jsx)(`div`,{className:`v2-first-success-guide-check first-success-guide-check`,children:`✓`}),(0,$.jsx)(`strong`,{children:r?Y(`You made your first panel.`,`첫 패널을 만들었어요.`):Y(`You made your first shot.`,`첫 샷을 만들었어요.`)}),(0,$.jsx)(`p`,{children:r?Y(`Describe, review on the Board, then stylize or export. You can close this guide and keep adding panels.`,`설명하고, 보드에서 확인한 뒤 스타일을 입히거나 내보내세요. 가이드를 닫고 패널을 계속 추가하세요.`):Y(`Select, move, ask, and play are the core CozyClay loop. You can close this guide and keep blocking.`,`선택하고, 움직이고, 요청하고, 재생하는 것이 CozyClay의 핵심 흐름입니다. 가이드를 닫고 계속 블로킹하세요.`)}),(0,$.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-next first-success-guide-next btn primary`,onClick:t,children:Y(`Continue editing`,`편집 계속하기`)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{id:`first-success-guide-description`,className:`v2-first-success-guide-intro first-success-guide-intro`,children:Y(`Follow these four actions to see a result quickly.`,`네 가지 동작으로 빠르게 결과를 확인해 보세요.`)}),(0,$.jsx)(`ol`,{className:`v2-first-success-guide-steps first-success-guide-steps`,children:i.map((e,t)=>(0,$.jsxs)(`li`,{className:t<a?`done`:t===a?`current`:``,children:[(0,$.jsx)(`span`,{className:`v2-first-success-guide-step-mark first-success-guide-step-mark`,children:t<a?`✓`:t+1}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{children:Y(e.en,e.ko,e.zh)}),t===a&&(0,$.jsx)(`span`,{children:Y(e.hintEn,e.hintKo,e.hintZh)})]})]},e.en))}),(0,$.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-next first-success-guide-next btn primary`,onClick:()=>o(e=>e+1),children:Y(a===i.length-1?`Mark complete`:`I did this`,a===i.length-1?`완료로 표시`:`했어요`,a===i.length-1?`标记完成`:`我做了这一步`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-skip first-success-guide-skip`,onClick:t,children:Y(`Skip guide`,`가이드 건너뛰기`)})]})}var Bue=Object.freeze([[`animation`,`Animation`,`애니메이션`,`动画`],[`film`,`Film / drama`,`영화·드라마`,`影视剧`],[`game`,`Game`,`게임`,`游戏`],[`ad_mv`,`Ad / music video`,`광고·뮤비`,`广告 / MV`],[`personal`,`Personal project`,`개인 작업`,`个人项目`],[`other`,`Something else`,`기타`,`其他`]]),Vue=Object.freeze([[`team`,`With a team or company`,`팀·회사에서`,`与团队或公司`],[`solo`,`On my own`,`혼자`,`我自己`]]);function Hue({open:e,isKo:t,isZh:n,onAnswer:r}){let[i,a]=(0,Q.useState)(null),o=(e,r,i)=>t?r:n?i:e;if((0,Q.useEffect)(()=>{e||a(null)},[e]),!e)return null;let s=()=>r(i??`skip`,`skip`);return(0,$.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,$.jsxs)(`div`,{className:`use-case-ask-head`,children:[(0,$.jsx)(`strong`,{id:`use-case-ask-title`,children:o(`Quick question (optional)`,`짧은 질문 (선택)`,`快速提问(可选)`)}),(0,$.jsx)(`button`,{type:`button`,className:`use-case-ask-close`,"aria-label":o(`Close`,`닫기`,`关闭`),onClick:s,children:`×`})]}),(0,$.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,$.jsx)(`div`,{className:`use-case-ask-choices`,role:`group`,"aria-label":i?o(`Team or solo`,`팀 또는 혼자`,`团队或个人`):o(`Use case`,`용도`,`用途`),children:(i?Vue:Bue).map(([e,t,n,s])=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>i?r(i,e):a(e),children:o(t,n,s)},e))}),(0,$.jsx)(`p`,{className:`use-case-ask-note`,children:o(`Anonymous. Only the choice is sent.`,`익명이에요. 고른 항목만 전송돼요.`,`匿名。只发送所选项目。`)})]})}var $8=`gizmoHandleProxy`,Uue=[$8,`keyLightPick`,`pathAxis`,`pathIndex`,`pathRing`,`pathLine`,`craneAxis`,`craneIndex`];function Wue(e){for(let t=e;t;t=t.parent){let e=t.userData;if(e){for(let t of Uue)if(e[t]!==void 0)return!0}}return!1}function Gue(e){return e.some(e=>Wue(e.object))}var e5=(e,t)=>Math.max(0,Math.min(e.frameCount-1,Math.round(t)||0)),Kue=(e,t)=>typeof t.parent==`string`?e.get(t.parent):null;function que(e,t,n){let r=new Set;for(let i=e.get(n);i&&!r.has(i.id);i=Kue(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 Jue(e,t){return e?.hold?e.hold[e5(e,t)]===1?`held`:null:e?`hinge`:null}function Yue(e,t){return t.set(0,e.renderer===`empty`?0:(e.height??1)/2,0)}function Xue(e,t,n,r){let i=e.get(t),a=i?gX(e,t,n,r,new af):null;if(!a)return null;let o=new Tu;return a.decompose(new Z,o,new Z),{centre:Yue(i,new Z).applyMatrix4(a).toArray(),quat:o.toArray()}}function Zue(e,t){let n=e5(e,t);return{pos:new Z().fromArray(e.pos,n*3),quat:new Tu().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 Tu().setFromAxisAngle(r.clone().normalize(),i*Math.PI/180),n=new Z().fromArray(t);a.sub(n).applyQuaternion(e).add(n),o.premultiply(e).normalize()}return n&&a.add(n),{pos:a,quat:o}}function Que(e,t,n,r,i){let a=new Z().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 $ue(e,t,n=0){let r=new Z;for(let i of t)r.addScaledVector(i,n5(e.dot(i),n));return r}var ede=(e,t=0)=>n5(e,t);function tde(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 nde(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 rde(e,t,n,r,i=[]){let a=e.get(t),o=n?.track?.hold;if(!a||!o)return null;let s=new Z(0,a.renderer===`empty`?0:a.height??1,0),c=new af,l=n=>gX(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 ide({selected:e,objects:t,tracks:n,frame:r,frameCount:i,fps:a,motion:o,run:s}){let[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(null),d=(0,Q.useMemo)(()=>new Map(t.map(e=>[e.id,e])),[t]),f=tde(n,c),p=e?.id??null,m=p?que(d,f,p):null,h=m?Xue(d,p,r,{frameCount:i,fps:a,objectTracks:f}):null,g=m?n.get(m.id):null,_=g?.characterId??null,v=m?Jue(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,Q.useMemo)(()=>{if(!S||!T)return null;let e={frameCount:E,pos:C,quat:w,hold:T},t=x?x.split(`,`).map(Number):[];return rde(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,Q.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:Zue(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?Que(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`,nde(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 ade({trail:e}){let t=(0,Q.useMemo)(()=>e?new pl().setFromPoints(e.points.map(e=>new Z(...e))):null,[e]);(0,Q.useEffect)(()=>()=>t?.dispose(),[t]);let n=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{n.current?.traverse(e=>e.layers.set(5))}),e?(0,$.jsxs)(`group`,{ref:n,children:[(0,$.jsx)(`line`,{geometry:t,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{color:i5,transparent:!0,opacity:.8,depthTest:!1,depthWrite:!1})}),e.keys.map((e,t)=>(0,$.jsxs)(`mesh`,{position:e,renderOrder:997,children:[(0,$.jsx)(`sphereGeometry`,{args:[.025,10,8]}),(0,$.jsx)(`meshBasicMaterial`,{color:i5,depthTest:!1,depthWrite:!1,transparent:!0})]},t))]}):null}var a5=[{axis:`x`,dir:new Z(1,0,0),color:`#ff5340`},{axis:`y`,dir:new Z(0,1,0),color:`#54e05c`},{axis:`z`,dir:new Z(0,0,1),color:`#3d8bff`}],o5={x:a5[0].dir,y:a5[1].dir,z:a5[2].dir},ode=[{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,sde=.05,l5=.14,u5=.52,cde=.28,lde=`#ffd23d`,d5=.022,f5=.09,p5=.09,ude=.07,dde=.16;function fde(e){return(e.y??0)+Math.max(oe(e).height/2,.25)}function m5(e){return e.corner?`corner:${e.corner.id}`:e.axis??(e.plane?`plane:${e.plane.id}`:`centre`)}var pde=[{id:`tr`,sx:1,sy:1},{id:`tl`,sx:-1,sy:1},{id:`br`,sx:1,sy:-1},{id:`bl`,sx:-1,sy:-1}],mde=new Xs(new Z(0,1,0),0);function h5(e,t,n){return t?.pose?n.fromArray(t.pose.centre):n.set(e.x,fde(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=nE,onChange:l,onSelect:u,onGroundClick:d,onDragStart:f,onDragEnd:p,claimPointer:m,held:h=null}){let{gl:g,scene:_}=ry(),v=e=>{let t={x:e.left,y:e.top,w:e.width,h:e.height};return c?$T(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,Q.useRef)(null),x=(0,Q.useRef)(new Map),S=(0,Q.useRef)(null),C=(0,Q.useRef)({}),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(null),O=(0,Q.useRef)(null),k=(0,Q.useRef)(null),A=(0,Q.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,Q.useMemo)(()=>({raycaster:new ll,ndc:new kd,hit:new Z,delta:new Z,eye:new Z,origin:new Z,camPos:new Z}),[]),M=(0,Q.useMemo)(()=>a5.map(({axis:e,dir:t})=>{let n=new Tu().setFromUnitVectors(new Z(0,1,0),t);return{axis:e,u:new Z(1,0,0).applyQuaternion(n),v:new Z(0,0,1).applyQuaternion(n)}}),[]),N=(0,Q.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,Q.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,Q.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+=Sa((e-n.lastAngle)*180/Math.PI),n.lastAngle=e,n.held)return void A.current.held?.rotate(n.dir,ede(n.turned,o?5:0));if(n.axis===`screen`){let e=os(n.start,n.dir,n.turned,o?void 0:0);e&&i?.(n.id,e,n.token);return}let t=fi(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=qn(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($ue(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,No(n.start,t,j.delta.dot(o5[t]),o?void 0:0));i?.(n.id,e,n.token);return}let s=No(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 Tu(...t)):i;p=new Xs().setFromNormalAndCoplanarPoint(n,j.origin.clone());let a=new Z;if(!j.raycaster.ray.intersectPlane(p,a))return!1;let o=new Z(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 Z().crossVectors(j.eye,new Z(0,1,0)).normalize(),t=e.clone().cross(j.eye).cross(e).normalize();p=new Xs().setFromNormalAndCoplanarPoint(t,j.origin.clone());let n=new Z;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 Z(Math.cos(e),0,-Math.sin(e)),n=new Z(0,1,0),r=new Z().crossVectors(t,n).normalize();p=new Xs().setFromNormalAndCoplanarPoint(r,j.origin.clone());let a=new Z;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 Xs().setFromNormalAndCoplanarPoint(e,j.origin.clone());let t=new Z;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 Xs().setFromNormalAndCoplanarPoint(e,j.origin.clone());let t=new Z;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),Gue(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(mde,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]),iy(()=>{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)*dde)),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 Tu(...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,Q.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 Z).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,Q.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}))},ee=e=>t=>{t&&(t.layers.set(5),t.userData[$8]=!0,x.current.set(`corner:${e.id}`,{mesh:t,axis:null,corner:e}))},B=(0,$.jsx)(`meshBasicMaterial`,{visible:!1}),V=w===`screen`,H=E===`screen`,U=w===`centre`,W=E===`centre`;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ade,{trail:h?.trail??null}),(0,$.jsxs)(`group`,{ref:b,position:h5(e,h,new Z).toArray(),quaternion:g5(h,n)??[0,0,0,1],renderOrder:999,children:[a5.map(({axis:e,dir:t,color:r})=>{let i=new Tu().setFromUnitVectors(new Z(0,1,0),t),a=w===e,o=E===e,s=a?lde:r,c=a?2.2:o?3.6:2.2,l=(e=.95)=>(0,$.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:s,emissiveIntensity:c,toneMapped:!1,depthTest:!1,depthWrite:!1,transparent:!0,opacity:e});return(0,$.jsx)(`group`,{quaternion:i,children:n===`rotate`?(0,$.jsxs)(`group`,{ref:R(e),rotation:[Math.PI/2,0,0],children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`torusGeometry`,{args:[u5,d5,8,24,Math.PI]}),l()]}),(0,$.jsxs)(`mesh`,{rotation:[0,0,Math.PI],renderOrder:999,children:[(0,$.jsx)(`torusGeometry`,{args:[u5,d5,8,24,Math.PI]}),l(cde)]}),(0,$.jsxs)(`mesh`,{ref:L(e,t),children:[(0,$.jsx)(`torusGeometry`,{args:[u5,ude,6,32]}),B]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`mesh`,{position:[0,s5/2,0],renderOrder:999,children:[(0,$.jsx)(`cylinderGeometry`,{args:[c5,c5,s5,8]}),l()]}),(0,$.jsxs)(`mesh`,{position:[0,s5+(n===`scale`?f5/2:l5/2),0],renderOrder:999,children:[n===`scale`?(0,$.jsx)(`boxGeometry`,{args:[f5,f5,f5]}):(0,$.jsx)(`coneGeometry`,{args:[sde,l5,14]}),l()]}),(0,$.jsxs)(`mesh`,{ref:L(e,t),position:[0,(s5+l5)/2,0],children:[(0,$.jsx)(`cylinderGeometry`,{args:[p5,p5,s5+l5,8]}),B]})]})},e)}),n===`rotate`&&(0,$.jsxs)(`group`,{ref:S,children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`torusGeometry`,{args:[.68,.022,8,64]}),(0,$.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:V?`#ffd23d`:`#f2f2f2`,emissiveIntensity:V?2.2:H?3.6:2.2,toneMapped:!1,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})]}),(0,$.jsxs)(`mesh`,{ref:L(`screen`,null),children:[(0,$.jsx)(`torusGeometry`,{args:[.68,.07,6,48]}),B]})]}),n===`move`&&ode.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,$.jsxs)(`group`,{position:t,rotation:r,children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`planeGeometry`,{args:[.2,.2]}),(0,$.jsx)(`meshBasicMaterial`,{color:i?`#ffd23d`:e.color,transparent:!0,opacity:i?.6:a?.55:.34,side:2,depthTest:!1,depthWrite:!1})]}),(0,$.jsxs)(`mesh`,{ref:z(e),children:[(0,$.jsx)(`planeGeometry`,{args:[.2*1.5,.2*1.5]}),(0,$.jsx)(`meshBasicMaterial`,{visible:!1,side:2})]})]},e.id)}),n===`scale`&&e?.renderer===`cutout`&&pde.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,$.jsxs)(`group`,{position:u,children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`boxGeometry`,{args:[.085,.085,.085]}),(0,$.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:o?`#ffd23d`:`#f2f2f2`,emissiveIntensity:o?2:s?3.4:2,toneMapped:!1,depthTest:!1,depthWrite:!1})]}),(0,$.jsxs)(`mesh`,{ref:ee(t),children:[(0,$.jsx)(`sphereGeometry`,{args:[.13,8,6]}),B]})]},a)}),n===`scale`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`boxGeometry`,{args:[.11,.11,.11]}),(0,$.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:U?`#ffd23d`:`#f2f2f2`,emissiveIntensity:U?2:W?3.4:2,toneMapped:!1,depthTest:!1,depthWrite:!1})]}),(0,$.jsxs)(`mesh`,{ref:L(null,null),children:[(0,$.jsx)(`sphereGeometry`,{args:[.16,8,6]}),B]})]})]})]})}function hde({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?Y(`your AI video tool`,`AI 영상 도구`):Y(`your selected image model`,`선택한 이미지 모델`)),u=!!e.frame,d;return d=c&&e.frameB?(0,$.jsxs)(`p`,{children:[Y(`Paste the prompt into ${l}, set `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},设置 `),(0,$.jsx)(`code`,{children:`blocking-frame-A-start.png`}),Y(` as the start frame, and `,`를 시작 프레임으로, `,` 作为起始帧,并将 `),(0,$.jsx)(`code`,{children:`blocking-frame-B-end.png`}),Y(` as the end frame.`,`를 끝 프레임으로 설정하세요.`)]}):c&&u?(0,$.jsxs)(`p`,{children:[Y(`Paste the prompt into ${l} and attach `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},并附加 `),(0,$.jsx)(`code`,{children:`blocking-frame.png`}),Y(` as the reference frame.`,`를 참고 프레임으로 첨부하세요.`,` 作为参考帧。`)]}):u?(0,$.jsxs)(`p`,{children:[Y(`Paste the prompt into ${l} and attach `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},并附加 `),(0,$.jsx)(`code`,{children:`blocking-frame.png`}),Y(` as the reference image.`,`를 참고 이미지로 첨부하세요.`,` 作为参考图像。`)]}):(0,$.jsx)(`p`,{children:Y(`Paste the copied prompt into ${l} to create the scene.`,`복사한 프롬프트를 ${l}에 붙여 넣어 장면을 만드세요.`,`将复制的提示词粘贴到 ${l} 以创建场景。`)}),(0,$.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,$.jsxs)(`div`,{className:`modal result-modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`result-title`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(`h3`,{id:`result-title`,children:Y(`Your shot is ready`,`장면이 준비됐어요`)}),(0,$.jsx)(`button`,{type:`button`,className:`x`,onClick:r,"aria-label":Y(`Close the result`,`결과 닫기`),children:`✕`})]}),e.frameB?(0,$.jsxs)(`div`,{className:`move-frames`,children:[(0,$.jsxs)(`figure`,{children:[(0,$.jsx)(`img`,{className:`preview`,src:e.frame,alt:Y(`Camera move start frame`,`카메라 움직임 시작 프레임`)}),(0,$.jsxs)(`figcaption`,{children:[`A · `,Y(`Start`,`시작`)]})]}),(0,$.jsxs)(`figure`,{children:[(0,$.jsx)(`img`,{className:`preview`,src:e.frameB,alt:Y(`Camera move end frame`,`카메라 움직임 끝 프레임`)}),(0,$.jsxs)(`figcaption`,{children:[`B · `,Y(`End`,`끝`)]})]})]}):e.frame&&(0,$.jsx)(`img`,{className:`preview`,src:e.frame,alt:Y(`Finished scene frame`,`완성된 장면 프레임`)}),e.move&&(0,$.jsxs)(`div`,{className:`move-slate result-move-slate`,children:[(0,$.jsxs)(`span`,{children:[e.move.displaySlate??e.move.slate,` · `,e.move.spanS,Y(`s`,`초`,`秒`)]}),(0,$.jsx)(`small`,{children:Y(`Camera move made from timeline keyframes`,`타임라인 키프레임으로 만든 카메라 움직임`)})]}),(0,$.jsxs)(`label`,{className:`modal-label`,children:[Y(`Prompt`,`프롬프트`),` `,t&&(0,$.jsxs)(`em`,{children:[`· `,Y(`copied`,`복사됨`)]})]}),(0,$.jsx)(`div`,{className:`promptbox`,children:e.prompt}),(0,$.jsxs)(`div`,{className:`modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:i,children:t?Y(`Copied ✓`,`복사됨 ✓`):Y(`Copy prompt`,`프롬프트 복사`)}),e.frame&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:a,disabled:o,children:e.downloaded?Y(`Exported`,`내보냄`):e.frameB?Y(`Export start and end frames`,`시작·끝 프레임 내보내기`):Y(`Export frame`,`프레임 내보내기`)})]}),s,(0,$.jsxs)(`section`,{className:`result-next`,"aria-labelledby":`result-next-title`,children:[(0,$.jsx)(`span`,{className:`result-next-kicker`,children:Y(`Next · ${l}`,`다음 · ${l}`,`下一步 · ${l}`)}),(0,$.jsx)(`h4`,{id:`result-next-title`,children:Y(`Handing off to your AI`,`AI에 넣는 순서`)}),(0,$.jsx)(`div`,{className:`result-next-intro`,children:d}),(0,$.jsxs)(`ol`,{className:`result-handoff-steps`,children:[(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:Y(`Copy the prompt`,`프롬프트 복사`)}),(0,$.jsx)(`span`,{children:t?Y(`Copied. Paste it into your AI service's prompt box.`,`복사됐어요. AI 서비스의 입력창에 붙여 넣으세요.`):Y(`Press “Copy prompt” above, then paste it into your AI service.`,`위의 ‘프롬프트 복사’를 누른 뒤 AI 서비스 입력창에 붙여 넣으세요.`)})]}),(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:Y(`Export the frame`,`프레임 내보내기`)}),(0,$.jsx)(`span`,{children:e.frameB?Y(`Press “Export start and end frames” to save both PNGs.`,`‘시작·끝 프레임 내보내기’를 눌러 두 PNG를 저장하세요.`):u?Y(`Press “Export frame” to save the PNG.`,`‘프레임 내보내기’를 눌러 PNG를 저장하세요.`):Y(`This result has no frame to export.`,`이 결과에는 내보낼 프레임이 없어요.`)})]}),(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:Y(`Attach the image to your AI`,`AI에 이미지 첨부`)}),(0,$.jsx)(`span`,{children:e.frameB?Y(`Use your AI service's image attach button to upload the start and end frames together.`,`AI 서비스의 이미지 첨부 버튼에서 시작 프레임과 끝 프레임을 함께 올리세요.`):Y(`Use your AI service's image attach button to upload blocking-frame.png.`,`AI 서비스의 이미지 첨부 버튼에서 blocking-frame.png를 올리세요.`)})]})]}),(0,$.jsx)(`p`,{className:`result-handoff-note`,children:Y(`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,$.jsxs)(`p`,{className:`result-reference-video`,children:[(0,$.jsx)(`strong`,{children:Y(`Optional · Reference video`,`선택 사항 · 참고 영상`)}),Y(`A video recorded with the recording feature: `,`녹화 기능으로 만든 `),(0,$.jsx)(`code`,{children:n}),Y(` 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 gde(){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 _de=3;function vde({rig:e,take:t,objects:n,propTake:r}){let i=ms(Io),a=BB(),o=ry(e=>e.scene),s=ry(e=>e.gl),c=ry(e=>e.invalidate),l=(0,Q.useMemo)(()=>new iQ({layer:5}),[]),u=a.mode!==`off`&&!!e&&Ba(t),d=(0,Q.useMemo)(()=>u&&a.mode===`keys`?GB(t,n):[],[u,a.mode,t,n]),f=(0,Q.useMemo)(()=>u?HB({frame:i,last:t.frameCount-1,...a,keyFrames:d}):[],[u,i,t,a,d]);return(0,Q.useEffect)(()=>{if(u)return o.add(l.object),()=>{o.remove(l.object)}},[u,o,l]),(0,Q.useEffect)(()=>()=>l.dispose(),[l]),(0,Q.useEffect)(()=>{c()},[c,u,f]),(0,Q.useEffect)(()=>{typeof window<`u`&&(window.__cozyclayGhosts={set:l,gl:s,scene:o,entries:f})},[l,s,o,f]),iy(()=>{l.show(u&&!!e.parent)&&(l.setRig(e),l.syncSources(o,n,t,_de),e.parent.updateWorldMatrix(!0,!1),l.update({entries:f,take:t,placement:e.parent.matrixWorld,propTake:r,objects:n,count:a.count}))}),null}var yde=3,bde=.3,b5=.042,x5={w:512,h:96},xde=()=>{},S5=new WeakMap;function Sde(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 Cde(){let e=document.createElement(`canvas`);Object.assign(e,{width:x5.w,height:x5.h});let t=new Wl(e);t.colorSpace=Vu;let n=new Mp(new Qp({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=xde,n.userData={canvas:e,texture:t,text:null},n}function wde(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=Ia,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`:Ia,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 Tde({set:e,label:t,draft:n,rig:r,scene:i,objects:a,propTake:o}){let s=n?bo(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,yde),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(Ia).multiplyScalar(1.15),l.material.opacity=s.opacity;let u=Sde(l.rig);u&&(e.object.updateMatrixWorld(!0),u.getWorldPosition(t.position),t.position.y+=bde,t.material.opacity=Math.min(1,s.opacity/Lo))}function Ede({rigs:e,objects:t}){let n=(0,Q.useSyncExternalStore)(vi,As,As),r=(0,Q.useMemo)(()=>hs(),[n]),i=na(),a=ry(e=>e.scene),o=ry(e=>e.invalidate),s=(0,Q.useMemo)(()=>new iQ({layer:5}),[]),c=(0,Q.useMemo)(()=>Cde(),[]),l=r?e?.[r.characterId]??null:null,u=i&&!!l&&!!r?.take,d=(0,Q.useMemo)(()=>r?.take?{frameCount:r.take.frameCount,fps:r.take.fps,objectTracks:eQ(r.take)}:null,[r]);return(0,Q.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,Q.useEffect)(()=>()=>{s.dispose(),c.material.dispose(),c.userData.texture.dispose()},[s,c]),(0,Q.useEffect)(()=>{r&&wde(c,Ja(r),r.qa?.total===0)},[r,c]),(0,Q.useEffect)(()=>{if(o(),!u)return;let e=setInterval(()=>{(bo(r,Date.now()).shown||s.object.visible)&&o()},1e3/(r.take.fps||24));return()=>clearInterval(e)},[u,r,s,o]),iy(()=>Tde({set:s,label:c,draft:u?r:null,rig:l,scene:a,objects:t,propTake:d})),null}var Dde=.42,Ode=.2,kde=420,Ade=Math.PI/180,jde=44,Mde=()=>{},Nde=e=>1-(1-e)**3;function Pde(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 af().compose(new Z(r.x,r.y,r.z),new Tu().setFromAxisAngle(new Z(0,1,0),r.rot*Ade),new Z(1,1,1))}function Fde(e,t){let n=[];for(let r of e){let e=Pde(r,t);for(let t of Qt(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 af().fromArray(a))})}}return n}var Ide=class{root=new el;meshes=new Map;constructor(){this.root.name=`sculpt-sketch`,this.root.userData.sculptSketch=!0}make(e,t){let n=f8(e.shape===`scatter`?{...e,shape:`blob`,roundness:.5,taper:0}:e),r=new jf({color:e.color,emissive:e.color,emissiveIntensity:.18,roughness:.85,metalness:0,transparent:!0,opacity:0,depthWrite:!1}),i=new rd(n,r);return Object.assign(i,{raycast:Mde,castShadow:!1,receiveShadow:!1,matrixAutoUpdate:!1,renderOrder:jde,frustumCulled:!1}),i.layers.set(5),i.userData.sculptSketch=!0,this.root.add(i),{mesh:i,base:new af,born:t,opacity:e.shape===`scatter`?Ode:Dde}}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 af;for(let r of this.meshes.values()){let i=Math.min(1,Math.max(0,(e-r.born)/kde)),a=Nde(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 Lde({objects:e}){let t=(0,Q.useSyncExternalStore)(pn,Sn,Sn),n=ry(e=>e.scene),i=ry(e=>e.invalidate),a=(0,Q.useMemo)(()=>new Ide,[]),o=(0,Q.useMemo)(()=>Fde(t,e),[t,e]);return(0,Q.useEffect)(()=>(n.add(a.root),typeof window<`u`&&(window.__cozyclaySculptSketch={frame:yt,clear:r,meshes:()=>a.meshes.size,root:a.root}),()=>{n.remove(a.root),a.dispose()}),[n,a]),(0,Q.useEffect)(()=>{a.update(o,performance.now()),i()},[a,o,i]),iy(()=>{a.frame(performance.now())&&i()}),null}function C5(e){if(!e)throw Error(`Assertion failed.`)}var w5=e=>e&&e[e.length-1],T5=e=>e>=0&&e<2**32,E5=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)},D5=e=>{let t=E5(e);return t&1?t+1>>1:-(t>>1)},O5=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),k5=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),A5=new TextEncoder,j5={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},M5={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},N5={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Rde=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,P5=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),F5=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}},zde=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},I5=e=>{throw Error(`Unexpected value: ${e}`)},Bde=(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))},Vde=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Hde=/^[a-z]{3}$/,Ude=e=>Hde.test(e),L5=1e6*(1+2**-52),Wde=(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}},R5=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Gde=e=>{C5(Number.isInteger(e.num)),C5(Number.isInteger(e.den)),C5(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}},z5=e=>Array.isArray(e)?e:[e],B5=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)}}},Kde=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),V5;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(V5||={});var H5=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==V5.Silent&&t!==V5.Errors&&t!==V5.Warnings&&t!==V5.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 B5}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=V5.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=V5.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=V5.Info&&console.info(...t)}};H5._level=V5.Info,H5._emitterInstance=null;var U5=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.`)}},qde=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.`)}},Jde=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 U5)&&!(t instanceof qde)&&!Kde(t))throw TypeError(`Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},Yde=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.`)},W5=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}},G5=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],K5=[-1,1,2,3,4,5,6,8],Xde=e=>{let t=G5.indexOf(e.sampleRate),n=null;t===-1&&(t=15,n=e.sampleRate);let r=K5.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 W5(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},q5=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],J5=[`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`],Y5=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],X5=[...Y5,...J5],Z5=[`webvtt`],Q5=[{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}],$5=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],e7=[`dtsc`,`dtsh`,`dtsl`,`dtse`],Zde=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]},t7=/^pcm-([usf])(\d+)(be)?$/,n7=e=>{if(C5(J5.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=t7.exec(e);C5(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}},r7=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`:$5.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`:e7.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:t7.test(e)?e:e===`webvtt`?`webvtt`:null,Qde=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...$5],$de=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,efe=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,tfe=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,nfe=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,i7=(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(!Qde.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&&!P5(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(j5);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(M5);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(N5);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(!$de.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(!efe.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(!tfe.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(!nfe.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($5.some(t=>e.decoderConfig.codec.startsWith(t))&&!$5.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: ${$5.join(`, `)}.`);if(t!==null&&r7(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},rfe=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],a7=(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(!rfe.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&&!P5(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(!e7.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${e7.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!J5.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${J5.join(`, `)}).`);if(t!==null&&r7(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},ife=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.`)},afe=[48e3,44100,32e3],ofe=[24e3,22050,16e3],o7;(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`})(o7||={});var s7;(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`})(s7||={});var c7=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})},sfe=e=>e&31,l7=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 cfe=(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:Bde(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},lfe=e=>{try{let t=[],n=[],r=[];for(let i of c7(e)){let a=e.subarray(i.offset,i.offset+i.length),o=sfe(a[0]);o===o7.SPS?t.push(a):o===o7.PPS?n.push(a):o===o7.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=dfe(i);C5(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 H5._error(`Error building AVC Decoder Configuration Record:`,e),null}},ufe=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){C5(e.chromaFormat!==null),C5(e.bitDepthLumaMinus8!==null),C5(e.bitDepthChromaMinus8!==null),C5(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)},u7={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}},dfe=e=>{try{let t=new W5(l7(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let n=t.readAlignedByte(),r=t.readAlignedByte(),i=t.readAlignedByte();E5(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=E5(t),a===3&&(c=t.readBits(1)),o=E5(t),s=E5(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=D5(t);i=(r+e+256)%256}r=i===0?r:i}}}E5(t);let l=E5(t);if(l===0)E5(t);else if(l===1){t.skipBits(1),D5(t),D5(t);let e=E5(t);for(let n=0;n<e;n++)D5(t)}E5(t),t.skipBits(1);let u=E5(t),d=E5(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=E5(t),n=E5(t),r=E5(t),i=E5(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=u7[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)&&(E5(t),E5(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&d7(t);let n=t.readBits(1);n&&d7(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),E5(t),E5(t),E5(t),E5(t),S=E5(t),C=E5(t))}if(S===null){C5(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=Q5.find(e=>e.level>=i)??w5(Q5),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);S=a,C=a}}return C5(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 H5._error(`Error parsing AVC SPS:`,e),null}},d7=e=>{let t=E5(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)E5(e),E5(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},f7=e=>e>>1&63,ffe=e=>{try{let t=new W5(l7(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}=mfe(t,n);E5(t);let u=E5(t),d=0;u===3&&(d=t.readBits(1));let f=E5(t),p=E5(t),m=f,h=p;if(t.readBits(1)){let e=E5(t),n=E5(t),r=E5(t),i=E5(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=E5(t),_=E5(t);E5(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)E5(t),y=E5(t),E5(t);if(E5(t),E5(t),E5(t),E5(t),E5(t),E5(t),t.readBits(1)&&t.readBits(1)&&hfe(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),E5(t),E5(t),t.skipBits(1)),gfe(t,E5(t)),t.readBits(1)){let e=E5(t);for(let n=0;n<e;n++)E5(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=vfe(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 H5._error(`Error parsing HEVC SPS:`,e),null}},pfe=e=>{try{let t=[],n=[],r=[],i=[];for(let a of c7(e)){let o=e.subarray(a.offset,a.offset+a.length),s=f7(o[0]);s===s7.VPS_NUT?t.push(o):s===s7.SPS_NUT?n.push(o):s===s7.PPS_NUT?r.push(o):(s===s7.PREFIX_SEI_NUT||s===s7.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=ffe(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new W5(l7(e));t.skipBits(16),E5(t),E5(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),E5(t),E5(t),D5(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&E5(t),D5(t),D5(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:s7.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:s7.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:s7.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:f7(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 H5._error(`Error building HEVC Decoder Configuration Record:`,e),null}},mfe=(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}},hfe=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))E5(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&D5(e);for(let t=0;t<n;t++)D5(e)}},gfe=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=_fe(e,r,t,n)},_fe=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(E5(e)+1):t-1,e.readBits(1),E5(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=E5(e),n=E5(e);for(let n=0;n<t;n++)E5(e),e.readBits(1);for(let t=0;t<n;t++)E5(e),e.readBits(1);i=t+n}return i},vfe=(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=u7[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)&&(E5(e),E5(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(E5(e),E5(e),E5(e),E5(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&E5(e),e.readBits(1)&&yfe(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=E5(e),E5(e),E5(e),E5(e),E5(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},yfe=(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?E5(e):o=e.readBits(1)===1;let s=1;o||(s=E5(e)+1),r&&p7(e,s,a),i&&p7(e,s,a)}},p7=(e,t,n)=>{for(let r=0;r<t;r++)E5(e),E5(e),n&&(E5(e),E5(e)),e.readBits(1)},bfe=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)},xfe;(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`})(xfe||={});var Sfe=e=>{let t=k5(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}},Cfe;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(Cfe||={});var wfe=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new W5(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 Tfe=[1,2,3,6],Efe=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new W5(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=Tfe[o],d;return d=i<3?afe[i]/1e3:ofe[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}]}},Dfe=8,Ofe=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],kfe=[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],Afe=[16,16,20,20,0,24,24,0],m7=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],jfe=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Mfe=8,Nfe=[32e3,44100,48e3,0],Pfe=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ffe=[512,1024,2048,4096],Ife=e=>{let t=Lfe(e),n=k5(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=Rfe(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}},Lfe=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new W5(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%Dfe!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=m7.length)return null;let o=Ofe[t.readBits(4)];if(o===0)return null;let s=kfe[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=Afe[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:m7[a]+ +!!u,sampleCount:r*32,channelLayout:jfe[a]|(u?Mfe:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},Rfe=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new W5(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=Nfe[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*Vde(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=Pfe[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}}},zfe=e=>{let t=new Uint8Array(20),n=k5(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 W5(t);return i.seekToByte(13),i.writeBits(2,Math.max(Ffe.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},h7=new Uint8Array,g7=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===h7&&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===h7}get microsecondTimestamp(){return Math.trunc(L5*this.timestamp)}get microsecondDuration(){return Math.trunc(L5*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)}},Bfe=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},_7=e=>{let t=e.filePos,n=new W5(Ufe(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}},Vfe=n(((e,t)=>{t.exports={}})),v7=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,k5(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)}},Hfe=(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.`)},Ufe=(e,t)=>{Hfe(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},Wfe=class{constructor(e){this.mutex=new F5,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)}}},y7=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Gfe=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`)},b7=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);C5(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}}},x7=new Uint8Array(8),S7=new DataView(x7.buffer),C7=e=>[(e%256+256)%256],w7=e=>(S7.setUint16(0,e,!1),[x7[0],x7[1]]),T7=e=>(S7.setInt16(0,e,!1),[x7[0],x7[1]]),E7=e=>(S7.setUint32(0,e,!1),[x7[1],x7[2],x7[3]]),D7=e=>(S7.setUint32(0,e,!1),[x7[0],x7[1],x7[2],x7[3]]),O7=e=>(S7.setInt32(0,e,!1),[x7[0],x7[1],x7[2],x7[3]]),k7=e=>(S7.setUint32(0,Math.floor(e/2**32),!1),S7.setUint32(4,e,!1),[x7[0],x7[1],x7[2],x7[3],x7[4],x7[5],x7[6],x7[7]]),Kfe=e=>(S7.setInt32(0,Math.floor(e/2**32),!1),S7.setUint32(4,e,!1),[x7[0],x7[1],x7[2],x7[3],x7[4],x7[5],x7[6],x7[7]]),A7=e=>(S7.setInt16(0,2**8*e,!1),[x7[0],x7[1]]),j7=e=>(S7.setInt32(0,2**16*e,!1),[x7[0],x7[1],x7[2],x7[3]]),M7=e=>(S7.setInt32(0,2**30*e,!1),[x7[0],x7[1],x7[2],x7[3]]),N7=(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()},P7=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},F7=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]},I7=F7(0),L7=e=>[j7(e[0]),j7(e[1]),M7(e[2]),j7(e[3]),j7(e[4]),M7(e[5]),j7(e[6]),j7(e[7]),M7(e[8])],R7=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),z7=(e,t,n,r,i)=>R7(e,[C7(t),E7(n),r??[]],i),qfe=e=>e.isQuickTime?R7(`ftyp`,[P7(`qt `),D7(512),P7(`qt `)]):e.fragmented?e.cmaf?R7(`ftyp`,[P7(`iso5`),D7(512),P7(`iso5`),P7(`iso6`),P7(`mp41`),P7(`cmfc`),P7(`dash`)]):R7(`ftyp`,[P7(`iso5`),D7(512),P7(`iso5`),P7(`iso6`),P7(`mp41`)]):R7(`ftyp`,[P7(`isom`),D7(512),P7(`isom`),e.holdsAvc?P7(`avc1`):[],P7(`mp41`)]),B7=()=>R7(`styp`,[P7(`iso5`),D7(0),P7(`iso5`),P7(`iso6`),P7(`mp41`),P7(`cmfc`),P7(`dash`)]),V7=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),z7(`sidx`,1,0,[D7(1),D7(u9),k7(d9(e.minWrittenTimestamp,u9)),k7(0),w7(0),w7(1),D7(t&2147483647),D7(d9(n,u9)),D7(0)])},H7=e=>({type:`mdat`,largeSize:e}),Jfe=e=>({type:`free`,size:e}),U7=e=>R7(`moov`,void 0,[Yfe(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Xfe(t,e.creationTime)),e.isFragmented?Npe(e.trackDatas):null,Kpe(e)]),Yfe=(e,t)=>{let n=Math.max(0,...t.map(e=>d9(W7(e),u9)+d9(e.startTimestampOffset??0,u9))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!T5(e)||!T5(n),a=i?k7:D7;return z7(`mvhd`,+i,0,[a(e),a(e),D7(u9),a(n),j7(1),A7(1),Array(10).fill(0),L7(I7),Array(24).fill(0),D7(r)])},W7=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},Xfe=(e,t)=>{let n=rme(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return R7(`trak`,void 0,[Zfe(e,t),r?Qfe(e,e.startTimestampOffset):null,$fe(e,t),n.name===void 0?null:R7(`udta`,void 0,[R7(`name`,[...A5.encode(n.name)])])])},Zfe=(e,t)=>{let n=d9(W7(e),u9)+d9(e.startTimestampOffset??0,u9),r=!T5(t)||!T5(n),i=r?k7:D7,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=F7(t??0)}else a=I7;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:I5(e);return z7(`tkhd`,+r,o,[i(t),i(t),D7(e.track.id),D7(0),i(n),Array(8).fill(0),w7(0),w7(s),A7(+(e.type===`audio`)),w7(0),L7(a),j7(e.type===`video`?e.info.width:0),j7(e.type===`video`?e.info.height:0)])},Qfe=(e,t)=>{let n=d9(t,u9),r=d9(W7(e),u9),i=!T5(n)||!T5(r),a=i?k7:D7,o=i?Kfe:O7;return R7(`edts`,void 0,[z7(`elst`,+!!i,0,[D7(2),a(n),o(-1),j7(1),a(r),o(0),j7(1)])])},$fe=(e,t)=>R7(`mdia`,void 0,[epe(e,t),G7(!0,tpe[e.type],npe[e.type]),rpe(e)]),epe=(e,t)=>{let n=d9(W7(e),e.timescale),r=!T5(t)||!T5(n),i=r?k7:D7;return z7(`mdhd`,+r,0,[i(t),i(t),D7(e.timescale),i(n),w7(r9(e.track.metadata.languageCode??`und`)),w7(0)])},tpe={video:`vide`,audio:`soun`,subtitle:`text`},npe={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},G7=(e,t,n,r=`\0\0\0\0`)=>z7(`hdlr`,0,0,[e?P7(`mhlr`):D7(0),P7(t),P7(r),D7(0),D7(0),P7(n,!0)]),rpe=e=>R7(`minf`,void 0,[ipe[e.type](),ape(),cpe(e)]),ipe={video:()=>z7(`vmhd`,0,1,[w7(0),w7(0),w7(0),w7(0)]),audio:()=>z7(`smhd`,0,0,[w7(0),w7(0)]),subtitle:()=>z7(`nmhd`,0,0)},ape=()=>R7(`dinf`,void 0,[ope()]),ope=()=>z7(`dref`,0,0,[D7(1)],[spe()]),spe=()=>z7(`url `,0,1),cpe=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return R7(`stbl`,void 0,[lpe(e),Epe(e),t?jpe(e):null,t?Mpe(e):null,Ope(e),kpe(e),Ape(e),Dpe(e)])},lpe=e=>{let t;if(e.type===`video`)t=upe(Xpe(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=n9(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);C5(n),t=gpe(n,e)}else e.type===`subtitle`&&(t=wpe($pe[e.track.source._codec],e));return C5(t),z7(`stsd`,0,0,[D7(1)],[t])},upe=(e,t)=>R7(e,[[,,,,,,].fill(0),w7(1),w7(0),w7(0),Array(12).fill(0),w7(t.info.width),w7(t.info.height),D7(4718592),D7(4718592),D7(0),w7(1),C7(10),P7(`Mediabunny`),Array(21).fill(0),w7(t.info.hasAlphaChannel?32:24),T7(65535)],[Zpe[t.track.source._codec]?.(t)??null,dpe(t),Rde(t.info.decoderConfig.colorSpace)?fpe(t):null]),dpe=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:R7(`pasp`,[D7(e.info.pixelAspectRatio.num),D7(e.info.pixelAspectRatio.den)]),fpe=e=>R7(`colr`,[P7(e.muxer.isQuickTime?`nclc`:`nclx`),w7(j5[e.info.decoderConfig.colorSpace.primaries]),w7(M5[e.info.decoderConfig.colorSpace.transfer]),w7(N5[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:C7(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),ppe=e=>e.info.decoderConfig&&R7(`avcC`,[...O5(e.info.decoderConfig.description)]),mpe=e=>e.info.decoderConfig&&R7(`hvcC`,[...O5(e.info.decoderConfig.description)]),K7=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?j5[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?M5[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?N5[t.colorSpace.matrix]:2;return z7(`vpcC`,1,0,[C7(r),C7(i),C7(c),C7(l),C7(u),C7(d),w7(0)])},hpe=e=>R7(`av1C`,Zde(e.info.decoderConfig.codec)),gpe=(e,t)=>{let n=0,r,i=16,a=J5.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=n7(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),w7(1),w7(n),w7(0),D7(0),w7(t.info.numberOfChannels),w7(i),w7(0),w7(0),w7(t.info.sampleRate<2**16?t.info.sampleRate:0),w7(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),w7(1),w7(n),w7(0),D7(0),w7(t.info.numberOfChannels),w7(Math.min(i,16)),T7(e),w7(0),w7(t.info.sampleRate<2**16?t.info.sampleRate:0),w7(0),a?[D7(1),D7(i/8),D7(t.info.numberOfChannels*i/8)]:[D7(0),D7(0),D7(0)],D7(2)]}return R7(e,r,[Qpe(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},q7=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=[...C7(t),...C7(21),...E7(0),...D7(0),...D7(0)];if(e.info.decoderConfig.description){let t=O5(e.info.decoderConfig.description);n=[...n,...C7(5),...N7(t.byteLength),...t]}return n=[...w7(1),...C7(0),...C7(4),...N7(n.length),...n,...C7(6),...C7(1),...C7(2)],n=[...C7(3),...N7(n.length),...n],z7(`esds`,0,0,n)},J7=e=>R7(`wave`,void 0,[_pe(e),vpe(e),R7(`\0\0\0\0`)]),_pe=e=>R7(`frma`,[P7(n9(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),vpe=e=>{let{littleEndian:t}=n7(e.track.source._codec);return R7(`enda`,[w7(+t)])},ype=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){C5(s.byteLength>=18);let e=Sfe(O5(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return R7(`dOps`,[C7(0),C7(t),w7(n),D7(r),T7(i),C7(a),...o])},bpe=e=>{let t=e.info.decoderConfig?.description;return C5(t),z7(`dfLa`,0,0,[...O5(t).subarray(4)])},Y7=e=>{let{littleEndian:t,sampleSize:n}=n7(e.track.source._codec);return z7(`pcmC`,0,0,[C7(+t),C7(8*n)])},xpe=e=>{C5(e.info.primingPacket);let t=wfe(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 W5(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),R7(`dac3`,[...n])},Spe=e=>{C5(e.info.primingPacket);let t=Efe(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 W5(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 R7(`dec3`,[...i])},Cpe=e=>{C5(e.info.primingPacket);let t=Ife(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 R7(`ddts`,[...zfe(t)])},wpe=(e,t)=>R7(e,[[,,,,,,].fill(0),w7(1)],[eme[t.track.source._codec](t)]),Tpe=e=>R7(`vttC`,[...A5.encode(e.info.config.description)]),Epe=e=>z7(`stts`,0,0,[D7(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[D7(e.sampleCount),D7(e.sampleDelta)])]),Dpe=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return z7(`stss`,0,0,[D7(t.length),t.map(([e])=>D7(e+1))])},Ope=e=>z7(`stsc`,0,0,[D7(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[D7(e.firstChunk),D7(e.samplesPerChunk),D7(1)])]),kpe=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=n7(e.track.source._codec);return z7(`stsz`,0,0,[D7(t*e.info.numberOfChannels),D7(e.samples.reduce((t,n)=>t+d9(n.duration,e.timescale),0))])}return z7(`stsz`,0,0,[D7(0),D7(e.samples.length),e.samples.map(e=>D7(e.size))])},Ape=e=>e.finalizedChunks.length>0&&w5(e.finalizedChunks).offset>=2**32?z7(`co64`,0,0,[D7(e.finalizedChunks.length),e.finalizedChunks.map(e=>k7(e.offset))]):z7(`stco`,0,0,[D7(e.finalizedChunks.length),e.finalizedChunks.map(e=>D7(e.offset))]),jpe=e=>z7(`ctts`,1,0,[D7(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[D7(e.sampleCount),O7(e.sampleCompositionTimeOffset)])]),Mpe=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;C5(e.compositionTimeOffsetTable.length>0),C5(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,d9(n.timestamp,e.timescale)),i=Math.max(i,d9(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:z7(`cslg`,0,0,[O7(a),O7(t),O7(n),O7(r),O7(i)])},Npe=e=>R7(`mvex`,void 0,e.map(Ppe)),Ppe=e=>z7(`trex`,0,0,[D7(e.track.id),D7(1),D7(0),D7(0),D7(0)]),X7=(e,t)=>R7(`moof`,void 0,[Fpe(e),...t.map(Ipe)]),Fpe=e=>z7(`mfhd`,0,0,[D7(e)]),Z7=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Ipe=e=>R7(`traf`,void 0,[Lpe(e),Rpe(e),zpe(e)]),Lpe=e=>{C5(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:Z7(n)};return z7(`tfhd`,0,t,[D7(e.track.id),D7(r.duration),D7(r.size),D7(r.flags)])},Rpe=e=>(C5(e.currentChunk),z7(`tfdt`,1,0,[k7(d9(e.currentChunk.startTimestamp,e.timescale))])),zpe=e=>{C5(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Z7),i=e.currentChunk.samples.map(t=>d9(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,z7(`trun`,1,m,[D7(e.currentChunk.samples.length),D7(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?D7(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?D7(t[a]):[],d?D7(n[a]):[],f?D7(r[a]):[],p?O7(i[a]):[]])])},Bpe=e=>R7(`mfra`,void 0,[...e.map(Vpe),Hpe()]),Vpe=e=>z7(`tfra`,1,0,[D7(e.track.id),D7(63),D7(e.finalizedChunks.length),e.finalizedChunks.map(t=>[k7(d9(t.samples[0].timestamp,e.timescale)),k7(t.moofOffset),D7(t.trafIndex+1),D7(1),D7(1)])]),Hpe=()=>z7(`mfro`,0,0,[D7(0)]),Upe=()=>R7(`vtte`),Wpe=(e,t,n,r,i)=>R7(`vttc`,void 0,[i===null?null:R7(`vsid`,[O7(i)]),n===null?null:R7(`iden`,[...A5.encode(n)]),t===null?null:R7(`ctim`,[...A5.encode(Gfe(t))]),r===null?null:R7(`sttg`,[...A5.encode(r)]),R7(`payl`,[...A5.encode(e)])]),Gpe=e=>R7(`vtta`,[...A5.encode(e)]),Kpe=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Jpe(r);e&&t.push(e)}else if(n===`mdta`){let e=Ype(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&qpe(t,e.output._metadataTags);return t.length===0?null:R7(`udta`,void 0,t)},qpe=(e,t)=>{for(let{key:n,value:r}of R5(t))switch(n){case`title`:e.push(Q7(`©nam`,r));break;case`description`:e.push(Q7(`©des`,r));break;case`artist`:e.push(Q7(`©ART`,r));break;case`album`:e.push(Q7(`©alb`,r));break;case`albumArtist`:e.push(Q7(`albr`,r));break;case`genre`:e.push(Q7(`©gen`,r));break;case`date`:e.push(Q7(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(Q7(`©cmt`,r));break;case`lyrics`:e.push(Q7(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:I5(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(Q7(n,r)):r instanceof Uint8Array&&e.push(R7(n,Array.from(r))))}},Q7=(e,t)=>{let n=A5.encode(t);return R7(e,[w7(n.length),w7(r9(`und`)),Array.from(n)])},$7={"image/jpeg":13,"image/png":14,"image/bmp":27},e9=(e,t)=>{let n=[];for(let{key:r,value:i}of R5(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:t9(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:t9(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:t9(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:t9(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:t9(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:t9(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:t9(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:t9(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:t9(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:R7(`data`,[D7($7[e.mimeType]??0),D7(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:t9(t)})}else n.push({key:`trkn`,value:R7(`data`,[D7(0),D7(0),w7(0),w7(i),w7(e.tracksTotal??0),w7(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:R7(`data`,[D7(0),D7(0),w7(0),w7(i),w7(e.discsTotal??0),w7(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:I5(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:t9(i)}):i instanceof Uint8Array?n.push({key:r,value:R7(`data`,[D7(0),D7(0),Array.from(i)])}):i instanceof U5&&n.push({key:r,value:R7(`data`,[D7($7[i.mimeType]??0),D7(0),Array.from(i.data)])}))}return n},Jpe=e=>{let t=e9(e,!1);return t.length===0?null:z7(`meta`,0,0,void 0,[G7(!1,`mdir`,``,`appl`),R7(`ilst`,void 0,t.map(e=>R7(e.key,void 0,[e.value])))])},Ype=e=>{let t=e9(e,!0);return t.length===0?null:R7(`meta`,void 0,[G7(!1,`mdta`,``),z7(`keys`,0,0,[D7(t.length)],t.map(e=>R7(`mdta`,[...A5.encode(e.key)]))),R7(`ilst`,void 0,t.map((e,t)=>R7(String.fromCharCode(...D7(t+1)),void 0,[e.value])))])},t9=e=>R7(`data`,[D7(1),D7(0),...A5.encode(e)]),Xpe=(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}},Zpe={avc:ppe,hevc:mpe,vp8:K7,vp9:K7,av1:hpe,prores:null},n9=(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`}},Qpe=(e,t)=>{switch(e){case`aac`:return q7;case`mp3`:return q7;case`opus`:return ype;case`vorbis`:return q7;case`flac`:return bpe;case`ac3`:return xpe;case`eac3`:return Spe;case`dts`:return Cpe}if(t)switch(e){case`pcm-s24`:return J7;case`pcm-s24be`:return J7;case`pcm-s32`:return J7;case`pcm-s32be`:return J7;case`pcm-f32`:return J7;case`pcm-f32be`:return J7;case`pcm-f64`:return J7;case`pcm-f64be`:return J7}else switch(e){case`pcm-s16`:return Y7;case`pcm-s16be`:return Y7;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}return null},$pe={webvtt:`wvtt`},eme={webvtt:Tpe},r9=e=>{C5(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},i9=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(){C5(!this.started),this.target._start(),this.started=!0}write(e){C5(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 C5(this.started&&!this.finalized),this.target._flush()}async finalize(){C5(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}};Vfe();var a9=class extends B5{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 tme(this,e)}},o9=2**16,s9=2**32,c9=class extends a9{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(o9,{maxByteLength:s9})}catch{this._buffer=new ArrayBuffer(o9),this._supportsResize=!1}else this._buffer=new ArrayBuffer(o9);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>s9)throw Error(`ArrayBuffer exceeded maximum size of ${s9} 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)}},tme=class extends a9{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)}},l9=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.`)}},u9=57600,nme=2082844800,rme=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},d9=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},ime=class extends Wfe{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new c9,this.auxWriter=new i9(this.auxTarget,!1),this.auxBoxWriter=new b7(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=zde(),this.creationTime=Math.floor(Date.now()/1e3)+nme,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 v9,this.isCmaf=t instanceof _9,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof _9?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 c9:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new b7(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof c9&&`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 i9(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new b7(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(C5(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(qfe({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||(C5(this.writer),C5(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=H7(!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 Bfe({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;i7(n,e.source._codec),C5(n),C5(n.decoderConfig);let i={...n.decoderConfig};C5(i.codedWidth!==void 0),C5(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=lfe(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=ufe(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=pfe(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=bfe(e),a=!0}let o=Wde(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:Gde({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;a7(n,e.source._codec),C5(n),C5(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=_7(v7.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=G5[e.samplingFrequencyIndex],r=K5[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=Xde({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&&J5.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;ife(t),C5(t),C5(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=[...c7(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=cfe(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=_7(v7.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=n7(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=d9(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=n7(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)C5(r.timestamp<=t),C5(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=Upe();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;y7.lastIndex=0;let r=y7.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=Gpe(n.notes);this.auxBoxWriter.writeBox(e)}let c=Wpe(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:d9(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=d9(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=w5(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=d9(r.timestamp-r.decodeTimestamp,e.timescale),a=d9(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){C5(e.lastSample);let t=d9(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(C5(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=w5(e.timeToSampleTable);if(C5(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=w5(e.compositionTimeOffsetTable);C5(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=d9(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,C5(e.lastSample),C5(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){C5(t.type===`key`);let n=d9(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(C5(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}),C5(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(C5(!this.isFragmented),C5(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+d9(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||w5(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)C5(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(C5(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(C5(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;C5(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=U7(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){C5(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new b7(this.writer);let e=this.boxWriter.measureBox(B7()),t=this.boxWriter.measureBox(V7(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}C5(this.writer),C5(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=X7(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=X7(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}C5(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=H7(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(){C5(this.writer),C5(this.boxWriter),this.ensureOneEnabledTrack();let e=U7(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;C5(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=H7(!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(){C5(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;C5(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(){C5(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(C5(this.writer),C5(this.boxWriter),this.fastStart===`in-memory`){this.mdat=H7(!1);let e;for(let t=0;t<2;t++){let t=U7(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)C5(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=U7(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)C5(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(B7()),this.boxWriter.writeBox(V7(this,e))}else{let e=this.writer.getPos(),t=Bpe(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{C5(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);C5(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=U7(this);if(this.fastStart===`reserve`){C5(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(Jfe(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()}},f9=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})()}},p9=class extends f9{constructor(e){if(super(),this._connectedTrack=null,!q5.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${q5.join(`, `)}.`);this._codec=e}},ame=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},ome=class extends p9{constructor(e){super(e)}add(e,t){if(!(e instanceof g7))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(),ame(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},sme=class extends f9{constructor(e){if(super(),this._connectedTrack=null,!X5.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${X5.join(`, `)}.`);this._codec=e}},cme=class extends f9{constructor(e){if(super(),this._connectedTrack=null,!Z5.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Z5.join(`, `)}.`);this._codec=e}},m9=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>q5.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>X5.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Z5.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},h9=class extends m9{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 ime(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},g9=class extends h9{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...q5,...Y5,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Z5]}_codecUnsupportedHint(e){return new v9().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},_9=class extends h9{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...q5,...Y5,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Z5]}},v9=class extends h9{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...q5,...X5]}_codecUnsupportedHint(e){return new g9().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},y9=[`video`,`audio`,`subtitle`],b9=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=z5(this.metadata.group),r=z5(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}},lme=class extends b9{constructor(e,t,n,r){super(e,t,`video`,n,r)}},ume=class extends b9{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},dme=class extends b9{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},x9=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)}},S9=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Ude(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&&Yde(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 x9)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof x9))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},fme=class extends B5{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 x9,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new F5,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 m9))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof a9||e.target instanceof l9))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof a9&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof a9)&&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 a9&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){C5(this._target instanceof l9);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof a9))throw TypeError(`getTarget must return a Target.`);return e};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){C5(this._target instanceof l9);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(C5(this._initTarget!==null),this._initTarget instanceof a9)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 a9)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 i9(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof p9))throw TypeError(`source must be a VideoSource.`);if(S9(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&&i7({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof g7))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 lme(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof sme))throw TypeError(`source must be an AudioSource.`);if(S9(t),t.decoderConfig!==void 0&&a7({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof g7))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 ume(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof cme))throw TypeError(`source must be a SubtitleSource.`);S9(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new dme(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Jde(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 y9)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 y9){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?(H5._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 H5._warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&H5._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?(H5._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()}})()}},pme=e=>{if(e.startsWith(`avc1`))return`avc`;throw RangeError(`unsupported MP4 video codec: ${e}`)};async function mme({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 c9,a=new fme({format:new g9({fastStart:`in-memory`}),target:i}),o=new ome(pme(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 g7(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 hme=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 gme(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 _me(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 vme(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 C9(e,t){try{Object.defineProperty(e,"exportFailureCode",{value:e?.name===`AbortError`?`aborted`:t,configurable:!0})}catch{}return e}function w9(e,t){return t?new Promise((n,r)=>{let i=()=>{a(),r(T9())},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 yme(e,t,n,r,i){for(let a of hme){if(i?.aborted)throw T9();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 w9(r.isConfigSupported(o),i);if(e.supported)return e.config}catch(e){if(e?.name===`AbortError`)throw e}}throw i?.aborted?T9():C9(Error(`This browser has no H.264 WebCodecs encoder for MP4 export`),`unsupported_codec`)}function T9(){return new DOMException(`Offscreen export was cancelled`,`AbortError`)}async function bme({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 T9();let f=gme(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 C9(Error(`This browser does not support WebCodecs video export`),`unsupported_codec`);let p=await yme(r,i,n,u,o);if(o?.aborted)throw T9();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 T9();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 T9();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 w9(_me(u),o);if(g.push(p),vme(u,e,r,i),y=`encode_failed`,o?.aborted)throw T9();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 w9(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 w9(v.flush(),o),o?.aborted))throw T9();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 mme({chunks:m,codec:p.codec,decoderConfig:h??{codec:p.codec,codedWidth:r,codedHeight:i},signal:o});if(o?.aborted)throw T9();return{...f,fps:n,width:r,height:i,codec:p.codec,mimeType:S.type,encodedFrameCount:m.length,hashes:g,blob:S}}catch(e){throw C9(e,y)}finally{o?.removeEventListener(`abort`,b),b()}}var E9=e=>Number.isFinite(e)?e:null;function D9({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:E9(l?.focalMm)??E9(c?.focalMm),fovDeg:E9(l?.fovDeg)??E9(c?.fovDeg),aspect:typeof i==`string`&&i?i:null,size:{width:E9(a?.width),height:E9(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:E9(e?.startFrame),end:E9(e?.endFrame)},fps:E9(r),shotIndex:Number.isInteger(s)&&s>=0?s:null,shotTitle:typeof e?.name==`string`&&e.name?e.name:null,targetModel:e?.targetModel??null,frame:E9(o)}}var xme=(()=>{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 Sme(e){let t=4294967295;for(let n=0;n<e.length;n++)t=xme[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}var O9=new TextEncoder,k9=0,A9=23585,j9=2048,M9=0,N9=20;function P9(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function F9(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 I9(e){if(!Array.isArray(e))throw TypeError(`buildZip expects an array of { name, data } entries`);let t=e.map(e=>{let t=O9.encode(e.name),n=typeof e.data==`string`?O9.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:Sme(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),F9(i,a,67324752),P9(i,a+4,N9),P9(i,a+6,j9),P9(i,a+8,M9),P9(i,a+10,k9),P9(i,a+12,A9),F9(i,a+14,r),F9(i,a+18,n.length),F9(i,a+22,n.length),P9(i,a+26,e.length),P9(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];F9(i,a,33639248),P9(i,a+4,N9),P9(i,a+6,N9),P9(i,a+8,j9),P9(i,a+10,M9),P9(i,a+12,k9),P9(i,a+14,A9),F9(i,a+16,s),F9(i,a+20,r.length),F9(i,a+24,r.length),P9(i,a+28,n.length),P9(i,a+30,0),P9(i,a+32,0),P9(i,a+34,0),P9(i,a+36,0),F9(i,a+38,0),F9(i,a+42,o[e]),i.set(n,a+46),a+=46+n.length}let c=a-s;return F9(i,a,101010256),P9(i,a+4,0),P9(i,a+6,0),P9(i,a+8,t.length),P9(i,a+10,t.length),F9(i,a+12,c),F9(i,a+16,s),P9(i,a+20,0),i}function L9(e){return String(e??``).toLowerCase().normalize(`NFKD`).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`shot`}function Cme(e){return`cozyclay-shot-${e.index}-${L9(e.title)}.zip`}function wme({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 jle(){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 $f(e,128,128,Ws);return r.minFilter=Bc,r.magFilter=ql,r.generateMipmaps=!0,r.needsUpdate=!0,r}function _8(e,t,n={}){return new Ed({uniforms:{...Mc.merge([Pm.lights,Pm.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 v8(e,t,n){let r=new df(1,1),i={};for(let[e,a]of Object.entries(n))i[e]=new td(new Float32Array(t*a),a).setUsage(jl),r.setAttribute(e,i[e]);let a=new hd(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 y8=(e,t)=>{for(let n of Object.values(e))n.clearUpdateRanges(),n.addUpdateRange(0,t*n.itemSize),n.needsUpdate=!0};function Mle(){let e=jle(),t=v8(_8(Dle,Ole,{map:{value:e}}),zQ,{iPos:3,iParams:4,iColor:4,iStreak:4}),n=v8(_8(kle,Ale),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;a$(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,y8(r,s),y8(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 b8=Symbol(`effects`),Nle=`#7fd4f0`,x8=e=>{e&&e.layers.set(5)};function Ple({object:e}){let t=e.effect?.preset===`trail`,n=t?Math.max(.05,(e.effect?.width??.5)/2):.06,r=(0,Q.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 pl;return a.setAttribute(`position`,new Yl([...r,...i].flat(),3)),a},[t,n]);return(0,Q.useEffect)(()=>()=>r.dispose(),[r]),(0,$.jsxs)(`group`,{userData:{effectMarker:!0},children:[(0,$.jsx)(`lineSegments`,{ref:x8,geometry:r,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{color:Nle,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),(0,$.jsxs)(`mesh`,{ref:x8,visible:!1,userData:{emptyPick:!0},children:[(0,$.jsx)(`sphereGeometry`,{args:[.08,12,8]}),(0,$.jsx)(`meshBasicMaterial`,{})]})]})}var Fle=e=>(t,n)=>{let r=e?.current?.get(t);return r?(r.place(),r.world(n)):null};function Ile({objects:e,frameRef:t=null,take:n=null,registryRef:r=null,fadeOpacity:i=null}){let a=(0,Q.useMemo)(()=>c$(e),[e]),o=a.records.length>0,s=(0,Q.useMemo)(()=>o?Mle():null,[o]);(0,Q.useEffect)(()=>()=>s?.dispose(),[s]);let c=(0,Q.useMemo)(()=>Fle(r),[r]),l=(0,Q.useMemo)(()=>({...a,take:n??{},live:c}),[a,n,c]),u=(0,Q.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 iy(d),(0,Q.useEffect)(()=>(s$(()=>l),()=>s$(null)),[l]),(0,Q.useEffect)(()=>{let e=r?.current;if(!(!e||!s))return e.set(b8,{place:d,world:()=>null}),()=>{e.delete(b8)}}),s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`primitive`,{object:s.particles}),(0,$.jsx)(`primitive`,{object:s.ribbons})]}):null}var Lle=.2,S8=`cozyclay.poseObjectOpacity`;function Rle(e=globalThis.localStorage){let t=Number(e?.getItem?.(S8));return e?.getItem?.(`cozyclay.poseObjectOpacity`)==null||!Number.isFinite(t)?Lle:Math.min(1,Math.max(0,t))}function zle(e,t=globalThis.localStorage){try{t?.setItem?.(S8,String(e))}catch{return}}var C8=new WeakMap,w8=()=>{};function Ble(e){return Array.isArray(e.material)?e.material:e.material?[e.material]:[]}var T8=!1;function E8(e){T8=e}function Vle(e,t){E8(!0),e?.();try{return t()}finally{E8(!1),e?.()}}function Hle(e,t,n=1){let r=T8||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 Ble(e))if(a){C8.has(t)||C8.set(t,{transparent:t.transparent,opacity:t.opacity,depthWrite:t.depthWrite});let e=C8.get(t).opacity*i;(t.opacity!==e||!t.transparent||t.depthWrite)&&(t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.needsUpdate=!0)}else C8.has(t)&&(Object.assign(t,C8.get(t)),C8.delete(t),t.needsUpdate=!0);o&&e.raycast!==w8?(e.userData.poseFadeRaycast=e.raycast,e.raycast=w8):!o&&e.raycast===w8&&(e.raycast=e.userData.poseFadeRaycast,delete e.userData.poseFadeRaycast)}})}var Ule=.2,Wle=.02,Gle=()=>{},D8=new WeakMap;function Kle(e){return D8.has(e)}var O8=null;function qle(){if(O8)return O8;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 O8=new $f(e,64,64),O8.magFilter=ql,O8.minFilter=ql,O8.needsUpdate=!0,O8}function Jle(){let e=new Qp({map:qle(),blending:2,transparent:!0,depthWrite:!1,fog:!1}),t=new Mp(e);return t.userData.glowHalo=!0,t.userData.beautyOnly=!0,t.raycast=Gle,t.castShadow=!1,t.receiveShadow=!1,t.renderOrder=2,t}function Yle(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 Xle(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(),D8.delete(e)}function Zle(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:Wle}}function Qle(e,t,n){let r=t.glow,i=D8.get(e);if(!r){i&&Xle(e,i);return}i||(i={halo:Jle(),bases:new Map,shadowless:new Set},D8.set(e,i)),i.halo.parent!==e&&e.add(i.halo);let a=r.intensity*n;Yle(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}=Zle(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(Ule*a)}var $le=Math.PI/180,k8=new Z(0,-1,0),A8=new Z,j8=new Z,M8=new Tu,eue=new Z;function N8(e,t){for(let n of e.children)if(n.userData?.[t])return n;return null}function tue(e,t,n){let r=N8(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*go*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*$le,r.penumbra=c,e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(j8,M8,eue),l?A8.set(l.x-j8.x,l.y-j8.y,l.z-j8.z):A8.copy(k8).applyQuaternion(M8),A8.lengthSq()<1e-10&&A8.copy(k8).applyQuaternion(M8),A8.normalize(),r.target.position.copy(j8).add(A8),r.target.updateMatrixWorld();let u=N8(e,`lightMarker`)?.children.find(e=>e.userData?.lightCone);u&&u.quaternion.setFromUnitVectors(k8,A8.applyQuaternion(M8.invert()))}function nue(e,t,n,r){if(!t.light&&!t.glow&&!Kle(e))return;let i=lX(t.id,n,r)*(t.light?Ra(t.id,n,t.light.flicker,r?.fps):1);t.light&&tue(e,t,i),Qle(e,t,i)}var rue=Math.PI/180,P8=.07,iue=.7;function aue(e,t){let n=e===`spot`?new Bd:new Cl;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 F8(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 I8(e){let t=new pl;return t.setAttribute(`position`,new Yl(e,3)),t}function oue(){let e=[];F8(e,P8,0,2),F8(e,P8,0,1),F8(e,P8,1,2);for(let t=0;t<8;t+=1){let n=t/8*Math.PI*2;e.push(Math.cos(n)*P8*1.3,0,Math.sin(n)*P8*1.3,Math.cos(n)*P8*2,0,Math.sin(n)*P8*2)}return I8(e)}function sue(e){let t=iue*Math.tan(e*rue),n=F8([],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 I8(n)}var L8=e=>{e&&e.layers.set(5)};function cue({type:e,angle:t,color:n}){let r=(0,Q.useMemo)(()=>oue(),[]),i=(0,Q.useMemo)(()=>e===`spot`?sue(t):null,[e,t]);return(0,Q.useEffect)(()=>()=>r.dispose(),[r]),(0,Q.useEffect)(()=>()=>i?.dispose(),[i]),(0,$.jsxs)(`group`,{userData:{lightMarker:!0},children:[(0,$.jsx)(`lineSegments`,{ref:L8,geometry:r,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{color:n,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),i&&(0,$.jsx)(`group`,{userData:{lightCone:!0},children:(0,$.jsx)(`lineSegments`,{ref:L8,geometry:i,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{color:n,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.55})})}),(0,$.jsxs)(`mesh`,{ref:L8,visible:!1,userData:{emptyPick:!0},children:[(0,$.jsx)(`sphereGeometry`,{args:[ri*.45,12,8]}),(0,$.jsx)(`meshBasicMaterial`,{})]})]})}function lue({object:e}){let{type:t,shadow:n,angle:r,color:i}=e.light,a=(0,Q.useMemo)(()=>aue(t,n),[t,n]);return(0,Q.useEffect)(()=>()=>a.dispose(),[a]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`primitive`,{object:a}),(0,$.jsx)(cue,{type:t,angle:r,color:i})]})}function uue(e){let t=ry(e=>e.invalidate);(0,Q.useEffect)(()=>{t()},[t,e.light,e.glow])}function due({kind:e,object:t,color:n,autoColor:r,depthRank:i=0}){let a=e===`plane`?2:0,o=hle(t,e,a,i),s=!(o?.transmission>0),c=o?(0,$.jsx)(`primitive`,{object:o,attach:`material`}):r?(0,$.jsx)(`meshStandardMaterial`,{...q1(r),side:a,...p8(i)}):(0,$.jsx)(`meshStandardMaterial`,{color:n,roughness:.82,side:a,...p8(i)});return e===`sphere`?(0,$.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`sphereGeometry`,{args:[.5,28,18]}),c]}):e===`capsule`?(0,$.jsxs)(`mesh`,{position:[0,.7,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`capsuleGeometry`,{args:[.35,.7,6,18]}),c]}):e===`cylinder`?(0,$.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`cylinderGeometry`,{args:[.5,.5,1,26]}),c]}):e===`cone`?(0,$.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`coneGeometry`,{args:[.5,1,26]}),c]}):e===`plane`?(0,$.jsxs)(`mesh`,{position:[0,.004,0],rotation:[-Math.PI/2,0,0],receiveShadow:!0,children:[(0,$.jsx)(`planeGeometry`,{args:[2,2]}),c]}):(0,$.jsxs)(`mesh`,{position:[0,.5,0],castShadow:s,receiveShadow:!0,children:[(0,$.jsx)(`boxGeometry`,{args:[1,1,1]}),c]})}function fue(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(n(null),e)return io(e,n)},[e]),t}var pue=`#c2c6c8`;function mue({object:e}){let t=fue(e.assetId),n=e.footprint?.width??1,r=e.height??1;return(0,$.jsxs)(`mesh`,{position:[0,r/2,0],castShadow:!0,receiveShadow:!0,userData:{cutoutTexture:t??null},children:[(0,$.jsx)(`planeGeometry`,{args:[n,r]}),(0,$.jsx)(`meshStandardMaterial`,{map:t??null,color:t?e.color:pue,side:2,alphaTest:t?.15:0,alphaToCoverage:!!t,roughness:.92,metalness:0})]})}function hue({object:e,depthRank:t=0}){let{recipe:n,autoColor:r}=e,i=(0,Q.useMemo)(()=>{let e=fle(n,r?{materialFor:()=>new jf(q1(r))}:{});return e.traverse(e=>e.material&&Object.assign(e.material,p8(t))),e},[n,r,t]);return(0,Q.useEffect)(()=>()=>ple(i),[i]),(0,$.jsx)(`primitive`,{object:i})}var gue=new Set([`cube`,`sphere`,`capsule`,`cylinder`,`cone`,`plane`]),_ue=[{to:[1,0,0],color:`#e5594f`},{to:[0,1,0],color:`#5fb95f`},{to:[0,0,1],color:`#4f86e5`}];function vue(){let e=ri/2,t=(0,Q.useMemo)(()=>{let t=[],n=[],r=new X;for(let i of _ue)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 pl;return i.setAttribute(`position`,new Yl(t,3)),i.setAttribute(`color`,new Yl(n,3)),i},[e]);(0,Q.useEffect)(()=>()=>t.dispose(),[t]);let n=e=>e?.layers.set(5);return(0,$.jsxs)(`group`,{userData:{emptyMarker:!0},children:[(0,$.jsx)(`lineSegments`,{ref:n,geometry:t,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{vertexColors:!0,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})}),(0,$.jsxs)(`mesh`,{ref:n,visible:!1,userData:{emptyPick:!0},children:[(0,$.jsx)(`sphereGeometry`,{args:[e*1.25,12,8]}),(0,$.jsx)(`meshBasicMaterial`,{})]})]})}function yue({object:e,depthRank:t=0}){let{renderer:n,color:r,autoColor:i}=e;return n===`empty`?(0,$.jsx)(vue,{}):n===`light`?(0,$.jsx)(lue,{object:e}):n===`effect`?(0,$.jsx)(Ple,{object:e}):n===`cutout`?(0,$.jsx)(mue,{object:e}):n===`mesh`?(0,$.jsx)(Ele,{object:e}):n===`sculpt`?(0,$.jsx)(hue,{object:e,depthRank:t}):n===`text`?(0,$.jsx)(o0,{object:e}):gue.has(n)?(0,$.jsx)(due,{kind:n,object:e,color:r,autoColor:i,depthRank:t}):null}function bue({object:e}){let t=e.renderer===`empty`||e.renderer===`light`||e.renderer===`effect`,n=t?ri:Math.max(e.height??1,.08),r=t?ri:e.footprint?.width??1,i=t?ri:e.footprint?.depth??1,a=(0,Q.useMemo)(()=>new Zs(new pf(r*1.04,n*1.04,i*1.04)),[r,n,i]);return(0,Q.useEffect)(()=>()=>a.dispose(),[a]),(0,$.jsx)(`lineSegments`,{ref:e=>{e&&e.layers.set(5)},geometry:a,position:[0,t?0:n/2,0],renderOrder:998,children:(0,$.jsx)(`lineBasicMaterial`,{color:`#e7b557`,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1})})}var R8=Math.PI/180,z8=new Z,B8=new Tu,V8=new Z,H8=new vl,U8=new af,W8=new af,xue=new af;function Sue({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,Q.useRef)(null),u=e.attach??null,d=()=>{let t=l.current;if(!t)return;let a=n?.current??0,c=n&&!u&&o?.current?gX(o.current,e.id,a,r??{},W8):null;if((t.visible=cX(e.id,a,r,o?.current))&&c)c.decompose(t.position,t.quaternion,t.scale);else if(u||e.path){if(z8.set(e.x,e.y??0,e.z),H8.set((e.rotX??0)*R8,e.rot*R8,(e.rotZ??0)*R8,`XYZ`),V8.set(e.scaleX??1,e.scaleY??1,e.scaleZ??1),n&&e.path){let t=ga(e,a,r??{});if(t){z8.set(t.x,t.y,t.z);let n=iX(e,t);H8.set(n.rotX*R8,n.rot*R8,n.rotZ*R8,`YXZ`)}}let o=u?i?.current?.(u.characterId,u.bone??null,xue)??null:null;o?(U8.compose(z8,B8.setFromEuler(H8),V8),W8.multiplyMatrices(o,U8).decompose(z8,B8,V8),t.position.copy(z8),t.quaternion.copy(B8),t.scale.copy(V8)):(t.position.copy(z8),t.rotation.copy(H8),t.scale.copy(V8))}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}),Hle(t,s,e.opacity??1),nue(t,e,a,r)};iy(d),uue(e);let f=(0,Q.useRef)(d);f.current=d;let p=(0,Q.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,Q.useEffect)(()=>{if(!a)return;let t=a.current;return t.set(e.id,p.current),()=>{t.delete(e.id)}},[a,e.id]),(0,$.jsxs)(`group`,{ref:l,position:[e.x,e.y??0,e.z],rotation:[(e.rotX??0)*R8,e.rot*R8,(e.rotZ??0)*R8],scale:[e.scaleX??1,e.scaleY??1,e.scaleZ??1],userData:{sceneObjectId:e.id},children:[(0,$.jsx)(yue,{object:e,depthRank:c}),t&&(0,$.jsx)(bue,{object:e})]})}function Cue({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,Q.useRef)(null),u=(0,Q.useRef)(null);u.current=(0,Q.useMemo)(()=>t?new Map(t.map(e=>[e.id,e])):null,[t]);let d=(0,Q.useMemo)(()=>Qk(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,$.jsxs)(`group`,{children:[Da(e).map(e=>(0,$.jsx)(Sue,{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,$.jsx)(Ile,{objects:t??e,frameRef:r,take:i,registryRef:l,fadeOpacity:c})]})}var wue=new af;function Tue({objectId:e=null,objectsRef:t,frameRef:n=null,take:r=null,registryRef:i=null,children:a}){let o=(0,Q.useRef)(null),s=()=>{let i=o.current;if(!i)return;let a=e&&t?.current?vX(t.current,e,n?.current??0,r??{},wue):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))};iy(s,-1);let c=(0,Q.useRef)(s);return c.current=s,(0,Q.useEffect)(()=>{if(!i)return;let e=i.current,t=()=>c.current();return e.add(t),()=>{e.delete(t)}},[i]),(0,$.jsx)(`group`,{ref:o,children:a})}var Eue=[139,92,246],G8=.62,Due=`#141819`,Oue=512,K8=1,q8=(e,t,n)=>Math.min(n,Math.max(t,e));function kue(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)*q8(a.view.zoom,K8,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?q8(s.x,i,a.preview.width-i):a.preview.width/2,s.y=r>=e.height?q8(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]=Eue;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*G8,u=u*.38+h*G8,f=f*.38+g*G8),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=Due,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+=jN(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=AN(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=q8(a.view.zoom*n,K8,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,Oue/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=q8(Number(e)||0,.01,.9);let t=AN(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=q8(Number(e)||0,.01,.9)},setBrush(e){a.brush=q8(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 Aue={name:`cozyclay`,version:`3.1.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.`,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 J8({id:e}){let t=`/thumbs/${e}-${_m()}.webp`,[n,r]=(0,Q.useState)(null);return n===t?null:(0,$.jsx)(`img`,{className:`v2-start-art`,src:t,alt:``,"aria-hidden":`true`,draggable:`false`,decoding:`async`,onError:()=>r(t)})}function jue(){return(0,$.jsx)(`img`,{className:`v2-start-brand-mark`,src:`/icons/icon-192.png`,alt:``,"aria-hidden":`true`,draggable:`false`,width:`26`,height:`26`})}var Mue=Aue.version,Y8=Object.freeze({id:`new-project`,thumbId:`blank-stage`,kind:`blank`,defaultName:`Untitled Project`,get name(){return Y(`New project`,`새 프로젝트`)},get description(){return Y(`Start from an empty stage.`,`빈 무대에서 시작합니다.`)}}),Nue=[{id:`storyboard`,label:()=>Y(`Storyboard`,`스토리보드`),blurb:()=>Y(`Describe scenes in words and direct one panel at a time. Output: image references.`,`말로 장면을 설명하면 한 장씩 패널을 연출합니다. 결과물: 이미지 레퍼런스.`)},{id:`animation`,label:()=>Y(`Animation`,`애니메이션`),blurb:()=>Y(`Block and shoot continuous motion. Output: clip references.`,`연속 동작을 블로킹하고 촬영합니다. 결과물: 클립 레퍼런스.`)}],X8=null;function Z8(e){X8=e}function Pue(e){let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`,year:`numeric`}):Y(`Recently`,`최근`)}function Fue(e){return{id:`sample-${e.id}`,starterId:e.id,name:e.name,description:e.blurb,kind:`sample`}}function Iue({open:e,initialName:t=`My Project`,onCancel:n,onSubmit:r}){let[i,a]=(0,Q.useState)(t);return(0,Q.useEffect)(()=>{if(e){if(X8!==null){let e=X8;X8=null,a(e),r(e);return}a(t)}},[e,t]),e?(0,$.jsx)(`div`,{className:`v2-project-name-dialog-backdrop project-name-dialog-backdrop`,role:`presentation`,children:(0,$.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,$.jsx)(`strong`,{id:`project-name-dialog-title`,children:Y(`Project name`,`프로젝트 이름`)}),(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`span`,{children:Y(`Name`,`이름`)}),(0,$.jsx)(`input`,{autoFocus:!0,value:i,onChange:e=>a(e.target.value),"aria-label":Y(`Project name`,`프로젝트 이름`)})]}),(0,$.jsxs)(`div`,{className:`v2-project-name-dialog-actions project-name-dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`v2-dialog-secondary btn ghost`,onClick:n,children:Y(`Cancel`,`취소`)}),(0,$.jsx)(`button`,{type:`submit`,className:`v2-dialog-primary btn primary`,children:Y(`Create`,`생성`)})]})]})}):null}function Lue({currentName:e,onOpen:t,onOpenFile:n,onNew:r,onClose:i,startup:a=!1,starters:o=[],onStarter:s}){let c=(0,Q.useMemo)(()=>o.map(Fue),[o]),[l,u]=(0,Q.useState)(Sr),d=l===`storyboard`?[]:c,f=c[0]??Y8,[p,m]=(0,Q.useState)(a?`new`:`recent`),[h,g]=(0,Q.useState)(f.id),[_,v]=(0,Q.useState)(e||f.defaultName||f.name||`My Project`),[y,b]=(0,Q.useState)(`24`),[x,S]=(0,Q.useState)(`Meters`),[C,w]=(0,Q.useState)([]),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)([]),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(null),N=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=!0;return Xi().then(t=>{e&&w(Array.isArray(t)?t:[])}),Br().then(async t=>{if(!e||!t)return;let n=await no(t);if(e){if(n!==`granted`){A(!0),n===`prompt`&&M(t);return}E(t),O(await Wr(t))}}).catch(()=>{e&&A(!0)}),()=>{e=!1}},[]),(0,Q.useEffect)(()=>{a&&N.current?.focus()},[a]),(0,Q.useEffect)(()=>()=>{queueMicrotask(()=>Z8(null))},[]);let P=d.find(e=>e.id===h)??Y8,F=_.trim().length>0,I=Y(`Enter a project name to create a project`,`프로젝트를 만들려면 이름을 입력하세요`),L=T?.name||Y(`Browser project store`,`브라우저 프로젝트 저장소`),R=Dr()&&Bi(),z=async()=>{if(!j||await _o(j)!==`granted`)return;let e=j;M(null),A(!1),E(e),O(await Wr(e))},ee=async()=>{if(R)try{let e=await Xo();await Oa(e),E(e),A(!1),M(null),O(await Wr(e))}catch(e){e?.name!==`AbortError`&&A(!0)}},B=async()=>{T&&O(await Wr(T))},V=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(Y8.id),v(e=>e.trim()===P?.name?Y8.defaultName:e))},U=e=>{e.preventDefault();let t=_.trim();if(t){if(P?.starterId){s?.(P.starterId,t,{previsMode:`animation`});return}Z8(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:Y(`Recent`,`최근`)},{id:`new`,label:Y(`New Project`,`새 프로젝트`)},{id:`learn`,label:Y(`Learn`,`배우기`)}];return(0,$.jsx)(`div`,{className:`v2-start-screen project-browser-backdrop${a?` startup`:``}`,onPointerDown:e=>{!a&&e.target===e.currentTarget&&i?.()},children:(0,$.jsxs)(`div`,{className:`v2-start-window project-browser${a?` startup`:``}`,role:`dialog`,"aria-modal":`true`,"aria-label":Y(`Choose project`,`프로젝트 선택`),children:[(0,$.jsxs)(`nav`,{className:`v2-start-nav`,"aria-label":Y(`Project navigation`,`프로젝트 탐색`),children:[(0,$.jsxs)(`div`,{className:`v2-start-brand`,children:[(0,$.jsx)(jue,{}),(0,$.jsx)(`strong`,{children:`CozyClay`})]}),(0,$.jsx)(`div`,{className:`v2-start-nav-list`,children:G.map(e=>(0,$.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,$.jsxs)(`div`,{className:`v2-start-version`,children:[`v`,Mue]})]}),(0,$.jsxs)(`main`,{className:`v2-start-main`,children:[(0,$.jsxs)(`div`,{className:`v2-start-main-head`,children:[(0,$.jsxs)(`div`,{className:`v2-start-title-row`,children:[(0,$.jsx)(`h1`,{children:p===`recent`?Y(`Recent`,`최근`):p===`learn`?Y(`Learn`,`배우기`):Y(`New Project`,`새 프로젝트`)}),p!==`new`&&(0,$.jsx)(`button`,{type:`button`,className:`v2-start-close x`,onClick:i,"aria-label":Y(`Close`,`닫기`),children:`×`})]}),p===`new`&&(0,$.jsx)(`div`,{className:`v2-start-mode`,role:`radiogroup`,"aria-label":Y(`Project mode`,`프로젝트 모드`),"data-testid":`start-previs-mode`,children:Nue.map(e=>(0,$.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,$.jsx)(`strong`,{children:e.label()}),(0,$.jsx)(`span`,{children:e.blurb()})]},e.id))})]}),p===`learn`?(0,$.jsxs)(`div`,{className:`v2-start-learn`,children:[(0,$.jsx)(`strong`,{children:Y(`Block a shot in three moves`,`세 단계로 샷을 블로킹하세요`)}),(0,$.jsx)(`p`,{children:Y(`Choose a template, name the project, then place a character and frame the camera in the editor.`,`템플릿을 고르고 프로젝트 이름을 정한 다음 편집기에서 인물을 배치하고 카메라를 잡아 보세요.`)}),(0,$.jsx)(`button`,{type:`button`,className:`v2-start-learn-action`,onClick:()=>m(`new`),children:Y(`Start a new project`,`새 프로젝트 시작`)})]}):p===`recent`?(0,$.jsxs)(`div`,{className:`v2-start-recent-page`,children:[(0,$.jsxs)(`div`,{className:`v2-start-recent-heading`,children:[(0,$.jsx)(`span`,{children:Y(`Recent projects`,`최근 프로젝트`)}),(0,$.jsxs)(`div`,{className:`v2-start-recent-actions`,children:[T&&(0,$.jsx)(`button`,{type:`button`,onClick:B,children:Y(`Refresh`,`새로고침`)}),(0,$.jsx)(`button`,{type:`button`,onClick:n,children:Y(`Open project file…`,`프로젝트 파일 열기…`)})]})]}),(0,$.jsx)(Q8,{entries:W,currentName:e,onOpen:t,onOpenFile:n,onRemove:async e=>{await Ca(e.name),w(await Xi())}})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`v2-start-template-grid`,role:`list`,"aria-label":Y(`Project templates`,`프로젝트 템플릿`),children:[d.map(e=>(0,$.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-template${P?.id===e.id?` selected`:``}`,"data-template-id":e.id,onClick:()=>V(e),onDoubleClick:()=>e.starterId&&s?.(e.starterId),children:[(0,$.jsx)(`span`,{className:`v2-start-template-art ${e.kind}`,children:(0,$.jsx)(J8,{id:e.starterId??e.id})}),(0,$.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`span`,{children:e.description})]})]},e.id)),(0,$.jsxs)(`button`,{type:`button`,role:`listitem`,className:`v2-start-add-card${P?.id===Y8.id?` selected`:``}`,"data-testid":`start-new-project-card`,onClick:()=>{V(Y8),requestAnimationFrame(()=>N.current?.select())},children:[(0,$.jsx)(`span`,{className:`v2-start-add-art`,"aria-hidden":`true`,children:(0,$.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`20`,height:`20`,children:(0,$.jsx)(`path`,{d:`M10 3.5v13M3.5 10h13`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})})}),(0,$.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,$.jsx)(`strong`,{children:Y(`New project`,`새 프로젝트`)}),(0,$.jsx)(`span`,{children:Y(`Start from an empty stage`,`빈 무대에서 시작`)})]})]}),(0,$.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,$.jsx)(`span`,{className:`v2-start-add-art`,"aria-hidden":`true`,children:(0,$.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`20`,height:`20`,children:(0,$.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,$.jsxs)(`span`,{className:`v2-start-template-copy`,children:[(0,$.jsx)(`strong`,{children:Y(`Open project`,`프로젝트 열기`)}),(0,$.jsx)(`span`,{children:Y(`A saved .cclayproject file`,`저장한 .cclayproject 파일`)})]})]})]}),(0,$.jsxs)(`div`,{className:`v2-start-recent-block`,children:[(0,$.jsx)(`div`,{className:`v2-start-recent-heading`,children:(0,$.jsx)(`span`,{children:Y(`Recent`,`최근`)})}),(0,$.jsx)(Q8,{entries:C.map(e=>({...e,key:`recent-${e.name}`,removable:!0,date:e.openedAt})),currentName:e,onOpen:t,onOpenFile:n,onRemove:async e=>{await Ca(e.name),w(await Xi())},compact:!0})]})]})]}),(0,$.jsxs)(`aside`,{className:`v2-start-preview`,"data-testid":`start-project-preview`,"aria-label":Y(`Project preview`,`프로젝트 미리보기`),children:[(0,$.jsx)(`div`,{className:`v2-start-preview-art ${P?.kind||`blank`}`,children:(0,$.jsx)(J8,{id:P.starterId??P.thumbId})}),(0,$.jsxs)(`div`,{className:`v2-start-preview-copy`,children:[(0,$.jsx)(`strong`,{children:P?.name}),(0,$.jsx)(`span`,{children:P?.description})]}),(0,$.jsxs)(`form`,{className:`v2-start-project-form`,onSubmit:U,children:[(0,$.jsxs)(`label`,{className:`v2-start-field`,children:[(0,$.jsx)(`span`,{children:Y(`Name`,`이름`)}),(0,$.jsx)(`input`,{ref:N,"data-testid":`start-project-name`,"aria-label":Y(`Name`,`이름`),value:_,onChange:e=>v(e.target.value)})]}),(0,$.jsxs)(`label`,{className:`v2-start-field`,children:[(0,$.jsx)(`span`,{children:Y(`Location`,`위치`)}),(0,$.jsxs)(`button`,{type:`button`,className:`v2-start-location`,onClick:ee,disabled:!R,title:R?Y(`Choose the project storage folder`,`프로젝트 저장 폴더 선택`):Y(`Projects are stored in this browser`,`프로젝트는 이 브라우저에 저장됩니다`),children:[(0,$.jsx)(`span`,{children:L}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`⌄`})]})]}),(0,$.jsxs)(`label`,{className:`v2-start-field`,children:[(0,$.jsx)(`span`,{children:Y(`Frame rate`,`프레임 레이트`)}),(0,$.jsx)(`span`,{className:`v2-start-select-wrap`,children:(0,$.jsxs)(`select`,{"aria-label":Y(`Frame rate`,`프레임 레이트`),value:y,onChange:e=>b(e.target.value),children:[(0,$.jsx)(`option`,{value:`24`,children:`24 fps`}),(0,$.jsx)(`option`,{value:`30`,children:`30 fps`})]})})]}),(0,$.jsxs)(`label`,{className:`v2-start-field`,children:[(0,$.jsx)(`span`,{children:Y(`Units`,`단위`)}),(0,$.jsx)(`span`,{className:`v2-start-select-wrap`,children:(0,$.jsxs)(`select`,{"aria-label":Y(`Units`,`단위`),value:x,onChange:e=>S(e.target.value),children:[(0,$.jsx)(`option`,{value:`Meters`,children:`Meters`}),(0,$.jsx)(`option`,{value:`Feet`,children:`Feet`})]})})]}),k&&(0,$.jsxs)(`p`,{className:`v2-start-location-status`,role:`status`,children:[j?Y(`Folder access needs to be re-allowed.`,`폴더 접근을 다시 허용해야 해요.`):Y(`Using the browser project store.`,`브라우저 프로젝트 저장소를 사용합니다.`),j&&(0,$.jsx)(`button`,{type:`button`,onClick:z,children:Y(`Re-allow`,`다시 허용`)})]}),(0,$.jsxs)(`div`,{className:`v2-start-preview-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`v2-start-cancel`,onClick:i,children:Y(`Cancel`,`취소`)}),(0,$.jsx)(`button`,{type:`submit`,className:`v2-start-create btn primary`,"data-testid":`start-create`,disabled:!F,title:F?Y(`Create project`,`프로젝트 만들기`):I,children:Y(`Create`,`생성`)})]})]})]})]})})}function Q8({entries:e,currentName:t,onOpen:n,onOpenFile:r,onRemove:i,compact:a=!1}){return e.length===0?(0,$.jsxs)(`p`,{className:`v2-start-empty${a?` compact`:``}`,children:[Y(`No recent projects in this browser yet. `,`이 브라우저에 최근 프로젝트가 없습니다. `),(0,$.jsx)(`button`,{type:`button`,className:`v2-start-empty-open`,onClick:r,children:Y(`Open a project file…`,`프로젝트 파일 열기…`)})]}):(0,$.jsx)(`div`,{className:`v2-start-recent-list${a?` compact`:``}`,role:`list`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`v2-start-recent-row${e.name===t?` active`:``}`,role:`listitem`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`v2-start-recent-open`,onClick:()=>n(e),children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`span`,{children:Pue(e.date)}),(0,$.jsxs)(`small`,{children:[e.shots??`—`,Y(` shots`,` 샷`)]})]}),e.removable&&(0,$.jsx)(`button`,{type:`button`,className:`v2-start-recent-remove`,"aria-label":Y(`Remove ${e.name} from recent projects`,`최근 프로젝트에서 ${e.name} 제거`,`从最近项目中移除 ${e.name}`),title:Y(`Remove from list`,`목록에서 제거`),onClick:()=>i(e),children:`×`})]},e.key))})}var Rue={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 zue({open:e,onDismiss:t,previsMode:n=`animation`}){let r=n===`storyboard`,i=Rue[r?`storyboard`:`animation`],[a,o]=(0,Q.useState)(0);if((0,Q.useEffect)(()=>{e&&o(0)},[e]),!e)return null;let s=a>=i.length;return(0,$.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,$.jsxs)(`div`,{className:`v2-first-success-guide-head first-success-guide-head`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{id:`first-success-guide-title`,children:Y(`Your first 60 seconds`,`첫 60초`)}),(0,$.jsx)(`span`,{children:s?Y(`Core loop complete`,`핵심 흐름 완료`,`核心流程完成`):Y(`Step ${a+1} of ${i.length}`,`${a+1} / ${i.length} 단계`,`第 ${a+1} / ${i.length} 步`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-close first-success-guide-close`,onClick:t,"aria-label":Y(`Dismiss guide`,`가이드 닫기`),children:`×`})]}),s?(0,$.jsxs)(`div`,{className:`v2-first-success-guide-complete first-success-guide-complete`,id:`first-success-guide-description`,role:`status`,children:[(0,$.jsx)(`div`,{className:`v2-first-success-guide-check first-success-guide-check`,children:`✓`}),(0,$.jsx)(`strong`,{children:r?Y(`You made your first panel.`,`첫 패널을 만들었어요.`):Y(`You made your first shot.`,`첫 샷을 만들었어요.`)}),(0,$.jsx)(`p`,{children:r?Y(`Describe, review on the Board, then stylize or export. You can close this guide and keep adding panels.`,`설명하고, 보드에서 확인한 뒤 스타일을 입히거나 내보내세요. 가이드를 닫고 패널을 계속 추가하세요.`):Y(`Select, move, ask, and play are the core CozyClay loop. You can close this guide and keep blocking.`,`선택하고, 움직이고, 요청하고, 재생하는 것이 CozyClay의 핵심 흐름입니다. 가이드를 닫고 계속 블로킹하세요.`)}),(0,$.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-next first-success-guide-next btn primary`,onClick:t,children:Y(`Continue editing`,`편집 계속하기`)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{id:`first-success-guide-description`,className:`v2-first-success-guide-intro first-success-guide-intro`,children:Y(`Follow these four actions to see a result quickly.`,`네 가지 동작으로 빠르게 결과를 확인해 보세요.`)}),(0,$.jsx)(`ol`,{className:`v2-first-success-guide-steps first-success-guide-steps`,children:i.map((e,t)=>(0,$.jsxs)(`li`,{className:t<a?`done`:t===a?`current`:``,children:[(0,$.jsx)(`span`,{className:`v2-first-success-guide-step-mark first-success-guide-step-mark`,children:t<a?`✓`:t+1}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{children:Y(e.en,e.ko,e.zh)}),t===a&&(0,$.jsx)(`span`,{children:Y(e.hintEn,e.hintKo,e.hintZh)})]})]},e.en))}),(0,$.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-next first-success-guide-next btn primary`,onClick:()=>o(e=>e+1),children:Y(a===i.length-1?`Mark complete`:`I did this`,a===i.length-1?`완료로 표시`:`했어요`,a===i.length-1?`标记完成`:`我做了这一步`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`v2-first-success-guide-skip first-success-guide-skip`,onClick:t,children:Y(`Skip guide`,`가이드 건너뛰기`)})]})}var Bue=Object.freeze([[`animation`,`Animation`,`애니메이션`,`动画`],[`film`,`Film / drama`,`영화·드라마`,`影视剧`],[`game`,`Game`,`게임`,`游戏`],[`ad_mv`,`Ad / music video`,`광고·뮤비`,`广告 / MV`],[`personal`,`Personal project`,`개인 작업`,`个人项目`],[`other`,`Something else`,`기타`,`其他`]]),Vue=Object.freeze([[`team`,`With a team or company`,`팀·회사에서`,`与团队或公司`],[`solo`,`On my own`,`혼자`,`我自己`]]);function Hue({open:e,isKo:t,isZh:n,onAnswer:r}){let[i,a]=(0,Q.useState)(null),o=(e,r,i)=>t?r:n?i:e;if((0,Q.useEffect)(()=>{e||a(null)},[e]),!e)return null;let s=()=>r(i??`skip`,`skip`);return(0,$.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,$.jsxs)(`div`,{className:`use-case-ask-head`,children:[(0,$.jsx)(`strong`,{id:`use-case-ask-title`,children:o(`Quick question (optional)`,`짧은 질문 (선택)`,`快速提问(可选)`)}),(0,$.jsx)(`button`,{type:`button`,className:`use-case-ask-close`,"aria-label":o(`Close`,`닫기`,`关闭`),onClick:s,children:`×`})]}),(0,$.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,$.jsx)(`div`,{className:`use-case-ask-choices`,role:`group`,"aria-label":i?o(`Team or solo`,`팀 또는 혼자`,`团队或个人`):o(`Use case`,`용도`,`用途`),children:(i?Vue:Bue).map(([e,t,n,s])=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>i?r(i,e):a(e),children:o(t,n,s)},e))}),(0,$.jsx)(`p`,{className:`use-case-ask-note`,children:o(`Anonymous. Only the choice is sent.`,`익명이에요. 고른 항목만 전송돼요.`,`匿名。只发送所选项目。`)})]})}var $8=`gizmoHandleProxy`,Uue=[$8,`keyLightPick`,`pathAxis`,`pathIndex`,`pathRing`,`pathLine`,`craneAxis`,`craneIndex`];function Wue(e){for(let t=e;t;t=t.parent){let e=t.userData;if(e){for(let t of Uue)if(e[t]!==void 0)return!0}}return!1}function Gue(e){return e.some(e=>Wue(e.object))}var e5=(e,t)=>Math.max(0,Math.min(e.frameCount-1,Math.round(t)||0)),Kue=(e,t)=>typeof t.parent==`string`?e.get(t.parent):null;function que(e,t,n){let r=new Set;for(let i=e.get(n);i&&!r.has(i.id);i=Kue(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 Jue(e,t){return e?.hold?e.hold[e5(e,t)]===1?`held`:null:e?`hinge`:null}function Yue(e,t){return t.set(0,e.renderer===`empty`?0:(e.height??1)/2,0)}function Xue(e,t,n,r){let i=e.get(t),a=i?gX(e,t,n,r,new af):null;if(!a)return null;let o=new Tu;return a.decompose(new Z,o,new Z),{centre:Yue(i,new Z).applyMatrix4(a).toArray(),quat:o.toArray()}}function Zue(e,t){let n=e5(e,t);return{pos:new Z().fromArray(e.pos,n*3),quat:new Tu().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 Tu().setFromAxisAngle(r.clone().normalize(),i*Math.PI/180),n=new Z().fromArray(t);a.sub(n).applyQuaternion(e).add(n),o.premultiply(e).normalize()}return n&&a.add(n),{pos:a,quat:o}}function Que(e,t,n,r,i){let a=new Z().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 $ue(e,t,n=0){let r=new Z;for(let i of t)r.addScaledVector(i,n5(e.dot(i),n));return r}var ede=(e,t=0)=>n5(e,t);function tde(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 nde(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 rde(e,t,n,r,i=[]){let a=e.get(t),o=n?.track?.hold;if(!a||!o)return null;let s=new Z(0,a.renderer===`empty`?0:a.height??1,0),c=new af,l=n=>gX(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 ide({selected:e,objects:t,tracks:n,frame:r,frameCount:i,fps:a,motion:o,run:s}){let[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(null),d=(0,Q.useMemo)(()=>new Map(t.map(e=>[e.id,e])),[t]),f=tde(n,c),p=e?.id??null,m=p?que(d,f,p):null,h=m?Xue(d,p,r,{frameCount:i,fps:a,objectTracks:f}):null,g=m?n.get(m.id):null,_=g?.characterId??null,v=m?Jue(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,Q.useMemo)(()=>{if(!S||!T)return null;let e={frameCount:E,pos:C,quat:w,hold:T},t=x?x.split(`,`).map(Number):[];return rde(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,Q.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:Zue(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?Que(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`,nde(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 ade({trail:e}){let t=(0,Q.useMemo)(()=>e?new pl().setFromPoints(e.points.map(e=>new Z(...e))):null,[e]);(0,Q.useEffect)(()=>()=>t?.dispose(),[t]);let n=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{n.current?.traverse(e=>e.layers.set(5))}),e?(0,$.jsxs)(`group`,{ref:n,children:[(0,$.jsx)(`line`,{geometry:t,renderOrder:997,frustumCulled:!1,children:(0,$.jsx)(`lineBasicMaterial`,{color:i5,transparent:!0,opacity:.8,depthTest:!1,depthWrite:!1})}),e.keys.map((e,t)=>(0,$.jsxs)(`mesh`,{position:e,renderOrder:997,children:[(0,$.jsx)(`sphereGeometry`,{args:[.025,10,8]}),(0,$.jsx)(`meshBasicMaterial`,{color:i5,depthTest:!1,depthWrite:!1,transparent:!0})]},t))]}):null}var a5=[{axis:`x`,dir:new Z(1,0,0),color:`#ff5340`},{axis:`y`,dir:new Z(0,1,0),color:`#54e05c`},{axis:`z`,dir:new Z(0,0,1),color:`#3d8bff`}],o5={x:a5[0].dir,y:a5[1].dir,z:a5[2].dir},ode=[{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,sde=.05,l5=.14,u5=.52,cde=.28,lde=`#ffd23d`,d5=.022,f5=.09,p5=.09,ude=.07,dde=.16;function fde(e){return(e.y??0)+Math.max(oe(e).height/2,.25)}function m5(e){return e.corner?`corner:${e.corner.id}`:e.axis??(e.plane?`plane:${e.plane.id}`:`centre`)}var pde=[{id:`tr`,sx:1,sy:1},{id:`tl`,sx:-1,sy:1},{id:`br`,sx:1,sy:-1},{id:`bl`,sx:-1,sy:-1}],mde=new Xs(new Z(0,1,0),0);function h5(e,t,n){return t?.pose?n.fromArray(t.pose.centre):n.set(e.x,fde(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=nE,onChange:l,onSelect:u,onGroundClick:d,onDragStart:f,onDragEnd:p,claimPointer:m,held:h=null}){let{gl:g,scene:_}=ry(),v=e=>{let t={x:e.left,y:e.top,w:e.width,h:e.height};return c?$T(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,Q.useRef)(null),x=(0,Q.useRef)(new Map),S=(0,Q.useRef)(null),C=(0,Q.useRef)({}),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(null),O=(0,Q.useRef)(null),k=(0,Q.useRef)(null),A=(0,Q.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,Q.useMemo)(()=>({raycaster:new ll,ndc:new kd,hit:new Z,delta:new Z,eye:new Z,origin:new Z,camPos:new Z}),[]),M=(0,Q.useMemo)(()=>a5.map(({axis:e,dir:t})=>{let n=new Tu().setFromUnitVectors(new Z(0,1,0),t);return{axis:e,u:new Z(1,0,0).applyQuaternion(n),v:new Z(0,0,1).applyQuaternion(n)}}),[]),N=(0,Q.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,Q.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,Q.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+=Sa((e-n.lastAngle)*180/Math.PI),n.lastAngle=e,n.held)return void A.current.held?.rotate(n.dir,ede(n.turned,o?5:0));if(n.axis===`screen`){let e=os(n.start,n.dir,n.turned,o?void 0:0);e&&i?.(n.id,e,n.token);return}let t=fi(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=qn(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($ue(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,No(n.start,t,j.delta.dot(o5[t]),o?void 0:0));i?.(n.id,e,n.token);return}let s=No(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 Tu(...t)):i;p=new Xs().setFromNormalAndCoplanarPoint(n,j.origin.clone());let a=new Z;if(!j.raycaster.ray.intersectPlane(p,a))return!1;let o=new Z(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 Z().crossVectors(j.eye,new Z(0,1,0)).normalize(),t=e.clone().cross(j.eye).cross(e).normalize();p=new Xs().setFromNormalAndCoplanarPoint(t,j.origin.clone());let n=new Z;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 Z(Math.cos(e),0,-Math.sin(e)),n=new Z(0,1,0),r=new Z().crossVectors(t,n).normalize();p=new Xs().setFromNormalAndCoplanarPoint(r,j.origin.clone());let a=new Z;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 Xs().setFromNormalAndCoplanarPoint(e,j.origin.clone());let t=new Z;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 Xs().setFromNormalAndCoplanarPoint(e,j.origin.clone());let t=new Z;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),Gue(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(mde,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]),iy(()=>{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)*dde)),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 Tu(...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,Q.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 Z).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,Q.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}))},ee=e=>t=>{t&&(t.layers.set(5),t.userData[$8]=!0,x.current.set(`corner:${e.id}`,{mesh:t,axis:null,corner:e}))},B=(0,$.jsx)(`meshBasicMaterial`,{visible:!1}),V=w===`screen`,H=E===`screen`,U=w===`centre`,W=E===`centre`;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ade,{trail:h?.trail??null}),(0,$.jsxs)(`group`,{ref:b,position:h5(e,h,new Z).toArray(),quaternion:g5(h,n)??[0,0,0,1],renderOrder:999,children:[a5.map(({axis:e,dir:t,color:r})=>{let i=new Tu().setFromUnitVectors(new Z(0,1,0),t),a=w===e,o=E===e,s=a?lde:r,c=a?2.2:o?3.6:2.2,l=(e=.95)=>(0,$.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:s,emissiveIntensity:c,toneMapped:!1,depthTest:!1,depthWrite:!1,transparent:!0,opacity:e});return(0,$.jsx)(`group`,{quaternion:i,children:n===`rotate`?(0,$.jsxs)(`group`,{ref:R(e),rotation:[Math.PI/2,0,0],children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`torusGeometry`,{args:[u5,d5,8,24,Math.PI]}),l()]}),(0,$.jsxs)(`mesh`,{rotation:[0,0,Math.PI],renderOrder:999,children:[(0,$.jsx)(`torusGeometry`,{args:[u5,d5,8,24,Math.PI]}),l(cde)]}),(0,$.jsxs)(`mesh`,{ref:L(e,t),children:[(0,$.jsx)(`torusGeometry`,{args:[u5,ude,6,32]}),B]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`mesh`,{position:[0,s5/2,0],renderOrder:999,children:[(0,$.jsx)(`cylinderGeometry`,{args:[c5,c5,s5,8]}),l()]}),(0,$.jsxs)(`mesh`,{position:[0,s5+(n===`scale`?f5/2:l5/2),0],renderOrder:999,children:[n===`scale`?(0,$.jsx)(`boxGeometry`,{args:[f5,f5,f5]}):(0,$.jsx)(`coneGeometry`,{args:[sde,l5,14]}),l()]}),(0,$.jsxs)(`mesh`,{ref:L(e,t),position:[0,(s5+l5)/2,0],children:[(0,$.jsx)(`cylinderGeometry`,{args:[p5,p5,s5+l5,8]}),B]})]})},e)}),n===`rotate`&&(0,$.jsxs)(`group`,{ref:S,children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`torusGeometry`,{args:[.68,.022,8,64]}),(0,$.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:V?`#ffd23d`:`#f2f2f2`,emissiveIntensity:V?2.2:H?3.6:2.2,toneMapped:!1,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.95})]}),(0,$.jsxs)(`mesh`,{ref:L(`screen`,null),children:[(0,$.jsx)(`torusGeometry`,{args:[.68,.07,6,48]}),B]})]}),n===`move`&&ode.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,$.jsxs)(`group`,{position:t,rotation:r,children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`planeGeometry`,{args:[.2,.2]}),(0,$.jsx)(`meshBasicMaterial`,{color:i?`#ffd23d`:e.color,transparent:!0,opacity:i?.6:a?.55:.34,side:2,depthTest:!1,depthWrite:!1})]}),(0,$.jsxs)(`mesh`,{ref:z(e),children:[(0,$.jsx)(`planeGeometry`,{args:[.2*1.5,.2*1.5]}),(0,$.jsx)(`meshBasicMaterial`,{visible:!1,side:2})]})]},e.id)}),n===`scale`&&e?.renderer===`cutout`&&pde.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,$.jsxs)(`group`,{position:u,children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`boxGeometry`,{args:[.085,.085,.085]}),(0,$.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:o?`#ffd23d`:`#f2f2f2`,emissiveIntensity:o?2:s?3.4:2,toneMapped:!1,depthTest:!1,depthWrite:!1})]}),(0,$.jsxs)(`mesh`,{ref:ee(t),children:[(0,$.jsx)(`sphereGeometry`,{args:[.13,8,6]}),B]})]},a)}),n===`scale`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`mesh`,{renderOrder:999,children:[(0,$.jsx)(`boxGeometry`,{args:[.11,.11,.11]}),(0,$.jsx)(`meshStandardMaterial`,{color:`#000000`,emissive:U?`#ffd23d`:`#f2f2f2`,emissiveIntensity:U?2:W?3.4:2,toneMapped:!1,depthTest:!1,depthWrite:!1})]}),(0,$.jsxs)(`mesh`,{ref:L(null,null),children:[(0,$.jsx)(`sphereGeometry`,{args:[.16,8,6]}),B]})]})]})]})}function hde({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?Y(`your AI video tool`,`AI 영상 도구`):Y(`your selected image model`,`선택한 이미지 모델`)),u=!!e.frame,d;return d=c&&e.frameB?(0,$.jsxs)(`p`,{children:[Y(`Paste the prompt into ${l}, set `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},设置 `),(0,$.jsx)(`code`,{children:`blocking-frame-A-start.png`}),Y(` as the start frame, and `,`를 시작 프레임으로, `,` 作为起始帧,并将 `),(0,$.jsx)(`code`,{children:`blocking-frame-B-end.png`}),Y(` as the end frame.`,`를 끝 프레임으로 설정하세요.`)]}):c&&u?(0,$.jsxs)(`p`,{children:[Y(`Paste the prompt into ${l} and attach `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},并附加 `),(0,$.jsx)(`code`,{children:`blocking-frame.png`}),Y(` as the reference frame.`,`를 참고 프레임으로 첨부하세요.`,` 作为参考帧。`)]}):u?(0,$.jsxs)(`p`,{children:[Y(`Paste the prompt into ${l} and attach `,`${l}에 프롬프트를 붙여 넣고 `,`将提示词粘贴到 ${l},并附加 `),(0,$.jsx)(`code`,{children:`blocking-frame.png`}),Y(` as the reference image.`,`를 참고 이미지로 첨부하세요.`,` 作为参考图像。`)]}):(0,$.jsx)(`p`,{children:Y(`Paste the copied prompt into ${l} to create the scene.`,`복사한 프롬프트를 ${l}에 붙여 넣어 장면을 만드세요.`,`将复制的提示词粘贴到 ${l} 以创建场景。`)}),(0,$.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,$.jsxs)(`div`,{className:`modal result-modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`result-title`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(`h3`,{id:`result-title`,children:Y(`Your shot is ready`,`장면이 준비됐어요`)}),(0,$.jsx)(`button`,{type:`button`,className:`x`,onClick:r,"aria-label":Y(`Close the result`,`결과 닫기`),children:`✕`})]}),e.frameB?(0,$.jsxs)(`div`,{className:`move-frames`,children:[(0,$.jsxs)(`figure`,{children:[(0,$.jsx)(`img`,{className:`preview`,src:e.frame,alt:Y(`Camera move start frame`,`카메라 움직임 시작 프레임`)}),(0,$.jsxs)(`figcaption`,{children:[`A · `,Y(`Start`,`시작`)]})]}),(0,$.jsxs)(`figure`,{children:[(0,$.jsx)(`img`,{className:`preview`,src:e.frameB,alt:Y(`Camera move end frame`,`카메라 움직임 끝 프레임`)}),(0,$.jsxs)(`figcaption`,{children:[`B · `,Y(`End`,`끝`)]})]})]}):e.frame&&(0,$.jsx)(`img`,{className:`preview`,src:e.frame,alt:Y(`Finished scene frame`,`완성된 장면 프레임`)}),e.move&&(0,$.jsxs)(`div`,{className:`move-slate result-move-slate`,children:[(0,$.jsxs)(`span`,{children:[e.move.displaySlate??e.move.slate,` · `,e.move.spanS,Y(`s`,`초`,`秒`)]}),(0,$.jsx)(`small`,{children:Y(`Camera move made from timeline keyframes`,`타임라인 키프레임으로 만든 카메라 움직임`)})]}),(0,$.jsxs)(`label`,{className:`modal-label`,children:[Y(`Prompt`,`프롬프트`),` `,t&&(0,$.jsxs)(`em`,{children:[`· `,Y(`copied`,`복사됨`)]})]}),(0,$.jsx)(`div`,{className:`promptbox`,children:e.prompt}),(0,$.jsxs)(`div`,{className:`modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:i,children:t?Y(`Copied ✓`,`복사됨 ✓`):Y(`Copy prompt`,`프롬프트 복사`)}),e.frame&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:a,disabled:o,children:e.downloaded?Y(`Exported`,`내보냄`):e.frameB?Y(`Export start and end frames`,`시작·끝 프레임 내보내기`):Y(`Export frame`,`프레임 내보내기`)})]}),s,(0,$.jsxs)(`section`,{className:`result-next`,"aria-labelledby":`result-next-title`,children:[(0,$.jsx)(`span`,{className:`result-next-kicker`,children:Y(`Next · ${l}`,`다음 · ${l}`,`下一步 · ${l}`)}),(0,$.jsx)(`h4`,{id:`result-next-title`,children:Y(`Handing off to your AI`,`AI에 넣는 순서`)}),(0,$.jsx)(`div`,{className:`result-next-intro`,children:d}),(0,$.jsxs)(`ol`,{className:`result-handoff-steps`,children:[(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:Y(`Copy the prompt`,`프롬프트 복사`)}),(0,$.jsx)(`span`,{children:t?Y(`Copied. Paste it into your AI service's prompt box.`,`복사됐어요. AI 서비스의 입력창에 붙여 넣으세요.`):Y(`Press “Copy prompt” above, then paste it into your AI service.`,`위의 ‘프롬프트 복사’를 누른 뒤 AI 서비스 입력창에 붙여 넣으세요.`)})]}),(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:Y(`Export the frame`,`프레임 내보내기`)}),(0,$.jsx)(`span`,{children:e.frameB?Y(`Press “Export start and end frames” to save both PNGs.`,`‘시작·끝 프레임 내보내기’를 눌러 두 PNG를 저장하세요.`):u?Y(`Press “Export frame” to save the PNG.`,`‘프레임 내보내기’를 눌러 PNG를 저장하세요.`):Y(`This result has no frame to export.`,`이 결과에는 내보낼 프레임이 없어요.`)})]}),(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:Y(`Attach the image to your AI`,`AI에 이미지 첨부`)}),(0,$.jsx)(`span`,{children:e.frameB?Y(`Use your AI service's image attach button to upload the start and end frames together.`,`AI 서비스의 이미지 첨부 버튼에서 시작 프레임과 끝 프레임을 함께 올리세요.`):Y(`Use your AI service's image attach button to upload blocking-frame.png.`,`AI 서비스의 이미지 첨부 버튼에서 blocking-frame.png를 올리세요.`)})]})]}),(0,$.jsx)(`p`,{className:`result-handoff-note`,children:Y(`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,$.jsxs)(`p`,{className:`result-reference-video`,children:[(0,$.jsx)(`strong`,{children:Y(`Optional · Reference video`,`선택 사항 · 참고 영상`)}),Y(`A video recorded with the recording feature: `,`녹화 기능으로 만든 `),(0,$.jsx)(`code`,{children:n}),Y(` 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 gde(){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 _de=3;function vde({rig:e,take:t,objects:n,propTake:r}){let i=ms(Io),a=BB(),o=ry(e=>e.scene),s=ry(e=>e.gl),c=ry(e=>e.invalidate),l=(0,Q.useMemo)(()=>new iQ({layer:5}),[]),u=a.mode!==`off`&&!!e&&Ba(t),d=(0,Q.useMemo)(()=>u&&a.mode===`keys`?GB(t,n):[],[u,a.mode,t,n]),f=(0,Q.useMemo)(()=>u?HB({frame:i,last:t.frameCount-1,...a,keyFrames:d}):[],[u,i,t,a,d]);return(0,Q.useEffect)(()=>{if(u)return o.add(l.object),()=>{o.remove(l.object)}},[u,o,l]),(0,Q.useEffect)(()=>()=>l.dispose(),[l]),(0,Q.useEffect)(()=>{c()},[c,u,f]),(0,Q.useEffect)(()=>{typeof window<`u`&&(window.__cozyclayGhosts={set:l,gl:s,scene:o,entries:f})},[l,s,o,f]),iy(()=>{l.show(u&&!!e.parent)&&(l.setRig(e),l.syncSources(o,n,t,_de),e.parent.updateWorldMatrix(!0,!1),l.update({entries:f,take:t,placement:e.parent.matrixWorld,propTake:r,objects:n,count:a.count}))}),null}var yde=3,bde=.3,b5=.042,x5={w:512,h:96},xde=()=>{},S5=new WeakMap;function Sde(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 Cde(){let e=document.createElement(`canvas`);Object.assign(e,{width:x5.w,height:x5.h});let t=new Wl(e);t.colorSpace=Vu;let n=new Mp(new Qp({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=xde,n.userData={canvas:e,texture:t,text:null},n}function wde(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=Ia,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`:Ia,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 Tde({set:e,label:t,draft:n,rig:r,scene:i,objects:a,propTake:o}){let s=n?bo(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,yde),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(Ia).multiplyScalar(1.15),l.material.opacity=s.opacity;let u=Sde(l.rig);u&&(e.object.updateMatrixWorld(!0),u.getWorldPosition(t.position),t.position.y+=bde,t.material.opacity=Math.min(1,s.opacity/Lo))}function Ede({rigs:e,objects:t}){let n=(0,Q.useSyncExternalStore)(vi,As,As),r=(0,Q.useMemo)(()=>hs(),[n]),i=na(),a=ry(e=>e.scene),o=ry(e=>e.invalidate),s=(0,Q.useMemo)(()=>new iQ({layer:5}),[]),c=(0,Q.useMemo)(()=>Cde(),[]),l=r?e?.[r.characterId]??null:null,u=i&&!!l&&!!r?.take,d=(0,Q.useMemo)(()=>r?.take?{frameCount:r.take.frameCount,fps:r.take.fps,objectTracks:eQ(r.take)}:null,[r]);return(0,Q.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,Q.useEffect)(()=>()=>{s.dispose(),c.material.dispose(),c.userData.texture.dispose()},[s,c]),(0,Q.useEffect)(()=>{r&&wde(c,Ja(r),r.qa?.total===0)},[r,c]),(0,Q.useEffect)(()=>{if(o(),!u)return;let e=setInterval(()=>{(bo(r,Date.now()).shown||s.object.visible)&&o()},1e3/(r.take.fps||24));return()=>clearInterval(e)},[u,r,s,o]),iy(()=>Tde({set:s,label:c,draft:u?r:null,rig:l,scene:a,objects:t,propTake:d})),null}var Dde=.42,Ode=.2,kde=420,Ade=Math.PI/180,jde=44,Mde=()=>{},Nde=e=>1-(1-e)**3;function Pde(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 af().compose(new Z(r.x,r.y,r.z),new Tu().setFromAxisAngle(new Z(0,1,0),r.rot*Ade),new Z(1,1,1))}function Fde(e,t){let n=[];for(let r of e){let e=Pde(r,t);for(let t of Qt(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 af().fromArray(a))})}}return n}var Ide=class{root=new el;meshes=new Map;constructor(){this.root.name=`sculpt-sketch`,this.root.userData.sculptSketch=!0}make(e,t){let n=f8(e.shape===`scatter`?{...e,shape:`blob`,roundness:.5,taper:0}:e),r=new jf({color:e.color,emissive:e.color,emissiveIntensity:.18,roughness:.85,metalness:0,transparent:!0,opacity:0,depthWrite:!1}),i=new rd(n,r);return Object.assign(i,{raycast:Mde,castShadow:!1,receiveShadow:!1,matrixAutoUpdate:!1,renderOrder:jde,frustumCulled:!1}),i.layers.set(5),i.userData.sculptSketch=!0,this.root.add(i),{mesh:i,base:new af,born:t,opacity:e.shape===`scatter`?Ode:Dde}}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 af;for(let r of this.meshes.values()){let i=Math.min(1,Math.max(0,(e-r.born)/kde)),a=Nde(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 Lde({objects:e}){let t=(0,Q.useSyncExternalStore)(pn,Sn,Sn),n=ry(e=>e.scene),i=ry(e=>e.invalidate),a=(0,Q.useMemo)(()=>new Ide,[]),o=(0,Q.useMemo)(()=>Fde(t,e),[t,e]);return(0,Q.useEffect)(()=>(n.add(a.root),typeof window<`u`&&(window.__cozyclaySculptSketch={frame:yt,clear:r,meshes:()=>a.meshes.size,root:a.root}),()=>{n.remove(a.root),a.dispose()}),[n,a]),(0,Q.useEffect)(()=>{a.update(o,performance.now()),i()},[a,o,i]),iy(()=>{a.frame(performance.now())&&i()}),null}function C5(e){if(!e)throw Error(`Assertion failed.`)}var w5=e=>e&&e[e.length-1],T5=e=>e>=0&&e<2**32,E5=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)},D5=e=>{let t=E5(e);return t&1?t+1>>1:-(t>>1)},O5=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),k5=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),A5=new TextEncoder,j5={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},M5={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},N5={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Rde=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,P5=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),F5=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}},zde=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},I5=e=>{throw Error(`Unexpected value: ${e}`)},Bde=(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))},Vde=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Hde=/^[a-z]{3}$/,Ude=e=>Hde.test(e),L5=1e6*(1+2**-52),Wde=(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}},R5=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Gde=e=>{C5(Number.isInteger(e.num)),C5(Number.isInteger(e.den)),C5(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}},z5=e=>Array.isArray(e)?e:[e],B5=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)}}},Kde=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),V5;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(V5||={});var H5=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==V5.Silent&&t!==V5.Errors&&t!==V5.Warnings&&t!==V5.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 B5}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=V5.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=V5.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=V5.Info&&console.info(...t)}};H5._level=V5.Info,H5._emitterInstance=null;var U5=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.`)}},qde=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.`)}},Jde=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 U5)&&!(t instanceof qde)&&!Kde(t))throw TypeError(`Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},Yde=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.`)},W5=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}},G5=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],K5=[-1,1,2,3,4,5,6,8],Xde=e=>{let t=G5.indexOf(e.sampleRate),n=null;t===-1&&(t=15,n=e.sampleRate);let r=K5.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 W5(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},q5=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],J5=[`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`],Y5=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],X5=[...Y5,...J5],Z5=[`webvtt`],Q5=[{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}],$5=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],e7=[`dtsc`,`dtsh`,`dtsl`,`dtse`],Zde=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]},t7=/^pcm-([usf])(\d+)(be)?$/,n7=e=>{if(C5(J5.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=t7.exec(e);C5(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}},r7=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`:$5.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`:e7.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:t7.test(e)?e:e===`webvtt`?`webvtt`:null,Qde=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...$5],$de=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,efe=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,tfe=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,nfe=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,i7=(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(!Qde.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&&!P5(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(j5);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(M5);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(N5);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(!$de.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(!efe.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(!tfe.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(!nfe.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($5.some(t=>e.decoderConfig.codec.startsWith(t))&&!$5.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: ${$5.join(`, `)}.`);if(t!==null&&r7(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},rfe=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],a7=(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(!rfe.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&&!P5(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(!e7.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${e7.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!J5.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${J5.join(`, `)}).`);if(t!==null&&r7(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},ife=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.`)},afe=[48e3,44100,32e3],ofe=[24e3,22050,16e3],o7;(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`})(o7||={});var s7;(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`})(s7||={});var c7=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})},sfe=e=>e&31,l7=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 cfe=(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:Bde(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},lfe=e=>{try{let t=[],n=[],r=[];for(let i of c7(e)){let a=e.subarray(i.offset,i.offset+i.length),o=sfe(a[0]);o===o7.SPS?t.push(a):o===o7.PPS?n.push(a):o===o7.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=dfe(i);C5(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 H5._error(`Error building AVC Decoder Configuration Record:`,e),null}},ufe=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){C5(e.chromaFormat!==null),C5(e.bitDepthLumaMinus8!==null),C5(e.bitDepthChromaMinus8!==null),C5(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)},u7={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}},dfe=e=>{try{let t=new W5(l7(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let n=t.readAlignedByte(),r=t.readAlignedByte(),i=t.readAlignedByte();E5(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=E5(t),a===3&&(c=t.readBits(1)),o=E5(t),s=E5(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=D5(t);i=(r+e+256)%256}r=i===0?r:i}}}E5(t);let l=E5(t);if(l===0)E5(t);else if(l===1){t.skipBits(1),D5(t),D5(t);let e=E5(t);for(let n=0;n<e;n++)D5(t)}E5(t),t.skipBits(1);let u=E5(t),d=E5(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=E5(t),n=E5(t),r=E5(t),i=E5(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=u7[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)&&(E5(t),E5(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&d7(t);let n=t.readBits(1);n&&d7(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),E5(t),E5(t),E5(t),E5(t),S=E5(t),C=E5(t))}if(S===null){C5(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=Q5.find(e=>e.level>=i)??w5(Q5),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);S=a,C=a}}return C5(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 H5._error(`Error parsing AVC SPS:`,e),null}},d7=e=>{let t=E5(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)E5(e),E5(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},f7=e=>e>>1&63,ffe=e=>{try{let t=new W5(l7(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}=mfe(t,n);E5(t);let u=E5(t),d=0;u===3&&(d=t.readBits(1));let f=E5(t),p=E5(t),m=f,h=p;if(t.readBits(1)){let e=E5(t),n=E5(t),r=E5(t),i=E5(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=E5(t),_=E5(t);E5(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)E5(t),y=E5(t),E5(t);if(E5(t),E5(t),E5(t),E5(t),E5(t),E5(t),t.readBits(1)&&t.readBits(1)&&hfe(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),E5(t),E5(t),t.skipBits(1)),gfe(t,E5(t)),t.readBits(1)){let e=E5(t);for(let n=0;n<e;n++)E5(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=vfe(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 H5._error(`Error parsing HEVC SPS:`,e),null}},pfe=e=>{try{let t=[],n=[],r=[],i=[];for(let a of c7(e)){let o=e.subarray(a.offset,a.offset+a.length),s=f7(o[0]);s===s7.VPS_NUT?t.push(o):s===s7.SPS_NUT?n.push(o):s===s7.PPS_NUT?r.push(o):(s===s7.PREFIX_SEI_NUT||s===s7.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=ffe(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new W5(l7(e));t.skipBits(16),E5(t),E5(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),E5(t),E5(t),D5(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&E5(t),D5(t),D5(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:s7.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:s7.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:s7.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:f7(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 H5._error(`Error building HEVC Decoder Configuration Record:`,e),null}},mfe=(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}},hfe=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))E5(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&D5(e);for(let t=0;t<n;t++)D5(e)}},gfe=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=_fe(e,r,t,n)},_fe=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(E5(e)+1):t-1,e.readBits(1),E5(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=E5(e),n=E5(e);for(let n=0;n<t;n++)E5(e),e.readBits(1);for(let t=0;t<n;t++)E5(e),e.readBits(1);i=t+n}return i},vfe=(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=u7[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)&&(E5(e),E5(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(E5(e),E5(e),E5(e),E5(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&E5(e),e.readBits(1)&&yfe(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=E5(e),E5(e),E5(e),E5(e),E5(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},yfe=(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?E5(e):o=e.readBits(1)===1;let s=1;o||(s=E5(e)+1),r&&p7(e,s,a),i&&p7(e,s,a)}},p7=(e,t,n)=>{for(let r=0;r<t;r++)E5(e),E5(e),n&&(E5(e),E5(e)),e.readBits(1)},bfe=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)},xfe;(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`})(xfe||={});var Sfe=e=>{let t=k5(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}},Cfe;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(Cfe||={});var wfe=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new W5(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 Tfe=[1,2,3,6],Efe=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new W5(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=Tfe[o],d;return d=i<3?afe[i]/1e3:ofe[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}]}},Dfe=8,Ofe=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],kfe=[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],Afe=[16,16,20,20,0,24,24,0],m7=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],jfe=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Mfe=8,Nfe=[32e3,44100,48e3,0],Pfe=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ffe=[512,1024,2048,4096],Ife=e=>{let t=Lfe(e),n=k5(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=Rfe(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}},Lfe=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new W5(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%Dfe!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=m7.length)return null;let o=Ofe[t.readBits(4)];if(o===0)return null;let s=kfe[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=Afe[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:m7[a]+ +!!u,sampleCount:r*32,channelLayout:jfe[a]|(u?Mfe:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},Rfe=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new W5(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=Nfe[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*Vde(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=Pfe[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}}},zfe=e=>{let t=new Uint8Array(20),n=k5(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 W5(t);return i.seekToByte(13),i.writeBits(2,Math.max(Ffe.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},h7=new Uint8Array,g7=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===h7&&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===h7}get microsecondTimestamp(){return Math.trunc(L5*this.timestamp)}get microsecondDuration(){return Math.trunc(L5*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)}},Bfe=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},_7=e=>{let t=e.filePos,n=new W5(Ufe(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}},Vfe=n(((e,t)=>{t.exports={}})),v7=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,k5(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)}},Hfe=(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.`)},Ufe=(e,t)=>{Hfe(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},Wfe=class{constructor(e){this.mutex=new F5,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)}}},y7=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Gfe=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`)},b7=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);C5(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}}},x7=new Uint8Array(8),S7=new DataView(x7.buffer),C7=e=>[(e%256+256)%256],w7=e=>(S7.setUint16(0,e,!1),[x7[0],x7[1]]),T7=e=>(S7.setInt16(0,e,!1),[x7[0],x7[1]]),E7=e=>(S7.setUint32(0,e,!1),[x7[1],x7[2],x7[3]]),D7=e=>(S7.setUint32(0,e,!1),[x7[0],x7[1],x7[2],x7[3]]),O7=e=>(S7.setInt32(0,e,!1),[x7[0],x7[1],x7[2],x7[3]]),k7=e=>(S7.setUint32(0,Math.floor(e/2**32),!1),S7.setUint32(4,e,!1),[x7[0],x7[1],x7[2],x7[3],x7[4],x7[5],x7[6],x7[7]]),Kfe=e=>(S7.setInt32(0,Math.floor(e/2**32),!1),S7.setUint32(4,e,!1),[x7[0],x7[1],x7[2],x7[3],x7[4],x7[5],x7[6],x7[7]]),A7=e=>(S7.setInt16(0,2**8*e,!1),[x7[0],x7[1]]),j7=e=>(S7.setInt32(0,2**16*e,!1),[x7[0],x7[1],x7[2],x7[3]]),M7=e=>(S7.setInt32(0,2**30*e,!1),[x7[0],x7[1],x7[2],x7[3]]),N7=(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()},P7=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},F7=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]},I7=F7(0),L7=e=>[j7(e[0]),j7(e[1]),M7(e[2]),j7(e[3]),j7(e[4]),M7(e[5]),j7(e[6]),j7(e[7]),M7(e[8])],R7=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),z7=(e,t,n,r,i)=>R7(e,[C7(t),E7(n),r??[]],i),qfe=e=>e.isQuickTime?R7(`ftyp`,[P7(`qt `),D7(512),P7(`qt `)]):e.fragmented?e.cmaf?R7(`ftyp`,[P7(`iso5`),D7(512),P7(`iso5`),P7(`iso6`),P7(`mp41`),P7(`cmfc`),P7(`dash`)]):R7(`ftyp`,[P7(`iso5`),D7(512),P7(`iso5`),P7(`iso6`),P7(`mp41`)]):R7(`ftyp`,[P7(`isom`),D7(512),P7(`isom`),e.holdsAvc?P7(`avc1`):[],P7(`mp41`)]),B7=()=>R7(`styp`,[P7(`iso5`),D7(0),P7(`iso5`),P7(`iso6`),P7(`mp41`),P7(`cmfc`),P7(`dash`)]),V7=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),z7(`sidx`,1,0,[D7(1),D7(u9),k7(d9(e.minWrittenTimestamp,u9)),k7(0),w7(0),w7(1),D7(t&2147483647),D7(d9(n,u9)),D7(0)])},H7=e=>({type:`mdat`,largeSize:e}),Jfe=e=>({type:`free`,size:e}),U7=e=>R7(`moov`,void 0,[Yfe(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Xfe(t,e.creationTime)),e.isFragmented?Npe(e.trackDatas):null,Kpe(e)]),Yfe=(e,t)=>{let n=Math.max(0,...t.map(e=>d9(W7(e),u9)+d9(e.startTimestampOffset??0,u9))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!T5(e)||!T5(n),a=i?k7:D7;return z7(`mvhd`,+i,0,[a(e),a(e),D7(u9),a(n),j7(1),A7(1),Array(10).fill(0),L7(I7),Array(24).fill(0),D7(r)])},W7=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},Xfe=(e,t)=>{let n=rme(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return R7(`trak`,void 0,[Zfe(e,t),r?Qfe(e,e.startTimestampOffset):null,$fe(e,t),n.name===void 0?null:R7(`udta`,void 0,[R7(`name`,[...A5.encode(n.name)])])])},Zfe=(e,t)=>{let n=d9(W7(e),u9)+d9(e.startTimestampOffset??0,u9),r=!T5(t)||!T5(n),i=r?k7:D7,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=F7(t??0)}else a=I7;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:I5(e);return z7(`tkhd`,+r,o,[i(t),i(t),D7(e.track.id),D7(0),i(n),Array(8).fill(0),w7(0),w7(s),A7(+(e.type===`audio`)),w7(0),L7(a),j7(e.type===`video`?e.info.width:0),j7(e.type===`video`?e.info.height:0)])},Qfe=(e,t)=>{let n=d9(t,u9),r=d9(W7(e),u9),i=!T5(n)||!T5(r),a=i?k7:D7,o=i?Kfe:O7;return R7(`edts`,void 0,[z7(`elst`,+!!i,0,[D7(2),a(n),o(-1),j7(1),a(r),o(0),j7(1)])])},$fe=(e,t)=>R7(`mdia`,void 0,[epe(e,t),G7(!0,tpe[e.type],npe[e.type]),rpe(e)]),epe=(e,t)=>{let n=d9(W7(e),e.timescale),r=!T5(t)||!T5(n),i=r?k7:D7;return z7(`mdhd`,+r,0,[i(t),i(t),D7(e.timescale),i(n),w7(r9(e.track.metadata.languageCode??`und`)),w7(0)])},tpe={video:`vide`,audio:`soun`,subtitle:`text`},npe={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},G7=(e,t,n,r=`\0\0\0\0`)=>z7(`hdlr`,0,0,[e?P7(`mhlr`):D7(0),P7(t),P7(r),D7(0),D7(0),P7(n,!0)]),rpe=e=>R7(`minf`,void 0,[ipe[e.type](),ape(),cpe(e)]),ipe={video:()=>z7(`vmhd`,0,1,[w7(0),w7(0),w7(0),w7(0)]),audio:()=>z7(`smhd`,0,0,[w7(0),w7(0)]),subtitle:()=>z7(`nmhd`,0,0)},ape=()=>R7(`dinf`,void 0,[ope()]),ope=()=>z7(`dref`,0,0,[D7(1)],[spe()]),spe=()=>z7(`url `,0,1),cpe=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return R7(`stbl`,void 0,[lpe(e),Epe(e),t?jpe(e):null,t?Mpe(e):null,Ope(e),kpe(e),Ape(e),Dpe(e)])},lpe=e=>{let t;if(e.type===`video`)t=upe(Xpe(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=n9(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);C5(n),t=gpe(n,e)}else e.type===`subtitle`&&(t=wpe($pe[e.track.source._codec],e));return C5(t),z7(`stsd`,0,0,[D7(1)],[t])},upe=(e,t)=>R7(e,[[,,,,,,].fill(0),w7(1),w7(0),w7(0),Array(12).fill(0),w7(t.info.width),w7(t.info.height),D7(4718592),D7(4718592),D7(0),w7(1),C7(10),P7(`Mediabunny`),Array(21).fill(0),w7(t.info.hasAlphaChannel?32:24),T7(65535)],[Zpe[t.track.source._codec]?.(t)??null,dpe(t),Rde(t.info.decoderConfig.colorSpace)?fpe(t):null]),dpe=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:R7(`pasp`,[D7(e.info.pixelAspectRatio.num),D7(e.info.pixelAspectRatio.den)]),fpe=e=>R7(`colr`,[P7(e.muxer.isQuickTime?`nclc`:`nclx`),w7(j5[e.info.decoderConfig.colorSpace.primaries]),w7(M5[e.info.decoderConfig.colorSpace.transfer]),w7(N5[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:C7(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),ppe=e=>e.info.decoderConfig&&R7(`avcC`,[...O5(e.info.decoderConfig.description)]),mpe=e=>e.info.decoderConfig&&R7(`hvcC`,[...O5(e.info.decoderConfig.description)]),K7=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?j5[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?M5[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?N5[t.colorSpace.matrix]:2;return z7(`vpcC`,1,0,[C7(r),C7(i),C7(c),C7(l),C7(u),C7(d),w7(0)])},hpe=e=>R7(`av1C`,Zde(e.info.decoderConfig.codec)),gpe=(e,t)=>{let n=0,r,i=16,a=J5.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=n7(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),w7(1),w7(n),w7(0),D7(0),w7(t.info.numberOfChannels),w7(i),w7(0),w7(0),w7(t.info.sampleRate<2**16?t.info.sampleRate:0),w7(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),w7(1),w7(n),w7(0),D7(0),w7(t.info.numberOfChannels),w7(Math.min(i,16)),T7(e),w7(0),w7(t.info.sampleRate<2**16?t.info.sampleRate:0),w7(0),a?[D7(1),D7(i/8),D7(t.info.numberOfChannels*i/8)]:[D7(0),D7(0),D7(0)],D7(2)]}return R7(e,r,[Qpe(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},q7=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=[...C7(t),...C7(21),...E7(0),...D7(0),...D7(0)];if(e.info.decoderConfig.description){let t=O5(e.info.decoderConfig.description);n=[...n,...C7(5),...N7(t.byteLength),...t]}return n=[...w7(1),...C7(0),...C7(4),...N7(n.length),...n,...C7(6),...C7(1),...C7(2)],n=[...C7(3),...N7(n.length),...n],z7(`esds`,0,0,n)},J7=e=>R7(`wave`,void 0,[_pe(e),vpe(e),R7(`\0\0\0\0`)]),_pe=e=>R7(`frma`,[P7(n9(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),vpe=e=>{let{littleEndian:t}=n7(e.track.source._codec);return R7(`enda`,[w7(+t)])},ype=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){C5(s.byteLength>=18);let e=Sfe(O5(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return R7(`dOps`,[C7(0),C7(t),w7(n),D7(r),T7(i),C7(a),...o])},bpe=e=>{let t=e.info.decoderConfig?.description;return C5(t),z7(`dfLa`,0,0,[...O5(t).subarray(4)])},Y7=e=>{let{littleEndian:t,sampleSize:n}=n7(e.track.source._codec);return z7(`pcmC`,0,0,[C7(+t),C7(8*n)])},xpe=e=>{C5(e.info.primingPacket);let t=wfe(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 W5(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),R7(`dac3`,[...n])},Spe=e=>{C5(e.info.primingPacket);let t=Efe(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 W5(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 R7(`dec3`,[...i])},Cpe=e=>{C5(e.info.primingPacket);let t=Ife(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 R7(`ddts`,[...zfe(t)])},wpe=(e,t)=>R7(e,[[,,,,,,].fill(0),w7(1)],[eme[t.track.source._codec](t)]),Tpe=e=>R7(`vttC`,[...A5.encode(e.info.config.description)]),Epe=e=>z7(`stts`,0,0,[D7(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[D7(e.sampleCount),D7(e.sampleDelta)])]),Dpe=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return z7(`stss`,0,0,[D7(t.length),t.map(([e])=>D7(e+1))])},Ope=e=>z7(`stsc`,0,0,[D7(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[D7(e.firstChunk),D7(e.samplesPerChunk),D7(1)])]),kpe=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=n7(e.track.source._codec);return z7(`stsz`,0,0,[D7(t*e.info.numberOfChannels),D7(e.samples.reduce((t,n)=>t+d9(n.duration,e.timescale),0))])}return z7(`stsz`,0,0,[D7(0),D7(e.samples.length),e.samples.map(e=>D7(e.size))])},Ape=e=>e.finalizedChunks.length>0&&w5(e.finalizedChunks).offset>=2**32?z7(`co64`,0,0,[D7(e.finalizedChunks.length),e.finalizedChunks.map(e=>k7(e.offset))]):z7(`stco`,0,0,[D7(e.finalizedChunks.length),e.finalizedChunks.map(e=>D7(e.offset))]),jpe=e=>z7(`ctts`,1,0,[D7(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[D7(e.sampleCount),O7(e.sampleCompositionTimeOffset)])]),Mpe=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;C5(e.compositionTimeOffsetTable.length>0),C5(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,d9(n.timestamp,e.timescale)),i=Math.max(i,d9(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:z7(`cslg`,0,0,[O7(a),O7(t),O7(n),O7(r),O7(i)])},Npe=e=>R7(`mvex`,void 0,e.map(Ppe)),Ppe=e=>z7(`trex`,0,0,[D7(e.track.id),D7(1),D7(0),D7(0),D7(0)]),X7=(e,t)=>R7(`moof`,void 0,[Fpe(e),...t.map(Ipe)]),Fpe=e=>z7(`mfhd`,0,0,[D7(e)]),Z7=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Ipe=e=>R7(`traf`,void 0,[Lpe(e),Rpe(e),zpe(e)]),Lpe=e=>{C5(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:Z7(n)};return z7(`tfhd`,0,t,[D7(e.track.id),D7(r.duration),D7(r.size),D7(r.flags)])},Rpe=e=>(C5(e.currentChunk),z7(`tfdt`,1,0,[k7(d9(e.currentChunk.startTimestamp,e.timescale))])),zpe=e=>{C5(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Z7),i=e.currentChunk.samples.map(t=>d9(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,z7(`trun`,1,m,[D7(e.currentChunk.samples.length),D7(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?D7(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?D7(t[a]):[],d?D7(n[a]):[],f?D7(r[a]):[],p?O7(i[a]):[]])])},Bpe=e=>R7(`mfra`,void 0,[...e.map(Vpe),Hpe()]),Vpe=e=>z7(`tfra`,1,0,[D7(e.track.id),D7(63),D7(e.finalizedChunks.length),e.finalizedChunks.map(t=>[k7(d9(t.samples[0].timestamp,e.timescale)),k7(t.moofOffset),D7(t.trafIndex+1),D7(1),D7(1)])]),Hpe=()=>z7(`mfro`,0,0,[D7(0)]),Upe=()=>R7(`vtte`),Wpe=(e,t,n,r,i)=>R7(`vttc`,void 0,[i===null?null:R7(`vsid`,[O7(i)]),n===null?null:R7(`iden`,[...A5.encode(n)]),t===null?null:R7(`ctim`,[...A5.encode(Gfe(t))]),r===null?null:R7(`sttg`,[...A5.encode(r)]),R7(`payl`,[...A5.encode(e)])]),Gpe=e=>R7(`vtta`,[...A5.encode(e)]),Kpe=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Jpe(r);e&&t.push(e)}else if(n===`mdta`){let e=Ype(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&qpe(t,e.output._metadataTags);return t.length===0?null:R7(`udta`,void 0,t)},qpe=(e,t)=>{for(let{key:n,value:r}of R5(t))switch(n){case`title`:e.push(Q7(`©nam`,r));break;case`description`:e.push(Q7(`©des`,r));break;case`artist`:e.push(Q7(`©ART`,r));break;case`album`:e.push(Q7(`©alb`,r));break;case`albumArtist`:e.push(Q7(`albr`,r));break;case`genre`:e.push(Q7(`©gen`,r));break;case`date`:e.push(Q7(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(Q7(`©cmt`,r));break;case`lyrics`:e.push(Q7(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:I5(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(Q7(n,r)):r instanceof Uint8Array&&e.push(R7(n,Array.from(r))))}},Q7=(e,t)=>{let n=A5.encode(t);return R7(e,[w7(n.length),w7(r9(`und`)),Array.from(n)])},$7={"image/jpeg":13,"image/png":14,"image/bmp":27},e9=(e,t)=>{let n=[];for(let{key:r,value:i}of R5(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:t9(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:t9(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:t9(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:t9(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:t9(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:t9(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:t9(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:t9(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:t9(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:R7(`data`,[D7($7[e.mimeType]??0),D7(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:t9(t)})}else n.push({key:`trkn`,value:R7(`data`,[D7(0),D7(0),w7(0),w7(i),w7(e.tracksTotal??0),w7(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:R7(`data`,[D7(0),D7(0),w7(0),w7(i),w7(e.discsTotal??0),w7(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:I5(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:t9(i)}):i instanceof Uint8Array?n.push({key:r,value:R7(`data`,[D7(0),D7(0),Array.from(i)])}):i instanceof U5&&n.push({key:r,value:R7(`data`,[D7($7[i.mimeType]??0),D7(0),Array.from(i.data)])}))}return n},Jpe=e=>{let t=e9(e,!1);return t.length===0?null:z7(`meta`,0,0,void 0,[G7(!1,`mdir`,``,`appl`),R7(`ilst`,void 0,t.map(e=>R7(e.key,void 0,[e.value])))])},Ype=e=>{let t=e9(e,!0);return t.length===0?null:R7(`meta`,void 0,[G7(!1,`mdta`,``),z7(`keys`,0,0,[D7(t.length)],t.map(e=>R7(`mdta`,[...A5.encode(e.key)]))),R7(`ilst`,void 0,t.map((e,t)=>R7(String.fromCharCode(...D7(t+1)),void 0,[e.value])))])},t9=e=>R7(`data`,[D7(1),D7(0),...A5.encode(e)]),Xpe=(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}},Zpe={avc:ppe,hevc:mpe,vp8:K7,vp9:K7,av1:hpe,prores:null},n9=(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`}},Qpe=(e,t)=>{switch(e){case`aac`:return q7;case`mp3`:return q7;case`opus`:return ype;case`vorbis`:return q7;case`flac`:return bpe;case`ac3`:return xpe;case`eac3`:return Spe;case`dts`:return Cpe}if(t)switch(e){case`pcm-s24`:return J7;case`pcm-s24be`:return J7;case`pcm-s32`:return J7;case`pcm-s32be`:return J7;case`pcm-f32`:return J7;case`pcm-f32be`:return J7;case`pcm-f64`:return J7;case`pcm-f64be`:return J7}else switch(e){case`pcm-s16`:return Y7;case`pcm-s16be`:return Y7;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}return null},$pe={webvtt:`wvtt`},eme={webvtt:Tpe},r9=e=>{C5(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},i9=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(){C5(!this.started),this.target._start(),this.started=!0}write(e){C5(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 C5(this.started&&!this.finalized),this.target._flush()}async finalize(){C5(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}};Vfe();var a9=class extends B5{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 tme(this,e)}},o9=2**16,s9=2**32,c9=class extends a9{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(o9,{maxByteLength:s9})}catch{this._buffer=new ArrayBuffer(o9),this._supportsResize=!1}else this._buffer=new ArrayBuffer(o9);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>s9)throw Error(`ArrayBuffer exceeded maximum size of ${s9} 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)}},tme=class extends a9{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)}},l9=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.`)}},u9=57600,nme=2082844800,rme=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},d9=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},ime=class extends Wfe{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new c9,this.auxWriter=new i9(this.auxTarget,!1),this.auxBoxWriter=new b7(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=zde(),this.creationTime=Math.floor(Date.now()/1e3)+nme,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 v9,this.isCmaf=t instanceof _9,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof _9?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 c9:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new b7(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof c9&&`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 i9(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new b7(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(C5(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(qfe({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||(C5(this.writer),C5(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=H7(!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 Bfe({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;i7(n,e.source._codec),C5(n),C5(n.decoderConfig);let i={...n.decoderConfig};C5(i.codedWidth!==void 0),C5(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=lfe(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=ufe(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=pfe(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=bfe(e),a=!0}let o=Wde(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:Gde({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;a7(n,e.source._codec),C5(n),C5(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=_7(v7.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=G5[e.samplingFrequencyIndex],r=K5[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=Xde({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&&J5.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;ife(t),C5(t),C5(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=[...c7(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=cfe(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=_7(v7.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=n7(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=d9(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=n7(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)C5(r.timestamp<=t),C5(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=Upe();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;y7.lastIndex=0;let r=y7.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=Gpe(n.notes);this.auxBoxWriter.writeBox(e)}let c=Wpe(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:d9(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=d9(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=w5(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=d9(r.timestamp-r.decodeTimestamp,e.timescale),a=d9(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){C5(e.lastSample);let t=d9(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(C5(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=w5(e.timeToSampleTable);if(C5(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=w5(e.compositionTimeOffsetTable);C5(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=d9(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,C5(e.lastSample),C5(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){C5(t.type===`key`);let n=d9(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(C5(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}),C5(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(C5(!this.isFragmented),C5(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+d9(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||w5(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)C5(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(C5(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(C5(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;C5(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=U7(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){C5(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new b7(this.writer);let e=this.boxWriter.measureBox(B7()),t=this.boxWriter.measureBox(V7(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}C5(this.writer),C5(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=X7(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=X7(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}C5(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=H7(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(){C5(this.writer),C5(this.boxWriter),this.ensureOneEnabledTrack();let e=U7(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;C5(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=H7(!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(){C5(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;C5(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(){C5(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(C5(this.writer),C5(this.boxWriter),this.fastStart===`in-memory`){this.mdat=H7(!1);let e;for(let t=0;t<2;t++){let t=U7(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)C5(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=U7(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)C5(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(B7()),this.boxWriter.writeBox(V7(this,e))}else{let e=this.writer.getPos(),t=Bpe(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{C5(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);C5(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=U7(this);if(this.fastStart===`reserve`){C5(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(Jfe(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()}},f9=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})()}},p9=class extends f9{constructor(e){if(super(),this._connectedTrack=null,!q5.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${q5.join(`, `)}.`);this._codec=e}},ame=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},ome=class extends p9{constructor(e){super(e)}add(e,t){if(!(e instanceof g7))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(),ame(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},sme=class extends f9{constructor(e){if(super(),this._connectedTrack=null,!X5.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${X5.join(`, `)}.`);this._codec=e}},cme=class extends f9{constructor(e){if(super(),this._connectedTrack=null,!Z5.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Z5.join(`, `)}.`);this._codec=e}},m9=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>q5.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>X5.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Z5.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},h9=class extends m9{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 ime(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},g9=class extends h9{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...q5,...Y5,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Z5]}_codecUnsupportedHint(e){return new v9().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},_9=class extends h9{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...q5,...Y5,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Z5]}},v9=class extends h9{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...q5,...X5]}_codecUnsupportedHint(e){return new g9().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},y9=[`video`,`audio`,`subtitle`],b9=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=z5(this.metadata.group),r=z5(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}},lme=class extends b9{constructor(e,t,n,r){super(e,t,`video`,n,r)}},ume=class extends b9{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},dme=class extends b9{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},x9=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)}},S9=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Ude(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&&Yde(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 x9)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof x9))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},fme=class extends B5{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 x9,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new F5,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 m9))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof a9||e.target instanceof l9))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof a9&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof a9)&&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 a9&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){C5(this._target instanceof l9);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof a9))throw TypeError(`getTarget must return a Target.`);return e};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){C5(this._target instanceof l9);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(C5(this._initTarget!==null),this._initTarget instanceof a9)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 a9)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 i9(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof p9))throw TypeError(`source must be a VideoSource.`);if(S9(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&&i7({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof g7))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 lme(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof sme))throw TypeError(`source must be an AudioSource.`);if(S9(t),t.decoderConfig!==void 0&&a7({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof g7))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 ume(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof cme))throw TypeError(`source must be a SubtitleSource.`);S9(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new dme(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Jde(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 y9)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 y9){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?(H5._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 H5._warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&H5._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?(H5._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()}})()}},pme=e=>{if(e.startsWith(`avc1`))return`avc`;throw RangeError(`unsupported MP4 video codec: ${e}`)};async function mme({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 c9,a=new fme({format:new g9({fastStart:`in-memory`}),target:i}),o=new ome(pme(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 g7(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 hme=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 gme(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 _me(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 vme(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 C9(e,t){try{Object.defineProperty(e,"exportFailureCode",{value:e?.name===`AbortError`?`aborted`:t,configurable:!0})}catch{}return e}function w9(e,t){return t?new Promise((n,r)=>{let i=()=>{a(),r(T9())},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 yme(e,t,n,r,i){for(let a of hme){if(i?.aborted)throw T9();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 w9(r.isConfigSupported(o),i);if(e.supported)return e.config}catch(e){if(e?.name===`AbortError`)throw e}}throw i?.aborted?T9():C9(Error(`This browser has no H.264 WebCodecs encoder for MP4 export`),`unsupported_codec`)}function T9(){return new DOMException(`Offscreen export was cancelled`,`AbortError`)}async function bme({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 T9();let f=gme(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 C9(Error(`This browser does not support WebCodecs video export`),`unsupported_codec`);let p=await yme(r,i,n,u,o);if(o?.aborted)throw T9();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 T9();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 T9();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 w9(_me(u),o);if(g.push(p),vme(u,e,r,i),y=`encode_failed`,o?.aborted)throw T9();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 w9(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 w9(v.flush(),o),o?.aborted))throw T9();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 mme({chunks:m,codec:p.codec,decoderConfig:h??{codec:p.codec,codedWidth:r,codedHeight:i},signal:o});if(o?.aborted)throw T9();return{...f,fps:n,width:r,height:i,codec:p.codec,mimeType:S.type,encodedFrameCount:m.length,hashes:g,blob:S}}catch(e){throw C9(e,y)}finally{o?.removeEventListener(`abort`,b),b()}}var E9=e=>Number.isFinite(e)?e:null;function D9({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:E9(l?.focalMm)??E9(c?.focalMm),fovDeg:E9(l?.fovDeg)??E9(c?.fovDeg),aspect:typeof i==`string`&&i?i:null,size:{width:E9(a?.width),height:E9(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:E9(e?.startFrame),end:E9(e?.endFrame)},fps:E9(r),shotIndex:Number.isInteger(s)&&s>=0?s:null,shotTitle:typeof e?.name==`string`&&e.name?e.name:null,targetModel:e?.targetModel??null,frame:E9(o)}}var xme=(()=>{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 Sme(e){let t=4294967295;for(let n=0;n<e.length;n++)t=xme[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}var O9=new TextEncoder,k9=0,A9=23585,j9=2048,M9=0,N9=20;function P9(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function F9(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 I9(e){if(!Array.isArray(e))throw TypeError(`buildZip expects an array of { name, data } entries`);let t=e.map(e=>{let t=O9.encode(e.name),n=typeof e.data==`string`?O9.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:Sme(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),F9(i,a,67324752),P9(i,a+4,N9),P9(i,a+6,j9),P9(i,a+8,M9),P9(i,a+10,k9),P9(i,a+12,A9),F9(i,a+14,r),F9(i,a+18,n.length),F9(i,a+22,n.length),P9(i,a+26,e.length),P9(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];F9(i,a,33639248),P9(i,a+4,N9),P9(i,a+6,N9),P9(i,a+8,j9),P9(i,a+10,M9),P9(i,a+12,k9),P9(i,a+14,A9),F9(i,a+16,s),F9(i,a+20,r.length),F9(i,a+24,r.length),P9(i,a+28,n.length),P9(i,a+30,0),P9(i,a+32,0),P9(i,a+34,0),P9(i,a+36,0),F9(i,a+38,0),F9(i,a+42,o[e]),i.set(n,a+46),a+=46+n.length}let c=a-s;return F9(i,a,101010256),P9(i,a+4,0),P9(i,a+6,0),P9(i,a+8,t.length),P9(i,a+10,t.length),F9(i,a+12,c),F9(i,a+16,s),P9(i,a+20,0),i}function L9(e){return String(e??``).toLowerCase().normalize(`NFKD`).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`shot`}function Cme(e){return`cozyclay-shot-${e.index}-${L9(e.title)}.zip`}function wme({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 R9({shot:e,fps:t,firstFramePng:n,lastFramePng:r,clip:i,camera:a,prompt:o,stylizedPng:s=null,folder:c=`${e.index}-${L9(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:wme({shot:e,fps:t,hasLast:r!=null,hasClip:i!=null,ext:i?i.ext:`mp4`,hasStylized:s!=null})}),l}function Tme(e){return I9(R9(e))}var Eme=90,z9=.5;function Dme(e){return((typeof e.caption==`string`?e.caption.trim():``)||String(e.prompt??``)).slice(0,Eme)}function B9({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*z9,n=p*z9;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(Dme(e),s,c)}),c}var Ome=Object.freeze([`depth`,`normal`]);function kme(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 Ame(e){if(!Ome.includes(e))throw Error(`Unknown render pass: ${e}`);return`blocking-frame-${e}.png`}var jme=`
|