openvideo 0.2.17 → 0.2.18

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/dist/index.umd.js CHANGED
@@ -3506,7 +3506,7 @@ fn mainFragment(
3506
3506
  `)}function Ak(r,e,t,i,n){const{domElement:s,styleElement:o,svgRoot:a}=n;s.innerHTML=`<style>${e.cssStyle}</style><div style='padding:0;'>${r}</div>`,s.setAttribute("style",`transform: scale(${t});transform-origin: top left; display: inline-block`),o.textContent=i;const{width:l,height:u}=n.image;return a.setAttribute("width",l.toString()),a.setAttribute("height",u.toString()),new XMLSerializer().serializeToString(a)}function Ek(r,e){const t=ki.getOptimalCanvasAndContext(r.width,r.height,e),{context:i}=t;return i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),t}function Pk(r,e,t){return new Promise(async i=>{t&&await new Promise(n=>setTimeout(n,100)),r.onload=()=>{i()},r.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(e)}`,r.crossOrigin="anonymous"})}class Wb{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===vr.WEBGPU}getTexture(e){return this.getTexturePromise(e)}getManagedTexture(e){const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].promise;const i=this._buildTexturePromise(e).then(n=>(this._activeTextures[t].texture=n,n));return this._activeTextures[t]={texture:null,promise:i,usageCount:1},i}getReferenceCount(e){return this._activeTextures[e]?.usageCount??null}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t.texture):t.promise.then(i=>{t.texture=i,this._cleanUp(t.texture)}).catch(()=>{de("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[e]=null))}getTexturePromise(e){return this._buildTexturePromise(e)}async _buildTexturePromise(e){const{text:t,style:i,resolution:n,textureStyle:s}=e,o=It.get(n2),a=wk(t,i),l=await Ck(a),u=s2(t,i,l,o),c=Math.ceil(Math.ceil(Math.max(1,u.width)+i.padding*2)*n),h=Math.ceil(Math.ceil(Math.max(1,u.height)+i.padding*2)*n),d=o.image,f=2;d.width=(c|0)+f,d.height=(h|0)+f;const p=Ak(t,i,n,l,o);await Pk(d,p,_k()&&a.length>0);const m=d;let g;this._createCanvas&&(g=Ek(d,n));const v=Hb(g?g.canvas:m,d.width-f,d.height-f,n);return s&&(v.source.style=s),this._createCanvas&&(this._renderer.texture.initSource(v.source),ki.returnCanvasAndContext(g)),It.return(o),v}returnTexturePromise(e){e.then(t=>{this._cleanUp(t)}).catch(()=>{de("HTMLTextSystem: Failed to clean texture")})}_cleanUp(e){ze.returnTexture(e,!0),e.source.resource=null,e.source.uploadMethodId="unknown"}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexturePromise(this._activeTextures[e].promise);this._activeTextures=null}}Wb.extension={type:[F.WebGLSystem,F.WebGPUSystem,F.CanvasSystem],name:"htmlText"};class Vb extends Ie{constructor(e){const{text:t,style:i,autoSplit:n,lineAnchor:s,wordAnchor:o,charAnchor:a,...l}=e;super(l),this._dirty=!1,this._canReuseChars=!1,this.chars=[],this.words=[],this.lines=[],this._originalText=t,this._autoSplit=n,this._lineAnchor=s,this._wordAnchor=o,this._charAnchor=a,this.style=i}split(){const e=this.splitFn();this.chars=e.chars,this.words=e.words,this.lines=e.lines,this.addChild(...this.lines),this.charAnchor=this._charAnchor,this.wordAnchor=this._wordAnchor,this.lineAnchor=this._lineAnchor,this._dirty=!1,this._canReuseChars=!0}get text(){return this._originalText}set text(e){this._originalText=e,this.lines.forEach(t=>t.destroy({children:!0})),this.lines.length=0,this.words.length=0,this.chars.length=0,this._canReuseChars=!1,this.onTextUpdate()}_setOrigin(e,t,i){let n;typeof e=="number"?n={x:e,y:e}:n={x:e.x,y:e.y},t.forEach(s=>{const o=s.getLocalBounds(),a=o.minX+o.width*n.x,l=o.minY+o.height*n.y;s.origin.set(a,l)}),this[i]=e}get lineAnchor(){return this._lineAnchor}set lineAnchor(e){this._setOrigin(e,this.lines,"_lineAnchor")}get wordAnchor(){return this._wordAnchor}set wordAnchor(e){this._setOrigin(e,this.words,"_wordAnchor")}get charAnchor(){return this._charAnchor}set charAnchor(e){this._setOrigin(e,this.chars,"_charAnchor")}get style(){return this._style}set style(e){e||(e={}),this._style=new Bt(e),this.words.forEach(t=>t.destroy()),this.words.length=0,this.lines.forEach(t=>t.destroy()),this.lines.length=0,this._canReuseChars=!0,this.onTextUpdate()}onTextUpdate(){this._dirty=!0,this._autoSplit&&this.split()}destroy(e){super.destroy(e),this.chars=[],this.words=[],this.lines=[],(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._originalText=""}}const Ik=class zh extends Vb{constructor(e){const t={...zh.defaultOptions,...e};super(t)}static from(e,t){const i={...zh.defaultOptions,...t,text:e.text,style:new Bt(e.style)};return new zh({...i})}splitFn(){return yk({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};Ik.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let kl=Ik;function pV(r,e,t){switch(r){case"center":return(t-e)/2;case"right":return t-e;case"left":default:return 0}}function Bk(r){return r==="\r"||r===`
3507
3507
  `||r===`\r
3508
3508
  `}function mV(r,e,t){const i=[];let n=e.lines[0],s="",o=[],a=0;return t.wordWrap=!1,r.forEach(l=>{const u=/^\s*$/.test(l),c=Bk(l),h=s.length===0&&u;if(u&&!c&&h)return;c||(s+=l);const d=Ht.measureText(l,t);o.push({char:l,metric:d}),s.length>=n.length&&(i.push({line:s,chars:o,width:o.reduce((f,p)=>f+p.metric.width,0)}),o=[],s="",a++,n=e.lines[a])}),i}function kk(r){const{text:e,style:t,chars:i}=r,n=t,s=Ht.measureText(e,n),o=Ht.graphemeSegmenter(e),a=mV(o,s,n.clone()),l=n.align,u=s.lineWidths.reduce((g,v)=>Math.max(g,v),0),c=[],h=[],d=[];let f=0;const p=n.stroke?.width||0,m=n.dropShadow?.distance||0;return a.forEach((g,v)=>{const x=new Ie({label:`line-${v}`});x.y=f,h.push(x);const y=s.lineWidths[v];let b=pV(l,y,u),T=new Ie({label:"word"});T.x=b,g.chars.forEach((E,C)=>{if(E.metric.width!==0){if(Bk(E.char)){b+=E.metric.width-p;return}if(E.char===" ")T.children.length>0&&(d.push(T),x.addChild(T)),b+=E.metric.width+n.letterSpacing-p,T=new Ie({label:"word"}),T.x=b;else{let P;i.length>0?(P=i.shift(),P.text=E.char,P.style=n,P.setFromMatrix(ae.IDENTITY),P.x=b-T.x-m*C):P=new eh({text:E.char,style:n,x:b-T.x-m*C}),c.push(P),T.addChild(P),b+=E.metric.width+n.letterSpacing-p}}}),T.children.length>0&&(d.push(T),x.addChild(T)),f+=s.lineHeight}),{chars:c,lines:h,words:d}}const Rk=class Lh extends Vb{constructor(e){const t={...Lh.defaultOptions,...e};super(t)}static from(e,t){const i={...Lh.defaultOptions,...t,text:e.text,style:new Bt(e.style)};return new Lh({...i})}splitFn(){return kk({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};Rk.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let gV=Rk;class Fk extends Pl{constructor(e){super(),this._renderer=e,e.runners.resolutionChange.add(this)}resolutionChange(){const e=this.renderable;e._autoResolution&&e.onViewUpdate()}destroy(){const{canvasText:e}=this._renderer;e.getReferenceCount(this.currentKey)>0?e.decreaseReferenceCount(this.currentKey):this.texture&&e.returnTexture(this.texture),this._renderer.runners.resolutionChange.remove(this),this._renderer=null}}class Xb{constructor(e){this._renderer=e}validateRenderable(e){const t=this._getGpuText(e),i=e.styleKey;return t.currentKey!==i?!0:e._didTextUpdate}addRenderable(e,t){const i=this._getGpuText(e);if(e._didTextUpdate){const n=e._autoResolution?this._renderer.resolution:e.resolution;(i.currentKey!==e.styleKey||e.resolution!==n)&&this._updateGpuText(e),e._didTextUpdate=!1,bh(i,e)}this._renderer.renderPipes.batch.addToBatch(i,t)}updateRenderable(e){const t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){const t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new Fk(this._renderer);return t.currentKey="--",t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}Xb.extension={type:[F.WebGLPipes,F.WebGPUPipes,F.CanvasPipes],name:"text"};class Yb{constructor(e){this._activeTextures={},this._renderer=e}getTexture(e,t,i,n){typeof e=="string"&&($("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:i,resolution:t}),e.style instanceof Bt||(e.style=new Bt(e.style)),e.textureStyle instanceof Mr||(e.textureStyle=new Mr(e.textureStyle)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:s,style:o,textureStyle:a}=e,l=e.resolution??this._renderer.resolution,{frame:u,canvasAndContext:c}=Do.getCanvasAndContext({text:s,style:o,resolution:l}),h=Hb(c.canvas,u.width,u.height,l);if(a&&(h.source.style=a),o.trim&&(u.pad(o.padding),h.frame.copyFrom(u),h.frame.scale(1/l),h.updateUvs()),o.filters){const d=this._applyFilters(h,o.filters);return this.returnTexture(h),Do.returnCanvasAndContext(c),d}return this._renderer.texture.initSource(h._source),Do.returnCanvasAndContext(c),h}returnTexture(e){const t=e.source;t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",ze.returnTexture(e,!0)}renderTextToCanvas(){$("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;const i=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle});return this._activeTextures[t]={texture:i,usageCount:1},i}decreaseReferenceCount(e){const t=this._activeTextures[e];t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null)}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const i=this._renderer.renderTarget.renderTarget,n=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind(i,!1),n}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}Yb.extension={type:[F.WebGLSystem,F.WebGPUSystem,F.CanvasSystem],name:"canvasText"};const Mk=["align","breakWords","cssOverrides","fontVariant","fontWeight","leading","letterSpacing","lineHeight","padding","textBaseline","trim","whiteSpace","wordWrap","wordWrapWidth","fontFamily","fontStyle","fontSize"];function vV(r){const e=[];let t=0;for(let i=0;i<Mk.length;i++){const n=`_${Mk[i]}`;e[t++]=r[n]}return t=Dk(r._fill,e,t),t=yV(r._stroke,e,t),t=bV(r.dropShadow,e,t),t=xV(r.filters,e,t),e.join("-")}function xV(r,e,t){if(!r)return t;for(const i of r)e[t++]=i.uid;return t}function Dk(r,e,t){return r&&(e[t++]=r.color,e[t++]=r.alpha,e[t++]=r.fill?.styleKey),t}function yV(r,e,t){return r&&(t=Dk(r,e,t),e[t++]=r.width,e[t++]=r.alignment,e[t++]=r.cap,e[t++]=r.join,e[t++]=r.miterLimit),t}function bV(r,e,t){return r&&(e[t++]=r.alpha,e[t++]=r.angle,e[t++]=r.blur,e[t++]=r.distance,e[t++]=ye.shared.setValue(r.color).toNumber()),t}async function _V(r,e,t=200){const i=await e.extract.base64(r);await e.encoder.commandFinished;const n=t;console.log(`logging texture ${r.source.width}px ${r.source.height}px`);const s=["font-size: 1px;",`padding: ${n}px 300px;`,`background: url(${i}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",s)}const wV=["#000080","#228B22","#8B0000","#4169E1","#008080","#800000","#9400D3","#FF8C00","#556B2F","#8B008B"];let SV=0;function Ok(r,e=0,t={color:"#000000"}){r.renderGroup&&(t.color=wV[SV++]);let i="";for(let o=0;o<e;o++)i+=" ";let n=r.label;!n&&r instanceof $e&&(n=`sprite:${r.texture.label}`);let s=`%c ${i}|- ${n} (worldX:${r.worldTransform.tx}, relativeRenderX:${r.relativeGroupTransform.tx}, renderX:${r.groupTransform.tx}, localX:${r.x})`;r.renderGroup&&(s+=" (RenderGroup)"),r.filters&&(s+="(*filters)"),console.log(s,`color:${t.color}; font-weight:bold;`),e++;for(let o=0;o<r.children.length;o++){const a=r.children[o];Ok(a,e,{...t})}}function Uk(r,e=0,t={index:0,color:"#000000"}){let i="";for(let s=0;s<e;s++)i+=" ";const n=`%c ${i}- ${t.index}: ${r.root.label} worldX:${r.worldTransform.tx}`;console.log(n,`color:${t.color}; font-weight:bold;`),e++;for(let s=0;s<r.renderGroupChildren.length;s++){const o=r.renderGroupChildren[s];Uk(o,e,{...t,index:s})}}xe.add(W3,V3);const TV=Object.freeze(Object.defineProperty({__proto__:null,AbstractBitmapFont:Vx,AbstractRenderer:tl,AbstractSplitText:Vb,AbstractText:Jc,AccessibilitySystem:oC,AlphaFilter:TP,AlphaMask:hx,AlphaMaskPipe:c2,AnimatedSprite:Al,Application:bc,ApplicationInitHook:Nx,Assets:ys,AssetsClass:KE,BLEND_TO_NPM:mA,BUFFER_TYPE:El,BackgroundLoader:CE,BackgroundSystem:nB,Batch:xA,BatchGeometry:TA,BatchTextureArray:vA,BatchableGraphics:Mc,BatchableHTMLText:bk,BatchableMesh:xh,BatchableSprite:Pl,BatchableText:Fk,Batcher:wA,BatcherPipe:u2,BigPool:It,BindGroup:Bi,BindGroupSystem:lb,BitmapFont:Sy,BitmapFontManager:Po,BitmapText:i2,BitmapTextGraphics:vk,BitmapTextPipe:Nb,BlendModeFilter:_t,BlendModePipe:Q2,BlurFilter:Fn,BlurFilterPass:Fo,Bounds:Dt,BrowserAdapter:FT,Buffer:yr,BufferImageSource:Ku,BufferResource:oh,BufferUsage:Ne,CLEAR:xr,Cache:Ze,CanvasObserver:yx,CanvasPool:ki,CanvasPoolClass:yE,CanvasSource:Pi,CanvasTextGenerator:Do,CanvasTextMetrics:Ht,CanvasTextPipe:Xb,CanvasTextSystem:Yb,Circle:al,Color:ye,ColorBlend:IC,ColorBurnBlend:BC,ColorDodgeBlend:kC,ColorMask:dx,ColorMaskPipe:h2,ColorMatrixFilter:Zc,CompressedSource:vl,Container:Ie,Culler:hP,CullerPlugin:dP,CustomRenderPipe:W2,D3D10_RESOURCE_DIMENSION:zy,D3DFMT:br,DATA_URI:_7,DDS:Ae,DEG_TO_RAD:as,DEPRECATED_SCALE_MODES:mh,DEPRECATED_WRAP_MODES:ph,DOMAdapter:Pe,DOMContainer:E9,DOMPipe:Hy,DRAW_MODES:NW,DXGI_FORMAT:Uy,DXGI_TO_TEXTURE_FORMAT:_r,DarkenBlend:RC,DefaultBatcher:Rc,DefaultShader:iy,DifferenceBlend:FC,DisplacementFilter:G9,DivideBlend:MC,DynamicBitmapFont:wy,Ellipse:_c,EventBoundary:bP,EventEmitter:mr,EventSystem:Xy,EventsTicker:Ri,ExclusionBlend:DC,ExtensionType:F,ExtractSystem:sB,FOURCC_TO_TEXTURE_FORMAT:Ly,FederatedContainer:_P,FederatedEvent:po,FederatedMouseEvent:Sl,FederatedPointerEvent:ei,FederatedWheelEvent:_s,FillGradient:zr,FillPattern:ol,Filter:fe,FilterEffect:Ha,FilterPipe:Jy,FilterSystem:t2,FontStylePromiseCache:_h,GAUSSIAN_VALUES:qy,GL_FORMATS:nh,GL_INTERNAL_FORMAT:iP,GL_TARGETS:g2,GL_TYPES:je,GL_WRAP_MODES:gI,GenerateTextureSystem:$2,Geometry:gs,GlBackBufferSystem:yI,GlBatchAdaptor:o2,GlBuffer:pI,GlBufferSystem:f2,GlColorMaskSystem:y2,GlContextSystem:mI,GlEncoderSystem:b2,GlGeometrySystem:v2,GlGraphicsAdaptor:G2,GlLimitsSystem:_2,GlMeshAdaptor:H2,GlParticleContainerAdaptor:VB,GlParticleContainerPipe:kb,GlProgram:le,GlProgramData:BI,GlRenderTarget:bI,GlRenderTargetAdaptor:CI,GlRenderTargetSystem:B2,GlShaderSystem:D2,GlStateSystem:VI,GlStencilSystem:w2,GlTexture:XI,GlTextureSystem:N2,GlUboSystem:E2,GlUniformGroupSystem:O2,GlobalResourceRegistry:fs,GlobalUniformSystem:eb,GpuBatchAdaptor:a2,GpuBlendModesToPixi:nr,GpuBufferSystem:ub,GpuColorMaskSystem:cb,GpuDeviceSystem:fh,GpuEncoderSystem:hb,GpuGraphicsAdaptor:Sb,GpuGraphicsContext:JA,GpuLimitsSystem:db,GpuMeshAdapter:Tb,GpuMipmapGenerator:CB,GpuParticleContainerAdaptor:XB,GpuParticleContainerPipe:Rb,GpuProgram:me,GpuRenderTarget:bB,GpuRenderTargetAdaptor:_B,GpuRenderTargetSystem:vb,GpuShaderSystem:xb,GpuStateSystem:yb,GpuStencilModesToPixi:Qi,GpuStencilSystem:fb,GpuTextureSystem:wb,GpuUboSystem:pb,GpuUniformBatchPipe:mb,Graphics:Je,GraphicsContext:ir,GraphicsContextRenderData:$A,GraphicsContextSystem:Dc,GraphicsGpuData:kB,GraphicsPath:ci,GraphicsPipe:Cb,HTMLText:lI,HTMLTextPipe:Gb,HTMLTextRenderData:n2,HTMLTextStyle:th,HTMLTextSystem:Wb,HardLightBlend:OC,HardMixBlend:UC,HelloSystem:dh,IGLUniformData:sW,ImageSource:Zr,InstructionSet:lx,KTX:St,LightenBlend:zC,LinearBurnBlend:LC,LinearDodgeBlend:NC,LinearLightBlend:GC,Loader:DE,LoaderParserPriority:Dr,LuminosityBlend:HC,MaskEffectManager:Zu,MaskEffectManagerClass:yT,MaskFilter:HP,Matrix:ae,Mesh:Mo,MeshGeometry:Mn,MeshGpuData:Ab,MeshPipe:Eb,MeshPlane:nV,MeshRope:sV,MeshSimple:oV,NOOP:Kv,NegationBlend:WC,NineSliceGeometry:Un,NineSlicePlane:dV,NineSliceSprite:rk,NineSliceSpriteGpuData:ik,NineSliceSpritePipe:Mb,NoiseFilter:H9,ObservablePoint:at,OverlayBlend:VC,PI_2:Y3,Particle:uV,ParticleBuffer:jB,ParticleContainer:hV,ParticleContainerPipe:Bb,ParticleShader:ZB,PassthroughFilter:UP,PerspectiveMesh:iV,PerspectivePlaneGeometry:LB,PinLightBlend:XC,PipelineSystem:gb,PlaneGeometry:gh,Point:ve,Polygon:yo,Pool:pT,PoolGroupClass:mT,PrepareBase:VP,PrepareQueue:$P,PrepareSystem:cI,PrepareUpload:uI,QuadGeometry:ak,RAD_TO_DEG:q3,Rectangle:he,RenderContainer:YW,RenderGroup:ec,RenderGroupPipe:V2,RenderGroupSystem:q2,RenderLayer:ZW,RenderTarget:sh,RenderTargetSystem:I2,RenderTexture:Ot,RenderableGCSystem:cB,RendererInitHook:Gx,RendererType:vr,ResizePlugin:Hx,Resolver:In,RopeGeometry:HB,RoundedRectangle:Sc,SCALE_MODES:HW,STENCIL_MODES:wt,SVGParser:dE,SaturationBlend:YC,SchedulerSystem:tb,ScissorMask:eW,SdfShader:gk,Shader:Or,ShaderStage:vo,ShapePath:oE,SharedRenderPipes:ab,SharedSystems:ob,SoftLightBlend:qC,SplitBitmapText:kl,SplitText:gV,Sprite:$e,SpritePipe:j2,Spritesheet:xx,State:Ur,StencilMask:fx,StencilMaskPipe:d2,SubtractBlend:jC,SystemRunner:Lx,TEXTURE_FORMAT_BLOCK_SIZE:tP,Text:eh,TextStyle:Bt,Texture:Q,TextureGCSystem:hB,TextureMatrix:Zv,TexturePool:ze,TexturePoolClass:kT,TextureSource:dt,TextureStyle:Mr,TextureUvs:WW,Ticker:Ft,TickerListener:ac,TickerPlugin:Wx,TilingSprite:jP,TilingSpriteGpuData:hk,TilingSpritePipe:Ub,TilingSpriteShader:ok,Transform:YP,Triangle:e2,UNIFORM_TO_ARRAY_SETTERS:NI,UNIFORM_TO_SINGLE_SETTERS:LI,UNIFORM_TYPES_MAP:_C,UNIFORM_TYPES_VALUES:Ax,UPDATE_BLEND:nc,UPDATE_COLOR:Xa,UPDATE_PRIORITY:Ii,UPDATE_TRANSFORM:zG,UPDATE_VISIBLE:ho,UboBatch:gB,UboSystem:S2,UniformGroup:nt,VERSION:nl,VideoSource:fo,ViewContainer:Ei,ViewSystem:sb,ViewableBuffer:ms,VividLightBlend:KC,WGSL_ALIGN_SIZE_DATA:Bl,WGSL_TO_STD40_SIZE:T2,WRAP_MODES:GW,WebGLRenderer:mB,WebGPURenderer:IB,WebWorkerAdapter:F9,WorkerManager:Iy,accessibilityTarget:aC,addBits:Qx,addMaskBounds:sc,addMaskLocalBounds:oc,addProgramDefines:cC,alphaFrag:wP,alphaWgsl:Yy,appendSVGPath:yy,applyMatrix:uk,applyProjectiveTransformationToPlane:MB,applyStyleParams:L2,assignWithIgnore:tc,autoDetectEnvironment:i7,autoDetectRenderer:sA,autoDetectSource:GG,basisTranscoderUrls:Xc,bgr2rgb:co,bitmapFontCachePlugin:SE,bitmapFontTextParser:Lc,bitmapFontXMLParser:Ty,bitmapFontXMLStringParser:Cy,bitmapTextSplit:yk,blendTemplateFrag:CC,blendTemplateVert:AC,blendTemplateWgsl:EC,blockDataMap:bb,blurTemplateWgsl:PP,boundsPool:Ai,browserExt:W3,buildAdaptiveBezier:cy,buildAdaptiveQuadratic:eE,buildArc:fy,buildArcTo:tE,buildArcToSvg:iE,buildCircle:Ao,buildContextBatches:QA,buildEllipse:NA,buildGeometryFromPath:QW,buildLine:VA,buildPixelLine:XA,buildPolygon:YA,buildRectangle:qA,buildRoundedRectangle:GA,buildSimpleUvs:sy,buildTriangle:jA,buildUvs:ny,cacheAsTextureMixin:gT,cacheTextureArray:AE,calculatePathArea:hE,calculateProjection:AI,canvasTextSplit:kk,checkChildrenDidChange:ax,checkDataUrl:xs,checkExtension:$r,checkForNestedPattern:uE,checkMaxIfStatementsInShader:jx,childrenHelperMixin:vT,cleanArray:uB,cleanHash:lB,clearList:hh,closePointEps:oy,collectAllRenderables:qW,collectRenderablesMixin:xT,color32BitToUniform:zo,colorBit:Ec,colorBitGl:Pc,colorMatrixFilterFrag:kP,colorMatrixFilterWgsl:jy,colorToUniform:CW,compareModeToGlCompare:QI,compileHighShader:PA,compileHighShaderGl:IA,compileHighShaderGlProgram:So,compileHighShaderGpuProgram:wo,compileHooks:Zx,compileInputs:Jx,compileOutputs:EA,compileShader:k2,compute2DProjection:zB,convertFormatIfRequired:g9,convertToList:Jr,copySearchParams:uc,createIdFromString:go,createIndicesForQuads:Pb,createLevelBuffers:ZH,createLevelBuffersFromKTX:v9,createStringVariations:LT,createTexture:Rn,createUboElementsSTD40:_I,createUboElementsWGSL:vB,createUboSyncFunction:C2,createUboSyncFunctionSTD40:TI,createUboSyncFunctionWGSL:yB,crossOrigin:VE,cullingMixin:dT,curveEps:ay,defaultFilterVert:Cl,defaultValue:F2,definedProps:ai,deprecation:$,detectAvif:EE,detectBasis:YH,detectCompressed:T9,detectDefaults:IE,detectMp4:BE,detectOgv:kE,detectVideoAlphaMode:mx,detectWebm:RE,detectWebp:FE,determineCrossOrigin:YE,displacementFrag:RP,displacementVert:FP,displacementWgsl:Ky,earcut:rA,effectsMixin:bT,ensureAttributes:m2,ensureIsBuffer:Kx,ensurePrecision:hC,ensureTextOptions:$c,executeInstructions:ch,extensions:xe,extractAttributesFromGlProgram:FI,extractAttributesFromGpuProgram:vC,extractFontFamilies:wk,extractStructAndGroups:fc,extractSubpaths:cE,extractSvgUrlId:gy,fastCopy:Cc,findMixin:_T,fontStringFromTextStyle:sl,formatShader:Z9,fragmentGPUTemplate:FA,fragmentGlTemplate:DA,generateArraySyncSTD40:SI,generateArraySyncWGSL:xB,generateBlurFragSource:CP,generateBlurGlProgram:EP,generateBlurProgram:IP,generateBlurVertSource:AP,generateGPULayout:K9,generateGpuLayoutGroups:xC,generateLayout:Q9,generateLayoutHash:yC,generateParticleUpdateFunction:YB,generateProgram:zI,generateShaderSyncCode:II,generateTextStyleKey:vV,generateTextureBatchBit:Ic,generateTextureBatchBitGl:Bc,generateTextureMatrix:KA,generateUniformsSync:GI,getAdjustedBlendModeBlend:bo,getAttributeInfoFromFormat:qi,getBatchSamplersUniformGroup:kc,getBitmapTextLayout:Uc,getCanvasBoundingBox:ZP,getCanvasFillStyle:ml,getCanvasTexture:P2,getDefaultUniformValue:wC,getFastGlobalBounds:XW,getFastGlobalBoundsMixin:wT,getFillInstructionData:hH,getFontCss:Ck,getFontFamilyName:zE,getGeometryBounds:SA,getGlTypeFromFormat:xI,getGlobalBounds:Wa,getGlobalMixin:CT,getGlobalRenderableBounds:LP,getLocalBounds:$u,getMaxFragmentPrecision:uC,getMaxTexturesPerBatch:gA,getOrientationOfPoints:HA,getPo2TextureFromSource:Hb,getResolutionOfUrl:Nc,getSVGUrl:Ak,getSupportedCompressedTextureFormats:Oy,getSupportedGPUCompressedTextureFormats:Dy,getSupportedGlCompressedTextureFormats:My,getSupportedTextureFormats:xl,getTemporaryCanvasFromImage:Ek,getTestContext:Tx,getTextureBatchBindGroup:Tc,getTextureDefaultMatrix:aV,getTextureFormatFromKTXTexture:b9,getUboData:MI,getUniformData:DI,getUrlExtension:NT,glFormatToGPUFormat:uP,glUploadBufferImageResource:YI,glUploadCompressedTextureResource:qI,glUploadImageResource:U2,glUploadVideoResource:jI,globalUniformsBit:OA,globalUniformsBitGl:UA,globalUniformsUBOBitGl:G7,gpuFormatToBasisTranscoderFormat:$H,gpuFormatToKTXBasisTranscoderFormat:w9,gpuUploadBufferImageResource:wB,gpuUploadCompressedTextureResource:SB,gpuUploadImageResource:_b,gpuUploadVideoResource:TB,groupD8:Be,hasCachedCanvasTexture:nW,hslWgsl:X9,hslgl:pc,hslgpu:mc,injectBits:$x,insertVersion:dC,isMobile:rC,isPow2:Qv,isRenderingToScreen:EI,isSafari:_k,isSingleItem:qa,isWebGLSupported:rl,isWebGPUSupported:il,ktxTranscoderUrls:Yc,loadBasis:QH,loadBasisOnWorker:eP,loadBitmapFont:TE,loadDDS:o9,loadEnvironmentExtensions:Dx,loadFontAsBase64:Sk,loadFontCSS:Tk,loadImageBitmap:WE,loadJson:OE,loadKTX:h9,loadKTX2:m9,loadKTX2onWorker:aP,loadSVGImage:Pk,loadSvg:NE,loadTextures:By,loadTxt:UE,loadVideoTextures:qE,loadWebFont:LE,localUniformBit:Oo,localUniformBitGl:ih,localUniformBitGroup2:hI,localUniformMSDFBit:dk,localUniformMSDFBitGl:fk,log2:SG,logDebugTexture:_V,logProgramError:UI,logRenderGroupScene:Uk,logScene:Ok,mSDFBit:pk,mSDFBitGl:mk,mapFormatToGlFormat:ZI,mapFormatToGlInternalFormat:JI,mapFormatToGlType:$I,mapGlToVertexFormat:RI,mapSize:uW,mapType:M2,mapWebGLBlendModesToPixi:HI,maskFrag:NP,maskVert:GP,maskWgsl:r2,matrixPool:Zt,measureHtmlText:s2,measureMixin:ET,migrateFragmentFromV7toV8:aW,mipmapScaleModeToGlFilter:KI,multiplyColors:Va,multiplyHexColors:ox,nextPow2:ds,noiseFrag:MP,noiseWgsl:Qy,nonCompressedFormats:ZE,normalizeExtensionPriority:La,onRenderMixin:PT,parseDDS:rP,parseFunctionBody:VW,parseKTX:nP,parseSVGDefinitions:aE,parseSVGFloatAttribute:vt,parseSVGPath:fA,parseSVGStyle:xy,particleData:Fb,particlesFrag:KB,particlesVert:QB,particlesWgsl:Ib,passthroughFrag:OP,passthroughWgsl:Zy,path:gr,pointInTriangle:$y,preloadVideo:XE,removeItems:sx,removeStructAndGroupDuplicates:bC,resetUids:wG,resolveCharacters:wE,resolveCompressedTextureUrl:S9,resolveJsonUrl:jE,resolveTextureUrl:Fy,resourceToTexture:OT,roundPixelsBit:To,roundPixelsBitGl:Co,roundedShapeArc:nE,roundedShapeQuadraticCurve:sE,sayHello:aB,scaleModeToGlFilter:z2,setBasisTranscoderPath:jH,setKTXTranscoderPath:f9,setPositions:lk,setProgramName:fC,setUvs:ck,shapeBuilders:Eo,sortMixin:IT,spritesheetAsset:WT,squaredDistanceToLineSegment:ll,stripVersion:pC,styleAttributes:vy,testImageFormat:Ay,testVideoFormat:gl,textStyleToCSS:eI,textureBit:dI,textureBitGl:fI,textureFrom:UT,tilingBit:nk,tilingBitGl:sk,toFillStyle:kn,toLocalGlobalMixin:BT,toStrokeStyle:pl,transformVertices:Fc,triangulateWithHoles:ly,uboSyncFunctionsSTD40:A2,uboSyncFunctionsWGSL:wI,uid:it,uniformParsers:Dn,unpremultiplyAlpha:vW,unsafeEvalSupported:Ox,updateLocalTransform:jW,updateQuadBounds:Jv,updateRenderGroupTransform:tB,updateRenderGroupTransforms:X2,updateTextBounds:bh,updateTransformAndChildren:Y2,updateTransformBackwards:Ju,updateWorldTransform:KW,v8_0_0:Ce,v8_3_4:Q3,validFormats:qc,validateRenderables:iB,vertexGPUTemplate:RA,vertexGlTemplate:MA,vkFormatToGPUFormat:cP,warn:de,webworkerExt:V3,wrapModeToGlAddress:uh},Symbol.toStringTag,{value:"Module"}));Lv.registerPlugin(Wv),Wv.registerPIXI(TV);class Tt{id;type;options;params;timeline=null;lastTarget=null;constructor(e,t,i="gsap"){this.id=t.id||`gsap_${Math.random().toString(36).substr(2,9)}`,this.type=i,this.params=e,this.options={duration:t.duration,delay:t.delay??0,easing:t.easing??"none",iterCount:t.iterCount??1,id:this.id,disableGlobalEasing:t.disableGlobalEasing??!1}}getTransform(e){return{}}getTargetCount(e){if(!e)return 0;const{type:t}=this.params;if(t==="character"){const i=(n,s=!1)=>{if(!n.children||n.children.length===0)return s?0:1;let o=0;for(const a of n.children)o+=i(a);return o};return i(e,!0)}else if(t==="word")return e.children?e.children.length:0;return 1}apply(e,t){const{duration:i,delay:n}=this.options,s=t-n;let o=this.lastTarget!==e||!this.timeline;const a=this.getCurrentTargets(e);if(!o&&this.timeline){const c=this.timeline.getChildren();if(c.length===0)e&&e.children&&e.children.length>0&&(o=!0);else{const h=c[0],d=typeof h.targets=="function"?h.targets():[],f=this.getTargetCount(e);if(d.length!==f)o=!0;else if(d&&d.length>0&&a.length>0)if(d[0]===e&&e.children&&e.children.length>0)o=!0;else for(let p=0;p<d.length;p++){const m=d[p];if(m.destroyed||!m.parent){o=!0;break}if(p<a.length&&m!==a[p]){o=!0;break}}else e&&e.children&&e.children.length>0&&(o=!0)}}if(o&&(this.initTimeline(e),this.lastTarget=e),!this.timeline)return;if(s<0){this.timeline.pause(0);return}const l=this.options.iterCount===1/0?i:i/this.options.iterCount;if(this.options.iterCount!==1/0&&s>=i){this.timeline.progress(1);return}const u=s%l/l;this.timeline.progress(u)}getCurrentTargets(e){if(!e||!e.children)return[e];const{type:t}=this.params;if(t==="character"){const i=(n,s=!1)=>{if(!n.children||n.children.length===0)return s?[]:[n];let o=[];for(const a of n.children)o=o.concat(i(a));return o};return i(e,!0)}else if(t==="word")return[...e.children||[]];return[e]}initTimeline(e){const{from:t,to:i,stagger:n,type:s}=this.params,o=this.options.duration/1e6;let a=[];if(e&&e.children)if(s==="character"){const f=(p,m=!1)=>{if(!p.children||p.children.length===0)return m?[]:[p];let g=[];for(const v of p.children)g=g.concat(f(v));return g};a=f(e,!0)}else s==="word"?a=e.children||[]:a=[e];else a=[e];if((s==="character"||s==="word")&&a.length===0){this.timeline&&(this.timeline.kill(),this.timeline=null);return}this.timeline&&this.timeline.kill(),this.timeline=Lv.timeline({paused:!0}),a.forEach(f=>{if(f.anchor){if(f.anchor.x!==.5||f.anchor.y!==.5){const p=f.anchor.x,m=f.anchor.y;f.anchor.set(.5,.5);const g=f.width/(f.scale?.x||1),v=f.height/(f.scale?.y||1);f.x+=(.5-p)*g*(f.scale?.x||1),f.y+=(.5-m)*v*(f.scale?.y||1)}}else if(f.pivot&&f.getLocalBounds){const p=f.getLocalBounds(),m=p.x+p.width/2,g=p.y+p.height/2;if(f.pivot.x!==m||f.pivot.y!==g){const v=f.pivot.x,x=f.pivot.y;f.pivot.set(m,g),f.x+=(m-v)*(f.scale?.x||1),f.y+=(g-x)*(f.scale?.y||1)}}});const l=["scale","scaleX","scaleY","rotation","skewX","skewY","skew","pivotX","pivotY","pivot","anchorX","anchorY","anchor","blur","brightness","contrast","grayscale","hueRotate","invert","saturate","threshold","matrix"],u=f=>f&&Object.keys(f).some(p=>l.includes(p)),c=f=>{if(!u(f))return f;const p={...f},m={};return l.forEach(g=>{g in p&&(m[g]=p[g],delete p[g])}),p.pixi=m,p},h=c(t),d=c(i);this.timeline.fromTo(a,h,{duration:o,stagger:n||0,ease:this.options.easing,...d})}destroy(){this.timeline&&(this.timeline.kill(),this.timeline=null)}}function L(r){return r&&r.presetParams?{...r.presetParams,...r}:r}const CV=(r,e)=>{const t=L(e),i=Math.max(r.duration/1e6,1),n=t?.easing||r.easing||"easeOutQuad",s=X("pulse",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,iterCount:i*3,easing:n},"pulse"):new B(s,{...r,easing:n,iterCount:i*3},"pulse")},AV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("fadeIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fadeIn"):new B(n,{...r,easing:i},"fadeIn")},EV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInQuad",n=X("fadeOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fadeOut"):new B(n,{...r,easing:i},"fadeOut")},PV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutCubic",n=X("slideIn",e);if(t&&(t["0%"]||t["100%"]))return new B(t,{...r,easing:i},"slideIn");const s=new B(n,{...r,easing:i},"slideIn");return s.presetParams=e,s},IV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInCubic",n=X("slideOut",e);if(t&&(t["0%"]||t["100%"]))return new B(t,{...r,easing:i},"slideOut");const s=new B(n,{...r,easing:i},"slideOut");return s.presetParams=e,s},BV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutBack",n=X("zoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomIn"):new B(n,{...r,easing:i},"zoomIn")},kV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInBack",n=X("zoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomOut"):new B(n,{...r,easing:i},"zoomOut")},RV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("blurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurIn"):new B(n,{...r,easing:i},"blurIn")},FV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInQuad",n=X("blurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurOut"):new B(n,{...r,easing:i},"blurOut")},MV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("motionBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"motionBlurIn"):new B(n,{...r,easing:i},"motionBlurIn")},DV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInQuad",n=X("motionBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"motionBlurOut"):new B(n,{...r,easing:i},"motionBlurOut")},OV=(r,e)=>{const t=L(e);return new Tt({type:"character",from:{alpha:0,scale:.5},to:{alpha:1,scale:1},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"back.out"},"charFadeIn")},UV=(r,e)=>{const t=L(e);return new Tt({type:"character",from:{alpha:0,y:"+=50"},to:{alpha:1,y:"-=50"},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"power2.out"},"charSlideUp")},zV=(r,e)=>{const t=L(e);return new Tt({type:"character",from:{alpha:0},to:{alpha:1,duration:.001},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"none"},"charTypewriter")},LV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0},to:{alpha:1},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"none"},"fadeByWord")},NV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,x:"+=50"},to:{alpha:1,x:"-=50"},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"none"},"slideFadeByWord")},GV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{scale:0,immediateRender:!0},to:{keyframes:{"0%":{scale:0},"50%":{scale:1.2},"100%":{scale:1}},ease:"none"},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"none"},"popByWord")},HV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,scale:.7},to:{alpha:1,scale:1},stagger:t?.stagger??.08},{...r,easing:t?.easing||r.easing||"back.out(1.5)"},"scaleFadeByWord")},WV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,y:"-=30",scale:.8},to:{alpha:1,y:"+=30",scale:1},stagger:t?.stagger??.1},{...r,easing:t?.easing||r.easing||"bounce.out"},"bounceByWord")},VV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,rotation:-10},to:{alpha:1,rotation:0},stagger:t?.stagger??.08},{...r,easing:t?.easing||r.easing||"power2.out"},"rotateInByWord")},XV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,x:"-=50"},to:{alpha:1,x:"+=50"},stagger:t?.stagger??.1},{...r,easing:t?.easing||r.easing||"power2.out"},"slideRightByWord")},YV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,x:"+=50"},to:{alpha:1,x:"-=50"},stagger:t?.stagger??.1},{...r,easing:t?.easing||r.easing||"power2.out"},"slideLeftByWord")},qV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,rotation:90},to:{alpha:1,rotation:0},stagger:t?.stagger??.1},{...r,easing:t?.easing||r.easing||"power2.out"},"fadeRotateByWord")},jV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,skewX:45},to:{alpha:1,skewX:0},stagger:t?.stagger??.08},{...r,easing:t?.easing||r.easing||"power3.out"},"skewByWord")},KV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,y:"+=20"},to:{alpha:1,y:"-=20",repeat:1,yoyo:!0},stagger:t?.stagger??.12},{...r,easing:t?.easing||r.easing||"sine.inOut"},"waveByWord")},QV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,blur:10},to:{alpha:1,blur:0},stagger:t?.stagger??.08},{...r,easing:t?.easing||r.easing||"power2.out"},"blurInByWord")},ZV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,y:"-=60",scaleY:2},to:{alpha:1,y:"+=60",scaleY:1},stagger:t?.stagger??.09},{...r,easing:t?.easing||r.easing||"power3.out"},"dropSoftByWord")},JV=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,scale:0},to:{alpha:1,scale:1},stagger:t?.stagger??.07},{...r,easing:t?.easing||r.easing||"elastic.out(1, 0.5)"},"elasticPopByWord")},$V=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,skewX:-20},to:{alpha:1,skewX:0},stagger:t?.stagger??.1},{...r,easing:t?.easing||r.easing||"power2.out"},"flipUpByWord")},eX=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,rotation:-180,scale:.5},to:{alpha:1,rotation:0,scale:1},stagger:t?.stagger??.09},{...r,easing:t?.easing||r.easing||"power3.out"},"spinInByWord")},tX=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,scaleX:1.5,scaleY:.5},to:{alpha:1,scaleX:1,scaleY:1},stagger:t?.stagger??.08},{...r,easing:t?.easing||r.easing||"power2.out"},"stretchInByWord")},rX=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,scale:1.4},to:{alpha:1,scale:1},stagger:t?.stagger??.1},{...r,easing:t?.easing||r.easing||"power4.out"},"revealZoomByWord")},iX=(r,e)=>{const t=L(e);return new Tt({type:"word",from:{alpha:0,y:"+=25"},to:{alpha:1,y:"-=25"},stagger:t?.stagger??.15},{...r,easing:t?.easing||r.easing||"sine.out"},"floatWaveByWord")},nX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("blurSlideRightIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideRightIn"):new B(n,{...r,easing:i},"blurSlideRightIn")},sX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("wobbleZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"wobbleZoomIn"):new B(n,{...r,easing:i},"wobbleZoomIn")},oX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("spinZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spinZoomIn"):new B(n,{...r,easing:i},"spinZoomIn")},aX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("blurSlideLeftIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideLeftIn"):new B(n,{...r,easing:i},"blurSlideLeftIn")},lX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("blurSlideRightStrongIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideRightStrongIn"):new B(n,{...r,easing:i},"blurSlideRightStrongIn")},uX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("cinematicZoomSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"cinematicZoomSlideIn"):new B(n,{...r,easing:i},"cinematicZoomSlideIn")},cX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("elasticTwistIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"elasticTwistIn"):new B(n,{...r,easing:i},"elasticTwistIn")},hX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("spinFadeIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spinFadeIn"):new B(n,{...r,easing:i},"spinFadeIn")},dX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("flashZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"flashZoomIn"):new B(n,{...r,easing:i},"flashZoomIn")},fX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("tiltSlideRightIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltSlideRightIn"):new B(n,{...r,easing:i},"tiltSlideRightIn")},pX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("tiltZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltZoomIn"):new B(n,{...r,easing:i},"tiltZoomIn")},mX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("glitchSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"glitchSlideIn"):new B(n,{...r,easing:i},"glitchSlideIn")},gX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("dropBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dropBlurIn"):new B(n,{...r,easing:i},"dropBlurIn")},vX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("fallZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fallZoomIn"):new B(n,{...r,easing:i},"fallZoomIn")},xX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("zoomSpinIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomSpinIn"):new B(n,{...r,easing:i},"zoomSpinIn")},yX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("dramaticSpinSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dramaticSpinSlideIn"):new B(n,{...r,easing:i},"dramaticSpinSlideIn")},bX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("tiltSlideRightOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltSlideRightOut"):new B(n,{...r,easing:i},"tiltSlideRightOut")},_X=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("tiltZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltZoomOut"):new B(n,{...r,easing:i},"tiltZoomOut")},wX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("glitchSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"glitchSlideOut"):new B(n,{...r,easing:i},"glitchSlideOut")},SX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("dropBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dropBlurOut"):new B(n,{...r,easing:i},"dropBlurOut")},TX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("fallZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fallZoomOut"):new B(n,{...r,easing:i},"fallZoomOut")},CX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("zoomSpinOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomSpinOut"):new B(n,{...r,easing:i},"zoomSpinOut")},AX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("dramaticSpinSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dramaticSpinSlideOut"):new B(n,{...r,easing:i},"dramaticSpinSlideOut")},EX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("blurSlideRightOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideRightOut"):new B(n,{...r,easing:i},"blurSlideRightOut")},PX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("wobbleZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"wobbleZoomOut"):new B(n,{...r,easing:i},"wobbleZoomOut")},IX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("spinZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spinZoomOut"):new B(n,{...r,easing:i},"spinZoomOut")},BX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("blurSlideLeftOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideLeftOut"):new B(n,{...r,easing:i},"blurSlideLeftOut")},kX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("blurSlideRightStrongOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideRightStrongOut"):new B(n,{...r,easing:i},"blurSlideRightStrongOut")},RX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("cinematicZoomSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"cinematicZoomSlideOut"):new B(n,{...r,easing:i},"cinematicZoomSlideOut")},FX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("elasticTwistOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"elasticTwistOut"):new B(n,{...r,easing:i},"elasticTwistOut")},MX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("spinFadeOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spinFadeOut"):new B(n,{...r,easing:i},"spinFadeOut")},DX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("flashZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"flashZoomOut"):new B(n,{...r,easing:i},"flashZoomOut")},OX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideRotateIn"):new B(n,{...r,easing:i},"slideRotateIn")},UX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideRotateOut"):new B(n,{...r,easing:i},"slideRotateOut")},zX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideBlurIn"):new B(n,{...r,easing:i},"slideBlurIn")},LX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideBlurOut"):new B(n,{...r,easing:i},"slideBlurOut")},NX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("zoomRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomRotateIn"):new B(n,{...r,easing:i},"zoomRotateIn")},GX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("zoomRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomRotateOut"):new B(n,{...r,easing:i},"zoomRotateOut")},HX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("zoomBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomBlurIn"):new B(n,{...r,easing:i},"zoomBlurIn")},WX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("zoomBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomBlurOut"):new B(n,{...r,easing:i},"zoomBlurOut")},VX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideZoomIn"):new B(n,{...r,easing:i},"slideZoomIn")},XX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideZoomOut"):new B(n,{...r,easing:i},"slideZoomOut")},YX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("verticalBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"verticalBlurIn"):new B(n,{...r,easing:i},"verticalBlurIn")},qX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("verticalBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"verticalBlurOut"):new B(n,{...r,easing:i},"verticalBlurOut")},jX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("rotateBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"rotateBlurIn"):new B(n,{...r,easing:i},"rotateBlurIn")},KX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("rotateBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"rotateBlurOut"):new B(n,{...r,easing:i},"rotateBlurOut")},QX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("cinematicSlideZoomBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"cinematicSlideZoomBlurIn"):new B(n,{...r,easing:i},"cinematicSlideZoomBlurIn")},ZX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("cinematicSlideZoomBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"cinematicSlideZoomBlurOut"):new B(n,{...r,easing:i},"cinematicSlideZoomBlurOut")},JX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("brightnessZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"brightnessZoomIn"):new B(n,{...r,easing:i},"brightnessZoomIn")},$X=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("brightnessZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"brightnessZoomOut"):new B(n,{...r,easing:i},"brightnessZoomOut")},eY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("brightnessSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"brightnessSlideIn"):new B(n,{...r,easing:i},"brightnessSlideIn")},tY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("brightnessSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"brightnessSlideOut"):new B(n,{...r,easing:i},"brightnessSlideOut")},rY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("tiltZoomBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltZoomBlurIn"):new B(n,{...r,easing:i},"tiltZoomBlurIn")},iY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("tiltZoomBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltZoomBlurOut"):new B(n,{...r,easing:i},"tiltZoomBlurOut")},nY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("dropRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dropRotateIn"):new B(n,{...r,easing:i},"dropRotateIn")},sY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("dropRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dropRotateOut"):new B(n,{...r,easing:i},"dropRotateOut")},oY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("spiralIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spiralIn"):new B(n,{...r,easing:i},"spiralIn")},aY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("spiralOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spiralOut"):new B(n,{...r,easing:i},"spiralOut")},lY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("flashSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"flashSlideIn"):new B(n,{...r,easing:i},"flashSlideIn")},uY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("flashSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"flashSlideOut"):new B(n,{...r,easing:i},"flashSlideOut")},cY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("heavyCinematicIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"heavyCinematicIn"):new B(n,{...r,easing:i},"heavyCinematicIn")},hY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("heavyCinematicOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"heavyCinematicOut"):new B(n,{...r,easing:i},"heavyCinematicOut")},dY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("diagonalSlideRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"diagonalSlideRotateIn"):new B(n,{...r,easing:i},"diagonalSlideRotateIn")},fY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("diagonalSlideRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"diagonalSlideRotateOut"):new B(n,{...r,easing:i},"diagonalSlideRotateOut")},pY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("diagonalBlurZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"diagonalBlurZoomIn"):new B(n,{...r,easing:i},"diagonalBlurZoomIn")},mY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("diagonalBlurZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"diagonalBlurZoomOut"):new B(n,{...r,easing:i},"diagonalBlurZoomOut")},gY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("rotateBrightnessIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"rotateBrightnessIn"):new B(n,{...r,easing:i},"rotateBrightnessIn")},vY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("rotateBrightnessOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"rotateBrightnessOut"):new B(n,{...r,easing:i},"rotateBrightnessOut")},xY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("zoomBrightnessBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomBrightnessBlurIn"):new B(n,{...r,easing:i},"zoomBrightnessBlurIn")},yY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("zoomBrightnessBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomBrightnessBlurOut"):new B(n,{...r,easing:i},"zoomBrightnessBlurOut")},bY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideUpRotateZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideUpRotateZoomIn"):new B(n,{...r,easing:i},"slideUpRotateZoomIn")},_Y=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideUpRotateZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideUpRotateZoomOut"):new B(n,{...r,easing:i},"slideUpRotateZoomOut")},wY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("fallBlurRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fallBlurRotateIn"):new B(n,{...r,easing:i},"fallBlurRotateIn")},SY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("fallBlurRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fallBlurRotateOut"):new B(n,{...r,easing:i},"fallBlurRotateOut")},TY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("sideStretchZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"sideStretchZoomIn"):new B(n,{...r,easing:i},"sideStretchZoomIn")},CY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("sideStretchZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"sideStretchZoomOut"):new B(n,{...r,easing:i},"sideStretchZoomOut")},AY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("darkSlideBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"darkSlideBlurIn"):new B(n,{...r,easing:i},"darkSlideBlurIn")},EY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("darkSlideBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"darkSlideBlurOut"):new B(n,{...r,easing:i},"darkSlideBlurOut")},PY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("liftZoomRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"liftZoomRotateIn"):new B(n,{...r,easing:i},"liftZoomRotateIn")},IY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("liftZoomRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"liftZoomRotateOut"):new B(n,{...r,easing:i},"liftZoomRotateOut")},BY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("overexposedZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"overexposedZoomIn"):new B(n,{...r,easing:i},"overexposedZoomIn")},kY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("overexposedZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"overexposedZoomOut"):new B(n,{...r,easing:i},"overexposedZoomOut")},RY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("pushDownZoomBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"pushDownZoomBlurIn"):new B(n,{...r,easing:i},"pushDownZoomBlurIn")},FY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("pushDownZoomBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"pushDownZoomBlurOut"):new B(n,{...r,easing:i},"pushDownZoomBlurOut")},MY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("twistSlideBrightnessIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"twistSlideBrightnessIn"):new B(n,{...r,easing:i},"twistSlideBrightnessIn")},DY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("twistSlideBrightnessOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"twistSlideBrightnessOut"):new B(n,{...r,easing:i},"twistSlideBrightnessOut")},OY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("collapseRotateZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"collapseRotateZoomIn"):new B(n,{...r,easing:i},"collapseRotateZoomIn")},UY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("collapseRotateZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"collapseRotateZoomOut"):new B(n,{...r,easing:i},"collapseRotateZoomOut")},zY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("ultraCinematicIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"ultraCinematicIn"):new B(n,{...r,easing:i},"ultraCinematicIn")},LY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("ultraCinematicOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"ultraCinematicOut"):new B(n,{...r,easing:i},"ultraCinematicOut")},NY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("popCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"popCaption"):new B(n,{...r,easing:i},"popCaption")},GY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("bounceCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"bounceCaption"):new B(n,{...r,easing:i},"bounceCaption")},HY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("scaleCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"scaleCaption"):new B(n,{...r,easing:i},"scaleCaption")},WY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideLeftCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideLeftCaption"):new B(n,{...r,easing:i},"slideLeftCaption")},VY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideRightCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideRightCaption"):new B(n,{...r,easing:i},"slideRightCaption")},XY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideUpCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideUpCaption"):new B(n,{...r,easing:i},"slideUpCaption")},YY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("slideDownCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideDownCaption"):new B(n,{...r,easing:i},"slideDownCaption")},qY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("fadeCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fadeCaption"):new B(n,{...r,easing:i},"fadeCaption")},jY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("scaleMidCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"scaleMidCaption"):new B(n,{...r,easing:i},"scaleMidCaption")},KY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("scaleDownCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"scaleDownCaption"):new B(n,{...r,easing:i},"scaleDownCaption")},QY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("upDownCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i,iterCount:1/0},"upDownCaption"):new B(n,{...r,easing:i,iterCount:1/0},"upDownCaption")},ZY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=X("upLeftCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i,iterCount:1/0},"upLeftCaption"):new B(n,{...r,easing:i,iterCount:1/0},"upLeftCaption")},JY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboZoom1",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboZoom1"):new B(n,{...r,easing:i},"comboZoom1")},$Y=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboZoom2",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboZoom2"):new B(n,{...r,easing:i},"comboZoom2")},eq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboPendulum1",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboPendulum1"):new B(n,{...r,easing:i},"comboPendulum1")},tq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboPendulum2",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboPendulum2"):new B(n,{...r,easing:i},"comboPendulum2")},rq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboRightDistort",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboRightDistort"):new B(n,{...r,easing:i},"comboRightDistort")},iq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboLeftDistort",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboLeftDistort"):new B(n,{...r,easing:i},"comboLeftDistort")},nq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboWobble",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboWobble"):new B(n,{...r,easing:i},"comboWobble")},sq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboSpinningTop1",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboSpinningTop1"):new B(n,{...r,easing:i},"comboSpinningTop1")},oq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboSwayOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboSwayOut"):new B(n,{...r,easing:i},"comboSwayOut")},aq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboBounce1",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboBounce1"):new B(n,{...r,easing:i},"comboBounce1")},lq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboSwayIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboSwayIn"):new B(n,{...r,easing:i},"comboSwayIn")},uq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=X("comboSpinningTop2",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboSpinningTop2"):new B(n,{...r,easing:i},"comboSpinningTop2")};U.register("fadeIn",AV),U.register("fadeOut",EV),U.register("slideIn",PV),U.register("slideOut",IV),U.register("zoomIn",BV),U.register("zoomOut",kV),U.register("charFadeIn",OV),U.register("charSlideUp",UV),U.register("charTypewriter",zV),U.register("fadeByWord",LV),U.register("slideFadeByWord",NV),U.register("popByWord",GV),U.register("scaleFadeByWord",HV),U.register("bounceByWord",WV),U.register("rotateInByWord",VV),U.register("slideRightByWord",XV),U.register("slideLeftByWord",YV),U.register("fadeRotateByWord",qV),U.register("skewByWord",jV),U.register("waveByWord",KV),U.register("blurInByWord",QV),U.register("dropSoftByWord",ZV),U.register("elasticPopByWord",JV),U.register("flipUpByWord",$V),U.register("spinInByWord",eX),U.register("stretchInByWord",tX),U.register("revealZoomByWord",rX),U.register("floatWaveByWord",iX),U.register("pulse",CV),U.register("blurIn",RV),U.register("blurOut",FV),U.register("blurSlideRightIn",nX),U.register("wobbleZoomIn",sX),U.register("spinZoomIn",oX),U.register("blurSlideLeftIn",aX),U.register("blurSlideRightStrongIn",lX),U.register("cinematicZoomSlideIn",uX),U.register("elasticTwistIn",cX),U.register("spinFadeIn",hX),U.register("flashZoomIn",dX),U.register("tiltSlideRightIn",fX),U.register("tiltZoomIn",pX),U.register("glitchSlideIn",mX),U.register("dropBlurIn",gX),U.register("fallZoomIn",vX),U.register("zoomSpinIn",xX),U.register("dramaticSpinSlideIn",yX),U.register("tiltSlideRightOut",bX),U.register("tiltZoomOut",_X),U.register("glitchSlideOut",wX),U.register("dropBlurOut",SX),U.register("fallZoomOut",TX),U.register("zoomSpinOut",CX),U.register("dramaticSpinSlideOut",AX),U.register("blurSlideRightOut",EX),U.register("wobbleZoomOut",PX),U.register("spinZoomOut",IX),U.register("blurSlideLeftOut",BX),U.register("blurSlideRightStrongOut",kX),U.register("cinematicZoomSlideOut",RX),U.register("elasticTwistOut",FX),U.register("spinFadeOut",MX),U.register("flashZoomOut",DX),U.register("slideRotateIn",OX),U.register("slideRotateOut",UX),U.register("slideBlurIn",zX),U.register("slideBlurOut",LX),U.register("zoomRotateIn",NX),U.register("zoomRotateOut",GX),U.register("zoomBlurIn",HX),U.register("zoomBlurOut",WX),U.register("slideZoomIn",VX),U.register("slideZoomOut",XX),U.register("verticalBlurIn",YX),U.register("verticalBlurOut",qX),U.register("rotateBlurIn",jX),U.register("rotateBlurOut",KX),U.register("cinematicSlideZoomBlurIn",QX),U.register("cinematicSlideZoomBlurOut",ZX),U.register("brightnessZoomIn",JX),U.register("brightnessZoomOut",$X),U.register("brightnessSlideIn",eY),U.register("brightnessSlideOut",tY),U.register("tiltZoomBlurIn",rY),U.register("tiltZoomBlurOut",iY),U.register("dropRotateIn",nY),U.register("dropRotateOut",sY),U.register("spiralIn",oY),U.register("spiralOut",aY),U.register("flashSlideIn",lY),U.register("flashSlideOut",uY),U.register("heavyCinematicIn",cY),U.register("heavyCinematicOut",hY),U.register("diagonalSlideRotateIn",dY),U.register("diagonalSlideRotateOut",fY),U.register("diagonalBlurZoomIn",pY),U.register("diagonalBlurZoomOut",mY),U.register("rotateBrightnessIn",gY),U.register("rotateBrightnessOut",vY),U.register("zoomBrightnessBlurIn",xY),U.register("zoomBrightnessBlurOut",yY),U.register("slideUpRotateZoomIn",bY),U.register("slideUpRotateZoomOut",_Y),U.register("fallBlurRotateIn",wY),U.register("fallBlurRotateOut",SY),U.register("sideStretchZoomIn",TY),U.register("sideStretchZoomOut",CY),U.register("darkSlideBlurIn",AY),U.register("darkSlideBlurOut",EY),U.register("liftZoomRotateIn",PY),U.register("liftZoomRotateOut",IY),U.register("overexposedZoomIn",BY),U.register("overexposedZoomOut",kY),U.register("pushDownZoomBlurIn",RY),U.register("pushDownZoomBlurOut",FY),U.register("twistSlideBrightnessIn",MY),U.register("twistSlideBrightnessOut",DY),U.register("collapseRotateZoomIn",OY),U.register("collapseRotateZoomOut",UY),U.register("ultraCinematicIn",zY),U.register("ultraCinematicOut",LY),U.register("motionBlurIn",MV),U.register("motionBlurOut",DV),U.register("popCaption",NY),U.register("bounceCaption",GY),U.register("scaleCaption",HY),U.register("slideLeftCaption",WY),U.register("slideRightCaption",VY),U.register("slideUpCaption",XY),U.register("slideDownCaption",YY),U.register("fadeCaption",qY),U.register("scaleMidCaption",jY),U.register("scaleDownCaption",KY),U.register("upDownCaption",QY),U.register("upLeftCaption",ZY),U.register("comboZoom1",JY),U.register("comboZoom2",$Y),U.register("comboPendulum1",eq),U.register("comboPendulum2",tq),U.register("comboRightDistort",rq),U.register("comboLeftDistort",iq),U.register("comboWobble",nq),U.register("comboSpinningTop1",sq),U.register("comboSwayOut",oq),U.register("comboBounce1",aq),U.register("comboSwayIn",lq),U.register("comboSpinningTop2",uq);function X(r,e){const t=L(e),i=t?.mirror||0,n=t?.opacityInit||null,s=t?.opacityEnd||null,o=t?.xPositionInit||null,a=t?.xPositionEnd||null,l=t?.yPositionInit||null,u=t?.yPositionEnd||null,c=t?.angleInit||null,h=t?.angleEnd||null,d=t?.blurInit||null,f=t?.blurEnd||null,p=t?.scaleInit||null,m=t?.scaleEnd||null,g=t?.brightnessInit||null,v=t?.brightnessEnd||null,x=t?.motionBlurInit||null,y=t?.motionBlurEnd||null;switch(r){case"fadeIn":return{"0%":{opacity:n??0,scale:.9,mirror:i},"100%":{opacity:s??1,scale:1,mirror:i}};case"fadeOut":return{"0%":{opacity:n??1,mirror:i},"100%":{opacity:s??0,mirror:i}};case"zoomIn":return{"0%":{scale:p??0,opacity:n??0,mirror:i},"100%":{scale:m??1,opacity:s??1,mirror:i}};case"zoomOut":return{"0%":{scale:p??1,opacity:n??1,mirror:i},"100%":{scale:m??0,opacity:s??0,mirror:i}};case"slideIn":{const b=t?.direction||"left",T=t?.distance||300;return{"0%":{x:b==="left"?-T:b==="right"?T:o??0,y:b==="top"?-T:b==="bottom"?T:l??0,opacity:n??0,mirror:i},"100%":{x:a??0,y:u??0,opacity:s??1,mirror:i}}}case"slideOut":{const b=t?.direction||"left",T=t?.distance||300;return{"0%":{x:o??0,y:l??0,opacity:n??1,mirror:i},"100%":{x:b==="left"?-T:b==="right"?T:a??0,y:b==="top"?-T:b==="bottom"?T:u??0,opacity:s??0,mirror:i}}}case"pulse":return{"0%":{scale:p??1,mirror:i},"25%":{scale:m??.9,mirror:i},"50%":{scale:p??1,mirror:i},"75%":{scale:m??.9,mirror:i},"100%":{scale:p??1,mirror:i}};case"blurIn":return{"0%":{blur:d??20,opacity:n??0,mirror:i},"100%":{blur:f??0,opacity:s??1,mirror:i}};case"blurOut":return{"0%":{blur:d??0,opacity:n??1,mirror:i},"100%":{blur:f??20,opacity:s??0,mirror:i}};case"motionBlurIn":return{"0%":{motionBlur:x??40,opacity:n??0,mirror:i},"100%":{motionBlur:y??0,opacity:s??1,mirror:i}};case"motionBlurOut":return{"0%":{motionBlur:x??0,opacity:n??1,mirror:i},"100%":{motionBlur:y??40,opacity:s??0,mirror:i}};case"blurSlideRightIn":return{"0%":{blur:d??20,x:o??300,scale:p??.7,mirror:i},"40%":{blur:5,x:20,scale:1.05,mirror:i},"100%":{blur:f??0,x:a??0,scale:m??1,mirror:i}};case"wobbleZoomIn":return{"0%":{scale:p??1.3,angle:c??-8,mirror:i},"15%":{scale:.95,angle:4,mirror:i},"30%":{scale:1.05,angle:-2,mirror:i},"100%":{scale:m??1,angle:h??0,mirror:i}};case"spinZoomIn":return{"0%":{blur:d??15,angle:c??180,scale:p??.7,mirror:i},"60%":{blur:5,angle:-10,scale:1.1,mirror:i},"100%":{blur:f??0,angle:h??0,scale:m??1,mirror:i}};case"blurSlideLeftIn":return{"0%":{x:o??-400,blur:d??25,scale:p??.7,mirror:i},"30%":{x:a??0,blur:0,scale:m??1,mirror:i},"100%":{x:a??0,blur:0,scale:m??1,mirror:i}};case"blurSlideRightStrongIn":return{"0%":{x:o??600,blur:d??40,scale:p??.8,mirror:i},"25%":{x:-20,blur:10,scale:m??1,mirror:i},"100%":{x:0,blur:0,scale:m??1,mirror:i}};case"cinematicZoomSlideIn":return{"0%":{scale:p??1.5,blur:d??20,x:o??100,mirror:i},"40%":{scale:1.1,blur:5,x:a??0,mirror:i},"100%":{scale:m??1,blur:f??0,x:a??0,mirror:i}};case"elasticTwistIn":return{"0%":{scale:p??.7,blur:d??15,angle:c??45,mirror:i},"50%":{scale:1.2,blur:0,angle:-10,mirror:i},"75%":{scale:.95,blur:0,angle:5,mirror:i},"100%":{scale:m??1,blur:f??0,angle:h??0,mirror:i}};case"spinFadeIn":return{"0%":{blur:d??30,angle:c??90,scale:p??.7,mirror:i},"100%":{blur:f??0,angle:h??0,scale:m??1,mirror:i}};case"flashZoomIn":return{"0%":{scale:1,brightness:6,mirror:i},"15%":{scale:1.3,brightness:4,mirror:i},"30%":{scale:1,brightness:1,mirror:i},"100%":{scale:1,brightness:1,mirror:i}};case"tiltSlideRightIn":return{"0%":{angle:c??-12,x:o??-400,scale:p??1.1,mirror:i},"30%":{angle:3,x:10,scale:1,mirror:i},"100%":{angle:h??0,x:a??0,scale:m??1,mirror:i}};case"tiltZoomIn":return{"0%":{angle:c??15,scale:p??.7,mirror:i},"100%":{angle:h??0,scale:m??1,mirror:i}};case"glitchSlideIn":return{"0%":{x:o??600,angle:c??25,scale:p??.7,mirror:i},"20%":{x:50,angle:-10,scale:1.1,mirror:i},"40%":{x:-30,angle:5,scale:1.05,mirror:i},"100%":{x:a??0,angle:h??0,scale:m??1,mirror:i}};case"dropBlurIn":return{"0%":{y:l??-500,blur:d??30,scale:p??.9,mirror:i},"100%":{y:u??0,blur:f??0,scale:m??1,mirror:i}};case"fallZoomIn":return{"0%":{y:l??-400,scale:p??1.5,mirror:i},"30%":{y:20,scale:1.05,mirror:i},"100%":{y:u??0,scale:m??1,mirror:i}};case"zoomSpinIn":return{"0%":{scale:p??3,angle:c??-45,blur:d??15,mirror:i},"100%":{scale:m??1,angle:h??0,blur:f??0,mirror:i}};case"dramaticSpinSlideIn":return{"0%":{x:o??800,angle:c??-60,blur:d??40,scale:p??.7,mirror:i},"30%":{x:-50,angle:5,blur:0,scale:1,mirror:i},"100%":{x:a??0,angle:h??0,blur:f??0,scale:m??1,mirror:i}};case"blurSlideRightOut":return{"0%":{blur:d??0,x:o??0,scale:p??1,mirror:i},"40%":{blur:5,x:-20,scale:1.05,mirror:i},"100%":{blur:f??20,x:a??300,scale:m??.7,mirror:i}};case"wobbleZoomOut":return{"0%":{scale:p??1,angle:c??0,mirror:i},"15%":{scale:1.05,angle:-4,mirror:i},"30%":{scale:.95,angle:2,mirror:i},"100%":{scale:m??1.3,angle:h??8,mirror:i}};case"spinZoomOut":return{"0%":{blur:d??0,angle:c??0,scale:p??1,mirror:i},"60%":{blur:5,angle:10,scale:1.1,mirror:i},"100%":{blur:f??15,angle:h??-180,scale:m??.7,mirror:i}};case"blurSlideLeftOut":return{"0%":{x:o??0,blur:d??0,scale:p??1,mirror:i},"30%":{x:0,blur:5,scale:1,mirror:i},"100%":{x:a??-400,blur:f??25,scale:m??.7,mirror:i}};case"blurSlideRightStrongOut":return{"0%":{x:o??0,blur:d??0,scale:p??1,mirror:i},"25%":{x:20,blur:10,scale:1,mirror:i},"100%":{x:a??600,blur:f??40,scale:m??.8,mirror:i}};case"cinematicZoomSlideOut":return{"0%":{scale:p??1,blur:d??0,x:o??0,mirror:i},"40%":{scale:1.1,blur:5,x:-50,mirror:i},"100%":{scale:m??1.5,blur:f??20,x:a??-100,mirror:i}};case"elasticTwistOut":return{"0%":{scale:p??1,blur:d??0,angle:c??0,mirror:i},"50%":{scale:.9,blur:0,angle:10,mirror:i},"75%":{scale:1.1,blur:5,angle:-5,mirror:i},"100%":{scale:m??.7,blur:f??15,angle:h??-45,mirror:i}};case"spinFadeOut":return{"0%":{blur:d??0,angle:c??0,scale:p??1,mirror:i},"100%":{blur:f??30,angle:h??-90,scale:m??.7,mirror:i}};case"flashZoomOut":return{"0%":{scale:p??1,brightness:g??1,mirror:i},"15%":{scale:1.3,brightness:3,mirror:i},"30%":{scale:1,brightness:5,mirror:i},"100%":{scale:m??1,brightness:v??6,mirror:i}};case"tiltSlideRightOut":return{"0%":{angle:c??0,x:o??0,scale:p??1,mirror:i},"30%":{angle:-3,x:-10,scale:1,mirror:i},"100%":{angle:h??12,x:a??400,scale:m??1.1,mirror:i}};case"tiltZoomOut":return{"0%":{angle:c??0,scale:p??1,mirror:i},"100%":{angle:h??-15,scale:m??.7,mirror:i}};case"glitchSlideOut":return{"0%":{x:o??0,angle:c??0,scale:p??1,mirror:i},"20%":{x:-30,angle:5,scale:1.05,mirror:i},"40%":{x:50,angle:-10,scale:1.1,mirror:i},"100%":{x:a??-600,angle:h??-25,scale:m??.7,mirror:i}};case"dropBlurOut":return{"0%":{y:l??0,blur:d??0,scale:p??1,mirror:i},"100%":{y:u??500,blur:f??30,scale:m??.9,mirror:i}};case"fallZoomOut":return{"0%":{y:l??0,scale:p??1,mirror:i},"30%":{y:-20,scale:1.05,mirror:i},"100%":{y:u??400,scale:m??1.5,mirror:i}};case"zoomSpinOut":return{"0%":{scale:p??1,angle:c??0,blur:d??0,mirror:i},"100%":{scale:m??3,angle:h??45,blur:f??15,mirror:i}};case"dramaticSpinSlideOut":return{"0%":{x:o??0,angle:c??0,blur:d??0,scale:p??1,mirror:i},"30%":{x:50,angle:-5,blur:0,scale:1,mirror:i},"100%":{x:a??-800,angle:h??60,blur:f??40,scale:m??.7,mirror:i}};case"slideRotateIn":return{"0%":{x:o??-200,angle:c??-15,mirror:i},"100%":{x:a??0,angle:h??0,mirror:i}};case"slideRotateOut":return{"0%":{x:o??0,angle:c??0,mirror:i},"100%":{x:a??-200,angle:h??-15,mirror:i}};case"slideBlurIn":return{"0%":{x:o??250,blur:d??20,mirror:i},"100%":{x:a??0,blur:f??0,mirror:i}};case"slideBlurOut":return{"0%":{x:o??0,blur:d??0,mirror:i},"100%":{x:a??250,blur:f??20,mirror:i}};case"zoomRotateIn":return{"0%":{scale:p??1.4,angle:c??20,mirror:i},"100%":{scale:m??1,angle:h??0,mirror:i}};case"zoomRotateOut":return{"0%":{scale:p??1,angle:c??0,mirror:i},"100%":{scale:m??1.4,angle:h??20,mirror:i}};case"zoomBlurIn":return{"0%":{scale:p??1.6,blur:d??30,mirror:i},"100%":{scale:m??1,blur:f??0,mirror:i}};case"zoomBlurOut":return{"0%":{scale:p??1,blur:d??0,mirror:i},"100%":{scale:m??1.6,blur:f??30,mirror:i}};case"slideZoomIn":return{"0%":{x:o??-300,scale:p??.7,mirror:i},"100%":{x:a??0,scale:m??1,mirror:i}};case"slideZoomOut":return{"0%":{x:o??0,scale:p??1,mirror:i},"100%":{x:a??-300,scale:m??.7,mirror:i}};case"verticalBlurIn":return{"0%":{y:l??200,blur:d??25,mirror:i},"100%":{y:u??0,blur:f??0,mirror:i}};case"verticalBlurOut":return{"0%":{y:l??0,blur:d??0,mirror:i},"100%":{y:u??200,blur:f??25,mirror:i}};case"rotateBlurIn":return{"0%":{angle:c??45,blur:d??20,mirror:i},"100%":{angle:h??0,blur:f??0,mirror:i}};case"rotateBlurOut":return{"0%":{angle:c??0,blur:d??0,mirror:i},"100%":{angle:h??45,blur:f??20,mirror:i}};case"cinematicSlideZoomBlurIn":return{"0%":{x:o??300,scale:p??.7,blur:d??40,mirror:i},"100%":{x:a??0,scale:m??1,blur:f??0,mirror:i}};case"cinematicSlideZoomBlurOut":return{"0%":{x:o??0,scale:p??1,blur:d??0,mirror:i},"100%":{x:a??300,scale:m??.7,blur:f??40,mirror:i}};case"brightnessZoomIn":return{"0%":{scale:p??1.3,brightness:g??3,mirror:i},"100%":{scale:m??1,brightness:v??1,mirror:i}};case"brightnessZoomOut":return{"0%":{scale:p??1,brightness:g??1,mirror:i},"100%":{scale:m??1.3,brightness:v??3,mirror:i}};case"brightnessSlideIn":return{"0%":{x:o??-200,brightness:g??.3,mirror:i},"100%":{x:a??0,brightness:v??1,mirror:i}};case"brightnessSlideOut":return{"0%":{x:o??0,brightness:g??1,mirror:i},"100%":{x:a??-200,brightness:v??.3,mirror:i}};case"tiltZoomBlurIn":return{"0%":{angle:c??-10,scale:p??1.4,blur:d??20,mirror:i},"100%":{angle:h??0,scale:m??1,blur:f??0,mirror:i}};case"tiltZoomBlurOut":return{"0%":{angle:c??0,scale:p??1,blur:d??0,mirror:i},"100%":{angle:h??-10,scale:m??1.4,blur:f??20,mirror:i}};case"dropRotateIn":return{"0%":{y:l??-250,angle:c??15,mirror:i},"100%":{y:u??0,angle:h??0,mirror:i}};case"dropRotateOut":return{"0%":{y:l??0,angle:c??0,mirror:i},"100%":{y:u??-250,angle:h??15,mirror:i}};case"spiralIn":return{"0%":{scale:p??.7,angle:c??90,blur:d??30,mirror:i},"100%":{scale:m??1,angle:h??0,blur:f??0,mirror:i}};case"spiralOut":return{"0%":{scale:p??1,angle:c??0,blur:d??0,mirror:i},"100%":{scale:m??.7,angle:h??90,blur:f??30,mirror:i}};case"flashSlideIn":return{"0%":{x:o??150,brightness:g??4,mirror:i},"100%":{x:a??0,brightness:v??1,mirror:i}};case"flashSlideOut":return{"0%":{x:o??0,brightness:g??1,mirror:i},"100%":{x:a??150,brightness:v??4,mirror:i}};case"heavyCinematicIn":return{"0%":{x:o??-300,scale:p??.7,angle:c??-20,blur:d??50,mirror:i},"100%":{x:a??0,scale:m??1,angle:h??0,blur:f??0,mirror:i}};case"heavyCinematicOut":return{"0%":{x:o??0,scale:p??1,angle:c??0,blur:d??0,mirror:i},"100%":{x:a??-300,scale:m??.7,angle:h??-20,blur:f??50,mirror:i}};case"diagonalSlideRotateIn":return{"0%":{x:o??-200,y:l??150,angle:c??-20,mirror:i},"100%":{x:a??0,y:u??0,angle:h??0,mirror:i}};case"diagonalSlideRotateOut":return{"0%":{x:o??0,y:l??0,angle:c??0,mirror:i},"100%":{x:a??-200,y:u??150,angle:h??-20,mirror:i}};case"diagonalBlurZoomIn":return{"0%":{x:o??150,y:l??-150,scale:p??.7,blur:d??30,mirror:i},"100%":{x:a??0,y:u??0,scale:m??1,blur:f??0,mirror:i}};case"diagonalBlurZoomOut":return{"0%":{x:o??0,y:l??0,scale:p??1,blur:d??0,mirror:i},"100%":{x:a??150,y:u??-150,scale:m??.7,blur:f??30,mirror:i}};case"rotateBrightnessIn":return{"0%":{angle:c??60,brightness:g??.2,mirror:i},"100%":{angle:h??0,brightness:v??1,mirror:i}};case"rotateBrightnessOut":return{"0%":{angle:c??0,brightness:g??1,mirror:i},"100%":{angle:h??60,brightness:v??.2,mirror:i}};case"zoomBrightnessBlurIn":return{"0%":{scale:p??1.8,brightness:g??3,blur:d??25,mirror:i},"100%":{scale:m??1,brightness:v??1,blur:f??0,mirror:i}};case"zoomBrightnessBlurOut":return{"0%":{scale:p??1,brightness:g??1,blur:d??0,mirror:i},"100%":{scale:m??1.8,brightness:v??3,blur:f??25,mirror:i}};case"slideUpRotateZoomIn":return{"0%":{y:l??250,angle:c??-15,scale:p??.7,mirror:i},"100%":{y:u??0,angle:h??0,scale:m??1,mirror:i}};case"slideUpRotateZoomOut":return{"0%":{y:l??0,angle:c??0,scale:p??1,mirror:i},"100%":{y:u??250,angle:h??-15,scale:m??.7,mirror:i}};case"fallBlurRotateIn":return{"0%":{y:l??-300,blur:d??40,angle:c??25,mirror:i},"100%":{y:u??0,blur:f??0,angle:h??0,mirror:i}};case"fallBlurRotateOut":return{"0%":{y:l??0,blur:d??0,angle:c??0,mirror:i},"100%":{y:u??-300,blur:f??40,angle:h??25,mirror:i}};case"sideStretchZoomIn":return{"0%":{x:o??300,scale:p??1.6,mirror:i},"100%":{x:a??0,scale:m??1,mirror:i}};case"sideStretchZoomOut":return{"0%":{x:o??0,scale:p??1,mirror:i},"100%":{x:a??300,scale:m??1.6,mirror:i}};case"darkSlideBlurIn":return{"0%":{x:o??-250,blur:d??35,brightness:g??.3,mirror:i},"100%":{x:a??0,blur:f??0,brightness:v??1,mirror:i}};case"darkSlideBlurOut":return{"0%":{x:o??0,blur:d??0,brightness:g??1,mirror:i},"100%":{x:a??-250,blur:f??35,brightness:v??.3,mirror:i}};case"liftZoomRotateIn":return{"0%":{y:l??200,scale:p??.7,angle:c??12,mirror:i},"100%":{y:u??0,scale:m??1,angle:h??0,mirror:i}};case"liftZoomRotateOut":return{"0%":{y:l??0,scale:p??1,angle:c??0,mirror:i},"100%":{y:u??200,scale:m??.7,angle:h??12,mirror:i}};case"overexposedZoomIn":return{"0%":{scale:p??1.4,brightness:g??4,mirror:i},"100%":{scale:m??1,brightness:v??1,mirror:i}};case"overexposedZoomOut":return{"0%":{scale:p??1,brightness:g??1,mirror:i},"100%":{scale:m??1.4,brightness:v??4,mirror:i}};case"driftRotateBlurIn":return{"0%":{x:o??120,angle:c??-30,blur:d??25,mirror:i},"100%":{x:a??0,angle:h??0,blur:f??0,mirror:i}};case"driftRotateBlurOut":return{"0%":{x:o??0,angle:c??0,blur:d??0,mirror:i},"100%":{x:a??120,angle:h??-30,blur:f??25,mirror:i}};case"pushDownZoomBlurIn":return{"0%":{y:l??-180,scale:p??1.5,blur:d??20,mirror:i},"100%":{y:u??0,scale:m??1,blur:f??0,mirror:i}};case"pushDownZoomBlurOut":return{"0%":{y:l??0,scale:p??1,blur:d??0,mirror:i},"100%":{y:u??-180,scale:m??1.5,blur:f??20,mirror:i}};case"twistSlideBrightnessIn":return{"0%":{x:o??200,angle:c??25,brightness:g??.4,mirror:i},"100%":{x:a??0,angle:h??0,brightness:v??1,mirror:i}};case"twistSlideBrightnessOut":return{"0%":{x:o??0,angle:c??0,brightness:g??1,mirror:i},"100%":{x:a??200,angle:h??25,brightness:v??.4,mirror:i}};case"collapseRotateZoomIn":return{"0%":{scale:p??.7,angle:c??-45,mirror:i},"100%":{scale:m??1,angle:h??0,mirror:i}};case"collapseRotateZoomOut":return{"0%":{scale:p??1,angle:c??0,mirror:i},"100%":{scale:m??.7,angle:h??-45,mirror:i}};case"ultraCinematicIn":return{"0%":{x:o??400,y:l??200,scale:p??.7,blur:d??60,angle:c??30,mirror:i},"100%":{x:a??0,y:u??0,scale:m??1,blur:f??0,angle:h??0,mirror:i}};case"ultraCinematicOut":return{"0%":{x:o??0,y:l??0,scale:p??1,blur:d??0,angle:c??0,mirror:i},"100%":{x:a??400,y:u??200,scale:m??.7,blur:f??60,angle:h??30,mirror:i}};case"popCaption":return{"0%":{scale:p??.7},"50%":{scale:1.1},"100%":{scale:m??1}};case"bounceCaption":return{"0%":{y:0,scaleY:1,scaleX:1},"20%":{y:30,scaleY:.8,scaleX:1.2},"40%":{y:15,scaleY:1,scaleX:1},"60%":{y:20,scaleY:.9,scaleX:1.1},"80%":{y:10,scaleY:1,scaleX:1},"100%":{y:0,scaleY:1,scaleX:1}};case"scaleCaption":return{"0%":{scale:p??0},"100%":{scale:m??1}};case"slideLeftCaption":return{"0%":{x:o??50},"100%":{x:a??0}};case"slideRightCaption":return{"0%":{x:o??-50},"100%":{x:a??0}};case"slideUpCaption":return{"0%":{y:l??50},"100%":{y:u??0}};case"slideDownCaption":return{"0%":{y:l??-50},"100%":{y:u??0}};case"fadeCaption":return{"0%":{opacity:n??0},"100%":{opacity:s??1}};case"scaleMidCaption":return{"0%":{scale:p??.8},"100%":{scale:m??1}};case"scaleDownCaption":return{"0%":{scale:p??1.2},"100%":{scale:m??1}};case"upDownCaption":return{"0%":{y:0},"50%":{y:-300},"100%":{y:0}};case"upLeftCaption":return{"0%":{x:0,y:0},"50%":{x:-50,y:-50},"100%":{x:0,y:0}};case"comboZoom1":return{"0%":{scale:p??2.5,motionBlur:x??8,angle:c??0,mirror:1},"30%":{scale:1.2,motionBlur:0,angle:0,mirror:1},"60%":{scale:1,motionBlur:0,angle:0,mirror:1},"100%":{scale:m??2.5,motionBlur:y??8,angle:h??0,mirror:1}};case"comboZoom2":return{"0%":{scale:p??.7,motionBlur:x??8,angle:c??0,mirror:1},"30%":{scale:1,motionBlur:0,angle:0,mirror:1},"60%":{scale:1,motionBlur:0,angle:0,mirror:1},"100%":{scale:m??.7,motionBlur:y??8,angle:h??0,mirror:1}};case"comboPendulum1":return{"0%":{x:-250,blur:d??7,angle:c??5,mirror:1},"45%":{x:-40,blur:1,angle:2,mirror:1},"55%":{x:0,blur:0,angle:0,mirror:1},"60%":{x:0,blur:0,angle:0,mirror:1},"85%":{x:-40,blur:0,angle:-2,mirror:1},"100%":{x:-250,blur:f??0,angle:h??-5,mirror:1}};case"comboPendulum2":return{"0%":{x:250,blur:d??7,angle:c??-5,mirror:1},"45%":{x:40,blur:1,angle:-2,mirror:1},"55%":{x:0,blur:0,angle:0,mirror:1},"60%":{x:0,blur:0,angle:0,mirror:1},"85%":{x:40,blur:0,angle:2,mirror:1},"100%":{x:250,blur:f??0,angle:h??5,mirror:1}};case"comboRightDistort":return{"0%":{scale:p??3,angle:c??-15,blur:d??5,mirror:1},"40%":{blur:1,angle:-6,scale:1.5,mirror:1},"60%":{blur:0,angle:0,scale:1,mirror:1},"70%":{blur:0,angle:0,scale:1,mirror:1},"85%":{scale:.95,mirror:1},"100%":{scale:m??.8,mirror:1}};case"comboLeftDistort":return{"0%":{scale:p??2.5,blur:d??5,mirror:1,angle:0},"45%":{blur:0,scale:1,mirror:1,angle:0},"50%":{blur:0,scale:1,mirror:1,angle:0},"60%":{blur:0,angle:-3,scale:1,mirror:1},"75%":{blur:0,angle:-6,scale:1,mirror:1},"100%":{scale:m??.7,angle:-6,blur:0,mirror:1}};case"comboWobble":return{"0%":{scale:p??1.2,angle:c??15,x:o??-400,blur:d??5,mirror:1},"6%":{scale:1,mirror:1,angle:0,blur:0,x:0},"18%":{scale:1,mirror:1,angle:-10,x:-100},"30%":{angle:-10,scale:1,mirror:1,x:0},"35%":{angle:0,scale:1,mirror:1,x:0},"45%":{angle:5,scale:1,mirror:1,x:0},"55%":{angle:0,scale:1,mirror:1,x:0},"60%":{angle:0,scale:1,mirror:1,blur:0,x:0},"100%":{scale:m??2.5,blur:f??5,mirror:1}};case"comboSpinningTop1":return{"0%":{scale:p??3,blur:d??5,mirror:1},"25%":{scale:1,mirror:1,blur:0,angle:0},"55%":{scale:.7,mirror:1,angle:8},"100%":{angle:h??90,scale:m??.7,mirror:1}};case"comboSwayOut":return{"0%":{scale:p??3,blur:d??5,mirror:1},"50%":{scale:1,mirror:1,blur:0,angle:0},"100%":{mirror:1,angle:h??45,scale:m??3,blur:f??5}};case"comboBounce1":return{"0%":{scale:p??1.2,blur:d??5,mirror:1},"18%":{scale:1,mirror:1,blur:0,angle:0},"50%":{scale:1.5,mirror:1,blur:0,angle:-5},"55%":{scale:1.5,mirror:1,blur:0,angle:-5},"100%":{mirror:1,angle:h??0,scale:m??.9}};case"comboSwayIn":return{"0%":{scale:p??3,blur:d??5,angle:c??-45,mirror:1},"50%":{scale:1,mirror:1,blur:0,angle:0},"100%":{mirror:1,scale:m??3,blur:f??5}};case"comboSpinningTop2":return{"0%":{scale:p??.8,angle:c??-90,mirror:1},"40%":{scale:.8,mirror:1,angle:-15},"60%":{scale:1,mirror:1,angle:0,blur:0},"100%":{scale:m??3,blur:f??5,mirror:1}};case"custom":default:return{"0%":{},"100%":{}}}}class cq extends Z0{id="";name="";display={from:0,to:0};duration=0;playbackRate=1;trim={from:0,to:0};constructor(){super()}_left=0;get left(){return this._left}set left(e){const t=this._left!==e;this._left=e,t&&this.emit("propsChange",{left:e})}_top=0;get top(){return this._top}set top(e){const t=this._top!==e;this._top=e,t&&this.emit("propsChange",{top:e})}_width=0;get width(){return this._width}set width(e){const t=this._width!==e;this._width=e,t&&this.emit("propsChange",{width:e})}_height=0;get height(){return this._height}set height(e){const t=this._height!==e;this._height=e,t&&this.emit("propsChange",{height:e})}_angle=0;get angle(){return this._angle}set angle(e){const t=this._angle!==e;this._angle=e,t&&this.emit("propsChange",{angle:e})}get center(){return{x:this.left+this.width/2,y:this.top+this.height/2}}_zIndex=0;get zIndex(){return this._zIndex}set zIndex(e){const t=this._zIndex!==e;this._zIndex=e,t&&this.emit("propsChange",{zIndex:e})}_opacity=1;get opacity(){return this._opacity}set opacity(e){const t=this._opacity!==e;this._opacity=e,t&&this.emit("propsChange",{opacity:e})}_volume=1;get volume(){return this._volume}set volume(e){const t=this._volume!==e;this._volume=e,t&&this.emit("propsChange",{volume:e})}_locked=!1;get locked(){return this._locked}set locked(e){const t=this._locked!==e;this._locked=e,t&&this.emit("propsChange",{locked:e})}flip=null;effects=[];chromaKey={enabled:!1,color:"#00FF00",similarity:.1,spill:0};colorAdjustment={enabled:!1,type:"basic",basic:{},hsl:{},curves:{}};_style={};get style(){return this._style}set style(e){this._style=e}animatKeyFrame=null;animatOpts=null;animations=[];renderTransform={x:0,y:0,width:0,height:0,scale:1,scaleX:1,scaleY:1,opacity:1,angle:0,blur:0,brightness:1,mirror:0,motionBlur:0};_render(e){const{center:t}=this;e.setTransform(this.flip==="horizontal"?-1:1,0,0,this.flip==="vertical"?-1:1,t.x,t.y),e.globalAlpha=this.opacity*(this.renderTransform.opacity??1)*(this.renderTransform.brightness??1);const i=this.renderTransform.x??0,n=this.renderTransform.y??0,s=this.renderTransform.angle??0,o=this.renderTransform.scale??1,a=this.renderTransform.scaleX??1,l=this.renderTransform.scaleY??1;e.translate(i,n),e.scale(o*a,o*l),e.rotate((this.flip==null?1:-1)*(s*Math.PI)/180)}setAnimation(e,t){this.animatKeyFrame=Object.entries(e).map(([i,n])=>{const s={from:0,to:100}[i]??Number(i.slice(0,-1));if(isNaN(s)||s>100||s<0)throw Error("keyFrame must between 0~100");return[s/100,n]}),this.animatOpts=Object.assign({},this.animatOpts,{duration:t.duration,delay:t.delay??0,iterCount:t.iterCount??1/0}),this.emit("propsChange",{animations:this.animations})}animate(e,t){this.renderTransform={x:0,y:0,width:0,height:0,scale:1,scaleX:1,scaleY:1,opacity:1,angle:0,blur:0,brightness:1,mirror:0,motionBlur:0};for(const n of this.animations){const s=n.getTransform(e);s.x!==void 0&&(this.renderTransform.x+=s.x),s.y!==void 0&&(this.renderTransform.y+=s.y),s.width!==void 0&&(this.renderTransform.width+=s.width),s.height!==void 0&&(this.renderTransform.height+=s.height),s.angle!==void 0&&(this.renderTransform.angle+=s.angle),s.blur!==void 0&&(this.renderTransform.blur+=s.blur),s.motionBlur!==void 0&&(this.renderTransform.motionBlur+=s.motionBlur),s.scale!==void 0&&(this.renderTransform.scale*=s.scale),s.scaleX!==void 0&&(this.renderTransform.scaleX*=s.scaleX),s.scaleY!==void 0&&(this.renderTransform.scaleY*=s.scaleY),s.opacity!==void 0&&(this.renderTransform.opacity*=s.opacity),s.brightness!==void 0&&(this.renderTransform.brightness*=s.brightness),s.mirror!==void 0&&(this.renderTransform.mirror=Math.max(this.renderTransform.mirror||0,s.mirror)),t&&n.apply&&n.apply(t,e)}if(this.animatKeyFrame==null||this.animatOpts==null||e<this.animatOpts.delay)return;const i=hq(e,this.animatKeyFrame,this.animatOpts);for(const n in i)switch(n){case"opacity":this.opacity=i[n];break;case"x":this.left=i[n];break;case"y":this.top=i[n];break;case"w":this.width=i[n];break;case"h":this.height=i[n];break;case"angle":this.angle=i[n];break}}addAnimation(e,t,i){const n=U.create(e,t,i);return this.animations.push(n),this.emit("propsChange",{animations:this.animations}),n.id}removeAnimation(e){this.animations=this.animations.filter(t=>t.id!==e),this.emit("propsChange",{animations:this.animations})}clearAnimations(){this.animations=[],this.emit("propsChange",{animations:this.animations})}updateAnimation(e,t,i,n){const s=this.animations.findIndex(a=>a.id===e);if(s===-1)return;const o=U.create(t,{...i,id:e},n);this.animations[s]=o,this.emit("propsChange",{animations:this.animations})}copyStateTo(e){e.animatKeyFrame=this.animatKeyFrame,e.animatOpts=this.animatOpts,e.zIndex=this.zIndex,e.opacity=this.opacity,e.volume=this.volume,e.flip=this.flip,e.left=this.left,e.top=this.top,e.width=this.width,e.height=this.height,e.angle=this.angle,e.display={...this.display},e.duration=this.duration,e.playbackRate=this.playbackRate,e.trim={...this.trim},e.style=JSON.parse(JSON.stringify(this.style||{})),e.animations=[...this.animations],e.chromaKey={...this.chromaKey},e.colorAdjustment=JSON.parse(JSON.stringify(this.colorAdjustment||{})),e.locked=this.locked,"src"in this&&"src"in e&&(e.src=this.src),"metadata"in this&&"metadata"in e&&(e.metadata=JSON.parse(JSON.stringify(this.metadata||{})))}update(e){Object.assign(this,e),this.emit("propsChange",e)}destroy(){this.all.clear()}}function hq(r,e,t){const i=r-t.delay,n=i%t.duration,s=i/t.duration>=t.iterCount||i===t.duration?1:n/t.duration,o=e.findIndex(f=>f[0]>=s);if(o===-1)return{};const a=e[o-1],l=e[o],u=l[1];if(a==null)return u;const c=a[1],h={},d=(s-a[0])/(l[0]-a[0]);for(const f in u){if(!Object.hasOwn(u,f)||typeof f!="string")continue;const p=f;c[p]!=null&&(h[p]=(u[p]-c[p])*d+c[p])}return h}class zn extends cq{lastVf=null;destroyed=!1;src="";metadata={};transition;constructor(){super()}async getFrame(e){const t=e*this.playbackRate,{video:i,audio:n,state:s}=await this.tick(t);let o=n??[];n!=null&&this.playbackRate!==1&&(o=n.map(l=>lS(l,this.playbackRate)));let a=null;return i!=null?(this.lastVf?.close(),i instanceof VideoFrame?(a=await createImageBitmap(i),i.close()):a=i,this.lastVf=a):this.lastVf!=null&&(a=this.lastVf),{video:a,audio:o,done:s==="done"}}async offscreenRender(e,t){const i=t*this.playbackRate;this.animate(i),super._render(e);const{width:n,height:s}=this,{video:o,audio:a,state:l}=await this.tick(i);let u=a??[];if(a!=null&&this.playbackRate!==1&&(u=a.map(h=>lS(h,this.playbackRate))),l==="done")return{audio:u,done:!0};const c=o??this.lastVf;if(c!=null){const h=this.style.borderRadius||0,d=this.style.dropShadow;if(e.save(),d&&(d.blur>0||d.distance>0)){const p=d.distance??0,m=d.angle??0;e.shadowColor=d.color||"#000000",e.shadowBlur=d.blur||0,e.shadowOffsetX=Math.cos(m)*p,e.shadowOffsetY=Math.sin(m)*p}if(h>0){const p=Math.min(h,n/2,s/2);e.beginPath(),e.roundRect(-n/2,-s/2,n,s,p),e.clip()}e.drawImage(c,-n/2,-s/2,n,s),e.restore();const f=this.style.stroke;if(f&&f.width>0){if(e.save(),e.strokeStyle=f.color,e.lineWidth=f.width,h>0){const p=Math.min(h,n/2,s/2);e.beginPath(),e.roundRect(-n/2,-s/2,n,s,p),e.stroke()}else e.strokeRect(-n/2,-s/2,n,s);e.restore()}}return o!=null&&(this.lastVf?.close(),o instanceof ImageBitmap&&(this.lastVf=o)),{audio:u,done:!1}}set(e,t=30){return e.display&&(e.display.from!==void 0&&(this.display.from=e.display.from),e.display.to!==void 0&&(this.display.to=e.display.to)),e.x!==void 0&&(this.left=e.x),e.y!==void 0&&(this.top=e.y),e.width!==void 0&&(this.width=e.width),e.height!==void 0&&(this.height=e.height),e.duration!==void 0&&(this.duration=e.duration,this.display.from!==void 0&&(this.display.to=this.display.from+this.duration)),this}toJSON(e=!1){const t=this.animatKeyFrame&&this.animatOpts?{keyFrames:this.animatKeyFrame.reduce((n,[s,o])=>{const a=s===0?"from":s===1?"to":`${Math.round(s*100)}%`;return n[a]=o,n},{}),opts:this.animatOpts}:void 0,i=this.animations.map(n=>"toJSON"in n&&typeof n.toJSON=="function"?n.toJSON():{type:n.type,opts:n.options,params:n.params||{}});return{type:this.constructor.name,id:this.id,name:this.name,src:this.src,display:{from:this.display.from,to:this.display.to},playbackRate:this.playbackRate,duration:this.duration,left:this.left,top:this.top,width:this.width,height:this.height,angle:this.angle,zIndex:this.zIndex,opacity:this.opacity,flip:this.flip,style:this.style,trim:{from:this.trim.from,to:this.trim.to},...t&&{animation:t},...i.length>0&&{animations:i},...e&&{main:!0},chromaKey:this.chromaKey,colorAdjustment:this.colorAdjustment,locked:this.locked,metadata:this.metadata}}getVisibleHandles(){return["tl","tr","bl","br","ml","mr","mt","mb","rot"]}async scaleToFit(e,t){await this.ready;const{width:i,height:n}=this.meta;if(i===0||n===0)return;const s=Math.min(e/i,t/n);this.width=i*s,this.height=n*s}async scaleToFill(e,t){await this.ready;const{width:i,height:n}=this.meta;if(i===0||n===0)return;const s=Math.max(e/i,t/n);this.width=i*s,this.height=n*s}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}destroy(){this.destroyed||(this.destroyed=!0,Ee.info("BaseClip destroy"),super.destroy(),this.lastVf?.close(),this.lastVf=null)}}let qb=null;async function zk(){return qb===null&&(qb=bL()),await qb}const st={get codec(){return Tu()?.codec??"mp4a.40.2"},get codecType(){return Tu()?.codecType??"aac"},get sampleRate(){return Tu()?.sampleRate??48e3},get channelCount(){return Tu()?.channelCount??2}};class Lo{static async getCacheKey(e){const i=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-1",i);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}static getPath(e){return`assets/${e}`}static async get(e){const t=await this.getCacheKey(e),i=this.getPath(t),n=Zn(i);return await n.exists()?n:null}static async put(e,t){const i=await this.getCacheKey(e),n=this.getPath(i),s=Zn(n);return await Ys(s,t),s}}class No{resources=new Map;loadingPromises=new Map;async preload(e){const i=[...new Set(e)].filter(n=>n&&!n.startsWith("data:")&&!n.startsWith("blob:")).map(n=>this.loadResource(n));await Promise.allSettled(i)}static async getReadableStream(e){const t=await Lo.get(e);if(t){const a=await t.getOriginFile();if(a)return a.stream()}const i=await fetch(e);if(!i.ok)throw new Error(`Failed to fetch: ${i.status} ${i.statusText}`);const n=i.body;if(!n)throw new Error("Response body is null");if(e.startsWith("data:")||e.startsWith("blob:"))return n;const[s,o]=n.tee();return Lo.put(e,o).catch(a=>{console.error(`ResourceManager: Failed to cache ${e}`,a)}),s}static async getImageBitmap(e){const t=await Lo.get(e);if(t){const l=await t.getOriginFile();if(l)return await createImageBitmap(l)}if(e.startsWith("data:")||e.startsWith("blob:")){const u=await(await fetch(e)).blob();return await createImageBitmap(u)}const i=await fetch(e);if(!i.ok)throw new Error(`Failed to fetch: ${i.status} ${i.statusText}`);const n=i.body;if(!n)throw new Error("Response body is null");const[s,o]=n.tee(),a=(async()=>{const u=await new Response(s).blob();return await createImageBitmap(u)})();return Lo.put(e,o).catch(l=>{console.error(`ResourceManager: Failed to cache ${e}`,l)}),await a}async loadResource(e){const t=this.loadingPromises.get(e);if(t)return t;if(this.resources.has(e)){const n=this.resources.get(e);if(n.status==="completed")return n}const i=(async()=>{const n={url:e,status:"loading"};this.resources.set(e,n);try{const s=await Lo.get(e);if(s)return n.status="completed",n.localFile=s,n;const o=await fetch(e);if(!o.ok)throw new Error(`Fetch failed: ${o.status}`);const a=o.body;if(!a)throw new Error("No body");const l=await Lo.put(e,a);return n.status="completed",n.localFile=l,n}catch(s){return n.status="failed",n.error=s instanceof Error?s:new Error(String(s)),n}finally{this.loadingPromises.delete(e)}})();return this.loadingPromises.set(e,i),i}async resolve(e){if(!e||e.startsWith("data:")||e.startsWith("blob:"))return e;const t=await this.loadResource(e);return t.status==="completed"&&t.localFile?t.localFile:e}getStatus(e){return this.resources.get(e)}clear(){this.resources.clear(),this.loadingPromises.clear()}}class ti extends zn{type="Audio";static ctx=null;ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta,sampleRate:st.sampleRate,chanCount:2}}chan0Buf=new Float32Array;chan1Buf=new Float32Array;getPCMData(){return[this.chan0Buf,this.chan1Buf]}opts;loop=!1;static async fromUrl(e,t={}){const i=await No.getReadableStream(e);return new ti(i,t,e)}static async fromObject(e){if(e.type!=="Audio")throw new Error(`Expected Audio, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("Audio requires a valid source URL");const t={};e.loop!==void 0&&(t.loop=e.loop),e.volume!==void 0&&(t.volume=e.volume);const i=await ti.fromUrl(e.src,t);return i.left=e.left,i.top=e.top,i.width=e.width,i.height=e.height,i.angle=e.angle,i.display.from=e.display.from,i.display.to=e.display.to,i.duration=e.duration,i.playbackRate=e.playbackRate,i.zIndex=e.zIndex,i.opacity=e.opacity,i.flip=e.flip,e.animation&&i.setAnimation(e.animation.keyFrames,e.animation.opts),i}constructor(e,t={},i){super(),this.src=i!==void 0?i:"",this.opts={loop:!1,volume:1,...t},this.loop=this.opts.loop??!1,this.volume=this.opts.volume??1,this.ready=this.init(e).then(n=>{const s={width:0,height:0,duration:t.loop?1/0:this._meta.duration};return this.width=this.width===0?s.width:this.width,this.height=this.height===0?s.height:this.height,this.duration=this.duration===0?s.duration:this.duration,this.display.to=this.display.from+this.duration,s})}async init(e){ti.ctx==null&&(ti.ctx=new AudioContext({sampleRate:st.sampleRate}));const t=performance.now(),i=e instanceof ReadableStream?await fq(e,ti.ctx):e;Ee.info("Audio clip decoded complete:",performance.now()-t),this._meta.duration=i[0].length/st.sampleRate*1e6,this.chan0Buf=i[0],this.chan1Buf=i[1]??this.chan0Buf,Ee.info("Audio clip convert to AudioData, time:",performance.now()-t)}tickInterceptor=async(e,t)=>t;timestamp=0;frameOffset=0;async tick(e){if(!this.opts.loop&&e>=this._meta.duration)return await this.tickInterceptor(e,{audio:[],state:"done"});const t=e-this.timestamp;if(e<this.timestamp||t>3e6)return this.timestamp=e,this.frameOffset=Math.ceil(this.timestamp/1e6*st.sampleRate),await this.tickInterceptor(e,{audio:[new Float32Array(0),new Float32Array(0)],state:"success"});this.timestamp=e;const i=Math.ceil(t/1e6*st.sampleRate),n=this.frameOffset+i,s=this.opts.loop?[K0(this.chan0Buf,this.frameOffset,n),K0(this.chan1Buf,this.frameOffset,n)]:[this.chan0Buf.slice(this.frameOffset,n),this.chan1Buf.slice(this.frameOffset,n)];if(this.volume!==1)for(const o of s)for(let a=0;a<o.length;a++)o[a]*=this.volume;return this.frameOffset=n,await this.tickInterceptor(e,{audio:s,state:"success"})}async split(e){await this.ready;const t=Math.ceil(e/1e6*st.sampleRate),i=new ti(this.getPCMData().map(s=>s.slice(0,t)),this.opts,this.src),n=new ti(this.getPCMData().map(s=>s.slice(t)),this.opts,this.src);return[i,n]}async clone(){await this.ready;const e=new ti(this.getPCMData(),this.opts,this.src);return await e.ready,this.copyStateTo(e),e}destroy(){this.chan0Buf=new Float32Array(0),this.chan1Buf=new Float32Array(0),Ee.info("---- audioclip destroy ----"),super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Audio",loop:this.loop,id:this.id,volume:this.volume}}static concatAudio=dq;async createPlaybackElement(){if(await this.ready,!this.src||this.src.trim()==="")throw new Error("Audio requires a source URL for playback");const e=this.src.startsWith("blob:")?this.src:void 0,t=document.createElement("audio");return t.crossOrigin="anonymous",t.autoplay=!1,t.preload="auto",t.loop=this.opts.loop||!1,t.src=this.src,await new Promise((i,n)=>{const s=()=>{t.removeEventListener("loadeddata",s),t.removeEventListener("error",o),t.pause(),t.currentTime=0,i()},o=()=>{t.removeEventListener("loadeddata",s),t.removeEventListener("error",o),n(new Error("Failed to load audio"))};t.addEventListener("loadeddata",s,{once:!0}),t.addEventListener("error",o,{once:!0}),t.load()}),{element:t,objectUrl:e}}async play(e,t){const i=e;if(Math.abs(i.currentTime-t)>.1&&(i.currentTime=t),i.paused)try{await i.play()}catch{try{await i.play()}catch(s){console.warn("Failed to play audio:",s)}}}pause(e){e.pause()}async seek(e,t){const i=e;return i.pause(),i.currentTime=t,new Promise(n=>{if(Math.abs(i.currentTime-t)<.01){n();return}const s=()=>{i.removeEventListener("seeked",s),n()};i.addEventListener("seeked",s,{once:!0}),setTimeout(()=>{i.removeEventListener("seeked",s),n()},500)})}syncPlayback(e,t,i){const n=e,s=this.meta.duration/1e6,o=i>=0&&i<s;n.volume=this.volume,t&&o?n.paused&&this.play(n,i).catch(console.warn):(n.paused||n.pause(),o&&Math.abs(n.currentTime-i)>.1&&(n.currentTime=i))}cleanupPlayback(e,t){const i=e;i.pause(),i.removeAttribute("src"),i.load(),t&&t.startsWith("blob:")&&URL.revokeObjectURL(t)}}async function dq(r,e){const t=[];for(const i of r)await i.ready,t.push(i.getPCMData());return new ti(sS(t),e)}async function fq(r,e){const t=await new Response(r).arrayBuffer();return j0(await e.decodeAudioData(t))}function xt(r){if(r!=null){if(typeof r=="number")return r;if(typeof r=="string"){if(r==="transparent")return;if(r.startsWith("#")){const t=parseInt(r.slice(1),16);if(!isNaN(t))return t}if(r.startsWith("0x")){const t=parseInt(r,16);if(!isNaN(t))return t}const e=parseInt(r,16);if(!isNaN(e))return e;try{return new ye(r).toNumber()}catch{return}}}}const Lk=r=>r==="transparent",Ln=(r,e=16777215)=>Lk(r)?{color:e,alpha:0}:{color:xt(r)??e,alpha:1};function Rl(r){try{const t=new ye(r).toRgbArray();return{r:Math.round(t[0]*255),g:Math.round(t[1]*255),b:Math.round(t[2]*255)}}catch{return null}}class Nn extends zn{type="Caption";_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}animate(e){super.animate(e,this.pixiTextContainer)}_visualPaddingX=20;_visualPaddingY=15;_lastTickTime=0;get width(){return this._width}set width(e){Math.abs(this._width-e)<.1||(this._width=e,e>0?(this._isWidthConstrained=!0,this.opts.wordWrapWidth=e,this.opts.wordWrap=!0,this.originalOpts&&(this.originalOpts.wordWrapWidth=e,this.originalOpts.wordWrap=!0)):(this._isWidthConstrained=!1,this.opts.wordWrapWidth=0,this.opts.wordWrap=!1,this.originalOpts&&(this.originalOpts.wordWrapWidth=0,this.originalOpts.wordWrap=!1)),this.refreshCaptions().then(()=>{this.emit("propsChange",{width:e})}))}get height(){return this._height}set height(e){Math.abs(this._height-e)<.1||(this._height=e,this.refreshCaptions().then(()=>{this.emit("propsChange",{height:e})}))}get left(){return this._left}set left(e){Math.abs(this._left-e)<.1||(this._left=e,this._refreshing||(this._isXPositionedManually=!0),this.emit("propsChange",{left:e}))}get top(){return this._top}set top(e){Math.abs(this._top-e)<.1||(this._top=e,this.emit("propsChange",{top:e}))}_initialLayoutApplied=!1;_isXPositionedManually=!1;_isWidthConstrained=!1;_lastContentWidth=0;_lastContentHeight=0;_lastProcessedText="";_text="";get text(){return this._text}set text(e){if(this._text===e)return;this._text=e;const i=(this.opts?.words||[]).map(s=>s.text).join(" "),n=s=>s.replace(/\s+/g," ").trim();if(n(e)!==n(i)){const s=this.duration>0&&this.duration!==1/0?this.duration/1e3:5e3,o=e.split(`
3509
- `),a=[];if(o.forEach((l,u)=>{l.trim().split(/\s+/).filter(h=>h!=="").forEach(h=>{a.push({text:h,paragraphIndex:u})})}),a.length===0)this.opts.words=[];else{const l=s/a.length;this.opts.words=a.map((u,c)=>({text:u.text,from:c*l,to:(c+1)*l,isKeyWord:!1,paragraphIndex:u.paragraphIndex}))}}this.originalOpts&&(this.originalOpts.caption?this.originalOpts.caption.words=this.opts.words:this.originalOpts.words=this.opts.words),this.originalOpts&&this.textStyle&&this.refreshCaptions().then(()=>{this.emit("propsChange",{text:e})})}get style(){if(!this.originalOpts)return{};const e=this.originalOpts;return{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,color:e.fill,align:e.align,textCase:e.textCase,verticalAlign:e.verticalAlign,wordsPerLine:e.wordsPerLine,wordAnimation:e.wordAnimation,stroke:e.stroke?typeof e.stroke=="object"?{color:e.stroke.color,width:e.stroke.width}:{color:e.stroke,width:e.strokeWidth??0}:void 0,shadow:e.dropShadow?{color:e.dropShadow.color??"#000000",alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,distance:e.dropShadow.distance??0,angle:e.dropShadow.angle??0}:void 0}}set style(e){this.updateStyle(e)}get wordsPerLine(){return this.opts.wordsPerLine}set wordsPerLine(e){this.updateStyle({wordsPerLine:e})}get fontFamily(){return this.opts.fontFamily}set fontFamily(e){this.updateStyle({fontFamily:e})}get fontUrl(){return this.opts.fontUrl}set fontUrl(e){this.updateStyle({fontUrl:e})}get fontSize(){return this.opts.fontSize}set fontSize(e){this.updateStyle({fontSize:e})}get fontWeight(){return this.opts.fontWeight}set fontWeight(e){this.updateStyle({fontWeight:e})}get fontStyle(){return this.opts.fontStyle}set fontStyle(e){this.updateStyle({fontStyle:e})}get fill(){return this.opts.fill}set fill(e){this.updateStyle({fill:e})}get align(){return this.opts.align}set align(e){this.updateStyle({align:e})}get stroke(){return this.originalOpts?.stroke}set stroke(e){this.updateStyle({stroke:e})}get strokeWidth(){return this.opts.strokeWidth}set strokeWidth(e){this.updateStyle({strokeWidth:e})}get dropShadow(){return this.originalOpts?.dropShadow}set dropShadow(e){this.updateStyle({dropShadow:e})}get caption(){return this.originalOpts?.caption}set caption(e){this.updateStyle({caption:e})}get textBoxStyle(){return this.originalOpts?.caption?.textBoxStyle??this.originalOpts?.textBoxStyle??{}}set textBoxStyle(e){this.updateStyle({textBoxStyle:e})}bottomOffset;get textCase(){return this.originalOpts?.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;get mediaId(){return this.opts.mediaId}set mediaId(e){this.opts.mediaId=e,this.originalOpts&&(this.originalOpts.mediaId=e)}effects=[];get words(){return this.opts.words}set words(e){const t=e??[];this.opts.words=t,this.originalOpts&&(this.originalOpts.caption?this.originalOpts.caption.words=e:this.originalOpts.words=e);const i=t.map(n=>n.text).filter(n=>n&&n.trim()!=="").join(" ");this._text!==i?this.text=i:this.refreshCaptions().then(()=>{this.emit("propsChange",{words:e})})}opts;pixiTextContainer=null;renderTexture=null;wordTexts=[];textStyle;textStyleBase;_refreshing=!1;_needsRefresh=!1;externalRenderer=null;pixiApp=null;originalOpts=null;constructor(e,t={},i){super(),this.originalOpts={...t},this.externalRenderer=i??null,this.opts={fontSize:t.fontSize??30,fontFamily:t.fontFamily??"Arial",fontUrl:t.fontUrl??"",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",fill:t.fill??"#ffffff",strokeWidth:t.strokeWidth??0,align:t.align??"center",wordWrapWidth:t.wordWrapWidth??0,wordWrap:t.wordWrap??!1,lineHeight:t.lineHeight??1,letterSpacing:t.letterSpacing??0,textCase:t.textCase??"none",videoWidth:t.caption?.positioning?.videoWidth??t.videoWidth??1280,videoHeight:t.caption?.positioning?.videoHeight??t.videoHeight??720,bottomOffset:t.caption?.positioning?.bottomOffset??t.bottomOffset??30,keyword:t.caption?.colors?.keyword??t.colors?.keyword??"#ffff00",background:t.caption?.colors?.background??t.colors?.background??"#000000",active:t.caption?.colors?.active??t.colors?.active??"#ffffff",activeFill:t.caption?.colors?.activeFill??t.colors?.activeFill??"#00ff00",appeared:t.caption?.colors?.appeared??t.colors?.appeared??"#ffffff",words:t.caption?.words??t.words??[],preserveKeywordColor:t.caption?.preserveKeywordColor??t.preserveKeywordColor??!1,mediaId:t.mediaId,wordsPerLine:t.wordsPerLine??"multiple",wordAnimation:t.caption?.wordAnimation??t.wordAnimation,textBoxStyle:t.caption?.textBoxStyle??t.textBoxStyle??{}},this._initialLayoutApplied=t.initialLayoutApplied??!1,this._initialLayoutApplied&&(this._isXPositionedManually=!0),this.opts.wordWrapWidth>0&&(this._isWidthConstrained=!0,this._width=this.opts.wordWrapWidth,this.opts.wordWrap=!0),this.text=e,this._lastProcessedText=this._text;const n={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(t.fill&&typeof t.fill=="object"&&t.fill.type==="gradient"){const c=new zr(t.fill.x0,t.fill.y0,t.fill.x1,t.fill.y1);t.fill.colors.forEach(({ratio:h,color:d})=>{const f=typeof d=="number"?d:xt(d)??16777215;c.addColorStop(h,f)}),n.fill={fill:c}}else{let c;t.fill==="transparent"?c=16777215:(typeof t.fill=="string"||typeof t.fill=="number")&&(c=xt(t.fill)),n.fill=c??16777215}const s=c=>c==="transparent";if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke){if(!s(t.stroke.color)){const c=xt(t.stroke.color);c!==void 0&&(n.stroke={color:c,width:t.stroke.width},t.stroke.join&&(n.stroke.join=t.stroke.join))}}else{const c=t.stroke??void 0;if(!s(c)){const h=xt(c);h!==void 0?n.stroke={color:h,width:this.opts.strokeWidth??0}:this.opts.strokeWidth&&this.opts.strokeWidth>0&&(n.stroke={color:0,width:this.opts.strokeWidth})}}if(t.dropShadow){const c=xt(t.dropShadow.color);c!==void 0&&(n.dropShadow={color:c,alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,angle:t.dropShadow.angle??Math.PI/6,distance:t.dropShadow.distance??2})}const o=new Bt(n);this.textStyle=o;const{align:a,fill:l,...u}=n;this.textStyleBase=new Bt(u),this.ready=(async()=>{await this.refreshCaptions();const c={...this._meta};return Ee.info("CaptionClip ready:",c),c})()}async updateStyle(e){this.originalOpts||(this.originalOpts={});let t={...e};e.style&&(t={...t,...e.style},delete t.style),this.originalOpts={...this.originalOpts,...t},t.fontSize!==void 0&&(this.opts.fontSize=t.fontSize),t.fontFamily!==void 0&&(this.opts.fontFamily=t.fontFamily),t.fontUrl!==void 0&&(this.opts.fontUrl=t.fontUrl),t.fontWeight!==void 0&&(this.opts.fontWeight=t.fontWeight),t.fontStyle!==void 0&&(this.opts.fontStyle=t.fontStyle),t.fill!==void 0&&(this.opts.fill=t.fill),t.align!==void 0&&(this.opts.align=t.align),t.letterSpacing!==void 0&&(this.opts.letterSpacing=t.letterSpacing),t.lineHeight!==void 0&&(this.opts.lineHeight=t.lineHeight),t.textCase!==void 0&&(this.opts.textCase=t.textCase),t.wordWrapWidth!==void 0&&(this.opts.wordWrapWidth=t.wordWrapWidth,t.wordWrapWidth>0&&(this._isWidthConstrained=!0,this.opts.wordWrap=!0)),t.wordsPerLine!==void 0&&(this.opts.wordsPerLine=t.wordsPerLine),t.wordAnimation!==void 0&&(this.opts.wordAnimation=t.wordAnimation),t.textBoxStyle!==void 0&&(this.opts.textBoxStyle=t.textBoxStyle),t.caption?.colors&&(t.caption.colors.appeared!==void 0&&(this.opts.appeared=t.caption.colors.appeared),t.caption.colors.active!==void 0&&(this.opts.active=t.caption.colors.active),t.caption.colors.activeFill!==void 0&&(this.opts.activeFill=t.caption.colors.activeFill),t.caption.colors.background!==void 0&&(this.opts.background=t.caption.colors.background),t.caption.colors.keyword!==void 0&&(this.opts.keyword=t.caption.colors.keyword),t.caption.wordAnimation!==void 0&&(this.opts.wordAnimation=t.caption.wordAnimation)),t.caption?.preserveKeywordColor!==void 0&&(this.opts.preserveKeywordColor=t.caption.preserveKeywordColor);const i={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(this.opts.fill&&typeof this.opts.fill=="object"&&this.opts.fill.type==="gradient"){const u=new zr(this.opts.fill.x0,this.opts.fill.y0,this.opts.fill.x1,this.opts.fill.y1);this.opts.fill.colors.forEach(({ratio:c,color:h})=>{const d=typeof h=="number"?h:xt(h)??16777215;u.addColorStop(c,d)}),i.fill={fill:u}}else i.fill=16777215;if(e.stroke!==void 0||e.strokeWidth!==void 0||this.originalOpts.stroke||this.originalOpts.strokeWidth){if(this.originalOpts.stroke&&typeof this.originalOpts.stroke=="object"&&"color"in this.originalOpts.stroke){const u=xt(this.originalOpts.stroke.color);u!==void 0&&(i.stroke={color:u,width:this.originalOpts.stroke.width},this.originalOpts.stroke.join&&(i.stroke.join=this.originalOpts.stroke.join))}else if(this.originalOpts?.stroke){const u=this.originalOpts.stroke,c=xt(typeof u=="object"&&u!==null&&"color"in u?u.color:u),h=e.strokeWidth!==void 0?e.strokeWidth:this.originalOpts.strokeWidth!==void 0?this.originalOpts.strokeWidth:0;c!==void 0?i.stroke={color:c,width:h}:h>0&&(i.stroke={color:0,width:h})}}const s=e.dropShadow!==void 0?e.dropShadow:this.originalOpts.dropShadow;if(s){const u=xt(s.color);u!==void 0&&(i.dropShadow={color:u,alpha:s.alpha!==void 0?s.alpha:.5,blur:s.blur!==void 0?s.blur:4,angle:s.angle!==void 0?s.angle:Math.PI/6,distance:s.distance!==void 0?s.distance:2})}this.textStyle=new Bt(i);const{align:o,fill:a,...l}=i;this.textStyleBase=new Bt(l),await this.refreshCaptions(),this.emit("propsChange",e)}async refreshCaptions(){if(this._refreshing){this._needsRefresh=!0;return}this._refreshing=!0,this._needsRefresh=!1;try{typeof document<"u"&&await document.fonts.ready;const e=this._width,t=this._height,i=this.originalOpts?.verticalAlign||"center";this.pixiTextContainer?this.pixiTextContainer.removeChildren():this.pixiTextContainer=new Ie,this.wordTexts.forEach(z=>{z.destroyed||z.destroy()}),this.wordTexts=[];const n=Ht.measureText(" ",this.textStyle),s=[];this.opts.words.forEach((z,ne)=>{const oe=this.opts.textCase;let te=z.text||"";oe==="uppercase"?te=te.toUpperCase():oe==="lowercase"?te=te.toLowerCase():oe==="title"&&(te=te.replace(/\w\S*/g,Ue=>Ue.charAt(0).toUpperCase()+Ue.substring(1).toLowerCase())),te.split(/\s+/).filter(Ue=>Ue.length>0).forEach(Ue=>{const Ge=new kl({text:Ue,style:this.textStyle});Ge.segmentIndex=ne;const ke="#ffffff",Ve=typeof ke=="object"&&ke!==null&&"type"in ke?16777215:ke,Me=xt(Ve);Ge.tint=Me??16777215,s.push(Ge)})}),this.wordTexts=s;const o=this._visualPaddingX,a=this._visualPaddingY,l=this.opts.lineHeight*(this.opts.fontSize||30),u=new kl({text:" ",style:this.textStyleBase}),c=Math.ceil(u.getLocalBounds().width||u.width||n.width);u.destroy();const h=!this._isWidthConstrained&&(this.width===0||this._lastContentWidth===0||Math.abs(this.width-this._lastContentWidth)<2),d=this.opts.videoWidth||1280;let f=0;this.opts.wordWrapWidth>0&&this.opts.wordsPerLine!=="single"?f=this.opts.wordWrapWidth-o*2:this.opts.wordsPerLine==="single"?f=d*5:!h&&this.width>0?f=this.width+10:f=d*5,(isNaN(f)||f<=0)&&(f=d);let p=[];const m=this.opts.textBoxStyle.textAlign||this.opts.align,g=this.opts.textBoxStyle,v=g.style==="tiktok",x=[],y=g.horizontalPadding??0,b=g.verticalPadding??0;let T=[],E=0,C=0;this.wordTexts.forEach((z,ne)=>{const oe=z.getLocalBounds(),te=Math.ceil(oe.width||z.width),be=Math.ceil(oe.height||z.height),Ue=z.segmentIndex,Ge=this.opts.words[Ue],ke=ne>0?this.wordTexts[ne-1]:null,Ve=ke?this.opts.words[ke.segmentIndex]:null,Me=Ve&&Ge&&Ge.paragraphIndex!==void 0&&Ge.paragraphIndex!==Ve.paragraphIndex||this.opts.wordsPerLine==="single",Ct=E+(E>0?c:0)+te;!Me&&(Ct<=f+1||T.length===0)?(T.push(z),E=Ct,C=Math.max(C,be)):(T.length>0&&p.push({words:T,width:E,height:Math.max(C,l)+b*2}),T=[z],E=te,C=be)}),T.length>0&&p.push({words:T,width:E,height:Math.max(C,l)+b*2}),this.opts.textBoxStyle.maxLines&&this.opts.textBoxStyle.maxLines>0&&(p=p.slice(0,this.opts.textBoxStyle.maxLines));let P=0,_=0;p.forEach(z=>{P=Math.max(P,z.width),_+=z.height});const S=P,I=_,M=S+Math.max(o,y)*2,O=I,H=this._text!==this._lastProcessedText;this._lastProcessedText=this._text;let K=M;const D=O;this._isWidthConstrained&&(H?K=M:K=Math.max(M,e),this.opts.wordWrapWidth>0&&(K=Math.min(K,this.opts.wordWrapWidth)));const k=K,W=D,G=I;let J=0;const q=Math.max(a,b);i==="top"?J=q:i==="bottom"?J=W-G-q:J=(W-G)/2;let _e=J;if(p.forEach(z=>{const ne=new Ie;ne.label="lineContainer",this.pixiTextContainer.addChild(ne);let oe=0;const te=z.width;let be=0;m==="center"?be=(k-te)/2:m==="right"?be=k-te-o:be=o,ne.x=be,ne.y=_e,v&&x.push({x:be-y,y:_e,w:te+y*2,h:z.height}),z.words.forEach((Ue,Ge)=>{const ke=Ue.getLocalBounds(),Ve=ke.width||Ue.width,Me=ke.height||Ue.height;Ue.pivot.set(Ve/2,Me/2),Ue.x=Math.round(oe+Ve/2),Ue.y=Math.round(z.height/2),ne.addChild(Ue),oe+=Ve+(Ge<z.words.length-1?c:0)}),_e+=z.height}),v&&x.length>0){const z=new Je;z.label="tiktokBackground";const ne=xt(this.opts.background)??0,oe=g.borderRadius??10;this.drawRoundedTiktokPath(z,x,oe,ne),this.pixiTextContainer.addChildAt(z,0)}if(!v){const z=new Je;z.label="containerBackground";const ne=this.opts.background==="transparent"||!this.opts.background,oe=ne?0:xt(this.opts.background),te=ne?0:1;z.roundRect(0,0,k,W,10),z.fill({color:oe,alpha:te}),this.pixiTextContainer.addChildAt(z,0)}this.renderTexture?(Math.abs(this.renderTexture.width-k)>.5||Math.abs(this.renderTexture.height-W)>.5)&&(this.renderTexture.destroy(),this.renderTexture=Ot.create({width:k,height:W})):this.renderTexture=Ot.create({width:k,height:W}),this.updateState(this._lastTickTime);try{(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture})}catch(z){Ee.warn("CaptionClip: Could not render captions during refresh",z)}const Re=!this._isWidthConstrained,ge=this.height===0||this._lastContentHeight===0||Math.abs(this.height-this._lastContentHeight)<2;if(Re&&this._initialLayoutApplied&&e>0&&t>0){const z=K-e;Math.abs(z)>.1&&!this._isXPositionedManually&&this.opts.align==="center"?this.left-=z/2:Math.abs(z)>.1&&!this._isXPositionedManually&&this.opts.align==="right"&&(this.left-=z)}if(this._meta.width=S,this._meta.height=I,this._meta.duration=1/0,this._width=k,this._height=W,this._lastContentWidth=this._width,this._lastContentHeight=this._height,!this._initialLayoutApplied&&(Re||ge)){const z=this.opts.videoWidth,ne=this.opts.videoHeight,oe=this.opts.bottomOffset,te=ne-I-oe,be=(z-S)/2;this.top=te,this.left=be,this._initialLayoutApplied=!0}}finally{this._refreshing=!1,this._needsRefresh&&this.refreshCaptions()}}lastLoggedTime=-1;updateState(e){const t=e/1e3,i=Math.floor(e/1e6);i!==this.lastLoggedTime&&(this.lastLoggedTime=i),this.wordTexts.forEach(n=>{const s=n.segmentIndex,o=this.opts.words[s];if(!o)return;n.scale.set(1,1);const a=t>=o.from&&t<o.to,l=t>=o.to,u=this.opts.wordAnimation;let c=0,h=!1;if(u&&u.application!=="none"&&((u.application==="active"&&a||u.application==="keyword"&&o.isKeyWord)&&(h=!0),h)){if(u.mode==="dynamic"&&a){const v=o.to-o.from;if(v>0){const x=(t-o.from)/v,y=Math.max(0,Math.min(1,x));u.value<1?c=y:c=Math.sin(y*Math.PI)}else c=1}else c=1;if(u.type==="scale"){let v=1;u.value<1&&u.mode==="dynamic"&&a?v=u.value+(1-u.value)*c:v=1+(u.value-1)*c,n.scale.set(v,v)}}const d=o.isKeyWord&&!Lk(this.opts.keyword);let f=16777215,p=1;if(o.isKeyWord&&a&&d)({color:f,alpha:p}=Ln(this.opts.keyword,16776960));else if(a)p=Ln(this.opts.active,16777215).alpha,f=Ln(this.opts.active,16777215).color;else if(l&&this.opts.preserveKeywordColor&&d)({color:f,alpha:p}=Ln(this.opts.keyword));else if(l)({color:f,alpha:p}=Ln(this.opts.appeared));else{const v=this.opts.fill,x=typeof v=="object"&&v!==null&&"type"in v?16777215:v;({color:f,alpha:p}=Ln(x))}if(h&&u?.type==="opacity"){let v=1;u.value<1&&u.mode==="dynamic"&&a?v=u.value+(1-u.value)*c:v=1+(u.value-1)*c,p*=v}n.children.forEach(v=>{v.label!=="bgRect"&&(v.tint=f,v.alpha=p)});const m=n.getChildByLabel("bgRect"),g=this.opts.textBoxStyle.style==="tiktok";if(a&&!g){const{color:v,alpha:x}=Ln(this.opts.activeFill,16753920),y=15,b=40;m&&(m.visible=!1);const T=n.getLocalBounds();m&&(m.visible=!0);const E=10,C=m??new Je;C.label="bgRect",C.clear(),C.roundRect(T.x-b/2,T.y-y/2,T.width+b,T.height+y,E),C.fill({color:v,alpha:x}),C.tint=16777215,m||n.addChildAt(C,0)}else m&&(n.removeChild(m),m.destroy())})}async getTexture(){return this.pixiTextContainer==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture)}async offscreenRender(e,t){const i=t*this.playbackRate;this._lastTickTime=i*1e6,this.animate(i*1e6),this._render(e);const{width:n,height:s}=this,{video:o,audio:a,done:l}=await this.getFrame(t),u=a??[];return l?{audio:u,done:!0}:(o!=null&&(e.save(),e.drawImage(o,-n/2,-s/2,n,s),e.restore()),{audio:u,done:!1})}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("CaptionClip: No renderer available. Provide a renderer via setRenderer().");return this.pixiApp.renderer}async tick(e){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("CaptionClip not initialized");this._lastTickTime=e,this.updateState(e);const t=await this.getRenderer();t.render({container:this.pixiTextContainer,target:this.renderTexture});const i=this.renderTexture.source?.resource?.source;let n;if(i instanceof HTMLCanvasElement)n=await createImageBitmap(i);else if(i instanceof OffscreenCanvas)n=await createImageBitmap(i);else{const o=t.extract.canvas(this.renderTexture);if(o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas)n=await createImageBitmap(o);else throw new Error("Unable to extract canvas from render texture")}return{video:n,state:"success"}}async split(e){await this.ready;const t=await this.clone(),i=await this.clone();return[t,i]}addEffect(e){this.effects.push(e)}editEffect(e,t){const i=this.effects.find(n=>n.id===e);i&&Object.assign(i,t)}removeEffect(e){const t=this.effects.findIndex(i=>i.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.originalOpts||{},t=new Nn(this.text,e);return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){if(!this.destroyed){Ee.info("Caption destroy");try{this.wordTexts.forEach(e=>{e!=null&&!e.destroyed&&e.destroy({children:!0})})}catch{}finally{this.wordTexts=[]}try{this.pixiTextContainer!=null&&(this.pixiTextContainer.destroyed||this.pixiTextContainer.destroy({children:!0}))}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&(this.renderTexture.destroyed||this.renderTexture.destroy(!0))}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),i={};if(this.originalOpts){const f=this.originalOpts;f.fontSize!==void 0&&(i.fontSize=f.fontSize),f.fontFamily!==void 0&&(i.fontFamily=f.fontFamily),f.fontWeight!==void 0&&(i.fontWeight=f.fontWeight),f.fontStyle!==void 0&&(i.fontStyle=f.fontStyle),f.fill!==void 0&&(i.color=f.fill),f.align!==void 0&&(i.align=f.align),f.textCase!==void 0&&(i.textCase=f.textCase),f.fontUrl!==void 0&&(i.fontUrl=f.fontUrl),f.verticalAlign!==void 0&&(i.verticalAlign=f.verticalAlign),f.wordWrapWidth!==void 0&&(i.wordWrapWidth=f.wordWrapWidth),f.wordWrap!==void 0&&(i.wordWrap=f.wordWrap),f.wordAnimation!==void 0&&(i.wordAnimation=f.wordAnimation),f.textBoxStyle!==void 0&&(i.textBoxStyle=f.textBoxStyle),f.stroke&&(typeof f.stroke=="object"?i.stroke={color:f.stroke.color,width:f.stroke.width}:i.stroke={color:f.stroke,width:this.opts.strokeWidth??0}),f.dropShadow&&(i.shadow={color:f.dropShadow.color??"#000000",alpha:f.dropShadow.alpha??.5,blur:f.dropShadow.blur??4,distance:f.dropShadow.distance??0,angle:f.dropShadow.angle??0})}const n={};this.opts.words&&this.opts.words.length>0&&(n.words=this.opts.words);const s={},o=this.originalOpts?.caption?.colors??this.originalOpts?.colors;o?.appeared!==void 0&&(s.appeared=o.appeared),o?.active!==void 0&&(s.active=o.active),o?.activeFill!==void 0&&(s.activeFill=o.activeFill),o?.background!==void 0&&(s.background=o.background),o?.keyword!==void 0&&(s.keyword=o.keyword);let a;this.originalOpts?.caption?.preserveKeywordColor!==void 0?a=this.originalOpts.caption.preserveKeywordColor:this.originalOpts?.preserveKeywordColor!==void 0&&(a=this.originalOpts.preserveKeywordColor),Object.keys(s).length>0&&(n.colors=s),a!==void 0&&(n.preserveKeywordColor=a);const l={};this.bottomOffset!==void 0&&(l.bottomOffset=this.bottomOffset);const u=this.originalOpts?.caption?.positioning?.videoWidth??this.originalOpts?.videoWidth,c=this.originalOpts?.caption?.positioning?.videoHeight??this.originalOpts?.videoHeight;u!==void 0&&(l.videoWidth=u),c!==void 0&&(l.videoHeight=c),Object.keys(l).length>0&&(n.positioning=l);const h=this.originalOpts?.caption?.wordAnimation??this.originalOpts?.wordAnimation;h!==void 0&&(n.wordAnimation=h);const d=this.originalOpts?.caption?.textBoxStyle??this.originalOpts?.textBoxStyle;return d!==void 0&&(n.textBoxStyle=d),{...t,type:"Caption",text:this.text,style:i,caption:Object.keys(n).length>0?n:void 0,textBoxStyle:d,id:this.id,effects:this.effects,mediaId:this.mediaId,wordsPerLine:this.opts.wordsPerLine}}static async fromObject(e){if(e.type!=="Caption")throw new Error(`Expected Caption, got ${e.type}`);const t=e.text||"",i=e.style||{},n={};i.fontSize!==void 0&&(n.fontSize=i.fontSize),i.fontFamily!==void 0&&(n.fontFamily=i.fontFamily),i.fontWeight!==void 0&&(n.fontWeight=i.fontWeight),i.fontStyle!==void 0&&(n.fontStyle=i.fontStyle),i.color!==void 0&&(n.fill=i.color),i.align!==void 0&&(n.align=i.align),i.textCase!==void 0&&(n.textCase=i.textCase),i.verticalAlign!==void 0&&(n.verticalAlign=i.verticalAlign),i.wordWrapWidth!==void 0&&(n.wordWrapWidth=i.wordWrapWidth),i.wordWrap!==void 0&&(n.wordWrap=i.wordWrap),i.wordsPerLine!==void 0?n.wordsPerLine=i.wordsPerLine:e.wordsPerLine!==void 0&&(n.wordsPerLine=e.wordsPerLine),i.fontUrl!==void 0?n.fontUrl=i.fontUrl:e.fontUrl!==void 0&&(n.fontUrl=e.fontUrl),e.mediaId&&(n.mediaId=e.mediaId),i.stroke&&(n.stroke=i.stroke.color,n.strokeWidth=i.stroke.width),i.shadow&&(n.dropShadow={color:i.shadow.color,alpha:i.shadow.alpha,blur:i.shadow.blur,distance:i.shadow.distance,angle:i.shadow.angle}),i.wordAnimation!==void 0&&(n.wordAnimation=i.wordAnimation),e.textBoxStyle!==void 0?n.textBoxStyle=e.textBoxStyle:i.textBoxStyle!==void 0&&(n.textBoxStyle=i.textBoxStyle),e.caption?(n.caption=e.caption,e.caption.wordAnimation&&(n.wordAnimation=e.caption.wordAnimation),e.caption.textBoxStyle&&(n.textBoxStyle=e.caption.textBoxStyle)):(e.bottomOffset!==void 0&&(n.bottomOffset=e.bottomOffset),e.words!==void 0&&(n.words=e.words),(e.appearedColor!==void 0||e.activeColor!==void 0||e.activeFillColor!==void 0||e.backgroundColor!==void 0||e.isKeyWordColor!==void 0)&&(n.colors={},e.appearedColor!==void 0&&(n.colors.appeared=e.appearedColor),e.activeColor!==void 0&&(n.colors.active=e.activeColor),e.activeFillColor!==void 0&&(n.colors.activeFill=e.activeFillColor),e.backgroundColor!==void 0&&(n.colors.background=e.backgroundColor),e.isKeyWordColor!==void 0&&(n.colors.keyword=e.isKeyWordColor)),e.preservedColorKeyWord!==void 0&&(n.preserveKeywordColor=e.preservedColorKeyWord),e.videoWidth!==void 0&&(n.videoWidth=e.videoWidth),e.videoHeight!==void 0&&(n.videoHeight=e.videoHeight)),n.initialLayoutApplied=!0;const s=new Nn(t,n);return s.left=e.left,s.top=e.top,s.width=e.width,s.height=e.height,s.angle=e.angle,s.display.from=e.display.from,s.display.to=e.display.to,s.duration=e.duration,s.playbackRate=e.playbackRate,s.zIndex=e.zIndex,s.opacity=e.opacity,s.flip=e.flip,s.wordsPerLine=e.wordsPerLine??"multiple",e.animation&&s.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(s.id=e.id),e.effects&&(s.effects=e.effects),await s.ready,s}getVisibleHandles(){return["mr","mb","br","rot"]}drawRoundedTiktokPath(e,t,i,n){if(t.length===0)return;const s=Math.max(i*.8,15);let o=!0,a=0;for(;o&&a<5;){o=!1,a++;for(let h=0;h<t.length;h++)for(let d=h+1;d<t.length;d++){const f=t[h].x+t[h].w,p=t[d].x+t[d].w;if(Math.abs(f-p)>.1&&Math.abs(f-p)<s){const m=Math.max(f,p);t[h].w=m-t[h].x,t[d].w=m-t[d].x,o=!0}if(Math.abs(t[h].x-t[d].x)>.1&&Math.abs(t[h].x-t[d].x)<s){const m=Math.min(t[h].x,t[d].x);t[h].w+=t[h].x-m,t[h].x=m,t[d].w+=t[d].x-m,t[d].x=m,o=!0}}}const l=[];l.push({x:t[0].x,y:t[0].y}),l.push({x:t[0].x+t[0].w,y:t[0].y});for(let h=0;h<t.length-1;h++){const d=t[h],f=t[h+1];if(Math.abs(d.x+d.w-(f.x+f.w))>.1){const p=(d.y+d.h+f.y)/2;l.push({x:d.x+d.w,y:p}),l.push({x:f.x+f.w,y:p})}}l.push({x:t[t.length-1].x+t[t.length-1].w,y:t[t.length-1].y+t[t.length-1].h}),l.push({x:t[t.length-1].x,y:t[t.length-1].y+t[t.length-1].h});for(let h=t.length-1;h>0;h--){const d=t[h],f=t[h-1];if(Math.abs(d.x-f.x)>.1){const p=(d.y+f.y+f.h)/2;l.push({x:d.x,y:p}),l.push({x:f.x,y:p})}}e.clear();const u=l[l.length-1],c=l[0];e.moveTo((u.x+c.x)/2,(u.y+c.y)/2);for(let h=0;h<l.length;h++){const d=l[h],f=l[(h+1)%l.length];e.arcTo(d.x,d.y,(d.x+f.x)/2,(d.y+f.y)/2,i)}e.fill({color:n,alpha:1})}}let Fl=class Wn extends zn{type="Image";ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t){let i=null,n;if(e.startsWith("blob:"))try{const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch image: ${o.status} ${o.statusText}`);const a=await o.blob();n=await createImageBitmap(a);try{i=Q.from(n)}catch(l){Ee.warn("Failed to create Pixi texture from bitmap:",l)}}catch(o){throw Ee.error(`Failed to load blob image from ${e}`,o),o}else n=await No.getImageBitmap(e);if(!n)throw new Error(`Failed to load image from ${e}`);const s=new Wn(n,t||e);return i&&(s.pixiTexture=i),s}getTexture(){return this.pixiTexture}constructor(e,t){super(),this.src=t!==void 0?t:"";const i=n=>{this.img=n,this._meta.width=n.width,this._meta.height=n.height,this._meta.duration=1/0;const s={...this._meta};return this.width=this.width===0?s.width:this.width,this.height=this.height===0?s.height:this.height,this.duration===0&&s.duration!==1/0&&(this.duration=s.duration,this.display.to=this.display.from+this.duration),s};if(e instanceof ReadableStream)this.ready=new Response(e).blob().then(n=>createImageBitmap(n)).then(i);else if(e instanceof ImageBitmap)this.ready=Promise.resolve(i(e));else if(Array.isArray(e)&&e.every(n=>n instanceof VideoFrame)){this.frames=e;const n=this.frames[0];if(n==null)throw Error("The frame count must be greater than 0");this._meta={width:n.displayWidth,height:n.displayHeight,duration:this.frames.reduce((o,a)=>o+(a.duration??0),0)};const s={...this._meta,duration:1/0};this.width=this.width===0?s.width:this.width,this.height=this.height===0?s.height:this.height,this.duration===0&&s.duration!==1/0&&(this.duration=s.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(s)}else if("type"in e)this.ready=this.initAnimateImg(e.stream,e.type).then(()=>{const n={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),n});else throw Error("Illegal arguments")}async initAnimateImg(e,t){this.frames=await LL(e,t);const i=this.frames[0];if(i==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((n,s)=>n+(s.duration??0),0),width:i.codedWidth,height:i.codedHeight},Ee.info("Image ready:",this._meta)}tickInterceptor=async(e,t)=>t;async tick(e){if(this.img!=null)return await this.tickInterceptor(e,{video:await createImageBitmap(this.img),state:"success"});const t=e%this._meta.duration;return await this.tickInterceptor(e,{video:(this.frames.find(i=>t>=i.timestamp&&t<=i.timestamp+(i.duration??0))??this.frames[0]).clone(),state:"success"})}async split(e){if(await this.ready,this.img!=null)return[new Wn(await createImageBitmap(this.img),this.src),new Wn(await createImageBitmap(this.img),this.src)];let t=-1;for(let s=0;s<this.frames.length;s++){const o=this.frames[s];if(!(e>o.timestamp)){t=s;break}}if(t===-1)throw Error("Not found frame by time");const i=this.frames.slice(0,t).map(s=>new VideoFrame(s)),n=this.frames.slice(t).map(s=>new VideoFrame(s,{timestamp:s.timestamp-e}));return[new Wn(i,this.src),new Wn(n,this.src)]}async clone(){await this.ready;const e=this.img==null?this.frames.map(i=>i.clone()):await createImageBitmap(this.img),t=new Wn(e,this.src);return t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t.transition=this.transition,t}addEffect(e){this.effects.push(e)}editEffect(e,t){const i=this.effects.find(n=>n.id===e);i&&Object.assign(i,t)}removeEffect(e){const t=this.effects.findIndex(i=>i.id===e);t!==-1&&this.effects.splice(t,1)}destroy(){Ee.info("Image destroy"),this.img?.close(),this.frames.forEach(e=>e.close()),this.pixiTexture=null,super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Image",id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Image")throw new Error(`Expected Image, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("Image requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let t;try{const i=await No.getImageBitmap(e.src);t=new Wn(i,e.src)}catch(i){throw i instanceof Error&&i.message.includes("could not be decoded")?new Error(`Failed to decode image from ${e.src}. The image may be decoded, in an unsupported format, or there may be CORS issues.`):i}return t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.style&&(t.style={...t.style,...e.style}),e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),e.effects&&(t.effects=e.effects),e.transition&&(t.transition=e.transition),e.chromaKey&&(t.chromaKey={...t.chromaKey,...e.chromaKey}),e.colorAdjustment&&(t.colorAdjustment={...t.colorAdjustment,...e.colorAdjustment}),e.locked!==void 0&&(t.locked=e.locked),t}};function jb(r,e){const t={},i=e.videoTracks[0];if(i!=null){const s=mq(r.getTrackById(i.id))?.buffer,o=pq(i.codec);o&&(t.videoTrackConf={timescale:i.timescale,duration:i.duration,width:i.video.width,height:i.video.height,brands:e.brands,type:o.type,[o.descKey]:s}),t.videoDecoderConf={codec:i.codec,codedHeight:i.video.height,codedWidth:i.video.width,description:s}}const n=e.audioTracks[0];if(n!=null){const s=gq(r),o=s?vq(s):{};t.audioTrackConf={timescale:n.timescale,samplerate:o.sampleRate??n.audio.sample_rate,channel_count:o.numberOfChannels??n.audio.channel_count,hdlr:"soun",type:n.codec.startsWith("mp4a")?"mp4a":n.codec,description:s},t.audioDecoderConf={codec:o.codec??st.codec,numberOfChannels:o.numberOfChannels??n.audio.channel_count,sampleRate:o.sampleRate??n.audio.sample_rate}}return t}function pq(r){return r.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:r.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:null}function mq(r){for(const e of r.mdia.minf.stbl.stsd.entries){const t=e.avcC??e.hvcC??e.av1C??e.vpcC;if(t!=null){const i=new Qn.DataStream(void 0,0,void 0);return t.write(i),new Uint8Array(i.buffer.slice(8))}}}function gq(r,e="mp4a"){return r.moov?.traks.flatMap(t=>t.mdia.minf.stbl.stsd.entries).find(t=>t.type===e)}function vq(r){const e=r.esd?.descs?.[0];if(!e)return{};let t=`mp4a.${e.oti.toString(16)}`;const i=e.descs?.[0];if(!i)return t.endsWith(".40")&&(t+=".2"),{codec:t};const n=i.data;if(!n)return{codec:t};const s=(n[0]&248)>>3;t+=`.${s}`;const o=(n[0]&7)<<1|n[1]>>7,a=(n[1]&120)>>3;return{codec:t,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][o],numberOfChannels:a}}async function xq(r,e,t){const i=Qn.createFile(!1);i.onReady=o=>{e({mp4boxFile:i,info:o}),[o.videoTracks[0],o.audioTracks[0]].forEach(a=>{if(a){const l=a.video?"video":"audio";i.setExtractionOptions(a.id,l,{nbSamples:100})}}),i.start()},i.onSamples=t;let n=0;const s=30*1024*1024;for(;;){const o=await r.read(s,{at:n});if(o.byteLength===0)break;o.fileStart=n;const a=i.appendBuffer(o);if(a==null)break;n=a}i.stop()}function yq(r){if(r?.length!==9)return{};const e=new Int32Array(r.buffer),t=c=>c/65536,i=t(e[0]),n=t(e[1]),s=t(e[3]),o=t(e[4]),a=t(e[6]),l=t(e[7]),u=e[8]/(1<<30);return{scaleX:Math.sqrt(i*i+s*s),scaleY:Math.sqrt(n*n+o*o),rotationRad:Math.atan2(s,i),rotationDeg:Math.atan2(s,i)*180/Math.PI,translateX:a,translateY:l,perspective:u}}function bq(r,e,t){const i=(Math.round(t/90)*90+360)%360;if(i===0)return u=>u;const n=i===90||i===270,s=n?e:r,o=n?r:e,a=new OffscreenCanvas(s,o),l=a.getContext("2d");return l.translate(s/2,o/2),l.rotate(-i*Math.PI/180),l.translate(-r/2,-e/2),u=>{if(!u)return null;l.drawImage(u,0,0);const c=new VideoFrame(a,{timestamp:u.timestamp,duration:u.duration??void 0});return u.close(),c}}let Kb=0;function Qb(r){return r.kind==="file"&&r.createReader instanceof Function}class wr extends zn{type="Video";insId=Kb++;logger=Ee.create(`Video id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const e=await this.localFile.getOriginFile();if(e==null)throw Error("Video localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:t,size:i})=>e.slice(t,t+i))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=e=>e;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t={}){const i=await No.getReadableStream(e),n=new wr(i,{},e);return await n.ready,t.x!==void 0&&(n.left=t.x),t.y!==void 0&&(n.top=t.y),t.width!==void 0&&(n.width=t.width),t.height!==void 0&&(n.height=t.height),n}constructor(e,t={},i){if(super(),this.src=i!==void 0?i:"",!(e instanceof ReadableStream)&&!Qb(e)&&!Array.isArray(e.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...t},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof t.audio=="object"&&"volume"in t.audio?t.audio.volume:t.volume??1;const n=async s=>(await Ys(this.localFile,s),this.localFile);this.localFile=Qb(e)?e:"localFile"in e?e.localFile:q0(),this.ready=(e instanceof ReadableStream?n(e).then(s=>Nk(s,this.opts)):Qb(e)?Nk(e,this.opts):Promise.resolve(e)).then(async({videoSamples:s,audioSamples:o,decoderConf:a,headerBoxPos:l,parsedMatrix:u})=>{this.videoSamples=s,this.audioSamples=o,this.decoderConf=a,this.headerBoxPos=l,this.parsedMatrix=u;const{videoFrameFinder:c,audioFrameFinder:h}=wq({video:a.video==null?null:{...a.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:a.audio},await this.localFile.createReader(),s,o,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=c,this.audioFrameFinder=h;const{codedWidth:d,codedHeight:f}=a.video??{};d&&f&&(this.vfRotater=bq(d,f,u.rotationDeg)),this._meta=_q(a,s,o,u.rotationDeg),this.logger.info("Video meta:",this._meta);const p={...this._meta};this.width=this.width===0?p.width:this.width,this.height=this.height===0?p.height:this.height,this.trim.to=this.trim.to===0?p.duration:Math.min(this.trim.to,p.duration),this.trim.from=Math.min(this.trim.from,this.trim.to);const m=(this.trim.to-this.trim.from)/this.playbackRate;return this.duration=this.duration===0?m:this.duration,Math.abs(this.duration-m)>1&&(this.duration=m),this.display.to=this.display.from+this.duration,this.on("propsChange",g=>{g.volume!==void 0&&this.audioFrameFinder&&this.audioFrameFinder.setVolume(g.volume)}),p})}tickInterceptor=async(e,t)=>t;async tick(e){const t=e+this.trim.from;if(t>this.trim.to||t>this._meta.duration)return await this.tickInterceptor(e,{audio:await this.audioFrameFinder?.find(t)??[],state:"done"});const[i,n]=await Promise.all([this.audioFrameFinder?.find(t)??[],this.videoFrameFinder?.find(t).then(this.vfRotater)]);return n==null?await this.tickInterceptor(e,{audio:i,state:"success"}):await this.tickInterceptor(e,{video:n,audio:i,state:"success"})}thumbAborter=new AbortController;thumbFinder=null;async thumbnails(e=100,t){this.thumbAborter.abort(),this.thumbAborter=new AbortController;const i=this.thumbAborter.signal;await this.ready;const n="generate thumbnails aborted";if(i.aborted)throw Error(n);const{width:s,height:o}=this._meta,a=kq(e,Math.round(o*(e/s)),{quality:.1,type:"image/png"});return new Promise(async(l,u)=>{const c=[],h=this.decoderConf.video;if(h==null||this.videoSamples.length===0){l([]);return}let d=null;i.addEventListener("abort",()=>{u(Error(n))});try{const{start:f=0,end:p=this._meta.duration,step:m}=t??{};if(m){let g=f;for(this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null),d=new Hk(await this.localFile.createReader(),this.videoSamples,{...h,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__}),this.thumbFinder=d;g<=p&&!i.aborted;){const v=await d.find(g);if(v){const x=await a(v);c.push({ts:v.timestamp,img:x})}g+=m}if(c.length===0&&!i.aborted){const v=await d.find(0);if(v){const x=await a(v);c.push({ts:v.timestamp,img:x})}}}else await Bq(this.videoSamples,this.localFile,h,i,{start:f,end:p},async(g,v)=>{if(g!=null){const x=await a(g);c.push({ts:g.timestamp,img:x})}})}catch(f){u(f);return}finally{d&&(await d.destroy(),this.thumbFinder===d&&(this.thumbFinder=null))}l(c)})}async split(e){if(await this.ready,e<=0||e>=this._meta.duration)throw Error("time out of bounds");const[t,i]=Eq(this.videoSamples,e),[n,s]=Pq(this.audioSamples,e),o=new wr({localFile:this.localFile,videoSamples:t??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),a=new wr({localFile:this.localFile,videoSamples:i??[],audioSamples:s??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await Promise.all([o.ready,a.ready]),[o,a]}addEffect(e){this.effects.push(e)}editEffect(e,t){const i=this.effects.find(n=>n.id===e);i&&Object.assign(i,t)}removeEffect(e){const t=this.effects.findIndex(i=>i.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=new wr({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await e.ready,e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e.id=this.id,e.effects=[...this.effects],e}async splitTrack(){await this.ready;const e=[];if(this.videoSamples.length>0){const t=new wr({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[],decoderConf:{video:this.decoderConf.video,audio:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}if(this.audioSamples.length>0){const t=new wr({localFile:this.localFile,videoSamples:[],audioSamples:[...this.audioSamples],decoderConf:{audio:this.decoderConf.audio,video:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}return e}cleanupThumbnails=async()=>{this.thumbAborter.abort(),this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null)};destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("Video destroy"),super.destroy(),this.thumbAborter.abort(),this.thumbFinder?.destroy(),this.thumbFinder=null,this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(e=!1){return{...super.toJSON(e),type:"Video",audio:this.audio,volume:this.volume,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Video")throw new Error(`Expected Video, got ${e.type}`);const t=e.audio!==void 0?{audio:e.audio,volume:e.volume}:{volume:e.volume},i=await No.getReadableStream(e.src),n=new wr(i,t,e.src);return n.left=e.left,n.top=e.top,n.width=e.width,n.height=e.height,n.angle=e.angle,n.display.from=e.display.from,n.display.to=e.display.to,n.duration=e.duration,n.playbackRate=e.playbackRate,n.zIndex=e.zIndex,n.opacity=e.opacity,n.flip=e.flip,e.style&&(n.style={...n.style,...e.style}),e.animation&&n.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(n.id=e.id),e.effects&&(n.effects=e.effects),e.transition&&(n.transition=e.transition),e.trim&&(n.trim.from=e.trim.from,n.trim.to=e.trim.to),e.volume!==void 0&&(n.volume=e.volume),e.chromaKey&&(n.chromaKey={...n.chromaKey,...e.chromaKey}),e.colorAdjustment&&(n.colorAdjustment={...n.colorAdjustment,...e.colorAdjustment}),e.locked!==void 0&&(n.locked=e.locked),n}async createPlaybackElement(){await this.ready;const t=this.localFile;if(!t||typeof t.getOriginFile!="function")throw new Error("Video does not have a local file for playback");const i=await t.getOriginFile();if(!i)throw new Error("Failed to get origin file from VideoClip");const n=URL.createObjectURL(i),s=document.createElement("video");return s.crossOrigin="anonymous",s.muted=!0,s.autoplay=!1,s.playsInline=!0,s.preload="auto",s.loop=!1,s.src=n,await new Promise((o,a)=>{const l=()=>{s.removeEventListener("loadeddata",l),s.removeEventListener("error",u),s.pause(),s.currentTime=0,o()},u=()=>{s.removeEventListener("loadeddata",l),s.removeEventListener("error",u),a(new Error("Failed to load video"))};s.addEventListener("loadeddata",l,{once:!0}),s.addEventListener("error",u,{once:!0}),s.load()}),{element:s,objectUrl:n}}async play(e,t){const i=e,n=t+this.trim.from/1e6;if(Math.abs(i.currentTime-n)>.1&&(i.currentTime=n),i.muted=!1,i.paused)try{await i.play()}catch{try{await i.play()}catch(o){console.warn("Failed to play video:",o)}}}pause(e){const t=e;t.pause(),t.muted=!0}async seek(e,t){const i=e,n=t+this.trim.from/1e6;return i.pause(),i.currentTime=n,new Promise(s=>{if(Math.abs(i.currentTime-t)<.01){s();return}const o=()=>{i.removeEventListener("seeked",o),s()};i.addEventListener("seeked",o,{once:!0}),setTimeout(()=>{i.removeEventListener("seeked",o),s()},500)})}syncPlayback(e,t,i){const n=e,s=(this.trim.to-this.trim.from)/1e6,o=i>=0&&i<s,a=i+this.trim.from/1e6;n.volume=this.volume,t&&o?n.paused?this.play(n,i).catch(console.warn):(n.muted&&(n.muted=!1),(n.ended||n.currentTime>=this.trim.to/1e6)&&(n.currentTime=a,n.play().catch(console.warn))):(n.paused||n.pause(),n.muted=!0,o&&Math.abs(n.currentTime-a)>.1&&(n.currentTime=a))}cleanupPlayback(e,t){const i=e;i.pause(),i.removeAttribute("src"),i.load(),t&&URL.revokeObjectURL(t)}async scaleToFit(e,t){await this.ready;const{width:i,height:n}=this.meta;if(i===0||n===0)return;const s=Math.min(e/i,t/n);this.width=i*s,this.height=n*s}async scaleToFill(e,t){await this.ready;const{width:i,height:n}=this.meta;if(i===0||n===0)return;const s=Math.max(e/i,t/n);this.width=i*s,this.height=n*s}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}}function _q(r,e,t,i){const n={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(r.video!=null&&e.length>0){n.width=r.video.codedWidth??0,n.height=r.video.codedHeight??0;const a=(Math.round(i/90)*90+360)%360;(a===90||a===270)&&([n.width,n.height]=[n.height,n.width])}r.audio!=null&&t.length>0&&(n.audioSampleRate=st.sampleRate,n.audioChanCount=st.channelCount);let s=0,o=0;if(e.length>0)for(let a=e.length-1;a>=0;a--){const l=e[a];if(!l.deleted){s=l.cts+l.duration;break}}if(t.length>0){const a=t.at(-1);o=a.cts+a.duration}return n.duration=Math.max(s,o),n}function wq(r,e,t,i,n){return{audioFrameFinder:n===0||r.audio==null||i.length===0?null:new Tq(e,i,r.audio,{volume:n,targetSampleRate:st.sampleRate}),videoFrameFinder:r.video==null||t.length===0?null:new Hk(e,t,r.video)}}async function Nk(r,e={}){let t=null;const i={video:null,audio:null};let n=[],s=[],o=[];const a={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let l=-1,u=-1;const c=await r.createReader();await xq(c,async d=>{t=d.info;const f=d.mp4boxFile.ftyp;o.push({start:f.start,size:f.size});const p=d.mp4boxFile.moov;o.push({start:p.start,size:p.size}),Object.assign(a,yq(t.videoTracks[0]?.matrix));let{videoDecoderConf:m,audioDecoderConf:g}=jb(d.mp4boxFile,d.info);if(i.video=m??null,i.audio=g??null,m==null&&g==null&&Ee.error("Video no video and audio track"),g!=null){const{supported:v}=await AudioDecoder.isConfigSupported(g);v||Ee.error(`Video audio codec is not supported: ${g.codec}`)}if(m!=null){const{supported:v}=await VideoDecoder.isConfigSupported(m);v||Ee.error(`Video video codec is not supported: ${m.codec}`)}Ee.info("mp4BoxFile moov ready",{...d.info,tracks:null,videoTracks:null,audioTracks:null},i)},(d,f,p)=>{if(f==="video"){l===-1&&(l=p[0].dts);for(const m of p)n.push(Gk(m,l,"video"))}else if(f==="audio"&&e.audio){u===-1&&(u=p[0].dts);for(const m of p)s.push(Gk(m,u,"audio"))}}),await c.close();const h=n.at(-1)??s.at(-1);if(t==null)throw Error("Video stream is done, but not emit ready");if(h==null)throw Error("Video stream not contain any sample");return Jb(n),Ee.info("mp4 stream parsed"),{videoSamples:n,audioSamples:s,decoderConf:i,headerBoxPos:o,parsedMatrix:a}}function Gk(r,e=0,t){let i=r.offset;const n=t==="video"&&r.is_sync?Iq(r.data,r.description.type):-1;let s=r.size;return n>0&&(i+=n,s-=n),{...r,is_idr:n>=0,offset:i,size:s,cts:(r.cts-e)/r.timescale*1e6,dts:(r.dts-e)/r.timescale*1e6,duration:r.duration/r.timescale*1e6,timescale:1e6,data:t==="video"?null:r.data}}class Hk{constructor(e,t,i){this.localFileReader=e,this.samples=t,this.conf=i}decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async e=>{(this.decoder==null||this.decoder.state==="closed"||e<=this.timestamp||e-this.timestamp>3e6)&&this.reset(e),this.curAborter.abort=!0,this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const t=await this.parseFrame(e,this.decoder,this.curAborter);return this.sleepCnt=0,t};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;parseFrame=async(e,t,i)=>{if(t==null||t.state==="closed"||i.abort)return null;if(this.videoFrames.length>0){const n=this.videoFrames[0];return e<n.timestamp?null:(this.videoFrames.shift(),e>n.timestamp+(n.duration??0)?(n.close(),await this.parseFrame(e,t,i)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(t).catch(s=>{throw this.predecodeErr=!0,this.reset(e),s}),n))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&t.decodeQueueSize>0){if(performance.now()-i.st>6e3)throw Error(`Video.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await Au(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(t)}catch(n){throw this.reset(e),n}}return await this.parseFrame(e,t,i)};decoding=!1;startDecode=async e=>{if(this.decoding||e.decodeQueueSize>600)return;let t=this.videoDecCursorIdx+1;if(t>this.samples.length)return;this.decoding=!0;let i=!1;for(;t<this.samples.length;t++){const n=this.samples[t];if(!i&&!n.deleted&&(i=!0),n.is_idr)break}if(i){const n=this.samples.slice(this.videoDecCursorIdx,t);if(n[0]?.is_idr!==!0)Ee.warn("First sample not idr frame");else{const s=performance.now(),o=await Vk(n,this.localFileReader),a=performance.now()-s;if(a>1e3){const l=n[0],u=n.at(-1),c=u.offset+u.size-l.offset;Ee.warn(`Read video samples time cost: ${Math.round(a)}ms, file chunk size: ${c}`)}if(e.state==="closed")return;this.lastVfDur=o[0]?.duration??0,Zb(e,o,{onDecodingError:l=>{if(this.downgradeSoftDecode)throw l;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,Ee.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=o.length}}this.videoDecCursorIdx=t,this.decoding=!1};reset=e=>{if(this.decoding=!1,this.videoFrames.forEach(i=>i.close()),this.videoFrames=[],e==null||e===0)this.videoDecCursorIdx=0;else{let i=0;for(let n=0;n<this.samples.length;n++){const s=this.samples[n];if(s.is_idr&&(i=n),!(s.cts<e)){this.videoDecCursorIdx=i;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const t={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:i=>{if(this.outputFrameCnt+=1,i.timestamp===-1){i.close();return}let n=i;i.duration==null&&(n=new VideoFrame(i,{duration:this.lastVfDur}),i.close()),this.videoFrames.push(n)},error:i=>{if(i.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,Ee.warn(i.message);return}const n=`VideoFinder VideoDecoder err: ${i.message}, config: ${JSON.stringify(t)}, state: ${JSON.stringify(this.getState())}`;throw Ee.error(n),Error(n)}}),this.decoder.configure(t)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:Kb,sleepCnt:this.sleepCnt,memInfo:Xk()});destroy=async()=>{if(this.curAborter.abort=!0,this.videoFrames.forEach(e=>e.close()),this.videoFrames=[],this.decoder&&this.decoder.state!=="closed")try{this.decoder.close()}catch{}this.decoder=null,this.localFileReader.close()}}function Sq(r,e){for(let t=0;t<e.length;t++){const i=e[t];if(r>=i.cts&&r<i.cts+i.duration)return t;if(i.cts>r)break}return 0}class Tq{constructor(e,t,i,n){this.localFileReader=e,this.samples=t,this.conf=i,this.volume=n.volume,this.sampleRate=n.targetSampleRate}volume=1;sampleRate;setVolume(e){this.volume=e,this.reset()}decoder=null;curAborter={abort:!1,st:performance.now()};find=async e=>{const t=e<=this.timestamp||e-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||t)&&this.reset(),t&&(this.timestamp=e,this.decCursorIdx=Sq(e,this.samples)),this.curAborter.abort=!0;const i=e-this.timestamp;this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const n=await this.parseFrame(Math.ceil(i*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,n};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(e,t=null,i)=>{if(t==null||i.abort||t.state==="closed"||e===0)return[];const n=this.pcmData.frameCnt-e;if(n>0)return n<st.sampleRate/10&&this.startDecode(t),Wk(this.pcmData,e);if(t.decoding){if(performance.now()-i.st>3e3)throw i.abort=!0,Error(`Video.tick audio timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await Au(15)}else{if(this.decCursorIdx>=this.samples.length-1)return Wk(this.pcmData,this.pcmData.frameCnt);this.startDecode(t)}return this.parseFrame(e,t,i)};startDecode=e=>{if(e.decodeQueueSize>10)return;const i=[];let n=this.decCursorIdx;for(;n<this.samples.length;){const s=this.samples[n];if(n+=1,!s.deleted&&(i.push(s),i.length>=10))break}this.decCursorIdx=n,e.decode(i.map(s=>new EncodedAudioChunk({type:"key",timestamp:s.cts,duration:s.duration,data:s.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=Cq(this.conf,{resampleRate:st.sampleRate,volume:this.volume},e=>{this.pcmData.data.push(e),this.pcmData.frameCnt+=e[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:Kb,sleepCnt:this.sleepCnt,memInfo:Xk()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function Cq(r,e,t){let i=0,n=0;const s=c=>{if(n+=1,c.length!==0){if(e.volume!==1)for(const h of c)for(let d=0;d<h.length;d++)h[d]*=e.volume;c.length===1&&(c=[c[0],c[0]]),t(c)}},o=Aq(s),a=e.resampleRate!==r.sampleRate;let l=new AudioDecoder({output:c=>{const h=oS(c);a?o(()=>gL(h,c.sampleRate,{rate:e.resampleRate,chanCount:c.numberOfChannels})):s(h),c.close()},error:c=>{c.message.includes("Codec reclaimed due to inactivity")||u("Video AudioDecoder err",c)}});l.configure(r);function u(c,h){const d=`${c}: ${h.message}, state: ${JSON.stringify({qSize:l.decodeQueueSize,state:l.state,inputCnt:i,outputCnt:n})}`;throw Ee.error(d),Error(d)}return{decode(c){i+=c.length;try{for(const h of c)l.decode(h)}catch(h){u("decode audio chunk error",h)}},close(){l.state!=="closed"&&l.close()},get decoding(){return i>n&&l.decodeQueueSize>0},get state(){return l.state},get decodeQueueSize(){return l.decodeQueueSize}}}function Aq(r){const e=[];let t=0;function i(o,a){e[a]=o,n()}function n(){const o=e[t];o!=null&&(r(o),t+=1,n())}let s=0;return o=>{const a=s;s+=1,o().then(l=>i(l,a)).catch(l=>i(l,a))}}function Wk(r,e){const t=[new Float32Array(e),new Float32Array(e)];let i=0,n=0;for(;n<r.data.length;){const[s,o]=r.data[n];if(i+s.length>e){const a=e-i;t[0].set(s.subarray(0,a),i),t[1].set(o.subarray(0,a),i),r.data[n][0]=s.subarray(a,s.length),r.data[n][1]=o.subarray(a,o.length);break}else t[0].set(s,i),t[1].set(o,i),i+=s.length,n++}return r.data=r.data.slice(n),r.frameCnt-=e,t}async function Vk(r,e){const t=r[0],i=r.at(-1);if(i==null)return[];const n=i.offset+i.size-t.offset;if(n<3e7){const s=new Uint8Array(await e.read(n,{at:t.offset}));return r.map(o=>{const a=o.offset-t.offset;return new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:s.subarray(a,a+o.size)})})}return await Promise.all(r.map(async s=>new EncodedVideoChunk({type:s.is_sync?"key":"delta",timestamp:s.cts,duration:s.duration,data:await e.read(s.size,{at:s.offset})})))}function Eq(r,e){if(r.length===0)return[];let t=0,i=0,n=-1;for(let l=0;l<r.length;l++){const u=r[l];if(n===-1&&e<u.cts&&(n=l-1),u.is_idr)if(n===-1)t=l;else{i=l;break}}const s=r[n];if(s==null)throw Error("Not found video sample by time");const o=r.slice(0,i===0?r.length:i).map(l=>({...l}));for(let l=t;l<o.length;l++){const u=o[l];e<u.cts&&(u.deleted=!0,u.cts=-1)}Jb(o);const a=r.slice(s.is_idr?n:t).map(l=>({...l,cts:l.cts-e}));for(const l of a)l.cts<0&&(l.deleted=!0,l.cts=-1);return Jb(a),[o,a]}function Pq(r,e){if(r.length===0)return[];let t=-1;for(let s=0;s<r.length;s++){const o=r[s];if(!(e>o.cts)){t=s;break}}if(t===-1)throw Error("Not found audio sample by time");const i=r.slice(0,t).map(s=>({...s})),n=r.slice(t).map(s=>({...s,cts:s.cts-e}));return[i,n]}function Zb(r,e,t){if(r.state==="configured"){for(let i=0;i<e.length;i++)r.decode(e[i]);r.flush().catch(i=>{if(!(i instanceof Error))throw i;if(i.message.includes("Decoding error")&&t.onDecodingError!=null){t.onDecodingError(i);return}if(!i.message.includes("Aborted due to close"))throw i})}}function Iq(r,e){if(e!=="avc1"&&e!=="hvc1")return 0;const t=new DataView(r.buffer);for(let i=0;i<r.byteLength-4;){if(e==="avc1"){const n=t.getUint8(i+4)&31;if(n===5||n===7||n===8)return i}else if(e==="hvc1"){const n=t.getUint8(i+4)>>1&63;if(n===19||n===20||n===32||n===33||n===34)return i}i+=t.getUint32(i)+4}return-1}function Jb(r){let e=0,t=null;for(const i of r)if(!i.deleted){if(i.is_sync&&(e+=1),e>=2)break;(t==null||i.cts<t.cts)&&(t=i)}t!=null&&t.cts<2e5&&(t.duration+=t.cts,t.cts=0)}function Xk(){try{const r=performance.memory;return{jsHeapSizeLimit:r.jsHeapSizeLimit,totalJSHeapSize:r.totalJSHeapSize,usedJSHeapSize:r.usedJSHeapSize,percentUsed:(r.usedJSHeapSize/r.jsHeapSizeLimit).toFixed(3),percentTotal:(r.totalJSHeapSize/r.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}async function Bq(r,e,t,i,n,s){const o=await e.createReader(),a=await Vk(r.filter(c=>!c.deleted&&c.is_sync&&c.cts>=n.start&&c.cts<=n.end),o);if(a.length===0||i.aborted){s(null,!0);return}let l=0;Zb(u(),a,{onDecodingError:c=>{Ee.warn("thumbnailsByKeyFrame",c),l===0?Zb(u(!0),a,{onDecodingError:h=>{o.close(),Ee.error("thumbnailsByKeyFrame retry soft deocde",h)}}):(s(null,!0),o.close())}});function u(c=!1){const h={...t,...c?{hardwareAcceleration:"prefer-software"}:{}},d=new VideoDecoder({output:f=>{l+=1;const p=l===a.length;s(f,p),p&&(o.close(),d.state!=="closed"&&d.close())},error:f=>{const p=`thumbnails decoder error: ${f.message}, config: ${JSON.stringify(h)}, state: ${JSON.stringify({qSize:d.decodeQueueSize,state:d.state,outputCnt:l,inputCnt:a.length})}`;throw Ee.error(p),Error(p)}});return i.addEventListener("abort",()=>{o.close(),d.state!=="closed"&&d.close()}),d.configure(h),d}}function kq(r,e,t){return async i=>{try{const n=Math.max(1,Math.round(r)),s=Math.max(1,Math.round(e));Ee.info(`[Video.convtr] START: ${n}x${s}, ts: ${i.timestamp}`),Ee.info("[Video.convtr] Creating OffscreenCanvas");const o=new OffscreenCanvas(n,s);Ee.info("[Video.convtr] Getting Context");const a=o.getContext("2d");Ee.info("[Video.convtr] Drawing image"),a.drawImage(i,0,0,n,s),Ee.info("[Video.convtr] Closing VideoFrame"),i.close(),Ee.info("[Video.convtr] Calling convertToBlob");const l=await o.convertToBlob(t);return Ee.info(`[Video.convtr] FINISHED: ${l.size} bytes`),l}catch(n){throw Ee.error(`[Video.convtr] ERROR: ${n?.message||n}`),n}}}class Zi extends zn{type="Text";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}get width(){return this._width}set width(e){Math.abs(this.width-e)<.1||(this._width=e,this.refreshText().then(()=>{this.emit("propsChange",{width:e})}))}get height(){return this._height}set height(e){Math.abs(this.height-e)<.1||(this._height=e,this.refreshText().then(()=>{this.emit("propsChange",{height:e})}))}_lastContentWidth=0;_lastContentHeight=0;_text="";get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this.originalOpts&&this.textStyle&&this.refreshText().then(()=>{this.emit("propsChange",{text:e})}))}get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,fill:this.originalOpts.fill,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,dropShadow:this.originalOpts.dropShadow?{color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing,textCase:this.originalOpts.textCase,textDecoration:this.originalOpts.textDecoration}}set style(e){this.updateStyle(e)}get textAlign(){return this.originalOpts.align||this.originalOpts.textAlign||"left"}set textAlign(e){this.updateStyle({align:e})}get verticalAlign(){return this.originalOpts.verticalAlign||this.originalOpts.textDecoration||"top"}set verticalAlign(e){["underline","overline","strikethrough","line-through"].includes(e)?(this.updateStyle({textDecoration:e==="strikethrough"?"line-through":e}),this.originalOpts.verticalAlign=e):this.updateStyle({verticalAlign:e})}get textCase(){return this.originalOpts.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}pixiTextContainer=null;wordTexts=[];textStyle;textStyleBase;renderTexture=null;externalRenderer=null;pixiApp=null;originalOpts;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];constructor(e,t={},i){super(),this.originalOpts={...t},this.text=e,this.externalRenderer=i??null;const n=this.createStyleFromOpts(t),{wordWrap:s,wordWrapWidth:o,lineHeight:a,letterSpacing:l,fill:u,...c}=n,h=new Bt(n),d=new Bt(c);this.textStyle=h,this.textStyleBase=d,this.ready=(async()=>(await this.refreshText(),{...this._meta}))()}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("TextClip: Failed to create renderer. Please provide a renderer via constructor or setRenderer() method.");return this.pixiApp.renderer}async getTexture(){return this.pixiTextContainer==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture)}async tick(e){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("Text not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture});const i=this.renderTexture.source?.resource?.source;let n;if(i instanceof HTMLCanvasElement)n=await createImageBitmap(i);else if(i instanceof OffscreenCanvas)n=await createImageBitmap(i);else{const a=(await this.getRenderer()).extract.canvas(this.renderTexture);if(a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas)n=await createImageBitmap(a);else{const l=this.renderTexture.width,u=this.renderTexture.height;throw new OffscreenCanvas(l,u).getContext("2d")==null?new Error("Failed to create 2d context for fallback rendering"):new Error("Unable to extract canvas from render texture")}}return{video:n,state:"success"}}async split(e){await this.ready;const t=await this.clone(),i=await this.clone();return[t,i]}animate(e){super.animate(e,this.pixiTextContainer)}addEffect(e){this.effects.push(e)}editEffect(e,t){const i=this.effects.find(n=>n.id===e);i&&Object.assign(i,t)}removeEffect(e){const t=this.effects.findIndex(i=>i.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.textStyle,t=this.originalOpts||{},i=o=>{if(o!=null){if(typeof o=="number")return o;if(o instanceof ye)return o.toNumber()}},n={fontSize:t.fontSize??e.fontSize,fontFamily:t.fontFamily??(Array.isArray(e.fontFamily)?e.fontFamily[0]:typeof e.fontFamily=="string"?e.fontFamily:"Roboto"),fontWeight:t.fontWeight??e.fontWeight,fontStyle:t.fontStyle??e.fontStyle,align:t.align??(e.align==="justify"?"left":e.align),textCase:t.textCase,textDecoration:t.textDecoration};if(t.fill&&typeof t.fill=="object"&&"type"in t.fill&&t.fill.type==="gradient")n.fill=t.fill;else{const o=i(e.fill);n.fill=o??16777215}if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke)n.stroke=t.stroke;else{const o=i(e.stroke);o!==void 0&&(n.stroke=o),n.strokeWidth=t.strokeWidth??e.strokeThickness??0}if(t.dropShadow)n.dropShadow=t.dropShadow;else if(e.dropShadow){const o=e.dropShadow,a=i(o.color);a!==void 0&&(n.dropShadow={color:a,alpha:o.alpha,blur:o.blur,angle:o.angle,distance:o.distance})}if(t.wordWrap!==void 0?(n.wordWrap=t.wordWrap,n.wordWrapWidth=t.wordWrapWidth):e.wordWrap&&(n.wordWrap=e.wordWrap,n.wordWrapWidth=e.wordWrapWidth),t.lineHeight!==void 0)n.lineHeight=t.lineHeight;else if(e.lineHeight!==void 0){const o=n.fontSize??e.fontSize??40;n.lineHeight=e.lineHeight/o}t.letterSpacing!==void 0?n.letterSpacing=t.letterSpacing:e.letterSpacing!==void 0&&(n.letterSpacing=e.letterSpacing);const s=new Zi(this.text,n);return await s.ready,this.copyStateTo(s),s.id=this.id,s.effects=[...this.effects],s}async updateStyle(e){let t={...e};e.style&&(t={...t,...e.style},delete t.style),this.originalOpts={...this.originalOpts,...t};const i=this.createStyleFromOpts(this.originalOpts),{wordWrap:n,wordWrapWidth:s,lineHeight:o,letterSpacing:a,fill:l,...u}=i,c=new Bt(u),h=new Bt(i);this.textStyle=h,this.textStyleBase=c,await this.refreshText(),this.emit("propsChange",e)}async refreshText(){const e=this.textStyle,t=this.textStyleBase;let i=this.text;const n=this.originalOpts.textCase;n==="uppercase"?i=i.toUpperCase():n==="lowercase"?i=i.toLowerCase():n==="title"&&(i=i.replace(/\w\S*/g,k=>k.charAt(0).toUpperCase()+k.substring(1).toLowerCase())),typeof document<"u"&&await document.fonts.ready,this.pixiTextContainer?this.pixiTextContainer.removeChildren():this.pixiTextContainer=new Ie;const s=i.split(/\s+/).filter(k=>k.length>0);this.wordTexts.forEach(k=>k.destroy()),this.wordTexts=s.map(k=>{const W=new kl({text:k,style:this.textStyle});return this.pixiTextContainer.addChild(W),W});const o=this.originalOpts.textDecoration||this.originalOpts.verticalAlign,a=this.originalOpts.lineHeight??1,l=e.fontSize??40,u=l*a,c=Ht.measureText(" ",t),h=new kl({text:" ",style:this.textStyleBase}),d=Math.ceil(h.getLocalBounds().width||h.width||c.width);h.destroy();const f=e.wordWrap&&e.wordWrapWidth>0?e.wordWrapWidth:1e5,p=[];let m=[],g=0,v=0;this.wordTexts.forEach(k=>{const W=k.getLocalBounds(),G=Math.ceil(W.width||k.width),J=Math.ceil(W.height||k.height),q=g+(g>0?d:0)+G;q<=f||m.length===0?(m.push(k),g=q,v=Math.max(v,J)):(m.length>0&&p.push({words:m,width:g,height:Math.max(v,u)}),m=[k],g=G,v=J)}),m.length>0&&p.push({words:m,width:g,height:Math.max(v,u)});let x=0,y=0;p.forEach(k=>{x=Math.max(x,k.width),y+=k.height});const b=x,T=y;let E=b;e.wordWrap&&e.wordWrapWidth>0&&(E=Math.max(E,e.wordWrapWidth));const C=T,P=this.width===0||Math.abs(this.width-this._lastContentWidth)<.1,_=this.height===0||Math.abs(this.height-this._lastContentHeight)<.1,S=P?E:Math.max(E,this.width||0),I=_?C:Math.max(C,this.height||0);this._lastContentWidth=E,this._lastContentHeight=C;let M=0;const O=this.originalOpts.verticalAlign||"top";O==="center"?M=(I-T)/2:O==="bottom"&&(M=I-T);let H=M;const K=new Je;let D=!1;p.forEach(k=>{let W=0;const G=this.textAlign;G==="center"?W=(S-k.width)/2:G==="right"&&(W=S-k.width);const J=W;if(k.words.forEach((q,_e)=>{q.x=Math.round(W),q.y=Math.round(H),W+=(q.getLocalBounds().width||q.width)+(_e<k.words.length-1?d:0)}),o&&o!=="none"&&["underline","overline","strikethrough","line-through"].includes(o)){D=!0;const q=o==="strikethrough"?"line-through":o,_e=Math.max(1,l/12);let Re=16777215;typeof e.fill=="number"?Re=e.fill:e.fill&&typeof e.fill=="object"&&"fill"in e.fill&&(Re=16777215);let ge=0;q==="underline"?ge=k.height:q==="line-through"?ge=k.height/2:q==="overline"&&(ge=0),K.rect(J,H+ge,k.width,_e),K.fill(Re)}H+=k.height}),D&&this.pixiTextContainer.addChild(K),this.renderTexture&&this.renderTexture.destroy(),this.renderTexture=Ot.create({width:S,height:I}),this._meta.width=S,this._meta.height=I,this._width=S,this._height=I,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration)}createStyleFromOpts(e){const t=e.fontSize??40,i=e.lineHeight??1,n={fontSize:t,fontFamily:e.fontFamily??"Roboto",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",align:e.align??"left",wordWrap:e.wordWrap??!1,wordWrapWidth:e.wordWrapWidth??100,lineHeight:t*i,letterSpacing:e.letterSpacing??0};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const s=new zr(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:o,color:a})=>{const l=typeof a=="number"?a:xt(a)??16777215;s.addColorStop(o,l)}),n.fill={fill:s}}else{const{color:s,alpha:o}=Ln(e.fill);n.fill=s,o<1&&(n.fillAlpha=o)}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const s=xt(e.stroke.color);s!==void 0&&(n.stroke={color:s,width:e.stroke.width,join:e.stroke.join,cap:e.stroke.cap,miterLimit:e.stroke.miterLimit})}else{const s=xt(e.stroke),o=e.strokeWidth??0;s!==void 0&&o>0?n.stroke={color:s,width:o}:e.strokeWidth&&e.strokeWidth>0&&(n.stroke={color:0,width:e.strokeWidth})}if(e.dropShadow){const s=xt(e.dropShadow.color);s!==void 0&&(n.dropShadow={color:s,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}return n}destroy(){if(!this.destroyed){Ee.info("Text destroy");try{this.pixiTextContainer!=null&&(this.pixiTextContainer.destroyed||this.pixiTextContainer.destroy({children:!0}))}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),i={};return this.originalOpts.fontSize!==void 0&&(i.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(i.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontWeight!==void 0&&(i.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(i.fontStyle=this.originalOpts.fontStyle),this.originalOpts.fill!==void 0&&(i.color=this.originalOpts.fill),this.originalOpts.align!==void 0&&(i.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(i.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(i.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(i.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(i.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?i.stroke={color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:i.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.dropShadow&&(i.shadow={color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}),{...t,type:"Text",text:this.text,style:i,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Text")throw new Error(`Expected Text, got ${e.type}`);const t=e.text||"",i=e.style||{},n={};i.fontSize!==void 0&&(n.fontSize=i.fontSize),i.fontFamily!==void 0&&(n.fontFamily=i.fontFamily),i.fontWeight!==void 0&&(n.fontWeight=i.fontWeight),i.fontStyle!==void 0&&(n.fontStyle=i.fontStyle),i.color!==void 0&&(n.fill=i.color),i.align!==void 0&&(n.align=i.align),i.wordWrap!==void 0&&(n.wordWrap=i.wordWrap),i.wordWrapWidth!==void 0&&(n.wordWrapWidth=i.wordWrapWidth),i.lineHeight!==void 0&&(n.lineHeight=i.lineHeight),i.letterSpacing!==void 0&&(n.letterSpacing=i.letterSpacing),i.stroke&&(i.stroke.join||i.stroke.cap||i.stroke.miterLimit!==void 0?n.stroke={color:i.stroke.color,width:i.stroke.width,join:i.stroke.join,cap:i.stroke.cap,miterLimit:i.stroke.miterLimit}:(n.stroke=i.stroke.color,n.strokeWidth=i.stroke.width)),i.shadow&&(n.dropShadow={color:i.shadow.color,alpha:i.shadow.alpha,blur:i.shadow.blur,distance:i.shadow.distance,angle:i.shadow.angle});const s=new Zi(t,n);return s.left=e.left,s.top=e.top,s.width=e.width,s.height=e.height,s.angle=e.angle,s.display.from=e.display.from,s.display.to=e.display.to,s.duration=e.duration,s.playbackRate=e.playbackRate,s.zIndex=e.zIndex,s.opacity=e.opacity,s.flip=e.flip,e.animation&&s.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(s.id=e.id),e.effects&&(s.effects=e.effects),await s.ready,s}getVisibleHandles(){return["mr","mb","br","rot"]}}function Rq(r){return r.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase())}class Ji extends zn{type="Effect";ready;_meta={duration:5e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effect;constructor(e){super(),this.effect={id:`eff_${Date.now()}`,key:e,name:e},this.name=Rq(e),this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Ji(this.effect.key);return this.copyStateTo(e),e.effect={...this.effect},e.id=this.id,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),i=await this.clone();return[t,i]}toJSON(e=!1){return{...super.toJSON(e),type:"Effect",effect:this.effect,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Effect")throw new Error(`Expected Effect, got ${e.type}`);const t=new Ji(e.effect.key);return t.effect=e.effect,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}class Ml extends zn{type="Placeholder";meta={width:0,height:0,duration:0};constructor(e,t={},i="Placeholder"){super(),this.type=i,this.src=e,this.meta={width:t.width||1280,height:t.height||720,duration:t.duration||5e6},this.width=this.meta.width,this.height=this.meta.height,this.duration=this.meta.duration,this.trim.to=this.duration,this.display.to=this.display.from+this.duration,this.ready=Promise.resolve(this.meta)}canvas=null;ctx=null;animationRafId=null;renderPending=!1;async tick(e){this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.width=this.meta.width,this.canvas.height=this.meta.height,this.ctx=this.canvas.getContext("2d"));const{canvas:t,ctx:i}=this;if(i){const{width:s,height:o}=t;if(s>0&&o>0){i.fillStyle="#1e1e1e",i.fillRect(0,0,s,o);const a=s/2,l=o/2,u=100,c=u/4,h=performance.now()/2e3*Math.PI*2;i.save();const d=i.createConicGradient(h,a,l);d.addColorStop(0,"#ffffff"),d.addColorStop(.2,"#ffffff"),d.addColorStop(.5,"rgba(255, 255, 255, 0.4)"),d.addColorStop(.8,"rgba(255, 255, 255, 0.1)"),d.addColorStop(1,"rgba(255, 255, 255, 0)"),i.strokeStyle=d,i.lineWidth=c,i.lineCap="round",i.beginPath(),i.arc(a,l,u,h,h+Math.PI*1.5),i.stroke(),i.restore(),i.strokeStyle="#333333",i.lineWidth=10,i.strokeRect(0,0,s,o)}}if(this.renderPending=!1,this.animationRafId===null){const s=()=>{if(this.destroyed){this.animationRafId=null;return}this.renderPending||(this.renderPending=!0,this.emit("request-render")),this.animationRafId=requestAnimationFrame(s)};this.animationRafId=requestAnimationFrame(s)}return{video:t.width>0&&t.height>0?await createImageBitmap(t):null,state:"success",audio:[]}}async clone(){const e=new Ml(this.src,this.meta);return this.copyStateTo(e),e.id=this.id,e}async split(e){const t=await this.clone(),i=await this.clone();return t.trim.to=e+this.trim.from,i.trim.from=e+this.trim.from,t.duration=t.trim.to-t.trim.from,i.duration=i.trim.to-i.trim.from,t.display.to=t.display.from+t.duration,i.display.from=t.display.to,i.display.to=i.display.from+i.duration,[t,i]}static async fromObject(e){if(e.type!=="Placeholder")throw new Error(`Expected Placeholder, got ${e.type}`);const t=new Ml(e.src,{width:e.width,height:e.height,duration:e.duration});return t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.id&&(t.id=e.id),await t.ready,t}}class Fi extends zn{type="Transition";ready;_meta={duration:2e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;transitionEffect;fromClipId=null;toClipId=null;constructor(e){super(),this.transitionEffect={id:`trans_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Fi(this.transitionEffect.key);return this.copyStateTo(e),e.fromClipId=this.fromClipId,e.toClipId=this.toClipId,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),i=await this.clone();return[t,i]}toJSON(e=!1){return{...super.toJSON(e),type:"Transition",transitionEffect:this.transitionEffect,fromClipId:this.fromClipId,toClipId:this.toClipId,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Transition")throw new Error(`Expected Transition, got ${e.type}`);const t=new Fi(e.transitionEffect.key);return t.transitionEffect=e.transitionEffect,t.fromClipId=e.fromClipId||null,t.toClipId=e.toClipId||null,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}function Yk(r,e){let t=!1;async function i(){const n=r.getReader();for(;!t;){const{value:s,done:o}=await n.read();if(o){e.onDone();return}await e.onChunk(s)}n.releaseLock(),await r.cancel()}return i().catch(console.error),()=>{t=!0}}class qk{readable;writable;inputBufOffset=0;isStreamCancelled=!1;constructor(){const e=Qn.createFile();this.readable=new ReadableStream({start:t=>this.initMP4Box(e,t),cancel:()=>{this.isStreamCancelled=!0,e.stop()}},{highWaterMark:50}),this.writable=new WritableStream({write:async t=>{if(this.isStreamCancelled)throw new Error("Stream cancelled");const i=t.buffer;i.fileStart=this.inputBufOffset,this.inputBufOffset+=i.byteLength,e.appendBuffer(i)},close:()=>{e.flush(),e.stop(),e.onFlush?.()},abort:t=>{Fq.error("SampleTransform writable aborted:",t),e.stop()}})}initMP4Box(e,t){e.onReady=n=>{[n.videoTracks[0],n.audioTracks[0]].forEach(s=>{s&&e.setExtractionOptions(s.id,s.video?"video":"audio",{nbSamples:100})}),t.enqueue({chunkType:"ready",data:{info:n,file:e}}),e.start()};const i={};e.onSamples=(n,s,o)=>{const a=o.map(l=>({...l}));t.enqueue({chunkType:"samples",data:{id:n,type:s,samples:a}}),i[n]=(i[n]??0)+o.length,e.releaseUsedSamples(n,i[n])},e.onFlush=()=>{t.close()},e.onError=n=>{t.error(new Error(`mp4box error: ${n}`))}}}const Fq={error:(...r)=>console.error("[SampleTransform]",...r)};function Mq(r){let e=0;const t=r.boxes,i=[];let n=0;async function s(){const p=f(t,e);e=t.length,i.forEach(({track:m,id:g})=>{const v=m.samples.at(-1);v!=null&&(n=Math.max(n,v.cts+v.duration)),r.releaseUsedSamples(g,m.samples.length),m.samples=[]}),r.mdats=[],r.moofs=[],p!=null&&await c?.write(p)}let o=[];function a(){if(o.length>0)return!0;const p=t.findIndex(m=>m.type==="moov");if(p===-1)return!1;if(o=t.slice(0,p+1),e=p+1,i.length===0)for(let m=1;;m+=1){const g=r.getTrackById(m);if(g==null)break;i.push({track:g,id:m})}return!0}let l=0;const u=q0();let c=null;const h=(async()=>{c=await u.createWriter(),l=self.setInterval(()=>{a()&&s()},100)})();let d=!1;return async()=>{if(d)throw Error("File exported");if(d=!0,await h,clearInterval(l),!a()||c==null)return null;r.flush(),await s(),await c?.close();const p=o.find(v=>v.type==="moov");if(p==null)return null;p.mvhd.duration=n;const m=q0(),g=f(o,0);return await Ys(m,g.slice()),await Ys(m,u,{overwrite:!1}),await m.stream()};function f(p,m){if(m>=p.length)return null;const g=new Qn.DataStream;for(let v=m;v<p.length;v++)p[v]!==null&&(p[v].write(g),delete p[v]);return new Uint8Array(g.buffer).slice()}}function Dq(r){const e=new ArrayBuffer(r.byteLength);r.copyTo(e);const t=r.timestamp;return{duration:r.duration??0,dts:t,cts:t,is_sync:r.type==="key",data:e}}async function jk(r){const e=Qn.createFile(),t=Mq(e);await Oq(r,e);const i=await t();if(i==null)throw Error("Can not generate file from streams");return i}async function Oq(r,e){let t=0,i=0,n=0,s=0,o=0,a=0,l=null,u=null;for(const c of r){let h=null,d=null,f=null,p=null;if(await new Promise(async m=>{Yk(c.pipeThrough(new qk),{onDone:m,onChunk:async({chunkType:g,data:v})=>{if(g==="ready"){const{videoTrackConf:x,audioTrackConf:y}=jb(v.file,v.info);t===0&&x!=null&&(t=e.addTrack(x)),s===0&&y!=null&&(s=e.addTrack(y))}else if(g==="samples"){const{type:x,samples:y}=v,b=x==="video"?t:s,T=x==="video"?i:o,E=x==="video"?n:a;y.forEach(P=>{let _,S;x==="video"?(h===null&&(h=P.dts,d=P.cts),_=P.dts-h,S=P.cts-(d??0)):(f===null&&(f=P.dts,p=P.cts),_=P.dts-f,S=P.cts-(p??0)),e.addSample(b,new Uint8Array(P.data),{duration:P.duration,dts:_+T,cts:S+E,is_sync:P.is_sync})});const C=y.at(-1);if(C==null)return;x==="video"?l=C:x==="audio"&&(u=C)}}})}),l!=null&&h!==null&&d!==null){const m=l.dts-h+l.duration,g=l.cts-d+l.duration;i+=m,n+=g}if(u!=null&&l!=null){const m=u.timescale/l.timescale;o=Math.round(i*m),a=Math.round(n*m)}}}async function Uq(r){return await jk([r])}function zq(r){let e=[];const t=new AudioDecoder({output:i=>{e.push(i)},error:Ee.error});return t.configure(r),{decode:async i=>{i.forEach(s=>{t.decode(new EncodedAudioChunk({type:s.is_sync?"key":"delta",timestamp:1e6*s.cts/s.timescale,duration:1e6*s.duration/s.timescale,data:s.data}))}),await t.flush();const n=e;return e=[],n},close:()=>{t.close()}}}function Lq(r,e){const t={codec:r.codec,sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels},i=new AudioEncoder({output:o=>{e(Dq(o))},error:o=>{Ee.error("AudioEncoder error:",o,", config:",t)}});i.configure(t);let n=null;function s(o,a){return new AudioData({timestamp:a,numberOfChannels:r.numberOfChannels,numberOfFrames:o.length/r.numberOfChannels,sampleRate:r.sampleRate,format:"f32-planar",data:new Float32Array(o)})}return{encode:async(o,a)=>{n!=null&&i.encode(s(n.data,n.ts)),n={data:o,ts:a}},stop:async()=>{n!=null&&(Nq(n.data,r.numberOfChannels,r.sampleRate),i.encode(s(n.data,n.ts)),n=null),await i.flush(),i.close()}}}function Nq(r,e,t){const i=r.length-1,n=Math.min(t/2,i);for(let s=0;s<n;s++)for(let o=1;o<=e;o++)r[Math.floor(i/o)-s]*=s/n}function Gq(r,e){Ee.info("mixinMP4AndAudio, opts:",{volume:e.volume,loop:e.loop});const t=Qn.createFile();let i,n=0,s=0;const o=t.boxes;let a=!1;const l=()=>{if(!a)if(o.find(I=>I.type==="moof")!=null)a=!0;else return null;if(s>=o.length)return null;const P=new Qn.DataStream;let _=s;try{for(;_<o.length;)o[_].write(P),delete o[_],_+=1}catch(I){throw I}if(t.moov!=null){for(var S=0;S<t.moov.traks.length;S++)t.moov.traks[S].samples=[];t.mdats=[],t.moofs=[]}return s=o.length,new Uint8Array(P.buffer)};let u=!1,c=!1,h=null;i=new ReadableStream({start(P){n=self.setInterval(()=>{const _=l();_!=null&&!c&&P.enqueue(_)},500),h=_=>{if(clearInterval(n),t.flush(),_!=null){P.error(_);return}const S=l();S!=null&&!c&&P.enqueue(S),c||P.close()}},cancel(){c=!0,clearInterval(n)}});const d=P=>{u||(u=!0,h?.(P))};let f=null,p=null,m=[],g=0,v=0,x=0,y=!0,b=st.sampleRate;Yk(r.pipeThrough(new qk),{onDone:async()=>{await p?.stop(),f?.close(),d()},onChunk:async({chunkType:P,data:_})=>{if(P==="ready"){const{videoTrackConf:S,audioTrackConf:I,audioDecoderConf:M}=jb(_.file,_.info);g===0&&S!=null&&(g=t.addTrack(S));const O=I??{timescale:1e6,samplerate:b,channel_count:st.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};v===0&&(v=t.addTrack(O),b=I?.samplerate??b,y=I!=null);const H=new AudioContext({sampleRate:b});m=j0(await H.decodeAudioData(await new Response(e.stream).arrayBuffer())),M!=null&&(f=zq(M)),p=Lq(M??{codec:O.type==="mp4a"?st.codec:O.type,numberOfChannels:O.channel_count,sampleRate:O.samplerate},K=>t.addSample(v,new Uint8Array(K.data),K))}else if(P==="samples"){const{id:S,type:I,samples:M}=_;if(I==="video"){M.forEach(O=>t.addSample(S,new Uint8Array(O.data),O)),y||await E(M);return}I==="audio"&&await C(M)}}});function T(P){const _=m.map(S=>e.loop?K0(S,x,x+P):S.slice(x,x+P));if(x+=P,e.volume!==1)for(const S of _)for(let I=0;I<S.length;I++)S[I]*=e.volume;return _}async function E(P){const _=P[0],S=P[P.length-1],I=Math.floor((S.cts+S.duration-_.cts)/_.timescale*b),M=aS([T(I)]);M.length!==0&&p?.encode(M,_.cts/_.timescale*1e6)}async function C(P){if(f==null)return;const _=(await f.decode(P)).map(oS),S=sS(_),I=T(S[0].length),M=P[0];p?.encode(aS([S,I]),M.cts/M.timescale*1e6)}return i}const Go=`
3509
+ `),a=[];if(o.forEach((l,u)=>{l.trim().split(/\s+/).filter(h=>h!=="").forEach(h=>{a.push({text:h,paragraphIndex:u})})}),a.length===0)this.opts.words=[];else{const l=s/a.length;this.opts.words=a.map((u,c)=>({text:u.text,from:c*l,to:(c+1)*l,isKeyWord:!1,paragraphIndex:u.paragraphIndex}))}}this.originalOpts&&(this.originalOpts.caption?this.originalOpts.caption.words=this.opts.words:this.originalOpts.words=this.opts.words),this.originalOpts&&this.textStyle&&this.refreshCaptions().then(()=>{this.emit("propsChange",{text:e})})}get style(){if(!this.originalOpts)return{};const e=this.originalOpts;return{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,color:e.fill,align:e.align,textCase:e.textCase,verticalAlign:e.verticalAlign,wordsPerLine:e.wordsPerLine,wordAnimation:e.wordAnimation,stroke:e.stroke?typeof e.stroke=="object"?{color:e.stroke.color,width:e.stroke.width}:{color:e.stroke,width:e.strokeWidth??0}:void 0,shadow:e.dropShadow?{color:e.dropShadow.color??"#000000",alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,distance:e.dropShadow.distance??0,angle:e.dropShadow.angle??0}:void 0}}set style(e){this.updateStyle(e)}get wordsPerLine(){return this.opts.wordsPerLine}set wordsPerLine(e){this.updateStyle({wordsPerLine:e})}get fontFamily(){return this.opts.fontFamily}set fontFamily(e){this.updateStyle({fontFamily:e})}get fontUrl(){return this.opts.fontUrl}set fontUrl(e){this.updateStyle({fontUrl:e})}get fontSize(){return this.opts.fontSize}set fontSize(e){this.updateStyle({fontSize:e})}get fontWeight(){return this.opts.fontWeight}set fontWeight(e){this.updateStyle({fontWeight:e})}get fontStyle(){return this.opts.fontStyle}set fontStyle(e){this.updateStyle({fontStyle:e})}get fill(){return this.opts.fill}set fill(e){this.updateStyle({fill:e})}get align(){return this.opts.align}set align(e){this.updateStyle({align:e})}get stroke(){return this.originalOpts?.stroke}set stroke(e){this.updateStyle({stroke:e})}get strokeWidth(){return this.opts.strokeWidth}set strokeWidth(e){this.updateStyle({strokeWidth:e})}get dropShadow(){return this.originalOpts?.dropShadow}set dropShadow(e){this.updateStyle({dropShadow:e})}get caption(){return this.originalOpts?.caption}set caption(e){this.updateStyle({caption:e})}get textBoxStyle(){return this.originalOpts?.caption?.textBoxStyle??this.originalOpts?.textBoxStyle??{}}set textBoxStyle(e){this.updateStyle({textBoxStyle:e})}bottomOffset;get textCase(){return this.originalOpts?.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;get mediaId(){return this.opts.mediaId}set mediaId(e){this.opts.mediaId=e,this.originalOpts&&(this.originalOpts.mediaId=e)}effects=[];get words(){return this.opts.words}set words(e){const t=e??[];this.opts.words=t,this.originalOpts&&(this.originalOpts.caption?this.originalOpts.caption.words=e:this.originalOpts.words=e);const i=t.map(n=>n.text).filter(n=>n&&n.trim()!=="").join(" ");this._text!==i?this.text=i:this.refreshCaptions().then(()=>{this.emit("propsChange",{words:e})})}opts;pixiTextContainer=null;renderTexture=null;wordTexts=[];textStyle;textStyleBase;_refreshing=!1;_needsRefresh=!1;externalRenderer=null;pixiApp=null;originalOpts=null;constructor(e,t={},i){super(),this.originalOpts={...t},this.externalRenderer=i??null,this.opts={fontSize:t.fontSize??30,fontFamily:t.fontFamily??"Arial",fontUrl:t.fontUrl??"",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",fill:t.fill??"#ffffff",strokeWidth:t.strokeWidth??0,align:t.align??"center",wordWrapWidth:t.wordWrapWidth??0,wordWrap:t.wordWrap??!1,lineHeight:t.lineHeight??1,letterSpacing:t.letterSpacing??0,textCase:t.textCase??"none",videoWidth:t.caption?.positioning?.videoWidth??t.videoWidth??1280,videoHeight:t.caption?.positioning?.videoHeight??t.videoHeight??720,bottomOffset:t.caption?.positioning?.bottomOffset??t.bottomOffset??30,keyword:t.caption?.colors?.keyword??t.colors?.keyword??"#ffff00",background:t.caption?.colors?.background??t.colors?.background??"#000000",active:t.caption?.colors?.active??t.colors?.active??"#ffffff",activeFill:t.caption?.colors?.activeFill??t.colors?.activeFill??"#00ff00",appeared:t.caption?.colors?.appeared??t.colors?.appeared??"#ffffff",words:t.caption?.words??t.words??[],preserveKeywordColor:t.caption?.preserveKeywordColor??t.preserveKeywordColor??!1,mediaId:t.mediaId,wordsPerLine:t.wordsPerLine??"multiple",wordAnimation:t.caption?.wordAnimation??t.wordAnimation,textBoxStyle:t.caption?.textBoxStyle??t.textBoxStyle??{}},this._initialLayoutApplied=t.initialLayoutApplied??!1,this._initialLayoutApplied&&(this._isXPositionedManually=!0),this.opts.wordWrapWidth>0&&(this._isWidthConstrained=!0,this._width=this.opts.wordWrapWidth,this.opts.wordWrap=!0),this.text=e,this._lastProcessedText=this._text;const n={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(t.fill&&typeof t.fill=="object"&&t.fill.type==="gradient"){const c=new zr(t.fill.x0,t.fill.y0,t.fill.x1,t.fill.y1);t.fill.colors.forEach(({ratio:h,color:d})=>{const f=typeof d=="number"?d:xt(d)??16777215;c.addColorStop(h,f)}),n.fill={fill:c}}else{let c;t.fill==="transparent"?c=16777215:(typeof t.fill=="string"||typeof t.fill=="number")&&(c=xt(t.fill)),n.fill=c??16777215}const s=c=>c==="transparent";if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke){if(!s(t.stroke.color)){const c=xt(t.stroke.color);c!==void 0&&(n.stroke={color:c,width:t.stroke.width},t.stroke.join&&(n.stroke.join=t.stroke.join))}}else{const c=t.stroke??void 0;if(!s(c)){const h=xt(c);h!==void 0?n.stroke={color:h,width:this.opts.strokeWidth??0}:this.opts.strokeWidth&&this.opts.strokeWidth>0&&(n.stroke={color:0,width:this.opts.strokeWidth})}}if(t.dropShadow){const c=xt(t.dropShadow.color);c!==void 0&&(n.dropShadow={color:c,alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,angle:t.dropShadow.angle??Math.PI/6,distance:t.dropShadow.distance??2})}const o=new Bt(n);this.textStyle=o;const{align:a,fill:l,...u}=n;this.textStyleBase=new Bt(u),this.ready=(async()=>{await this.refreshCaptions();const c={...this._meta};return Ee.info("CaptionClip ready:",c),c})()}async updateStyle(e){this.originalOpts||(this.originalOpts={});let t={...e};e.style&&(t={...t,...e.style},delete t.style),this.originalOpts={...this.originalOpts,...t},t.fontSize!==void 0&&(this.opts.fontSize=t.fontSize),t.fontFamily!==void 0&&(this.opts.fontFamily=t.fontFamily),t.fontUrl!==void 0&&(this.opts.fontUrl=t.fontUrl),t.fontWeight!==void 0&&(this.opts.fontWeight=t.fontWeight),t.fontStyle!==void 0&&(this.opts.fontStyle=t.fontStyle),t.fill!==void 0&&(this.opts.fill=t.fill),t.align!==void 0&&(this.opts.align=t.align),t.letterSpacing!==void 0&&(this.opts.letterSpacing=t.letterSpacing),t.lineHeight!==void 0&&(this.opts.lineHeight=t.lineHeight),t.textCase!==void 0&&(this.opts.textCase=t.textCase),t.wordWrapWidth!==void 0&&(this.opts.wordWrapWidth=t.wordWrapWidth,t.wordWrapWidth>0&&(this._isWidthConstrained=!0,this.opts.wordWrap=!0)),t.wordsPerLine!==void 0&&(this.opts.wordsPerLine=t.wordsPerLine),t.wordAnimation!==void 0&&(this.opts.wordAnimation=t.wordAnimation),t.textBoxStyle!==void 0&&(this.opts.textBoxStyle=t.textBoxStyle),t.caption?.colors&&(t.caption.colors.appeared!==void 0&&(this.opts.appeared=t.caption.colors.appeared),t.caption.colors.active!==void 0&&(this.opts.active=t.caption.colors.active),t.caption.colors.activeFill!==void 0&&(this.opts.activeFill=t.caption.colors.activeFill),t.caption.colors.background!==void 0&&(this.opts.background=t.caption.colors.background),t.caption.colors.keyword!==void 0&&(this.opts.keyword=t.caption.colors.keyword),t.caption.wordAnimation!==void 0&&(this.opts.wordAnimation=t.caption.wordAnimation)),t.caption?.preserveKeywordColor!==void 0&&(this.opts.preserveKeywordColor=t.caption.preserveKeywordColor);const i={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(this.opts.fill&&typeof this.opts.fill=="object"&&this.opts.fill.type==="gradient"){const u=new zr(this.opts.fill.x0,this.opts.fill.y0,this.opts.fill.x1,this.opts.fill.y1);this.opts.fill.colors.forEach(({ratio:c,color:h})=>{const d=typeof h=="number"?h:xt(h)??16777215;u.addColorStop(c,d)}),i.fill={fill:u}}else i.fill=16777215;if(e.stroke!==void 0||e.strokeWidth!==void 0||this.originalOpts.stroke||this.originalOpts.strokeWidth){if(this.originalOpts.stroke&&typeof this.originalOpts.stroke=="object"&&"color"in this.originalOpts.stroke){const u=xt(this.originalOpts.stroke.color);u!==void 0&&(i.stroke={color:u,width:this.originalOpts.stroke.width},this.originalOpts.stroke.join&&(i.stroke.join=this.originalOpts.stroke.join))}else if(this.originalOpts?.stroke){const u=this.originalOpts.stroke,c=xt(typeof u=="object"&&u!==null&&"color"in u?u.color:u),h=e.strokeWidth!==void 0?e.strokeWidth:this.originalOpts.strokeWidth!==void 0?this.originalOpts.strokeWidth:0;c!==void 0?i.stroke={color:c,width:h}:h>0&&(i.stroke={color:0,width:h})}}const s=e.dropShadow!==void 0?e.dropShadow:this.originalOpts.dropShadow;if(s){const u=xt(s.color);u!==void 0&&(i.dropShadow={color:u,alpha:s.alpha!==void 0?s.alpha:.5,blur:s.blur!==void 0?s.blur:4,angle:s.angle!==void 0?s.angle:Math.PI/6,distance:s.distance!==void 0?s.distance:2})}this.textStyle=new Bt(i);const{align:o,fill:a,...l}=i;this.textStyleBase=new Bt(l),await this.refreshCaptions(),this.emit("propsChange",e)}async refreshCaptions(){if(this._refreshing){this._needsRefresh=!0;return}this._refreshing=!0,this._needsRefresh=!1;try{typeof document<"u"&&await document.fonts.ready;const e=this._width,t=this._height,i=this.originalOpts?.verticalAlign||"center";this.pixiTextContainer?this.pixiTextContainer.removeChildren():this.pixiTextContainer=new Ie,this.wordTexts.forEach(z=>{z.destroyed||z.destroy()}),this.wordTexts=[];const n=Ht.measureText(" ",this.textStyle),s=[];this.opts.words.forEach((z,ne)=>{const oe=this.opts.textCase;let te=z.text||"";oe==="uppercase"?te=te.toUpperCase():oe==="lowercase"?te=te.toLowerCase():oe==="title"&&(te=te.replace(/\w\S*/g,Ue=>Ue.charAt(0).toUpperCase()+Ue.substring(1).toLowerCase())),te.split(/\s+/).filter(Ue=>Ue.length>0).forEach(Ue=>{const Ge=new kl({text:Ue,style:this.textStyle});Ge.segmentIndex=ne;const ke="#ffffff",Ve=typeof ke=="object"&&ke!==null&&"type"in ke?16777215:ke,Me=xt(Ve);Ge.tint=Me??16777215,s.push(Ge)})}),this.wordTexts=s;const o=this._visualPaddingX,a=this._visualPaddingY,l=this.opts.lineHeight*(this.opts.fontSize||30),u=new kl({text:" ",style:this.textStyleBase}),c=Math.ceil(u.getLocalBounds().width||u.width||n.width);u.destroy();const h=!this._isWidthConstrained&&(this.width===0||this._lastContentWidth===0||Math.abs(this.width-this._lastContentWidth)<2),d=this.opts.videoWidth||1280;let f=0;this.opts.wordWrapWidth>0&&this.opts.wordsPerLine!=="single"?f=this.opts.wordWrapWidth-o*2:this.opts.wordsPerLine==="single"?f=d*5:!h&&this.width>0?f=this.width+10:f=d*5,(isNaN(f)||f<=0)&&(f=d);let p=[];const m=this.opts.textBoxStyle.textAlign||this.opts.align,g=this.opts.textBoxStyle,v=g.style==="tiktok",x=[],y=g.horizontalPadding??0,b=g.verticalPadding??0;let T=[],E=0,C=0;this.wordTexts.forEach((z,ne)=>{const oe=z.getLocalBounds(),te=Math.ceil(oe.width||z.width),be=Math.ceil(oe.height||z.height),Ue=z.segmentIndex,Ge=this.opts.words[Ue],ke=ne>0?this.wordTexts[ne-1]:null,Ve=ke?this.opts.words[ke.segmentIndex]:null,Me=Ve&&Ge&&Ge.paragraphIndex!==void 0&&Ge.paragraphIndex!==Ve.paragraphIndex||this.opts.wordsPerLine==="single",Ct=E+(E>0?c:0)+te;!Me&&(Ct<=f+1||T.length===0)?(T.push(z),E=Ct,C=Math.max(C,be)):(T.length>0&&p.push({words:T,width:E,height:Math.max(C,l)+b*2}),T=[z],E=te,C=be)}),T.length>0&&p.push({words:T,width:E,height:Math.max(C,l)+b*2}),this.opts.textBoxStyle.maxLines&&this.opts.textBoxStyle.maxLines>0&&(p=p.slice(0,this.opts.textBoxStyle.maxLines));let P=0,_=0;p.forEach(z=>{P=Math.max(P,z.width),_+=z.height});const S=P,I=_,M=S+Math.max(o,y)*2,O=I,H=this._text!==this._lastProcessedText;this._lastProcessedText=this._text;let K=M;const D=O;this._isWidthConstrained&&(H?K=M:K=Math.max(M,e),this.opts.wordWrapWidth>0&&(K=Math.min(K,this.opts.wordWrapWidth)));const k=K,W=D,G=I;let J=0;const q=Math.max(a,b);i==="top"?J=q:i==="bottom"?J=W-G-q:J=(W-G)/2;let _e=J;if(p.forEach(z=>{const ne=new Ie;ne.label="lineContainer",this.pixiTextContainer.addChild(ne);let oe=0;const te=z.width;let be=0;m==="center"?be=(k-te)/2:m==="right"?be=k-te-o:be=o,ne.x=be,ne.y=_e,v&&x.push({x:be-y,y:_e,w:te+y*2,h:z.height}),z.words.forEach((Ue,Ge)=>{const ke=Ue.getLocalBounds(),Ve=ke.width||Ue.width,Me=ke.height||Ue.height;Ue.pivot.set(Ve/2,Me/2),Ue.x=Math.round(oe+Ve/2),Ue.y=Math.round(z.height/2),ne.addChild(Ue),oe+=Ve+(Ge<z.words.length-1?c:0)}),_e+=z.height}),v&&x.length>0){const z=new Je;z.label="tiktokBackground";const ne=xt(this.opts.background)??0,oe=g.borderRadius??10;this.drawRoundedTiktokPath(z,x,oe,ne),this.pixiTextContainer.addChildAt(z,0)}if(!v){const z=new Je;z.label="containerBackground";const ne=this.opts.background==="transparent"||!this.opts.background,oe=ne?0:xt(this.opts.background),te=ne?0:1;z.roundRect(0,0,k,W,10),z.fill({color:oe,alpha:te}),this.pixiTextContainer.addChildAt(z,0)}this.renderTexture?(Math.abs(this.renderTexture.width-k)>.5||Math.abs(this.renderTexture.height-W)>.5)&&(this.renderTexture.destroy(),this.renderTexture=Ot.create({width:k,height:W})):this.renderTexture=Ot.create({width:k,height:W}),this.updateState(this._lastTickTime);try{(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture})}catch(z){Ee.warn("CaptionClip: Could not render captions during refresh",z)}const Re=!this._isWidthConstrained,ge=this.height===0||this._lastContentHeight===0||Math.abs(this.height-this._lastContentHeight)<2;if(Re&&this._initialLayoutApplied&&e>0&&t>0){const z=K-e;Math.abs(z)>.1&&!this._isXPositionedManually&&this.opts.align==="center"?this.left-=z/2:Math.abs(z)>.1&&!this._isXPositionedManually&&this.opts.align==="right"&&(this.left-=z)}if(this._meta.width=S,this._meta.height=I,this._meta.duration=1/0,this._width=k,this._height=W,this._lastContentWidth=this._width,this._lastContentHeight=this._height,!this._initialLayoutApplied&&(Re||ge)){const z=this.opts.videoWidth,ne=this.opts.videoHeight,oe=this.opts.bottomOffset,te=ne-I-oe,be=(z-S)/2;this.top=te,this.left=be,this._initialLayoutApplied=!0}}finally{this._refreshing=!1,this._needsRefresh&&this.refreshCaptions()}}lastLoggedTime=-1;updateState(e){const t=e/1e3,i=Math.floor(e/1e6);i!==this.lastLoggedTime&&(this.lastLoggedTime=i),this.wordTexts.forEach(n=>{const s=n.segmentIndex,o=this.opts.words[s];if(!o)return;n.scale.set(1,1);const a=t>=o.from&&t<o.to,l=t>=o.to,u=this.opts.wordAnimation;let c=0,h=!1;if(u&&u.application!=="none"&&((u.application==="active"&&a||u.application==="keyword"&&o.isKeyWord)&&(h=!0),h)){if(u.mode==="dynamic"&&a){const v=o.to-o.from;if(v>0){const x=(t-o.from)/v,y=Math.max(0,Math.min(1,x));u.value<1?c=y:c=Math.sin(y*Math.PI)}else c=1}else c=1;if(u.type==="scale"){let v=1;u.value<1&&u.mode==="dynamic"&&a?v=u.value+(1-u.value)*c:v=1+(u.value-1)*c,n.scale.set(v,v)}}const d=o.isKeyWord&&!Lk(this.opts.keyword);let f=16777215,p=1;if(o.isKeyWord&&a&&d)({color:f,alpha:p}=Ln(this.opts.keyword,16776960));else if(a)p=Ln(this.opts.active,16777215).alpha,f=Ln(this.opts.active,16777215).color;else if(l&&this.opts.preserveKeywordColor&&d)({color:f,alpha:p}=Ln(this.opts.keyword));else if(l)({color:f,alpha:p}=Ln(this.opts.appeared));else{const v=this.opts.fill,x=typeof v=="object"&&v!==null&&"type"in v?16777215:v;({color:f,alpha:p}=Ln(x))}if(h&&u?.type==="opacity"){let v=1;u.value<1&&u.mode==="dynamic"&&a?v=u.value+(1-u.value)*c:v=1+(u.value-1)*c,p*=v}n.children.forEach(v=>{v.label!=="bgRect"&&(v.tint=f,v.alpha=p)});const m=n.getChildByLabel("bgRect"),g=this.opts.textBoxStyle.style==="tiktok";if(a&&!g){const{color:v,alpha:x}=Ln(this.opts.activeFill,16753920),y=15,b=40;m&&(m.visible=!1);const T=n.getLocalBounds();m&&(m.visible=!0);const E=10,C=m??new Je;C.label="bgRect",C.clear(),C.roundRect(T.x-b/2,T.y-y/2,T.width+b,T.height+y,E),C.fill({color:v,alpha:x}),C.tint=16777215,m||n.addChildAt(C,0)}else m&&(n.removeChild(m),m.destroy())})}async getTexture(){return this.pixiTextContainer==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture)}async offscreenRender(e,t){const i=t*this.playbackRate;this._lastTickTime=i*1e6,this.animate(i*1e6),this._render(e);const{width:n,height:s}=this,{video:o,audio:a,done:l}=await this.getFrame(t),u=a??[];return l?{audio:u,done:!0}:(o!=null&&(e.save(),e.drawImage(o,-n/2,-s/2,n,s),e.restore()),{audio:u,done:!1})}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("CaptionClip: No renderer available. Provide a renderer via setRenderer().");return this.pixiApp.renderer}async tick(e){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("CaptionClip not initialized");this._lastTickTime=e,this.updateState(e);const t=await this.getRenderer();t.render({container:this.pixiTextContainer,target:this.renderTexture});const i=this.renderTexture.source?.resource?.source;let n;if(i instanceof HTMLCanvasElement)n=await createImageBitmap(i);else if(i instanceof OffscreenCanvas)n=await createImageBitmap(i);else{const o=t.extract.canvas(this.renderTexture);if(o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas)n=await createImageBitmap(o);else throw new Error("Unable to extract canvas from render texture")}return{video:n,state:"success"}}async split(e){await this.ready;const t=await this.clone(),i=await this.clone();return[t,i]}addEffect(e){this.effects.push(e)}editEffect(e,t){const i=this.effects.find(n=>n.id===e);i&&Object.assign(i,t)}removeEffect(e){const t=this.effects.findIndex(i=>i.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.originalOpts||{},t=new Nn(this.text,e);return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){if(!this.destroyed){Ee.info("Caption destroy");try{this.wordTexts.forEach(e=>{e!=null&&!e.destroyed&&e.destroy({children:!0})})}catch{}finally{this.wordTexts=[]}try{this.pixiTextContainer!=null&&(this.pixiTextContainer.destroyed||this.pixiTextContainer.destroy({children:!0}))}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&(this.renderTexture.destroyed||this.renderTexture.destroy(!0))}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),i={};if(this.originalOpts){const f=this.originalOpts;f.fontSize!==void 0&&(i.fontSize=f.fontSize),f.fontFamily!==void 0&&(i.fontFamily=f.fontFamily),f.fontWeight!==void 0&&(i.fontWeight=f.fontWeight),f.fontStyle!==void 0&&(i.fontStyle=f.fontStyle),f.fill!==void 0&&(i.color=f.fill),f.align!==void 0&&(i.align=f.align),f.textCase!==void 0&&(i.textCase=f.textCase),f.fontUrl!==void 0&&(i.fontUrl=f.fontUrl),f.verticalAlign!==void 0&&(i.verticalAlign=f.verticalAlign),f.wordWrapWidth!==void 0&&(i.wordWrapWidth=f.wordWrapWidth),f.wordWrap!==void 0&&(i.wordWrap=f.wordWrap),f.wordAnimation!==void 0&&(i.wordAnimation=f.wordAnimation),f.textBoxStyle!==void 0&&(i.textBoxStyle=f.textBoxStyle),f.stroke&&(typeof f.stroke=="object"?i.stroke={color:f.stroke.color,width:f.stroke.width}:i.stroke={color:f.stroke,width:this.opts.strokeWidth??0}),f.dropShadow&&(i.shadow={color:f.dropShadow.color??"#000000",alpha:f.dropShadow.alpha??.5,blur:f.dropShadow.blur??4,distance:f.dropShadow.distance??0,angle:f.dropShadow.angle??0})}const n={};this.opts.words&&this.opts.words.length>0&&(n.words=this.opts.words);const s={},o=this.originalOpts?.caption?.colors??this.originalOpts?.colors;o?.appeared!==void 0&&(s.appeared=o.appeared),o?.active!==void 0&&(s.active=o.active),o?.activeFill!==void 0&&(s.activeFill=o.activeFill),o?.background!==void 0&&(s.background=o.background),o?.keyword!==void 0&&(s.keyword=o.keyword);let a;this.originalOpts?.caption?.preserveKeywordColor!==void 0?a=this.originalOpts.caption.preserveKeywordColor:this.originalOpts?.preserveKeywordColor!==void 0&&(a=this.originalOpts.preserveKeywordColor),Object.keys(s).length>0&&(n.colors=s),a!==void 0&&(n.preserveKeywordColor=a);const l={};this.bottomOffset!==void 0&&(l.bottomOffset=this.bottomOffset);const u=this.originalOpts?.caption?.positioning?.videoWidth??this.originalOpts?.videoWidth,c=this.originalOpts?.caption?.positioning?.videoHeight??this.originalOpts?.videoHeight;u!==void 0&&(l.videoWidth=u),c!==void 0&&(l.videoHeight=c),Object.keys(l).length>0&&(n.positioning=l);const h=this.originalOpts?.caption?.wordAnimation??this.originalOpts?.wordAnimation;h!==void 0&&(n.wordAnimation=h);const d=this.originalOpts?.caption?.textBoxStyle??this.originalOpts?.textBoxStyle;return d!==void 0&&(n.textBoxStyle=d),{...t,type:"Caption",text:this.text,style:i,caption:Object.keys(n).length>0?n:void 0,textBoxStyle:d,id:this.id,effects:this.effects,mediaId:this.mediaId,wordsPerLine:this.opts.wordsPerLine}}static async fromObject(e){if(e.type!=="Caption")throw new Error(`Expected Caption, got ${e.type}`);const t=e.text||"",i=e.style||{},n={};i.fontSize!==void 0&&(n.fontSize=i.fontSize),i.fontFamily!==void 0&&(n.fontFamily=i.fontFamily),i.fontWeight!==void 0&&(n.fontWeight=i.fontWeight),i.fontStyle!==void 0&&(n.fontStyle=i.fontStyle),i.color!==void 0&&(n.fill=i.color),i.align!==void 0&&(n.align=i.align),i.textCase!==void 0&&(n.textCase=i.textCase),i.verticalAlign!==void 0&&(n.verticalAlign=i.verticalAlign),i.wordWrapWidth!==void 0&&(n.wordWrapWidth=i.wordWrapWidth),i.wordWrap!==void 0&&(n.wordWrap=i.wordWrap),i.wordsPerLine!==void 0?n.wordsPerLine=i.wordsPerLine:e.wordsPerLine!==void 0&&(n.wordsPerLine=e.wordsPerLine),i.fontUrl!==void 0?n.fontUrl=i.fontUrl:e.fontUrl!==void 0&&(n.fontUrl=e.fontUrl),e.mediaId&&(n.mediaId=e.mediaId),i.stroke&&(n.stroke=i.stroke.color,n.strokeWidth=i.stroke.width),i.shadow&&(n.dropShadow={color:i.shadow.color,alpha:i.shadow.alpha,blur:i.shadow.blur,distance:i.shadow.distance,angle:i.shadow.angle}),i.wordAnimation!==void 0&&(n.wordAnimation=i.wordAnimation),e.textBoxStyle!==void 0?n.textBoxStyle=e.textBoxStyle:i.textBoxStyle!==void 0&&(n.textBoxStyle=i.textBoxStyle),e.caption?(n.caption=e.caption,e.caption.wordAnimation&&(n.wordAnimation=e.caption.wordAnimation),e.caption.textBoxStyle&&(n.textBoxStyle=e.caption.textBoxStyle)):(e.bottomOffset!==void 0&&(n.bottomOffset=e.bottomOffset),e.words!==void 0&&(n.words=e.words),(e.appearedColor!==void 0||e.activeColor!==void 0||e.activeFillColor!==void 0||e.backgroundColor!==void 0||e.isKeyWordColor!==void 0)&&(n.colors={},e.appearedColor!==void 0&&(n.colors.appeared=e.appearedColor),e.activeColor!==void 0&&(n.colors.active=e.activeColor),e.activeFillColor!==void 0&&(n.colors.activeFill=e.activeFillColor),e.backgroundColor!==void 0&&(n.colors.background=e.backgroundColor),e.isKeyWordColor!==void 0&&(n.colors.keyword=e.isKeyWordColor)),e.preservedColorKeyWord!==void 0&&(n.preserveKeywordColor=e.preservedColorKeyWord),e.videoWidth!==void 0&&(n.videoWidth=e.videoWidth),e.videoHeight!==void 0&&(n.videoHeight=e.videoHeight)),n.initialLayoutApplied=!0;const s=new Nn(t,n);return s.left=e.left,s.top=e.top,s.width=e.width,s.height=e.height,s.angle=e.angle,s.display.from=e.display.from,s.display.to=e.display.to,s.duration=e.duration,s.playbackRate=e.playbackRate,s.zIndex=e.zIndex,s.opacity=e.opacity,s.flip=e.flip,s.wordsPerLine=e.wordsPerLine??"multiple",e.animation&&s.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(s.id=e.id),e.effects&&(s.effects=e.effects),await s.ready,s}getVisibleHandles(){return["mr","mb","br","rot"]}drawRoundedTiktokPath(e,t,i,n){if(t.length===0)return;const s=Math.max(i*.8,15);let o=!0,a=0;for(;o&&a<5;){o=!1,a++;for(let h=0;h<t.length;h++)for(let d=h+1;d<t.length;d++){const f=t[h].x+t[h].w,p=t[d].x+t[d].w;if(Math.abs(f-p)>.1&&Math.abs(f-p)<s){const m=Math.max(f,p);t[h].w=m-t[h].x,t[d].w=m-t[d].x,o=!0}if(Math.abs(t[h].x-t[d].x)>.1&&Math.abs(t[h].x-t[d].x)<s){const m=Math.min(t[h].x,t[d].x);t[h].w+=t[h].x-m,t[h].x=m,t[d].w+=t[d].x-m,t[d].x=m,o=!0}}}const l=[];l.push({x:t[0].x,y:t[0].y}),l.push({x:t[0].x+t[0].w,y:t[0].y});for(let h=0;h<t.length-1;h++){const d=t[h],f=t[h+1];if(Math.abs(d.x+d.w-(f.x+f.w))>.1){const p=(d.y+d.h+f.y)/2;l.push({x:d.x+d.w,y:p}),l.push({x:f.x+f.w,y:p})}}l.push({x:t[t.length-1].x+t[t.length-1].w,y:t[t.length-1].y+t[t.length-1].h}),l.push({x:t[t.length-1].x,y:t[t.length-1].y+t[t.length-1].h});for(let h=t.length-1;h>0;h--){const d=t[h],f=t[h-1];if(Math.abs(d.x-f.x)>.1){const p=(d.y+f.y+f.h)/2;l.push({x:d.x,y:p}),l.push({x:f.x,y:p})}}e.clear();const u=l[l.length-1],c=l[0];e.moveTo((u.x+c.x)/2,(u.y+c.y)/2);for(let h=0;h<l.length;h++){const d=l[h],f=l[(h+1)%l.length];e.arcTo(d.x,d.y,(d.x+f.x)/2,(d.y+f.y)/2,i)}e.fill({color:n,alpha:1})}}let Fl=class Wn extends zn{type="Image";ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];getVisibleHandles(){return["tl","tr","bl","br","rot"]}static async fromUrl(e,t){let i=null,n;if(e.startsWith("blob:"))try{const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch image: ${o.status} ${o.statusText}`);const a=await o.blob();n=await createImageBitmap(a);try{i=Q.from(n)}catch(l){Ee.warn("Failed to create Pixi texture from bitmap:",l)}}catch(o){throw Ee.error(`Failed to load blob image from ${e}`,o),o}else n=await No.getImageBitmap(e);if(!n)throw new Error(`Failed to load image from ${e}`);const s=new Wn(n,t||e);return i&&(s.pixiTexture=i),s}getTexture(){return this.pixiTexture}constructor(e,t){super(),this.src=t!==void 0?t:"";const i=n=>{this.img=n,this._meta.width=n.width,this._meta.height=n.height,this._meta.duration=1/0;const s={...this._meta};return this.width=this.width===0?s.width:this.width,this.height=this.height===0?s.height:this.height,this.duration===0&&s.duration!==1/0&&(this.duration=s.duration,this.display.to=this.display.from+this.duration),s};if(e instanceof ReadableStream)this.ready=new Response(e).blob().then(n=>createImageBitmap(n)).then(i);else if(e instanceof ImageBitmap)this.ready=Promise.resolve(i(e));else if(Array.isArray(e)&&e.every(n=>n instanceof VideoFrame)){this.frames=e;const n=this.frames[0];if(n==null)throw Error("The frame count must be greater than 0");this._meta={width:n.displayWidth,height:n.displayHeight,duration:this.frames.reduce((o,a)=>o+(a.duration??0),0)};const s={...this._meta,duration:1/0};this.width=this.width===0?s.width:this.width,this.height=this.height===0?s.height:this.height,this.duration===0&&s.duration!==1/0&&(this.duration=s.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(s)}else if("type"in e)this.ready=this.initAnimateImg(e.stream,e.type).then(()=>{const n={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),n});else throw Error("Illegal arguments")}async initAnimateImg(e,t){this.frames=await LL(e,t);const i=this.frames[0];if(i==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((n,s)=>n+(s.duration??0),0),width:i.codedWidth,height:i.codedHeight},Ee.info("Image ready:",this._meta)}tickInterceptor=async(e,t)=>t;async tick(e){if(this.img!=null)return await this.tickInterceptor(e,{video:await createImageBitmap(this.img),state:"success"});const t=e%this._meta.duration;return await this.tickInterceptor(e,{video:(this.frames.find(i=>t>=i.timestamp&&t<=i.timestamp+(i.duration??0))??this.frames[0]).clone(),state:"success"})}async split(e){if(await this.ready,this.img!=null)return[new Wn(await createImageBitmap(this.img),this.src),new Wn(await createImageBitmap(this.img),this.src)];let t=-1;for(let s=0;s<this.frames.length;s++){const o=this.frames[s];if(!(e>o.timestamp)){t=s;break}}if(t===-1)throw Error("Not found frame by time");const i=this.frames.slice(0,t).map(s=>new VideoFrame(s)),n=this.frames.slice(t).map(s=>new VideoFrame(s,{timestamp:s.timestamp-e}));return[new Wn(i,this.src),new Wn(n,this.src)]}async clone(){await this.ready;const e=this.img==null?this.frames.map(i=>i.clone()):await createImageBitmap(this.img),t=new Wn(e,this.src);return t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t.transition=this.transition,t}addEffect(e){this.effects.push(e)}editEffect(e,t){const i=this.effects.find(n=>n.id===e);i&&Object.assign(i,t)}removeEffect(e){const t=this.effects.findIndex(i=>i.id===e);t!==-1&&this.effects.splice(t,1)}destroy(){Ee.info("Image destroy"),this.img?.close(),this.frames.forEach(e=>e.close()),this.pixiTexture=null,super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Image",id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Image")throw new Error(`Expected Image, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("Image requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let t;try{const i=await No.getImageBitmap(e.src);t=new Wn(i,e.src)}catch(i){throw i instanceof Error&&i.message.includes("could not be decoded")?new Error(`Failed to decode image from ${e.src}. The image may be decoded, in an unsupported format, or there may be CORS issues.`):i}return t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.style&&(t.style={...t.style,...e.style}),e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),e.effects&&(t.effects=e.effects),e.transition&&(t.transition=e.transition),e.chromaKey&&(t.chromaKey={...t.chromaKey,...e.chromaKey}),e.colorAdjustment&&(t.colorAdjustment={...t.colorAdjustment,...e.colorAdjustment}),e.locked!==void 0&&(t.locked=e.locked),t}};function jb(r,e){const t={},i=e.videoTracks[0];if(i!=null){const s=mq(r.getTrackById(i.id))?.buffer,o=pq(i.codec);o&&(t.videoTrackConf={timescale:i.timescale,duration:i.duration,width:i.video.width,height:i.video.height,brands:e.brands,type:o.type,[o.descKey]:s}),t.videoDecoderConf={codec:i.codec,codedHeight:i.video.height,codedWidth:i.video.width,description:s}}const n=e.audioTracks[0];if(n!=null){const s=gq(r),o=s?vq(s):{};t.audioTrackConf={timescale:n.timescale,samplerate:o.sampleRate??n.audio.sample_rate,channel_count:o.numberOfChannels??n.audio.channel_count,hdlr:"soun",type:n.codec.startsWith("mp4a")?"mp4a":n.codec,description:s},t.audioDecoderConf={codec:o.codec??st.codec,numberOfChannels:o.numberOfChannels??n.audio.channel_count,sampleRate:o.sampleRate??n.audio.sample_rate}}return t}function pq(r){return r.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:r.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:null}function mq(r){for(const e of r.mdia.minf.stbl.stsd.entries){const t=e.avcC??e.hvcC??e.av1C??e.vpcC;if(t!=null){const i=new Qn.DataStream(void 0,0,void 0);return t.write(i),new Uint8Array(i.buffer.slice(8))}}}function gq(r,e="mp4a"){return r.moov?.traks.flatMap(t=>t.mdia.minf.stbl.stsd.entries).find(t=>t.type===e)}function vq(r){const e=r.esd?.descs?.[0];if(!e)return{};let t=`mp4a.${e.oti.toString(16)}`;const i=e.descs?.[0];if(!i)return t.endsWith(".40")&&(t+=".2"),{codec:t};const n=i.data;if(!n)return{codec:t};const s=(n[0]&248)>>3;t+=`.${s}`;const o=(n[0]&7)<<1|n[1]>>7,a=(n[1]&120)>>3;return{codec:t,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][o],numberOfChannels:a}}async function xq(r,e,t){const i=Qn.createFile(!1);i.onReady=o=>{e({mp4boxFile:i,info:o}),[o.videoTracks[0],o.audioTracks[0]].forEach(a=>{if(a){const l=a.video?"video":"audio";i.setExtractionOptions(a.id,l,{nbSamples:100})}}),i.start()},i.onSamples=t;let n=0;const s=30*1024*1024;for(;;){const o=await r.read(s,{at:n});if(o.byteLength===0)break;o.fileStart=n;const a=i.appendBuffer(o);if(a==null)break;n=a}i.stop()}function yq(r){if(r?.length!==9)return{};const e=new Int32Array(r.buffer),t=c=>c/65536,i=t(e[0]),n=t(e[1]),s=t(e[3]),o=t(e[4]),a=t(e[6]),l=t(e[7]),u=e[8]/(1<<30);return{scaleX:Math.sqrt(i*i+s*s),scaleY:Math.sqrt(n*n+o*o),rotationRad:Math.atan2(s,i),rotationDeg:Math.atan2(s,i)*180/Math.PI,translateX:a,translateY:l,perspective:u}}function bq(r,e,t){const i=(Math.round(t/90)*90+360)%360;if(i===0)return u=>u;const n=i===90||i===270,s=n?e:r,o=n?r:e,a=new OffscreenCanvas(s,o),l=a.getContext("2d");return l.translate(s/2,o/2),l.rotate(-i*Math.PI/180),l.translate(-r/2,-e/2),u=>{if(!u)return null;l.drawImage(u,0,0);const c=new VideoFrame(a,{timestamp:u.timestamp,duration:u.duration??void 0});return u.close(),c}}let Kb=0;function Qb(r){return r.kind==="file"&&r.createReader instanceof Function}class wr extends zn{type="Video";insId=Kb++;logger=Ee.create(`Video id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const e=await this.localFile.getOriginFile();if(e==null)throw Error("Video localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:t,size:i})=>e.slice(t,t+i))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=e=>e;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];getVisibleHandles(){return["tl","tr","bl","br","rot"]}static async fromUrl(e,t={}){const i=await No.getReadableStream(e),n=new wr(i,{},e);return await n.ready,t.x!==void 0&&(n.left=t.x),t.y!==void 0&&(n.top=t.y),t.width!==void 0&&(n.width=t.width),t.height!==void 0&&(n.height=t.height),n}constructor(e,t={},i){if(super(),this.src=i!==void 0?i:"",!(e instanceof ReadableStream)&&!Qb(e)&&!Array.isArray(e.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...t},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof t.audio=="object"&&"volume"in t.audio?t.audio.volume:t.volume??1;const n=async s=>(await Ys(this.localFile,s),this.localFile);this.localFile=Qb(e)?e:"localFile"in e?e.localFile:q0(),this.ready=(e instanceof ReadableStream?n(e).then(s=>Nk(s,this.opts)):Qb(e)?Nk(e,this.opts):Promise.resolve(e)).then(async({videoSamples:s,audioSamples:o,decoderConf:a,headerBoxPos:l,parsedMatrix:u})=>{this.videoSamples=s,this.audioSamples=o,this.decoderConf=a,this.headerBoxPos=l,this.parsedMatrix=u;const{videoFrameFinder:c,audioFrameFinder:h}=wq({video:a.video==null?null:{...a.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:a.audio},await this.localFile.createReader(),s,o,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=c,this.audioFrameFinder=h;const{codedWidth:d,codedHeight:f}=a.video??{};d&&f&&(this.vfRotater=bq(d,f,u.rotationDeg)),this._meta=_q(a,s,o,u.rotationDeg),this.logger.info("Video meta:",this._meta);const p={...this._meta};this.width=this.width===0?p.width:this.width,this.height=this.height===0?p.height:this.height,this.trim.to=this.trim.to===0?p.duration:Math.min(this.trim.to,p.duration),this.trim.from=Math.min(this.trim.from,this.trim.to);const m=(this.trim.to-this.trim.from)/this.playbackRate;return this.duration=this.duration===0?m:this.duration,Math.abs(this.duration-m)>1&&(this.duration=m),this.display.to=this.display.from+this.duration,this.on("propsChange",g=>{g.volume!==void 0&&this.audioFrameFinder&&this.audioFrameFinder.setVolume(g.volume)}),p})}tickInterceptor=async(e,t)=>t;async tick(e){const t=e+this.trim.from;if(t>this.trim.to||t>this._meta.duration)return await this.tickInterceptor(e,{audio:await this.audioFrameFinder?.find(t)??[],state:"done"});const[i,n]=await Promise.all([this.audioFrameFinder?.find(t)??[],this.videoFrameFinder?.find(t).then(this.vfRotater)]);return n==null?await this.tickInterceptor(e,{audio:i,state:"success"}):await this.tickInterceptor(e,{video:n,audio:i,state:"success"})}thumbAborter=new AbortController;thumbFinder=null;async thumbnails(e=100,t){this.thumbAborter.abort(),this.thumbAborter=new AbortController;const i=this.thumbAborter.signal;await this.ready;const n="generate thumbnails aborted";if(i.aborted)throw Error(n);const{width:s,height:o}=this._meta,a=kq(e,Math.round(o*(e/s)),{quality:.1,type:"image/png"});return new Promise(async(l,u)=>{const c=[],h=this.decoderConf.video;if(h==null||this.videoSamples.length===0){l([]);return}let d=null;i.addEventListener("abort",()=>{u(Error(n))});try{const{start:f=0,end:p=this._meta.duration,step:m}=t??{};if(m){let g=f;for(this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null),d=new Hk(await this.localFile.createReader(),this.videoSamples,{...h,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__}),this.thumbFinder=d;g<=p&&!i.aborted;){const v=await d.find(g);if(v){const x=await a(v);c.push({ts:v.timestamp,img:x})}g+=m}if(c.length===0&&!i.aborted){const v=await d.find(0);if(v){const x=await a(v);c.push({ts:v.timestamp,img:x})}}}else await Bq(this.videoSamples,this.localFile,h,i,{start:f,end:p},async(g,v)=>{if(g!=null){const x=await a(g);c.push({ts:g.timestamp,img:x})}})}catch(f){u(f);return}finally{d&&(await d.destroy(),this.thumbFinder===d&&(this.thumbFinder=null))}l(c)})}async split(e){if(await this.ready,e<=0||e>=this._meta.duration)throw Error("time out of bounds");const[t,i]=Eq(this.videoSamples,e),[n,s]=Pq(this.audioSamples,e),o=new wr({localFile:this.localFile,videoSamples:t??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),a=new wr({localFile:this.localFile,videoSamples:i??[],audioSamples:s??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await Promise.all([o.ready,a.ready]),[o,a]}addEffect(e){this.effects.push(e)}editEffect(e,t){const i=this.effects.find(n=>n.id===e);i&&Object.assign(i,t)}removeEffect(e){const t=this.effects.findIndex(i=>i.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=new wr({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await e.ready,e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e.id=this.id,e.effects=[...this.effects],e}async splitTrack(){await this.ready;const e=[];if(this.videoSamples.length>0){const t=new wr({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[],decoderConf:{video:this.decoderConf.video,audio:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}if(this.audioSamples.length>0){const t=new wr({localFile:this.localFile,videoSamples:[],audioSamples:[...this.audioSamples],decoderConf:{audio:this.decoderConf.audio,video:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}return e}cleanupThumbnails=async()=>{this.thumbAborter.abort(),this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null)};destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("Video destroy"),super.destroy(),this.thumbAborter.abort(),this.thumbFinder?.destroy(),this.thumbFinder=null,this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(e=!1){return{...super.toJSON(e),type:"Video",audio:this.audio,volume:this.volume,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Video")throw new Error(`Expected Video, got ${e.type}`);const t=e.audio!==void 0?{audio:e.audio,volume:e.volume}:{volume:e.volume},i=await No.getReadableStream(e.src),n=new wr(i,t,e.src);return n.left=e.left,n.top=e.top,n.width=e.width,n.height=e.height,n.angle=e.angle,n.display.from=e.display.from,n.display.to=e.display.to,n.duration=e.duration,n.playbackRate=e.playbackRate,n.zIndex=e.zIndex,n.opacity=e.opacity,n.flip=e.flip,e.style&&(n.style={...n.style,...e.style}),e.animation&&n.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(n.id=e.id),e.effects&&(n.effects=e.effects),e.transition&&(n.transition=e.transition),e.trim&&(n.trim.from=e.trim.from,n.trim.to=e.trim.to),e.volume!==void 0&&(n.volume=e.volume),e.chromaKey&&(n.chromaKey={...n.chromaKey,...e.chromaKey}),e.colorAdjustment&&(n.colorAdjustment={...n.colorAdjustment,...e.colorAdjustment}),e.locked!==void 0&&(n.locked=e.locked),n}async createPlaybackElement(){await this.ready;const t=this.localFile;if(!t||typeof t.getOriginFile!="function")throw new Error("Video does not have a local file for playback");const i=await t.getOriginFile();if(!i)throw new Error("Failed to get origin file from VideoClip");const n=URL.createObjectURL(i),s=document.createElement("video");return s.crossOrigin="anonymous",s.muted=!0,s.autoplay=!1,s.playsInline=!0,s.preload="auto",s.loop=!1,s.src=n,await new Promise((o,a)=>{const l=()=>{s.removeEventListener("loadeddata",l),s.removeEventListener("error",u),s.pause(),s.currentTime=0,o()},u=()=>{s.removeEventListener("loadeddata",l),s.removeEventListener("error",u),a(new Error("Failed to load video"))};s.addEventListener("loadeddata",l,{once:!0}),s.addEventListener("error",u,{once:!0}),s.load()}),{element:s,objectUrl:n}}async play(e,t){const i=e,n=t+this.trim.from/1e6;if(Math.abs(i.currentTime-n)>.1&&(i.currentTime=n),i.muted=!1,i.paused)try{await i.play()}catch{try{await i.play()}catch(o){console.warn("Failed to play video:",o)}}}pause(e){const t=e;t.pause(),t.muted=!0}async seek(e,t){const i=e,n=t+this.trim.from/1e6;return i.pause(),i.currentTime=n,new Promise(s=>{if(Math.abs(i.currentTime-t)<.01){s();return}const o=()=>{i.removeEventListener("seeked",o),s()};i.addEventListener("seeked",o,{once:!0}),setTimeout(()=>{i.removeEventListener("seeked",o),s()},500)})}syncPlayback(e,t,i){const n=e,s=(this.trim.to-this.trim.from)/1e6,o=i>=0&&i<s,a=i+this.trim.from/1e6;n.volume=this.volume,t&&o?n.paused?this.play(n,i).catch(console.warn):(n.muted&&(n.muted=!1),(n.ended||n.currentTime>=this.trim.to/1e6)&&(n.currentTime=a,n.play().catch(console.warn))):(n.paused||n.pause(),n.muted=!0,o&&Math.abs(n.currentTime-a)>.1&&(n.currentTime=a))}cleanupPlayback(e,t){const i=e;i.pause(),i.removeAttribute("src"),i.load(),t&&URL.revokeObjectURL(t)}async scaleToFit(e,t){await this.ready;const{width:i,height:n}=this.meta;if(i===0||n===0)return;const s=Math.min(e/i,t/n);this.width=i*s,this.height=n*s}async scaleToFill(e,t){await this.ready;const{width:i,height:n}=this.meta;if(i===0||n===0)return;const s=Math.max(e/i,t/n);this.width=i*s,this.height=n*s}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}}function _q(r,e,t,i){const n={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(r.video!=null&&e.length>0){n.width=r.video.codedWidth??0,n.height=r.video.codedHeight??0;const a=(Math.round(i/90)*90+360)%360;(a===90||a===270)&&([n.width,n.height]=[n.height,n.width])}r.audio!=null&&t.length>0&&(n.audioSampleRate=st.sampleRate,n.audioChanCount=st.channelCount);let s=0,o=0;if(e.length>0)for(let a=e.length-1;a>=0;a--){const l=e[a];if(!l.deleted){s=l.cts+l.duration;break}}if(t.length>0){const a=t.at(-1);o=a.cts+a.duration}return n.duration=Math.max(s,o),n}function wq(r,e,t,i,n){return{audioFrameFinder:n===0||r.audio==null||i.length===0?null:new Tq(e,i,r.audio,{volume:n,targetSampleRate:st.sampleRate}),videoFrameFinder:r.video==null||t.length===0?null:new Hk(e,t,r.video)}}async function Nk(r,e={}){let t=null;const i={video:null,audio:null};let n=[],s=[],o=[];const a={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let l=-1,u=-1;const c=await r.createReader();await xq(c,async d=>{t=d.info;const f=d.mp4boxFile.ftyp;o.push({start:f.start,size:f.size});const p=d.mp4boxFile.moov;o.push({start:p.start,size:p.size}),Object.assign(a,yq(t.videoTracks[0]?.matrix));let{videoDecoderConf:m,audioDecoderConf:g}=jb(d.mp4boxFile,d.info);if(i.video=m??null,i.audio=g??null,m==null&&g==null&&Ee.error("Video no video and audio track"),g!=null){const{supported:v}=await AudioDecoder.isConfigSupported(g);v||Ee.error(`Video audio codec is not supported: ${g.codec}`)}if(m!=null){const{supported:v}=await VideoDecoder.isConfigSupported(m);v||Ee.error(`Video video codec is not supported: ${m.codec}`)}Ee.info("mp4BoxFile moov ready",{...d.info,tracks:null,videoTracks:null,audioTracks:null},i)},(d,f,p)=>{if(f==="video"){l===-1&&(l=p[0].dts);for(const m of p)n.push(Gk(m,l,"video"))}else if(f==="audio"&&e.audio){u===-1&&(u=p[0].dts);for(const m of p)s.push(Gk(m,u,"audio"))}}),await c.close();const h=n.at(-1)??s.at(-1);if(t==null)throw Error("Video stream is done, but not emit ready");if(h==null)throw Error("Video stream not contain any sample");return Jb(n),Ee.info("mp4 stream parsed"),{videoSamples:n,audioSamples:s,decoderConf:i,headerBoxPos:o,parsedMatrix:a}}function Gk(r,e=0,t){let i=r.offset;const n=t==="video"&&r.is_sync?Iq(r.data,r.description.type):-1;let s=r.size;return n>0&&(i+=n,s-=n),{...r,is_idr:n>=0,offset:i,size:s,cts:(r.cts-e)/r.timescale*1e6,dts:(r.dts-e)/r.timescale*1e6,duration:r.duration/r.timescale*1e6,timescale:1e6,data:t==="video"?null:r.data}}class Hk{constructor(e,t,i){this.localFileReader=e,this.samples=t,this.conf=i}decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async e=>{(this.decoder==null||this.decoder.state==="closed"||e<=this.timestamp||e-this.timestamp>3e6)&&this.reset(e),this.curAborter.abort=!0,this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const t=await this.parseFrame(e,this.decoder,this.curAborter);return this.sleepCnt=0,t};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;parseFrame=async(e,t,i)=>{if(t==null||t.state==="closed"||i.abort)return null;if(this.videoFrames.length>0){const n=this.videoFrames[0];return e<n.timestamp?null:(this.videoFrames.shift(),e>n.timestamp+(n.duration??0)?(n.close(),await this.parseFrame(e,t,i)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(t).catch(s=>{throw this.predecodeErr=!0,this.reset(e),s}),n))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&t.decodeQueueSize>0){if(performance.now()-i.st>6e3)throw Error(`Video.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await Au(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(t)}catch(n){throw this.reset(e),n}}return await this.parseFrame(e,t,i)};decoding=!1;startDecode=async e=>{if(this.decoding||e.decodeQueueSize>600)return;let t=this.videoDecCursorIdx+1;if(t>this.samples.length)return;this.decoding=!0;let i=!1;for(;t<this.samples.length;t++){const n=this.samples[t];if(!i&&!n.deleted&&(i=!0),n.is_idr)break}if(i){const n=this.samples.slice(this.videoDecCursorIdx,t);if(n[0]?.is_idr!==!0)Ee.warn("First sample not idr frame");else{const s=performance.now(),o=await Vk(n,this.localFileReader),a=performance.now()-s;if(a>1e3){const l=n[0],u=n.at(-1),c=u.offset+u.size-l.offset;Ee.warn(`Read video samples time cost: ${Math.round(a)}ms, file chunk size: ${c}`)}if(e.state==="closed")return;this.lastVfDur=o[0]?.duration??0,Zb(e,o,{onDecodingError:l=>{if(this.downgradeSoftDecode)throw l;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,Ee.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=o.length}}this.videoDecCursorIdx=t,this.decoding=!1};reset=e=>{if(this.decoding=!1,this.videoFrames.forEach(i=>i.close()),this.videoFrames=[],e==null||e===0)this.videoDecCursorIdx=0;else{let i=0;for(let n=0;n<this.samples.length;n++){const s=this.samples[n];if(s.is_idr&&(i=n),!(s.cts<e)){this.videoDecCursorIdx=i;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const t={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:i=>{if(this.outputFrameCnt+=1,i.timestamp===-1){i.close();return}let n=i;i.duration==null&&(n=new VideoFrame(i,{duration:this.lastVfDur}),i.close()),this.videoFrames.push(n)},error:i=>{if(i.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,Ee.warn(i.message);return}const n=`VideoFinder VideoDecoder err: ${i.message}, config: ${JSON.stringify(t)}, state: ${JSON.stringify(this.getState())}`;throw Ee.error(n),Error(n)}}),this.decoder.configure(t)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:Kb,sleepCnt:this.sleepCnt,memInfo:Xk()});destroy=async()=>{if(this.curAborter.abort=!0,this.videoFrames.forEach(e=>e.close()),this.videoFrames=[],this.decoder&&this.decoder.state!=="closed")try{this.decoder.close()}catch{}this.decoder=null,this.localFileReader.close()}}function Sq(r,e){for(let t=0;t<e.length;t++){const i=e[t];if(r>=i.cts&&r<i.cts+i.duration)return t;if(i.cts>r)break}return 0}class Tq{constructor(e,t,i,n){this.localFileReader=e,this.samples=t,this.conf=i,this.volume=n.volume,this.sampleRate=n.targetSampleRate}volume=1;sampleRate;setVolume(e){this.volume=e,this.reset()}decoder=null;curAborter={abort:!1,st:performance.now()};find=async e=>{const t=e<=this.timestamp||e-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||t)&&this.reset(),t&&(this.timestamp=e,this.decCursorIdx=Sq(e,this.samples)),this.curAborter.abort=!0;const i=e-this.timestamp;this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const n=await this.parseFrame(Math.ceil(i*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,n};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(e,t=null,i)=>{if(t==null||i.abort||t.state==="closed"||e===0)return[];const n=this.pcmData.frameCnt-e;if(n>0)return n<st.sampleRate/10&&this.startDecode(t),Wk(this.pcmData,e);if(t.decoding){if(performance.now()-i.st>3e3)throw i.abort=!0,Error(`Video.tick audio timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await Au(15)}else{if(this.decCursorIdx>=this.samples.length-1)return Wk(this.pcmData,this.pcmData.frameCnt);this.startDecode(t)}return this.parseFrame(e,t,i)};startDecode=e=>{if(e.decodeQueueSize>10)return;const i=[];let n=this.decCursorIdx;for(;n<this.samples.length;){const s=this.samples[n];if(n+=1,!s.deleted&&(i.push(s),i.length>=10))break}this.decCursorIdx=n,e.decode(i.map(s=>new EncodedAudioChunk({type:"key",timestamp:s.cts,duration:s.duration,data:s.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=Cq(this.conf,{resampleRate:st.sampleRate,volume:this.volume},e=>{this.pcmData.data.push(e),this.pcmData.frameCnt+=e[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:Kb,sleepCnt:this.sleepCnt,memInfo:Xk()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function Cq(r,e,t){let i=0,n=0;const s=c=>{if(n+=1,c.length!==0){if(e.volume!==1)for(const h of c)for(let d=0;d<h.length;d++)h[d]*=e.volume;c.length===1&&(c=[c[0],c[0]]),t(c)}},o=Aq(s),a=e.resampleRate!==r.sampleRate;let l=new AudioDecoder({output:c=>{const h=oS(c);a?o(()=>gL(h,c.sampleRate,{rate:e.resampleRate,chanCount:c.numberOfChannels})):s(h),c.close()},error:c=>{c.message.includes("Codec reclaimed due to inactivity")||u("Video AudioDecoder err",c)}});l.configure(r);function u(c,h){const d=`${c}: ${h.message}, state: ${JSON.stringify({qSize:l.decodeQueueSize,state:l.state,inputCnt:i,outputCnt:n})}`;throw Ee.error(d),Error(d)}return{decode(c){i+=c.length;try{for(const h of c)l.decode(h)}catch(h){u("decode audio chunk error",h)}},close(){l.state!=="closed"&&l.close()},get decoding(){return i>n&&l.decodeQueueSize>0},get state(){return l.state},get decodeQueueSize(){return l.decodeQueueSize}}}function Aq(r){const e=[];let t=0;function i(o,a){e[a]=o,n()}function n(){const o=e[t];o!=null&&(r(o),t+=1,n())}let s=0;return o=>{const a=s;s+=1,o().then(l=>i(l,a)).catch(l=>i(l,a))}}function Wk(r,e){const t=[new Float32Array(e),new Float32Array(e)];let i=0,n=0;for(;n<r.data.length;){const[s,o]=r.data[n];if(i+s.length>e){const a=e-i;t[0].set(s.subarray(0,a),i),t[1].set(o.subarray(0,a),i),r.data[n][0]=s.subarray(a,s.length),r.data[n][1]=o.subarray(a,o.length);break}else t[0].set(s,i),t[1].set(o,i),i+=s.length,n++}return r.data=r.data.slice(n),r.frameCnt-=e,t}async function Vk(r,e){const t=r[0],i=r.at(-1);if(i==null)return[];const n=i.offset+i.size-t.offset;if(n<3e7){const s=new Uint8Array(await e.read(n,{at:t.offset}));return r.map(o=>{const a=o.offset-t.offset;return new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:s.subarray(a,a+o.size)})})}return await Promise.all(r.map(async s=>new EncodedVideoChunk({type:s.is_sync?"key":"delta",timestamp:s.cts,duration:s.duration,data:await e.read(s.size,{at:s.offset})})))}function Eq(r,e){if(r.length===0)return[];let t=0,i=0,n=-1;for(let l=0;l<r.length;l++){const u=r[l];if(n===-1&&e<u.cts&&(n=l-1),u.is_idr)if(n===-1)t=l;else{i=l;break}}const s=r[n];if(s==null)throw Error("Not found video sample by time");const o=r.slice(0,i===0?r.length:i).map(l=>({...l}));for(let l=t;l<o.length;l++){const u=o[l];e<u.cts&&(u.deleted=!0,u.cts=-1)}Jb(o);const a=r.slice(s.is_idr?n:t).map(l=>({...l,cts:l.cts-e}));for(const l of a)l.cts<0&&(l.deleted=!0,l.cts=-1);return Jb(a),[o,a]}function Pq(r,e){if(r.length===0)return[];let t=-1;for(let s=0;s<r.length;s++){const o=r[s];if(!(e>o.cts)){t=s;break}}if(t===-1)throw Error("Not found audio sample by time");const i=r.slice(0,t).map(s=>({...s})),n=r.slice(t).map(s=>({...s,cts:s.cts-e}));return[i,n]}function Zb(r,e,t){if(r.state==="configured"){for(let i=0;i<e.length;i++)r.decode(e[i]);r.flush().catch(i=>{if(!(i instanceof Error))throw i;if(i.message.includes("Decoding error")&&t.onDecodingError!=null){t.onDecodingError(i);return}if(!i.message.includes("Aborted due to close"))throw i})}}function Iq(r,e){if(e!=="avc1"&&e!=="hvc1")return 0;const t=new DataView(r.buffer);for(let i=0;i<r.byteLength-4;){if(e==="avc1"){const n=t.getUint8(i+4)&31;if(n===5||n===7||n===8)return i}else if(e==="hvc1"){const n=t.getUint8(i+4)>>1&63;if(n===19||n===20||n===32||n===33||n===34)return i}i+=t.getUint32(i)+4}return-1}function Jb(r){let e=0,t=null;for(const i of r)if(!i.deleted){if(i.is_sync&&(e+=1),e>=2)break;(t==null||i.cts<t.cts)&&(t=i)}t!=null&&t.cts<2e5&&(t.duration+=t.cts,t.cts=0)}function Xk(){try{const r=performance.memory;return{jsHeapSizeLimit:r.jsHeapSizeLimit,totalJSHeapSize:r.totalJSHeapSize,usedJSHeapSize:r.usedJSHeapSize,percentUsed:(r.usedJSHeapSize/r.jsHeapSizeLimit).toFixed(3),percentTotal:(r.totalJSHeapSize/r.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}async function Bq(r,e,t,i,n,s){const o=await e.createReader(),a=await Vk(r.filter(c=>!c.deleted&&c.is_sync&&c.cts>=n.start&&c.cts<=n.end),o);if(a.length===0||i.aborted){s(null,!0);return}let l=0;Zb(u(),a,{onDecodingError:c=>{Ee.warn("thumbnailsByKeyFrame",c),l===0?Zb(u(!0),a,{onDecodingError:h=>{o.close(),Ee.error("thumbnailsByKeyFrame retry soft deocde",h)}}):(s(null,!0),o.close())}});function u(c=!1){const h={...t,...c?{hardwareAcceleration:"prefer-software"}:{}},d=new VideoDecoder({output:f=>{l+=1;const p=l===a.length;s(f,p),p&&(o.close(),d.state!=="closed"&&d.close())},error:f=>{const p=`thumbnails decoder error: ${f.message}, config: ${JSON.stringify(h)}, state: ${JSON.stringify({qSize:d.decodeQueueSize,state:d.state,outputCnt:l,inputCnt:a.length})}`;throw Ee.error(p),Error(p)}});return i.addEventListener("abort",()=>{o.close(),d.state!=="closed"&&d.close()}),d.configure(h),d}}function kq(r,e,t){return async i=>{try{const n=Math.max(1,Math.round(r)),s=Math.max(1,Math.round(e));Ee.info(`[Video.convtr] START: ${n}x${s}, ts: ${i.timestamp}`),Ee.info("[Video.convtr] Creating OffscreenCanvas");const o=new OffscreenCanvas(n,s);Ee.info("[Video.convtr] Getting Context");const a=o.getContext("2d");Ee.info("[Video.convtr] Drawing image"),a.drawImage(i,0,0,n,s),Ee.info("[Video.convtr] Closing VideoFrame"),i.close(),Ee.info("[Video.convtr] Calling convertToBlob");const l=await o.convertToBlob(t);return Ee.info(`[Video.convtr] FINISHED: ${l.size} bytes`),l}catch(n){throw Ee.error(`[Video.convtr] ERROR: ${n?.message||n}`),n}}}class Zi extends zn{type="Text";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}get width(){return this._width}set width(e){Math.abs(this.width-e)<.1||(this._width=e,this.refreshText().then(()=>{this.emit("propsChange",{width:e})}))}get height(){return this._height}set height(e){Math.abs(this.height-e)<.1||(this._height=e,this.refreshText().then(()=>{this.emit("propsChange",{height:e})}))}_lastContentWidth=0;_lastContentHeight=0;_text="";get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this.originalOpts&&this.textStyle&&this.refreshText().then(()=>{this.emit("propsChange",{text:e})}))}get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,fill:this.originalOpts.fill,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,dropShadow:this.originalOpts.dropShadow?{color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing,textCase:this.originalOpts.textCase,textDecoration:this.originalOpts.textDecoration}}set style(e){this.updateStyle(e)}get textAlign(){return this.originalOpts.align||this.originalOpts.textAlign||"left"}set textAlign(e){this.updateStyle({align:e})}get verticalAlign(){return this.originalOpts.verticalAlign||this.originalOpts.textDecoration||"top"}set verticalAlign(e){["underline","overline","strikethrough","line-through"].includes(e)?(this.updateStyle({textDecoration:e==="strikethrough"?"line-through":e}),this.originalOpts.verticalAlign=e):this.updateStyle({verticalAlign:e})}get textCase(){return this.originalOpts.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}pixiTextContainer=null;wordTexts=[];textStyle;textStyleBase;renderTexture=null;externalRenderer=null;pixiApp=null;originalOpts;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];constructor(e,t={},i){super(),this.originalOpts={...t},this.text=e,this.externalRenderer=i??null;const n=this.createStyleFromOpts(t),{wordWrap:s,wordWrapWidth:o,lineHeight:a,letterSpacing:l,fill:u,...c}=n,h=new Bt(n),d=new Bt(c);this.textStyle=h,this.textStyleBase=d,this.ready=(async()=>(await this.refreshText(),{...this._meta}))()}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("TextClip: Failed to create renderer. Please provide a renderer via constructor or setRenderer() method.");return this.pixiApp.renderer}async getTexture(){return this.pixiTextContainer==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture)}async tick(e){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("Text not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture});const i=this.renderTexture.source?.resource?.source;let n;if(i instanceof HTMLCanvasElement)n=await createImageBitmap(i);else if(i instanceof OffscreenCanvas)n=await createImageBitmap(i);else{const a=(await this.getRenderer()).extract.canvas(this.renderTexture);if(a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas)n=await createImageBitmap(a);else{const l=this.renderTexture.width,u=this.renderTexture.height;throw new OffscreenCanvas(l,u).getContext("2d")==null?new Error("Failed to create 2d context for fallback rendering"):new Error("Unable to extract canvas from render texture")}}return{video:n,state:"success"}}async split(e){await this.ready;const t=await this.clone(),i=await this.clone();return[t,i]}animate(e){super.animate(e,this.pixiTextContainer)}addEffect(e){this.effects.push(e)}editEffect(e,t){const i=this.effects.find(n=>n.id===e);i&&Object.assign(i,t)}removeEffect(e){const t=this.effects.findIndex(i=>i.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.textStyle,t=this.originalOpts||{},i=o=>{if(o!=null){if(typeof o=="number")return o;if(o instanceof ye)return o.toNumber()}},n={fontSize:t.fontSize??e.fontSize,fontFamily:t.fontFamily??(Array.isArray(e.fontFamily)?e.fontFamily[0]:typeof e.fontFamily=="string"?e.fontFamily:"Roboto"),fontWeight:t.fontWeight??e.fontWeight,fontStyle:t.fontStyle??e.fontStyle,align:t.align??(e.align==="justify"?"left":e.align),textCase:t.textCase,textDecoration:t.textDecoration};if(t.fill&&typeof t.fill=="object"&&"type"in t.fill&&t.fill.type==="gradient")n.fill=t.fill;else{const o=i(e.fill);n.fill=o??16777215}if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke)n.stroke=t.stroke;else{const o=i(e.stroke);o!==void 0&&(n.stroke=o),n.strokeWidth=t.strokeWidth??e.strokeThickness??0}if(t.dropShadow)n.dropShadow=t.dropShadow;else if(e.dropShadow){const o=e.dropShadow,a=i(o.color);a!==void 0&&(n.dropShadow={color:a,alpha:o.alpha,blur:o.blur,angle:o.angle,distance:o.distance})}if(t.wordWrap!==void 0?(n.wordWrap=t.wordWrap,n.wordWrapWidth=t.wordWrapWidth):e.wordWrap&&(n.wordWrap=e.wordWrap,n.wordWrapWidth=e.wordWrapWidth),t.lineHeight!==void 0)n.lineHeight=t.lineHeight;else if(e.lineHeight!==void 0){const o=n.fontSize??e.fontSize??40;n.lineHeight=e.lineHeight/o}t.letterSpacing!==void 0?n.letterSpacing=t.letterSpacing:e.letterSpacing!==void 0&&(n.letterSpacing=e.letterSpacing);const s=new Zi(this.text,n);return await s.ready,this.copyStateTo(s),s.id=this.id,s.effects=[...this.effects],s}async updateStyle(e){let t={...e};e.style&&(t={...t,...e.style},delete t.style),this.originalOpts={...this.originalOpts,...t};const i=this.createStyleFromOpts(this.originalOpts),{wordWrap:n,wordWrapWidth:s,lineHeight:o,letterSpacing:a,fill:l,...u}=i,c=new Bt(u),h=new Bt(i);this.textStyle=h,this.textStyleBase=c,await this.refreshText(),this.emit("propsChange",e)}async refreshText(){const e=this.textStyle,t=this.textStyleBase;let i=this.text;const n=this.originalOpts.textCase;n==="uppercase"?i=i.toUpperCase():n==="lowercase"?i=i.toLowerCase():n==="title"&&(i=i.replace(/\w\S*/g,k=>k.charAt(0).toUpperCase()+k.substring(1).toLowerCase())),typeof document<"u"&&await document.fonts.ready,this.pixiTextContainer?this.pixiTextContainer.removeChildren():this.pixiTextContainer=new Ie;const s=i.split(/\s+/).filter(k=>k.length>0);this.wordTexts.forEach(k=>k.destroy()),this.wordTexts=s.map(k=>{const W=new kl({text:k,style:this.textStyle});return this.pixiTextContainer.addChild(W),W});const o=this.originalOpts.textDecoration||this.originalOpts.verticalAlign,a=this.originalOpts.lineHeight??1,l=e.fontSize??40,u=l*a,c=Ht.measureText(" ",t),h=new kl({text:" ",style:this.textStyleBase}),d=Math.ceil(h.getLocalBounds().width||h.width||c.width);h.destroy();const f=e.wordWrap&&e.wordWrapWidth>0?e.wordWrapWidth:1e5,p=[];let m=[],g=0,v=0;this.wordTexts.forEach(k=>{const W=k.getLocalBounds(),G=Math.ceil(W.width||k.width),J=Math.ceil(W.height||k.height),q=g+(g>0?d:0)+G;q<=f||m.length===0?(m.push(k),g=q,v=Math.max(v,J)):(m.length>0&&p.push({words:m,width:g,height:Math.max(v,u)}),m=[k],g=G,v=J)}),m.length>0&&p.push({words:m,width:g,height:Math.max(v,u)});let x=0,y=0;p.forEach(k=>{x=Math.max(x,k.width),y+=k.height});const b=x,T=y;let E=b;e.wordWrap&&e.wordWrapWidth>0&&(E=Math.max(E,e.wordWrapWidth));const C=T,P=this.width===0||Math.abs(this.width-this._lastContentWidth)<.1,_=this.height===0||Math.abs(this.height-this._lastContentHeight)<.1,S=P?E:Math.max(E,this.width||0),I=_?C:Math.max(C,this.height||0);this._lastContentWidth=E,this._lastContentHeight=C;let M=0;const O=this.originalOpts.verticalAlign||"top";O==="center"?M=(I-T)/2:O==="bottom"&&(M=I-T);let H=M;const K=new Je;let D=!1;p.forEach(k=>{let W=0;const G=this.textAlign;G==="center"?W=(S-k.width)/2:G==="right"&&(W=S-k.width);const J=W;if(k.words.forEach((q,_e)=>{q.x=Math.round(W),q.y=Math.round(H),W+=(q.getLocalBounds().width||q.width)+(_e<k.words.length-1?d:0)}),o&&o!=="none"&&["underline","overline","strikethrough","line-through"].includes(o)){D=!0;const q=o==="strikethrough"?"line-through":o,_e=Math.max(1,l/12);let Re=16777215;typeof e.fill=="number"?Re=e.fill:e.fill&&typeof e.fill=="object"&&"fill"in e.fill&&(Re=16777215);let ge=0;q==="underline"?ge=k.height:q==="line-through"?ge=k.height/2:q==="overline"&&(ge=0),K.rect(J,H+ge,k.width,_e),K.fill(Re)}H+=k.height}),D&&this.pixiTextContainer.addChild(K),this.renderTexture&&this.renderTexture.destroy(),this.renderTexture=Ot.create({width:S,height:I}),this._meta.width=S,this._meta.height=I,this._width=S,this._height=I,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration)}createStyleFromOpts(e){const t=e.fontSize??40,i=e.lineHeight??1,n={fontSize:t,fontFamily:e.fontFamily??"Roboto",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",align:e.align??"left",wordWrap:e.wordWrap??!1,wordWrapWidth:e.wordWrapWidth??100,lineHeight:t*i,letterSpacing:e.letterSpacing??0};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const s=new zr(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:o,color:a})=>{const l=typeof a=="number"?a:xt(a)??16777215;s.addColorStop(o,l)}),n.fill={fill:s}}else{const{color:s,alpha:o}=Ln(e.fill);n.fill=s,o<1&&(n.fillAlpha=o)}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const s=xt(e.stroke.color);s!==void 0&&(n.stroke={color:s,width:e.stroke.width,join:e.stroke.join,cap:e.stroke.cap,miterLimit:e.stroke.miterLimit})}else{const s=xt(e.stroke),o=e.strokeWidth??0;s!==void 0&&o>0?n.stroke={color:s,width:o}:e.strokeWidth&&e.strokeWidth>0&&(n.stroke={color:0,width:e.strokeWidth})}if(e.dropShadow){const s=xt(e.dropShadow.color);s!==void 0&&(n.dropShadow={color:s,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}return n}destroy(){if(!this.destroyed){Ee.info("Text destroy");try{this.pixiTextContainer!=null&&(this.pixiTextContainer.destroyed||this.pixiTextContainer.destroy({children:!0}))}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),i={};return this.originalOpts.fontSize!==void 0&&(i.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(i.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontWeight!==void 0&&(i.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(i.fontStyle=this.originalOpts.fontStyle),this.originalOpts.fill!==void 0&&(i.color=this.originalOpts.fill),this.originalOpts.align!==void 0&&(i.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(i.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(i.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(i.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(i.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?i.stroke={color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:i.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.dropShadow&&(i.shadow={color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}),{...t,type:"Text",text:this.text,style:i,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Text")throw new Error(`Expected Text, got ${e.type}`);const t=e.text||"",i=e.style||{},n={};i.fontSize!==void 0&&(n.fontSize=i.fontSize),i.fontFamily!==void 0&&(n.fontFamily=i.fontFamily),i.fontWeight!==void 0&&(n.fontWeight=i.fontWeight),i.fontStyle!==void 0&&(n.fontStyle=i.fontStyle),i.color!==void 0&&(n.fill=i.color),i.align!==void 0&&(n.align=i.align),i.wordWrap!==void 0&&(n.wordWrap=i.wordWrap),i.wordWrapWidth!==void 0&&(n.wordWrapWidth=i.wordWrapWidth),i.lineHeight!==void 0&&(n.lineHeight=i.lineHeight),i.letterSpacing!==void 0&&(n.letterSpacing=i.letterSpacing),i.stroke&&(i.stroke.join||i.stroke.cap||i.stroke.miterLimit!==void 0?n.stroke={color:i.stroke.color,width:i.stroke.width,join:i.stroke.join,cap:i.stroke.cap,miterLimit:i.stroke.miterLimit}:(n.stroke=i.stroke.color,n.strokeWidth=i.stroke.width)),i.shadow&&(n.dropShadow={color:i.shadow.color,alpha:i.shadow.alpha,blur:i.shadow.blur,distance:i.shadow.distance,angle:i.shadow.angle});const s=new Zi(t,n);return s.left=e.left,s.top=e.top,s.width=e.width,s.height=e.height,s.angle=e.angle,s.display.from=e.display.from,s.display.to=e.display.to,s.duration=e.duration,s.playbackRate=e.playbackRate,s.zIndex=e.zIndex,s.opacity=e.opacity,s.flip=e.flip,e.animation&&s.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(s.id=e.id),e.effects&&(s.effects=e.effects),await s.ready,s}getVisibleHandles(){return["mr","mb","br","rot"]}}function Rq(r){return r.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase())}class Ji extends zn{type="Effect";ready;_meta={duration:5e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effect;constructor(e){super(),this.effect={id:`eff_${Date.now()}`,key:e,name:e},this.name=Rq(e),this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Ji(this.effect.key);return this.copyStateTo(e),e.effect={...this.effect},e.id=this.id,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),i=await this.clone();return[t,i]}toJSON(e=!1){return{...super.toJSON(e),type:"Effect",effect:this.effect,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Effect")throw new Error(`Expected Effect, got ${e.type}`);const t=new Ji(e.effect.key);return t.effect=e.effect,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}class Ml extends zn{type="Placeholder";meta={width:0,height:0,duration:0};constructor(e,t={},i="Placeholder"){super(),this.type=i,this.src=e,this.meta={width:t.width||1280,height:t.height||720,duration:t.duration||5e6},this.width=this.meta.width,this.height=this.meta.height,this.duration=this.meta.duration,this.trim.to=this.duration,this.display.to=this.display.from+this.duration,this.ready=Promise.resolve(this.meta)}canvas=null;ctx=null;animationRafId=null;renderPending=!1;async tick(e){this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.width=this.meta.width,this.canvas.height=this.meta.height,this.ctx=this.canvas.getContext("2d"));const{canvas:t,ctx:i}=this;if(i){const{width:s,height:o}=t;if(s>0&&o>0){i.fillStyle="#1e1e1e",i.fillRect(0,0,s,o);const a=s/2,l=o/2,u=100,c=u/4,h=performance.now()/2e3*Math.PI*2;i.save();const d=i.createConicGradient(h,a,l);d.addColorStop(0,"#ffffff"),d.addColorStop(.2,"#ffffff"),d.addColorStop(.5,"rgba(255, 255, 255, 0.4)"),d.addColorStop(.8,"rgba(255, 255, 255, 0.1)"),d.addColorStop(1,"rgba(255, 255, 255, 0)"),i.strokeStyle=d,i.lineWidth=c,i.lineCap="round",i.beginPath(),i.arc(a,l,u,h,h+Math.PI*1.5),i.stroke(),i.restore(),i.strokeStyle="#333333",i.lineWidth=10,i.strokeRect(0,0,s,o)}}if(this.renderPending=!1,this.animationRafId===null){const s=()=>{if(this.destroyed){this.animationRafId=null;return}this.renderPending||(this.renderPending=!0,this.emit("request-render")),this.animationRafId=requestAnimationFrame(s)};this.animationRafId=requestAnimationFrame(s)}return{video:t.width>0&&t.height>0?await createImageBitmap(t):null,state:"success",audio:[]}}async clone(){const e=new Ml(this.src,this.meta);return this.copyStateTo(e),e.id=this.id,e}async split(e){const t=await this.clone(),i=await this.clone();return t.trim.to=e+this.trim.from,i.trim.from=e+this.trim.from,t.duration=t.trim.to-t.trim.from,i.duration=i.trim.to-i.trim.from,t.display.to=t.display.from+t.duration,i.display.from=t.display.to,i.display.to=i.display.from+i.duration,[t,i]}static async fromObject(e){if(e.type!=="Placeholder")throw new Error(`Expected Placeholder, got ${e.type}`);const t=new Ml(e.src,{width:e.width,height:e.height,duration:e.duration});return t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.id&&(t.id=e.id),await t.ready,t}}class Fi extends zn{type="Transition";ready;_meta={duration:2e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;transitionEffect;fromClipId=null;toClipId=null;constructor(e){super(),this.transitionEffect={id:`trans_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Fi(this.transitionEffect.key);return this.copyStateTo(e),e.fromClipId=this.fromClipId,e.toClipId=this.toClipId,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),i=await this.clone();return[t,i]}toJSON(e=!1){return{...super.toJSON(e),type:"Transition",transitionEffect:this.transitionEffect,fromClipId:this.fromClipId,toClipId:this.toClipId,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Transition")throw new Error(`Expected Transition, got ${e.type}`);const t=new Fi(e.transitionEffect.key);return t.transitionEffect=e.transitionEffect,t.fromClipId=e.fromClipId||null,t.toClipId=e.toClipId||null,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}function Yk(r,e){let t=!1;async function i(){const n=r.getReader();for(;!t;){const{value:s,done:o}=await n.read();if(o){e.onDone();return}await e.onChunk(s)}n.releaseLock(),await r.cancel()}return i().catch(console.error),()=>{t=!0}}class qk{readable;writable;inputBufOffset=0;isStreamCancelled=!1;constructor(){const e=Qn.createFile();this.readable=new ReadableStream({start:t=>this.initMP4Box(e,t),cancel:()=>{this.isStreamCancelled=!0,e.stop()}},{highWaterMark:50}),this.writable=new WritableStream({write:async t=>{if(this.isStreamCancelled)throw new Error("Stream cancelled");const i=t.buffer;i.fileStart=this.inputBufOffset,this.inputBufOffset+=i.byteLength,e.appendBuffer(i)},close:()=>{e.flush(),e.stop(),e.onFlush?.()},abort:t=>{Fq.error("SampleTransform writable aborted:",t),e.stop()}})}initMP4Box(e,t){e.onReady=n=>{[n.videoTracks[0],n.audioTracks[0]].forEach(s=>{s&&e.setExtractionOptions(s.id,s.video?"video":"audio",{nbSamples:100})}),t.enqueue({chunkType:"ready",data:{info:n,file:e}}),e.start()};const i={};e.onSamples=(n,s,o)=>{const a=o.map(l=>({...l}));t.enqueue({chunkType:"samples",data:{id:n,type:s,samples:a}}),i[n]=(i[n]??0)+o.length,e.releaseUsedSamples(n,i[n])},e.onFlush=()=>{t.close()},e.onError=n=>{t.error(new Error(`mp4box error: ${n}`))}}}const Fq={error:(...r)=>console.error("[SampleTransform]",...r)};function Mq(r){let e=0;const t=r.boxes,i=[];let n=0;async function s(){const p=f(t,e);e=t.length,i.forEach(({track:m,id:g})=>{const v=m.samples.at(-1);v!=null&&(n=Math.max(n,v.cts+v.duration)),r.releaseUsedSamples(g,m.samples.length),m.samples=[]}),r.mdats=[],r.moofs=[],p!=null&&await c?.write(p)}let o=[];function a(){if(o.length>0)return!0;const p=t.findIndex(m=>m.type==="moov");if(p===-1)return!1;if(o=t.slice(0,p+1),e=p+1,i.length===0)for(let m=1;;m+=1){const g=r.getTrackById(m);if(g==null)break;i.push({track:g,id:m})}return!0}let l=0;const u=q0();let c=null;const h=(async()=>{c=await u.createWriter(),l=self.setInterval(()=>{a()&&s()},100)})();let d=!1;return async()=>{if(d)throw Error("File exported");if(d=!0,await h,clearInterval(l),!a()||c==null)return null;r.flush(),await s(),await c?.close();const p=o.find(v=>v.type==="moov");if(p==null)return null;p.mvhd.duration=n;const m=q0(),g=f(o,0);return await Ys(m,g.slice()),await Ys(m,u,{overwrite:!1}),await m.stream()};function f(p,m){if(m>=p.length)return null;const g=new Qn.DataStream;for(let v=m;v<p.length;v++)p[v]!==null&&(p[v].write(g),delete p[v]);return new Uint8Array(g.buffer).slice()}}function Dq(r){const e=new ArrayBuffer(r.byteLength);r.copyTo(e);const t=r.timestamp;return{duration:r.duration??0,dts:t,cts:t,is_sync:r.type==="key",data:e}}async function jk(r){const e=Qn.createFile(),t=Mq(e);await Oq(r,e);const i=await t();if(i==null)throw Error("Can not generate file from streams");return i}async function Oq(r,e){let t=0,i=0,n=0,s=0,o=0,a=0,l=null,u=null;for(const c of r){let h=null,d=null,f=null,p=null;if(await new Promise(async m=>{Yk(c.pipeThrough(new qk),{onDone:m,onChunk:async({chunkType:g,data:v})=>{if(g==="ready"){const{videoTrackConf:x,audioTrackConf:y}=jb(v.file,v.info);t===0&&x!=null&&(t=e.addTrack(x)),s===0&&y!=null&&(s=e.addTrack(y))}else if(g==="samples"){const{type:x,samples:y}=v,b=x==="video"?t:s,T=x==="video"?i:o,E=x==="video"?n:a;y.forEach(P=>{let _,S;x==="video"?(h===null&&(h=P.dts,d=P.cts),_=P.dts-h,S=P.cts-(d??0)):(f===null&&(f=P.dts,p=P.cts),_=P.dts-f,S=P.cts-(p??0)),e.addSample(b,new Uint8Array(P.data),{duration:P.duration,dts:_+T,cts:S+E,is_sync:P.is_sync})});const C=y.at(-1);if(C==null)return;x==="video"?l=C:x==="audio"&&(u=C)}}})}),l!=null&&h!==null&&d!==null){const m=l.dts-h+l.duration,g=l.cts-d+l.duration;i+=m,n+=g}if(u!=null&&l!=null){const m=u.timescale/l.timescale;o=Math.round(i*m),a=Math.round(n*m)}}}async function Uq(r){return await jk([r])}function zq(r){let e=[];const t=new AudioDecoder({output:i=>{e.push(i)},error:Ee.error});return t.configure(r),{decode:async i=>{i.forEach(s=>{t.decode(new EncodedAudioChunk({type:s.is_sync?"key":"delta",timestamp:1e6*s.cts/s.timescale,duration:1e6*s.duration/s.timescale,data:s.data}))}),await t.flush();const n=e;return e=[],n},close:()=>{t.close()}}}function Lq(r,e){const t={codec:r.codec,sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels},i=new AudioEncoder({output:o=>{e(Dq(o))},error:o=>{Ee.error("AudioEncoder error:",o,", config:",t)}});i.configure(t);let n=null;function s(o,a){return new AudioData({timestamp:a,numberOfChannels:r.numberOfChannels,numberOfFrames:o.length/r.numberOfChannels,sampleRate:r.sampleRate,format:"f32-planar",data:new Float32Array(o)})}return{encode:async(o,a)=>{n!=null&&i.encode(s(n.data,n.ts)),n={data:o,ts:a}},stop:async()=>{n!=null&&(Nq(n.data,r.numberOfChannels,r.sampleRate),i.encode(s(n.data,n.ts)),n=null),await i.flush(),i.close()}}}function Nq(r,e,t){const i=r.length-1,n=Math.min(t/2,i);for(let s=0;s<n;s++)for(let o=1;o<=e;o++)r[Math.floor(i/o)-s]*=s/n}function Gq(r,e){Ee.info("mixinMP4AndAudio, opts:",{volume:e.volume,loop:e.loop});const t=Qn.createFile();let i,n=0,s=0;const o=t.boxes;let a=!1;const l=()=>{if(!a)if(o.find(I=>I.type==="moof")!=null)a=!0;else return null;if(s>=o.length)return null;const P=new Qn.DataStream;let _=s;try{for(;_<o.length;)o[_].write(P),delete o[_],_+=1}catch(I){throw I}if(t.moov!=null){for(var S=0;S<t.moov.traks.length;S++)t.moov.traks[S].samples=[];t.mdats=[],t.moofs=[]}return s=o.length,new Uint8Array(P.buffer)};let u=!1,c=!1,h=null;i=new ReadableStream({start(P){n=self.setInterval(()=>{const _=l();_!=null&&!c&&P.enqueue(_)},500),h=_=>{if(clearInterval(n),t.flush(),_!=null){P.error(_);return}const S=l();S!=null&&!c&&P.enqueue(S),c||P.close()}},cancel(){c=!0,clearInterval(n)}});const d=P=>{u||(u=!0,h?.(P))};let f=null,p=null,m=[],g=0,v=0,x=0,y=!0,b=st.sampleRate;Yk(r.pipeThrough(new qk),{onDone:async()=>{await p?.stop(),f?.close(),d()},onChunk:async({chunkType:P,data:_})=>{if(P==="ready"){const{videoTrackConf:S,audioTrackConf:I,audioDecoderConf:M}=jb(_.file,_.info);g===0&&S!=null&&(g=t.addTrack(S));const O=I??{timescale:1e6,samplerate:b,channel_count:st.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};v===0&&(v=t.addTrack(O),b=I?.samplerate??b,y=I!=null);const H=new AudioContext({sampleRate:b});m=j0(await H.decodeAudioData(await new Response(e.stream).arrayBuffer())),M!=null&&(f=zq(M)),p=Lq(M??{codec:O.type==="mp4a"?st.codec:O.type,numberOfChannels:O.channel_count,sampleRate:O.samplerate},K=>t.addSample(v,new Uint8Array(K.data),K))}else if(P==="samples"){const{id:S,type:I,samples:M}=_;if(I==="video"){M.forEach(O=>t.addSample(S,new Uint8Array(O.data),O)),y||await E(M);return}I==="audio"&&await C(M)}}});function T(P){const _=m.map(S=>e.loop?K0(S,x,x+P):S.slice(x,x+P));if(x+=P,e.volume!==1)for(const S of _)for(let I=0;I<S.length;I++)S[I]*=e.volume;return _}async function E(P){const _=P[0],S=P[P.length-1],I=Math.floor((S.cts+S.duration-_.cts)/_.timescale*b),M=aS([T(I)]);M.length!==0&&p?.encode(M,_.cts/_.timescale*1e6)}async function C(P){if(f==null)return;const _=(await f.decode(P)).map(oS),S=sS(_),I=T(S[0].length),M=P[0];p?.encode(aS([S,I]),M.cts/M.timescale*1e6)}return i}const Go=`
3510
3510
  in vec2 aPosition;
3511
3511
  out vec2 vTextureCoord;
3512
3512
 
@@ -14414,4 +14414,4 @@ vec4 transition(vec2 uv) {
14414
14414
  bool nextImage = distance(fract(uv * dots), vec2(0.5, 0.5)) < ( progress / distance(uv, center));
14415
14415
  return nextImage ? getToColor(uv) : getFromColor(uv);
14416
14416
  }
14417
- `,yte={radialSwipe:{label:"Radial Swipe",fragment:Cee}},Fh={};function bte(r,e){Fh[r]=e}function _te(r){delete Fh[r]}function Ko(){return{...jo.reduce((r,e)=>(r[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:""},r),{}),...yte,...Fh}}Ko();function G4(){const r=Object.keys(Fh);return Object.entries(Ko()).map(([e,t])=>({key:e,label:t.label,isCustom:r.includes(e),previewStatic:t.previewStatic||`https://cdn.subgen.co/previews/static/transition_${e}_static.webp`,previewDynamic:t.previewDynamic||`https://cdn.subgen.co/previews/dynamic/transition_${e}_dynamic.webp`}))}const wte=G4();function x1({name:r,renderer:e}){let t=jo.find(z=>z.name===r);if(!t){const z=Ko(),ne=Object.keys(z).find(oe=>oe.toLowerCase()===r.toLowerCase());ne&&(t=z[ne])}if(t||(t=jo.find(z=>z.name.toLowerCase()===r.toLowerCase())),!t){const z=[r,r.toLowerCase(),r.charAt(0).toUpperCase()+r.slice(1).toLowerCase(),r.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),r.replace(/_/g,"")],ne=Ko();for(const oe of z){if(t=jo.find(be=>be.name.toLowerCase()===oe.toLowerCase()),t)break;const te=Object.keys(ne).find(be=>be.toLowerCase()===oe.toLowerCase());if(te){t=ne[te];break}}}if(!t){const z=jo.length,ne=jo.slice(0,5).map(be=>be.name).join(", "),oe=Ko(),te=Object.keys(oe).slice(0,3).join(", ");throw console.error(`Transition not found: "${r}". Available in gl-transitions (${z} total):`,ne+"..."),console.error("Available locally:",te+"..."),new Error(`Transition "${r}" not found in gl-transitions library or local definitions`)}const i=new $e(Q.WHITE),n=Ot.create({width:e.width,height:e.height}),s=new Zr({}),o=new Zr({}),a=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",l=a?new Zr({}):void 0;let u=null;if(a){u=document.createElement("canvas"),u.width=256,u.height=256;const z=u.getContext("2d");if(z){const ne=z.createImageData(256,256);for(let oe=0;oe<ne.data.length;oe+=4){const te=Math.random();ne.data[oe]=te*255,ne.data[oe+1]=te*255,ne.data[oe+2]=te*255,ne.data[oe+3]=255}z.putImageData(ne,0,0)}}let c=t.glsl||t.fragment;if(!c)throw new Error(`Transition "${r}" has no glsl or fragment code`);let h={...ot.basics,...ot.custom(t)};Object.entries(h).forEach(([,z])=>{z.type==="int<f32>"&&(z.type="i32",typeof z.value=="number"&&(z.value=Math.trunc(z.value))),z.type==="ivec2<f32>"&&(z.type="vec2<f32>")});const d=t.name==="GridFlip"||r.toLowerCase()==="gridflip"||t.label==="gridflip",f=t.name==="circle"||r.toLowerCase()==="circle"||t.label==="circle",p=t.name==="directional"||r.toLowerCase()==="directional"||t.label==="directional",m=t.name==="UndulatingBurnOut"||r.toLowerCase()==="undulatingburnout"||t.label==="undulatingBurnOut",g=t.name==="SquaresWire"||r.toLowerCase()==="squareswire"||t.label==="squaresWire",v=t.name==="rotate_scale_fade"||r.toLowerCase()==="rotatescalefade"||t.label==="rotateScaleFade",x=t.name==="RandomSquares"||r.toLowerCase()==="randomsquares"||t.label==="randomSquares",y=t.name==="polar_function"||r.toLowerCase()==="polar_function"||t.label==="polar_function",b=t.name==="pixelate"||r.toLowerCase()==="pixelate"||t.label==="pixelate",T=t.name==="perlin"||r.toLowerCase()==="perlin"||t.label==="perlin",E=t.name==="luma"||r.toLowerCase()==="luma"||t.label==="luma",C=t.name==="luminance_melt"||r.toLowerCase()==="luminance_melt"||r.toLowerCase()==="luminancemelt"||t.label==="luminance_melt",P=t.name==="hexagonalize"||r.toLowerCase()==="hexagonalize"||t.label==="hexagonalize",_=t.name==="heart"||r.toLowerCase()==="heart"||t.label==="heart",S=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",I=t.name==="directionalwipe"||r.toLowerCase()==="directionalwipe"||r.toLowerCase()==="directional_wipe"||t.label==="directionalwipe",M=t.name==="directionalwarp"||r.toLowerCase()==="directionalwarp"||r.toLowerCase()==="directional_warp"||t.label==="directionalwarp",O=t.name==="crosshatch"||r.toLowerCase()==="crosshatch"||t.label==="crosshatch",H=t.name==="circleopen"||r.toLowerCase()==="circleopen"||r.toLowerCase()==="circle_open"||t.label==="circleopen",K=t.name==="cannabisleaf"||r.toLowerCase()==="cannabisleaf"||r.toLowerCase()==="cannabis_leaf"||t.label==="cannabisleaf",D=t.name==="StereoViewer"||r.toLowerCase()==="stereoviewer"||r.toLowerCase()==="stereo_viewer"||t.label==="StereoViewer",k=t.name==="GlitchDisplace"||r.toLowerCase()==="glitchDisplace"||t.label==="GlitchDisplace",W=t.name==="CrossZoom"||r.toLowerCase()==="crosszoom"||t.label==="CrossZoom",G=t.name==="CrazyParametricFun"||r.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",J=t.name==="BowTieHorizontal"||r.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",q=t.name==="PolkaDotsCurtain"||r.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",_e=t.name==="Pixelize"||r.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(c=Aee,h={...ot.basics,...Eee}),f&&(c=Pee,h={...ot.basics,...N4}),p&&(c=Iee,h={...ot.basics,...Bee}),m&&(c=kee,h={...ot.basics,...Ree}),g&&(c=Fee,h={...ot.basics,...Mee}),v&&(c=Dee,h={...ot.basics,...Oee}),x&&(c=Uee,h={...ot.basics,...zee}),y&&(c=Lee,h={...ot.basics,...Nee}),b&&(c=Kk,h={...ot.basics,...Qk}),T&&(c=Wee,h={...ot.basics,...Vee}),E&&(c=Xee,h={...ot.basics,...Yee}),C&&(c=qee,h={...ot.basics,...jee}),P&&(c=Kee,h={...ot.basics,...Qee}),_&&(c=Zee,h={...ot.basics,...Jee}),S&&(c=$ee,h={...ot.basics,...ete}),I&&(c=tte,h={...ot.basics,...rte}),M&&(c=ite,h={...ot.basics,...nte}),O&&(c=ste,h={...ot.basics,...ote}),H&&(c=ate,h={...ot.basics,...N4}),K&&(c=lte,h={...ot.basics,...ute}),D&&(c=cte,h={...ot.basics,...hte}),k&&(c=dte),W&&(c=fte,h={...ot.basics,...pte}),G&&(c=mte,h={...ot.basics,...gte}),J&&(c=vte),q&&(c=xte),_e&&(c=Gee,h={...ot.basics,...Hee});const Re={from:s,to:o,uniforms:h};a&&l&&(Re.displacementMap=l,u&&(l.resource=u,l.update()));const ge=new fe({glProgram:new le({vertex:wee,fragment:Tee(c)}),resources:Re});return i.filters=[ge],{render({width:z,height:ne,from:oe,to:te,progress:be}){if((i.width!==z||i.height!==ne)&&(i.setSize({width:z,height:ne}),n.resize(z,ne)),oe instanceof Q?ge.resources.from=oe.source:(s.resource=oe,s.update(),ge.resources.from=s),te instanceof Q?ge.resources.to=te.source:(o.resource=te,o.update(),ge.resources.to=o),a&&l&&u){if(u.width!==z||u.height!==ne){u.width=z,u.height=ne;const Ue=u.getContext("2d");if(Ue){const Ge=Ue.createImageData(z,ne);for(let ke=0;ke<Ge.data.length;ke+=4){const Ve=Math.random();Ge.data[ke]=Ve*255,Ge.data[ke+1]=Ve*255,Ge.data[ke+2]=Ve*255,Ge.data[ke+3]=255}Ue.putImageData(Ge,0,0)}}l.resource=u,l.update()}return ge.resources.uniforms.uniforms.progress=be,e.render({container:i,target:n,clear:!0,width:z,height:ne}),n},destroy(){n.destroy(),i.destroy({children:!0})}}}let Ste=0;async function H4(r){r()>50&&(await Au(15),await H4(r))}class Tte extends Z0{static async isSupported(e={}){return(self.OffscreenCanvas!=null&&self.VideoEncoder!=null&&self.VideoDecoder!=null&&self.VideoFrame!=null&&self.AudioEncoder!=null&&self.AudioDecoder!=null&&self.AudioData!=null&&((await self.VideoEncoder.isConfigSupported({codec:e.videoCodec??"avc1.42E032",width:e.width??1920,height:e.height??1080,bitrate:e.bitrate??7e6})).supported??!1)&&(await self.AudioEncoder.isConfigSupported({codec:(await zk()).codec,sampleRate:st.sampleRate,numberOfChannels:st.channelCount})).supported)??!1}logger=Ee.create(`id:${Ste++},`);destroyed=!1;sprites=[];canvas;pixiApp=null;stopOutput=null;opts;hasVideoTrack;constructor(e={}){super(),console.log("Compositor constructor",e);const{width:t=0,height:i=0}=e;this.canvas=new OffscreenCanvas(t,i),this.opts=Object.assign({bgColor:"#000",width:0,height:0,format:"mp4",videoCodec:"avc1.42E032",audio:!0,audioCodec:"aac",audioSampleRate:48e3,bitrate:5e6,fps:30,metaDataTags:null},e),console.log("Compositor opts",this.opts),this.hasVideoTrack=t*i>0,zk().catch(n=>{this.logger.warn("Failed to detect audio codec:",n)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new bc,await this.pixiApp.init({canvas:this.canvas,width:e,height:t,backgroundColor:0,antialias:!1,autoDensity:!1,resolution:1,preference:"webgl"}),this.pixiApp.renderer==null||this.pixiApp.stage==null)throw new Error("Pixi.js Application failed to initialize properly");try{const i=this.pixiApp;i.ticker&&typeof i.ticker.stop=="function"&&i.ticker.stop()}catch{}}async addSprite(e,t={}){const i={rect:{x:e.left,y:e.top,w:e.width,h:e.height},display:{...e.display},duration:e.duration,playbackRate:e.playbackRate,zIndex:e.zIndex};this.logger.info("Compositor add clip",i);const n=await e.clone();this.pixiApp!=null&&this.pixiApp.renderer!=null&&typeof n.setRenderer=="function"&&n.setRenderer(this.pixiApp.renderer),this.logger.info("Compositor add clip ready"),this.sprites.push(Object.assign(n,{main:t.main??!1,expired:!1})),this.sprites.sort((s,o)=>s.zIndex-o.zIndex)}initMuxer(e){const{fps:t,width:i,height:n,videoCodec:s,bitrate:o,audio:a,metaDataTags:l,format:u,audioCodec:c,audioSampleRate:h}=this.opts,d=this.sprites.some(m=>m.width>0&&m.height>0),f=this.hasVideoTrack&&d;return VO({format:u||"mp4",video:f?{width:i,height:n,expectFPS:t,codec:s,bitrate:o,__unsafe_hardwareAcceleration__:this.opts.__unsafe_hardwareAcceleration__}:null,audio:a===!1?null:{codec:c||st.codecType,sampleRate:h||st.sampleRate,channelCount:st.channelCount},duration:e,metaDataTags:l})}output(e={}){if(console.log("Compositor output",e),this.sprites.length===0)throw Error("No sprite added");const t=this.sprites.find(u=>u.main),n=this.sprites.map(u=>u.display.from+u.duration).filter(u=>u!==1/0),s=e.maxTime??(t!=null?t.display.from+t.duration:n.length>0?Math.max(...n):0);if(s===1/0||s<=0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of Image, Audio");s===-1&&this.logger.warn("Unable to determine the end time, process value don't update"),this.logger.info(`start combinate video, maxTime:${s}`);const o=this.initMuxer(s);let a=performance.now();const l=this.runEncoding(o,s,{onProgress:u=>{this.logger.debug("OutputProgress:",u),this.emit("OutputProgress",u)},onEnded:async()=>{await o.flush(),this.logger.info("===== output ended =====, cost:",performance.now()-a),this.emit("OutputProgress",1),this.destroy()},onError:u=>{this.emit("error",u),o.close(),this.destroy()}});return this.stopOutput=()=>{l(),o.close()},o.stream}destroy(){if(!this.destroyed&&(this.destroyed=!0,this.stopOutput?.(),this.off("OutputProgress"),this.off("error"),this.pixiApp!=null))try{const e=this.pixiApp;if(e.destroyed===!0){this.pixiApp=null;return}if(e.ticker&&typeof e.ticker.stop=="function")try{e.ticker.stop()}catch{}if(e.renderer!=null){const t=e.renderer.gl;if(t&&t.isContextLost()){this.pixiApp=null;return}this.pixiApp.destroy()}}catch(e){console.warn("Error while destroying Pixi application:",e)}finally{this.pixiApp=null}}runEncoding(e,t,{onProgress:i,onEnded:n,onError:s}){let o=0;const a={aborted:!1};let l=null,u=null;const c=async()=>{const{fps:f,bgColor:p,audio:m}=this.opts,g=Math.round(1e6/f),v=this.sprites.some(b=>b.width>0&&b.height>0);u=W4({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=Cte({muxer:e,canvas:this.canvas,outputAudio:m,hasVideoTrack:this.hasVideoTrack&&v,timeSlice:g,fps:f});let y=0;for(;;){if(l!=null)return;if(a.aborted||t!==-1&&y>t||this.sprites.length===0){h(),await n();return}o=y/t;const{audios:b,mainSprDone:T}=await u.render(y);if(T){h(),await n();return}if(a.aborted)return;this.hasVideoTrack&&await Au(0),x(y,b,!0),y+=g,await H4(e.getEncodeQueueSize)}},h=()=>{a.aborted||(a.aborted=!0,clearInterval(d),u?.cleanup(),this.sprites.forEach(f=>{f.destroy()}))};c().catch(f=>{l=f,this.logger.error(f),h(),s(f)});const d=setInterval(()=>{i(o)},500);return h}exportToJSON(){const e=this.sprites.map(i=>Dl(i,i.main)),t=[];return this.sprites.forEach(i=>{if(i.transition){const n=this.sprites.filter(s=>s.id!==i.id&&s.zIndex===i.zIndex&&s.display.from<i.display.from&&(s instanceof wr||s instanceof Fl)).sort((s,o)=>o.display.to-s.display.to)[0];n&&t.push({key:i.transition.name,duration:i.transition.duration,clips:[n.id,i.id]})}}),{clips:e,settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor,format:this.opts.format,videoCodec:this.opts.videoCodec,bitrate:this.opts.bitrate,audio:this.opts.audio,audioCodec:this.opts.audioCodec,audioSampleRate:this.opts.audioSampleRate,metaDataTags:this.opts.metaDataTags}}}async loadFromJSON(e){this.sprites.forEach(t=>{t.destroy()}),this.sprites=[],e.settings&&(e.settings.width!==void 0&&(this.opts.width=e.settings.width),e.settings.height!==void 0&&(this.opts.height=e.settings.height),e.settings.fps!==void 0&&(this.opts.fps=e.settings.fps),e.settings.bgColor!==void 0&&(this.opts.bgColor=e.settings.bgColor),e.settings.format!==void 0&&(this.opts.format=e.settings.format),e.settings.videoCodec!==void 0&&(this.opts.videoCodec=e.settings.videoCodec),e.settings.bitrate!==void 0&&(this.opts.bitrate=e.settings.bitrate),e.settings.audio!==void 0&&(this.opts.audio=e.settings.audio===!1?!1:void 0),e.settings.audioCodec!==void 0&&(this.opts.audioCodec=e.settings.audioCodec),e.settings.audioSampleRate!==void 0&&(this.opts.audioSampleRate=e.settings.audioSampleRate),e.settings.metaDataTags!==void 0&&(this.opts.metaDataTags=e.settings.metaDataTags));for(const t of e.clips){const i=await qo(t);await this.addSprite(i,{main:t.main||!1})}}async renderFrame(e){if(this.destroyed)throw new Error("Compositor has been destroyed.");if(this.pixiApp==null&&await this.initPixiApp(),this.pixiApp==null)throw new Error("Compositor Pixi application could not be initialised. Ensure width and height are greater than 0.");const t=e*1e3,i=W4({pixiApp:this.pixiApp,bgColor:this.opts.bgColor,sprites:this.sprites,aborter:{aborted:!1}});try{await i.render(t)}finally{i.cleanup()}return await this.pixiApp.renderer.extract.base64(this.pixiApp.stage,"image/png",1)}}function W4(r){const{pixiApp:e,sprites:t,aborter:i}=r,n=e!=null,s=new Map,o=new Map,a=new Map,l=Ot.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),u=Ot.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),c=new Je().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),h=new Map,d=async(b,T,E)=>{const C=Math.max(0,Math.min(T-b.display.from,b.duration));b.animate(C*b.playbackRate);const{video:P}=await E(b,C);return P},f=(b,T,E)=>{if(!e)return;const C=b.style||{},{renderTransform:P}=b,_=(P?.mirror??0)>.5,S=T instanceof Q?T:Q.from(T),I=P?.x??0,M=P?.y??0,O=P?.angle??0,H=P?.scale??1,K=P?.scaleX??1,D=P?.scaleY??1,k=P?.opacity??1,W=P?.blur??0,G=P?.brightness??1,J=S.width||1,q=S.height||1,_e=b.type==="Caption",Re=!_e&&b.width&&b.width!==0?Math.abs(b.width)/J:1,ge=!_e&&b.height&&b.height!==0?Math.abs(b.height)/q:1,z=Re*H*K,ne=ge*H*D,oe=new Ie;oe.x=b.center.x+I,oe.y=b.center.y+M,oe.rotation=(b.flip==null?1:-1)*((b.angle+O)*Math.PI)/180,oe.alpha=b.opacity*k;const te=new $e(S);te.anchor.set(.5,.5);let be=[];if(_){const Se=z,Xe=ne,Fe=J*Se,He=q*Xe;te.position.set(0,0),te.scale.set(Se,Xe);const or=[[Fe,0,-Se,Xe],[-Fe,0,-Se,Xe],[0,He,Se,-Xe],[0,-He,Se,-Xe],[Fe,He,-Se,-Xe],[-Fe,He,-Se,-Xe],[Fe,-He,-Se,-Xe],[-Fe,-He,-Se,-Xe]];for(const[At,Ps,Ol,Ul]of or){const tn=new $e(S);tn.anchor.set(.5,.5),tn.position.set(At,Ps),tn.scale.set(Ol,Ul),be.push(tn)}if(b.flip==="horizontal"){te.scale.x=-Se;for(let At=0;At<8;At++)be[At].scale.x=-or[At][2]}else if(b.flip==="vertical"){te.scale.y=-Xe;for(let At=0;At<8;At++)be[At].scale.y=-or[At][3]}oe.addChild(te);for(const At of be)oe.addChild(At)}else b.flip==="horizontal"?(te.scale.x=-z,te.scale.y=ne):b.flip==="vertical"?(te.scale.x=z,te.scale.y=-ne):(te.scale.x=z,te.scale.y=ne),oe.addChild(te);const Ue=[];if(W>0){const Se=new Fn;Se.strength=W,Se.quality=4,Se.repeatEdgePixels=!0,Ue.push(Se)}const Ge=m1(b.colorAdjustment);if(G!==1||Ge){const Se=new Zc;g1(Se,b.colorAdjustment,G),Ue.push(Se)}const ke=Rh(b.colorAdjustment);for(let Se=0;Se<ke.length;Se++){const Xe=ke[Se],Fe=new nt({uTargetColor:{value:[1,1,0],type:"vec3<f32>"},uHueShift:{value:Xe.hue,type:"f32"},uSatShift:{value:Xe.saturation/100,type:"f32"},uLightShift:{value:Xe.lightness/100,type:"f32"},uTolerance:{value:.22,type:"f32"},uSoftness:{value:.12,type:"f32"}}),He=Rl(Xe.targetColor);He&&(Fe.uniforms.uTargetColor[0]=He.r/255,Fe.uniforms.uTargetColor[1]=He.g/255,Fe.uniforms.uTargetColor[2]=He.b/255);const or=new fe({glProgram:new le({vertex:Go,fragment:$b,name:`SelectiveHslShader_${Se}`}),resources:{hslUniforms:Fe}});Ue.push(or)}if(b.chromaKey&&b.chromaKey.enabled){const Se=new nt({uKeyColor:{value:[0,1,0],type:"vec3<f32>"},uSimilarity:{value:.1,type:"f32"},uSpill:{value:0,type:"f32"}}),Xe=Rl(b.chromaKey.color);Xe&&(Se.uniforms.uKeyColor[0]=Xe.r/255,Se.uniforms.uKeyColor[1]=Xe.g/255,Se.uniforms.uKeyColor[2]=Xe.b/255),Se.uniforms.uSimilarity=b.chromaKey.similarity,Se.uniforms.uSpill=b.chromaKey.spill;const Fe=new fe({glProgram:new le({vertex:Go,fragment:Zk,name:"ChromaKeyShader"}),resources:{chromaUniforms:Se}});Ue.push(Fe)}oe.filters=Ue;const Ve=C.borderRadius||0;let Me=null;Ve>0&&(Me=new Je,Me.roundRect(-J/2,-q/2,J,q,Math.min(Ve,J/2,q/2)),Me.fill({color:16777215,alpha:1}),te.addChild(Me),te.mask=Me);const Ct=C.stroke;let et=null;if(Ct&&Ct.width>0){et=new Je;const Se=xt(Ct.color)??16777215;if(et.setStrokeStyle({width:Ct.width,color:Se,alignment:1}),Ve>0){const Xe=Math.min(Ve,J/2,q/2);et.roundRect(-J/2,-q/2,J,q,Xe)}else et.rect(-J/2,-q/2,J,q);et.stroke(),te.addChild(et)}const sr=C.dropShadow;let Sr=null;if(sr&&(sr.blur>0||sr.distance>0)){Sr=new Je;const Se=xt(sr.color)??0,Xe=sr.alpha??.5,Fe=sr.distance??0,He=sr.angle??0,or=Math.cos(He)*Fe,At=Math.sin(He)*Fe;if(Ve>0){const Ps=Math.min(Ve,J/2,q/2);Sr.roundRect(-J/2+or,-q/2+At,J,q,Ps)}else Sr.rect(-J/2+or,-q/2+At,J,q);Sr.fill({color:Se,alpha:Xe}),oe.addChildAt(Sr,0)}e.renderer.render({container:oe,target:E,clear:!0}),T instanceof Q||te.texture.destroy(!0),et&&et.destroy(),Me&&Me.destroy(),Sr&&Sr.destroy();for(const Se of be)Se.destroy();te.destroy(),oe.destroy()};let p=null,m=null,g=null;n&&e!=null&&(p=new Ie,m=new Ie,g=new Ie,m.sortableChildren=!0,g.sortableChildren=!0,e.stage.addChild(m),e.stage.addChild(g),p.visible=!1,e.stage.addChild(p));const v=[...t].sort((b,T)=>b.zIndex-T.zIndex);return{render:async b=>{const T=[];let E=!1,C=!1;const P=new Map,_=async(S,I)=>{if(P.has(S))return P.get(S);const M=await S.getFrame(I);return P.set(S,M),M};for(const S of a.values())S.visible=!1;for(const S of v){if(i.aborted)break;if(b<S.display.from||S.expired){if(n&&e!=null){const D=s.get(S);D&&await D.updateFrame(null)}continue}const I=b-S.display.from,M=I*S.playbackRate;S.animate(M);const{video:O,audio:H,done:K}=await _(S,I);if(T.push(H),n&&e!=null&&m!=null){if(S instanceof Fi){const k=t.find(G=>G.id===S.fromClipId),W=t.find(G=>G.id===S.toClipId);if(k&&W){const G=b-S.display.from;if(G>=S.duration){S.expired=!0;const J=a.get(S.id);J&&(J.visible=!1)}else{const J=await d(k,b,_),q=await d(W,b,_);if(J&&q){const _e=Math.min(Math.max(G/S.duration,0),1);f(k,J,l),f(W,q,u);let Re=o.get(S.id);Re||(Re=x1({name:S.transitionEffect.key,renderer:e.renderer}),o.set(S.id,Re));const ge=Re.render({width:e.renderer.width,height:e.renderer.height,from:l,to:u,progress:_e});let z=a.get(S.id);z||(z=new $e,z.label=`TransitionSprite_${S.id}`,a.set(S.id,z),m.addChild(z)),z.texture=ge,z.visible=!0,z.x=0,z.y=0,z.width=e.renderer.width,z.height=e.renderer.height,z.anchor.set(0,0),z.zIndex=S.zIndex,C=!0;const ne=s.get(k);if(ne){const te=ne.getRoot();te&&(te.visible=!1)}const oe=s.get(W);if(oe){const te=oe.getRoot();te&&(te.visible=!1)}continue}}}}let D=s.get(S);if(D==null&&O!=null&&(D=new z4(e,S,m),s.set(S,D)),D!=null){const k=D.getRoot();O!=null?(C=!0,k&&(k.visible=!0),await D.updateFrame(O)):(k&&(k.visible=!1),await D.updateFrame(null)),D.updateTransforms()}}if(S.duration>0&&I>S.duration||K){if(S.main&&(E=!0),S.expired=!0,n){const D=s.get(S);if(D!=null){const k=D.getRoot();k&&(k.visible=!1)}}}else if(n){const D=s.get(S);D?.updateTransforms()}}if(n&&e!=null&&p!=null&&m!=null&&g!=null){const S=[];for(const I of t)if(I instanceof Ji&&b>=I.display.from&&b<I.display.from+I.duration&&S.push({id:I.id,key:I.effect.key,startTime:I.display.from,duration:I.duration,zIndex:I.zIndex,values:I.effect.values}),I.effects&&I.effects.length>0)for(const M of I.effects)b>=M.startTime&&b<M.startTime+M.duration&&S.push({...M,zIndex:I.zIndex});S.sort((I,M)=>I.zIndex-M.zIndex),g.removeChildren();for(const I of s.values()){const M=I.getRoot();M&&M.parent!==m&&(M.parent&&M.parent.removeChild(M),m.addChild(M))}if(S.length>0){const I=e.renderer.width,M=e.renderer.height;let O=null;const H=new Set,K=[];for(const D of S){const{key:k,startTime:W,duration:G,id:J,zIndex:q}=D,_e=b-W,Re=G>0?Math.min(Math.max(_e/G,0),1):0,ge=t.some(z=>z.id===J&&z instanceof Ji);if(p.removeChildren(),O){const z=new $e(O);z.width=I,z.height=M,p.addChild(z)}for(const z of t){if(H.has(z.id))continue;let ne=!1;if(ge?ne=z.id!==J&&z.zIndex<q:ne=!!z.effects&&z.effects.some(oe=>oe.id===J),ne){const oe=s.get(z);if(oe){const be=oe.getRoot();be&&(be.parent&&be.parent.removeChild(be),p.addChild(be),H.add(z.id))}const te=a.get(z.id);te&&(te.parent&&te.parent.removeChild(te),p.addChild(te),H.add(z.id))}}if(p.children.length>0){let z=h.get(J);if(!z)try{const ne=await p1({name:k,renderer:e.renderer,values:D.values});ne&&ne.filter&&(z={filter:ne.filter,render:ne.render},h.set(J,z))}catch(ne){console.warn("Failed to create effect",k,ne)}if(z){const{filter:ne,render:oe}=z;ne.resources&&ne.resources.effectUniforms&&(ne.resources.effectUniforms.uniforms.uTime=Re);const te=Ot.create({width:I,height:M});K.push(te),p.visible=!0,e.renderer.render({container:p,target:te,clear:!0}),p.visible=!1,oe&&(O=oe({canvasTexture:te,progress:Re,width:I,height:M}))}}}if(O){const D=new $e(O);D.width=I,D.height=M,g.addChild(D)}for(const D of K)D.destroy(!0)}}return n&&e!=null&&e.render(),{audios:T,mainSprDone:E,hasVideo:C}},cleanup:()=>{l&&l.destroy(!0),u&&u.destroy(!0),c&&c.destroy(!0);for(const b of a.values())b.destroy();a.clear(),o.clear(),p&&p.destroy({children:!0}),m&&m.destroy({children:!0}),g&&g.destroy({children:!0}),s.forEach(b=>{b.destroy()}),s.clear()}}}function Cte(r){const{canvas:e,outputAudio:t,muxer:i,hasVideoTrack:n,timeSlice:s}=r;let o=0;const a=Math.floor(3*r.fps),l=Ate(1024);return(u,c,h)=>{if(t!==!1)for(const d of l(u,c))i.encodeAudio(d);if(n&&h)try{const d=new VideoFrame(e,{duration:s,timestamp:u});i.encodeVideo(d,{keyFrame:o%a===0}),o+=1}catch(d){console.warn("Failed to create VideoFrame from canvas, skipping frame:",d)}}}function Ate(r){const e=r*st.channelCount,t=new Float32Array(e*3);let i=0,n=0;const s=r/st.sampleRate*1e6,o=new Float32Array(e),a=l=>{let u=0;const c=Math.floor(i/e),h=[];for(let d=0;d<c;d++)h.push(new AudioData({timestamp:n,numberOfChannels:st.channelCount,numberOfFrames:r,sampleRate:st.sampleRate,format:"f32",data:t.subarray(u,u+e)})),u+=e,n+=s;for(t.set(t.subarray(u,i),0),i-=u;l-n>s;)h.push(new AudioData({timestamp:n,numberOfChannels:st.channelCount,numberOfFrames:r,sampleRate:st.sampleRate,format:"f32",data:o})),n+=s;return h};return(l,u)=>{const c=Math.max(...u.map(h=>h[0]?.length??0));for(let h=0;h<c;h++){let d=0,f=0;for(let p=0;p<u.length;p++){const m=u[p][0]?.[h]??0,g=u[p][1]?.[h]??m;d+=m,f+=g}t[i]=d,t[i+1]=f,i+=2}return a(l)}}class Ete extends Je{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(e,t=1){const n=1.5*t;this.clear(),this.setStrokeStyle({width:n,color:165063}).rect(e.x,e.y,e.width,e.height).stroke(),this.hitArea=e}}class en extends Je{#e=!1;handle;cursor;callbacks;constructor(e,t,i){super(),this.handle=e,this.cursor=t,this.callbacks=i,this.eventMode="static",this.#l(),this.on("pointerdown",this.#r),this.on("globalpointermove",this.#n),this.on("pointerup",this.#u),this.on("pointerupoutside",this.#u)}#l(){this.clear();const e=165063;if(this.handle==="rot")this.circle(0,0,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-4),this.arc(0,0,4,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new al(0,0,24);else if(["ml","mr","mt","mb"].includes(this.handle)){const t=this.handle==="ml"||this.handle==="mr",i=t?6:24,n=t?24:6;this.roundRect(-i/2,-n/2,i,n,3),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new he(-15,-15,30,30)}else this.rect(-4,-4,8,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new he(-15,-15,30,30)}#r=e=>{this.#e=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,e.global)};#n=e=>{this.#e&&this.callbacks.updateDrag(this.handle,e.global)};#u=e=>{this.#e&&(this.#e=!1,this.cursor="pointer",this.callbacks.endDrag())}}class Mh{constructor(e,t,i=1){this.artboardWidth=e,this.artboardHeight=t,this.scale=i}static SNAP_THRESHOLD=5;updateContext(e,t,i){this.artboardWidth=e,this.artboardHeight=t,this.scale=i}snapMove(e){const t=[];let i=0,n=0;const s=Mh.SNAP_THRESHOLD/this.scale,o=[{value:this.artboardWidth/2,label:"center"},{value:0,label:"start"},{value:this.artboardWidth,label:"end"}],a=[{value:e.x,type:"start"},{value:e.x+e.width/2,type:"center"},{value:e.x+e.width,type:"end"}];let l=!1;for(const d of o){if(l)break;for(const f of a){const p=d.value-f.value;if(Math.abs(p)<s){i=p,l=!0,t.push({type:"vertical",position:d.value,start:Math.min(0,e.y),end:Math.max(this.artboardHeight,e.y+e.height)});break}}}const u=[{value:this.artboardHeight/2,label:"center"},{value:0,label:"start"},{value:this.artboardHeight,label:"end"}],c=[{value:e.y,type:"start"},{value:e.y+e.height/2,type:"center"},{value:e.y+e.height,type:"end"}];let h=!1;for(const d of u){if(h)break;for(const f of c){const p=d.value-f.value;if(Math.abs(p)<s){n=p,h=!0,t.push({type:"horizontal",position:d.value,start:Math.min(0,e.x),end:Math.max(this.artboardWidth,e.x+e.width)});break}}}return{dx:i,dy:n,guides:t}}snapResize(e){const t=e.clone(),{dx:i,dy:n,guides:s}=this.snapMove(t);return t.x+=i,t.y+=n,{corrected:t,guides:s}}snapPoint(e){const t=Mh.SNAP_THRESHOLD/this.scale,i=[],n=e.clone(),s=[0,this.artboardWidth/2,this.artboardWidth];for(const a of s)if(Math.abs(a-e.x)<t){n.x=a,i.push({type:"vertical",position:a,start:0,end:this.artboardHeight});break}const o=[0,this.artboardHeight/2,this.artboardHeight];for(const a of o)if(Math.abs(a-e.y)<t){n.y=a,i.push({type:"horizontal",position:a,start:0,end:this.artboardWidth});break}return{p:n,guides:i}}}const V4={delta:new ae};class X4 extends Ie{group;wireframe=new Ete;selectionOutlines=new Je;isDragging=!1;lastPointer=new ve;activeHandle=null;#e;#l=new Map;#r=new ve;#n=0;#u=0;#c=new he;#i=new ve;#s=new he;#t=[new ve,new ve,new ve,new ve];#o=1;#a=1;#h;#d=new Je;#m=new ve;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static",this.#h=new Mh(e.artboardWidth??1920,e.artboardHeight??1080),this.addChild(this.#d);const t={beginDrag:(i,n)=>this.#A(i,n),updateDrag:(i,n)=>this.#E(i,n),endDrag:()=>this.#v()};this.#e={tl:new en("tl","nwse-resize",t),tr:new en("tr","nesw-resize",t),bl:new en("bl","nesw-resize",t),br:new en("br","nwse-resize",t),ml:new en("ml","ew-resize",t),mr:new en("mr","ew-resize",t),mt:new en("mt","ns-resize",t),mb:new en("mb","ns-resize",t),rot:new en("rot","crosshair",{beginDrag:(i,n)=>this.#B(n),updateDrag:(i,n)=>this.#k(n),endDrag:()=>this.#v()})},this.addChild(this.selectionOutlines,this.wireframe,...Object.values(this.#e)),this.#w(),this.visible=!1,Ft.shared.addOnce(()=>{this.showImmediate()})}#x=!1;showImmediate(){this.#x||this.destroyed||!this.parent||(this.#f(),this.visible=!0,this.#x=!0)}#w(){this.on("pointerdown",this.#S),this.on("pointerup",this.#y),this.on("pointerupoutside",this.#y),this.on("globalpointermove",this.#T)}#f(){if(this.group.length===1){const e=this.group[0];this.#n=e.rotation;const t=this.#g(e);let i,n;this.opts.clip?(i=this.opts.clip.width,n=this.opts.clip.height):(i=t.width,n=t.height);const s=e.toGlobal(new ve(0,0));this.#r.set(s.x,s.y),this.#s.copyFrom(new he(-i/2,-n/2,i,n))}else{let e=1/0,t=1/0,i=-1/0,n=-1/0;if(this.parent)for(const u of this.group){const c=this.#g(u);this.#t[0].set(c.x,c.y),this.#t[1].set(c.x+c.width,c.y),this.#t[2].set(c.x+c.width,c.y+c.height),this.#t[3].set(c.x,c.y+c.height);for(const h of this.#t)u.toGlobal(h,h),this.toLocal(h,void 0,h),e=Math.min(e,h.x),t=Math.min(t,h.y),i=Math.max(i,h.x),n=Math.max(n,h.y)}const s=i-e,o=n-t,a=e+s/2,l=t+o/2;if(this.#s.copyFrom(new he(-s/2,-o/2,s,o)),this.parent){const u=this.toGlobal(new ve(a,l));this.#r.set(u.x,u.y)}}this.#p()}#g(e){let t=null;const i=u=>{if(u.label==="MainSprite"&&u instanceof $e)return u;for(const c of u.children)if(c instanceof Ie){const h=i(c);if(h)return h}return null};if(t=i(e),t){const u=t.getLocalBounds(),c=t.localTransform.clone(),h=c.apply(new ve(u.x,u.y)),d=c.apply(new ve(u.x+u.width,u.y)),f=c.apply(new ve(u.x+u.width,u.y+u.height)),p=c.apply(new ve(u.x,u.y+u.height)),m=Math.min(h.x,d.x,f.x,p.x),g=Math.max(h.x,d.x,f.x,p.x),v=Math.min(h.y,d.y,f.y,p.y),x=Math.max(h.y,d.y,f.y,p.y);return new he(m,v,g-m,x-v)}let n=1/0,s=1/0,o=-1/0,a=-1/0;const l=e.children.filter(u=>u.label!=="ShadowContainer"&&u.label!=="AnimationContainer");if(l.length===0&&e.children.length>0){const u=e.children.find(c=>c.label==="AnimationContainer");if(u){const c=u.getLocalBounds();return new he(c.minX,c.minY,c.maxX-c.minX,c.maxY-c.minY)}}for(const u of l){const c=u.getBounds(),h=e.toLocal(new ve(c.minX,c.minY)),d=e.toLocal(new ve(c.maxX,c.maxY));n=Math.min(n,h.x,d.x),s=Math.min(s,h.y,d.y),o=Math.max(o,h.x,d.x),a=Math.max(a,h.y,d.y)}if(n===1/0){const u=e.getLocalBounds();return new he(u.minX,u.minY,u.maxX-u.minX,u.maxY-u.minY)}return new he(n,s,o-n,a-s)}updateBounds(){this.#f()}#S=e=>{e.button===0&&(this.opts.locked||(this.#f(),this.#m.copyFrom(this.#r),this.isDragging=!0,this.lastPointer.copyFrom(e.global),this.cursor="grabbing"))};#y=()=>{this.isDragging&&this.#v(),this.cursor="default"};#T=e=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const{moveDx:t,moveDy:i,newPivotWorld:n}=this.#C(e);for(const s of this.group)s.x+=t,s.y+=i;this.#r.copyFrom(n),this.lastPointer.copyFrom(e.global),this.#p(),this.emit("transforming")};#C(e){const t=Math.abs(this.parent.worldTransform.a);this.#h.updateContext(this.opts.artboardWidth??1920,this.opts.artboardHeight??1080,t);const i=e.global.x-this.lastPointer.x,n=e.global.y-this.lastPointer.y;this.#m.x+=i,this.#m.y+=n;const s=this.parent.toLocal(this.#m),o=new he(s.x+this.#s.x,s.y+this.#s.y,this.#s.width,this.#s.height),{dx:a,dy:l,guides:u}=this.#h.snapMove(o);this.#b(u,t);const c=s.x+a,h=s.y+l,d=this.parent.toLocal(this.#r),f=c-d.x,p=h-d.y,m=this.parent.toGlobal(new ve(c,h));return{moveDx:f,moveDy:p,newPivotWorld:m}}#A(e,t){this.#f(),this.isDragging=!0,this.activeHandle=e,this.#l.clear();for(const i of this.group)this.#l.set(i,i.localTransform.clone());this.rotation=this.#n,this.#c.copyFrom(this.#s),this.#F(e)}#E(e,t){this.#P(e,t)}async#P(e,t){const{proposed:i,sx:n,sy:s,pivotWorld:o}=await this.#I(e,t),a=this.opts.clip&&this.opts.clip.type==="Text",l=this.opts.clip&&this.opts.clip.type==="Caption";a||l?this.emit("textClipResize",{handle:e,newWidth:i.width,newHeight:i.height,pivotWorld:o,proposed:i,sx:n,sy:s}):this.#_(this.#D(o,this.#n,n,s)),this.#s.copyFrom(i),this.#p(),this.emit("transforming")}async#I(e,t){const i=this.#i,n=this.#M(e,this.toLocal(t),i),s=this.parent?Math.abs(this.parent.worldTransform.a):1;this.#h.updateContext(this.opts.artboardWidth??1920,this.opts.artboardHeight??1080,s);const{dx:o,dy:a,guides:l}=this.#h.snapMove(n);n.x+=o,n.y+=a,this.#b(l,s);const u=n.width/this.#c.width,c=n.height/this.#c.height,h=this.toGlobal(i);return{proposed:n,sx:u,sy:c,pivotWorld:h}}#B(e){this.#f(),this.isDragging=!0,this.activeHandle="rot",this.#l.clear();for(const t of this.group)this.#l.set(t,t.localTransform.clone());this.#u=Math.atan2(e.y-this.#r.y,e.x-this.#r.x)}#k(e){const i=Math.atan2(e.y-this.#r.y,e.x-this.#r.x)-this.#u,n=this.#n+i;this.#_(this.#O(this.#r,i)),this.rotation=n,this.#p(n),this.emit("transforming")}#v(){this.isDragging=!1,this.#n=this.rotation,this.activeHandle=null,this.#d.clear(),this.#p(this.#n),this.emit("transformEnd")}#b(e,t){if(this.#d.clear(),!(!e.length||!this.parent)){this.#d.stroke({width:1/t,color:4774907});for(const i of e){let n,s;i.type==="vertical"?(n=new ve(i.position,i.start),s=new ve(i.position,i.end)):(n=new ve(i.start,i.position),s=new ve(i.end,i.position)),this.toLocal(n,this.parent,n),this.toLocal(s,this.parent,s),this.#d.moveTo(n.x,n.y).lineTo(s.x,s.y).stroke({width:1/t,color:4774907})}}}#p(e=this.#n){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#r)),this.rotation=e;const i=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),n=this.#s;this.wireframe.draw(n,i);const s=n.x+n.width/2,o=n.y+n.height/2,l=this.opts.locked?[]:this.opts.clip?.getVisibleHandles?.()??["tl","tr","bl","br","ml","mr","mt","mb","rot"],u=[this.#e.tl,this.#e.tr,this.#e.bl,this.#e.br,this.#e.ml,this.#e.mr,this.#e.mt,this.#e.mb,this.#e.rot];for(const c of u)c.scale.set(i);this.#e.tl.visible=l.includes("tl"),this.#e.tr.visible=l.includes("tr"),this.#e.bl.visible=l.includes("bl"),this.#e.br.visible=l.includes("br"),this.#e.ml.visible=l.includes("ml"),this.#e.mr.visible=l.includes("mr"),this.#e.mt.visible=l.includes("mt"),this.#e.mb.visible=l.includes("mb"),this.#e.rot.visible=l.includes("rot"),this.#e.tl.position.set(n.x,n.y),this.#e.tr.position.set(n.x+n.width,n.y),this.#e.bl.position.set(n.x,n.y+n.height),this.#e.br.position.set(n.x+n.width,n.y+n.height),this.#e.ml.position.set(n.x,o),this.#e.mr.position.set(n.x+n.width,o),this.#e.mt.position.set(s,n.y),this.#e.mb.position.set(s,n.y+n.height),this.#e.rot.position.set(s,n.y-30*i),this.#R(i)}#R(e){if(this.selectionOutlines.clear(),this.group.length<=1||!this.parent)return;const t={width:1*e,color:43775,alpha:1};for(const i of this.group){const n=this.#g(i);this.#t[0].set(n.x,n.y),this.#t[1].set(n.x+n.width,n.y),this.#t[2].set(n.x+n.width,n.y+n.height),this.#t[3].set(n.x,n.y+n.height);for(const s of this.#t)i.toGlobal(s,s),this.toLocal(s,void 0,s);this.selectionOutlines.moveTo(this.#t[0].x,this.#t[0].y).lineTo(this.#t[1].x,this.#t[1].y).lineTo(this.#t[2].x,this.#t[2].y).lineTo(this.#t[3].x,this.#t[3].y).closePath().stroke(t)}}#F(e){const t=this.#c;if(this.opts.centeredScaling){this.#i.set(t.x+t.width/2,t.y+t.height/2);return}e==="tl"?this.#i.set(t.x+t.width,t.y+t.height):e==="tr"?this.#i.set(t.x,t.y+t.height):e==="bl"?this.#i.set(t.x+t.width,t.y):e==="br"?this.#i.set(t.x,t.y):e==="ml"?this.#i.set(t.x+t.width,t.y+t.height/2):e==="mr"?this.#i.set(t.x,t.y+t.height/2):e==="mt"?this.#i.set(t.x+t.width/2,t.y+t.height):e==="mb"&&this.#i.set(t.x+t.width/2,t.y)}#M(e,t,i){if(this.opts.centeredScaling){const s=Math.max(this.#o,Math.abs(t.x-i.x)*2),o=Math.max(this.#a,Math.abs(t.y-i.y)*2);return new he(i.x-s/2,i.y-o/2,s,o)}if(e==="tl"){const s=Math.min(t.x,i.x-this.#o),o=Math.min(t.y,i.y-this.#a);return new he(s,o,i.x-s,i.y-o)}if(e==="tr"){const s=Math.max(t.x,i.x+this.#o),o=Math.min(t.y,i.y-this.#a);return new he(i.x,o,s-i.x,i.y-o)}if(e==="bl"){const s=Math.min(t.x,i.x-this.#o),o=Math.max(t.y,i.y+this.#a);return new he(s,i.y,i.x-s,o-i.y)}if(e==="br"){const s=Math.max(t.x,i.x+this.#o),o=Math.max(t.y,i.y+this.#a);return new he(i.x,i.y,s-i.x,o-i.y)}const n=this.#c;if(e==="ml"){const s=Math.min(t.x,i.x-this.#o);return new he(s,n.y,i.x-s,n.height)}if(e==="mr"){const s=Math.max(t.x,i.x+this.#o);return new he(i.x,n.y,s-i.x,n.height)}if(e==="mt"){const s=Math.min(t.y,i.y-this.#a);return new he(n.x,s,n.width,i.y-s)}if(e==="mb"){const s=Math.max(t.y,i.y+this.#a);return new he(n.x,i.y,n.width,s-i.y)}return new he(i.x,i.y,this.#o,this.#a)}#D(e,t,i,n){return V4.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(i,n).rotate(t).translate(e.x,e.y)}#O(e,t){return V4.delta.identity().translate(-e.x,-e.y).rotate(t).translate(e.x,e.y)}#_(e){for(const t of this.group){const i=this.#l.get(t),n=t.parent;if(!i||!n)continue;const s=n.worldTransform.clone().invert(),o=n.worldTransform.clone().append(i),a=e.clone().append(o),l=s.clone().append(a);t.setFromMatrix(l)}}}class Pte{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new ve;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;lastPointerDownTime=0;lastPointerDownClip=null;init(e,t){this.selectionGraphics=new Je,this.selectionGraphics.visible=!1,this.selectionGraphics.zIndex=1e3,t.addChild(this.selectionGraphics),e.stage.eventMode="static",e.stage.hitArea=e.screen,e.stage.on("pointerdown",i=>this.onStagePointerDown(i)),e.stage.on("globalpointermove",i=>this.onStagePointerMove(i)),e.stage.on("pointerup",()=>this.onStagePointerUp()),e.stage.on("pointerupoutside",()=>this.onStagePointerUp())}onStagePointerDown(e){e.target===this.studio.pixiApp?.stage&&(e.shiftKey||this.deselectClip(),this.isDragSelecting=!0,this.studio.artboard?.toLocal(e.global,void 0,this.dragSelectionStart),this.selectionGraphics&&(this.selectionGraphics.clear(),this.selectionGraphics.visible=!0))}onStagePointerMove(e){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const t=this.studio.artboard.toLocal(e.global),i=Math.min(this.dragSelectionStart.x,t.x),n=Math.min(this.dragSelectionStart.y,t.y),s=Math.abs(t.x-this.dragSelectionStart.x),o=Math.abs(t.y-this.dragSelectionStart.y);this.selectionGraphics.clear(),this.selectionGraphics.rect(i,n,s,o).fill({color:703971,alpha:.3}),this.selectionGraphics.rect(i,n,s,o).stroke({width:2,color:703971});const a=this.selectionGraphics.getBounds(),l=new he(a.x,a.y,a.width,a.height);if(l.width>2||l.height>2){const u=this.getIntersectingClips(l);this.updatePreviewSelection(u)}else this.selectedClips.size===0&&this.destroyTransformer();this.studio.pixiApp?.render()}}onStagePointerUp(){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const e=this.selectionGraphics.getBounds(),t=new he(e.x,e.y,e.width,e.height);if(t.width>2||t.height>2){const i=this.getIntersectingClips(t);if(i.length>0){for(const n of i)this.selectedClips.add(n);this.recreateTransformer(),this.studio.emit("selection:created",{selected:Array.from(this.selectedClips)})}else this.selectedClips.size===0&&this.destroyTransformer()}else this.selectedClips.size===0&&this.destroyTransformer();this.selectionGraphics.clear(),this.selectionGraphics.visible=!1,this.isDragSelecting=!1,this.studio.pixiApp?.render()}}getIntersectingClips(e){const t=[];for(const i of this.studio.clips){const n=this.studio.spriteRenderers.get(i);if(!n)continue;const s=n.getRoot();if(!s||!s.visible)continue;const o=s.getBounds();e.x<o.x+o.width&&e.x+e.width>o.x&&e.y<o.y+o.height&&e.y+e.height>o.y&&t.push(i)}return t}updatePreviewSelection(e){if(e.length===0){this.selectedClips.size===0?this.destroyTransformer():this.recreateTransformer();return}const t=new Set(e),i=[];let n=null;for(const s of t){const o=this.studio.spriteRenderers.get(s);if(o==null)continue;const a=o.getRoot();a!=null&&(i.push(a),t.size===1&&(n=s))}if(i.length===0){this.selectedClips.size===0&&this.destroyTransformer();return}this.activeTransformer?(this.activeTransformer.group=i,this.activeTransformer.opts.group=i,this.activeTransformer.opts.clip=n,this.activeTransformer.updateBounds(),this.activeTransformer.showImmediate()):(this.activeTransformer=new X4({group:i,clip:n,artboardWidth:this.studio.opts.width,artboardHeight:this.studio.opts.height}),this.studio.artboard?.addChild(this.activeTransformer),this.activeTransformer.showImmediate()),this.studio.pixiApp?.render()}setupSpriteInteractivity(e){if(this.interactiveClips.has(e))return;const t=this.studio.spriteRenderers.get(e);if(t==null)return;const i=t.getRoot();i!=null&&(i.eventMode="static",i.cursor="pointer",i.on("pointerdown",n=>{const s=Date.now(),o=this.getTopmostClipAtPoint(n.global);o===e&&o===this.lastPointerDownClip&&s-this.lastPointerDownTime<350&&(o.type==="Text"||o.type==="Caption")&&this.studio.emit("clip:dblclick",{clip:o}),this.lastPointerDownTime=s,this.lastPointerDownClip=o,o&&this.selectClip(o,n.shiftKey)}),this.interactiveClips.add(e))}getTopmostClipAtPoint(e){if(!this.studio.pixiApp)return null;let t=null,i=-1/0;for(const n of this.interactiveClips){const s=this.studio.spriteRenderers.get(n);if(!s)continue;const o=s.getRoot();if(!o||!o.visible)continue;const a=o.toLocal(e),l=o.getLocalBounds();a.x>=l.minX&&a.x<=l.maxX&&a.y>=l.minY&&a.y<=l.maxY&&n.zIndex>i&&(i=n.zIndex,t=n)}return t}selectClip(e,t=!1){if(!(this.studio.destroyed||this.studio.pixiApp==null)){if(t||this.deselectClip(),t&&this.selectedClips.has(e)){this.selectedClips.delete(e),this.recreateTransformer(),this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)}),this.studio.pixiApp?.render();return}this.selectedClips.add(e),this.recreateTransformer(),t?this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)}):this.studio.emit("selection:created",{selected:Array.from(this.selectedClips)}),this.studio.pixiApp?.render()}}selectClipsByIds(e){const t=this.studio.clips.filter(i=>e.includes(i.id));this.setSelection(t)}setSelection(e){if(!(this.studio.destroyed||this.studio.pixiApp==null)&&!(this.selectedClips.size===e.length&&e.every(t=>this.selectedClips.has(t)))){for(const t of this.selectedClips)this.syncSpriteToClipProperties(t);this.destroyTransformer(),this.selectedClips.clear();for(const t of e)this.selectedClips.add(t);this.selectedClips.size>0?(this.createTransformer(),this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)})):this.studio.emit("selection:cleared",{deselected:[]}),this.studio.pixiApp?.render()}}deselectClip(){if(this.selectedClips.size>0)for(const t of this.selectedClips)this.syncSpriteToClipProperties(t);this.destroyTransformer();const e=Array.from(this.selectedClips);this.selectedClips.clear(),e.length>0&&this.studio.emit("selection:cleared",{deselected:e}),this.studio.pixiApp?.render()}async move(e,t){if(this.selectedClips.size===0)return;const i=[];for(const n of this.selectedClips)i.push({id:n.id,updates:{left:(n.left??0)+e,top:(n.top??0)+t}});await this.studio.updateClips(i),this.activeTransformer&&this.activeTransformer.updateBounds()}clear(){this.deselectClip(),this.interactiveClips.clear()}recreateTransformer(){this.destroyTransformer(),this.selectedClips.size>0&&this.createTransformer()}destroyTransformer(){this.activeTransformer!=null&&(this.activeTransformer.parent!=null&&this.activeTransformer.parent.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null)}createTransformer(){if(this.studio.destroyed||this.studio.artboard==null||this.selectedClips.size===0)return;const e=[];let t=null;for(const s of this.selectedClips){const o=this.studio.spriteRenderers.get(s);if(o==null)continue;const a=o.getRoot();a!=null&&(e.push(a),this.selectedClips.size===1&&(t=s))}if(e.length===0){console.warn("Cannot create transformer: no sprites found");return}const i=t?.locked??!1;this.activeTransformer=new X4({group:e,clip:t,artboardWidth:this.studio.opts.width,artboardHeight:this.studio.opts.height,locked:i});let n=null;this.activeTransformer.on("transforming",()=>{n===null&&(n=requestAnimationFrame(()=>{n=null,this.syncSelectedClipsTransformsRealtime(),this.studio.pixiApp?.render()}))}),this.activeTransformer.on("textClipResize",s=>{this.textClipResizedWidth=s.newWidth,this.textClipResizeHandle=s.handle,this.textClipResizedSx=s.sx,this.textClipResizedSy=s.sy}),this.activeTransformer.on("transformEnd",async()=>{n!==null&&(cancelAnimationFrame(n),n=null),await this.syncSelectedClipsTransforms();for(const s of this.selectedClips)this.studio.emit("clip:updated",{clip:s});this.studio.emit("transform:end",{transformer:this.activeTransformer})}),this.activeTransformer.on("pointerdown",s=>{if(s.button!==0)return;this.studio.emit("transform:start",{transformer:this.activeTransformer});const o=this.getTopmostClipAtPoint(s.global),a=Date.now();o&&o===this.lastPointerDownClip&&a-this.lastPointerDownTime<350&&(o.type==="Text"||o.type==="Caption")&&this.studio.emit("clip:dblclick",{clip:o}),this.lastPointerDownTime=a,this.lastPointerDownClip=o,o&&!this.selectedClips.has(o)&&(this.selectClip(o,s.shiftKey),s.stopPropagation())}),this.studio.artboard.addChild(this.activeTransformer),this.activeTransformer.showImmediate(),this.studio.pixiApp?.render()}async syncSelectedClipsTransformsRealtime(){if(this.selectedClips.size===0||this.activeTransformer==null)return;const e=this.activeTransformer.activeHandle;if(e===null){for(const t of this.selectedClips){const i=this.studio.spriteRenderers.get(t);if(i==null)continue;const n=i.getRoot(),s=i.getSprite();if(n==null||s==null||s.texture==null)continue;const o=Math.abs(n.scale.x*s.scale.x)*s.texture.width,a=Math.abs(n.scale.y*s.scale.y)*s.texture.height;t.left=n.x-o/2,t.top=n.y-a/2}return}if(e==="mr"||e==="ml"){if(this.isUpdatingTextRealtime)return;this.isUpdatingTextRealtime=!0;try{for(const t of this.selectedClips){if(!(t instanceof Zi))continue;const i=this.studio.spriteRenderers.get(t);if(i==null)continue;const n=i.getRoot(),s=i.getSprite();if(n==null||s==null||s.texture==null)continue;const o=Math.abs(n.scale.x*s.scale.x);if(o===1)continue;const a=t.left,l=t.top,u=t.width,c=s.texture.width,h=o*c;await t.updateStyle({wordWrap:!0,wordWrapWidth:h});const d=await t.getTexture();d&&(await i.updateFrame(d),s.scale.set(1,1),n.scale.set(1,1),e==="ml"?t.left=a+u-t.width:t.left=a,t.top=l,n.x=t.left+t.width/2,n.y=t.top+t.height/2,this.activeTransformer.updateBounds())}}finally{this.isUpdatingTextRealtime=!1}}}async syncSelectedClipsTransforms(){if(!(this.selectedClips.size===0||this.activeTransformer==null)){for(const e of this.selectedClips){const t=this.studio.spriteRenderers.get(e);if(t==null)continue;const i=t.getRoot(),n=t.getSprite();if(i==null||n==null||n.texture==null)continue;const s=n.texture.width,o=n.texture.height,a=Math.abs(i.scale.x*n.scale.x)*s,l=Math.abs(i.scale.y*n.scale.y)*o,u=(e instanceof Zi||e instanceof Nn)&&this.textClipResizedWidth!==null?this.textClipResizedWidth:a,c=e.width,d=(e.style?.fontSize??16)*Math.max(this.textClipResizedSx||1,this.textClipResizedSy||1);let f=i.x;if((e instanceof Zi||e instanceof Nn)&&this.textClipResizedWidth!==null){const m={wordWrap:!0,wordWrapWidth:u};this.textClipResizeHandle==="mr"?(f=e.left+u/2,i.x=f):this.textClipResizeHandle==="ml"?(f=e.left+u/2-(u-c),i.x=f):["br","tr"].includes(this.textClipResizeHandle)?(f=e.left+u/2,m.fontSize=d):["bl","tl"].includes(this.textClipResizeHandle)&&(f=e.left+u/2-(u-c),m.fontSize=d),await e.updateStyle(m);const g=await e.getTexture();g&&(await t.updateFrame(g),e.width=u,e.height=g.height,this.textClipResizedWidth=null,e.left=f-e.width/2,e.top=i.y-e.height/2,n.scale.set(1,1),i.scale.set(1,1))}else{let m=a,g=l;e.left=i.x-m/2,e.top=i.y-g/2,e.width=m,e.height=g;const v=e.flip==null?1:-1;e.angle=v*i.angle}}this.activeTransformer!=null&&this.activeTransformer.updateBounds();for(const e of this.selectedClips){const t=this.studio.spriteRenderers.get(e);t?.updateTransforms()}}}syncSpriteToClipProperties(e){const t=this.studio.spriteRenderers.get(e);if(t!=null){const i=t.getRoot(),n=t.getSprite();if(i!=null&&n!=null&&n.texture!=null){const s=n.texture.width,o=n.texture.height,a=Math.abs(i.scale.x*n.scale.x)*s,l=Math.abs(i.scale.y*n.scale.y)*o;let u=a,c=l;const h=i.x-u/2,d=i.y-c/2;e.left=h,e.top=d,e.width=u,e.height=c;const f=e.flip==null?1:-1;e.angle=f*i.angle,t.updateTransforms(),this.studio.emit("clip:updated",{clip:e})}}}async deleteSelected(){return this.studio.deleteSelected()}}class Ite{constructor(e){this.studio=e}isPlaying=!1;currentTime=0;maxDuration=0;playStartTime=0;playStartTimestamp=0;rafId=null;playbackElements=new Map;setMaxDuration(e){this.maxDuration=e}async play(){if(!(this.isPlaying||this.studio.destroyed)){if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){console.warn("Cannot play: invalid duration",this.maxDuration);return}this.isPlaying||(this.isPlaying=!0),this.playStartTime=this.currentTime,this.playStartTimestamp=performance.now();for(const[e,{element:t}]of this.playbackElements.entries()){if(!(this.currentTime>=e.display.from&&(e.display.to===0||this.currentTime<=e.display.to))){this.isPlaybackCapable(e)&&e.pause(t);continue}const n=(this.currentTime-e.display.from)/1e6;this.isPlaybackCapable(e)&&await e.play(t,n)}this.renderLoop(),this.studio.emit("play",{isPlaying:!0})}}pause(){this.isPlaying=!1,this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null);for(const[e,{element:t}]of this.playbackElements.entries())this.isPlaybackCapable(e)&&e.pause(t);this.studio.emit("pause",{isPlaying:!1})}async stop(){this.pause(),await this.seek(0)}async seek(e){if(this.studio.destroyed)return;const t=this.isPlaying;this.playStartTime=Math.max(0,Math.min(e,this.maxDuration)),this.playStartTimestamp=performance.now(),this.currentTime=this.playStartTime;for(const[i,{element:n}]of this.playbackElements.entries()){if(!(this.currentTime>=i.display.from&&(i.display.to===0||this.currentTime<=i.display.to))){this.isPlaybackCapable(i)&&i.pause(n);continue}const o=(this.currentTime-i.display.from)/1e6;this.isPlaybackCapable(i)&&await i.seek(n,o)}if(await this.studio.updateFrame(this.currentTime),this.studio.emit("currentTime",{currentTime:this.currentTime}),t){this.isPlaying=!0;for(const[i,{element:n}]of this.playbackElements.entries()){if(!(this.currentTime>=i.display.from&&(i.display.to===0||this.currentTime<=i.display.to)))continue;const o=(this.currentTime-i.display.from)/1e6;this.isPlaybackCapable(i)&&await i.play(n,o)}}}async frameNext(){const t=1e6/(this.studio.opts.fps||30),i=Math.min(this.currentTime+t,this.maxDuration);await this.seek(i)}async framePrev(){const t=1e6/(this.studio.opts.fps||30),i=Math.max(0,this.currentTime-t);await this.seek(i)}async renderLoop(){if(!this.isPlaying||this.studio.destroyed||this.studio.pixiApp==null)return;if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){this.pause();return}const e=async()=>{if(!this.isPlaying||this.studio.destroyed||this.studio.pixiApp==null)return;if(this.currentTime>=this.maxDuration){this.currentTime=this.maxDuration,this.pause();return}const i=(performance.now()-this.playStartTimestamp)*1e3;this.currentTime=Math.min(this.playStartTime+i,this.maxDuration),this.studio.emit("currentTime",{currentTime:this.currentTime});try{await this.studio.updateFrame(this.currentTime)}catch(n){console.warn("Error updating frame:",n)}this.isPlaying&&(this.rafId=requestAnimationFrame(e))};e()}isPlaybackCapable(e){return"play"in e&&"pause"in e&&"seek"in e}}class Qo{static instance;fonts=new Map;constructor(){}static getInstance(){return Qo.instance||(Qo.instance=new Qo),Qo.instance}async addFont(e){if(!this.fonts.has(e.name))try{const i=await new FontFace(e.name,`url(${e.url})`).load();document.fonts.add(i),this.fonts.set(e.name,i)}catch(t){console.error(`Failed to load font ${e.name}:`,t)}}async loadFonts(e){await Promise.all(e.map(t=>this.addFont(t)))}removeFont(e){const t=this.fonts.get(e);t&&(document.fonts.delete(t),this.fonts.delete(e))}clear(){this.fonts.forEach(e=>{document.fonts.delete(e)}),this.fonts.clear()}getLoadedFonts(){return Array.from(this.fonts.keys())}}const Y4=Qo.getInstance();class Bte{constructor(e){this.studio=e}tracks=[];clips=[];getTrackById(e){return this.tracks.find(t=>t.id===e)}getClipById(e){return this.clips.find(t=>t.id===e)}findTrackIdByClipId(e){for(const t of this.tracks)if(t.clipIds.includes(e))return t.id}getTrackIndex(e){return this.tracks.findIndex(t=>t.id===e)}addTrack(e,t){const i={id:e.id||`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:e.name,type:e.type,clipIds:[]};return typeof t=="number"?this.tracks.splice(t,0,i):this.tracks.unshift(i),this.studio.emit("track:added",{track:i,index:t??0}),this.studio.emit("track:order-changed",{tracks:this.tracks}),i}async removeTrack(e){const t=this.tracks.findIndex(s=>s.id===e);if(t===-1)return;const n=[...this.tracks[t].clipIds];for(const s of n)await this.removeClipById(s);this.tracks.splice(t,1),this.studio.emit("track:removed",{trackId:e}),this.studio.emit("track:order-changed",{tracks:this.tracks})}async moveTrack(e,t){const i=this.tracks.findIndex(s=>s.id===e);if(i===-1)return;const n=this.tracks[i];this.tracks.splice(i,1),this.tracks.splice(t,0,n),this.studio.emit("track:order-changed",{tracks:this.tracks}),await this.studio.updateFrame(this.studio.currentTime)}async setTrackOrder(e){const t=[],i=new Map(this.tracks.map(n=>[n.id,n]));for(const n of e){const s=i.get(n);s&&t.push(s)}t.length!==this.tracks.length&&console.warn("[Studio] setTrackOrder: invalid track IDs provided, order not updated fully"),this.tracks=t,this.studio.emit("track:order-changed",{tracks:this.tracks}),await this.studio.updateFrame(this.studio.currentTime)}async addTransition(e,t=2e6,i,n){if(this.studio.destroyed)return;let s=null,o=null;if(i&&n&&(s=this.getClipById(i)??null,o=this.getClipById(n)??null),!s||!o){console.warn("[Studio] Invalid fromClipId or toClipId",{fromClipId:i,toClipId:n});return}await Promise.all([s.ready,o.ready]);const a=t,l=o.display.from-a/2,u=l+a,c={key:e,name:e,duration:a,fromClipId:s.id,toClipId:o.id,start:Math.max(0,l),end:u},h=this.findTrackIdByClipId(o.id);if(h){const p=this.tracks.find(m=>m.id===h);if(p){const m=p.clipIds.map(g=>this.getClipById(g)).filter(g=>{if(!g||g.type!=="Transition")return!1;const v=g;return v.fromClipId===s.id&&v.toClipId===o.id});for(const g of m)await this.removeClip(g)}}const d=`${s.id}_${o.id}`;this.studio.transitionRenderers.has(d)&&(this.studio.transitionRenderers.get(d)?.destroy(),this.studio.transitionRenderers.delete(d)),s.transition={...c},o.transition={...c};const f=new Fi(e);f.duration=a,f.fromClipId=Math.max(0,l)===0?null:s.id,f.toClipId=o.id,f.fromClipId===null&&s&&(f.fromClipId=s.id),f.display.from=Math.max(0,l),f.display.to=u,await this.addClip(f,{trackId:h}),this.studio.seek(this.studio.currentTime)}async addClip(e,t){const i=Array.isArray(e)?e:[e];if(i.length===0)return;const{trackId:n,audioSource:s}=this.normalizeAddClipOptions(t);if(this.studio.destroyed)return;if(this.studio.pixiApp==null)throw new Error("Failed to initialize Pixi.js Application");const o=[];for(const a of i)await this.prepareClipForTimeline(a,n),o.push(a);await this.recalculateMaxDuration();for(const a of o)await this.setupClipVisuals(a,s);await this.studio.updateFrame(this.studio.currentTime),this.emitAddClipEvents(o,n)}normalizeAddClipOptions(e){let t,i;if(e&&(typeof e=="string"||e instanceof File||e instanceof Blob))t=e;else if(typeof e=="object"&&e!==null&&!("size"in e)){const n=e;t=n.audioSource,i=n.trackId}return{trackId:i,audioSource:t}}async prepareClipForTimeline(e,t){e.id||(e.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.includes(e)||this.clips.push(e),this.addClipToTrack(e,t);const i=async()=>{await this.studio.updateFrame(this.studio.currentTime);const n=this.studio.selection;n.activeTransformer!=null&&n.selectedClips.has(e)&&typeof n.activeTransformer.updateBounds=="function"&&n.activeTransformer.updateBounds()};e.on("propsChange",i),this.studio.clipListeners.set(e,i),this.studio.pixiApp!=null&&typeof e.setRenderer=="function"&&e.setRenderer(this.studio.pixiApp.renderer),await e.ready}addClipToTrack(e,t){if(t){const i=this.tracks.find(n=>n.id===t);if(i)i.clipIds.includes(e.id)||i.clipIds.push(e.id);else{const n={id:t,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(n),this.studio.emit("track:added",{track:n,index:0}),this.studio.emit("track:order-changed",{tracks:this.tracks})}}else{const n={id:`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(n),this.studio.emit("track:added",{track:n,index:0}),this.studio.emit("track:order-changed",{tracks:this.tracks})}}async setupClipVisuals(e,t){const i=this.studio.spriteRenderers.get(e);if(i){const n=this.studio.clipsNormalContainer,s=i.getRoot();s&&!s.parent&&n.addChild(s)}else{const n=await e.ready;if(n.width>0&&n.height>0){const s=this.studio.clipsNormalContainer,o=e.type==="Video"&&this.isPlaybackCapable(e);if(!o||o&&e.tickInterceptor!=null){const a=new z4(this.studio.pixiApp,e,s);this.studio.spriteRenderers.set(e,a)}}}await this.setupPlaybackForClip(e,t),this.studio.opts.interactivity&&this.studio.selection.setupSpriteInteractivity(e)}emitAddClipEvents(e,t){if(e.length!==0)if(e.length===1){const i=e[0],n=t||this.tracks.find(s=>s.clipIds.includes(i.id))?.id||"";this.studio.emit("clip:added",{clip:i,trackId:n})}else this.studio.emit("clips:added",{clips:e,trackId:t})}async removeClip(e,t={permanent:!0}){const{permanent:i}=t;if(e.locked)return;const n=this.clips.findIndex(c=>c===e);if(n===-1)return;if(e instanceof Fi){if(e.fromClipId){const c=this.getClipById(e.fromClipId);c&&"transition"in c&&delete c.transition}if(e.toClipId){const c=this.getClipById(e.toClipId);c&&"transition"in c&&delete c.transition}}this.studio.selection.selectedClips.has(e)&&this.studio.selection.deselectClip(),this.clips.splice(n,1);const s=[];for(const c of this.tracks){const h=c.clipIds.indexOf(e.id);h!==-1&&(c.clipIds.splice(h,1),s.push(c.id))}this.reconcileTracks(),this.studio.selection.interactiveClips.delete(e);const o=this.studio.clipListeners.get(e);o&&(e.off("propsChange",o),this.studio.clipListeners.delete(e));const a=this.studio.spriteRenderers.get(e);if(a!=null)if(i)a.destroy(),this.studio.spriteRenderers.delete(e);else{const c=a.getRoot();c&&c.parent&&c.parent.removeChild(c)}const l=this.studio.transport.playbackElements.get(e);l!=null&&(this.isPlaybackCapable(e)&&e.pause(l.element),this.studio.transport.playbackElements.delete(e),i&&this.isPlaybackCapable(e)&&e.cleanupPlayback(l.element,l.objectUrl));const u=this.studio.videoSprites.get(e);u!=null&&this.studio.pixiApp!=null&&(u.parent&&u.parent.removeChild(u),i&&(u.destroy(),this.studio.videoSprites.delete(e))),await this.recalculateMaxDuration(),this.studio.emit("clip:removed",{clipId:e.id})}async removeClips(e,t={permanent:!0}){if(e.length!==0){for(const i of e){if(i.locked)continue;const n=this.clips.findIndex(u=>u===i);if(n===-1)continue;if(i instanceof Fi){if(i.fromClipId){const u=this.getClipById(i.fromClipId);u&&"transition"in u&&delete u.transition}if(i.toClipId){const u=this.getClipById(i.toClipId);u&&"transition"in u&&delete u.transition}}this.studio.selection.selectedClips.has(i)&&this.studio.selection.deselectClip(),this.clips.splice(n,1);for(const u of this.tracks){const c=u.clipIds.indexOf(i.id);c!==-1&&u.clipIds.splice(c,1)}this.studio.selection.interactiveClips.delete(i);const s=this.studio.clipListeners.get(i);s&&(i.off("propsChange",s),this.studio.clipListeners.delete(i));const o=this.studio.spriteRenderers.get(i);if(o!=null)if(t.permanent)o.destroy(),this.studio.spriteRenderers.delete(i);else{const u=o.getRoot();u&&u.parent&&u.parent.removeChild(u)}const a=this.studio.transport.playbackElements.get(i);a!=null&&(this.isPlaybackCapable(i)&&i.pause(a.element),this.studio.transport.playbackElements.delete(i),t.permanent&&this.isPlaybackCapable(i)&&i.cleanupPlayback(a.element,a.objectUrl));const l=this.studio.videoSprites.get(i);l!=null&&this.studio.pixiApp!=null&&(l.parent&&l.parent.removeChild(l),t.permanent&&(l.destroy(),this.studio.videoSprites.delete(i)))}for(let i=this.tracks.length-1;i>=0;i--)if(this.tracks[i].clipIds.length===0){const n=this.tracks[i].id;this.tracks.splice(i,1),this.studio.emit("track:removed",{trackId:n})}await this.recalculateMaxDuration(),this.studio.emit("clips:removed",{clipIds:e.map(i=>i.id)})}}async removeClipById(e){const t=this.clips.find(i=>i.id===e);t&&await this.removeClip(t)}async updateClip(e,t){const i=this.clips.find(n=>n.id===e);i&&(i.locked&&!("locked"in t)||(i.locked&&"locked"in t&&(Object.keys(t).length===1||(t={locked:t.locked})),await this.applyClipUpdate(i,t),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(i),this.studio.emit("clip:updated",{clip:i})))}async updateClips(e){const t=[];for(const{id:i,updates:n}of e){const s=this.clips.find(o=>o.id===i);s&&(await this.applyClipUpdate(s,n),t.push(s))}if(t.length!==0){await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime);for(const i of t)this.updateTransformer(i),this.studio.emit("clip:updated",{clip:i})}}async replaceClipsBySource(e,t){const i=this.clips.filter(n=>n.src===e);if(i.length!==0){this.studio.suspendRendering();for(const n of i){if(!this.clips.includes(n))continue;const s=this.findTrackIdByClipId(n.id);if(!s)continue;const o=this.getTrackById(s);if(!o)continue;const a=await t(n),l=async()=>{await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(a)};a.on("propsChange",l),this.studio.clipListeners.set(a,l),this.studio.pixiApp!=null&&typeof a.setRenderer=="function"&&a.setRenderer(this.studio.pixiApp.renderer),await a.ready;const u=this.clips.indexOf(n);u!==-1&&(this.clips[u]=a);const c=o.clipIds.indexOf(n.id);c!==-1&&(o.clipIds[c]=a.id),await this.setupClipVisuals(a);const h=this.studio.spriteRenderers.get(n);h&&(h.destroy(),this.studio.spriteRenderers.delete(n));const d=this.studio.videoSprites.get(n);d&&(d.parent&&d.parent.removeChild(d),d.destroy(),this.studio.videoSprites.delete(n));const f=this.studio.clipListeners.get(n);f&&(n.off("propsChange",f),this.studio.clipListeners.delete(n)),this.studio.selection.selectedClips.has(n)&&(this.studio.selection.selectedClips.delete(n),this.studio.selection.selectedClips.add(a)),this.studio.emit("clip:replaced",{oldClip:n,newClip:a,trackId:s})}await this.recalculateMaxDuration(),this.studio.resumeRendering(),await this.studio.updateFrame(this.studio.currentTime)}}async applyClipUpdate(e,t){if(e.type==="Text"||e.type==="Caption"){const i=e;typeof i.updateStyle=="function"&&await i.updateStyle(t),"style"in t&&delete t.style}if(Object.assign(e,t),t.display&&!t.duration?e.duration=t.display.to-t.display.from:t.duration&&(!t.display||!t.display.to)&&(e.display||(e.display={from:0,to:t.duration}),e.display.to=e.display.from+t.duration),t.display&&t.duration){const i=t.display.to-t.display.from;i!==t.duration&&(e.duration=i)}else e.display&&(e.display.to=e.display.from+e.duration)}updateTransformer(e){const t=this.studio.selection;t.selectedClips.has(e)&&t.activeTransformer&&t.activeTransformer.updateBounds()}exportToJSON(){this.reconcileTracks();const e=this.clips.map(n=>Dl(n,!1)),t=this.tracks.map(n=>({id:n.id,name:n.name,type:n.type,clipIds:[...n.clipIds]})),i=[];return this.clips.forEach(n=>{if(n.transition){const s=this.tracks.find(o=>o.clipIds.includes(n.id));if(s){const o=s.clipIds.indexOf(n.id);if(o>0){const a=s.clipIds[o-1];i.push({key:n.transition.name,duration:n.transition.duration,clips:[a,n.id]})}}}}),{tracks:t,clips:e,settings:{width:this.studio.opts.width,height:this.studio.opts.height,fps:this.studio.opts.fps,bgColor:this.studio.opts.bgColor}}}async loadFromJSON(e){if(await this.clear(),e.settings){const i=e.settings.width&&e.settings.width!==this.studio.opts.width||e.settings.height&&e.settings.height!==this.studio.opts.height;if(e.settings.width&&(this.studio.opts.width=e.settings.width),e.settings.height&&(this.studio.opts.height=e.settings.height),e.settings.fps&&(this.studio.opts.fps=e.settings.fps),e.settings.bgColor&&(this.studio.opts.bgColor=e.settings.bgColor),i&&this.studio.pixiApp!=null){const n=this.studio.opts.width,s=this.studio.opts.height;this.studio.pixiApp.renderer.resize(n,s),this.studio.opts.canvas&&(this.studio.opts.canvas.width=n,this.studio.opts.canvas.height=s)}}const t=[];if(e.clips){await this.ensureFontsForClips(e.clips);const i=e.clips.map(o=>o.src).filter(o=>o&&o.trim()!=="");this.studio.resourceManager.preload(i);const n=new Map;if(e.tracks){for(const o of e.tracks)if(o.clipIds)for(const a of o.clipIds)n.set(a,o.id)}if(e.tracks)for(const o of e.tracks)this.tracks.push({id:o.id,name:o.name,type:o.type,clipIds:[]});for(const o of e.clips)t.push((async()=>{try{let a=o.id?n.get(o.id):void 0;if(o.type==="Transition"){const u=o,c=u.toClipId||u.fromClipId;c&&(a=n.get(c))}if(o.type!=="Text"&&o.type!=="Caption"&&o.type!=="Effect"&&o.type!=="Transition"&&(!o.src||o.src.trim()===""))return console.warn(`Skipping clip ${o.type} with empty source`,o),{clip:null};const l=await qo(o);return(l.type==="Video"||l.type==="Image")&&(!o.width||!o.height)&&this.studio.opts.width&&this.studio.opts.height&&(typeof l.scaleToFit=="function"&&await l.scaleToFit(this.studio.opts.width,this.studio.opts.height),typeof l.centerInScene=="function"&&l.centerInScene(this.studio.opts.width,this.studio.opts.height)),{clip:l,intendedTrackId:a}}catch(a){return console.error(`Failed to load clip ${o.id||"unknown"}:`,a),{clip:null}}})());const s=await Promise.all(t);for(const{clip:o,intendedTrackId:a}of s)o&&(o.id||(o.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.push(o),this.addClipToTrack(o,a))}this.studio.pixiApp&&this.clips.forEach(i=>{const n=async()=>{await this.studio.updateFrame(this.studio.currentTime);const s=this.studio.selection;s.activeTransformer!=null&&s.selectedClips.has(i)&&typeof s.activeTransformer.updateBounds=="function"&&s.activeTransformer.updateBounds()};i.on("propsChange",n),this.studio.clipListeners.set(i,n),typeof i.setRenderer=="function"&&i.setRenderer(this.studio.pixiApp.renderer),(async()=>{try{await i.ready,await this.setupClipVisuals(i),await this.studio.updateFrame(this.studio.currentTime)}catch(s){console.warn(`[Studio] Failed to setup visuals for clip ${i.id}:`,s)}})()});for(const i of this.clips){const n=i.effects;if(Array.isArray(n))for(const s of n)this.studio.globalEffects.has(s.id)||this.studio.globalEffects.set(s.id,{id:s.id,key:s.key,startTime:s.startTime,duration:s.duration})}for(const i of this.clips)if(i instanceof Fi){const n={name:i.transitionEffect.key,key:i.transitionEffect.key,duration:i.duration,fromClipId:i.fromClipId,toClipId:i.toClipId,start:i.display.from,end:i.display.to};if(i.fromClipId){const s=this.getClipById(i.fromClipId);s&&(s.transition={...n})}if(i.toClipId){const s=this.getClipById(i.toClipId);s&&(s.transition={...n})}}await this.recalculateMaxDuration();try{await this.studio.updateFrame(this.studio.currentTime)}catch(i){console.error("[Studio] Failed to update initial frame:",i)}this.studio.emit("studio:restored",{clips:this.clips,tracks:this.tracks,settings:this.studio.opts})}async deleteSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e);if(t.length!==0)for(const i of t)await this.removeClip(i)}async duplicateSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e).filter(n=>!n.locked);if(t.length===0)return;const i=[];for(const n of t){const s=this.findTrackIdByClipId(n.id);if(!s)continue;const o=this.tracks.find(h=>h.id===s);if(!o)continue;const a=Dl(n,!1),l=await qo(a);l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const u=`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=`${o.name} (Copy)`;this.addTrack({id:u,name:c,type:o.type}),await this.addClip(l,{trackId:u}),i.push(l.id)}i.length>0&&this.studio.selection.selectClipsByIds(i)}async splitSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==1){console.warn("[Studio] Split requires exactly one selected clip");return}const i=t[0];if(i.locked){console.warn("[Studio] Cannot split a locked clip");return}const n=e??this.studio.currentTime;if(n<=i.display.from||i.display.to>0&&n>=i.display.to){console.warn("[Studio] Split time is outside clip bounds");return}const s=Dl(i,!1),o=n-i.display.from,a=i.playbackRate||1,l=o*a,u={duration:o,display:{from:i.display.from,to:n}};i.trim&&(u.trim={from:i.trim.from,to:i.trim.from+l}),await this.updateClip(i.id,u);const c={...s};c.display={from:n,to:s.display.to},c.duration=s.duration-o,c.trim&&(c.trim={from:c.trim.from+l,to:c.trim.to});const h=await qo(c);h.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const d=this.findTrackIdByClipId(i.id);d&&(await this.addClip(h,{trackId:d}),this.studio.selection.selectClipsByIds([h.id]))}async trimSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==1){console.warn("[Studio] Trim requires exactly one selected clip");return}const i=t[0];if(i.locked){console.warn("[Studio] Cannot trim a locked clip");return}const n=e*1e6,s=i.playbackRate||1,o=n*s;if(n>=i.duration){console.warn("[Studio] Trim amount exceeds clip duration");return}const a=i.duration-n,l=i.display.from+n,u=i.display.to,c={duration:a,display:{from:l,to:u}};if(i.trim)c.trim={from:i.trim.from+o,to:i.trim.to};else{const h=i.sourceDuration||i.duration;c.trim={from:o,to:h}}await this.updateClip(i.id,c)}async updateSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==0)for(const i of t)await this.updateClip(i.id,e)}async setTracks(e){const t=JSON.parse(JSON.stringify(this.tracks));this.tracks=JSON.parse(JSON.stringify(e)),this.reconcileTracks(),this.tracks.length===0&&this.clips.length>0&&(this.tracks=t,this.reconcileTracks()),await this.recalculateMaxDuration(),this.studio.isRestoring||this.studio.emit("track:order-changed",{tracks:this.tracks}),await this.studio.updateFrame(this.studio.currentTime)}reconcileTracks(){const e=new Set(this.clips.map(t=>t.id));for(let t=this.tracks.length-1;t>=0;t--){const i=this.tracks[t],n=i.clipIds.filter(s=>e.has(s));n.length!==i.clipIds.length&&(i.clipIds=n),i.clipIds.length===0&&(this.tracks.splice(t,1),this.studio.isRestoring||this.studio.emit("track:removed",{trackId:i.id}))}this.tracks.length===0&&!this.studio.isRestoring&&this.studio.emit("track:order-changed",{tracks:this.tracks})}async ensureFontsForClips(e){const t=new Map;for(const i of e){if(i.type==="Text"){const n=i.style?.fontUrl||i.fontUrl;n&&t.set(n,{name:i.style?.fontFamily||i.fontFamily||"CustomFont",url:n})}if(i.type==="Caption"){const n=i.style?.fontUrl||i.fontUrl;n&&t.set(n,{name:i.style?.fontFamily||i.fontFamily||"CustomFont",url:n})}}if(t.size>0)try{await Y4.loadFonts(Array.from(t.values()))}catch(i){console.warn("Failed to load some fonts:",i)}}async recalculateMaxDuration(){let e=0;for(const t of this.clips){t.display.to===0&&t.duration!==1/0&&!isNaN(t.duration)&&t.duration>0;const i=t.duration>0?t.duration:0;if(i===1/0)continue;const n=t.display.to>0?t.display.to:t.display.from+i;n>e&&(e=n)}this.studio.maxDuration=e}async setupPlaybackForClip(e,t){if(this.studio.pixiApp!=null&&this.isPlaybackCapable(e))try{const i=e;if(e.type==="Audio"&&t&&typeof t!="string"){const o=URL.createObjectURL(t);e.src=o}const{element:n,objectUrl:s}=await i.createPlaybackElement();if(e.type==="Video"){const o=Q.from(n),a=new $e(o);a.visible=!1,this.studio.clipsNormalContainer&&this.studio.clipsNormalContainer.addChild(a),this.studio.videoSprites.set(e,a)}this.studio.transport.playbackElements.set(e,{element:n,objectUrl:s})}catch(i){console.warn(`Failed to setup playback for ${e.constructor.name}`,i)}}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async clear(){this.studio.selection.deselectClip(),this.studio.selection.interactiveClips.clear();for(const[e,t]of this.studio.clipListeners)e.off("propsChange",t);this.studio.clipListeners.clear(),this.studio.globalEffects.clear(),this.studio.effectFilters.clear(),this.studio.transitionRenderers.forEach(e=>e.destroy()),this.studio.transitionRenderers.clear(),this.studio.transitionSprites.forEach(e=>{e.parent&&e.parent.removeChild(e),e.destroy()}),this.studio.transitionSprites.clear(),this.studio.spriteRenderers.forEach(e=>e.destroy()),this.studio.spriteRenderers.clear();for(const[e,t]of this.studio.transport.playbackElements)this.isPlaybackCapable(e)&&e.cleanupPlayback(t.element,t.objectUrl);this.studio.transport.playbackElements.clear();for(const e of this.studio.videoSprites.values())e.destroy();this.studio.videoSprites.clear(),this.tracks=[],this.clips=[],this.studio.maxDuration=0,this.studio.currentTime=0,this.studio.emit("reset")}async rippleDelete(e,t){if(e>=t)return;const i=t-e,n=[...this.clips];for(const s of n){const o=s.display.from,a=s.display.to;if(!(a<=e)){if(o>=t){await this.updateClip(s.id,{display:{from:s.display.from-i,to:s.display.to-i}});continue}if(o>=e&&a<=t){await this.removeClip(s);continue}if(o<e&&a>t){const l=await s.clone();l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const u=e,c=e+(a-t),h=s.trim.from+(t-o)*s.playbackRate,d=s.trim.to,f=this.tracks.find(p=>p.clipIds.includes(s.id));f&&(await this.addClip(l,{trackId:f.id}),await this.updateClip(l.id,{display:{from:u,to:c},trim:{from:h,to:d}})),await this.updateClip(s.id,{display:{from:s.display.from,to:e},trim:{from:s.trim.from,to:s.trim.from+(e-o)*s.playbackRate}});continue}if(o<e&&a<=t){await this.updateClip(s.id,{display:{from:s.display.from,to:e},trim:{from:s.trim.from,to:s.trim.from+(e-o)*s.playbackRate}});continue}if(o>=e&&a>t){await this.updateClip(s.id,{display:{from:e,to:e+(a-t)},trim:{from:s.trim.from+(t-o)*s.playbackRate,to:s.trim.to}});continue}}}await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}}const kte={Date:!0,RegExp:!0,String:!0,Number:!0};function q4(r,e,t={cyclesFix:!0},i=[]){let n=[];const s=Array.isArray(r);for(const a in r){const l=r[a],u=s?+a:a;if(!(a in e)){n.push({type:"REMOVE",path:[u],oldValue:r[a]});continue}const c=e[a],h=typeof l=="object"&&typeof c=="object"&&Array.isArray(l)===Array.isArray(c);l&&c&&h&&!kte[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!i.includes(l))?n.push.apply(n,q4(l,c,t,t.cyclesFix?i.concat([l]):[]).map(d=>(d.path.unshift(u),d))):l!==c&&!(Number.isNaN(l)&&Number.isNaN(c))&&!(h&&(isNaN(l)?l+""==c+"":+l==+c))&&n.push({path:[u],type:"CHANGE",value:c,oldValue:l})}const o=Array.isArray(e);for(const a in e)a in r||n.push({type:"CREATE",path:[o?+a:a],value:e[a]});return n}class Rte{past=[];future=[];lastState=null;maxSize;constructor(e={}){this.maxSize=e.maxSize||50}projectToHistoryState(e){const t={},i=JSON.parse(JSON.stringify(e.tracks||[]));return e.clips.forEach(n=>{n.id&&(t[n.id]=JSON.parse(JSON.stringify(n)))}),{clips:t,tracks:i,settings:JSON.parse(JSON.stringify(e.settings||{}))}}init(e){this.lastState=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),this.past=[],this.future=[]}push(e){if(!this.lastState){this.init(e);return}const t=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),i=q4(this.lastState,t);i.length!==0&&(this.past.push(i),this.past.length>this.maxSize&&this.past.shift(),this.future=[],this.lastState=t)}undo(e){const t=this.past.pop();if(!t)return null;const i=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),n=this.applyPatches(i,t,!0);return this.future.push(t),this.lastState=n,{patches:t,state:n}}redo(e){const t=this.future.pop();if(!t)return null;const i=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),n=this.applyPatches(i,t,!1);return this.past.push(t),this.lastState=n,{patches:t,state:n}}applyPatches(e,t,i){const n=JSON.parse(JSON.stringify(e)),s=i?[...t].reverse():t;for(const o of s){const{type:a,path:l}=o,u=o.value,c=o.oldValue;let h=n,d=!1;for(let p=0;p<l.length-1;p++){if(h[l[p]]===void 0||h[l[p]]===null){d=!0;break}h=h[l[p]]}if(d)continue;const f=l[l.length-1];if(i)switch(a){case"CREATE":Array.isArray(h)?h.splice(f,1):delete h[f];break;case"REMOVE":h[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break;case"CHANGE":h[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break}else switch(a){case"CREATE":h[f]=u&&typeof u=="object"?JSON.parse(JSON.stringify(u)):u;break;case"REMOVE":Array.isArray(h)?h.splice(f,1):delete h[f];break;case"CHANGE":h[f]=u&&typeof u=="object"?JSON.parse(JSON.stringify(u)):u;break}}return n}canUndo(){return this.past.length>0}canRedo(){return this.future.length>0}}class Fte extends Z0{selection;transport;timeline;history;resourceManager;pixiApp=null;get tracks(){return this.timeline.tracks}get clips(){return this.timeline.clips}spriteRenderers=new Map;artboard=null;clipContainer=null;artboardMask=null;artboardBg=null;get activeTransformer(){return this.selection.activeTransformer}set activeTransformer(e){this.selection.activeTransformer=e}get selectedClips(){return this.selection.selectedClips}set selectedClips(e){this.selection.selectedClips=e}get interactiveClips(){return this.selection.interactiveClips}set interactiveClips(e){this.selection.interactiveClips=e}get playbackElements(){return this.transport.playbackElements}videoSprites=new Map;clipListeners=new Map;get isPlaying(){return this.transport.isPlaying}set isPlaying(e){this.transport.isPlaying=e}get currentTime(){return this.transport.currentTime}set currentTime(e){this.transport.currentTime=e}get maxDuration(){return this.transport.maxDuration}set maxDuration(e){this.transport.maxDuration=e}opts;destroyed=!1;renderingSuspended=!1;historyPaused=!1;processingHistory=!1;isRestoring=!1;historyGroupDepth=0;clipCache=new Map;_isUpdatingLayout=!1;globalEffects=new Map;activeGlobalEffects=[];currentGlobalEffectSprite=null;effectFilters=new Map;transitionRenderers=new Map;transitionSprites=new Map;transFromTexture=null;transToTexture=null;transBgGraphics=null;clipsNormalContainer=null;clipsEffectContainer=null;videoTextureCache=new WeakMap;lastFromFrame=null;lastToFrame=null;hexToNumber(e){const t=e.startsWith("#")?e.slice(1):e;return parseInt(t,16)}ready;constructor(e){super(),this.opts={fps:30,bgColor:"#000000",interactivity:!0,spacing:0,...e},this.selection=new Pte(this),this.transport=new Ite(this),this.timeline=new Bte(this),this.history=new Rte,this.resourceManager=new No,this.ready=this.initPixiApp().then(()=>{this.history.init(this.exportToJSON())}),this.on("clip:added",t=>this.handleTimelineChange(t)),this.on("clips:added",t=>this.handleTimelineChange(t)),this.on("clip:replaced",t=>this.handleTimelineChange({clip:t.newClip})),this.on("studio:restored",t=>{t.clips.forEach(i=>this.attachClipEvents(i)),this.handleTimelineChange()}),this.on("clip:removed",this.handleClipRemoved),this.on("clips:removed",this.handleClipsRemoved),this.on("clip:updated",this.handleTimelineChange),this.on("track:removed",()=>this.handleTimelineChange()),this.on("track:added",()=>this.handleTimelineChange())}attachClipEvents(e){if(this.clipListeners.has(e))return;const t=()=>{this.updateFrame(this.currentTime)};e.on("request-render",t),this.clipListeners.set(e,t)}handleTimelineChange=e=>{e?.clip&&this.attachClipEvents(e.clip),e?.clips&&e.clips.forEach(t=>this.attachClipEvents(t)),this.updateFrame(this.currentTime),this.saveHistory()};saveHistory(){this.historyPaused||this.processingHistory||(this.history.push(this.exportToJSON()),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()}))}beginHistoryGroup(){this.processingHistory||this.isRestoring||(this.historyGroupDepth++,this.historyPaused=!0)}endHistoryGroup(){this.processingHistory||this.isRestoring||(this.historyGroupDepth=Math.max(0,this.historyGroupDepth-1),this.historyGroupDepth===0&&(this.historyPaused=!1,this.saveHistory()))}setPath(e,t,i){let n=e;for(let s=0;s<t.length-1;s++){const o=t[s];n[o]||(n[o]=typeof t[s+1]=="number"?[]:{}),n=n[o]}n[t[t.length-1]]=i}async applyHistoryPatches(e,t,i){const n=new Map,s=new Map,o=new Set;for(const a of e){const{type:l,path:u}=a,c=a.value,h=a.oldValue;if(u[0]==="clips"){const d=u[1];i?l==="CREATE"?o.add(d):l==="REMOVE"?s.set(d,h):l==="CHANGE"&&(n.has(d)||n.set(d,{}),this.setPath(n.get(d),u.slice(2),h)):l==="CREATE"?s.set(d,c):l==="REMOVE"?o.add(d):l==="CHANGE"&&(n.has(d)||n.set(d,{}),this.setPath(n.get(d),u.slice(2),c))}else u[0]==="settings"&&(i?this.setPath(this.opts,u.slice(1),h):this.setPath(this.opts,u.slice(1),c))}for(const a of o){const l=this.timeline.getClipById(a);l&&await this.removeClip(l)}for(const[a,l]of s){let u=this.clipCache.get(a);u||(u=await qo(l),this.clipCache.set(a,u),this.attachClipEvents(u));let c;for(const h of t.tracks)if(h.clipIds.includes(a)){c=h.id;break}await this.addClip(u,{trackId:c})}for(const[a,l]of n)await this.updateClip(a,l);this.timeline.setTracks(t.tracks),this.emit("studio:restored",{clips:this.clips,tracks:this.tracks,settings:this.opts})}async undo(){if(!(!this.history.canUndo()||this.processingHistory)){this.processingHistory=!0,this.isRestoring=!0,this.historyPaused=!0;try{const e=this.history.undo(this.exportToJSON());e&&await this.applyHistoryPatches(e.patches,e.state,!0),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}finally{this.historyPaused=!1,this.isRestoring=!1,this.processingHistory=!1}}}async redo(){if(!(!this.history.canRedo()||this.processingHistory)){this.processingHistory=!0,this.isRestoring=!0,this.historyPaused=!0;try{const e=this.history.redo(this.exportToJSON());e&&await this.applyHistoryPatches(e.patches,e.state,!1),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}finally{this.historyPaused=!1,this.isRestoring=!1,this.processingHistory=!1}}}cleanupClipVisuals=e=>{for(const[s,o]of this.spriteRenderers)if(s.id===e){const a=o.getRoot();a&&a.parent&&a.parent.removeChild(a),o.destroy(),this.spriteRenderers.delete(s);break}const t=this.transitionSprites.get(e);t&&(t.parent&&t.parent.removeChild(t),t.destroy(),this.transitionSprites.delete(e)),this.transitionRenderers.get(e)&&this.transitionRenderers.delete(e);for(const[s,o]of this.videoSprites)if(s.id===e){o.parent&&o.parent.removeChild(o),o.destroy(),this.videoSprites.delete(s);break}const n=this.timeline.getClipById(e);if(n){const s=this.clipListeners.get(n);s&&(n.off("request-render",s),this.clipListeners.delete(n))}};handleClipRemoved=({clipId:e})=>{this.cleanupClipVisuals(e),this.updateFrame(this.currentTime),this.saveHistory()};handleClipsRemoved=({clipIds:e})=>{for(const t of e)this.cleanupClipVisuals(t);this.updateFrame(this.currentTime),this.saveHistory()};async initPixiApp(){if(this.destroyed)return;const e=this.opts.canvas||document.createElement("canvas");e.width=this.opts.width,e.height=this.opts.height;const t=new bc,i=e.parentElement||window;await t.init({canvas:e,resizeTo:i,backgroundColor:this.hexToNumber(this.opts.bgColor),antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0,autoStart:!1}),this.pixiApp=t,t.render(),t.stage.eventMode="static",t.stage.hitArea=t.screen,this.artboard=new Ie,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new Je,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new Ie,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new Je,this.artboardMask.rect(0,0,this.opts.width,this.opts.height).fill({color:16777215}),this.clipContainer.addChild(this.artboardMask),this.clipContainer.mask=this.artboardMask,this.clipsEffectContainer=new Ie,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new Ie,this.clipsNormalContainer.label="ClipsNormal",this.clipsNormalContainer.zIndex=10,this.clipsNormalContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsNormalContainer),this.transFromTexture=Ot.create({width:this.opts.width,height:this.opts.height}),this.transToTexture=Ot.create({width:this.opts.width,height:this.opts.height}),this.transBgGraphics=new Je,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}),this.clipContainer.sortableChildren=!0,this.updateArtboardLayout(),t.renderer.on("resize",()=>{this.handleResize()})}getOptions(){return this.opts}setSize(e,t){this.updateDimensions(e,t)}setBgColor(e){this.opts.bgColor=e;const t=this.hexToNumber(e);this.pixiApp&&(this.pixiApp.renderer.background.color=t,this.pixiApp.render()),this.updateFrame(this.currentTime)}updateDimensions(e,t){this.opts.width=e,this.opts.height=t,this.artboardBg&&this.artboardBg.clear().rect(0,0,e,t).fill({color:0}),this.artboardMask&&this.artboardMask.clear().rect(0,0,e,t).fill({color:16777215}),this.transFromTexture&&this.transFromTexture.resize(e,t),this.transToTexture&&this.transToTexture.resize(e,t),this.transBgGraphics&&this.transBgGraphics.clear().rect(0,0,e,t).fill({color:0,alpha:0}),this.updateArtboardLayout(),this.updateFrame(this.currentTime)}handleResize=()=>{this.destroyed||!this.pixiApp||this._isUpdatingLayout||this.updateArtboardLayout()};updateArtboardLayout(){if(!(!this.pixiApp||!this.artboard||this._isUpdatingLayout)){this._isUpdatingLayout=!0;try{this.pixiApp.resize();const t=this.pixiApp.canvas.parentElement,i=t?t.getBoundingClientRect().width:this.pixiApp.screen.width,n=t?t.getBoundingClientRect().height:this.pixiApp.screen.height,s=this.opts.width,o=this.opts.height,a=this.opts.spacing||0,l=Math.max(0,i-a*2),u=Math.max(0,n-a*2),c=l/s,h=u/o,d=Math.min(c,h);this.artboard.scale.set(d),this.artboard.x=(i-s*d)/2,this.artboard.y=(n-o*d)/2,this.pixiApp.render()}finally{this._isUpdatingLayout=!1}}}getCanvas(){if(this.opts.canvas)return this.opts.canvas;if(this.pixiApp?.canvas)return this.pixiApp.canvas;throw new Error("Canvas not initialized yet. Wait for initPixiApp to complete.")}async addTransition(e,t=2e6,i,n){return this.timeline.addTransition(e,t,i,n)}findTrackIdByClipId(e){return this.timeline.findTrackIdByClipId(e)}async addClip(e,t){const i=Array.isArray(e)?e:[e];i.forEach(n=>this.clipCache.set(n.id,n)),this.beginHistoryGroup();try{const n=await this.timeline.addClip(e,t);return i.forEach(s=>this.attachClipEvents(s)),n}finally{this.endHistoryGroup()}}addTrack(e,t){return this.timeline.addTrack(e,t)}async setTracks(e){if(this.isRestoring)return;const t=new Set(this.timeline.clips.map(i=>i.id));if(!(e.length===0&&t.size>0)&&!(e.length>0&&t.size>0&&!e.some(n=>n.clipIds.some(s=>t.has(s)))))return this.timeline.setTracks(e)}async moveTrack(e,t){return this.timeline.moveTrack(e,t)}async setTrackOrder(e){return this.timeline.setTrackOrder(e)}async removeTrack(e){return this.timeline.removeTrack(e)}getClipById(e){return this.timeline.getClipById(e)}async updateClip(e,t){return this.timeline.updateClip(e,t)}async centerClip(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=(this.opts.width-t.width)/2,n=(this.opts.height-t.height)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{left:i,top:n});t.left=i,t.top=n}async centerClipH(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=(this.opts.width-t.width)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{left:i});t.left=i}async centerClipV(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=(this.opts.height-t.height)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{top:i});t.top=i}async scaleToFit(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=await t.ready,{width:n,height:s}=i;if(n===0||s===0)return;const o=Math.min(this.opts.width/n,this.opts.height/s),a=n*o,l=s*o;if(this.getClipById(t.id))return this.updateClip(t.id,{width:a,height:l});t.width=a,t.height=l}async scaleToCover(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=await t.ready,{width:n,height:s}=i;if(n===0||s===0)return;const o=Math.max(this.opts.width/n,this.opts.height/s),a=n*o,l=s*o;if(this.getClipById(t.id))return this.updateClip(t.id,{width:a,height:l});t.width=a,t.height=l}async updateClips(e){this.suspendRendering(),await this.timeline.updateClips(e),this.resumeRendering(),this.updateFrame(this.currentTime)}suspendRendering(){this.renderingSuspended=!0}resumeRendering(){this.renderingSuspended=!1}getTracks(){return this.timeline.tracks}getClip(e){return this.timeline.getClipById(e)}findClip(e){return this.timeline.getClipById(e)}setupSpriteInteractivity(e){this.selection.setupSpriteInteractivity(e)}async removeClip(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t){console.warn("[Studio] removeClip: Clip not found",e);return}this.beginHistoryGroup();try{return this.clipCache.set(t.id,t),this.timeline.removeClip(t,{permanent:!this.processingHistory})}finally{this.endHistoryGroup()}}async removeClips(e){this.beginHistoryGroup();try{return e.forEach(t=>this.clipCache.set(t.id,t)),this.timeline.removeClips(e,{permanent:!this.processingHistory})}finally{this.endHistoryGroup()}}async removeClipById(e){const t=this.timeline.getClipById(e);if(t)return this.removeClip(t)}async removeClipsById(e){const t=e.map(i=>this.timeline.getClipById(i)).filter(Boolean);return this.removeClips(t)}async deleteSelected(){const e=this.selection.selectedClips;if(e.size!==0){this.beginHistoryGroup();try{await this.removeClips(Array.from(e))}finally{this.endHistoryGroup()}}}async duplicateSelected(){this.beginHistoryGroup();try{return await this.timeline.duplicateSelected()}finally{this.endHistoryGroup()}}async splitSelected(e){this.beginHistoryGroup();try{return await this.timeline.splitSelected(e)}finally{this.endHistoryGroup()}}async trimSelected(e){return this.timeline.trimSelected(e)}async updateSelected(e){return this.timeline.updateSelected(e)}async clear(){await this.timeline.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null),this.transitionRenderers.forEach(e=>e.destroy()),this.transitionRenderers.clear(),this.transitionSprites.forEach(e=>e.destroy()),this.transitionSprites.clear(),this.emit("reset")}async play(){return this.transport.play()}pause(){this.transport.pause()}async stop(){return this.transport.stop()}async seek(e){return this.transport.seek(e)}async frameNext(){return this.transport.frameNext()}async framePrev(){return this.transport.framePrev()}async renderFrame(e){if(await this.ready,!this.pixiApp||!this.artboard)throw new Error("Studio is not initialized yet. Wait for studio.ready before calling renderFrame().");const t=e*1e3;await this.updateFrame(t);const i=this.artboard.scale.clone(),n=this.artboard.x,s=this.artboard.y;this.artboard.scale.set(1),this.artboard.x=0,this.artboard.y=0;let o;try{o=await this.pixiApp.renderer.extract.base64(this.artboard,"image/png",1)}finally{this.artboard.scale.set(i.x,i.y),this.artboard.x=n,this.artboard.y=s,this.pixiApp.render()}return o}getCurrentTime(){return this.transport.currentTime}getMaxDuration(){return this.transport.maxDuration}getIsPlaying(){return this.transport.isPlaying}getSelectedClips(){return Array.from(this.selectedClips)}getVideoTexture(e){let t=this.videoTextureCache.get(e);return t||(t=Q.from(e),this.videoTextureCache.set(e,t)),t}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async updateFrame(e){if(this.destroyed||this.pixiApp==null||this.renderingSuspended)return;this.updateActiveGlobalEffect(e);const t=new Set,i=new Set,n=this.tracks.length;for(const o of this.clips){const a=this.getTrackIndex(o.id);if(a!==-1){const l=(n-a)*10;o.zIndex=l;const u=this.spriteRenderers.get(o);if(u){const h=u.getRoot();h&&(h.zIndex=l)}const c=this.videoSprites.get(o);c&&(c.zIndex=l)}}const s=[...this.clips].sort((o,a)=>o.zIndex-a.zIndex);for(const o of s){if(e<o.display.from){const v=this.spriteRenderers.get(o);v!=null&&await v.updateFrame(null);const x=this.playbackElements.get(o);x!=null&&this.isPlaybackCapable(o)&&o.pause(x.element);continue}if(o.display.to>0&&e>o.display.to){const v=this.spriteRenderers.get(o);v!=null&&await v.updateFrame(null);const x=this.playbackElements.get(o);x!=null&&this.isPlaybackCapable(o)&&o.pause(x.element);continue}const a=e-o.display.from,l=a*o.playbackRate;o.animate(l);const u=await o.ready,c=o.duration||u.duration;if(c>0&&a>c){const v=this.spriteRenderers.get(o);v!=null&&await v.updateFrame(null);const x=this.playbackElements.get(o);x!=null&&this.isPlaybackCapable(o)&&o.pause(x.element);continue}const h=this.playbackElements.get(o),d=o.type==="Video"||o.type==="Image",f=o.transition?o.transition.start:0,p=o.transition?o.transition.end:0,m=d&&o.transition&&e>=f&&e<p;if(h!=null&&this.isPlaybackCapable(o)){const v=a/1e6;if(o.syncPlayback(h.element,this.isPlaying,v),o.type==="Video"&&this.isPlaybackCapable(o)){const x=this.videoSprites.get(o);if(x!=null){const y=o.meta.duration/1e6;if(this.spriteRenderers.has(o))x.visible=!1;else if(x.visible=!m&&v>=0&&v<y,x.visible&&yee(o,x),!m)continue}}else continue}if(m){const v=o?.transition?.fromClipId,x=o?.transition?.toClipId,y=`${v}_${x}`;if(i.has(y)){const P=this.spriteRenderers.get(o);P?.getRoot()&&(P.getRoot().visible=!1);const _=this.videoSprites.get(o);_&&(_.visible=!1);continue}i.add(y),this.transFromTexture||(this.transFromTexture=Ot.create({width:this.opts.width,height:this.opts.height})),this.transToTexture||(this.transToTexture=Ot.create({width:this.opts.width,height:this.opts.height})),this.transBgGraphics||(this.transBgGraphics=new Je,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}));const b=v?this.getClipById(v):null,T=x?this.getClipById(x):null;let E=null,C=null;if(b){const P=Math.max(0,e-b.display.from),{video:_}=await b.getFrame(P);_ instanceof HTMLVideoElement?E=this.getVideoTexture(_):E=_,E&&(this.lastFromFrame=E)}if(T){const P=Math.max(0,e-T.display.from),{video:_}=await T.getFrame(P);_ instanceof HTMLVideoElement?C=this.getVideoTexture(_):C=_,C&&(this.lastToFrame=C)}if(E||(E=this.lastFromFrame),C||(C=this.lastToFrame),!E||!C)continue;if(E&&C&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const P=(e-f)/o?.transition?.duration;b&&E&&this.renderClipToTransitionTexture(b,E,this.transFromTexture),T&&C&&this.renderClipToTransitionTexture(T,C,this.transToTexture);let _=this.transitionRenderers.get(y);if(!_)try{_=x1({name:o?.transition?.name,renderer:this.pixiApp.renderer}),this.transitionRenderers.set(y,_)}catch(S){console.error("[Studio] Failed to create transition renderer:",S)}if(_){const S=_.render({width:this.opts.width,height:this.opts.height,from:this.transFromTexture,to:this.transToTexture,progress:P});let I=this.transitionSprites.get(o.id);I||(I=new $e,I.label=`TransitionSprite_${o.id}`,this.transitionSprites.set(o.id,I),this.clipsNormalContainer&&this.clipsNormalContainer.addChild(I)),I.texture=S,I.visible=!0,I.x=0,I.y=0,I.width=this.opts.width,I.height=this.opts.height,I.anchor.set(0,0),I.zIndex=o.zIndex,t.add(o.id);const M=this.spriteRenderers.get(o);M?.getRoot()&&(M.getRoot().visible=!1);const O=this.videoSprites.get(o);if(O&&(O.visible=!1),b){const H=this.spriteRenderers.get(b);H?.getRoot()&&(H.getRoot().visible=!1);const K=this.videoSprites.get(b);K&&(K.visible=!1)}if(T){const H=this.spriteRenderers.get(T);H?.getRoot()&&(H.getRoot().visible=!1);const K=this.videoSprites.get(T);K&&(K.visible=!1)}continue}}}const g=this.spriteRenderers.get(o);if(g!=null){const v=this.selectedClips.has(o);if(o.type!=="Text"&&o.type!=="Caption"&&typeof o.getTexture=="function"&&o.getTexture()!=null){const y=o.getTexture();if(y!=null){await g.updateFrame(y),v||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(o);continue}}if(o.type==="Text"){const y=o;this.pixiApp?.renderer&&typeof y.setRenderer=="function"&&y.setRenderer(this.pixiApp.renderer);const b=await y.getTexture();if(b!=null){await g.updateFrame(b),v||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(o);continue}}if(o.type==="Caption"){o.updateState(a);const y=o;this.pixiApp?.renderer&&typeof y.setRenderer=="function"&&y.setRenderer(this.pixiApp.renderer);const b=await y.getTexture();if(b!=null){await g.updateFrame(b),v||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(o);continue}}const{video:x}=await o.getFrame(a);await g.updateFrame(x),v||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(o)}}if(this.activeGlobalEffects.length>0&&this.clipsNormalContainer&&this.clipsEffectContainer){for(const o of this.clips)this.moveClipToEffectContainer(o,!1);this.clipsNormalContainer.visible=!0,await this.applyGlobalEffects(e)}else if(this.clipsNormalContainer){for(const o of this.clips)this.moveClipToEffectContainer(o,!1);this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}for(const[o,a]of this.transitionSprites.entries())t.has(o)||(a.visible=!1);this.pixiApp!=null&&this.pixiApp.render()}moveClipToEffectContainer(e,t=!0){if(!this.clipsNormalContainer||!this.clipsEffectContainer)return;const i=t?this.clipsEffectContainer:this.clipsNormalContainer,n=this.spriteRenderers.get(e);if(n){const o=n.getRoot();if(o&&o.parent!==i){try{o.parent&&o.parent.removeChild&&o.parent.removeChild(o)}catch(a){console.warn("moveClipToEffectContainer: could not remove root from parent",a)}i.addChild(o)}}const s=this.transitionSprites.get(e.id);if(s&&s.parent!==i){try{s.parent&&s.parent.removeChild&&s.parent.removeChild(s)}catch(o){console.warn("moveClipToEffectContainer: could not remove transSprite from parent",o)}i.addChild(s)}}applyGlobalEffect(e,t,i){const n=t.id||`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s={id:n,key:e,startTime:t.startTime,duration:t.duration??1e6};for(const o of i)o instanceof Fl&&o.addEffect(s),o instanceof wr&&o.addEffect(s),o instanceof Zi&&o.addEffect(s),o instanceof Nn&&o.addEffect(s);return this.globalEffects.set(n,s),n}getTrackIndex(e){return this.tracks.findIndex(t=>t.clipIds.includes(e))}async getTransitionFromFrame(e,t){let i=null;if(e.transition?.prevClipId&&(i=this.clips.find(a=>a.id===e.transition.prevClipId)||null),i||(i=this.getPreviousClipOnTrack(e)),!i)return null;const n=i.duration>0?i.duration:0,s=Math.max(0,Math.min(t-i.display.from,n)),{video:o}=await i.getFrame(s);return o}getPreviousClipOnTrack(e){const t=this.getTrackIndex(e.id);return t===-1?null:this.clips.filter(i=>i.id!==e.id&&this.getTrackIndex(i.id)===t&&i.display.from<e.display.from&&(i instanceof wr||i instanceof Fl)).sort((i,n)=>n.display.to-i.display.to)[0]||null}renderClipToTransitionTexture(e,t,i){if(!this.pixiApp)return;const n=e.style||{},{renderTransform:s}=e,o=(s?.mirror??0)>.5,a=t instanceof Q?t:Q.from(t),l=s?.x??0,u=s?.y??0,c=s?.angle??0,h=s?.scale??1,d=s?.opacity??1,f=s?.blur??0,p=s?.brightness??1,m=a.width||1,g=a.height||1,v=e.type==="Caption",x=!v&&e.width&&e.width!==0?Math.abs(e.width)/m:1,y=!v&&e.height&&e.height!==0?Math.abs(e.height)/g:1,b=new Ie;b.x=e.center.x+l,b.y=e.center.y+u,b.rotation=(e.flip==null?1:-1)*((e.angle+c)*Math.PI)/180,b.alpha=e.opacity*d;const T=new $e(a);T.anchor.set(.5,.5);let E=[];if(o){const D=x*h,k=y*h,W=m*D,G=g*k;T.position.set(0,0),T.scale.set(D,k);const J=[[W,0,-D,k],[-W,0,-D,k],[0,G,D,-k],[0,-G,D,-k],[W,G,-D,-k],[-W,G,-D,-k],[W,-G,-D,-k],[-W,-G,-D,-k]];for(const[q,_e,Re,ge]of J){const z=new $e(a);z.anchor.set(.5,.5),z.position.set(q,_e),z.scale.set(Re,ge),E.push(z)}if(e.flip==="horizontal"){T.scale.x=-D;for(let q=0;q<8;q++)E[q].scale.x=-J[q][2]}else if(e.flip==="vertical"){T.scale.y=-k;for(let q=0;q<8;q++)E[q].scale.y=-J[q][3]}b.addChild(T);for(const q of E)b.addChild(q)}else e.flip==="horizontal"?(T.scale.x=-x*h,T.scale.y=y*h):e.flip==="vertical"?(T.scale.x=x*h,T.scale.y=-y*h):(T.scale.x=x*h,T.scale.y=y*h),b.addChild(T);const C=[];if(f>0){const D=new Fn;D.strength=f,D.quality=4,D.repeatEdgePixels=!0,C.push(D)}const P=m1(e.colorAdjustment);if(p!==1||P){const D=new Zc;g1(D,e.colorAdjustment,p),C.push(D)}const _=Rh(e.colorAdjustment);for(let D=0;D<_.length;D++){const k=_[D],W=new nt({uTargetColor:{value:[1,1,0],type:"vec3<f32>"},uHueShift:{value:k.hue,type:"f32"},uSatShift:{value:k.saturation/100,type:"f32"},uLightShift:{value:k.lightness/100,type:"f32"},uTolerance:{value:.22,type:"f32"},uSoftness:{value:.12,type:"f32"}}),G=Rl(k.targetColor);G&&(W.uniforms.uTargetColor[0]=G.r/255,W.uniforms.uTargetColor[1]=G.g/255,W.uniforms.uTargetColor[2]=G.b/255);const J=new fe({glProgram:new le({vertex:Go,fragment:$b,name:`SelectiveHslShader_${D}`}),resources:{hslUniforms:W}});C.push(J)}b.filters=C;const S=n.borderRadius||0;let I=null;S>0&&(I=new Je,I.roundRect(-m/2,-g/2,m,g,Math.min(S,m/2,g/2)),I.fill({color:16777215,alpha:1}),T.addChild(I),T.mask=I);const M=n.stroke;let O=null;if(M&&M.width>0){O=new Je;const D=xt(M.color)??16777215;if(O.setStrokeStyle({width:M.width,color:D,alignment:1}),S>0){const k=Math.min(S,m/2,g/2);O.roundRect(-m/2,-g/2,m,g,k)}else O.rect(-m/2,-g/2,m,g);O.stroke(),T.addChild(O)}const H=n.dropShadow;let K=null;if(H&&(H.blur>0||H.distance>0)){K=new Je;const D=xt(H.color)??0,k=H.alpha??.5,W=H.distance??0,G=H.angle??0,J=Math.cos(G)*W,q=Math.sin(G)*W;if(S>0){const _e=Math.min(S,m/2,g/2);K.roundRect(-m/2+J,-g/2+q,m,g,_e)}else K.rect(-m/2+J,-g/2+q,m,g);K.fill({color:D,alpha:k}),b.addChildAt(K,0)}this.pixiApp.renderer.render({container:b,target:i,clear:!0}),t instanceof Q||T.texture.destroy(!0),I&&I.destroy(),O&&O.destroy(),K&&K.destroy();for(const D of E)D.destroy();T.destroy(),b.destroy()}removeGlobalEffect(e){this.globalEffects.delete(e)}clearGlobalEffects(){this.globalEffects.clear()}updateActiveGlobalEffect(e){const t=[];for(const i of this.clips)i instanceof Ji&&e>=i.display.from&&(i.display.to===0||e<i.display.to)&&t.push({id:i.id,key:i.effect.key,startTime:i.display.from,duration:i.duration>0?i.duration:i.display.to-i.display.from,trackIndex:this.getTrackIndex(i.id),values:i.effect.values});for(const i of this.globalEffects.values()){const n=i.startTime+i.duration;e>=i.startTime&&e<n&&t.push({id:i.id,key:i.key,startTime:i.startTime,duration:i.duration,trackIndex:-1})}this.activeGlobalEffects=t.sort((i,n)=>(n.trackIndex??-1)-(i.trackIndex??-1))}async applyGlobalEffects(e){if(this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null),this.activeGlobalEffects.length===0||!this.pixiApp||!this.clipContainer||!this.clipsNormalContainer||!this.clipsEffectContainer)return;const t=this.opts.width,i=this.opts.height;let n=null,s=new Set;const o=[];for(const a of this.activeGlobalEffects){const{key:l,startTime:u,duration:c,trackIndex:h,values:d}=a,f=e-u,p=Math.min(Math.max(f/c,0),1);if(p<0||p>=1)continue;if(this.clipsEffectContainer.visible=!0,this.clipsEffectContainer.removeChildren(),n){const y=new $e(n);y.label="PrevEffectResult",y.width=t,y.height=i,this.clipsEffectContainer.addChild(y)}const m=h??-1;for(const y of this.clips){if(s.has(y.id))continue;const b=this.getTrackIndex(y.id);!(y instanceof Ji)&&(m===-1||b>m)&&(this.moveClipToEffectContainer(y,!0),s.add(y.id))}let g=this.effectFilters.get(l);if(!g)try{if(g=await p1({name:l,renderer:this.pixiApp.renderer,values:d}),g)this.effectFilters.set(l,g);else continue}catch(y){console.error(y);continue}const v=Ot.create({width:t,height:i});o.push(v),this.pixiApp.renderer.render({container:this.clipsEffectContainer,target:v,clear:!0});const x=g.render({canvasTexture:v,progress:p,width:t,height:i,values:d});this.clipsEffectContainer.visible=!1,n=x}if(n){const a=new $e(n);a.x=0,a.y=0,a.width=t,a.height=i,a.scale.set(1),a.zIndex=5,this.clipContainer.addChild(a),this.currentGlobalEffectSprite=a}for(const a of o)a.destroy(!0)}destroy(){if(!this.destroyed){window.removeEventListener("resize",this.handleResize),this.destroyed=!0,this.stop(),this.clear(),this.transitionRenderers.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null);for(const e of this.transitionSprites.values())e.destroy();this.transitionSprites.clear(),this.pixiApp&&(this.pixiApp.destroy(!0,{children:!0,texture:!0}),this.pixiApp=null)}}selectClip(e,t=!1){this.selection.selectClip(e,t)}setSelection(e){this.selection.setSelection(e)}selectClipsByIds(e){this.selection.selectClipsByIds(e)}deselectClip(){this.selection.deselectClip()}async lockClip(e,t){const i=this.timeline.getClipById(e);i&&(await this.timeline.updateClip(e,{locked:t}),this.emit("clip:lock-changed",{clip:i,locked:t}),this.selection.selectedClips.has(i)&&this.selection.recreateTransformer(),await this.updateFrame(this.currentTime))}exportToJSON(){return this.timeline.exportToJSON()}async loadFromJSON(e){return this.timeline.loadFromJSON(e)}}xe.add(oC),xe.mixin(Ie,aC),xe.add(Hx),xe.add(Wx),xe.add(Xy),xe.mixin(Ie,_P),xe.add(Hy),xe.add(Cb),xe.add(Dc),xe.add(Eb),xe.add(kb),xe.add(Rb),xe.add(Yb),xe.add(Xb),xe.add(Nb),xe.add(Wb),xe.add(Gb),xe.add(Ub),xe.add(Mb),xe.add(t2),xe.add(Jy);const Mte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Dte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));we.ANIMATABLE_PROPERTIES=NL,we.Audio=ti,we.Caption=Nn,we.Compositor=Tte,we.DEFAULT_AUDIO_CONF=st,we.Effect=Ji,we.GL_EFFECT_OPTIONS=EQ,we.GL_TRANSITION_OPTIONS=wte,we.Image=Fl,we.KeyframeAnimation=B,we.Log=Ee,we.MP4Clip=wr,we.Placeholder=Ml,we.Studio=Fte,we.Text=Zi,we.Transition=Fi,we.VALUES_FILTER_SPECIAL=f1,we.VALUES_FILTER_SPECIAL_LIMITS=mee,we.Video=wr,we.animationRegistry=U,we.clipToJSON=Dl,we.createChromakey=kL,we.createSlowMo=cS,we.easings=Eu,we.fastConcatMP4=jk,we.fixFMP4Duration=Uq,we.fontManager=Y4,we.getAllEffects=e1,we.getAllTransitions=Ko,we.getEasing=J0,we.getEffectOptions=Jk,we.getPresetTemplate=X,we.getTransitionOptions=G4,we.jsonToClip=qo,we.makeEffect=p1,we.makeTransition=x1,we.mixinMP4AndAudio=Gq,we.registerCustomEffect=TQ,we.registerCustomTransition=bte,we.renderTxt2ImgBitmap=zL,we.unregisterCustomEffect=CQ,we.unregisterCustomTransition=_te,Object.defineProperty(we,Symbol.toStringTag,{value:"Module"})}));
14417
+ `,yte={radialSwipe:{label:"Radial Swipe",fragment:Cee}},Fh={};function bte(r,e){Fh[r]=e}function _te(r){delete Fh[r]}function Ko(){return{...jo.reduce((r,e)=>(r[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:""},r),{}),...yte,...Fh}}Ko();function G4(){const r=Object.keys(Fh);return Object.entries(Ko()).map(([e,t])=>({key:e,label:t.label,isCustom:r.includes(e),previewStatic:t.previewStatic||`https://cdn.subgen.co/previews/static/transition_${e}_static.webp`,previewDynamic:t.previewDynamic||`https://cdn.subgen.co/previews/dynamic/transition_${e}_dynamic.webp`}))}const wte=G4();function x1({name:r,renderer:e}){let t=jo.find(z=>z.name===r);if(!t){const z=Ko(),ne=Object.keys(z).find(oe=>oe.toLowerCase()===r.toLowerCase());ne&&(t=z[ne])}if(t||(t=jo.find(z=>z.name.toLowerCase()===r.toLowerCase())),!t){const z=[r,r.toLowerCase(),r.charAt(0).toUpperCase()+r.slice(1).toLowerCase(),r.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),r.replace(/_/g,"")],ne=Ko();for(const oe of z){if(t=jo.find(be=>be.name.toLowerCase()===oe.toLowerCase()),t)break;const te=Object.keys(ne).find(be=>be.toLowerCase()===oe.toLowerCase());if(te){t=ne[te];break}}}if(!t){const z=jo.length,ne=jo.slice(0,5).map(be=>be.name).join(", "),oe=Ko(),te=Object.keys(oe).slice(0,3).join(", ");throw console.error(`Transition not found: "${r}". Available in gl-transitions (${z} total):`,ne+"..."),console.error("Available locally:",te+"..."),new Error(`Transition "${r}" not found in gl-transitions library or local definitions`)}const i=new $e(Q.WHITE),n=Ot.create({width:e.width,height:e.height}),s=new Zr({}),o=new Zr({}),a=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",l=a?new Zr({}):void 0;let u=null;if(a){u=document.createElement("canvas"),u.width=256,u.height=256;const z=u.getContext("2d");if(z){const ne=z.createImageData(256,256);for(let oe=0;oe<ne.data.length;oe+=4){const te=Math.random();ne.data[oe]=te*255,ne.data[oe+1]=te*255,ne.data[oe+2]=te*255,ne.data[oe+3]=255}z.putImageData(ne,0,0)}}let c=t.glsl||t.fragment;if(!c)throw new Error(`Transition "${r}" has no glsl or fragment code`);let h={...ot.basics,...ot.custom(t)};Object.entries(h).forEach(([,z])=>{z.type==="int<f32>"&&(z.type="i32",typeof z.value=="number"&&(z.value=Math.trunc(z.value))),z.type==="ivec2<f32>"&&(z.type="vec2<f32>")});const d=t.name==="GridFlip"||r.toLowerCase()==="gridflip"||t.label==="gridflip",f=t.name==="circle"||r.toLowerCase()==="circle"||t.label==="circle",p=t.name==="directional"||r.toLowerCase()==="directional"||t.label==="directional",m=t.name==="UndulatingBurnOut"||r.toLowerCase()==="undulatingburnout"||t.label==="undulatingBurnOut",g=t.name==="SquaresWire"||r.toLowerCase()==="squareswire"||t.label==="squaresWire",v=t.name==="rotate_scale_fade"||r.toLowerCase()==="rotatescalefade"||t.label==="rotateScaleFade",x=t.name==="RandomSquares"||r.toLowerCase()==="randomsquares"||t.label==="randomSquares",y=t.name==="polar_function"||r.toLowerCase()==="polar_function"||t.label==="polar_function",b=t.name==="pixelate"||r.toLowerCase()==="pixelate"||t.label==="pixelate",T=t.name==="perlin"||r.toLowerCase()==="perlin"||t.label==="perlin",E=t.name==="luma"||r.toLowerCase()==="luma"||t.label==="luma",C=t.name==="luminance_melt"||r.toLowerCase()==="luminance_melt"||r.toLowerCase()==="luminancemelt"||t.label==="luminance_melt",P=t.name==="hexagonalize"||r.toLowerCase()==="hexagonalize"||t.label==="hexagonalize",_=t.name==="heart"||r.toLowerCase()==="heart"||t.label==="heart",S=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",I=t.name==="directionalwipe"||r.toLowerCase()==="directionalwipe"||r.toLowerCase()==="directional_wipe"||t.label==="directionalwipe",M=t.name==="directionalwarp"||r.toLowerCase()==="directionalwarp"||r.toLowerCase()==="directional_warp"||t.label==="directionalwarp",O=t.name==="crosshatch"||r.toLowerCase()==="crosshatch"||t.label==="crosshatch",H=t.name==="circleopen"||r.toLowerCase()==="circleopen"||r.toLowerCase()==="circle_open"||t.label==="circleopen",K=t.name==="cannabisleaf"||r.toLowerCase()==="cannabisleaf"||r.toLowerCase()==="cannabis_leaf"||t.label==="cannabisleaf",D=t.name==="StereoViewer"||r.toLowerCase()==="stereoviewer"||r.toLowerCase()==="stereo_viewer"||t.label==="StereoViewer",k=t.name==="GlitchDisplace"||r.toLowerCase()==="glitchDisplace"||t.label==="GlitchDisplace",W=t.name==="CrossZoom"||r.toLowerCase()==="crosszoom"||t.label==="CrossZoom",G=t.name==="CrazyParametricFun"||r.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",J=t.name==="BowTieHorizontal"||r.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",q=t.name==="PolkaDotsCurtain"||r.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",_e=t.name==="Pixelize"||r.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(c=Aee,h={...ot.basics,...Eee}),f&&(c=Pee,h={...ot.basics,...N4}),p&&(c=Iee,h={...ot.basics,...Bee}),m&&(c=kee,h={...ot.basics,...Ree}),g&&(c=Fee,h={...ot.basics,...Mee}),v&&(c=Dee,h={...ot.basics,...Oee}),x&&(c=Uee,h={...ot.basics,...zee}),y&&(c=Lee,h={...ot.basics,...Nee}),b&&(c=Kk,h={...ot.basics,...Qk}),T&&(c=Wee,h={...ot.basics,...Vee}),E&&(c=Xee,h={...ot.basics,...Yee}),C&&(c=qee,h={...ot.basics,...jee}),P&&(c=Kee,h={...ot.basics,...Qee}),_&&(c=Zee,h={...ot.basics,...Jee}),S&&(c=$ee,h={...ot.basics,...ete}),I&&(c=tte,h={...ot.basics,...rte}),M&&(c=ite,h={...ot.basics,...nte}),O&&(c=ste,h={...ot.basics,...ote}),H&&(c=ate,h={...ot.basics,...N4}),K&&(c=lte,h={...ot.basics,...ute}),D&&(c=cte,h={...ot.basics,...hte}),k&&(c=dte),W&&(c=fte,h={...ot.basics,...pte}),G&&(c=mte,h={...ot.basics,...gte}),J&&(c=vte),q&&(c=xte),_e&&(c=Gee,h={...ot.basics,...Hee});const Re={from:s,to:o,uniforms:h};a&&l&&(Re.displacementMap=l,u&&(l.resource=u,l.update()));const ge=new fe({glProgram:new le({vertex:wee,fragment:Tee(c)}),resources:Re});return i.filters=[ge],{render({width:z,height:ne,from:oe,to:te,progress:be}){if((i.width!==z||i.height!==ne)&&(i.setSize({width:z,height:ne}),n.resize(z,ne)),oe instanceof Q?ge.resources.from=oe.source:(s.resource=oe,s.update(),ge.resources.from=s),te instanceof Q?ge.resources.to=te.source:(o.resource=te,o.update(),ge.resources.to=o),a&&l&&u){if(u.width!==z||u.height!==ne){u.width=z,u.height=ne;const Ue=u.getContext("2d");if(Ue){const Ge=Ue.createImageData(z,ne);for(let ke=0;ke<Ge.data.length;ke+=4){const Ve=Math.random();Ge.data[ke]=Ve*255,Ge.data[ke+1]=Ve*255,Ge.data[ke+2]=Ve*255,Ge.data[ke+3]=255}Ue.putImageData(Ge,0,0)}}l.resource=u,l.update()}return ge.resources.uniforms.uniforms.progress=be,e.render({container:i,target:n,clear:!0,width:z,height:ne}),n},destroy(){n.destroy(),i.destroy({children:!0})}}}let Ste=0;async function H4(r){r()>50&&(await Au(15),await H4(r))}class Tte extends Z0{static async isSupported(e={}){return(self.OffscreenCanvas!=null&&self.VideoEncoder!=null&&self.VideoDecoder!=null&&self.VideoFrame!=null&&self.AudioEncoder!=null&&self.AudioDecoder!=null&&self.AudioData!=null&&((await self.VideoEncoder.isConfigSupported({codec:e.videoCodec??"avc1.42E032",width:e.width??1920,height:e.height??1080,bitrate:e.bitrate??7e6})).supported??!1)&&(await self.AudioEncoder.isConfigSupported({codec:(await zk()).codec,sampleRate:st.sampleRate,numberOfChannels:st.channelCount})).supported)??!1}logger=Ee.create(`id:${Ste++},`);destroyed=!1;sprites=[];canvas;pixiApp=null;stopOutput=null;opts;hasVideoTrack;constructor(e={}){super(),console.log("Compositor constructor",e);const{width:t=0,height:i=0}=e;this.canvas=new OffscreenCanvas(t,i),this.opts=Object.assign({bgColor:"#000",width:0,height:0,format:"mp4",videoCodec:"avc1.42E032",audio:!0,audioCodec:"aac",audioSampleRate:48e3,bitrate:5e6,fps:30,metaDataTags:null},e),console.log("Compositor opts",this.opts),this.hasVideoTrack=t*i>0,zk().catch(n=>{this.logger.warn("Failed to detect audio codec:",n)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new bc,await this.pixiApp.init({canvas:this.canvas,width:e,height:t,backgroundColor:0,antialias:!1,autoDensity:!1,resolution:1,preference:"webgl"}),this.pixiApp.renderer==null||this.pixiApp.stage==null)throw new Error("Pixi.js Application failed to initialize properly");try{const i=this.pixiApp;i.ticker&&typeof i.ticker.stop=="function"&&i.ticker.stop()}catch{}}async addSprite(e,t={}){const i={rect:{x:e.left,y:e.top,w:e.width,h:e.height},display:{...e.display},duration:e.duration,playbackRate:e.playbackRate,zIndex:e.zIndex};this.logger.info("Compositor add clip",i);const n=await e.clone();this.pixiApp!=null&&this.pixiApp.renderer!=null&&typeof n.setRenderer=="function"&&n.setRenderer(this.pixiApp.renderer),this.logger.info("Compositor add clip ready"),this.sprites.push(Object.assign(n,{main:t.main??!1,expired:!1})),this.sprites.sort((s,o)=>s.zIndex-o.zIndex)}initMuxer(e){const{fps:t,width:i,height:n,videoCodec:s,bitrate:o,audio:a,metaDataTags:l,format:u,audioCodec:c,audioSampleRate:h}=this.opts,d=this.sprites.some(m=>m.width>0&&m.height>0),f=this.hasVideoTrack&&d;return VO({format:u||"mp4",video:f?{width:i,height:n,expectFPS:t,codec:s,bitrate:o,__unsafe_hardwareAcceleration__:this.opts.__unsafe_hardwareAcceleration__}:null,audio:a===!1?null:{codec:c||st.codecType,sampleRate:h||st.sampleRate,channelCount:st.channelCount},duration:e,metaDataTags:l})}output(e={}){if(console.log("Compositor output",e),this.sprites.length===0)throw Error("No sprite added");const t=this.sprites.find(u=>u.main),n=this.sprites.map(u=>u.display.from+u.duration).filter(u=>u!==1/0),s=e.maxTime??(t!=null?t.display.from+t.duration:n.length>0?Math.max(...n):0);if(s===1/0||s<=0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of Image, Audio");s===-1&&this.logger.warn("Unable to determine the end time, process value don't update"),this.logger.info(`start combinate video, maxTime:${s}`);const o=this.initMuxer(s);let a=performance.now();const l=this.runEncoding(o,s,{onProgress:u=>{this.logger.debug("OutputProgress:",u),this.emit("OutputProgress",u)},onEnded:async()=>{await o.flush(),this.logger.info("===== output ended =====, cost:",performance.now()-a),this.emit("OutputProgress",1),this.destroy()},onError:u=>{this.emit("error",u),o.close(),this.destroy()}});return this.stopOutput=()=>{l(),o.close()},o.stream}destroy(){if(!this.destroyed&&(this.destroyed=!0,this.stopOutput?.(),this.off("OutputProgress"),this.off("error"),this.pixiApp!=null))try{const e=this.pixiApp;if(e.destroyed===!0){this.pixiApp=null;return}if(e.ticker&&typeof e.ticker.stop=="function")try{e.ticker.stop()}catch{}if(e.renderer!=null){const t=e.renderer.gl;if(t&&t.isContextLost()){this.pixiApp=null;return}this.pixiApp.destroy()}}catch(e){console.warn("Error while destroying Pixi application:",e)}finally{this.pixiApp=null}}runEncoding(e,t,{onProgress:i,onEnded:n,onError:s}){let o=0;const a={aborted:!1};let l=null,u=null;const c=async()=>{const{fps:f,bgColor:p,audio:m}=this.opts,g=Math.round(1e6/f),v=this.sprites.some(b=>b.width>0&&b.height>0);u=W4({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=Cte({muxer:e,canvas:this.canvas,outputAudio:m,hasVideoTrack:this.hasVideoTrack&&v,timeSlice:g,fps:f});let y=0;for(;;){if(l!=null)return;if(a.aborted||t!==-1&&y>t||this.sprites.length===0){h(),await n();return}o=y/t;const{audios:b,mainSprDone:T}=await u.render(y);if(T){h(),await n();return}if(a.aborted)return;this.hasVideoTrack&&await Au(0),x(y,b,!0),y+=g,await H4(e.getEncodeQueueSize)}},h=()=>{a.aborted||(a.aborted=!0,clearInterval(d),u?.cleanup(),this.sprites.forEach(f=>{f.destroy()}))};c().catch(f=>{l=f,this.logger.error(f),h(),s(f)});const d=setInterval(()=>{i(o)},500);return h}exportToJSON(){const e=this.sprites.map(i=>Dl(i,i.main)),t=[];return this.sprites.forEach(i=>{if(i.transition){const n=this.sprites.filter(s=>s.id!==i.id&&s.zIndex===i.zIndex&&s.display.from<i.display.from&&(s instanceof wr||s instanceof Fl)).sort((s,o)=>o.display.to-s.display.to)[0];n&&t.push({key:i.transition.name,duration:i.transition.duration,clips:[n.id,i.id]})}}),{clips:e,settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor,format:this.opts.format,videoCodec:this.opts.videoCodec,bitrate:this.opts.bitrate,audio:this.opts.audio,audioCodec:this.opts.audioCodec,audioSampleRate:this.opts.audioSampleRate,metaDataTags:this.opts.metaDataTags}}}async loadFromJSON(e){this.sprites.forEach(t=>{t.destroy()}),this.sprites=[],e.settings&&(e.settings.width!==void 0&&(this.opts.width=e.settings.width),e.settings.height!==void 0&&(this.opts.height=e.settings.height),e.settings.fps!==void 0&&(this.opts.fps=e.settings.fps),e.settings.bgColor!==void 0&&(this.opts.bgColor=e.settings.bgColor),e.settings.format!==void 0&&(this.opts.format=e.settings.format),e.settings.videoCodec!==void 0&&(this.opts.videoCodec=e.settings.videoCodec),e.settings.bitrate!==void 0&&(this.opts.bitrate=e.settings.bitrate),e.settings.audio!==void 0&&(this.opts.audio=e.settings.audio===!1?!1:void 0),e.settings.audioCodec!==void 0&&(this.opts.audioCodec=e.settings.audioCodec),e.settings.audioSampleRate!==void 0&&(this.opts.audioSampleRate=e.settings.audioSampleRate),e.settings.metaDataTags!==void 0&&(this.opts.metaDataTags=e.settings.metaDataTags));for(const t of e.clips){const i=await qo(t);await this.addSprite(i,{main:t.main||!1})}}async renderFrame(e){if(this.destroyed)throw new Error("Compositor has been destroyed.");if(this.pixiApp==null&&await this.initPixiApp(),this.pixiApp==null)throw new Error("Compositor Pixi application could not be initialised. Ensure width and height are greater than 0.");const t=e*1e3,i=W4({pixiApp:this.pixiApp,bgColor:this.opts.bgColor,sprites:this.sprites,aborter:{aborted:!1}});try{await i.render(t)}finally{i.cleanup()}return await this.pixiApp.renderer.extract.base64(this.pixiApp.stage,"image/png",1)}}function W4(r){const{pixiApp:e,sprites:t,aborter:i}=r,n=e!=null,s=new Map,o=new Map,a=new Map,l=Ot.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),u=Ot.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),c=new Je().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),h=new Map,d=async(b,T,E)=>{const C=Math.max(0,Math.min(T-b.display.from,b.duration));b.animate(C*b.playbackRate);const{video:P}=await E(b,C);return P},f=(b,T,E)=>{if(!e)return;const C=b.style||{},{renderTransform:P}=b,_=(P?.mirror??0)>.5,S=T instanceof Q?T:Q.from(T),I=P?.x??0,M=P?.y??0,O=P?.angle??0,H=P?.scale??1,K=P?.scaleX??1,D=P?.scaleY??1,k=P?.opacity??1,W=P?.blur??0,G=P?.brightness??1,J=S.width||1,q=S.height||1,_e=b.type==="Caption",Re=!_e&&b.width&&b.width!==0?Math.abs(b.width)/J:1,ge=!_e&&b.height&&b.height!==0?Math.abs(b.height)/q:1,z=Re*H*K,ne=ge*H*D,oe=new Ie;oe.x=b.center.x+I,oe.y=b.center.y+M,oe.rotation=(b.flip==null?1:-1)*((b.angle+O)*Math.PI)/180,oe.alpha=b.opacity*k;const te=new $e(S);te.anchor.set(.5,.5);let be=[];if(_){const Se=z,Xe=ne,Fe=J*Se,He=q*Xe;te.position.set(0,0),te.scale.set(Se,Xe);const or=[[Fe,0,-Se,Xe],[-Fe,0,-Se,Xe],[0,He,Se,-Xe],[0,-He,Se,-Xe],[Fe,He,-Se,-Xe],[-Fe,He,-Se,-Xe],[Fe,-He,-Se,-Xe],[-Fe,-He,-Se,-Xe]];for(const[At,Ps,Ol,Ul]of or){const tn=new $e(S);tn.anchor.set(.5,.5),tn.position.set(At,Ps),tn.scale.set(Ol,Ul),be.push(tn)}if(b.flip==="horizontal"){te.scale.x=-Se;for(let At=0;At<8;At++)be[At].scale.x=-or[At][2]}else if(b.flip==="vertical"){te.scale.y=-Xe;for(let At=0;At<8;At++)be[At].scale.y=-or[At][3]}oe.addChild(te);for(const At of be)oe.addChild(At)}else b.flip==="horizontal"?(te.scale.x=-z,te.scale.y=ne):b.flip==="vertical"?(te.scale.x=z,te.scale.y=-ne):(te.scale.x=z,te.scale.y=ne),oe.addChild(te);const Ue=[];if(W>0){const Se=new Fn;Se.strength=W,Se.quality=4,Se.repeatEdgePixels=!0,Ue.push(Se)}const Ge=m1(b.colorAdjustment);if(G!==1||Ge){const Se=new Zc;g1(Se,b.colorAdjustment,G),Ue.push(Se)}const ke=Rh(b.colorAdjustment);for(let Se=0;Se<ke.length;Se++){const Xe=ke[Se],Fe=new nt({uTargetColor:{value:[1,1,0],type:"vec3<f32>"},uHueShift:{value:Xe.hue,type:"f32"},uSatShift:{value:Xe.saturation/100,type:"f32"},uLightShift:{value:Xe.lightness/100,type:"f32"},uTolerance:{value:.22,type:"f32"},uSoftness:{value:.12,type:"f32"}}),He=Rl(Xe.targetColor);He&&(Fe.uniforms.uTargetColor[0]=He.r/255,Fe.uniforms.uTargetColor[1]=He.g/255,Fe.uniforms.uTargetColor[2]=He.b/255);const or=new fe({glProgram:new le({vertex:Go,fragment:$b,name:`SelectiveHslShader_${Se}`}),resources:{hslUniforms:Fe}});Ue.push(or)}if(b.chromaKey&&b.chromaKey.enabled){const Se=new nt({uKeyColor:{value:[0,1,0],type:"vec3<f32>"},uSimilarity:{value:.1,type:"f32"},uSpill:{value:0,type:"f32"}}),Xe=Rl(b.chromaKey.color);Xe&&(Se.uniforms.uKeyColor[0]=Xe.r/255,Se.uniforms.uKeyColor[1]=Xe.g/255,Se.uniforms.uKeyColor[2]=Xe.b/255),Se.uniforms.uSimilarity=b.chromaKey.similarity,Se.uniforms.uSpill=b.chromaKey.spill;const Fe=new fe({glProgram:new le({vertex:Go,fragment:Zk,name:"ChromaKeyShader"}),resources:{chromaUniforms:Se}});Ue.push(Fe)}oe.filters=Ue;const Ve=C.borderRadius||0;let Me=null;Ve>0&&(Me=new Je,Me.roundRect(-J/2,-q/2,J,q,Math.min(Ve,J/2,q/2)),Me.fill({color:16777215,alpha:1}),te.addChild(Me),te.mask=Me);const Ct=C.stroke;let et=null;if(Ct&&Ct.width>0){et=new Je;const Se=xt(Ct.color)??16777215;if(et.setStrokeStyle({width:Ct.width,color:Se,alignment:1}),Ve>0){const Xe=Math.min(Ve,J/2,q/2);et.roundRect(-J/2,-q/2,J,q,Xe)}else et.rect(-J/2,-q/2,J,q);et.stroke(),te.addChild(et)}const sr=C.dropShadow;let Sr=null;if(sr&&(sr.blur>0||sr.distance>0)){Sr=new Je;const Se=xt(sr.color)??0,Xe=sr.alpha??.5,Fe=sr.distance??0,He=sr.angle??0,or=Math.cos(He)*Fe,At=Math.sin(He)*Fe;if(Ve>0){const Ps=Math.min(Ve,J/2,q/2);Sr.roundRect(-J/2+or,-q/2+At,J,q,Ps)}else Sr.rect(-J/2+or,-q/2+At,J,q);Sr.fill({color:Se,alpha:Xe}),oe.addChildAt(Sr,0)}e.renderer.render({container:oe,target:E,clear:!0}),T instanceof Q||te.texture.destroy(!0),et&&et.destroy(),Me&&Me.destroy(),Sr&&Sr.destroy();for(const Se of be)Se.destroy();te.destroy(),oe.destroy()};let p=null,m=null,g=null;n&&e!=null&&(p=new Ie,m=new Ie,g=new Ie,m.sortableChildren=!0,g.sortableChildren=!0,e.stage.addChild(m),e.stage.addChild(g),p.visible=!1,e.stage.addChild(p));const v=[...t].sort((b,T)=>b.zIndex-T.zIndex);return{render:async b=>{const T=[];let E=!1,C=!1;const P=new Map,_=async(S,I)=>{if(P.has(S))return P.get(S);const M=await S.getFrame(I);return P.set(S,M),M};for(const S of a.values())S.visible=!1;for(const S of v){if(i.aborted)break;if(b<S.display.from||S.expired){if(n&&e!=null){const D=s.get(S);D&&await D.updateFrame(null)}continue}const I=b-S.display.from,M=I*S.playbackRate;S.animate(M);const{video:O,audio:H,done:K}=await _(S,I);if(T.push(H),n&&e!=null&&m!=null){if(S instanceof Fi){const k=t.find(G=>G.id===S.fromClipId),W=t.find(G=>G.id===S.toClipId);if(k&&W){const G=b-S.display.from;if(G>=S.duration){S.expired=!0;const J=a.get(S.id);J&&(J.visible=!1)}else{const J=await d(k,b,_),q=await d(W,b,_);if(J&&q){const _e=Math.min(Math.max(G/S.duration,0),1);f(k,J,l),f(W,q,u);let Re=o.get(S.id);Re||(Re=x1({name:S.transitionEffect.key,renderer:e.renderer}),o.set(S.id,Re));const ge=Re.render({width:e.renderer.width,height:e.renderer.height,from:l,to:u,progress:_e});let z=a.get(S.id);z||(z=new $e,z.label=`TransitionSprite_${S.id}`,a.set(S.id,z),m.addChild(z)),z.texture=ge,z.visible=!0,z.x=0,z.y=0,z.width=e.renderer.width,z.height=e.renderer.height,z.anchor.set(0,0),z.zIndex=S.zIndex,C=!0;const ne=s.get(k);if(ne){const te=ne.getRoot();te&&(te.visible=!1)}const oe=s.get(W);if(oe){const te=oe.getRoot();te&&(te.visible=!1)}continue}}}}let D=s.get(S);if(D==null&&O!=null&&(D=new z4(e,S,m),s.set(S,D)),D!=null){const k=D.getRoot();O!=null?(C=!0,k&&(k.visible=!0),await D.updateFrame(O)):(k&&(k.visible=!1),await D.updateFrame(null)),D.updateTransforms()}}if(S.duration>0&&I>S.duration||K){if(S.main&&(E=!0),S.expired=!0,n){const D=s.get(S);if(D!=null){const k=D.getRoot();k&&(k.visible=!1)}}}else if(n){const D=s.get(S);D?.updateTransforms()}}if(n&&e!=null&&p!=null&&m!=null&&g!=null){const S=[];for(const I of t)if(I instanceof Ji&&b>=I.display.from&&b<I.display.from+I.duration&&S.push({id:I.id,key:I.effect.key,startTime:I.display.from,duration:I.duration,zIndex:I.zIndex,values:I.effect.values}),I.effects&&I.effects.length>0)for(const M of I.effects)b>=M.startTime&&b<M.startTime+M.duration&&S.push({...M,zIndex:I.zIndex});S.sort((I,M)=>I.zIndex-M.zIndex),g.removeChildren();for(const I of s.values()){const M=I.getRoot();M&&M.parent!==m&&(M.parent&&M.parent.removeChild(M),m.addChild(M))}if(S.length>0){const I=e.renderer.width,M=e.renderer.height;let O=null;const H=new Set,K=[];for(const D of S){const{key:k,startTime:W,duration:G,id:J,zIndex:q}=D,_e=b-W,Re=G>0?Math.min(Math.max(_e/G,0),1):0,ge=t.some(z=>z.id===J&&z instanceof Ji);if(p.removeChildren(),O){const z=new $e(O);z.width=I,z.height=M,p.addChild(z)}for(const z of t){if(H.has(z.id))continue;let ne=!1;if(ge?ne=z.id!==J&&z.zIndex<q:ne=!!z.effects&&z.effects.some(oe=>oe.id===J),ne){const oe=s.get(z);if(oe){const be=oe.getRoot();be&&(be.parent&&be.parent.removeChild(be),p.addChild(be),H.add(z.id))}const te=a.get(z.id);te&&(te.parent&&te.parent.removeChild(te),p.addChild(te),H.add(z.id))}}if(p.children.length>0){let z=h.get(J);if(!z)try{const ne=await p1({name:k,renderer:e.renderer,values:D.values});ne&&ne.filter&&(z={filter:ne.filter,render:ne.render},h.set(J,z))}catch(ne){console.warn("Failed to create effect",k,ne)}if(z){const{filter:ne,render:oe}=z;ne.resources&&ne.resources.effectUniforms&&(ne.resources.effectUniforms.uniforms.uTime=Re);const te=Ot.create({width:I,height:M});K.push(te),p.visible=!0,e.renderer.render({container:p,target:te,clear:!0}),p.visible=!1,oe&&(O=oe({canvasTexture:te,progress:Re,width:I,height:M}))}}}if(O){const D=new $e(O);D.width=I,D.height=M,g.addChild(D)}for(const D of K)D.destroy(!0)}}return n&&e!=null&&e.render(),{audios:T,mainSprDone:E,hasVideo:C}},cleanup:()=>{l&&l.destroy(!0),u&&u.destroy(!0),c&&c.destroy(!0);for(const b of a.values())b.destroy();a.clear(),o.clear(),p&&p.destroy({children:!0}),m&&m.destroy({children:!0}),g&&g.destroy({children:!0}),s.forEach(b=>{b.destroy()}),s.clear()}}}function Cte(r){const{canvas:e,outputAudio:t,muxer:i,hasVideoTrack:n,timeSlice:s}=r;let o=0;const a=Math.floor(3*r.fps),l=Ate(1024);return(u,c,h)=>{if(t!==!1)for(const d of l(u,c))i.encodeAudio(d);if(n&&h)try{const d=new VideoFrame(e,{duration:s,timestamp:u});i.encodeVideo(d,{keyFrame:o%a===0}),o+=1}catch(d){console.warn("Failed to create VideoFrame from canvas, skipping frame:",d)}}}function Ate(r){const e=r*st.channelCount,t=new Float32Array(e*3);let i=0,n=0;const s=r/st.sampleRate*1e6,o=new Float32Array(e),a=l=>{let u=0;const c=Math.floor(i/e),h=[];for(let d=0;d<c;d++)h.push(new AudioData({timestamp:n,numberOfChannels:st.channelCount,numberOfFrames:r,sampleRate:st.sampleRate,format:"f32",data:t.subarray(u,u+e)})),u+=e,n+=s;for(t.set(t.subarray(u,i),0),i-=u;l-n>s;)h.push(new AudioData({timestamp:n,numberOfChannels:st.channelCount,numberOfFrames:r,sampleRate:st.sampleRate,format:"f32",data:o})),n+=s;return h};return(l,u)=>{const c=Math.max(...u.map(h=>h[0]?.length??0));for(let h=0;h<c;h++){let d=0,f=0;for(let p=0;p<u.length;p++){const m=u[p][0]?.[h]??0,g=u[p][1]?.[h]??m;d+=m,f+=g}t[i]=d,t[i+1]=f,i+=2}return a(l)}}class Ete extends Je{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(e,t=1){const n=1.5*t;this.clear(),this.setStrokeStyle({width:n,color:165063}).rect(e.x,e.y,e.width,e.height).stroke(),this.hitArea=e}}class en extends Je{#e=!1;handle;cursor;callbacks;constructor(e,t,i){super(),this.handle=e,this.cursor=t,this.callbacks=i,this.eventMode="static",this.#a(),this.on("pointerdown",this.#r),this.on("globalpointermove",this.#n),this.on("pointerup",this.#l),this.on("pointerupoutside",this.#l)}#a(){this.clear();const e=165063;if(this.handle==="rot")this.circle(0,0,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-4),this.arc(0,0,4,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new al(0,0,24);else if(["ml","mr","mt","mb"].includes(this.handle)){const t=this.handle==="ml"||this.handle==="mr",i=t?6:24,n=t?24:6;this.roundRect(-i/2,-n/2,i,n,3),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new he(-15,-15,30,30)}else this.rect(-4,-4,8,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new he(-15,-15,30,30)}#r=e=>{this.#e=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,e.global)};#n=e=>{this.#e&&this.callbacks.updateDrag(this.handle,e.global)};#l=e=>{this.#e&&(this.#e=!1,this.cursor="pointer",this.callbacks.endDrag())}}class Mh{constructor(e,t,i=1){this.artboardWidth=e,this.artboardHeight=t,this.scale=i}static SNAP_THRESHOLD=5;updateContext(e,t,i){this.artboardWidth=e,this.artboardHeight=t,this.scale=i}snapMove(e){const t=[];let i=0,n=0;const s=Mh.SNAP_THRESHOLD/this.scale,o=[{value:this.artboardWidth/2,label:"center"},{value:0,label:"start"},{value:this.artboardWidth,label:"end"}],a=[{value:e.x,type:"start"},{value:e.x+e.width/2,type:"center"},{value:e.x+e.width,type:"end"}];let l=!1;for(const d of o){if(l)break;for(const f of a){const p=d.value-f.value;if(Math.abs(p)<s){i=p,l=!0,t.push({type:"vertical",position:d.value,start:Math.min(0,e.y),end:Math.max(this.artboardHeight,e.y+e.height)});break}}}const u=[{value:this.artboardHeight/2,label:"center"},{value:0,label:"start"},{value:this.artboardHeight,label:"end"}],c=[{value:e.y,type:"start"},{value:e.y+e.height/2,type:"center"},{value:e.y+e.height,type:"end"}];let h=!1;for(const d of u){if(h)break;for(const f of c){const p=d.value-f.value;if(Math.abs(p)<s){n=p,h=!0,t.push({type:"horizontal",position:d.value,start:Math.min(0,e.x),end:Math.max(this.artboardWidth,e.x+e.width)});break}}}return{dx:i,dy:n,guides:t}}snapResize(e){const t=e.clone(),{dx:i,dy:n,guides:s}=this.snapMove(t);return t.x+=i,t.y+=n,{corrected:t,guides:s}}snapPoint(e){const t=Mh.SNAP_THRESHOLD/this.scale,i=[],n=e.clone(),s=[0,this.artboardWidth/2,this.artboardWidth];for(const a of s)if(Math.abs(a-e.x)<t){n.x=a,i.push({type:"vertical",position:a,start:0,end:this.artboardHeight});break}const o=[0,this.artboardHeight/2,this.artboardHeight];for(const a of o)if(Math.abs(a-e.y)<t){n.y=a,i.push({type:"horizontal",position:a,start:0,end:this.artboardWidth});break}return{p:n,guides:i}}}const V4={delta:new ae};class X4 extends Ie{group;wireframe=new Ete;selectionOutlines=new Je;isDragging=!1;lastPointer=new ve;activeHandle=null;#e;#a=new Map;#r=new ve;#n=0;#l=0;#s=new he;#i=new ve;#o=new he;#t=[new ve,new ve,new ve,new ve];#u=1;#c=1;#h;#d=new Je;#m=new ve;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static",this.#h=new Mh(e.artboardWidth??1920,e.artboardHeight??1080),this.addChild(this.#d);const t={beginDrag:(i,n)=>this.#A(i,n),updateDrag:(i,n)=>this.#E(i,n),endDrag:()=>this.#v()};this.#e={tl:new en("tl","nwse-resize",t),tr:new en("tr","nesw-resize",t),bl:new en("bl","nesw-resize",t),br:new en("br","nwse-resize",t),ml:new en("ml","ew-resize",t),mr:new en("mr","ew-resize",t),mt:new en("mt","ns-resize",t),mb:new en("mb","ns-resize",t),rot:new en("rot","crosshair",{beginDrag:(i,n)=>this.#B(n),updateDrag:(i,n)=>this.#k(n),endDrag:()=>this.#v()})},this.addChild(this.selectionOutlines,this.wireframe,...Object.values(this.#e)),this.#w(),this.visible=!1,Ft.shared.addOnce(()=>{this.showImmediate()})}#x=!1;showImmediate(){this.#x||this.destroyed||!this.parent||(this.#f(),this.visible=!0,this.#x=!0)}#w(){this.on("pointerdown",this.#S),this.on("pointerup",this.#y),this.on("pointerupoutside",this.#y),this.on("globalpointermove",this.#T)}#f(){if(this.group.length===1){const e=this.group[0];this.#n=e.rotation;const t=this.#g(e);let i,n;this.opts.clip?(i=this.opts.clip.width,n=this.opts.clip.height):(i=t.width,n=t.height);const s=e.toGlobal(new ve(0,0));this.#r.set(s.x,s.y),this.#o.copyFrom(new he(-i/2,-n/2,i,n))}else{let e=1/0,t=1/0,i=-1/0,n=-1/0;if(this.parent)for(const u of this.group){const c=this.#g(u);this.#t[0].set(c.x,c.y),this.#t[1].set(c.x+c.width,c.y),this.#t[2].set(c.x+c.width,c.y+c.height),this.#t[3].set(c.x,c.y+c.height);for(const h of this.#t)u.toGlobal(h,h),this.toLocal(h,void 0,h),e=Math.min(e,h.x),t=Math.min(t,h.y),i=Math.max(i,h.x),n=Math.max(n,h.y)}const s=i-e,o=n-t,a=e+s/2,l=t+o/2;if(this.#o.copyFrom(new he(-s/2,-o/2,s,o)),this.parent){const u=this.toGlobal(new ve(a,l));this.#r.set(u.x,u.y)}}this.#p()}#g(e){let t=null;const i=u=>{if(u.label==="MainSprite"&&u instanceof $e)return u;for(const c of u.children)if(c instanceof Ie){const h=i(c);if(h)return h}return null};if(t=i(e),t){const u=t.getLocalBounds(),c=t.localTransform.clone(),h=c.apply(new ve(u.x,u.y)),d=c.apply(new ve(u.x+u.width,u.y)),f=c.apply(new ve(u.x+u.width,u.y+u.height)),p=c.apply(new ve(u.x,u.y+u.height)),m=Math.min(h.x,d.x,f.x,p.x),g=Math.max(h.x,d.x,f.x,p.x),v=Math.min(h.y,d.y,f.y,p.y),x=Math.max(h.y,d.y,f.y,p.y);return new he(m,v,g-m,x-v)}let n=1/0,s=1/0,o=-1/0,a=-1/0;const l=e.children.filter(u=>u.label!=="ShadowContainer"&&u.label!=="AnimationContainer");if(l.length===0&&e.children.length>0){const u=e.children.find(c=>c.label==="AnimationContainer");if(u){const c=u.getLocalBounds();return new he(c.minX,c.minY,c.maxX-c.minX,c.maxY-c.minY)}}for(const u of l){const c=u.getBounds(),h=e.toLocal(new ve(c.minX,c.minY)),d=e.toLocal(new ve(c.maxX,c.maxY));n=Math.min(n,h.x,d.x),s=Math.min(s,h.y,d.y),o=Math.max(o,h.x,d.x),a=Math.max(a,h.y,d.y)}if(n===1/0){const u=e.getLocalBounds();return new he(u.minX,u.minY,u.maxX-u.minX,u.maxY-u.minY)}return new he(n,s,o-n,a-s)}updateBounds(){this.#f()}#S=e=>{e.button===0&&(this.opts.locked||(this.#f(),this.#m.copyFrom(this.#r),this.isDragging=!0,this.lastPointer.copyFrom(e.global),this.cursor="grabbing"))};#y=()=>{this.isDragging&&this.#v(),this.cursor="default"};#T=e=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const{moveDx:t,moveDy:i,newPivotWorld:n}=this.#C(e);for(const s of this.group)s.x+=t,s.y+=i;this.#r.copyFrom(n),this.lastPointer.copyFrom(e.global),this.#p(),this.emit("transforming")};#C(e){const t=Math.abs(this.parent.worldTransform.a);this.#h.updateContext(this.opts.artboardWidth??1920,this.opts.artboardHeight??1080,t);const i=e.global.x-this.lastPointer.x,n=e.global.y-this.lastPointer.y;this.#m.x+=i,this.#m.y+=n;const s=this.parent.toLocal(this.#m),o=new he(s.x+this.#o.x,s.y+this.#o.y,this.#o.width,this.#o.height),{dx:a,dy:l,guides:u}=this.#h.snapMove(o);this.#b(u,t);const c=s.x+a,h=s.y+l,d=this.parent.toLocal(this.#r),f=c-d.x,p=h-d.y,m=this.parent.toGlobal(new ve(c,h));return{moveDx:f,moveDy:p,newPivotWorld:m}}#A(e,t){this.#f(),this.isDragging=!0,this.activeHandle=e,this.#a.clear();for(const i of this.group)this.#a.set(i,i.localTransform.clone());this.rotation=this.#n,this.#s.copyFrom(this.#o),this.#F(e)}#E(e,t){this.#P(e,t)}async#P(e,t){const{proposed:i,sx:n,sy:s,pivotWorld:o}=await this.#I(e,t),a=this.opts.clip&&this.opts.clip.type==="Text",l=this.opts.clip&&this.opts.clip.type==="Caption";a||l?this.emit("textClipResize",{handle:e,newWidth:i.width,newHeight:i.height,pivotWorld:o,proposed:i,sx:n,sy:s}):this.#_(this.#D(o,this.#n,n,s)),this.#o.copyFrom(i),this.#p(),this.emit("transforming")}async#I(e,t){const i=this.#i,n=this.#M(e,this.toLocal(t),i),s=this.parent?Math.abs(this.parent.worldTransform.a):1;this.#h.updateContext(this.opts.artboardWidth??1920,this.opts.artboardHeight??1080,s);const{dx:o,dy:a,guides:l}=this.#h.snapMove(n);n.x+=o,n.y+=a,this.#b(l,s);const u=n.width/this.#s.width,c=n.height/this.#s.height,h=this.toGlobal(i);return{proposed:n,sx:u,sy:c,pivotWorld:h}}#B(e){this.#f(),this.isDragging=!0,this.activeHandle="rot",this.#a.clear();for(const t of this.group)this.#a.set(t,t.localTransform.clone());this.#l=Math.atan2(e.y-this.#r.y,e.x-this.#r.x)}#k(e){const i=Math.atan2(e.y-this.#r.y,e.x-this.#r.x)-this.#l,n=this.#n+i;this.#_(this.#O(this.#r,i)),this.rotation=n,this.#p(n),this.emit("transforming")}#v(){this.isDragging=!1,this.#n=this.rotation,this.activeHandle=null,this.#d.clear(),this.#p(this.#n),this.emit("transformEnd")}#b(e,t){if(this.#d.clear(),!(!e.length||!this.parent)){this.#d.stroke({width:1/t,color:4774907});for(const i of e){let n,s;i.type==="vertical"?(n=new ve(i.position,i.start),s=new ve(i.position,i.end)):(n=new ve(i.start,i.position),s=new ve(i.end,i.position)),this.toLocal(n,this.parent,n),this.toLocal(s,this.parent,s),this.#d.moveTo(n.x,n.y).lineTo(s.x,s.y).stroke({width:1/t,color:4774907})}}}#p(e=this.#n){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#r)),this.rotation=e;const i=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),n=this.#o;this.wireframe.draw(n,i);const s=n.x+n.width/2,o=n.y+n.height/2,l=this.opts.locked?[]:this.opts.clip?.getVisibleHandles?.()??["tl","tr","bl","br","ml","mr","mt","mb","rot"],u=[this.#e.tl,this.#e.tr,this.#e.bl,this.#e.br,this.#e.ml,this.#e.mr,this.#e.mt,this.#e.mb,this.#e.rot];for(const c of u)c.scale.set(i);this.#e.tl.visible=l.includes("tl"),this.#e.tr.visible=l.includes("tr"),this.#e.bl.visible=l.includes("bl"),this.#e.br.visible=l.includes("br"),this.#e.ml.visible=l.includes("ml"),this.#e.mr.visible=l.includes("mr"),this.#e.mt.visible=l.includes("mt"),this.#e.mb.visible=l.includes("mb"),this.#e.rot.visible=l.includes("rot"),this.#e.tl.position.set(n.x,n.y),this.#e.tr.position.set(n.x+n.width,n.y),this.#e.bl.position.set(n.x,n.y+n.height),this.#e.br.position.set(n.x+n.width,n.y+n.height),this.#e.ml.position.set(n.x,o),this.#e.mr.position.set(n.x+n.width,o),this.#e.mt.position.set(s,n.y),this.#e.mb.position.set(s,n.y+n.height),this.#e.rot.position.set(s,n.y-30*i),this.#R(i)}#R(e){if(this.selectionOutlines.clear(),this.group.length<=1||!this.parent)return;const t={width:1*e,color:43775,alpha:1};for(const i of this.group){const n=this.#g(i);this.#t[0].set(n.x,n.y),this.#t[1].set(n.x+n.width,n.y),this.#t[2].set(n.x+n.width,n.y+n.height),this.#t[3].set(n.x,n.y+n.height);for(const s of this.#t)i.toGlobal(s,s),this.toLocal(s,void 0,s);this.selectionOutlines.moveTo(this.#t[0].x,this.#t[0].y).lineTo(this.#t[1].x,this.#t[1].y).lineTo(this.#t[2].x,this.#t[2].y).lineTo(this.#t[3].x,this.#t[3].y).closePath().stroke(t)}}#F(e){const t=this.#s;if(this.opts.centeredScaling){this.#i.set(t.x+t.width/2,t.y+t.height/2);return}e==="tl"?this.#i.set(t.x+t.width,t.y+t.height):e==="tr"?this.#i.set(t.x,t.y+t.height):e==="bl"?this.#i.set(t.x+t.width,t.y):e==="br"?this.#i.set(t.x,t.y):e==="ml"?this.#i.set(t.x+t.width,t.y+t.height/2):e==="mr"?this.#i.set(t.x,t.y+t.height/2):e==="mt"?this.#i.set(t.x+t.width/2,t.y+t.height):e==="mb"&&this.#i.set(t.x+t.width/2,t.y)}#M(e,t,i){let n=!1;if(this.opts.clip&&(this.opts.clip.type==="Image"||this.opts.clip.type==="Video")&&(n=!0),this.opts.centeredScaling){let o=Math.abs(t.x-i.x)*2,a=Math.abs(t.y-i.y)*2;if(n){const l=this.#s.width,u=this.#s.height,c=l/u;o/l>a/u?a=o/c:o=a*c}return o=Math.max(this.#u,o),a=Math.max(this.#c,a),new he(i.x-o/2,i.y-a/2,o,a)}if(["tl","tr","bl","br"].includes(e)){let o=Math.abs(t.x-i.x),a=Math.abs(t.y-i.y);if(n){const l=this.#s.width,u=this.#s.height,c=l/u;o/l>a/u?a=o/c:o=a*c}if(o=Math.max(this.#u,o),a=Math.max(this.#c,a),e==="tl")return new he(i.x-o,i.y-a,o,a);if(e==="tr")return new he(i.x,i.y-a,o,a);if(e==="bl")return new he(i.x-o,i.y,o,a);if(e==="br")return new he(i.x,i.y,o,a)}const s=this.#s;if(e==="ml"){const o=Math.min(t.x,i.x-this.#u);return new he(o,s.y,i.x-o,s.height)}if(e==="mr"){const o=Math.max(t.x,i.x+this.#u);return new he(i.x,s.y,o-i.x,s.height)}if(e==="mt"){const o=Math.min(t.y,i.y-this.#c);return new he(s.x,o,s.width,i.y-o)}if(e==="mb"){const o=Math.max(t.y,i.y+this.#c);return new he(s.x,i.y,s.width,o-i.y)}return new he(i.x,i.y,this.#u,this.#c)}#D(e,t,i,n){return V4.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(i,n).rotate(t).translate(e.x,e.y)}#O(e,t){return V4.delta.identity().translate(-e.x,-e.y).rotate(t).translate(e.x,e.y)}#_(e){for(const t of this.group){const i=this.#a.get(t),n=t.parent;if(!i||!n)continue;const s=n.worldTransform.clone().invert(),o=n.worldTransform.clone().append(i),a=e.clone().append(o),l=s.clone().append(a);t.setFromMatrix(l)}}}class Pte{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new ve;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;lastPointerDownTime=0;lastPointerDownClip=null;init(e,t){this.selectionGraphics=new Je,this.selectionGraphics.visible=!1,this.selectionGraphics.zIndex=1e3,t.addChild(this.selectionGraphics),e.stage.eventMode="static",e.stage.hitArea=e.screen,e.stage.on("pointerdown",i=>this.onStagePointerDown(i)),e.stage.on("globalpointermove",i=>this.onStagePointerMove(i)),e.stage.on("pointerup",()=>this.onStagePointerUp()),e.stage.on("pointerupoutside",()=>this.onStagePointerUp())}onStagePointerDown(e){e.target===this.studio.pixiApp?.stage&&(e.shiftKey||this.deselectClip(),this.isDragSelecting=!0,this.studio.artboard?.toLocal(e.global,void 0,this.dragSelectionStart),this.selectionGraphics&&(this.selectionGraphics.clear(),this.selectionGraphics.visible=!0))}onStagePointerMove(e){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const t=this.studio.artboard.toLocal(e.global),i=Math.min(this.dragSelectionStart.x,t.x),n=Math.min(this.dragSelectionStart.y,t.y),s=Math.abs(t.x-this.dragSelectionStart.x),o=Math.abs(t.y-this.dragSelectionStart.y);this.selectionGraphics.clear(),this.selectionGraphics.rect(i,n,s,o).fill({color:703971,alpha:.3}),this.selectionGraphics.rect(i,n,s,o).stroke({width:2,color:703971});const a=this.selectionGraphics.getBounds(),l=new he(a.x,a.y,a.width,a.height);if(l.width>2||l.height>2){const u=this.getIntersectingClips(l);this.updatePreviewSelection(u)}else this.selectedClips.size===0&&this.destroyTransformer();this.studio.pixiApp?.render()}}onStagePointerUp(){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const e=this.selectionGraphics.getBounds(),t=new he(e.x,e.y,e.width,e.height);if(t.width>2||t.height>2){const i=this.getIntersectingClips(t);if(i.length>0){for(const n of i)this.selectedClips.add(n);this.recreateTransformer(),this.studio.emit("selection:created",{selected:Array.from(this.selectedClips)})}else this.selectedClips.size===0&&this.destroyTransformer()}else this.selectedClips.size===0&&this.destroyTransformer();this.selectionGraphics.clear(),this.selectionGraphics.visible=!1,this.isDragSelecting=!1,this.studio.pixiApp?.render()}}getIntersectingClips(e){const t=[];for(const i of this.studio.clips){const n=this.studio.spriteRenderers.get(i);if(!n)continue;const s=n.getRoot();if(!s||!s.visible)continue;const o=s.getBounds();e.x<o.x+o.width&&e.x+e.width>o.x&&e.y<o.y+o.height&&e.y+e.height>o.y&&t.push(i)}return t}updatePreviewSelection(e){if(e.length===0){this.selectedClips.size===0?this.destroyTransformer():this.recreateTransformer();return}const t=new Set(e),i=[];let n=null;for(const s of t){const o=this.studio.spriteRenderers.get(s);if(o==null)continue;const a=o.getRoot();a!=null&&(i.push(a),t.size===1&&(n=s))}if(i.length===0){this.selectedClips.size===0&&this.destroyTransformer();return}this.activeTransformer?(this.activeTransformer.group=i,this.activeTransformer.opts.group=i,this.activeTransformer.opts.clip=n,this.activeTransformer.updateBounds(),this.activeTransformer.showImmediate()):(this.activeTransformer=new X4({group:i,clip:n,artboardWidth:this.studio.opts.width,artboardHeight:this.studio.opts.height}),this.studio.artboard?.addChild(this.activeTransformer),this.activeTransformer.showImmediate()),this.studio.pixiApp?.render()}setupSpriteInteractivity(e){if(this.interactiveClips.has(e))return;const t=this.studio.spriteRenderers.get(e);if(t==null)return;const i=t.getRoot();i!=null&&(i.eventMode="static",i.cursor="pointer",i.on("pointerdown",n=>{const s=Date.now(),o=this.getTopmostClipAtPoint(n.global);o===e&&o===this.lastPointerDownClip&&s-this.lastPointerDownTime<350&&(o.type==="Text"||o.type==="Caption")&&this.studio.emit("clip:dblclick",{clip:o}),this.lastPointerDownTime=s,this.lastPointerDownClip=o,o&&this.selectClip(o,n.shiftKey)}),this.interactiveClips.add(e))}getTopmostClipAtPoint(e){if(!this.studio.pixiApp)return null;let t=null,i=-1/0;for(const n of this.interactiveClips){const s=this.studio.spriteRenderers.get(n);if(!s)continue;const o=s.getRoot();if(!o||!o.visible)continue;const a=o.toLocal(e),l=o.getLocalBounds();a.x>=l.minX&&a.x<=l.maxX&&a.y>=l.minY&&a.y<=l.maxY&&n.zIndex>i&&(i=n.zIndex,t=n)}return t}selectClip(e,t=!1){if(!(this.studio.destroyed||this.studio.pixiApp==null)){if(t||this.deselectClip(),t&&this.selectedClips.has(e)){this.selectedClips.delete(e),this.recreateTransformer(),this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)}),this.studio.pixiApp?.render();return}this.selectedClips.add(e),this.recreateTransformer(),t?this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)}):this.studio.emit("selection:created",{selected:Array.from(this.selectedClips)}),this.studio.pixiApp?.render()}}selectClipsByIds(e){const t=this.studio.clips.filter(i=>e.includes(i.id));this.setSelection(t)}setSelection(e){if(!(this.studio.destroyed||this.studio.pixiApp==null)&&!(this.selectedClips.size===e.length&&e.every(t=>this.selectedClips.has(t)))){for(const t of this.selectedClips)this.syncSpriteToClipProperties(t);this.destroyTransformer(),this.selectedClips.clear();for(const t of e)this.selectedClips.add(t);this.selectedClips.size>0?(this.createTransformer(),this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)})):this.studio.emit("selection:cleared",{deselected:[]}),this.studio.pixiApp?.render()}}deselectClip(){if(this.selectedClips.size>0)for(const t of this.selectedClips)this.syncSpriteToClipProperties(t);this.destroyTransformer();const e=Array.from(this.selectedClips);this.selectedClips.clear(),e.length>0&&this.studio.emit("selection:cleared",{deselected:e}),this.studio.pixiApp?.render()}async move(e,t){if(this.selectedClips.size===0)return;const i=[];for(const n of this.selectedClips)i.push({id:n.id,updates:{left:(n.left??0)+e,top:(n.top??0)+t}});await this.studio.updateClips(i),this.activeTransformer&&this.activeTransformer.updateBounds()}clear(){this.deselectClip(),this.interactiveClips.clear()}recreateTransformer(){this.destroyTransformer(),this.selectedClips.size>0&&this.createTransformer()}destroyTransformer(){this.activeTransformer!=null&&(this.activeTransformer.parent!=null&&this.activeTransformer.parent.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null)}createTransformer(){if(this.studio.destroyed||this.studio.artboard==null||this.selectedClips.size===0)return;const e=[];let t=null;for(const s of this.selectedClips){const o=this.studio.spriteRenderers.get(s);if(o==null)continue;const a=o.getRoot();a!=null&&(e.push(a),this.selectedClips.size===1&&(t=s))}if(e.length===0){console.warn("Cannot create transformer: no sprites found");return}const i=t?.locked??!1;this.activeTransformer=new X4({group:e,clip:t,artboardWidth:this.studio.opts.width,artboardHeight:this.studio.opts.height,locked:i});let n=null;this.activeTransformer.on("transforming",()=>{n===null&&(n=requestAnimationFrame(()=>{n=null,this.syncSelectedClipsTransformsRealtime(),this.studio.pixiApp?.render()}))}),this.activeTransformer.on("textClipResize",s=>{this.textClipResizedWidth=s.newWidth,this.textClipResizeHandle=s.handle,this.textClipResizedSx=s.sx,this.textClipResizedSy=s.sy}),this.activeTransformer.on("transformEnd",async()=>{n!==null&&(cancelAnimationFrame(n),n=null),await this.syncSelectedClipsTransforms();for(const s of this.selectedClips)this.studio.emit("clip:updated",{clip:s});this.studio.emit("transform:end",{transformer:this.activeTransformer})}),this.activeTransformer.on("pointerdown",s=>{if(s.button!==0||(this.studio.emit("transform:start",{transformer:this.activeTransformer}),this.activeTransformer?.activeHandle!==null))return;const o=this.getTopmostClipAtPoint(s.global),a=Date.now();o&&o===this.lastPointerDownClip&&a-this.lastPointerDownTime<350&&(o.type==="Text"||o.type==="Caption")&&this.studio.emit("clip:dblclick",{clip:o}),this.lastPointerDownTime=a,this.lastPointerDownClip=o,o&&!this.selectedClips.has(o)&&(this.selectClip(o,s.shiftKey),s.stopPropagation())}),this.studio.artboard.addChild(this.activeTransformer),this.activeTransformer.showImmediate(),this.studio.pixiApp?.render()}async syncSelectedClipsTransformsRealtime(){if(this.selectedClips.size===0||this.activeTransformer==null)return;const e=this.activeTransformer.activeHandle;if(e===null){for(const t of this.selectedClips){const i=this.studio.spriteRenderers.get(t);if(i==null)continue;const n=i.getRoot(),s=i.getSprite();if(n==null||s==null||s.texture==null)continue;const o=Math.abs(n.scale.x*s.scale.x)*s.texture.width,a=Math.abs(n.scale.y*s.scale.y)*s.texture.height;t.left=n.x-o/2,t.top=n.y-a/2}return}if(e==="mr"||e==="ml"){if(this.isUpdatingTextRealtime)return;this.isUpdatingTextRealtime=!0;try{for(const t of this.selectedClips){if(!(t instanceof Zi))continue;const i=this.studio.spriteRenderers.get(t);if(i==null)continue;const n=i.getRoot(),s=i.getSprite();if(n==null||s==null||s.texture==null)continue;const o=Math.abs(n.scale.x*s.scale.x);if(o===1)continue;const a=t.left,l=t.top,u=t.width,c=s.texture.width,h=o*c;await t.updateStyle({wordWrap:!0,wordWrapWidth:h});const d=await t.getTexture();d&&(await i.updateFrame(d),s.scale.set(1,1),n.scale.set(1,1),e==="ml"?t.left=a+u-t.width:t.left=a,t.top=l,n.x=t.left+t.width/2,n.y=t.top+t.height/2,this.activeTransformer.updateBounds())}}finally{this.isUpdatingTextRealtime=!1}}}async syncSelectedClipsTransforms(){if(!(this.selectedClips.size===0||this.activeTransformer==null)){for(const e of this.selectedClips){const t=this.studio.spriteRenderers.get(e);if(t==null)continue;const i=t.getRoot(),n=t.getSprite();if(i==null||n==null||n.texture==null)continue;const s=n.texture.width,o=n.texture.height,a=Math.abs(i.scale.x*n.scale.x)*s,l=Math.abs(i.scale.y*n.scale.y)*o,u=(e instanceof Zi||e instanceof Nn)&&this.textClipResizedWidth!==null?this.textClipResizedWidth:a,c=e.width,d=(e.style?.fontSize??16)*Math.max(this.textClipResizedSx||1,this.textClipResizedSy||1);let f=i.x;if((e instanceof Zi||e instanceof Nn)&&this.textClipResizedWidth!==null){const m={wordWrap:!0,wordWrapWidth:u};this.textClipResizeHandle==="mr"?(f=e.left+u/2,i.x=f):this.textClipResizeHandle==="ml"?(f=e.left+u/2-(u-c),i.x=f):["br","tr"].includes(this.textClipResizeHandle)?(f=e.left+u/2,m.fontSize=d):["bl","tl"].includes(this.textClipResizeHandle)&&(f=e.left+u/2-(u-c),m.fontSize=d),await e.updateStyle(m);const g=await e.getTexture();g&&(await t.updateFrame(g),e.width=u,e.height=g.height,this.textClipResizedWidth=null,e.left=f-e.width/2,e.top=i.y-e.height/2,n.scale.set(1,1),i.scale.set(1,1))}else{const m=a,g=l;e.left=i.x-m/2,e.top=i.y-g/2,e.width=m,e.height=g;const v=e.flip==null?1:-1;e.angle=v*i.angle}}this.activeTransformer!=null&&this.activeTransformer.updateBounds();for(const e of this.selectedClips){const t=this.studio.spriteRenderers.get(e);t?.updateTransforms()}}}syncSpriteToClipProperties(e){const t=this.studio.spriteRenderers.get(e);if(t!=null){const i=t.getRoot(),n=t.getSprite();if(i!=null&&n!=null&&n.texture!=null){const s=n.texture.width,o=n.texture.height,a=Math.abs(i.scale.x*n.scale.x)*s,l=Math.abs(i.scale.y*n.scale.y)*o,u=a,c=l,h=i.x-u/2,d=i.y-c/2;e.left=h,e.top=d,e.width=u,e.height=c;const f=e.flip==null?1:-1;e.angle=f*i.angle,t.updateTransforms(),this.studio.emit("clip:updated",{clip:e})}}}async deleteSelected(){return this.studio.deleteSelected()}}class Ite{constructor(e){this.studio=e}isPlaying=!1;currentTime=0;maxDuration=0;playStartTime=0;playStartTimestamp=0;rafId=null;playbackElements=new Map;setMaxDuration(e){this.maxDuration=e}async play(){if(!(this.isPlaying||this.studio.destroyed)){if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){console.warn("Cannot play: invalid duration",this.maxDuration);return}this.isPlaying||(this.isPlaying=!0),this.playStartTime=this.currentTime,this.playStartTimestamp=performance.now();for(const[e,{element:t}]of this.playbackElements.entries()){if(!(this.currentTime>=e.display.from&&(e.display.to===0||this.currentTime<=e.display.to))){this.isPlaybackCapable(e)&&e.pause(t);continue}const n=(this.currentTime-e.display.from)/1e6;this.isPlaybackCapable(e)&&await e.play(t,n)}this.renderLoop(),this.studio.emit("play",{isPlaying:!0})}}pause(){this.isPlaying=!1,this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null);for(const[e,{element:t}]of this.playbackElements.entries())this.isPlaybackCapable(e)&&e.pause(t);this.studio.emit("pause",{isPlaying:!1})}async stop(){this.pause(),await this.seek(0)}async seek(e){if(this.studio.destroyed)return;const t=this.isPlaying;this.playStartTime=Math.max(0,Math.min(e,this.maxDuration)),this.playStartTimestamp=performance.now(),this.currentTime=this.playStartTime;for(const[i,{element:n}]of this.playbackElements.entries()){if(!(this.currentTime>=i.display.from&&(i.display.to===0||this.currentTime<=i.display.to))){this.isPlaybackCapable(i)&&i.pause(n);continue}const o=(this.currentTime-i.display.from)/1e6;this.isPlaybackCapable(i)&&await i.seek(n,o)}if(await this.studio.updateFrame(this.currentTime),this.studio.emit("currentTime",{currentTime:this.currentTime}),t){this.isPlaying=!0;for(const[i,{element:n}]of this.playbackElements.entries()){if(!(this.currentTime>=i.display.from&&(i.display.to===0||this.currentTime<=i.display.to)))continue;const o=(this.currentTime-i.display.from)/1e6;this.isPlaybackCapable(i)&&await i.play(n,o)}}}async frameNext(){const t=1e6/(this.studio.opts.fps||30),i=Math.min(this.currentTime+t,this.maxDuration);await this.seek(i)}async framePrev(){const t=1e6/(this.studio.opts.fps||30),i=Math.max(0,this.currentTime-t);await this.seek(i)}async renderLoop(){if(!this.isPlaying||this.studio.destroyed||this.studio.pixiApp==null)return;if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){this.pause();return}const e=async()=>{if(!this.isPlaying||this.studio.destroyed||this.studio.pixiApp==null)return;if(this.currentTime>=this.maxDuration){this.currentTime=this.maxDuration,this.pause();return}const i=(performance.now()-this.playStartTimestamp)*1e3;this.currentTime=Math.min(this.playStartTime+i,this.maxDuration),this.studio.emit("currentTime",{currentTime:this.currentTime});try{await this.studio.updateFrame(this.currentTime)}catch(n){console.warn("Error updating frame:",n)}this.isPlaying&&(this.rafId=requestAnimationFrame(e))};e()}isPlaybackCapable(e){return"play"in e&&"pause"in e&&"seek"in e}}class Qo{static instance;fonts=new Map;constructor(){}static getInstance(){return Qo.instance||(Qo.instance=new Qo),Qo.instance}async addFont(e){if(!this.fonts.has(e.name))try{const i=await new FontFace(e.name,`url(${e.url})`).load();document.fonts.add(i),this.fonts.set(e.name,i)}catch(t){console.error(`Failed to load font ${e.name}:`,t)}}async loadFonts(e){await Promise.all(e.map(t=>this.addFont(t)))}removeFont(e){const t=this.fonts.get(e);t&&(document.fonts.delete(t),this.fonts.delete(e))}clear(){this.fonts.forEach(e=>{document.fonts.delete(e)}),this.fonts.clear()}getLoadedFonts(){return Array.from(this.fonts.keys())}}const Y4=Qo.getInstance();class Bte{constructor(e){this.studio=e}tracks=[];clips=[];getTrackById(e){return this.tracks.find(t=>t.id===e)}getClipById(e){return this.clips.find(t=>t.id===e)}findTrackIdByClipId(e){for(const t of this.tracks)if(t.clipIds.includes(e))return t.id}getTrackIndex(e){return this.tracks.findIndex(t=>t.id===e)}addTrack(e,t){const i={id:e.id||`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:e.name,type:e.type,clipIds:[]};return typeof t=="number"?this.tracks.splice(t,0,i):this.tracks.unshift(i),this.studio.emit("track:added",{track:i,index:t??0}),this.studio.emit("track:order-changed",{tracks:this.tracks}),i}async removeTrack(e){const t=this.tracks.findIndex(s=>s.id===e);if(t===-1)return;const n=[...this.tracks[t].clipIds];for(const s of n)await this.removeClipById(s);this.tracks.splice(t,1),this.studio.emit("track:removed",{trackId:e}),this.studio.emit("track:order-changed",{tracks:this.tracks})}async moveTrack(e,t){const i=this.tracks.findIndex(s=>s.id===e);if(i===-1)return;const n=this.tracks[i];this.tracks.splice(i,1),this.tracks.splice(t,0,n),this.studio.emit("track:order-changed",{tracks:this.tracks}),await this.studio.updateFrame(this.studio.currentTime)}async setTrackOrder(e){const t=[],i=new Map(this.tracks.map(n=>[n.id,n]));for(const n of e){const s=i.get(n);s&&t.push(s)}t.length!==this.tracks.length&&console.warn("[Studio] setTrackOrder: invalid track IDs provided, order not updated fully"),this.tracks=t,this.studio.emit("track:order-changed",{tracks:this.tracks}),await this.studio.updateFrame(this.studio.currentTime)}async addTransition(e,t=2e6,i,n){if(this.studio.destroyed)return;let s=null,o=null;if(i&&n&&(s=this.getClipById(i)??null,o=this.getClipById(n)??null),!s||!o){console.warn("[Studio] Invalid fromClipId or toClipId",{fromClipId:i,toClipId:n});return}await Promise.all([s.ready,o.ready]);const a=t,l=o.display.from-a/2,u=l+a,c={key:e,name:e,duration:a,fromClipId:s.id,toClipId:o.id,start:Math.max(0,l),end:u},h=this.findTrackIdByClipId(o.id);if(h){const p=this.tracks.find(m=>m.id===h);if(p){const m=p.clipIds.map(g=>this.getClipById(g)).filter(g=>{if(!g||g.type!=="Transition")return!1;const v=g;return v.fromClipId===s.id&&v.toClipId===o.id});for(const g of m)await this.removeClip(g)}}const d=`${s.id}_${o.id}`;this.studio.transitionRenderers.has(d)&&(this.studio.transitionRenderers.get(d)?.destroy(),this.studio.transitionRenderers.delete(d)),s.transition={...c},o.transition={...c};const f=new Fi(e);f.duration=a,f.fromClipId=Math.max(0,l)===0?null:s.id,f.toClipId=o.id,f.fromClipId===null&&s&&(f.fromClipId=s.id),f.display.from=Math.max(0,l),f.display.to=u,await this.addClip(f,{trackId:h}),this.studio.seek(this.studio.currentTime)}async addClip(e,t){const i=Array.isArray(e)?e:[e];if(i.length===0)return;const{trackId:n,audioSource:s}=this.normalizeAddClipOptions(t);if(this.studio.destroyed)return;if(this.studio.pixiApp==null)throw new Error("Failed to initialize Pixi.js Application");const o=[];for(const a of i)await this.prepareClipForTimeline(a,n),o.push(a);await this.recalculateMaxDuration();for(const a of o)await this.setupClipVisuals(a,s);await this.studio.updateFrame(this.studio.currentTime),this.emitAddClipEvents(o,n)}normalizeAddClipOptions(e){let t,i;if(e&&(typeof e=="string"||e instanceof File||e instanceof Blob))t=e;else if(typeof e=="object"&&e!==null&&!("size"in e)){const n=e;t=n.audioSource,i=n.trackId}return{trackId:i,audioSource:t}}async prepareClipForTimeline(e,t){e.id||(e.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.includes(e)||this.clips.push(e),this.addClipToTrack(e,t);const i=async()=>{await this.studio.updateFrame(this.studio.currentTime);const n=this.studio.selection;n.activeTransformer!=null&&n.selectedClips.has(e)&&typeof n.activeTransformer.updateBounds=="function"&&n.activeTransformer.updateBounds()};e.on("propsChange",i),this.studio.clipListeners.set(e,i),this.studio.pixiApp!=null&&typeof e.setRenderer=="function"&&e.setRenderer(this.studio.pixiApp.renderer),await e.ready}addClipToTrack(e,t){if(t){const i=this.tracks.find(n=>n.id===t);if(i)i.clipIds.includes(e.id)||i.clipIds.push(e.id);else{const n={id:t,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(n),this.studio.emit("track:added",{track:n,index:0}),this.studio.emit("track:order-changed",{tracks:this.tracks})}}else{const n={id:`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(n),this.studio.emit("track:added",{track:n,index:0}),this.studio.emit("track:order-changed",{tracks:this.tracks})}}async setupClipVisuals(e,t){const i=this.studio.spriteRenderers.get(e);if(i){const n=this.studio.clipsNormalContainer,s=i.getRoot();s&&!s.parent&&n.addChild(s)}else{const n=await e.ready;if(n.width>0&&n.height>0){const s=this.studio.clipsNormalContainer,o=e.type==="Video"&&this.isPlaybackCapable(e);if(!o||o&&e.tickInterceptor!=null){const a=new z4(this.studio.pixiApp,e,s);this.studio.spriteRenderers.set(e,a)}}}await this.setupPlaybackForClip(e,t),this.studio.opts.interactivity&&this.studio.selection.setupSpriteInteractivity(e)}emitAddClipEvents(e,t){if(e.length!==0)if(e.length===1){const i=e[0],n=t||this.tracks.find(s=>s.clipIds.includes(i.id))?.id||"";this.studio.emit("clip:added",{clip:i,trackId:n})}else this.studio.emit("clips:added",{clips:e,trackId:t})}async removeClip(e,t={permanent:!0}){const{permanent:i}=t;if(e.locked)return;const n=this.clips.findIndex(c=>c===e);if(n===-1)return;if(e instanceof Fi){if(e.fromClipId){const c=this.getClipById(e.fromClipId);c&&"transition"in c&&delete c.transition}if(e.toClipId){const c=this.getClipById(e.toClipId);c&&"transition"in c&&delete c.transition}}this.studio.selection.selectedClips.has(e)&&this.studio.selection.deselectClip(),this.clips.splice(n,1);const s=[];for(const c of this.tracks){const h=c.clipIds.indexOf(e.id);h!==-1&&(c.clipIds.splice(h,1),s.push(c.id))}this.reconcileTracks(),this.studio.selection.interactiveClips.delete(e);const o=this.studio.clipListeners.get(e);o&&(e.off("propsChange",o),this.studio.clipListeners.delete(e));const a=this.studio.spriteRenderers.get(e);if(a!=null)if(i)a.destroy(),this.studio.spriteRenderers.delete(e);else{const c=a.getRoot();c&&c.parent&&c.parent.removeChild(c)}const l=this.studio.transport.playbackElements.get(e);l!=null&&(this.isPlaybackCapable(e)&&e.pause(l.element),this.studio.transport.playbackElements.delete(e),i&&this.isPlaybackCapable(e)&&e.cleanupPlayback(l.element,l.objectUrl));const u=this.studio.videoSprites.get(e);u!=null&&this.studio.pixiApp!=null&&(u.parent&&u.parent.removeChild(u),i&&(u.destroy(),this.studio.videoSprites.delete(e))),await this.recalculateMaxDuration(),this.studio.emit("clip:removed",{clipId:e.id})}async removeClips(e,t={permanent:!0}){if(e.length!==0){for(const i of e){if(i.locked)continue;const n=this.clips.findIndex(u=>u===i);if(n===-1)continue;if(i instanceof Fi){if(i.fromClipId){const u=this.getClipById(i.fromClipId);u&&"transition"in u&&delete u.transition}if(i.toClipId){const u=this.getClipById(i.toClipId);u&&"transition"in u&&delete u.transition}}this.studio.selection.selectedClips.has(i)&&this.studio.selection.deselectClip(),this.clips.splice(n,1);for(const u of this.tracks){const c=u.clipIds.indexOf(i.id);c!==-1&&u.clipIds.splice(c,1)}this.studio.selection.interactiveClips.delete(i);const s=this.studio.clipListeners.get(i);s&&(i.off("propsChange",s),this.studio.clipListeners.delete(i));const o=this.studio.spriteRenderers.get(i);if(o!=null)if(t.permanent)o.destroy(),this.studio.spriteRenderers.delete(i);else{const u=o.getRoot();u&&u.parent&&u.parent.removeChild(u)}const a=this.studio.transport.playbackElements.get(i);a!=null&&(this.isPlaybackCapable(i)&&i.pause(a.element),this.studio.transport.playbackElements.delete(i),t.permanent&&this.isPlaybackCapable(i)&&i.cleanupPlayback(a.element,a.objectUrl));const l=this.studio.videoSprites.get(i);l!=null&&this.studio.pixiApp!=null&&(l.parent&&l.parent.removeChild(l),t.permanent&&(l.destroy(),this.studio.videoSprites.delete(i)))}for(let i=this.tracks.length-1;i>=0;i--)if(this.tracks[i].clipIds.length===0){const n=this.tracks[i].id;this.tracks.splice(i,1),this.studio.emit("track:removed",{trackId:n})}await this.recalculateMaxDuration(),this.studio.emit("clips:removed",{clipIds:e.map(i=>i.id)})}}async removeClipById(e){const t=this.clips.find(i=>i.id===e);t&&await this.removeClip(t)}async updateClip(e,t){const i=this.clips.find(n=>n.id===e);i&&(i.locked&&!("locked"in t)||(i.locked&&"locked"in t&&(Object.keys(t).length===1||(t={locked:t.locked})),await this.applyClipUpdate(i,t),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(i),this.studio.emit("clip:updated",{clip:i})))}async updateClips(e){const t=[];for(const{id:i,updates:n}of e){const s=this.clips.find(o=>o.id===i);s&&(await this.applyClipUpdate(s,n),t.push(s))}if(t.length!==0){await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime);for(const i of t)this.updateTransformer(i),this.studio.emit("clip:updated",{clip:i})}}async replaceClipsBySource(e,t){const i=this.clips.filter(n=>n.src===e);if(i.length!==0){this.studio.suspendRendering();for(const n of i){if(!this.clips.includes(n))continue;const s=this.findTrackIdByClipId(n.id);if(!s)continue;const o=this.getTrackById(s);if(!o)continue;const a=await t(n),l=async()=>{await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(a)};a.on("propsChange",l),this.studio.clipListeners.set(a,l),this.studio.pixiApp!=null&&typeof a.setRenderer=="function"&&a.setRenderer(this.studio.pixiApp.renderer),await a.ready;const u=this.clips.indexOf(n);u!==-1&&(this.clips[u]=a);const c=o.clipIds.indexOf(n.id);c!==-1&&(o.clipIds[c]=a.id),await this.setupClipVisuals(a);const h=this.studio.spriteRenderers.get(n);h&&(h.destroy(),this.studio.spriteRenderers.delete(n));const d=this.studio.videoSprites.get(n);d&&(d.parent&&d.parent.removeChild(d),d.destroy(),this.studio.videoSprites.delete(n));const f=this.studio.clipListeners.get(n);f&&(n.off("propsChange",f),this.studio.clipListeners.delete(n)),this.studio.selection.selectedClips.has(n)&&(this.studio.selection.selectedClips.delete(n),this.studio.selection.selectedClips.add(a)),this.studio.emit("clip:replaced",{oldClip:n,newClip:a,trackId:s})}await this.recalculateMaxDuration(),this.studio.resumeRendering(),await this.studio.updateFrame(this.studio.currentTime)}}async applyClipUpdate(e,t){if(e.type==="Text"||e.type==="Caption"){const i=e;typeof i.updateStyle=="function"&&await i.updateStyle(t),"style"in t&&delete t.style}if(Object.assign(e,t),t.display&&!t.duration?e.duration=t.display.to-t.display.from:t.duration&&(!t.display||!t.display.to)&&(e.display||(e.display={from:0,to:t.duration}),e.display.to=e.display.from+t.duration),t.display&&t.duration){const i=t.display.to-t.display.from;i!==t.duration&&(e.duration=i)}else e.display&&(e.display.to=e.display.from+e.duration)}updateTransformer(e){const t=this.studio.selection;t.selectedClips.has(e)&&t.activeTransformer&&t.activeTransformer.updateBounds()}exportToJSON(){this.reconcileTracks();const e=this.clips.map(n=>Dl(n,!1)),t=this.tracks.map(n=>({id:n.id,name:n.name,type:n.type,clipIds:[...n.clipIds]})),i=[];return this.clips.forEach(n=>{if(n.transition){const s=this.tracks.find(o=>o.clipIds.includes(n.id));if(s){const o=s.clipIds.indexOf(n.id);if(o>0){const a=s.clipIds[o-1];i.push({key:n.transition.name,duration:n.transition.duration,clips:[a,n.id]})}}}}),{tracks:t,clips:e,settings:{width:this.studio.opts.width,height:this.studio.opts.height,fps:this.studio.opts.fps,bgColor:this.studio.opts.bgColor}}}async loadFromJSON(e){if(await this.clear(),e.settings){const i=e.settings.width&&e.settings.width!==this.studio.opts.width||e.settings.height&&e.settings.height!==this.studio.opts.height;if(e.settings.width&&(this.studio.opts.width=e.settings.width),e.settings.height&&(this.studio.opts.height=e.settings.height),e.settings.fps&&(this.studio.opts.fps=e.settings.fps),e.settings.bgColor&&(this.studio.opts.bgColor=e.settings.bgColor),i&&this.studio.pixiApp!=null){const n=this.studio.opts.width,s=this.studio.opts.height;this.studio.pixiApp.renderer.resize(n,s),this.studio.opts.canvas&&(this.studio.opts.canvas.width=n,this.studio.opts.canvas.height=s)}}const t=[];if(e.clips){await this.ensureFontsForClips(e.clips);const i=e.clips.map(o=>o.src).filter(o=>o&&o.trim()!=="");this.studio.resourceManager.preload(i);const n=new Map;if(e.tracks){for(const o of e.tracks)if(o.clipIds)for(const a of o.clipIds)n.set(a,o.id)}if(e.tracks)for(const o of e.tracks)this.tracks.push({id:o.id,name:o.name,type:o.type,clipIds:[]});for(const o of e.clips)t.push((async()=>{try{let a=o.id?n.get(o.id):void 0;if(o.type==="Transition"){const u=o,c=u.toClipId||u.fromClipId;c&&(a=n.get(c))}if(o.type!=="Text"&&o.type!=="Caption"&&o.type!=="Effect"&&o.type!=="Transition"&&(!o.src||o.src.trim()===""))return console.warn(`Skipping clip ${o.type} with empty source`,o),{clip:null};const l=await qo(o);return(l.type==="Video"||l.type==="Image")&&(!o.width||!o.height)&&this.studio.opts.width&&this.studio.opts.height&&(typeof l.scaleToFit=="function"&&await l.scaleToFit(this.studio.opts.width,this.studio.opts.height),typeof l.centerInScene=="function"&&l.centerInScene(this.studio.opts.width,this.studio.opts.height)),{clip:l,intendedTrackId:a}}catch(a){return console.error(`Failed to load clip ${o.id||"unknown"}:`,a),{clip:null}}})());const s=await Promise.all(t);for(const{clip:o,intendedTrackId:a}of s)o&&(o.id||(o.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.push(o),this.addClipToTrack(o,a))}this.studio.pixiApp&&this.clips.forEach(i=>{const n=async()=>{await this.studio.updateFrame(this.studio.currentTime);const s=this.studio.selection;s.activeTransformer!=null&&s.selectedClips.has(i)&&typeof s.activeTransformer.updateBounds=="function"&&s.activeTransformer.updateBounds()};i.on("propsChange",n),this.studio.clipListeners.set(i,n),typeof i.setRenderer=="function"&&i.setRenderer(this.studio.pixiApp.renderer),(async()=>{try{await i.ready,await this.setupClipVisuals(i),await this.studio.updateFrame(this.studio.currentTime)}catch(s){console.warn(`[Studio] Failed to setup visuals for clip ${i.id}:`,s)}})()});for(const i of this.clips){const n=i.effects;if(Array.isArray(n))for(const s of n)this.studio.globalEffects.has(s.id)||this.studio.globalEffects.set(s.id,{id:s.id,key:s.key,startTime:s.startTime,duration:s.duration})}for(const i of this.clips)if(i instanceof Fi){const n={name:i.transitionEffect.key,key:i.transitionEffect.key,duration:i.duration,fromClipId:i.fromClipId,toClipId:i.toClipId,start:i.display.from,end:i.display.to};if(i.fromClipId){const s=this.getClipById(i.fromClipId);s&&(s.transition={...n})}if(i.toClipId){const s=this.getClipById(i.toClipId);s&&(s.transition={...n})}}await this.recalculateMaxDuration();try{await this.studio.updateFrame(this.studio.currentTime)}catch(i){console.error("[Studio] Failed to update initial frame:",i)}this.studio.emit("studio:restored",{clips:this.clips,tracks:this.tracks,settings:this.studio.opts})}async deleteSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e);if(t.length!==0)for(const i of t)await this.removeClip(i)}async duplicateSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e).filter(n=>!n.locked);if(t.length===0)return;const i=[];for(const n of t){const s=this.findTrackIdByClipId(n.id);if(!s)continue;const o=this.tracks.find(h=>h.id===s);if(!o)continue;const a=Dl(n,!1),l=await qo(a);l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const u=`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=`${o.name} (Copy)`;this.addTrack({id:u,name:c,type:o.type}),await this.addClip(l,{trackId:u}),i.push(l.id)}i.length>0&&this.studio.selection.selectClipsByIds(i)}async splitSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==1){console.warn("[Studio] Split requires exactly one selected clip");return}const i=t[0];if(i.locked){console.warn("[Studio] Cannot split a locked clip");return}const n=e??this.studio.currentTime;if(n<=i.display.from||i.display.to>0&&n>=i.display.to){console.warn("[Studio] Split time is outside clip bounds");return}const s=Dl(i,!1),o=n-i.display.from,a=i.playbackRate||1,l=o*a,u={duration:o,display:{from:i.display.from,to:n}};i.trim&&(u.trim={from:i.trim.from,to:i.trim.from+l}),await this.updateClip(i.id,u);const c={...s};c.display={from:n,to:s.display.to},c.duration=s.duration-o,c.trim&&(c.trim={from:c.trim.from+l,to:c.trim.to});const h=await qo(c);h.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const d=this.findTrackIdByClipId(i.id);d&&(await this.addClip(h,{trackId:d}),this.studio.selection.selectClipsByIds([h.id]))}async trimSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==1){console.warn("[Studio] Trim requires exactly one selected clip");return}const i=t[0];if(i.locked){console.warn("[Studio] Cannot trim a locked clip");return}const n=e*1e6,s=i.playbackRate||1,o=n*s;if(n>=i.duration){console.warn("[Studio] Trim amount exceeds clip duration");return}const a=i.duration-n,l=i.display.from+n,u=i.display.to,c={duration:a,display:{from:l,to:u}};if(i.trim)c.trim={from:i.trim.from+o,to:i.trim.to};else{const h=i.sourceDuration||i.duration;c.trim={from:o,to:h}}await this.updateClip(i.id,c)}async updateSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==0)for(const i of t)await this.updateClip(i.id,e)}async setTracks(e){const t=JSON.parse(JSON.stringify(this.tracks));this.tracks=JSON.parse(JSON.stringify(e)),this.reconcileTracks(),this.tracks.length===0&&this.clips.length>0&&(this.tracks=t,this.reconcileTracks()),await this.recalculateMaxDuration(),this.studio.isRestoring||this.studio.emit("track:order-changed",{tracks:this.tracks}),await this.studio.updateFrame(this.studio.currentTime)}reconcileTracks(){const e=new Set(this.clips.map(t=>t.id));for(let t=this.tracks.length-1;t>=0;t--){const i=this.tracks[t],n=i.clipIds.filter(s=>e.has(s));n.length!==i.clipIds.length&&(i.clipIds=n),i.clipIds.length===0&&(this.tracks.splice(t,1),this.studio.isRestoring||this.studio.emit("track:removed",{trackId:i.id}))}this.tracks.length===0&&!this.studio.isRestoring&&this.studio.emit("track:order-changed",{tracks:this.tracks})}async ensureFontsForClips(e){const t=new Map;for(const i of e){if(i.type==="Text"){const n=i.style?.fontUrl||i.fontUrl;n&&t.set(n,{name:i.style?.fontFamily||i.fontFamily||"CustomFont",url:n})}if(i.type==="Caption"){const n=i.style?.fontUrl||i.fontUrl;n&&t.set(n,{name:i.style?.fontFamily||i.fontFamily||"CustomFont",url:n})}}if(t.size>0)try{await Y4.loadFonts(Array.from(t.values()))}catch(i){console.warn("Failed to load some fonts:",i)}}async recalculateMaxDuration(){let e=0;for(const t of this.clips){t.display.to===0&&t.duration!==1/0&&!isNaN(t.duration)&&t.duration>0;const i=t.duration>0?t.duration:0;if(i===1/0)continue;const n=t.display.to>0?t.display.to:t.display.from+i;n>e&&(e=n)}this.studio.maxDuration=e}async setupPlaybackForClip(e,t){if(this.studio.pixiApp!=null&&this.isPlaybackCapable(e))try{const i=e;if(e.type==="Audio"&&t&&typeof t!="string"){const o=URL.createObjectURL(t);e.src=o}const{element:n,objectUrl:s}=await i.createPlaybackElement();if(e.type==="Video"){const o=Q.from(n),a=new $e(o);a.visible=!1,this.studio.clipsNormalContainer&&this.studio.clipsNormalContainer.addChild(a),this.studio.videoSprites.set(e,a)}this.studio.transport.playbackElements.set(e,{element:n,objectUrl:s})}catch(i){console.warn(`Failed to setup playback for ${e.constructor.name}`,i)}}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async clear(){this.studio.selection.deselectClip(),this.studio.selection.interactiveClips.clear();for(const[e,t]of this.studio.clipListeners)e.off("propsChange",t);this.studio.clipListeners.clear(),this.studio.globalEffects.clear(),this.studio.effectFilters.clear(),this.studio.transitionRenderers.forEach(e=>e.destroy()),this.studio.transitionRenderers.clear(),this.studio.transitionSprites.forEach(e=>{e.parent&&e.parent.removeChild(e),e.destroy()}),this.studio.transitionSprites.clear(),this.studio.spriteRenderers.forEach(e=>e.destroy()),this.studio.spriteRenderers.clear();for(const[e,t]of this.studio.transport.playbackElements)this.isPlaybackCapable(e)&&e.cleanupPlayback(t.element,t.objectUrl);this.studio.transport.playbackElements.clear();for(const e of this.studio.videoSprites.values())e.destroy();this.studio.videoSprites.clear(),this.tracks=[],this.clips=[],this.studio.maxDuration=0,this.studio.currentTime=0,this.studio.emit("reset")}async rippleDelete(e,t){if(e>=t)return;const i=t-e,n=[...this.clips];for(const s of n){const o=s.display.from,a=s.display.to;if(!(a<=e)){if(o>=t){await this.updateClip(s.id,{display:{from:s.display.from-i,to:s.display.to-i}});continue}if(o>=e&&a<=t){await this.removeClip(s);continue}if(o<e&&a>t){const l=await s.clone();l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const u=e,c=e+(a-t),h=s.trim.from+(t-o)*s.playbackRate,d=s.trim.to,f=this.tracks.find(p=>p.clipIds.includes(s.id));f&&(await this.addClip(l,{trackId:f.id}),await this.updateClip(l.id,{display:{from:u,to:c},trim:{from:h,to:d}})),await this.updateClip(s.id,{display:{from:s.display.from,to:e},trim:{from:s.trim.from,to:s.trim.from+(e-o)*s.playbackRate}});continue}if(o<e&&a<=t){await this.updateClip(s.id,{display:{from:s.display.from,to:e},trim:{from:s.trim.from,to:s.trim.from+(e-o)*s.playbackRate}});continue}if(o>=e&&a>t){await this.updateClip(s.id,{display:{from:e,to:e+(a-t)},trim:{from:s.trim.from+(t-o)*s.playbackRate,to:s.trim.to}});continue}}}await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}}const kte={Date:!0,RegExp:!0,String:!0,Number:!0};function q4(r,e,t={cyclesFix:!0},i=[]){let n=[];const s=Array.isArray(r);for(const a in r){const l=r[a],u=s?+a:a;if(!(a in e)){n.push({type:"REMOVE",path:[u],oldValue:r[a]});continue}const c=e[a],h=typeof l=="object"&&typeof c=="object"&&Array.isArray(l)===Array.isArray(c);l&&c&&h&&!kte[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!i.includes(l))?n.push.apply(n,q4(l,c,t,t.cyclesFix?i.concat([l]):[]).map(d=>(d.path.unshift(u),d))):l!==c&&!(Number.isNaN(l)&&Number.isNaN(c))&&!(h&&(isNaN(l)?l+""==c+"":+l==+c))&&n.push({path:[u],type:"CHANGE",value:c,oldValue:l})}const o=Array.isArray(e);for(const a in e)a in r||n.push({type:"CREATE",path:[o?+a:a],value:e[a]});return n}class Rte{past=[];future=[];lastState=null;maxSize;constructor(e={}){this.maxSize=e.maxSize||50}projectToHistoryState(e){const t={},i=JSON.parse(JSON.stringify(e.tracks||[]));return e.clips.forEach(n=>{n.id&&(t[n.id]=JSON.parse(JSON.stringify(n)))}),{clips:t,tracks:i,settings:JSON.parse(JSON.stringify(e.settings||{}))}}init(e){this.lastState=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),this.past=[],this.future=[]}push(e){if(!this.lastState){this.init(e);return}const t=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),i=q4(this.lastState,t);i.length!==0&&(this.past.push(i),this.past.length>this.maxSize&&this.past.shift(),this.future=[],this.lastState=t)}undo(e){const t=this.past.pop();if(!t)return null;const i=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),n=this.applyPatches(i,t,!0);return this.future.push(t),this.lastState=n,{patches:t,state:n}}redo(e){const t=this.future.pop();if(!t)return null;const i=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),n=this.applyPatches(i,t,!1);return this.past.push(t),this.lastState=n,{patches:t,state:n}}applyPatches(e,t,i){const n=JSON.parse(JSON.stringify(e)),s=i?[...t].reverse():t;for(const o of s){const{type:a,path:l}=o,u=o.value,c=o.oldValue;let h=n,d=!1;for(let p=0;p<l.length-1;p++){if(h[l[p]]===void 0||h[l[p]]===null){d=!0;break}h=h[l[p]]}if(d)continue;const f=l[l.length-1];if(i)switch(a){case"CREATE":Array.isArray(h)?h.splice(f,1):delete h[f];break;case"REMOVE":h[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break;case"CHANGE":h[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break}else switch(a){case"CREATE":h[f]=u&&typeof u=="object"?JSON.parse(JSON.stringify(u)):u;break;case"REMOVE":Array.isArray(h)?h.splice(f,1):delete h[f];break;case"CHANGE":h[f]=u&&typeof u=="object"?JSON.parse(JSON.stringify(u)):u;break}}return n}canUndo(){return this.past.length>0}canRedo(){return this.future.length>0}}class Fte extends Z0{selection;transport;timeline;history;resourceManager;pixiApp=null;get tracks(){return this.timeline.tracks}get clips(){return this.timeline.clips}spriteRenderers=new Map;artboard=null;clipContainer=null;artboardMask=null;artboardBg=null;get activeTransformer(){return this.selection.activeTransformer}set activeTransformer(e){this.selection.activeTransformer=e}get selectedClips(){return this.selection.selectedClips}set selectedClips(e){this.selection.selectedClips=e}get interactiveClips(){return this.selection.interactiveClips}set interactiveClips(e){this.selection.interactiveClips=e}get playbackElements(){return this.transport.playbackElements}videoSprites=new Map;clipListeners=new Map;get isPlaying(){return this.transport.isPlaying}set isPlaying(e){this.transport.isPlaying=e}get currentTime(){return this.transport.currentTime}set currentTime(e){this.transport.currentTime=e}get maxDuration(){return this.transport.maxDuration}set maxDuration(e){this.transport.maxDuration=e}opts;destroyed=!1;renderingSuspended=!1;historyPaused=!1;processingHistory=!1;isRestoring=!1;historyGroupDepth=0;clipCache=new Map;_isUpdatingLayout=!1;globalEffects=new Map;activeGlobalEffects=[];currentGlobalEffectSprite=null;effectFilters=new Map;transitionRenderers=new Map;transitionSprites=new Map;transFromTexture=null;transToTexture=null;transBgGraphics=null;clipsNormalContainer=null;clipsEffectContainer=null;videoTextureCache=new WeakMap;lastFromFrame=null;lastToFrame=null;hexToNumber(e){const t=e.startsWith("#")?e.slice(1):e;return parseInt(t,16)}ready;constructor(e){super(),this.opts={fps:30,bgColor:"#000000",interactivity:!0,spacing:0,...e},this.selection=new Pte(this),this.transport=new Ite(this),this.timeline=new Bte(this),this.history=new Rte,this.resourceManager=new No,this.ready=this.initPixiApp().then(()=>{this.history.init(this.exportToJSON())}),this.on("clip:added",t=>this.handleTimelineChange(t)),this.on("clips:added",t=>this.handleTimelineChange(t)),this.on("clip:replaced",t=>this.handleTimelineChange({clip:t.newClip})),this.on("studio:restored",t=>{t.clips.forEach(i=>this.attachClipEvents(i)),this.handleTimelineChange()}),this.on("clip:removed",this.handleClipRemoved),this.on("clips:removed",this.handleClipsRemoved),this.on("clip:updated",this.handleTimelineChange),this.on("track:removed",()=>this.handleTimelineChange()),this.on("track:added",()=>this.handleTimelineChange())}attachClipEvents(e){if(this.clipListeners.has(e))return;const t=()=>{this.updateFrame(this.currentTime)};e.on("request-render",t),this.clipListeners.set(e,t)}handleTimelineChange=e=>{e?.clip&&this.attachClipEvents(e.clip),e?.clips&&e.clips.forEach(t=>this.attachClipEvents(t)),this.updateFrame(this.currentTime),this.saveHistory()};saveHistory(){this.historyPaused||this.processingHistory||(this.history.push(this.exportToJSON()),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()}))}beginHistoryGroup(){this.processingHistory||this.isRestoring||(this.historyGroupDepth++,this.historyPaused=!0)}endHistoryGroup(){this.processingHistory||this.isRestoring||(this.historyGroupDepth=Math.max(0,this.historyGroupDepth-1),this.historyGroupDepth===0&&(this.historyPaused=!1,this.saveHistory()))}setPath(e,t,i){let n=e;for(let s=0;s<t.length-1;s++){const o=t[s];n[o]||(n[o]=typeof t[s+1]=="number"?[]:{}),n=n[o]}n[t[t.length-1]]=i}async applyHistoryPatches(e,t,i){const n=new Map,s=new Map,o=new Set;for(const a of e){const{type:l,path:u}=a,c=a.value,h=a.oldValue;if(u[0]==="clips"){const d=u[1];i?l==="CREATE"?o.add(d):l==="REMOVE"?s.set(d,h):l==="CHANGE"&&(n.has(d)||n.set(d,{}),this.setPath(n.get(d),u.slice(2),h)):l==="CREATE"?s.set(d,c):l==="REMOVE"?o.add(d):l==="CHANGE"&&(n.has(d)||n.set(d,{}),this.setPath(n.get(d),u.slice(2),c))}else u[0]==="settings"&&(i?this.setPath(this.opts,u.slice(1),h):this.setPath(this.opts,u.slice(1),c))}for(const a of o){const l=this.timeline.getClipById(a);l&&await this.removeClip(l)}for(const[a,l]of s){let u=this.clipCache.get(a);u||(u=await qo(l),this.clipCache.set(a,u),this.attachClipEvents(u));let c;for(const h of t.tracks)if(h.clipIds.includes(a)){c=h.id;break}await this.addClip(u,{trackId:c})}for(const[a,l]of n)await this.updateClip(a,l);this.timeline.setTracks(t.tracks),this.emit("studio:restored",{clips:this.clips,tracks:this.tracks,settings:this.opts})}async undo(){if(!(!this.history.canUndo()||this.processingHistory)){this.processingHistory=!0,this.isRestoring=!0,this.historyPaused=!0;try{const e=this.history.undo(this.exportToJSON());e&&await this.applyHistoryPatches(e.patches,e.state,!0),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}finally{this.historyPaused=!1,this.isRestoring=!1,this.processingHistory=!1}}}async redo(){if(!(!this.history.canRedo()||this.processingHistory)){this.processingHistory=!0,this.isRestoring=!0,this.historyPaused=!0;try{const e=this.history.redo(this.exportToJSON());e&&await this.applyHistoryPatches(e.patches,e.state,!1),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}finally{this.historyPaused=!1,this.isRestoring=!1,this.processingHistory=!1}}}cleanupClipVisuals=e=>{for(const[s,o]of this.spriteRenderers)if(s.id===e){const a=o.getRoot();a&&a.parent&&a.parent.removeChild(a),o.destroy(),this.spriteRenderers.delete(s);break}const t=this.transitionSprites.get(e);t&&(t.parent&&t.parent.removeChild(t),t.destroy(),this.transitionSprites.delete(e)),this.transitionRenderers.get(e)&&this.transitionRenderers.delete(e);for(const[s,o]of this.videoSprites)if(s.id===e){o.parent&&o.parent.removeChild(o),o.destroy(),this.videoSprites.delete(s);break}const n=this.timeline.getClipById(e);if(n){const s=this.clipListeners.get(n);s&&(n.off("request-render",s),this.clipListeners.delete(n))}};handleClipRemoved=({clipId:e})=>{this.cleanupClipVisuals(e),this.updateFrame(this.currentTime),this.saveHistory()};handleClipsRemoved=({clipIds:e})=>{for(const t of e)this.cleanupClipVisuals(t);this.updateFrame(this.currentTime),this.saveHistory()};async initPixiApp(){if(this.destroyed)return;const e=this.opts.canvas||document.createElement("canvas");e.width=this.opts.width,e.height=this.opts.height;const t=new bc,i=e.parentElement||window;await t.init({canvas:e,resizeTo:i,backgroundColor:this.hexToNumber(this.opts.bgColor),antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0,autoStart:!1}),this.pixiApp=t,t.render(),t.stage.eventMode="static",t.stage.hitArea=t.screen,this.artboard=new Ie,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new Je,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new Ie,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new Je,this.artboardMask.rect(0,0,this.opts.width,this.opts.height).fill({color:16777215}),this.clipContainer.addChild(this.artboardMask),this.clipContainer.mask=this.artboardMask,this.clipsEffectContainer=new Ie,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new Ie,this.clipsNormalContainer.label="ClipsNormal",this.clipsNormalContainer.zIndex=10,this.clipsNormalContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsNormalContainer),this.transFromTexture=Ot.create({width:this.opts.width,height:this.opts.height}),this.transToTexture=Ot.create({width:this.opts.width,height:this.opts.height}),this.transBgGraphics=new Je,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}),this.clipContainer.sortableChildren=!0,this.updateArtboardLayout(),t.renderer.on("resize",()=>{this.handleResize()})}getOptions(){return this.opts}setSize(e,t){this.updateDimensions(e,t)}setBgColor(e){this.opts.bgColor=e;const t=this.hexToNumber(e);this.pixiApp&&(this.pixiApp.renderer.background.color=t,this.pixiApp.render()),this.updateFrame(this.currentTime)}updateDimensions(e,t){this.opts.width=e,this.opts.height=t,this.artboardBg&&this.artboardBg.clear().rect(0,0,e,t).fill({color:0}),this.artboardMask&&this.artboardMask.clear().rect(0,0,e,t).fill({color:16777215}),this.transFromTexture&&this.transFromTexture.resize(e,t),this.transToTexture&&this.transToTexture.resize(e,t),this.transBgGraphics&&this.transBgGraphics.clear().rect(0,0,e,t).fill({color:0,alpha:0}),this.updateArtboardLayout(),this.updateFrame(this.currentTime)}handleResize=()=>{this.destroyed||!this.pixiApp||this._isUpdatingLayout||this.updateArtboardLayout()};updateArtboardLayout(){if(!(!this.pixiApp||!this.artboard||this._isUpdatingLayout)){this._isUpdatingLayout=!0;try{this.pixiApp.resize();const t=this.pixiApp.canvas.parentElement,i=t?t.getBoundingClientRect().width:this.pixiApp.screen.width,n=t?t.getBoundingClientRect().height:this.pixiApp.screen.height,s=this.opts.width,o=this.opts.height,a=this.opts.spacing||0,l=Math.max(0,i-a*2),u=Math.max(0,n-a*2),c=l/s,h=u/o,d=Math.min(c,h);this.artboard.scale.set(d),this.artboard.x=(i-s*d)/2,this.artboard.y=(n-o*d)/2,this.pixiApp.render()}finally{this._isUpdatingLayout=!1}}}getCanvas(){if(this.opts.canvas)return this.opts.canvas;if(this.pixiApp?.canvas)return this.pixiApp.canvas;throw new Error("Canvas not initialized yet. Wait for initPixiApp to complete.")}async addTransition(e,t=2e6,i,n){return this.timeline.addTransition(e,t,i,n)}findTrackIdByClipId(e){return this.timeline.findTrackIdByClipId(e)}async addClip(e,t){const i=Array.isArray(e)?e:[e];i.forEach(n=>this.clipCache.set(n.id,n)),this.beginHistoryGroup();try{const n=await this.timeline.addClip(e,t);return i.forEach(s=>this.attachClipEvents(s)),n}finally{this.endHistoryGroup()}}addTrack(e,t){return this.timeline.addTrack(e,t)}async setTracks(e){if(this.isRestoring)return;const t=new Set(this.timeline.clips.map(i=>i.id));if(!(e.length===0&&t.size>0)&&!(e.length>0&&t.size>0&&!e.some(n=>n.clipIds.some(s=>t.has(s)))))return this.timeline.setTracks(e)}async moveTrack(e,t){return this.timeline.moveTrack(e,t)}async setTrackOrder(e){return this.timeline.setTrackOrder(e)}async removeTrack(e){return this.timeline.removeTrack(e)}getClipById(e){return this.timeline.getClipById(e)}async updateClip(e,t){return this.timeline.updateClip(e,t)}async centerClip(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=(this.opts.width-t.width)/2,n=(this.opts.height-t.height)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{left:i,top:n});t.left=i,t.top=n}async centerClipH(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=(this.opts.width-t.width)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{left:i});t.left=i}async centerClipV(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=(this.opts.height-t.height)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{top:i});t.top=i}async scaleToFit(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=await t.ready,{width:n,height:s}=i;if(n===0||s===0)return;const o=Math.min(this.opts.width/n,this.opts.height/s),a=n*o,l=s*o;if(this.getClipById(t.id))return this.updateClip(t.id,{width:a,height:l});t.width=a,t.height=l}async scaleToCover(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const i=await t.ready,{width:n,height:s}=i;if(n===0||s===0)return;const o=Math.max(this.opts.width/n,this.opts.height/s),a=n*o,l=s*o;if(this.getClipById(t.id))return this.updateClip(t.id,{width:a,height:l});t.width=a,t.height=l}async updateClips(e){this.suspendRendering(),await this.timeline.updateClips(e),this.resumeRendering(),this.updateFrame(this.currentTime)}suspendRendering(){this.renderingSuspended=!0}resumeRendering(){this.renderingSuspended=!1}getTracks(){return this.timeline.tracks}getClip(e){return this.timeline.getClipById(e)}findClip(e){return this.timeline.getClipById(e)}setupSpriteInteractivity(e){this.selection.setupSpriteInteractivity(e)}async removeClip(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t){console.warn("[Studio] removeClip: Clip not found",e);return}this.beginHistoryGroup();try{return this.clipCache.set(t.id,t),this.timeline.removeClip(t,{permanent:!this.processingHistory})}finally{this.endHistoryGroup()}}async removeClips(e){this.beginHistoryGroup();try{return e.forEach(t=>this.clipCache.set(t.id,t)),this.timeline.removeClips(e,{permanent:!this.processingHistory})}finally{this.endHistoryGroup()}}async removeClipById(e){const t=this.timeline.getClipById(e);if(t)return this.removeClip(t)}async removeClipsById(e){const t=e.map(i=>this.timeline.getClipById(i)).filter(Boolean);return this.removeClips(t)}async deleteSelected(){const e=this.selection.selectedClips;if(e.size!==0){this.beginHistoryGroup();try{await this.removeClips(Array.from(e))}finally{this.endHistoryGroup()}}}async duplicateSelected(){this.beginHistoryGroup();try{return await this.timeline.duplicateSelected()}finally{this.endHistoryGroup()}}async splitSelected(e){this.beginHistoryGroup();try{return await this.timeline.splitSelected(e)}finally{this.endHistoryGroup()}}async trimSelected(e){return this.timeline.trimSelected(e)}async updateSelected(e){return this.timeline.updateSelected(e)}async clear(){await this.timeline.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null),this.transitionRenderers.forEach(e=>e.destroy()),this.transitionRenderers.clear(),this.transitionSprites.forEach(e=>e.destroy()),this.transitionSprites.clear(),this.emit("reset")}async play(){return this.transport.play()}pause(){this.transport.pause()}async stop(){return this.transport.stop()}async seek(e){return this.transport.seek(e)}async frameNext(){return this.transport.frameNext()}async framePrev(){return this.transport.framePrev()}async renderFrame(e){if(await this.ready,!this.pixiApp||!this.artboard)throw new Error("Studio is not initialized yet. Wait for studio.ready before calling renderFrame().");const t=e*1e3;await this.updateFrame(t);const i=this.artboard.scale.clone(),n=this.artboard.x,s=this.artboard.y;this.artboard.scale.set(1),this.artboard.x=0,this.artboard.y=0;let o;try{o=await this.pixiApp.renderer.extract.base64(this.artboard,"image/png",1)}finally{this.artboard.scale.set(i.x,i.y),this.artboard.x=n,this.artboard.y=s,this.pixiApp.render()}return o}getCurrentTime(){return this.transport.currentTime}getMaxDuration(){return this.transport.maxDuration}getIsPlaying(){return this.transport.isPlaying}getSelectedClips(){return Array.from(this.selectedClips)}getVideoTexture(e){let t=this.videoTextureCache.get(e);return t||(t=Q.from(e),this.videoTextureCache.set(e,t)),t}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async updateFrame(e){if(this.destroyed||this.pixiApp==null||this.renderingSuspended)return;this.updateActiveGlobalEffect(e);const t=new Set,i=new Set,n=this.tracks.length;for(const o of this.clips){const a=this.getTrackIndex(o.id);if(a!==-1){const l=(n-a)*10;o.zIndex=l;const u=this.spriteRenderers.get(o);if(u){const h=u.getRoot();h&&(h.zIndex=l)}const c=this.videoSprites.get(o);c&&(c.zIndex=l)}}const s=[...this.clips].sort((o,a)=>o.zIndex-a.zIndex);for(const o of s){if(e<o.display.from){const v=this.spriteRenderers.get(o);v!=null&&await v.updateFrame(null);const x=this.playbackElements.get(o);x!=null&&this.isPlaybackCapable(o)&&o.pause(x.element);continue}if(o.display.to>0&&e>o.display.to){const v=this.spriteRenderers.get(o);v!=null&&await v.updateFrame(null);const x=this.playbackElements.get(o);x!=null&&this.isPlaybackCapable(o)&&o.pause(x.element);continue}const a=e-o.display.from,l=a*o.playbackRate;o.animate(l);const u=await o.ready,c=o.duration||u.duration;if(c>0&&a>c){const v=this.spriteRenderers.get(o);v!=null&&await v.updateFrame(null);const x=this.playbackElements.get(o);x!=null&&this.isPlaybackCapable(o)&&o.pause(x.element);continue}const h=this.playbackElements.get(o),d=o.type==="Video"||o.type==="Image",f=o.transition?o.transition.start:0,p=o.transition?o.transition.end:0,m=d&&o.transition&&e>=f&&e<p;if(h!=null&&this.isPlaybackCapable(o)){const v=a/1e6;if(o.syncPlayback(h.element,this.isPlaying,v),o.type==="Video"&&this.isPlaybackCapable(o)){const x=this.videoSprites.get(o);if(x!=null){const y=o.meta.duration/1e6;if(this.spriteRenderers.has(o))x.visible=!1;else if(x.visible=!m&&v>=0&&v<y,x.visible&&yee(o,x),!m)continue}}else continue}if(m){const v=o?.transition?.fromClipId,x=o?.transition?.toClipId,y=`${v}_${x}`;if(i.has(y)){const P=this.spriteRenderers.get(o);P?.getRoot()&&(P.getRoot().visible=!1);const _=this.videoSprites.get(o);_&&(_.visible=!1);continue}i.add(y),this.transFromTexture||(this.transFromTexture=Ot.create({width:this.opts.width,height:this.opts.height})),this.transToTexture||(this.transToTexture=Ot.create({width:this.opts.width,height:this.opts.height})),this.transBgGraphics||(this.transBgGraphics=new Je,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}));const b=v?this.getClipById(v):null,T=x?this.getClipById(x):null;let E=null,C=null;if(b){const P=Math.max(0,e-b.display.from),{video:_}=await b.getFrame(P);_ instanceof HTMLVideoElement?E=this.getVideoTexture(_):E=_,E&&(this.lastFromFrame=E)}if(T){const P=Math.max(0,e-T.display.from),{video:_}=await T.getFrame(P);_ instanceof HTMLVideoElement?C=this.getVideoTexture(_):C=_,C&&(this.lastToFrame=C)}if(E||(E=this.lastFromFrame),C||(C=this.lastToFrame),!E||!C)continue;if(E&&C&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const P=(e-f)/o?.transition?.duration;b&&E&&this.renderClipToTransitionTexture(b,E,this.transFromTexture),T&&C&&this.renderClipToTransitionTexture(T,C,this.transToTexture);let _=this.transitionRenderers.get(y);if(!_)try{_=x1({name:o?.transition?.name,renderer:this.pixiApp.renderer}),this.transitionRenderers.set(y,_)}catch(S){console.error("[Studio] Failed to create transition renderer:",S)}if(_){const S=_.render({width:this.opts.width,height:this.opts.height,from:this.transFromTexture,to:this.transToTexture,progress:P});let I=this.transitionSprites.get(o.id);I||(I=new $e,I.label=`TransitionSprite_${o.id}`,this.transitionSprites.set(o.id,I),this.clipsNormalContainer&&this.clipsNormalContainer.addChild(I)),I.texture=S,I.visible=!0,I.x=0,I.y=0,I.width=this.opts.width,I.height=this.opts.height,I.anchor.set(0,0),I.zIndex=o.zIndex,t.add(o.id);const M=this.spriteRenderers.get(o);M?.getRoot()&&(M.getRoot().visible=!1);const O=this.videoSprites.get(o);if(O&&(O.visible=!1),b){const H=this.spriteRenderers.get(b);H?.getRoot()&&(H.getRoot().visible=!1);const K=this.videoSprites.get(b);K&&(K.visible=!1)}if(T){const H=this.spriteRenderers.get(T);H?.getRoot()&&(H.getRoot().visible=!1);const K=this.videoSprites.get(T);K&&(K.visible=!1)}continue}}}const g=this.spriteRenderers.get(o);if(g!=null){const v=this.selectedClips.has(o);if(o.type!=="Text"&&o.type!=="Caption"&&typeof o.getTexture=="function"&&o.getTexture()!=null){const y=o.getTexture();if(y!=null){await g.updateFrame(y),v||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(o);continue}}if(o.type==="Text"){const y=o;this.pixiApp?.renderer&&typeof y.setRenderer=="function"&&y.setRenderer(this.pixiApp.renderer);const b=await y.getTexture();if(b!=null){await g.updateFrame(b),v||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(o);continue}}if(o.type==="Caption"){o.updateState(a);const y=o;this.pixiApp?.renderer&&typeof y.setRenderer=="function"&&y.setRenderer(this.pixiApp.renderer);const b=await y.getTexture();if(b!=null){await g.updateFrame(b),v||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(o);continue}}const{video:x}=await o.getFrame(a);await g.updateFrame(x),v||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(o)}}if(this.activeGlobalEffects.length>0&&this.clipsNormalContainer&&this.clipsEffectContainer){for(const o of this.clips)this.moveClipToEffectContainer(o,!1);this.clipsNormalContainer.visible=!0,await this.applyGlobalEffects(e)}else if(this.clipsNormalContainer){for(const o of this.clips)this.moveClipToEffectContainer(o,!1);this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}for(const[o,a]of this.transitionSprites.entries())t.has(o)||(a.visible=!1);this.pixiApp!=null&&this.pixiApp.render()}moveClipToEffectContainer(e,t=!0){if(!this.clipsNormalContainer||!this.clipsEffectContainer)return;const i=t?this.clipsEffectContainer:this.clipsNormalContainer,n=this.spriteRenderers.get(e);if(n){const o=n.getRoot();if(o&&o.parent!==i){try{o.parent&&o.parent.removeChild&&o.parent.removeChild(o)}catch(a){console.warn("moveClipToEffectContainer: could not remove root from parent",a)}i.addChild(o)}}const s=this.transitionSprites.get(e.id);if(s&&s.parent!==i){try{s.parent&&s.parent.removeChild&&s.parent.removeChild(s)}catch(o){console.warn("moveClipToEffectContainer: could not remove transSprite from parent",o)}i.addChild(s)}}applyGlobalEffect(e,t,i){const n=t.id||`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s={id:n,key:e,startTime:t.startTime,duration:t.duration??1e6};for(const o of i)o instanceof Fl&&o.addEffect(s),o instanceof wr&&o.addEffect(s),o instanceof Zi&&o.addEffect(s),o instanceof Nn&&o.addEffect(s);return this.globalEffects.set(n,s),n}getTrackIndex(e){return this.tracks.findIndex(t=>t.clipIds.includes(e))}async getTransitionFromFrame(e,t){let i=null;if(e.transition?.prevClipId&&(i=this.clips.find(a=>a.id===e.transition.prevClipId)||null),i||(i=this.getPreviousClipOnTrack(e)),!i)return null;const n=i.duration>0?i.duration:0,s=Math.max(0,Math.min(t-i.display.from,n)),{video:o}=await i.getFrame(s);return o}getPreviousClipOnTrack(e){const t=this.getTrackIndex(e.id);return t===-1?null:this.clips.filter(i=>i.id!==e.id&&this.getTrackIndex(i.id)===t&&i.display.from<e.display.from&&(i instanceof wr||i instanceof Fl)).sort((i,n)=>n.display.to-i.display.to)[0]||null}renderClipToTransitionTexture(e,t,i){if(!this.pixiApp)return;const n=e.style||{},{renderTransform:s}=e,o=(s?.mirror??0)>.5,a=t instanceof Q?t:Q.from(t),l=s?.x??0,u=s?.y??0,c=s?.angle??0,h=s?.scale??1,d=s?.opacity??1,f=s?.blur??0,p=s?.brightness??1,m=a.width||1,g=a.height||1,v=e.type==="Caption",x=!v&&e.width&&e.width!==0?Math.abs(e.width)/m:1,y=!v&&e.height&&e.height!==0?Math.abs(e.height)/g:1,b=new Ie;b.x=e.center.x+l,b.y=e.center.y+u,b.rotation=(e.flip==null?1:-1)*((e.angle+c)*Math.PI)/180,b.alpha=e.opacity*d;const T=new $e(a);T.anchor.set(.5,.5);let E=[];if(o){const D=x*h,k=y*h,W=m*D,G=g*k;T.position.set(0,0),T.scale.set(D,k);const J=[[W,0,-D,k],[-W,0,-D,k],[0,G,D,-k],[0,-G,D,-k],[W,G,-D,-k],[-W,G,-D,-k],[W,-G,-D,-k],[-W,-G,-D,-k]];for(const[q,_e,Re,ge]of J){const z=new $e(a);z.anchor.set(.5,.5),z.position.set(q,_e),z.scale.set(Re,ge),E.push(z)}if(e.flip==="horizontal"){T.scale.x=-D;for(let q=0;q<8;q++)E[q].scale.x=-J[q][2]}else if(e.flip==="vertical"){T.scale.y=-k;for(let q=0;q<8;q++)E[q].scale.y=-J[q][3]}b.addChild(T);for(const q of E)b.addChild(q)}else e.flip==="horizontal"?(T.scale.x=-x*h,T.scale.y=y*h):e.flip==="vertical"?(T.scale.x=x*h,T.scale.y=-y*h):(T.scale.x=x*h,T.scale.y=y*h),b.addChild(T);const C=[];if(f>0){const D=new Fn;D.strength=f,D.quality=4,D.repeatEdgePixels=!0,C.push(D)}const P=m1(e.colorAdjustment);if(p!==1||P){const D=new Zc;g1(D,e.colorAdjustment,p),C.push(D)}const _=Rh(e.colorAdjustment);for(let D=0;D<_.length;D++){const k=_[D],W=new nt({uTargetColor:{value:[1,1,0],type:"vec3<f32>"},uHueShift:{value:k.hue,type:"f32"},uSatShift:{value:k.saturation/100,type:"f32"},uLightShift:{value:k.lightness/100,type:"f32"},uTolerance:{value:.22,type:"f32"},uSoftness:{value:.12,type:"f32"}}),G=Rl(k.targetColor);G&&(W.uniforms.uTargetColor[0]=G.r/255,W.uniforms.uTargetColor[1]=G.g/255,W.uniforms.uTargetColor[2]=G.b/255);const J=new fe({glProgram:new le({vertex:Go,fragment:$b,name:`SelectiveHslShader_${D}`}),resources:{hslUniforms:W}});C.push(J)}b.filters=C;const S=n.borderRadius||0;let I=null;S>0&&(I=new Je,I.roundRect(-m/2,-g/2,m,g,Math.min(S,m/2,g/2)),I.fill({color:16777215,alpha:1}),T.addChild(I),T.mask=I);const M=n.stroke;let O=null;if(M&&M.width>0){O=new Je;const D=xt(M.color)??16777215;if(O.setStrokeStyle({width:M.width,color:D,alignment:1}),S>0){const k=Math.min(S,m/2,g/2);O.roundRect(-m/2,-g/2,m,g,k)}else O.rect(-m/2,-g/2,m,g);O.stroke(),T.addChild(O)}const H=n.dropShadow;let K=null;if(H&&(H.blur>0||H.distance>0)){K=new Je;const D=xt(H.color)??0,k=H.alpha??.5,W=H.distance??0,G=H.angle??0,J=Math.cos(G)*W,q=Math.sin(G)*W;if(S>0){const _e=Math.min(S,m/2,g/2);K.roundRect(-m/2+J,-g/2+q,m,g,_e)}else K.rect(-m/2+J,-g/2+q,m,g);K.fill({color:D,alpha:k}),b.addChildAt(K,0)}this.pixiApp.renderer.render({container:b,target:i,clear:!0}),t instanceof Q||T.texture.destroy(!0),I&&I.destroy(),O&&O.destroy(),K&&K.destroy();for(const D of E)D.destroy();T.destroy(),b.destroy()}removeGlobalEffect(e){this.globalEffects.delete(e)}clearGlobalEffects(){this.globalEffects.clear()}updateActiveGlobalEffect(e){const t=[];for(const i of this.clips)i instanceof Ji&&e>=i.display.from&&(i.display.to===0||e<i.display.to)&&t.push({id:i.id,key:i.effect.key,startTime:i.display.from,duration:i.duration>0?i.duration:i.display.to-i.display.from,trackIndex:this.getTrackIndex(i.id),values:i.effect.values});for(const i of this.globalEffects.values()){const n=i.startTime+i.duration;e>=i.startTime&&e<n&&t.push({id:i.id,key:i.key,startTime:i.startTime,duration:i.duration,trackIndex:-1})}this.activeGlobalEffects=t.sort((i,n)=>(n.trackIndex??-1)-(i.trackIndex??-1))}async applyGlobalEffects(e){if(this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null),this.activeGlobalEffects.length===0||!this.pixiApp||!this.clipContainer||!this.clipsNormalContainer||!this.clipsEffectContainer)return;const t=this.opts.width,i=this.opts.height;let n=null,s=new Set;const o=[];for(const a of this.activeGlobalEffects){const{key:l,startTime:u,duration:c,trackIndex:h,values:d}=a,f=e-u,p=Math.min(Math.max(f/c,0),1);if(p<0||p>=1)continue;if(this.clipsEffectContainer.visible=!0,this.clipsEffectContainer.removeChildren(),n){const y=new $e(n);y.label="PrevEffectResult",y.width=t,y.height=i,this.clipsEffectContainer.addChild(y)}const m=h??-1;for(const y of this.clips){if(s.has(y.id))continue;const b=this.getTrackIndex(y.id);!(y instanceof Ji)&&(m===-1||b>m)&&(this.moveClipToEffectContainer(y,!0),s.add(y.id))}let g=this.effectFilters.get(l);if(!g)try{if(g=await p1({name:l,renderer:this.pixiApp.renderer,values:d}),g)this.effectFilters.set(l,g);else continue}catch(y){console.error(y);continue}const v=Ot.create({width:t,height:i});o.push(v),this.pixiApp.renderer.render({container:this.clipsEffectContainer,target:v,clear:!0});const x=g.render({canvasTexture:v,progress:p,width:t,height:i,values:d});this.clipsEffectContainer.visible=!1,n=x}if(n){const a=new $e(n);a.x=0,a.y=0,a.width=t,a.height=i,a.scale.set(1),a.zIndex=5,this.clipContainer.addChild(a),this.currentGlobalEffectSprite=a}for(const a of o)a.destroy(!0)}destroy(){if(!this.destroyed){window.removeEventListener("resize",this.handleResize),this.destroyed=!0,this.stop(),this.clear(),this.transitionRenderers.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null);for(const e of this.transitionSprites.values())e.destroy();this.transitionSprites.clear(),this.pixiApp&&(this.pixiApp.destroy(!0,{children:!0,texture:!0}),this.pixiApp=null)}}selectClip(e,t=!1){this.selection.selectClip(e,t)}setSelection(e){this.selection.setSelection(e)}selectClipsByIds(e){this.selection.selectClipsByIds(e)}deselectClip(){this.selection.deselectClip()}async lockClip(e,t){const i=this.timeline.getClipById(e);i&&(await this.timeline.updateClip(e,{locked:t}),this.emit("clip:lock-changed",{clip:i,locked:t}),this.selection.selectedClips.has(i)&&this.selection.recreateTransformer(),await this.updateFrame(this.currentTime))}exportToJSON(){return this.timeline.exportToJSON()}async loadFromJSON(e){return this.timeline.loadFromJSON(e)}}xe.add(oC),xe.mixin(Ie,aC),xe.add(Hx),xe.add(Wx),xe.add(Xy),xe.mixin(Ie,_P),xe.add(Hy),xe.add(Cb),xe.add(Dc),xe.add(Eb),xe.add(kb),xe.add(Rb),xe.add(Yb),xe.add(Xb),xe.add(Nb),xe.add(Wb),xe.add(Gb),xe.add(Ub),xe.add(Mb),xe.add(t2),xe.add(Jy);const Mte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Dte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));we.ANIMATABLE_PROPERTIES=NL,we.Audio=ti,we.Caption=Nn,we.Compositor=Tte,we.DEFAULT_AUDIO_CONF=st,we.Effect=Ji,we.GL_EFFECT_OPTIONS=EQ,we.GL_TRANSITION_OPTIONS=wte,we.Image=Fl,we.KeyframeAnimation=B,we.Log=Ee,we.MP4Clip=wr,we.Placeholder=Ml,we.Studio=Fte,we.Text=Zi,we.Transition=Fi,we.VALUES_FILTER_SPECIAL=f1,we.VALUES_FILTER_SPECIAL_LIMITS=mee,we.Video=wr,we.animationRegistry=U,we.clipToJSON=Dl,we.createChromakey=kL,we.createSlowMo=cS,we.easings=Eu,we.fastConcatMP4=jk,we.fixFMP4Duration=Uq,we.fontManager=Y4,we.getAllEffects=e1,we.getAllTransitions=Ko,we.getEasing=J0,we.getEffectOptions=Jk,we.getPresetTemplate=X,we.getTransitionOptions=G4,we.jsonToClip=qo,we.makeEffect=p1,we.makeTransition=x1,we.mixinMP4AndAudio=Gq,we.registerCustomEffect=TQ,we.registerCustomTransition=bte,we.renderTxt2ImgBitmap=zL,we.unregisterCustomEffect=CQ,we.unregisterCustomTransition=_te,Object.defineProperty(we,Symbol.toStringTag,{value:"Module"})}));