openvideo 0.2.11 → 0.2.12

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 yk(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 bk(r,e){const t=Pi.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 _k(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 Ub{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===mr.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=Pt.get(Jy),a=mk(t,i),l=await xk(a),u=$y(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=yk(t,i,n,l,o);await _k(d,p,pk()&&a.length>0);const m=d;let g;this._createCanvas&&(g=bk(d,n));const v=Ob(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),Pi.returnCanvasAndContext(g)),Pt.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}}Ub.extension={type:[F.WebGLSystem,F.WebGPUSystem,F.CanvasSystem],name:"htmlText"};class zb extends Pe{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 It(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 wk=class Rh extends zb{constructor(e){const t={...Rh.defaultOptions,...e};super(t)}static from(e,t){const i={...Rh.defaultOptions,...t,text:e.text,style:new It(e.style)};return new Rh({...i})}splitFn(){return dk({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};wk.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let Il=wk;function aV(r,e,t){switch(r){case"center":return(t-e)/2;case"right":return t-e;case"left":default:return 0}}function Sk(r){return r==="\r"||r===`
3507
3507
  `||r===`\r
3508
3508
  `}function lV(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=Sk(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 Tk(r){const{text:e,style:t,chars:i}=r,n=t,s=Ht.measureText(e,n),o=Ht.graphemeSegmenter(e),a=lV(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 Pe({label:`line-${v}`});x.y=f,h.push(x);const y=s.lineWidths[v];let b=aV(l,y,u),T=new Pe({label:"word"});T.x=b,g.chars.forEach((P,A)=>{if(P.metric.width!==0){if(Sk(P.char)){b+=P.metric.width-p;return}if(P.char===" ")T.children.length>0&&(d.push(T),x.addChild(T)),b+=P.metric.width+n.letterSpacing-p,T=new Pe({label:"word"}),T.x=b;else{let E;i.length>0?(E=i.shift(),E.text=P.char,E.style=n,E.setFromMatrix(ae.IDENTITY),E.x=b-T.x-m*A):E=new Kc({text:P.char,style:n,x:b-T.x-m*A}),c.push(E),T.addChild(E),b+=P.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 Ck=class Fh extends zb{constructor(e){const t={...Fh.defaultOptions,...e};super(t)}static from(e,t){const i={...Fh.defaultOptions,...t,text:e.text,style:new It(e.style)};return new Fh({...i})}splitFn(){return Tk({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};Ck.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let uV=Ck;class Ak extends Al{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 Lb{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,mh(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 Ak(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}}Lb.extension={type:[F.WebGLPipes,F.WebGPUPipes,F.CanvasPipes],name:"text"};class Nb{constructor(e){this._activeTextures={},this._renderer=e}getTexture(e,t,i,n){typeof e=="string"&&(J("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:i,resolution:t}),e.style instanceof It||(e.style=new It(e.style)),e.textureStyle instanceof kr||(e.textureStyle=new kr(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}=Mo.getCanvasAndContext({text:s,style:o,resolution:l}),h=Ob(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),Mo.returnCanvasAndContext(c),d}return this._renderer.texture.initSource(h._source),Mo.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(){J("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}}Nb.extension={type:[F.WebGLSystem,F.WebGPUSystem,F.CanvasSystem],name:"canvasText"};const Ek=["align","breakWords","cssOverrides","fontVariant","fontWeight","leading","letterSpacing","lineHeight","padding","textBaseline","trim","whiteSpace","wordWrap","wordWrapWidth","fontFamily","fontStyle","fontSize"];function cV(r){const e=[];let t=0;for(let i=0;i<Ek.length;i++){const n=`_${Ek[i]}`;e[t++]=r[n]}return t=Pk(r._fill,e,t),t=dV(r._stroke,e,t),t=fV(r.dropShadow,e,t),t=hV(r.filters,e,t),e.join("-")}function hV(r,e,t){if(!r)return t;for(const i of r)e[t++]=i.uid;return t}function Pk(r,e,t){return r&&(e[t++]=r.color,e[t++]=r.alpha,e[t++]=r.fill?.styleKey),t}function dV(r,e,t){return r&&(t=Pk(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 fV(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 pV(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 mV=["#000080","#228B22","#8B0000","#4169E1","#008080","#800000","#9400D3","#FF8C00","#556B2F","#8B008B"];let gV=0;function Ik(r,e=0,t={color:"#000000"}){r.renderGroup&&(t.color=mV[gV++]);let i="";for(let o=0;o<e;o++)i+=" ";let n=r.label;!n&&r instanceof Je&&(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];Ik(a,e,{...t})}}function Bk(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];Bk(o,e,{...t,index:s})}}xe.add(O3,U3);const vV=Object.freeze(Object.defineProperty({__proto__:null,AbstractBitmapFont:zx,AbstractRenderer:$a,AbstractSplitText:zb,AbstractText:qc,AccessibilitySystem:$T,AlphaFilter:vP,AlphaMask:sx,AlphaMaskPipe:n2,AnimatedSprite:Tl,Application:gc,ApplicationInitHook:Mx,Assets:gs,AssetsClass:HE,BLEND_TO_NPM:lA,BUFFER_TYPE:Cl,BackgroundLoader:xE,BackgroundSystem:ZI,Batch:hA,BatchGeometry:vA,BatchTextureArray:cA,BatchableGraphics:Bc,BatchableHTMLText:fk,BatchableMesh:fh,BatchableSprite:Al,BatchableText:Ak,Batcher:mA,BatcherPipe:i2,BigPool:Pt,BindGroup:Ei,BindGroupSystem:rb,BitmapFont:vy,BitmapFontManager:Ao,BitmapText:Zy,BitmapTextGraphics:ck,BitmapTextPipe:Mb,BlendModeFilter:wt,BlendModePipe:V2,BlurFilter:ys,BlurFilterPass:ko,Bounds:Dt,BrowserAdapter:AT,Buffer:vr,BufferImageSource:Xu,BufferResource:th,BufferUsage:Ge,CLEAR:gr,Cache:Ke,CanvasObserver:fx,CanvasPool:Pi,CanvasPoolClass:dE,CanvasSource:Ci,CanvasTextGenerator:Mo,CanvasTextMetrics:Ht,CanvasTextPipe:Lb,CanvasTextSystem:Nb,Circle:sl,Color:ye,ColorBlend:wC,ColorBurnBlend:SC,ColorDodgeBlend:TC,ColorMask:ox,ColorMaskPipe:s2,ColorMatrixFilter:Ro,CompressedSource:ml,Container:Pe,Culler:nP,CullerPlugin:sP,CustomRenderPipe:U2,D3D10_RESOURCE_DIMENSION:Ry,D3DFMT:xr,DATA_URI:p7,DDS:Ce,DEG_TO_RAD:ns,DEPRECATED_SCALE_MODES:ch,DEPRECATED_WRAP_MODES:uh,DOMAdapter:Ee,DOMContainer:bH,DOMPipe:Oy,DRAW_MODES:FW,DXGI_FORMAT:ky,DXGI_TO_TEXTURE_FORMAT:yr,DarkenBlend:CC,DefaultBatcher:Pc,DefaultShader:Zx,DifferenceBlend:AC,DisplacementFilter:MH,DivideBlend:EC,DynamicBitmapFont:gy,Ellipse:vc,EventBoundary:fP,EventEmitter:fr,EventSystem:Ly,EventsTicker:Ii,ExclusionBlend:PC,ExtensionType:F,ExtractSystem:JI,FOURCC_TO_TEXTURE_FORMAT:Fy,FederatedContainer:pP,FederatedEvent:ho,FederatedMouseEvent:_l,FederatedPointerEvent:Zr,FederatedWheelEvent:xs,FillGradient:Dr,FillPattern:nl,Filter:ge,FilterEffect:Na,FilterPipe:Yy,FilterSystem:Ky,FontStylePromiseCache:gh,GAUSSIAN_VALUES:Gy,GL_FORMATS:$c,GL_INTERNAL_FORMAT:QE,GL_TARGETS:c2,GL_TYPES:Xe,GL_WRAP_MODES:uI,GenerateTextureSystem:q2,Geometry:fs,GlBackBufferSystem:dI,GlBatchAdaptor:e2,GlBuffer:aI,GlBufferSystem:a2,GlColorMaskSystem:f2,GlContextSystem:lI,GlEncoderSystem:p2,GlGeometrySystem:h2,GlGraphicsAdaptor:D2,GlLimitsSystem:m2,GlMeshAdaptor:O2,GlParticleContainerAdaptor:UB,GlParticleContainerPipe:Cb,GlProgram:ue,GlProgramData:SI,GlRenderTarget:fI,GlRenderTargetAdaptor:xI,GlRenderTargetSystem:T2,GlShaderSystem:I2,GlStateSystem:UI,GlStencilSystem:g2,GlTexture:zI,GlTextureSystem:M2,GlUboSystem:_2,GlUniformGroupSystem:B2,GlobalResourceRegistry:cs,GlobalUniformSystem:j2,GpuBatchAdaptor:t2,GpuBlendModesToPixi:nr,GpuBufferSystem:ib,GpuColorMaskSystem:nb,GpuDeviceSystem:lh,GpuEncoderSystem:sb,GpuGraphicsAdaptor:vb,GpuGraphicsContext:XA,GpuLimitsSystem:ob,GpuMeshAdapter:xb,GpuMipmapGenerator:xB,GpuParticleContainerAdaptor:zB,GpuParticleContainerPipe:Ab,GpuProgram:pe,GpuRenderTarget:fB,GpuRenderTargetAdaptor:pB,GpuRenderTargetSystem:hb,GpuShaderSystem:db,GpuStateSystem:fb,GpuStencilModesToPixi:ji,GpuStencilSystem:ab,GpuTextureSystem:gb,GpuUboSystem:lb,GpuUniformBatchPipe:ub,Graphics:Ze,GraphicsContext:ir,GraphicsContextRenderData:YA,GraphicsContextSystem:kc,GraphicsGpuData:TB,GraphicsPath:ai,GraphicsPipe:yb,HTMLText:tI,HTMLTextPipe:Db,HTMLTextRenderData:Jy,HTMLTextStyle:Qc,HTMLTextSystem:Ub,HardLightBlend:IC,HardMixBlend:BC,HelloSystem:ah,IGLUniformData:JH,ImageSource:jr,InstructionSet:rx,KTX:Tt,LightenBlend:kC,LinearBurnBlend:RC,LinearDodgeBlend:FC,LinearLightBlend:MC,Loader:PE,LoaderParserPriority:Rr,LuminosityBlend:DC,MaskEffectManager:qu,MaskEffectManagerClass:dT,MaskFilter:DP,Matrix:ae,Mesh:Fo,MeshGeometry:Bn,MeshGpuData:bb,MeshPipe:_b,MeshPlane:ZW,MeshRope:JW,MeshSimple:$W,NOOP:Wv,NegationBlend:OC,NineSliceGeometry:Fn,NineSlicePlane:sV,NineSliceSprite:KB,NineSliceSpriteGpuData:QB,NineSliceSpritePipe:Pb,NoiseFilter:DH,ObservablePoint:ot,OverlayBlend:UC,PI_2:L3,Particle:rV,ParticleBuffer:GB,ParticleContainer:nV,ParticleContainerPipe:Tb,ParticleShader:VB,PassthroughFilter:BP,PerspectiveMesh:QW,PerspectivePlaneGeometry:RB,PinLightBlend:zC,PipelineSystem:cb,PlaneGeometry:hh,Point:me,Polygon:vo,Pool:aT,PoolGroupClass:lT,PrepareBase:UP,PrepareQueue:YP,PrepareSystem:iI,PrepareUpload:rI,QuadGeometry:ek,RAD_TO_DEG:N3,Rectangle:he,RenderContainer:LW,RenderGroup:Qu,RenderGroupPipe:z2,RenderGroupSystem:G2,RenderLayer:VW,RenderTarget:eh,RenderTargetSystem:S2,RenderTexture:Ot,RenderableGCSystem:iB,RendererInitHook:Dx,RendererType:mr,ResizePlugin:Ox,Resolver:An,RopeGeometry:DB,RoundedRectangle:yc,SCALE_MODES:DW,STENCIL_MODES:St,SVGParser:sE,SaturationBlend:LC,SchedulerSystem:K2,ScissorMask:qH,SdfShader:uk,Shader:Fr,ShaderStage:mo,ShapePath:$A,SharedRenderPipes:tb,SharedSystems:eb,SoftLightBlend:NC,SplitBitmapText:Il,SplitText:uV,Sprite:Je,SpritePipe:H2,Spritesheet:dx,State:Mr,StencilMask:ax,StencilMaskPipe:o2,SubtractBlend:GC,SystemRunner:Fx,TEXTURE_FORMAT_BLOCK_SIZE:jE,Text:Kc,TextStyle:It,Texture:Q,TextureGCSystem:nB,TextureMatrix:Xv,TexturePool:ze,TexturePoolClass:TT,TextureSource:dt,TextureStyle:kr,TextureUvs:OW,Ticker:Ft,TickerListener:ic,TickerPlugin:Ux,TilingSprite:GP,TilingSpriteGpuData:nk,TilingSpritePipe:kb,TilingSpriteShader:$B,Transform:LP,Triangle:jy,UNIFORM_TO_ARRAY_SETTERS:FI,UNIFORM_TO_SINGLE_SETTERS:RI,UNIFORM_TYPES_MAP:pC,UNIFORM_TYPES_VALUES:bx,UPDATE_BLEND:ec,UPDATE_COLOR:Wa,UPDATE_PRIORITY:Ai,UPDATE_TRANSFORM:kG,UPDATE_VISIBLE:uo,UboBatch:uB,UboSystem:v2,UniformGroup:ft,VERSION:rl,VideoSource:co,ViewContainer:Ti,ViewSystem:$2,ViewableBuffer:ds,VividLightBlend:HC,WGSL_ALIGN_SIZE_DATA:Pl,WGSL_TO_STD40_SIZE:x2,WRAP_MODES:MW,WebGLRenderer:lB,WebGPURenderer:wB,WebWorkerAdapter:AH,WorkerManager:Sy,accessibilityTarget:eC,addBits:Vx,addMaskBounds:tc,addMaskLocalBounds:rc,addProgramDefines:iC,alphaFrag:mP,alphaWgsl:Ny,appendSVGPath:fy,applyMatrix:rk,applyProjectiveTransformationToPlane:EB,applyStyleParams:F2,assignWithIgnore:Zu,autoDetectEnvironment:QG,autoDetectRenderer:JC,autoDetectSource:MG,basisTranscoderUrls:Gc,bgr2rgb:lo,bitmapFontCachePlugin:gE,bitmapFontTextParser:Dc,bitmapFontXMLParser:xy,bitmapFontXMLStringParser:yy,bitmapTextSplit:dk,blendTemplateFrag:xC,blendTemplateVert:yC,blendTemplateWgsl:bC,blockDataMap:pb,blurTemplateWgsl:_P,boundsPool:Si,browserExt:O3,buildAdaptiveBezier:ny,buildAdaptiveQuadratic:qA,buildArc:ay,buildArcTo:jA,buildArcToSvg:QA,buildCircle:To,buildContextBatches:WA,buildEllipse:FA,buildGeometryFromPath:WW,buildLine:UA,buildPixelLine:zA,buildPolygon:LA,buildRectangle:NA,buildRoundedRectangle:MA,buildSimpleUvs:$x,buildTriangle:GA,buildUvs:Jx,cacheAsTextureMixin:uT,cacheTextureArray:yE,calculatePathArea:nE,calculateProjection:yI,canvasTextSplit:Tk,checkChildrenDidChange:tx,checkDataUrl:ms,checkExtension:Qr,checkForNestedPattern:rE,checkMaxIfStatementsInShader:Hx,childrenHelperMixin:cT,cleanArray:rB,cleanHash:tB,clearList:oh,closePointEps:ey,collectAllRenderables:NW,collectRenderablesMixin:hT,color32BitToUniform:Uo,colorBit:Sc,colorBitGl:Tc,colorMatrixFilterFrag:TP,colorMatrixFilterWgsl:Hy,colorToUniform:xW,compareModeToGlCompare:WI,compileHighShader:_A,compileHighShaderGl:wA,compileHighShaderGlProgram:_o,compileHighShaderGpuProgram:bo,compileHooks:Xx,compileInputs:Yx,compileOutputs:bA,compileShader:C2,compute2DProjection:kB,convertFormatIfRequired:uH,convertToList:Kr,copySearchParams:sc,createIdFromString:po,createIndicesForQuads:wb,createLevelBuffers:V9,createLevelBuffersFromKTX:cH,createStringVariations:RT,createTexture:In,createUboElementsSTD40:pI,createUboElementsWGSL:cB,createUboSyncFunction:y2,createUboSyncFunctionSTD40:vI,createUboSyncFunctionWGSL:dB,crossOrigin:UE,cullingMixin:sT,curveEps:ty,defaultFilterVert:Sl,defaultValue:E2,definedProps:ni,deprecation:J,detectAvif:bE,detectBasis:L9,detectCompressed:vH,detectDefaults:wE,detectMp4:SE,detectOgv:TE,detectVideoAlphaMode:ux,detectWebm:CE,detectWebp:AE,determineCrossOrigin:LE,displacementFrag:CP,displacementVert:AP,displacementWgsl:Wy,earcut:KC,effectsMixin:fT,ensureAttributes:u2,ensureIsBuffer:Wx,ensurePrecision:nC,ensureTextOptions:jc,executeInstructions:sh,extensions:xe,extractAttributesFromGlProgram:AI,extractAttributesFromGpuProgram:cC,extractFontFamilies:mk,extractStructAndGroups:uc,extractSubpaths:iE,extractSvgUrlId:cy,fastCopy:_c,findMixin:pT,fontStringFromTextStyle:il,formatShader:VH,fragmentGPUTemplate:AA,fragmentGlTemplate:PA,generateArraySyncSTD40:gI,generateArraySyncWGSL:hB,generateBlurFragSource:xP,generateBlurGlProgram:bP,generateBlurProgram:wP,generateBlurVertSource:yP,generateGPULayout:HH,generateGpuLayoutGroups:hC,generateLayout:WH,generateLayoutHash:dC,generateParticleUpdateFunction:LB,generateProgram:kI,generateShaderSyncCode:wI,generateTextStyleKey:cV,generateTextureBatchBit:Cc,generateTextureBatchBitGl:Ac,generateTextureMatrix:HA,generateUniformsSync:MI,getAdjustedBlendModeBlend:xo,getAttributeInfoFromFormat:Xi,getBatchSamplersUniformGroup:Ec,getBitmapTextLayout:Fc,getCanvasBoundingBox:VP,getCanvasFillStyle:fl,getCanvasTexture:w2,getDefaultUniformValue:mC,getFastGlobalBounds:zW,getFastGlobalBoundsMixin:mT,getFillInstructionData:n9,getFontCss:xk,getFontFamilyName:kE,getGeometryBounds:gA,getGlTypeFromFormat:hI,getGlobalBounds:Ga,getGlobalMixin:xT,getGlobalRenderableBounds:RP,getLocalBounds:Ku,getMaxFragmentPrecision:rC,getMaxTexturesPerBatch:uA,getOrientationOfPoints:DA,getPo2TextureFromSource:Ob,getResolutionOfUrl:Oc,getSVGUrl:yk,getSupportedCompressedTextureFormats:By,getSupportedGPUCompressedTextureFormats:Iy,getSupportedGlCompressedTextureFormats:Py,getSupportedTextureFormats:gl,getTemporaryCanvasFromImage:bk,getTestContext:xx,getTextureBatchBindGroup:bc,getTextureDefaultMatrix:eV,getTextureFormatFromKTXTexture:fH,getUboData:EI,getUniformData:PI,getUrlExtension:FT,glFormatToGPUFormat:rP,glUploadBufferImageResource:LI,glUploadCompressedTextureResource:NI,glUploadImageResource:k2,glUploadVideoResource:GI,globalUniformsBit:IA,globalUniformsBitGl:BA,globalUniformsUBOBitGl:M7,gpuFormatToBasisTranscoderFormat:Y9,gpuFormatToKTXBasisTranscoderFormat:mH,gpuUploadBufferImageResource:mB,gpuUploadCompressedTextureResource:gB,gpuUploadImageResource:mb,gpuUploadVideoResource:vB,groupD8:Be,hasCachedCanvasTexture:ZH,hslWgsl:zH,hslgl:cc,hslgpu:hc,injectBits:qx,insertVersion:sC,isMobile:KT,isPow2:Vv,isRenderingToScreen:bI,isSafari:pk,isSingleItem:Xa,isWebGLSupported:el,isWebGPUSupported:tl,ktxTranscoderUrls:Hc,loadBasis:W9,loadBasisOnWorker:qE,loadBitmapFont:vE,loadDDS:$9,loadEnvironmentExtensions:Ix,loadFontAsBase64:gk,loadFontCSS:vk,loadImageBitmap:OE,loadJson:IE,loadKTX:nH,loadKTX2:lH,loadKTX2onWorker:eP,loadSVGImage:_k,loadSvg:FE,loadTextures:Ty,loadTxt:BE,loadVideoTextures:NE,loadWebFont:RE,localUniformBit:Do,localUniformBitGl:Jc,localUniformBitGroup2:nI,localUniformMSDFBit:sk,localUniformMSDFBitGl:ok,log2:gG,logDebugTexture:pV,logProgramError:BI,logRenderGroupScene:Bk,logScene:Ik,mSDFBit:ak,mSDFBitGl:lk,mapFormatToGlFormat:VI,mapFormatToGlInternalFormat:XI,mapFormatToGlType:YI,mapGlToVertexFormat:CI,mapSize:rW,mapType:P2,mapWebGLBlendModesToPixi:DI,maskFrag:FP,maskVert:MP,maskWgsl:Qy,matrixPool:Zt,measureHtmlText:$y,measureMixin:bT,migrateFragmentFromV7toV8:eW,mipmapScaleModeToGlFilter:HI,multiplyColors:Ha,multiplyHexColors:ex,nextPow2:us,noiseFrag:EP,noiseWgsl:Vy,nonCompressedFormats:VE,normalizeExtensionPriority:Ua,onRenderMixin:_T,parseDDS:KE,parseFunctionBody:UW,parseKTX:ZE,parseSVGDefinitions:eE,parseSVGFloatAttribute:xt,parseSVGPath:oA,parseSVGStyle:dy,particleData:Eb,particlesFrag:HB,particlesVert:WB,particlesWgsl:Sb,passthroughFrag:IP,passthroughWgsl:Xy,path:pr,pointInTriangle:qy,preloadVideo:zE,removeItems:$v,removeStructAndGroupDuplicates:fC,resetUids:mG,resolveCharacters:mE,resolveCompressedTextureUrl:gH,resolveJsonUrl:GE,resolveTextureUrl:Ey,resourceToTexture:IT,roundPixelsBit:wo,roundPixelsBitGl:So,roundedShapeArc:ZA,roundedShapeQuadraticCurve:JA,sayHello:eB,scaleModeToGlFilter:R2,setBasisTranscoderPath:G9,setKTXTranscoderPath:oH,setPositions:tk,setProgramName:oC,setUvs:ik,shapeBuilders:Co,sortMixin:wT,spritesheetAsset:OT,squaredDistanceToLineSegment:ol,stripVersion:aC,styleAttributes:hy,testImageFormat:by,testVideoFormat:pl,textStyleToCSS:qP,textureBit:sI,textureBitGl:oI,textureFrom:BT,tilingBit:ZB,tilingBitGl:JB,toFillStyle:Pn,toLocalGlobalMixin:ST,toStrokeStyle:dl,transformVertices:Ic,triangulateWithHoles:ry,uboSyncFunctionsSTD40:b2,uboSyncFunctionsWGSL:mI,uid:tt,uniformParsers:kn,unpremultiplyAlpha:cW,unsafeEvalSupported:Bx,updateLocalTransform:GW,updateQuadBounds:Yv,updateRenderGroupTransform:jI,updateRenderGroupTransforms:L2,updateTextBounds:mh,updateTransformAndChildren:N2,updateTransformBackwards:ju,updateWorldTransform:HW,v8_0_0:Te,v8_3_4:W3,validFormats:Wc,validateRenderables:QI,vertexGPUTemplate:CA,vertexGlTemplate:EA,vkFormatToGPUFormat:iP,warn:de,webworkerExt:U3,wrapModeToGlAddress:nh},Symbol.toStringTag,{value:"Module"}));Fv.registerPlugin(Uv),Uv.registerPIXI(vV);class Ct{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=Fv.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 xV=(r,e)=>{const t=L(e),i=Math.max(r.duration/1e6,1),n=t?.easing||r.easing||"easeOutQuad",s=V("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")},yV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("fadeIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fadeIn"):new B(n,{...r,easing:i},"fadeIn")},bV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInQuad",n=V("fadeOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fadeOut"):new B(n,{...r,easing:i},"fadeOut")},_V=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutCubic",n=V("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},wV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInCubic",n=V("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},SV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutBack",n=V("zoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomIn"):new B(n,{...r,easing:i},"zoomIn")},TV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInBack",n=V("zoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomOut"):new B(n,{...r,easing:i},"zoomOut")},CV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("blurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurIn"):new B(n,{...r,easing:i},"blurIn")},AV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInQuad",n=V("blurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurOut"):new B(n,{...r,easing:i},"blurOut")},EV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("motionBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"motionBlurIn"):new B(n,{...r,easing:i},"motionBlurIn")},PV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeInQuad",n=V("motionBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"motionBlurOut"):new B(n,{...r,easing:i},"motionBlurOut")},IV=(r,e)=>{const t=L(e);return new Ct({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")},BV=(r,e)=>{const t=L(e);return new Ct({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")},kV=(r,e)=>{const t=L(e);return new Ct({type:"character",from:{alpha:0},to:{alpha:1,duration:.001},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"none"},"charTypewriter")},RV=(r,e)=>{const t=L(e);return new Ct({type:"word",from:{alpha:0},to:{alpha:1},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"none"},"fadeByWord")},FV=(r,e)=>{const t=L(e);return new Ct({type:"word",from:{alpha:0,x:"+=50"},to:{alpha:1,x:"-=50"},stagger:t?.stagger??.05},{...r,easing:t?.easing||r.easing||"none"},"slideFadeByWord")},MV=(r,e)=>{const t=L(e);return new Ct({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")},DV=(r,e)=>{const t=L(e);return new Ct({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")},OV=(r,e)=>{const t=L(e);return new Ct({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")},UV=(r,e)=>{const t=L(e);return new Ct({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")},zV=(r,e)=>{const t=L(e);return new Ct({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")},LV=(r,e)=>{const t=L(e);return new Ct({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")},NV=(r,e)=>{const t=L(e);return new Ct({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")},GV=(r,e)=>{const t=L(e);return new Ct({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")},HV=(r,e)=>{const t=L(e);return new Ct({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")},WV=(r,e)=>{const t=L(e);return new Ct({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")},VV=(r,e)=>{const t=L(e);return new Ct({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")},XV=(r,e)=>{const t=L(e);return new Ct({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")},YV=(r,e)=>{const t=L(e);return new Ct({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")},qV=(r,e)=>{const t=L(e);return new Ct({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")},jV=(r,e)=>{const t=L(e);return new Ct({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")},KV=(r,e)=>{const t=L(e);return new Ct({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")},QV=(r,e)=>{const t=L(e);return new Ct({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")},ZV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("blurSlideRightIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideRightIn"):new B(n,{...r,easing:i},"blurSlideRightIn")},JV=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("wobbleZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"wobbleZoomIn"):new B(n,{...r,easing:i},"wobbleZoomIn")},$V=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("spinZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spinZoomIn"):new B(n,{...r,easing:i},"spinZoomIn")},eX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("blurSlideLeftIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideLeftIn"):new B(n,{...r,easing:i},"blurSlideLeftIn")},tX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("blurSlideRightStrongIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideRightStrongIn"):new B(n,{...r,easing:i},"blurSlideRightStrongIn")},rX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("cinematicZoomSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"cinematicZoomSlideIn"):new B(n,{...r,easing:i},"cinematicZoomSlideIn")},iX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("elasticTwistIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"elasticTwistIn"):new B(n,{...r,easing:i},"elasticTwistIn")},nX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("spinFadeIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spinFadeIn"):new B(n,{...r,easing:i},"spinFadeIn")},sX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("flashZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"flashZoomIn"):new B(n,{...r,easing:i},"flashZoomIn")},oX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("tiltSlideRightIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltSlideRightIn"):new B(n,{...r,easing:i},"tiltSlideRightIn")},aX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("tiltZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltZoomIn"):new B(n,{...r,easing:i},"tiltZoomIn")},lX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("glitchSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"glitchSlideIn"):new B(n,{...r,easing:i},"glitchSlideIn")},uX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("dropBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dropBlurIn"):new B(n,{...r,easing:i},"dropBlurIn")},cX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("fallZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fallZoomIn"):new B(n,{...r,easing:i},"fallZoomIn")},hX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("zoomSpinIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomSpinIn"):new B(n,{...r,easing:i},"zoomSpinIn")},dX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("dramaticSpinSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dramaticSpinSlideIn"):new B(n,{...r,easing:i},"dramaticSpinSlideIn")},fX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("tiltSlideRightOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltSlideRightOut"):new B(n,{...r,easing:i},"tiltSlideRightOut")},pX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("tiltZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltZoomOut"):new B(n,{...r,easing:i},"tiltZoomOut")},mX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("glitchSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"glitchSlideOut"):new B(n,{...r,easing:i},"glitchSlideOut")},gX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("dropBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dropBlurOut"):new B(n,{...r,easing:i},"dropBlurOut")},vX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("fallZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fallZoomOut"):new B(n,{...r,easing:i},"fallZoomOut")},xX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("zoomSpinOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomSpinOut"):new B(n,{...r,easing:i},"zoomSpinOut")},yX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("dramaticSpinSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dramaticSpinSlideOut"):new B(n,{...r,easing:i},"dramaticSpinSlideOut")},bX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("blurSlideRightOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideRightOut"):new B(n,{...r,easing:i},"blurSlideRightOut")},_X=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("wobbleZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"wobbleZoomOut"):new B(n,{...r,easing:i},"wobbleZoomOut")},wX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("spinZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spinZoomOut"):new B(n,{...r,easing:i},"spinZoomOut")},SX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("blurSlideLeftOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideLeftOut"):new B(n,{...r,easing:i},"blurSlideLeftOut")},TX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("blurSlideRightStrongOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"blurSlideRightStrongOut"):new B(n,{...r,easing:i},"blurSlideRightStrongOut")},CX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("cinematicZoomSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"cinematicZoomSlideOut"):new B(n,{...r,easing:i},"cinematicZoomSlideOut")},AX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("elasticTwistOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"elasticTwistOut"):new B(n,{...r,easing:i},"elasticTwistOut")},EX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("spinFadeOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spinFadeOut"):new B(n,{...r,easing:i},"spinFadeOut")},PX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("flashZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"flashZoomOut"):new B(n,{...r,easing:i},"flashZoomOut")},IX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideRotateIn"):new B(n,{...r,easing:i},"slideRotateIn")},BX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideRotateOut"):new B(n,{...r,easing:i},"slideRotateOut")},kX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideBlurIn"):new B(n,{...r,easing:i},"slideBlurIn")},RX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideBlurOut"):new B(n,{...r,easing:i},"slideBlurOut")},FX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("zoomRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomRotateIn"):new B(n,{...r,easing:i},"zoomRotateIn")},MX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("zoomRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomRotateOut"):new B(n,{...r,easing:i},"zoomRotateOut")},DX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("zoomBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomBlurIn"):new B(n,{...r,easing:i},"zoomBlurIn")},OX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("zoomBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomBlurOut"):new B(n,{...r,easing:i},"zoomBlurOut")},UX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideZoomIn"):new B(n,{...r,easing:i},"slideZoomIn")},zX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideZoomOut"):new B(n,{...r,easing:i},"slideZoomOut")},LX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("verticalBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"verticalBlurIn"):new B(n,{...r,easing:i},"verticalBlurIn")},NX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("verticalBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"verticalBlurOut"):new B(n,{...r,easing:i},"verticalBlurOut")},GX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("rotateBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"rotateBlurIn"):new B(n,{...r,easing:i},"rotateBlurIn")},HX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("rotateBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"rotateBlurOut"):new B(n,{...r,easing:i},"rotateBlurOut")},WX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("cinematicSlideZoomBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"cinematicSlideZoomBlurIn"):new B(n,{...r,easing:i},"cinematicSlideZoomBlurIn")},VX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("cinematicSlideZoomBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"cinematicSlideZoomBlurOut"):new B(n,{...r,easing:i},"cinematicSlideZoomBlurOut")},XX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("brightnessZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"brightnessZoomIn"):new B(n,{...r,easing:i},"brightnessZoomIn")},YX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("brightnessZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"brightnessZoomOut"):new B(n,{...r,easing:i},"brightnessZoomOut")},qX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("brightnessSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"brightnessSlideIn"):new B(n,{...r,easing:i},"brightnessSlideIn")},jX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("brightnessSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"brightnessSlideOut"):new B(n,{...r,easing:i},"brightnessSlideOut")},KX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("tiltZoomBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltZoomBlurIn"):new B(n,{...r,easing:i},"tiltZoomBlurIn")},QX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("tiltZoomBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"tiltZoomBlurOut"):new B(n,{...r,easing:i},"tiltZoomBlurOut")},ZX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("dropRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dropRotateIn"):new B(n,{...r,easing:i},"dropRotateIn")},JX=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("dropRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"dropRotateOut"):new B(n,{...r,easing:i},"dropRotateOut")},$X=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("spiralIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spiralIn"):new B(n,{...r,easing:i},"spiralIn")},eY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("spiralOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"spiralOut"):new B(n,{...r,easing:i},"spiralOut")},tY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("flashSlideIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"flashSlideIn"):new B(n,{...r,easing:i},"flashSlideIn")},rY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("flashSlideOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"flashSlideOut"):new B(n,{...r,easing:i},"flashSlideOut")},iY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("heavyCinematicIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"heavyCinematicIn"):new B(n,{...r,easing:i},"heavyCinematicIn")},nY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("heavyCinematicOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"heavyCinematicOut"):new B(n,{...r,easing:i},"heavyCinematicOut")},sY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("diagonalSlideRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"diagonalSlideRotateIn"):new B(n,{...r,easing:i},"diagonalSlideRotateIn")},oY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("diagonalSlideRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"diagonalSlideRotateOut"):new B(n,{...r,easing:i},"diagonalSlideRotateOut")},aY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("diagonalBlurZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"diagonalBlurZoomIn"):new B(n,{...r,easing:i},"diagonalBlurZoomIn")},lY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("diagonalBlurZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"diagonalBlurZoomOut"):new B(n,{...r,easing:i},"diagonalBlurZoomOut")},uY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("rotateBrightnessIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"rotateBrightnessIn"):new B(n,{...r,easing:i},"rotateBrightnessIn")},cY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("rotateBrightnessOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"rotateBrightnessOut"):new B(n,{...r,easing:i},"rotateBrightnessOut")},hY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("zoomBrightnessBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomBrightnessBlurIn"):new B(n,{...r,easing:i},"zoomBrightnessBlurIn")},dY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("zoomBrightnessBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"zoomBrightnessBlurOut"):new B(n,{...r,easing:i},"zoomBrightnessBlurOut")},fY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideUpRotateZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideUpRotateZoomIn"):new B(n,{...r,easing:i},"slideUpRotateZoomIn")},pY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideUpRotateZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideUpRotateZoomOut"):new B(n,{...r,easing:i},"slideUpRotateZoomOut")},mY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("fallBlurRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fallBlurRotateIn"):new B(n,{...r,easing:i},"fallBlurRotateIn")},gY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("fallBlurRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fallBlurRotateOut"):new B(n,{...r,easing:i},"fallBlurRotateOut")},vY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("sideStretchZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"sideStretchZoomIn"):new B(n,{...r,easing:i},"sideStretchZoomIn")},xY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("sideStretchZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"sideStretchZoomOut"):new B(n,{...r,easing:i},"sideStretchZoomOut")},yY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("darkSlideBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"darkSlideBlurIn"):new B(n,{...r,easing:i},"darkSlideBlurIn")},bY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("darkSlideBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"darkSlideBlurOut"):new B(n,{...r,easing:i},"darkSlideBlurOut")},_Y=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("liftZoomRotateIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"liftZoomRotateIn"):new B(n,{...r,easing:i},"liftZoomRotateIn")},wY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("liftZoomRotateOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"liftZoomRotateOut"):new B(n,{...r,easing:i},"liftZoomRotateOut")},SY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("overexposedZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"overexposedZoomIn"):new B(n,{...r,easing:i},"overexposedZoomIn")},TY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("overexposedZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"overexposedZoomOut"):new B(n,{...r,easing:i},"overexposedZoomOut")},CY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("pushDownZoomBlurIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"pushDownZoomBlurIn"):new B(n,{...r,easing:i},"pushDownZoomBlurIn")},AY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("pushDownZoomBlurOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"pushDownZoomBlurOut"):new B(n,{...r,easing:i},"pushDownZoomBlurOut")},EY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("twistSlideBrightnessIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"twistSlideBrightnessIn"):new B(n,{...r,easing:i},"twistSlideBrightnessIn")},PY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("twistSlideBrightnessOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"twistSlideBrightnessOut"):new B(n,{...r,easing:i},"twistSlideBrightnessOut")},IY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("collapseRotateZoomIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"collapseRotateZoomIn"):new B(n,{...r,easing:i},"collapseRotateZoomIn")},BY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("collapseRotateZoomOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"collapseRotateZoomOut"):new B(n,{...r,easing:i},"collapseRotateZoomOut")},kY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("ultraCinematicIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"ultraCinematicIn"):new B(n,{...r,easing:i},"ultraCinematicIn")},RY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("ultraCinematicOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"ultraCinematicOut"):new B(n,{...r,easing:i},"ultraCinematicOut")},FY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("popCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"popCaption"):new B(n,{...r,easing:i},"popCaption")},MY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("bounceCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"bounceCaption"):new B(n,{...r,easing:i},"bounceCaption")},DY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("scaleCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"scaleCaption"):new B(n,{...r,easing:i},"scaleCaption")},OY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideLeftCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideLeftCaption"):new B(n,{...r,easing:i},"slideLeftCaption")},UY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideRightCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideRightCaption"):new B(n,{...r,easing:i},"slideRightCaption")},zY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideUpCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideUpCaption"):new B(n,{...r,easing:i},"slideUpCaption")},LY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("slideDownCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"slideDownCaption"):new B(n,{...r,easing:i},"slideDownCaption")},NY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("fadeCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"fadeCaption"):new B(n,{...r,easing:i},"fadeCaption")},GY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("scaleMidCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"scaleMidCaption"):new B(n,{...r,easing:i},"scaleMidCaption")},HY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("scaleDownCaption",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"scaleDownCaption"):new B(n,{...r,easing:i},"scaleDownCaption")},WY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("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")},VY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"easeOutQuad",n=V("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")},XY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboZoom1",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboZoom1"):new B(n,{...r,easing:i},"comboZoom1")},YY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboZoom2",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboZoom2"):new B(n,{...r,easing:i},"comboZoom2")},qY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboPendulum1",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboPendulum1"):new B(n,{...r,easing:i},"comboPendulum1")},jY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboPendulum2",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboPendulum2"):new B(n,{...r,easing:i},"comboPendulum2")},KY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboRightDistort",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboRightDistort"):new B(n,{...r,easing:i},"comboRightDistort")},QY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboLeftDistort",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboLeftDistort"):new B(n,{...r,easing:i},"comboLeftDistort")},ZY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboWobble",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboWobble"):new B(n,{...r,easing:i},"comboWobble")},JY=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboSpinningTop1",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboSpinningTop1"):new B(n,{...r,easing:i},"comboSpinningTop1")},$Y=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboSwayOut",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboSwayOut"):new B(n,{...r,easing:i},"comboSwayOut")},eq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboBounce1",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboBounce1"):new B(n,{...r,easing:i},"comboBounce1")},tq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboSwayIn",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboSwayIn"):new B(n,{...r,easing:i},"comboSwayIn")},rq=(r,e)=>{const t=L(e),i=t?.easing||r.easing||"linear",n=V("comboSpinningTop2",e);return t&&(t["0%"]||t["100%"])?new B(t,{...r,easing:i},"comboSpinningTop2"):new B(n,{...r,easing:i},"comboSpinningTop2")};z.register("fadeIn",yV),z.register("fadeOut",bV),z.register("slideIn",_V),z.register("slideOut",wV),z.register("zoomIn",SV),z.register("zoomOut",TV),z.register("charFadeIn",IV),z.register("charSlideUp",BV),z.register("charTypewriter",kV),z.register("fadeByWord",RV),z.register("slideFadeByWord",FV),z.register("popByWord",MV),z.register("scaleFadeByWord",DV),z.register("bounceByWord",OV),z.register("rotateInByWord",UV),z.register("slideRightByWord",zV),z.register("slideLeftByWord",LV),z.register("fadeRotateByWord",NV),z.register("skewByWord",GV),z.register("waveByWord",HV),z.register("blurInByWord",WV),z.register("dropSoftByWord",VV),z.register("elasticPopByWord",XV),z.register("flipUpByWord",YV),z.register("spinInByWord",qV),z.register("stretchInByWord",jV),z.register("revealZoomByWord",KV),z.register("floatWaveByWord",QV),z.register("pulse",xV),z.register("blurIn",CV),z.register("blurOut",AV),z.register("blurSlideRightIn",ZV),z.register("wobbleZoomIn",JV),z.register("spinZoomIn",$V),z.register("blurSlideLeftIn",eX),z.register("blurSlideRightStrongIn",tX),z.register("cinematicZoomSlideIn",rX),z.register("elasticTwistIn",iX),z.register("spinFadeIn",nX),z.register("flashZoomIn",sX),z.register("tiltSlideRightIn",oX),z.register("tiltZoomIn",aX),z.register("glitchSlideIn",lX),z.register("dropBlurIn",uX),z.register("fallZoomIn",cX),z.register("zoomSpinIn",hX),z.register("dramaticSpinSlideIn",dX),z.register("tiltSlideRightOut",fX),z.register("tiltZoomOut",pX),z.register("glitchSlideOut",mX),z.register("dropBlurOut",gX),z.register("fallZoomOut",vX),z.register("zoomSpinOut",xX),z.register("dramaticSpinSlideOut",yX),z.register("blurSlideRightOut",bX),z.register("wobbleZoomOut",_X),z.register("spinZoomOut",wX),z.register("blurSlideLeftOut",SX),z.register("blurSlideRightStrongOut",TX),z.register("cinematicZoomSlideOut",CX),z.register("elasticTwistOut",AX),z.register("spinFadeOut",EX),z.register("flashZoomOut",PX),z.register("slideRotateIn",IX),z.register("slideRotateOut",BX),z.register("slideBlurIn",kX),z.register("slideBlurOut",RX),z.register("zoomRotateIn",FX),z.register("zoomRotateOut",MX),z.register("zoomBlurIn",DX),z.register("zoomBlurOut",OX),z.register("slideZoomIn",UX),z.register("slideZoomOut",zX),z.register("verticalBlurIn",LX),z.register("verticalBlurOut",NX),z.register("rotateBlurIn",GX),z.register("rotateBlurOut",HX),z.register("cinematicSlideZoomBlurIn",WX),z.register("cinematicSlideZoomBlurOut",VX),z.register("brightnessZoomIn",XX),z.register("brightnessZoomOut",YX),z.register("brightnessSlideIn",qX),z.register("brightnessSlideOut",jX),z.register("tiltZoomBlurIn",KX),z.register("tiltZoomBlurOut",QX),z.register("dropRotateIn",ZX),z.register("dropRotateOut",JX),z.register("spiralIn",$X),z.register("spiralOut",eY),z.register("flashSlideIn",tY),z.register("flashSlideOut",rY),z.register("heavyCinematicIn",iY),z.register("heavyCinematicOut",nY),z.register("diagonalSlideRotateIn",sY),z.register("diagonalSlideRotateOut",oY),z.register("diagonalBlurZoomIn",aY),z.register("diagonalBlurZoomOut",lY),z.register("rotateBrightnessIn",uY),z.register("rotateBrightnessOut",cY),z.register("zoomBrightnessBlurIn",hY),z.register("zoomBrightnessBlurOut",dY),z.register("slideUpRotateZoomIn",fY),z.register("slideUpRotateZoomOut",pY),z.register("fallBlurRotateIn",mY),z.register("fallBlurRotateOut",gY),z.register("sideStretchZoomIn",vY),z.register("sideStretchZoomOut",xY),z.register("darkSlideBlurIn",yY),z.register("darkSlideBlurOut",bY),z.register("liftZoomRotateIn",_Y),z.register("liftZoomRotateOut",wY),z.register("overexposedZoomIn",SY),z.register("overexposedZoomOut",TY),z.register("pushDownZoomBlurIn",CY),z.register("pushDownZoomBlurOut",AY),z.register("twistSlideBrightnessIn",EY),z.register("twistSlideBrightnessOut",PY),z.register("collapseRotateZoomIn",IY),z.register("collapseRotateZoomOut",BY),z.register("ultraCinematicIn",kY),z.register("ultraCinematicOut",RY),z.register("motionBlurIn",EV),z.register("motionBlurOut",PV),z.register("popCaption",FY),z.register("bounceCaption",MY),z.register("scaleCaption",DY),z.register("slideLeftCaption",OY),z.register("slideRightCaption",UY),z.register("slideUpCaption",zY),z.register("slideDownCaption",LY),z.register("fadeCaption",NY),z.register("scaleMidCaption",GY),z.register("scaleDownCaption",HY),z.register("upDownCaption",WY),z.register("upLeftCaption",VY),z.register("comboZoom1",XY),z.register("comboZoom2",YY),z.register("comboPendulum1",qY),z.register("comboPendulum2",jY),z.register("comboRightDistort",KY),z.register("comboLeftDistort",QY),z.register("comboWobble",ZY),z.register("comboSpinningTop1",JY),z.register("comboSwayOut",$Y),z.register("comboBounce1",eq),z.register("comboSwayIn",tq),z.register("comboSpinningTop2",rq);function V(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 iq extends X0{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};_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=nq(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=z.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=z.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.locked=this.locked,"src"in this&&"src"in e&&(e.src=this.src)}update(e){Object.assign(this,e),this.emit("propsChange",e)}destroy(){this.all.clear()}}function nq(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 Mn extends iq{lastVf=null;destroyed=!1;src="";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=>tS(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=>tS(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){if(e.display&&(e.display.from!==void 0&&(this.display.from=e.display.from<1e6?e.display.from/t*1e6:e.display.from),e.display.to!==void 0&&(this.display.to=e.display.to<1e6?e.display.to/t*1e6: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){const i=e.duration<1e6?e.duration/t*1e6:e.duration;this.duration=i,this.display.from!==void 0&&(this.display.to=this.display.from+i)}return 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,locked:this.locked}}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,Ue.info("BaseClip destroy"),super.destroy(),this.lastVf?.close(),this.lastVf=null)}}let Gb=null;async function kk(){return Gb===null&&(Gb=fL()),await Gb}const rt={get codec(){return bu()?.codec??"mp4a.40.2"},get codecType(){return bu()?.codecType??"aac"},get sampleRate(){return bu()?.sampleRate??48e3},get channelCount(){return bu()?.channelCount??2}};class zo{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=jn(i);return await n.exists()?n:null}static async put(e,t){const i=await this.getCacheKey(e),n=this.getPath(i),s=jn(n);return await Vs(s,t),s}}class Lo{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 zo.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 zo.put(e,o).catch(a=>{console.error(`ResourceManager: Failed to cache ${e}`,a)}),s}static async getImageBitmap(e){const t=await zo.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 zo.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 zo.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 zo.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 Jr extends Mn{type="Audio";static ctx=null;ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta,sampleRate:rt.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 Lo.getReadableStream(e);return new Jr(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 Jr.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){Jr.ctx==null&&(Jr.ctx=new AudioContext({sampleRate:rt.sampleRate}));const t=performance.now(),i=e instanceof ReadableStream?await oq(e,Jr.ctx):e;Ue.info("Audio clip decoded complete:",performance.now()-t),this._meta.duration=i[0].length/rt.sampleRate*1e6,this.chan0Buf=i[0],this.chan1Buf=i[1]??this.chan0Buf,Ue.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*rt.sampleRate),await this.tickInterceptor(e,{audio:[new Float32Array(0),new Float32Array(0)],state:"success"});this.timestamp=e;const i=Math.ceil(t/1e6*rt.sampleRate),n=this.frameOffset+i,s=this.opts.loop?[W0(this.chan0Buf,this.frameOffset,n),W0(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*rt.sampleRate),i=new Jr(this.getPCMData().map(s=>s.slice(0,t)),this.opts,this.src),n=new Jr(this.getPCMData().map(s=>s.slice(t)),this.opts,this.src);return[i,n]}async clone(){await this.ready;const e=new Jr(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),Ue.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=sq;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 sq(r,e){const t=[];for(const i of r)await i.ready,t.push(i.getPCMData());return new Jr(Jw(t),e)}async function oq(r,e){const t=await new Response(r).arrayBuffer();return H0(await e.decodeAudioData(t))}function yt(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 Rk=r=>r==="transparent",Dn=(r,e=16777215)=>Rk(r)?{color:e,alpha:0}:{color:yt(r)??e,alpha:1};function Fk(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 On extends Mn{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 Dr(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:yt(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=yt(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=yt(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=yt(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=yt(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 It(n);this.textStyle=o;const{align:a,fill:l,...u}=n;this.textStyleBase=new It(u),this.ready=(async()=>{await this.refreshCaptions();const c={...this._meta};return Ue.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 Dr(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:yt(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=yt(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=yt(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=yt(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 It(i);const{align:o,fill:a,...l}=i;this.textStyleBase=new It(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 Pe,this.wordTexts.forEach(G=>{G.destroyed||G.destroy()}),this.wordTexts=[];const n=Ht.measureText(" ",this.textStyle),s=[];this.opts.words.forEach((G,ne)=>{const oe=this.opts.textCase;let te=G.text||"";oe==="uppercase"?te=te.toUpperCase():oe==="lowercase"?te=te.toLowerCase():oe==="title"&&(te=te.replace(/\w\S*/g,Le=>Le.charAt(0).toUpperCase()+Le.substring(1).toLowerCase())),te.split(/\s+/).filter(Le=>Le.length>0).forEach(Le=>{const ke=new Il({text:Le,style:this.textStyle});ke.segmentIndex=ne;const Ae="#ffffff",je=typeof Ae=="object"&&Ae!==null&&"type"in Ae?16777215:Ae,Fe=yt(je);ke.tint=Fe??16777215,s.push(ke)})}),this.wordTexts=s;const o=this._visualPaddingX,a=this._visualPaddingY,l=this.opts.lineHeight*(this.opts.fontSize||30),u=new Il({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=[],P=0,A=0;this.wordTexts.forEach((G,ne)=>{const oe=G.getLocalBounds(),te=Math.ceil(oe.width||G.width),be=Math.ceil(oe.height||G.height),Le=G.segmentIndex,ke=this.opts.words[Le],Ae=ne>0?this.wordTexts[ne-1]:null,je=Ae?this.opts.words[Ae.segmentIndex]:null,Fe=je&&ke&&ke.paragraphIndex!==void 0&&ke.paragraphIndex!==je.paragraphIndex||this.opts.wordsPerLine==="single",at=P+(P>0?c:0)+te;!Fe&&(at<=f+1||T.length===0)?(T.push(G),P=at,A=Math.max(A,be)):(T.length>0&&p.push({words:T,width:P,height:Math.max(A,l)+b*2}),T=[G],P=te,A=be)}),T.length>0&&p.push({words:T,width:P,height:Math.max(A,l)+b*2}),this.opts.textBoxStyle.maxLines&&this.opts.textBoxStyle.maxLines>0&&(p=p.slice(0,this.opts.textBoxStyle.maxLines));let E=0,_=0;p.forEach(G=>{E=Math.max(E,G.width),_+=G.height});const S=E,I=_,M=S+Math.max(o,y)*2,O=I,U=this._text!==this._lastProcessedText;this._lastProcessedText=this._text;let X=M,D=O;this._isWidthConstrained&&(U?X=M:X=Math.max(M,e),this.opts.wordWrapWidth>0&&(X=Math.min(X,this.opts.wordWrapWidth)));const k=X,Y=D,H=I;let $=0;const K=Math.max(a,b);i==="top"?$=K:i==="bottom"?$=Y-H-K:$=(Y-H)/2;let we=$;if(p.forEach(G=>{const ne=new Pe;ne.label="lineContainer",this.pixiTextContainer.addChild(ne);let oe=0;const te=G.width;let be=0;m==="center"?be=(k-te)/2:m==="right"?be=k-te-o:be=o,ne.x=be,ne.y=we,v&&x.push({x:be-y,y:we,w:te+y*2,h:G.height}),G.words.forEach((Le,ke)=>{const Ae=Le.getLocalBounds(),je=Ae.width||Le.width,Fe=Ae.height||Le.height;Le.pivot.set(je/2,Fe/2),Le.x=Math.round(oe+je/2),Le.y=Math.round(G.height/2),ne.addChild(Le),oe+=je+(ke<G.words.length-1?c:0)}),we+=G.height}),v&&x.length>0){const G=new Ze;G.label="tiktokBackground";const ne=yt(this.opts.background)??0,oe=g.borderRadius??10;this.drawRoundedTiktokPath(G,x,oe,ne),this.pixiTextContainer.addChildAt(G,0)}if(!v){const G=new Ze;G.label="containerBackground";const ne=this.opts.background==="transparent"||!this.opts.background,oe=ne?0:yt(this.opts.background),te=ne?0:1;G.roundRect(0,0,k,Y,10),G.fill({color:oe,alpha:te}),this.pixiTextContainer.addChildAt(G,0)}this.renderTexture?(Math.abs(this.renderTexture.width-k)>.5||Math.abs(this.renderTexture.height-Y)>.5)&&(this.renderTexture.destroy(),this.renderTexture=Ot.create({width:k,height:Y})):this.renderTexture=Ot.create({width:k,height:Y}),this.updateState(this._lastTickTime);try{(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture})}catch(G){Ue.warn("CaptionClip: Could not render captions during refresh",G)}const Ie=!this._isWidthConstrained,ve=this.height===0||this._lastContentHeight===0||Math.abs(this.height-this._lastContentHeight)<2;if(Ie&&this._initialLayoutApplied&&e>0&&t>0){const G=X-e;Math.abs(G)>.1&&!this._isXPositionedManually&&this.opts.align==="center"?this.left-=G/2:Math.abs(G)>.1&&!this._isXPositionedManually&&this.opts.align==="right"&&(this.left-=G)}if(this._meta.width=S,this._meta.height=I,this._meta.duration=1/0,this._width=k,this._height=Y,this._lastContentWidth=this._width,this._lastContentHeight=this._height,!this._initialLayoutApplied&&(Ie||ve)){const G=this.opts.videoWidth,ne=this.opts.videoHeight,oe=this.opts.bottomOffset,te=ne-I-oe,be=(G-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&&!Rk(this.opts.keyword);let f=16777215,p=1;if(o.isKeyWord&&a&&d)({color:f,alpha:p}=Dn(this.opts.keyword,16776960));else if(a)p=Dn(this.opts.active,16777215).alpha,f=Dn(this.opts.active,16777215).color;else if(l&&this.opts.preserveKeywordColor&&d)({color:f,alpha:p}=Dn(this.opts.keyword));else if(l)({color:f,alpha:p}=Dn(this.opts.appeared));else{const v=this.opts.fill,x=typeof v=="object"&&v!==null&&"type"in v?16777215:v;({color:f,alpha:p}=Dn(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}=Dn(this.opts.activeFill,16753920),y=15,b=40;m&&(m.visible=!1);const T=n.getLocalBounds();m&&(m.visible=!0);const P=10,A=m??new Ze;A.label="bgRect",A.clear(),A.roundRect(T.x-b/2,T.y-y/2,T.width+b,T.height+y,P),A.fill({color:v,alpha:x}),A.tint=16777215,m||n.addChildAt(A,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 On(this.text,e);return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){if(!this.destroyed){Ue.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 On(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=[];s.push({x:t[0].x,y:t[0].y}),s.push({x:t[0].x+t[0].w,y:t[0].y});for(let l=0;l<t.length-1;l++){const u=t[l],c=t[l+1];if(Math.abs(u.x+u.w-(c.x+c.w))>.1){const h=(u.y+u.h+c.y)/2;s.push({x:u.x+u.w,y:h}),s.push({x:c.x+c.w,y:h})}}s.push({x:t[t.length-1].x+t[t.length-1].w,y:t[t.length-1].y+t[t.length-1].h}),s.push({x:t[t.length-1].x,y:t[t.length-1].y+t[t.length-1].h});for(let l=t.length-1;l>0;l--){const u=t[l],c=t[l-1];if(Math.abs(u.x-c.x)>.1){const h=(u.y+c.y+c.h)/2;s.push({x:u.x,y:h}),s.push({x:c.x,y:h})}}e.clear();const o=s[s.length-1],a=s[0];e.moveTo((o.x+a.x)/2,(o.y+a.y)/2);for(let l=0;l<s.length;l++){const u=s[l],c=s[(l+1)%s.length];e.arcTo(u.x,u.y,(u.x+c.x)/2,(u.y+c.y)/2,i)}e.fill({color:n,alpha:1})}}let Bl=class Nn extends Mn{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){Ue.warn("Failed to create Pixi texture from bitmap:",l)}}catch(o){throw Ue.error(`Failed to load blob image from ${e}`,o),o}else n=await Lo.getImageBitmap(e);if(!n)throw new Error(`Failed to load image from ${e}`);const s=new Nn(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 RL(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},Ue.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 Nn(await createImageBitmap(this.img),this.src),new Nn(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 Nn(i,this.src),new Nn(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 Nn(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(){Ue.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 Lo.getImageBitmap(e.src);t=new Nn(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.locked!==void 0&&(t.locked=e.locked),t}};function Hb(r,e){const t={},i=e.videoTracks[0];if(i!=null){const s=lq(r.getTrackById(i.id))?.buffer,o=aq(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=uq(r),o=s?cq(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??rt.codec,numberOfChannels:o.numberOfChannels??n.audio.channel_count,sampleRate:o.sampleRate??n.audio.sample_rate}}return t}function aq(r){return r.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:r.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:null}function lq(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 uq(r,e="mp4a"){return r.moov?.traks.flatMap(t=>t.mdia.minf.stbl.stsd.entries).find(t=>t.type===e)}function cq(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 hq(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 dq(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 fq(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 Wb=0;function Vb(r){return r.kind==="file"&&r.createReader instanceof Function}class br extends Mn{type="Video";insId=Wb++;logger=Ue.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 Lo.getReadableStream(e),n=new br(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)&&!Vb(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 Vs(this.localFile,s),this.localFile);this.localFile=Vb(e)?e:"localFile"in e?e.localFile:G0(),this.ready=(e instanceof ReadableStream?n(e).then(s=>Mk(s,this.opts)):Vb(e)?Mk(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}=mq({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=fq(d,f,u.rotationDeg)),this._meta=pq(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=Tq(e,Math.round(o*(e/s)),{quality:.1,type:"image/png"});return new Promise(async(l,u)=>{let c=[];const h=this.decoderConf.video;if(h==null||this.videoSamples.length===0){d();return}i.addEventListener("abort",()=>{u(Error(n))});async function d(){i.aborted||l(await Promise.all(c.map(async v=>({ts:v.ts,img:await v.img}))))}function f(v){c.push({ts:v.timestamp,img:a(v)})}const{start:p=0,end:m=this._meta.duration,step:g}=t??{};if(g){let v=p;for(this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null),this.thumbFinder=new Ok(await this.localFile.createReader(),this.videoSamples,{...h,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__});v<=m&&!i.aborted;){const x=await this.thumbFinder.find(v);x&&f(x),v+=g}await this.thumbFinder.destroy(),this.thumbFinder=null,d()}else await Sq(this.videoSamples,this.localFile,h,i,{start:p,end:m},(v,x)=>{v!=null&&f(v),x&&d()})})}async split(e){if(await this.ready,e<=0||e>=this._meta.duration)throw Error("time out of bounds");const[t,i]=bq(this.videoSamples,e),[n,s]=_q(this.audioSamples,e),o=new br({localFile:this.localFile,videoSamples:t??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),a=new br({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 br({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 br({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 br({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 Lo.getReadableStream(e.src),n=new br(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<1e6?e.trim.from*1e6:e.trim.from,n.trim.to=e.trim.to<1e6?e.trim.to*1e6:e.trim.to),e.volume!==void 0&&(n.volume=e.volume),e.chromaKey&&(n.chromaKey={...n.chromaKey,...e.chromaKey}),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 pq(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=rt.sampleRate,n.audioChanCount=rt.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 mq(r,e,t,i,n){return{audioFrameFinder:n===0||r.audio==null||i.length===0?null:new vq(e,i,r.audio,{volume:n,targetSampleRate:rt.sampleRate}),videoFrameFinder:r.video==null||t.length===0?null:new Ok(e,t,r.video)}}async function Mk(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 hq(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,dq(t.videoTracks[0]?.matrix));let{videoDecoderConf:m,audioDecoderConf:g}=Hb(d.mp4boxFile,d.info);if(i.video=m??null,i.audio=g??null,m==null&&g==null&&Ue.error("Video no video and audio track"),g!=null){const{supported:v}=await AudioDecoder.isConfigSupported(g);v||Ue.error(`Video audio codec is not supported: ${g.codec}`)}if(m!=null){const{supported:v}=await VideoDecoder.isConfigSupported(m);v||Ue.error(`Video video codec is not supported: ${m.codec}`)}Ue.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(Dk(m,l,"video"))}else if(f==="audio"&&e.audio){u===-1&&(u=p[0].dts);for(const m of p)s.push(Dk(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 Yb(n),Ue.info("mp4 stream parsed"),{videoSamples:n,audioSamples:s,decoderConf:i,headerBoxPos:o,parsedMatrix:a}}function Dk(r,e=0,t){let i=r.offset;const n=t==="video"&&r.is_sync?wq(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 Ok{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 wu(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)Ue.warn("First sample not idr frame");else{const s=performance.now(),o=await zk(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;Ue.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,Xb(e,o,{onDecodingError:l=>{if(this.downgradeSoftDecode)throw l;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,Ue.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,Ue.warn(i.message);return}const n=`VideoFinder VideoDecoder err: ${i.message}, config: ${JSON.stringify(t)}, state: ${JSON.stringify(this.getState())}`;throw Ue.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:Wb,sleepCnt:this.sleepCnt,memInfo:Lk()});destroy=async()=>{if(this.curAborter.abort=!0,this.videoFrames.forEach(e=>e.close()),this.videoFrames=[],this.decoder&&this.decoder.state!=="closed"){try{await this.decoder.flush()}catch{}try{this.decoder.close()}catch{}}this.decoder=null,this.localFileReader.close()}}function gq(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 vq{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=gq(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<rt.sampleRate/10&&this.startDecode(t),Uk(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 wu(15)}else{if(this.decCursorIdx>=this.samples.length-1)return Uk(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=xq(this.conf,{resampleRate:rt.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:Wb,sleepCnt:this.sleepCnt,memInfo:Lk()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function xq(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=yq(s),a=e.resampleRate!==r.sampleRate;let l=new AudioDecoder({output:c=>{const h=$w(c);a?o(()=>uL(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 Ue.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 yq(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 Uk(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 zk(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 bq(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)}Yb(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 Yb(a),[o,a]}function _q(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 Xb(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 wq(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 Yb(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 Lk(){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 Sq(r,e,t,i,n,s){const o=await e.createReader(),a=await zk(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;Xb(u(),a,{onDecodingError:c=>{Ue.warn("thumbnailsByKeyFrame",c),l===0?Xb(u(!0),a,{onDecodingError:h=>{o.close(),Ue.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 Ue.error(p),Error(p)}});return i.addEventListener("abort",()=>{o.close(),d.state!=="closed"&&d.close()}),d.configure(h),d}}function Tq(r,e,t){const i=new OffscreenCanvas(r,e),n=i.getContext("2d");return async s=>(n.drawImage(s,0,0,r,e),s.close(),await i.convertToBlob(t))}class Ki extends Mn{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 It(n),d=new It(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 Ki(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 It(u),h=new It(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 Pe;const s=i.split(/\s+/).filter(k=>k.length>0);this.wordTexts.forEach(k=>k.destroy()),this.wordTexts=s.map(k=>{const Y=new Il({text:k,style:this.textStyle});return this.pixiTextContainer.addChild(Y),Y});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 Il({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 Y=k.getLocalBounds(),H=Math.ceil(Y.width||k.width),$=Math.ceil(Y.height||k.height),K=g+(g>0?d:0)+H;K<=f||m.length===0?(m.push(k),g=K,v=Math.max(v,$)):(m.length>0&&p.push({words:m,width:g,height:Math.max(v,u)}),m=[k],g=H,v=$)}),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 P=b;e.wordWrap&&e.wordWrapWidth>0&&(P=Math.max(P,e.wordWrapWidth));const A=T,E=this.width===0||Math.abs(this.width-this._lastContentWidth)<.1,_=this.height===0||Math.abs(this.height-this._lastContentHeight)<.1,S=E?P:Math.max(P,this.width||0),I=_?A:Math.max(A,this.height||0);this._lastContentWidth=P,this._lastContentHeight=A;let M=0;const O=this.originalOpts.verticalAlign||"top";O==="center"?M=(I-T)/2:O==="bottom"&&(M=I-T);let U=M;const X=new Ze;let D=!1;p.forEach(k=>{let Y=0;const H=this.textAlign;H==="center"?Y=(S-k.width)/2:H==="right"&&(Y=S-k.width);const $=Y;if(k.words.forEach((K,we)=>{K.x=Math.round(Y),K.y=Math.round(U),Y+=(K.getLocalBounds().width||K.width)+(we<k.words.length-1?d:0)}),o&&o!=="none"&&["underline","overline","strikethrough","line-through"].includes(o)){D=!0;const K=o==="strikethrough"?"line-through":o,we=Math.max(1,l/12);let Ie=16777215;typeof e.fill=="number"?Ie=e.fill:e.fill&&typeof e.fill=="object"&&"fill"in e.fill&&(Ie=16777215);let ve=0;K==="underline"?ve=k.height:K==="line-through"?ve=k.height/2:K==="overline"&&(ve=0),X.rect($,U+ve,k.width,we),X.fill(Ie)}U+=k.height}),D&&this.pixiTextContainer.addChild(X),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 Dr(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:yt(a)??16777215;s.addColorStop(o,l)}),n.fill={fill:s}}else{const{color:s,alpha:o}=Dn(e.fill);n.fill=s,o<1&&(n.fillAlpha=o)}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const s=yt(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=yt(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=yt(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){Ue.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 Ki(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 Cq(r){return r.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase())}class Qi extends Mn{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=Cq(e),this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Qi(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 Qi(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 kl extends Mn{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)}placeholderFrame=null;async tick(e){if(!this.placeholderFrame){const t=document.createElement("canvas");t.width=this.meta.width,t.height=this.meta.height;const i=t.getContext("2d");i&&(i.fillStyle="#1e1e1e",i.fillRect(0,0,t.width,t.height),i.fillStyle="#ffffff",i.font=`${Math.floor(t.height/10)}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText("Loading...",t.width/2,t.height/2),i.strokeStyle="#333333",i.lineWidth=10,i.strokeRect(0,0,t.width,t.height)),this.placeholderFrame=await createImageBitmap(t)}return{video:this.placeholderFrame,state:e>=this.duration?"done":"success",audio:[]}}async clone(){const e=new kl(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 kl(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 Bi extends Mn{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 Bi(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 Bi(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 Nk(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 Gk{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=>{Aq.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 Aq={error:(...r)=>console.error("[SampleTransform]",...r)};function Eq(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=G0();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=G0(),g=f(o,0);return await Vs(m,g.slice()),await Vs(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 Pq(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 Hk(r){const e=qn.createFile(),t=Eq(e);await Iq(r,e);const i=await t();if(i==null)throw Error("Can not generate file from streams");return i}async function Iq(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=>{Nk(c.pipeThrough(new Gk),{onDone:m,onChunk:async({chunkType:g,data:v})=>{if(g==="ready"){const{videoTrackConf:x,audioTrackConf:y}=Hb(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,P=x==="video"?n:a;y.forEach(E=>{let _,S;x==="video"?(h===null&&(h=E.dts,d=E.cts),_=E.dts-h,S=E.cts-(d??0)):(f===null&&(f=E.dts,p=E.cts),_=E.dts-f,S=E.cts-(p??0)),e.addSample(b,new Uint8Array(E.data),{duration:E.duration,dts:_+T,cts:S+P,is_sync:E.is_sync})});const A=y.at(-1);if(A==null)return;x==="video"?l=A:x==="audio"&&(u=A)}}})}),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 Bq(r){return await Hk([r])}function kq(r){let e=[];const t=new AudioDecoder({output:i=>{e.push(i)},error:Ue.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 Rq(r,e){const t={codec:r.codec,sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels},i=new AudioEncoder({output:o=>{e(Pq(o))},error:o=>{Ue.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&&(Fq(n.data,r.numberOfChannels,r.sampleRate),i.encode(s(n.data,n.ts)),n=null),await i.flush(),i.close()}}}function Fq(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 Mq(r,e){Ue.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 E=new qn.DataStream;let _=s;try{for(;_<o.length;)o[_].write(E),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(E.buffer)};let u=!1,c=!1,h=null;i=new ReadableStream({start(E){n=self.setInterval(()=>{const _=l();_!=null&&!c&&E.enqueue(_)},500),h=_=>{if(clearInterval(n),t.flush(),_!=null){E.error(_);return}const S=l();S!=null&&!c&&E.enqueue(S),c||E.close()}},cancel(){c=!0,clearInterval(n)}});const d=E=>{u||(u=!0,h?.(E))};let f=null,p=null,m=[],g=0,v=0,x=0,y=!0,b=rt.sampleRate;Nk(r.pipeThrough(new Gk),{onDone:async()=>{await p?.stop(),f?.close(),d()},onChunk:async({chunkType:E,data:_})=>{if(E==="ready"){const{videoTrackConf:S,audioTrackConf:I,audioDecoderConf:M}=Hb(_.file,_.info);g===0&&S!=null&&(g=t.addTrack(S));const O=I??{timescale:1e6,samplerate:b,channel_count:rt.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};v===0&&(v=t.addTrack(O),b=I?.samplerate??b,y=I!=null);const U=new AudioContext({sampleRate:b});m=H0(await U.decodeAudioData(await new Response(e.stream).arrayBuffer())),M!=null&&(f=kq(M)),p=Rq(M??{codec:O.type==="mp4a"?rt.codec:O.type,numberOfChannels:O.channel_count,sampleRate:O.samplerate},X=>t.addSample(v,new Uint8Array(X.data),X))}else if(E==="samples"){const{id:S,type:I,samples:M}=_;if(I==="video"){M.forEach(O=>t.addSample(S,new Uint8Array(O.data),O)),y||await P(M);return}I==="audio"&&await A(M)}}});function T(E){const _=m.map(S=>e.loop?W0(S,x,x+E):S.slice(x,x+E));if(x+=E,e.volume!==1)for(const S of _)for(let I=0;I<S.length;I++)S[I]*=e.volume;return _}async function P(E){const _=E[0],S=E[E.length-1],I=Math.floor((S.cts+S.duration-_.cts)/_.timescale*b),M=eS([T(I)]);M.length!==0&&p?.encode(M,_.cts/_.timescale*1e6)}async function A(E){if(f==null)return;const _=(await f.decode(E)).map($w),S=Jw(_),I=T(S[0].length),M=E[0];p?.encode(eS([S,I]),M.cts/M.timescale*1e6)}return i}const qb=`
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 Dr(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:yt(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=yt(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=yt(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=yt(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=yt(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 It(n);this.textStyle=o;const{align:a,fill:l,...u}=n;this.textStyleBase=new It(u),this.ready=(async()=>{await this.refreshCaptions();const c={...this._meta};return Ue.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 Dr(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:yt(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=yt(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=yt(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=yt(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 It(i);const{align:o,fill:a,...l}=i;this.textStyleBase=new It(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 Pe,this.wordTexts.forEach(G=>{G.destroyed||G.destroy()}),this.wordTexts=[];const n=Ht.measureText(" ",this.textStyle),s=[];this.opts.words.forEach((G,ne)=>{const oe=this.opts.textCase;let te=G.text||"";oe==="uppercase"?te=te.toUpperCase():oe==="lowercase"?te=te.toLowerCase():oe==="title"&&(te=te.replace(/\w\S*/g,Le=>Le.charAt(0).toUpperCase()+Le.substring(1).toLowerCase())),te.split(/\s+/).filter(Le=>Le.length>0).forEach(Le=>{const ke=new Il({text:Le,style:this.textStyle});ke.segmentIndex=ne;const Ae="#ffffff",je=typeof Ae=="object"&&Ae!==null&&"type"in Ae?16777215:Ae,Fe=yt(je);ke.tint=Fe??16777215,s.push(ke)})}),this.wordTexts=s;const o=this._visualPaddingX,a=this._visualPaddingY,l=this.opts.lineHeight*(this.opts.fontSize||30),u=new Il({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=[],P=0,A=0;this.wordTexts.forEach((G,ne)=>{const oe=G.getLocalBounds(),te=Math.ceil(oe.width||G.width),be=Math.ceil(oe.height||G.height),Le=G.segmentIndex,ke=this.opts.words[Le],Ae=ne>0?this.wordTexts[ne-1]:null,je=Ae?this.opts.words[Ae.segmentIndex]:null,Fe=je&&ke&&ke.paragraphIndex!==void 0&&ke.paragraphIndex!==je.paragraphIndex||this.opts.wordsPerLine==="single",at=P+(P>0?c:0)+te;!Fe&&(at<=f+1||T.length===0)?(T.push(G),P=at,A=Math.max(A,be)):(T.length>0&&p.push({words:T,width:P,height:Math.max(A,l)+b*2}),T=[G],P=te,A=be)}),T.length>0&&p.push({words:T,width:P,height:Math.max(A,l)+b*2}),this.opts.textBoxStyle.maxLines&&this.opts.textBoxStyle.maxLines>0&&(p=p.slice(0,this.opts.textBoxStyle.maxLines));let E=0,_=0;p.forEach(G=>{E=Math.max(E,G.width),_+=G.height});const S=E,I=_,M=S+Math.max(o,y)*2,O=I,U=this._text!==this._lastProcessedText;this._lastProcessedText=this._text;let X=M,D=O;this._isWidthConstrained&&(U?X=M:X=Math.max(M,e),this.opts.wordWrapWidth>0&&(X=Math.min(X,this.opts.wordWrapWidth)));const k=X,Y=D,H=I;let $=0;const K=Math.max(a,b);i==="top"?$=K:i==="bottom"?$=Y-H-K:$=(Y-H)/2;let we=$;if(p.forEach(G=>{const ne=new Pe;ne.label="lineContainer",this.pixiTextContainer.addChild(ne);let oe=0;const te=G.width;let be=0;m==="center"?be=(k-te)/2:m==="right"?be=k-te-o:be=o,ne.x=be,ne.y=we,v&&x.push({x:be-y,y:we,w:te+y*2,h:G.height}),G.words.forEach((Le,ke)=>{const Ae=Le.getLocalBounds(),je=Ae.width||Le.width,Fe=Ae.height||Le.height;Le.pivot.set(je/2,Fe/2),Le.x=Math.round(oe+je/2),Le.y=Math.round(G.height/2),ne.addChild(Le),oe+=je+(ke<G.words.length-1?c:0)}),we+=G.height}),v&&x.length>0){const G=new Ze;G.label="tiktokBackground";const ne=yt(this.opts.background)??0,oe=g.borderRadius??10;this.drawRoundedTiktokPath(G,x,oe,ne),this.pixiTextContainer.addChildAt(G,0)}if(!v){const G=new Ze;G.label="containerBackground";const ne=this.opts.background==="transparent"||!this.opts.background,oe=ne?0:yt(this.opts.background),te=ne?0:1;G.roundRect(0,0,k,Y,10),G.fill({color:oe,alpha:te}),this.pixiTextContainer.addChildAt(G,0)}this.renderTexture?(Math.abs(this.renderTexture.width-k)>.5||Math.abs(this.renderTexture.height-Y)>.5)&&(this.renderTexture.destroy(),this.renderTexture=Ot.create({width:k,height:Y})):this.renderTexture=Ot.create({width:k,height:Y}),this.updateState(this._lastTickTime);try{(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture})}catch(G){Ue.warn("CaptionClip: Could not render captions during refresh",G)}const Ie=!this._isWidthConstrained,ve=this.height===0||this._lastContentHeight===0||Math.abs(this.height-this._lastContentHeight)<2;if(Ie&&this._initialLayoutApplied&&e>0&&t>0){const G=X-e;Math.abs(G)>.1&&!this._isXPositionedManually&&this.opts.align==="center"?this.left-=G/2:Math.abs(G)>.1&&!this._isXPositionedManually&&this.opts.align==="right"&&(this.left-=G)}if(this._meta.width=S,this._meta.height=I,this._meta.duration=1/0,this._width=k,this._height=Y,this._lastContentWidth=this._width,this._lastContentHeight=this._height,!this._initialLayoutApplied&&(Ie||ve)){const G=this.opts.videoWidth,ne=this.opts.videoHeight,oe=this.opts.bottomOffset,te=ne-I-oe,be=(G-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&&!Rk(this.opts.keyword);let f=16777215,p=1;if(o.isKeyWord&&a&&d)({color:f,alpha:p}=Dn(this.opts.keyword,16776960));else if(a)p=Dn(this.opts.active,16777215).alpha,f=Dn(this.opts.active,16777215).color;else if(l&&this.opts.preserveKeywordColor&&d)({color:f,alpha:p}=Dn(this.opts.keyword));else if(l)({color:f,alpha:p}=Dn(this.opts.appeared));else{const v=this.opts.fill,x=typeof v=="object"&&v!==null&&"type"in v?16777215:v;({color:f,alpha:p}=Dn(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}=Dn(this.opts.activeFill,16753920),y=15,b=40;m&&(m.visible=!1);const T=n.getLocalBounds();m&&(m.visible=!0);const P=10,A=m??new Ze;A.label="bgRect",A.clear(),A.roundRect(T.x-b/2,T.y-y/2,T.width+b,T.height+y,P),A.fill({color:v,alpha:x}),A.tint=16777215,m||n.addChildAt(A,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 On(this.text,e);return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){if(!this.destroyed){Ue.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 On(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=[];s.push({x:t[0].x,y:t[0].y}),s.push({x:t[0].x+t[0].w,y:t[0].y});for(let l=0;l<t.length-1;l++){const u=t[l],c=t[l+1];if(Math.abs(u.x+u.w-(c.x+c.w))>.1){const h=(u.y+u.h+c.y)/2;s.push({x:u.x+u.w,y:h}),s.push({x:c.x+c.w,y:h})}}s.push({x:t[t.length-1].x+t[t.length-1].w,y:t[t.length-1].y+t[t.length-1].h}),s.push({x:t[t.length-1].x,y:t[t.length-1].y+t[t.length-1].h});for(let l=t.length-1;l>0;l--){const u=t[l],c=t[l-1];if(Math.abs(u.x-c.x)>.1){const h=(u.y+c.y+c.h)/2;s.push({x:u.x,y:h}),s.push({x:c.x,y:h})}}e.clear();const o=s[s.length-1],a=s[0];e.moveTo((o.x+a.x)/2,(o.y+a.y)/2);for(let l=0;l<s.length;l++){const u=s[l],c=s[(l+1)%s.length];e.arcTo(u.x,u.y,(u.x+c.x)/2,(u.y+c.y)/2,i)}e.fill({color:n,alpha:1})}}let Bl=class Nn extends Mn{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){Ue.warn("Failed to create Pixi texture from bitmap:",l)}}catch(o){throw Ue.error(`Failed to load blob image from ${e}`,o),o}else n=await Lo.getImageBitmap(e);if(!n)throw new Error(`Failed to load image from ${e}`);const s=new Nn(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 RL(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},Ue.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 Nn(await createImageBitmap(this.img),this.src),new Nn(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 Nn(i,this.src),new Nn(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 Nn(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(){Ue.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 Lo.getImageBitmap(e.src);t=new Nn(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.locked!==void 0&&(t.locked=e.locked),t}};function Hb(r,e){const t={},i=e.videoTracks[0];if(i!=null){const s=lq(r.getTrackById(i.id))?.buffer,o=aq(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=uq(r),o=s?cq(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??rt.codec,numberOfChannels:o.numberOfChannels??n.audio.channel_count,sampleRate:o.sampleRate??n.audio.sample_rate}}return t}function aq(r){return r.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:r.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:null}function lq(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 uq(r,e="mp4a"){return r.moov?.traks.flatMap(t=>t.mdia.minf.stbl.stsd.entries).find(t=>t.type===e)}function cq(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 hq(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 dq(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 fq(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 Wb=0;function Vb(r){return r.kind==="file"&&r.createReader instanceof Function}class br extends Mn{type="Video";insId=Wb++;logger=Ue.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 Lo.getReadableStream(e),n=new br(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)&&!Vb(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 Vs(this.localFile,s),this.localFile);this.localFile=Vb(e)?e:"localFile"in e?e.localFile:G0(),this.ready=(e instanceof ReadableStream?n(e).then(s=>Mk(s,this.opts)):Vb(e)?Mk(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}=mq({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=fq(d,f,u.rotationDeg)),this._meta=pq(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=Tq(e,Math.round(o*(e/s)),{quality:.1,type:"image/png"});return new Promise(async(l,u)=>{let c=[];const h=this.decoderConf.video;if(h==null||this.videoSamples.length===0){d();return}i.addEventListener("abort",()=>{u(Error(n))});async function d(){i.aborted||l(await Promise.all(c.map(async v=>({ts:v.ts,img:await v.img}))))}function f(v){c.push({ts:v.timestamp,img:a(v)})}const{start:p=0,end:m=this._meta.duration,step:g}=t??{};if(g){let v=p;for(this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null),this.thumbFinder=new Ok(await this.localFile.createReader(),this.videoSamples,{...h,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__});v<=m&&!i.aborted;){const x=await this.thumbFinder.find(v);x&&f(x),v+=g}await this.thumbFinder.destroy(),this.thumbFinder=null,d()}else await Sq(this.videoSamples,this.localFile,h,i,{start:p,end:m},(v,x)=>{v!=null&&f(v),x&&d()})})}async split(e){if(await this.ready,e<=0||e>=this._meta.duration)throw Error("time out of bounds");const[t,i]=bq(this.videoSamples,e),[n,s]=_q(this.audioSamples,e),o=new br({localFile:this.localFile,videoSamples:t??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),a=new br({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 br({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 br({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 br({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 Lo.getReadableStream(e.src),n=new br(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<1e6?e.trim.from*1e6:e.trim.from,n.trim.to=e.trim.to<1e6?e.trim.to*1e6:e.trim.to),e.volume!==void 0&&(n.volume=e.volume),e.chromaKey&&(n.chromaKey={...n.chromaKey,...e.chromaKey}),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 pq(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=rt.sampleRate,n.audioChanCount=rt.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 mq(r,e,t,i,n){return{audioFrameFinder:n===0||r.audio==null||i.length===0?null:new vq(e,i,r.audio,{volume:n,targetSampleRate:rt.sampleRate}),videoFrameFinder:r.video==null||t.length===0?null:new Ok(e,t,r.video)}}async function Mk(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 hq(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,dq(t.videoTracks[0]?.matrix));let{videoDecoderConf:m,audioDecoderConf:g}=Hb(d.mp4boxFile,d.info);if(i.video=m??null,i.audio=g??null,m==null&&g==null&&Ue.error("Video no video and audio track"),g!=null){const{supported:v}=await AudioDecoder.isConfigSupported(g);v||Ue.error(`Video audio codec is not supported: ${g.codec}`)}if(m!=null){const{supported:v}=await VideoDecoder.isConfigSupported(m);v||Ue.error(`Video video codec is not supported: ${m.codec}`)}Ue.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(Dk(m,l,"video"))}else if(f==="audio"&&e.audio){u===-1&&(u=p[0].dts);for(const m of p)s.push(Dk(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 Yb(n),Ue.info("mp4 stream parsed"),{videoSamples:n,audioSamples:s,decoderConf:i,headerBoxPos:o,parsedMatrix:a}}function Dk(r,e=0,t){let i=r.offset;const n=t==="video"&&r.is_sync?wq(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 Ok{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 wu(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)Ue.warn("First sample not idr frame");else{const s=performance.now(),o=await zk(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;Ue.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,Xb(e,o,{onDecodingError:l=>{if(this.downgradeSoftDecode)throw l;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,Ue.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,Ue.warn(i.message);return}const n=`VideoFinder VideoDecoder err: ${i.message}, config: ${JSON.stringify(t)}, state: ${JSON.stringify(this.getState())}`;throw Ue.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:Wb,sleepCnt:this.sleepCnt,memInfo:Lk()});destroy=async()=>{if(this.curAborter.abort=!0,this.videoFrames.forEach(e=>e.close()),this.videoFrames=[],this.decoder&&this.decoder.state!=="closed"){try{await this.decoder.flush()}catch{}try{this.decoder.close()}catch{}}this.decoder=null,this.localFileReader.close()}}function gq(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 vq{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=gq(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<rt.sampleRate/10&&this.startDecode(t),Uk(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 wu(15)}else{if(this.decCursorIdx>=this.samples.length-1)return Uk(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=xq(this.conf,{resampleRate:rt.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:Wb,sleepCnt:this.sleepCnt,memInfo:Lk()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function xq(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=yq(s),a=e.resampleRate!==r.sampleRate;let l=new AudioDecoder({output:c=>{const h=$w(c);a?o(()=>uL(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 Ue.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 yq(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 Uk(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 zk(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 bq(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)}Yb(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 Yb(a),[o,a]}function _q(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 Xb(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 wq(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 Yb(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 Lk(){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 Sq(r,e,t,i,n,s){const o=await e.createReader(),a=await zk(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;Xb(u(),a,{onDecodingError:c=>{Ue.warn("thumbnailsByKeyFrame",c),l===0?Xb(u(!0),a,{onDecodingError:h=>{o.close(),Ue.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 Ue.error(p),Error(p)}});return i.addEventListener("abort",()=>{o.close(),d.state!=="closed"&&d.close()}),d.configure(h),d}}function Tq(r,e,t){const i=new OffscreenCanvas(r,e),n=i.getContext("2d");return async s=>(n.drawImage(s,0,0,r,e),s.close(),await i.convertToBlob(t))}class Ki extends Mn{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 It(n),d=new It(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 Ki(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 It(u),h=new It(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 Pe;const s=i.split(/\s+/).filter(k=>k.length>0);this.wordTexts.forEach(k=>k.destroy()),this.wordTexts=s.map(k=>{const Y=new Il({text:k,style:this.textStyle});return this.pixiTextContainer.addChild(Y),Y});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 Il({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 Y=k.getLocalBounds(),H=Math.ceil(Y.width||k.width),$=Math.ceil(Y.height||k.height),K=g+(g>0?d:0)+H;K<=f||m.length===0?(m.push(k),g=K,v=Math.max(v,$)):(m.length>0&&p.push({words:m,width:g,height:Math.max(v,u)}),m=[k],g=H,v=$)}),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 P=b;e.wordWrap&&e.wordWrapWidth>0&&(P=Math.max(P,e.wordWrapWidth));const A=T,E=this.width===0||Math.abs(this.width-this._lastContentWidth)<.1,_=this.height===0||Math.abs(this.height-this._lastContentHeight)<.1,S=E?P:Math.max(P,this.width||0),I=_?A:Math.max(A,this.height||0);this._lastContentWidth=P,this._lastContentHeight=A;let M=0;const O=this.originalOpts.verticalAlign||"top";O==="center"?M=(I-T)/2:O==="bottom"&&(M=I-T);let U=M;const X=new Ze;let D=!1;p.forEach(k=>{let Y=0;const H=this.textAlign;H==="center"?Y=(S-k.width)/2:H==="right"&&(Y=S-k.width);const $=Y;if(k.words.forEach((K,we)=>{K.x=Math.round(Y),K.y=Math.round(U),Y+=(K.getLocalBounds().width||K.width)+(we<k.words.length-1?d:0)}),o&&o!=="none"&&["underline","overline","strikethrough","line-through"].includes(o)){D=!0;const K=o==="strikethrough"?"line-through":o,we=Math.max(1,l/12);let Ie=16777215;typeof e.fill=="number"?Ie=e.fill:e.fill&&typeof e.fill=="object"&&"fill"in e.fill&&(Ie=16777215);let ve=0;K==="underline"?ve=k.height:K==="line-through"?ve=k.height/2:K==="overline"&&(ve=0),X.rect($,U+ve,k.width,we),X.fill(Ie)}U+=k.height}),D&&this.pixiTextContainer.addChild(X),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 Dr(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:yt(a)??16777215;s.addColorStop(o,l)}),n.fill={fill:s}}else{const{color:s,alpha:o}=Dn(e.fill);n.fill=s,o<1&&(n.fillAlpha=o)}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const s=yt(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=yt(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=yt(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){Ue.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 Ki(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 Cq(r){return r.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase())}class Qi extends Mn{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=Cq(e),this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Qi(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 Qi(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 kl extends Mn{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 kl(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 kl(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 Bi extends Mn{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 Bi(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 Bi(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 Nk(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 Gk{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=>{Aq.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 Aq={error:(...r)=>console.error("[SampleTransform]",...r)};function Eq(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=G0();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=G0(),g=f(o,0);return await Vs(m,g.slice()),await Vs(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 Pq(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 Hk(r){const e=qn.createFile(),t=Eq(e);await Iq(r,e);const i=await t();if(i==null)throw Error("Can not generate file from streams");return i}async function Iq(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=>{Nk(c.pipeThrough(new Gk),{onDone:m,onChunk:async({chunkType:g,data:v})=>{if(g==="ready"){const{videoTrackConf:x,audioTrackConf:y}=Hb(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,P=x==="video"?n:a;y.forEach(E=>{let _,S;x==="video"?(h===null&&(h=E.dts,d=E.cts),_=E.dts-h,S=E.cts-(d??0)):(f===null&&(f=E.dts,p=E.cts),_=E.dts-f,S=E.cts-(p??0)),e.addSample(b,new Uint8Array(E.data),{duration:E.duration,dts:_+T,cts:S+P,is_sync:E.is_sync})});const A=y.at(-1);if(A==null)return;x==="video"?l=A:x==="audio"&&(u=A)}}})}),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 Bq(r){return await Hk([r])}function kq(r){let e=[];const t=new AudioDecoder({output:i=>{e.push(i)},error:Ue.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 Rq(r,e){const t={codec:r.codec,sampleRate:r.sampleRate,numberOfChannels:r.numberOfChannels},i=new AudioEncoder({output:o=>{e(Pq(o))},error:o=>{Ue.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&&(Fq(n.data,r.numberOfChannels,r.sampleRate),i.encode(s(n.data,n.ts)),n=null),await i.flush(),i.close()}}}function Fq(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 Mq(r,e){Ue.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 E=new qn.DataStream;let _=s;try{for(;_<o.length;)o[_].write(E),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(E.buffer)};let u=!1,c=!1,h=null;i=new ReadableStream({start(E){n=self.setInterval(()=>{const _=l();_!=null&&!c&&E.enqueue(_)},500),h=_=>{if(clearInterval(n),t.flush(),_!=null){E.error(_);return}const S=l();S!=null&&!c&&E.enqueue(S),c||E.close()}},cancel(){c=!0,clearInterval(n)}});const d=E=>{u||(u=!0,h?.(E))};let f=null,p=null,m=[],g=0,v=0,x=0,y=!0,b=rt.sampleRate;Nk(r.pipeThrough(new Gk),{onDone:async()=>{await p?.stop(),f?.close(),d()},onChunk:async({chunkType:E,data:_})=>{if(E==="ready"){const{videoTrackConf:S,audioTrackConf:I,audioDecoderConf:M}=Hb(_.file,_.info);g===0&&S!=null&&(g=t.addTrack(S));const O=I??{timescale:1e6,samplerate:b,channel_count:rt.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};v===0&&(v=t.addTrack(O),b=I?.samplerate??b,y=I!=null);const U=new AudioContext({sampleRate:b});m=H0(await U.decodeAudioData(await new Response(e.stream).arrayBuffer())),M!=null&&(f=kq(M)),p=Rq(M??{codec:O.type==="mp4a"?rt.codec:O.type,numberOfChannels:O.channel_count,sampleRate:O.samplerate},X=>t.addSample(v,new Uint8Array(X.data),X))}else if(E==="samples"){const{id:S,type:I,samples:M}=_;if(I==="video"){M.forEach(O=>t.addSample(S,new Uint8Array(O.data),O)),y||await P(M);return}I==="audio"&&await A(M)}}});function T(E){const _=m.map(S=>e.loop?W0(S,x,x+E):S.slice(x,x+E));if(x+=E,e.volume!==1)for(const S of _)for(let I=0;I<S.length;I++)S[I]*=e.volume;return _}async function P(E){const _=E[0],S=E[E.length-1],I=Math.floor((S.cts+S.duration-_.cts)/_.timescale*b),M=eS([T(I)]);M.length!==0&&p?.encode(M,_.cts/_.timescale*1e6)}async function A(E){if(f==null)return;const _=(await f.decode(E)).map($w),S=Jw(_),I=T(S[0].length),M=E[0];p?.encode(eS([S,I]),M.cts/M.timescale*1e6)}return i}const qb=`
3510
3510
  in vec2 aPosition;
3511
3511
  out vec2 vTextureCoord;
3512
3512
 
@@ -14342,4 +14342,4 @@ vec4 transition(vec2 uv) {
14342
14342
  bool nextImage = distance(fract(uv * dots), vec2(0.5, 0.5)) < ( progress / distance(uv, center));
14343
14343
  return nextImage ? getToColor(uv) : getFromColor(uv);
14344
14344
  }
14345
- `,hte={radialSwipe:{label:"Radial Swipe",fragment:vee}},Ah={};function dte(r,e){Ah[r]=e}function fte(r){delete Ah[r]}function qo(){return{...Yo.reduce((r,e)=>(r[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:""},r),{}),...hte,...Ah}}qo();function D4(){const r=Object.keys(Ah);return Object.entries(qo()).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 pte=D4();function c1({name:r,renderer:e}){let t=Yo.find(G=>G.name===r);if(!t){const G=qo(),ne=Object.keys(G).find(oe=>oe.toLowerCase()===r.toLowerCase());ne&&(t=G[ne])}if(t||(t=Yo.find(G=>G.name.toLowerCase()===r.toLowerCase())),!t){const G=[r,r.toLowerCase(),r.charAt(0).toUpperCase()+r.slice(1).toLowerCase(),r.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),r.replace(/_/g,"")],ne=qo();for(const oe of G){if(t=Yo.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 G=Yo.length,ne=Yo.slice(0,5).map(be=>be.name).join(", "),oe=qo(),te=Object.keys(oe).slice(0,3).join(", ");throw console.error(`Transition not found: "${r}". Available in gl-transitions (${G} total):`,ne+"..."),console.error("Available locally:",te+"..."),new Error(`Transition "${r}" not found in gl-transitions library or local definitions`)}const i=new Je(Q.WHITE),n=Ot.create({width:e.width,height:e.height}),s=new jr({}),o=new jr({}),a=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",l=a?new jr({}):void 0;let u=null;if(a){u=document.createElement("canvas"),u.width=256,u.height=256;const G=u.getContext("2d");if(G){const ne=G.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}G.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={...st.basics,...st.custom(t)};Object.entries(h).forEach(([,G])=>{G.type==="int<f32>"&&(G.type="i32",typeof G.value=="number"&&(G.value=Math.trunc(G.value))),G.type==="ivec2<f32>"&&(G.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",P=t.name==="luma"||r.toLowerCase()==="luma"||t.label==="luma",A=t.name==="luminance_melt"||r.toLowerCase()==="luminance_melt"||r.toLowerCase()==="luminancemelt"||t.label==="luminance_melt",E=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",U=t.name==="circleopen"||r.toLowerCase()==="circleopen"||r.toLowerCase()==="circle_open"||t.label==="circleopen",X=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",Y=t.name==="CrossZoom"||r.toLowerCase()==="crosszoom"||t.label==="CrossZoom",H=t.name==="CrazyParametricFun"||r.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",$=t.name==="BowTieHorizontal"||r.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",K=t.name==="PolkaDotsCurtain"||r.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",we=t.name==="Pixelize"||r.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(c=xee,h={...st.basics,...yee}),f&&(c=bee,h={...st.basics,...M4}),p&&(c=_ee,h={...st.basics,...wee}),m&&(c=See,h={...st.basics,...Tee}),g&&(c=Cee,h={...st.basics,...Aee}),v&&(c=Eee,h={...st.basics,...Pee}),x&&(c=Iee,h={...st.basics,...Bee}),y&&(c=kee,h={...st.basics,...Ree}),b&&(c=Wk,h={...st.basics,...Vk}),T&&(c=Dee,h={...st.basics,...Oee}),P&&(c=Uee,h={...st.basics,...zee}),A&&(c=Lee,h={...st.basics,...Nee}),E&&(c=Gee,h={...st.basics,...Hee}),_&&(c=Wee,h={...st.basics,...Vee}),S&&(c=Xee,h={...st.basics,...Yee}),I&&(c=qee,h={...st.basics,...jee}),M&&(c=Kee,h={...st.basics,...Qee}),O&&(c=Zee,h={...st.basics,...Jee}),U&&(c=$ee,h={...st.basics,...M4}),X&&(c=ete,h={...st.basics,...tte}),D&&(c=rte,h={...st.basics,...ite}),k&&(c=nte),Y&&(c=ste,h={...st.basics,...ote}),H&&(c=ate,h={...st.basics,...lte}),$&&(c=ute),K&&(c=cte),we&&(c=Fee,h={...st.basics,...Mee});const Ie={from:s,to:o,uniforms:h};a&&l&&(Ie.displacementMap=l,u&&(l.resource=u,l.update()));const ve=new ge({glProgram:new ue({vertex:pee,fragment:gee(c)}),resources:Ie});return i.filters=[ve],{render({width:G,height:ne,from:oe,to:te,progress:be}){if((i.width!==G||i.height!==ne)&&(i.setSize({width:G,height:ne}),n.resize(G,ne)),oe instanceof Q?ve.resources.from=oe.source:(s.resource=oe,s.update(),ve.resources.from=s),te instanceof Q?ve.resources.to=te.source:(o.resource=te,o.update(),ve.resources.to=o),a&&l&&u){if(u.width!==G||u.height!==ne){u.width=G,u.height=ne;const Le=u.getContext("2d");if(Le){const ke=Le.createImageData(G,ne);for(let Ae=0;Ae<ke.data.length;Ae+=4){const je=Math.random();ke.data[Ae]=je*255,ke.data[Ae+1]=je*255,ke.data[Ae+2]=je*255,ke.data[Ae+3]=255}Le.putImageData(ke,0,0)}}l.resource=u,l.update()}return ve.resources.uniforms.uniforms.progress=be,e.render({container:i,target:n,clear:!0,width:G,height:ne}),n},destroy(){n.destroy(),i.destroy({children:!0})}}}let mte=0;async function O4(r){r()>50&&(await wu(15),await O4(r))}class gte extends X0{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 kk()).codec,sampleRate:rt.sampleRate,numberOfChannels:rt.channelCount})).supported)??!1}logger=Ue.create(`id:${mte++},`);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,kk().catch(n=>{this.logger.warn("Failed to detect audio codec:",n)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new gc,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 UO({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||rt.codecType,sampleRate:h||rt.sampleRate,channelCount:rt.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=vte({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=xte({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 wu(0),x(y,b,!0),y+=g,await O4(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=>Rl(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 br||s instanceof Bl)).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 Xo(t);await this.addSprite(i,{main:t.main||!1})}}}function vte(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 Ze().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),h=new Map,d=async(b,T,P)=>{const A=Math.max(0,Math.min(T-b.display.from,b.duration));b.animate(A*b.playbackRate);const{video:E}=await P(b,A);return E},f=(b,T,P)=>{if(!e)return;const A=b.style||{},{renderTransform:E}=b,_=(E?.mirror??0)>.5,S=T instanceof Q?T:Q.from(T),I=E?.x??0,M=E?.y??0,O=E?.angle??0,U=E?.scale??1,X=E?.scaleX??1,D=E?.scaleY??1,k=E?.opacity??1,Y=E?.blur??0,H=E?.brightness??1,$=S.width||1,K=S.height||1,we=b.type==="Caption",Ie=!we&&b.width&&b.width!==0?Math.abs(b.width)/$:1,ve=!we&&b.height&&b.height!==0?Math.abs(b.height)/K:1,G=Ie*U*X,ne=ve*U*D,oe=new Pe;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 Je(S);te.anchor.set(.5,.5);let be=[];if(_){const Re=G,nt=ne,Bt=$*Re,Vt=K*nt;te.position.set(0,0),te.scale.set(Re,nt);const Qe=[[Bt,0,-Re,nt],[-Bt,0,-Re,nt],[0,Vt,Re,-nt],[0,-Vt,Re,-nt],[Bt,Vt,-Re,-nt],[-Bt,Vt,-Re,-nt],[Bt,-Vt,-Re,-nt],[-Bt,-Vt,-Re,-nt]];for(const[Oe,Ri,As,Fl]of Qe){const Un=new Je(S);Un.anchor.set(.5,.5),Un.position.set(Oe,Ri),Un.scale.set(As,Fl),be.push(Un)}if(b.flip==="horizontal"){te.scale.x=-Re;for(let Oe=0;Oe<8;Oe++)be[Oe].scale.x=-Qe[Oe][2]}else if(b.flip==="vertical"){te.scale.y=-nt;for(let Oe=0;Oe<8;Oe++)be[Oe].scale.y=-Qe[Oe][3]}oe.addChild(te);for(const Oe of be)oe.addChild(Oe)}else b.flip==="horizontal"?(te.scale.x=-G,te.scale.y=ne):b.flip==="vertical"?(te.scale.x=G,te.scale.y=-ne):(te.scale.x=G,te.scale.y=ne),oe.addChild(te);const Le=[];if(Y>0){const Re=new ys;Re.strength=Y,Re.quality=4,Re.repeatEdgePixels=!0,Le.push(Re)}if(H!==1){const Re=new Ro;Re.brightness(H,!1),Le.push(Re)}if(b.chromaKey&&b.chromaKey.enabled){const Re=new ft({uKeyColor:{value:[0,1,0],type:"vec3<f32>"},uSimilarity:{value:.1,type:"f32"},uSpill:{value:0,type:"f32"}}),nt=Fk(b.chromaKey.color);nt&&(Re.uniforms.uKeyColor[0]=nt.r/255,Re.uniforms.uKeyColor[1]=nt.g/255,Re.uniforms.uKeyColor[2]=nt.b/255),Re.uniforms.uSimilarity=b.chromaKey.similarity,Re.uniforms.uSpill=b.chromaKey.spill;const Bt=new ge({glProgram:new ue({vertex:qb,fragment:Xk,name:"ChromaKeyShader"}),resources:{chromaUniforms:Re}});Le.push(Bt)}oe.filters=Le;const ke=A.borderRadius||0;let Ae=null;ke>0&&(Ae=new Ze,Ae.roundRect(-$/2,-K/2,$,K,Math.min(ke,$/2,K/2)),Ae.fill({color:16777215,alpha:1}),te.addChild(Ae),te.mask=Ae);const je=A.stroke;let Fe=null;if(je&&je.width>0){Fe=new Ze;const Re=yt(je.color)??16777215;if(Fe.setStrokeStyle({width:je.width,color:Re,alignment:1}),ke>0){const nt=Math.min(ke,$/2,K/2);Fe.roundRect(-$/2,-K/2,$,K,nt)}else Fe.rect(-$/2,-K/2,$,K);Fe.stroke(),te.addChild(Fe)}const at=A.dropShadow;let it=null;if(at&&(at.blur>0||at.distance>0)){it=new Ze;const Re=yt(at.color)??0,nt=at.alpha??.5,Bt=at.distance??0,Vt=at.angle??0,Qe=Math.cos(Vt)*Bt,Oe=Math.sin(Vt)*Bt;if(ke>0){const Ri=Math.min(ke,$/2,K/2);it.roundRect(-$/2+Qe,-K/2+Oe,$,K,Ri)}else it.rect(-$/2+Qe,-K/2+Oe,$,K);it.fill({color:Re,alpha:nt}),oe.addChildAt(it,0)}e.renderer.render({container:oe,target:P,clear:!0}),T instanceof Q||te.texture.destroy(!0),Fe&&Fe.destroy(),Ae&&Ae.destroy(),it&&it.destroy();for(const Re of be)Re.destroy();te.destroy(),oe.destroy()};let p=null,m=null,g=null;n&&e!=null&&(p=new Pe,m=new Pe,g=new Pe,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 P=!1,A=!1;const E=new Map,_=async(S,I)=>{if(E.has(S))return E.get(S);const M=await S.getFrame(I);return E.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:U,done:X}=await _(S,I);if(T.push(U),n&&e!=null&&m!=null){if(S instanceof Bi){const k=t.find(H=>H.id===S.fromClipId),Y=t.find(H=>H.id===S.toClipId);if(k&&Y){const H=b-S.display.from;if(H>=S.duration){S.expired=!0;const $=a.get(S.id);$&&($.visible=!1)}else{const $=await d(k,b,_),K=await d(Y,b,_);if($&&K){const we=Math.min(Math.max(H/S.duration,0),1);f(k,$,l),f(Y,K,u);let Ie=o.get(S.id);Ie||(Ie=c1({name:S.transitionEffect.key,renderer:e.renderer}),o.set(S.id,Ie));const ve=Ie.render({width:e.renderer.width,height:e.renderer.height,from:l,to:u,progress:we});let G=a.get(S.id);G||(G=new Je,G.label=`TransitionSprite_${S.id}`,a.set(S.id,G),m.addChild(G)),G.texture=ve,G.visible=!0,G.x=0,G.y=0,G.width=e.renderer.width,G.height=e.renderer.height,G.anchor.set(0,0),G.zIndex=S.zIndex,A=!0;const ne=s.get(k);if(ne){const te=ne.getRoot();te&&(te.visible=!1)}const oe=s.get(Y);if(oe){const te=oe.getRoot();te&&(te.visible=!1)}continue}}}}let D=s.get(S);if(D==null&&O!=null&&(D=new R4(e,S,m),s.set(S,D)),D!=null){const k=D.getRoot();O!=null?(A=!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||X){if(S.main&&(P=!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 Qi&&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 U=new Set,X=[];for(const D of S){const{key:k,startTime:Y,duration:H,id:$,zIndex:K}=D,we=b-Y,Ie=H>0?Math.min(Math.max(we/H,0),1):0,ve=t.some(G=>G.id===$&&G instanceof Qi);if(p.removeChildren(),O){const G=new Je(O);G.width=I,G.height=M,p.addChild(G)}for(const G of t){if(U.has(G.id))continue;let ne=!1;if(ve?ne=G.id!==$&&G.zIndex<K:ne=!!G.effects&&G.effects.some(oe=>oe.id===$),ne){const oe=s.get(G);if(oe){const be=oe.getRoot();be&&(be.parent&&be.parent.removeChild(be),p.addChild(be),U.add(G.id))}const te=a.get(G.id);te&&(te.parent&&te.parent.removeChild(te),p.addChild(te),U.add(G.id))}}if(p.children.length>0){let G=h.get($);if(!G)try{const ne=await l1({name:k,renderer:e.renderer,values:D.values});ne&&ne.filter&&(G={filter:ne.filter,render:ne.render},h.set($,G))}catch(ne){console.warn("Failed to create effect",k,ne)}if(G){const{filter:ne,render:oe}=G;ne.resources&&ne.resources.effectUniforms&&(ne.resources.effectUniforms.uniforms.uTime=Ie);const te=Ot.create({width:I,height:M});X.push(te),p.visible=!0,e.renderer.render({container:p,target:te,clear:!0}),p.visible=!1,oe&&(O=oe({canvasTexture:te,progress:Ie,width:I,height:M}))}}}if(O){const D=new Je(O);D.width=I,D.height=M,g.addChild(D)}for(const D of X)D.destroy(!0)}}return n&&e!=null&&e.render(),{audios:T,mainSprDone:P,hasVideo:A}},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 xte(r){const{canvas:e,outputAudio:t,muxer:i,hasVideoTrack:n,timeSlice:s}=r;let o=0;const a=Math.floor(3*r.fps),l=yte(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 yte(r){const e=r*rt.channelCount,t=new Float32Array(e*3);let i=0,n=0;const s=r/rt.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:rt.channelCount,numberOfFrames:r,sampleRate:rt.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:rt.channelCount,numberOfFrames:r,sampleRate:rt.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 bte extends Ze{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 Ji extends Ze{#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 sl(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 Eh{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=Eh.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=Eh.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 U4={delta:new ae};class z4 extends Pe{group;wireframe=new bte;selectionOutlines=new Ze;isDragging=!1;lastPointer=new me;activeHandle=null;#e;#l=new Map;#r=new me;#n=0;#u=0;#c=new he;#i=new me;#s=new he;#t=[new me,new me,new me,new me];#o=1;#a=1;#h;#d=new Ze;#m=new me;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static",this.#h=new Eh(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 Ji("tl","nwse-resize",t),tr:new Ji("tr","nesw-resize",t),bl:new Ji("bl","nesw-resize",t),br:new Ji("br","nwse-resize",t),ml:new Ji("ml","ew-resize",t),mr:new Ji("mr","ew-resize",t),mt:new Ji("mt","ns-resize",t),mb:new Ji("mb","ns-resize",t),rot:new Ji("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 me(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 me(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 Je)return u;for(const c of u.children)if(c instanceof Pe){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 me(u.x,u.y)),d=c.apply(new me(u.x+u.width,u.y)),f=c.apply(new me(u.x+u.width,u.y+u.height)),p=c.apply(new me(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 me(c.minX,c.minY)),d=e.toLocal(new me(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 me(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 me(i.position,i.start),s=new me(i.position,i.end)):(n=new me(i.start,i.position),s=new me(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 U4.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(i,n).rotate(t).translate(e.x,e.y)}#O(e,t){return U4.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 _te{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new me;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;init(e,t){this.selectionGraphics=new Ze,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()}}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 z4({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=this.getTopmostClipAtPoint(n.global);s&&this.selectClip(s,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 z4({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);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 Ki))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 Ki||e instanceof On)&&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 Ki||e instanceof On)&&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 wte{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 jo{static instance;fonts=new Map;constructor(){}static getInstance(){return jo.instance||(jo.instance=new jo),jo.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 L4=jo.getInstance();class Ste{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 Bi(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 s=this.studio.clipsNormalContainer,o=i.getRoot();o&&!o.parent&&s.addChild(o);return}const n=await e.ready;if(await this.setupPlaybackForClip(e,t),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 R4(this.studio.pixiApp,e,s);this.studio.spriteRenderers.set(e,a)}}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 Bi){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))}for(const c of s){const h=this.tracks.findIndex(d=>d.id===c);h!==-1&&this.tracks[h].clipIds.length===0&&(this.tracks.splice(h,1),this.studio.emit("track:removed",{trackId:c}))}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&&i&&this.isPlaybackCapable(e)&&(e.cleanupPlayback(l.element,l.objectUrl),this.studio.transport.playbackElements.delete(e));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 Bi){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&&t.permanent&&this.isPlaybackCapable(i)&&(i.cleanupPlayback(a.element,a.objectUrl),this.studio.transport.playbackElements.delete(i));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(){const e=this.clips.map(n=>Rl(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 Xo(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 Bi){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=Rl(n,!1),l=await Xo(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=Rl(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 Xo(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){this.tracks=JSON.parse(JSON.stringify(e)),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}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 L4.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 Je(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 Tte={Date:!0,RegExp:!0,String:!0,Number:!0};function N4(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&&!Tte[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!i.includes(l))?n.push.apply(n,N4(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 Cte{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=N4(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 Ate extends X0{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;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 _te(this),this.transport=new wte(this),this.timeline=new Ste(this),this.history=new Cte,this.resourceManager=new Lo,this.ready=this.initPixiApp().then(()=>{this.history.init(this.exportToJSON())}),this.on("clip:removed",this.handleClipRemoved),this.on("clips:removed",this.handleClipsRemoved),this.on("clip:updated",this.handleTimelineChange),this.on("clip:added",this.handleTimelineChange),this.on("clips:added",this.handleTimelineChange),this.on("track:removed",this.handleTimelineChange),this.on("track:added",this.handleTimelineChange)}handleTimelineChange=()=>{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.historyGroupDepth++,this.historyPaused=!0}endHistoryGroup(){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 Xo(l),this.clipCache.set(a,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.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.processingHistory=!1}}}async redo(){if(!(!this.history.canRedo()||this.processingHistory)){this.processingHistory=!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.processingHistory=!1}}}cleanupClipVisuals=e=>{for(const[n,s]of this.spriteRenderers)if(n.id===e){const o=s.getRoot();o&&o.parent&&o.parent.removeChild(o),s.destroy(),this.spriteRenderers.delete(n);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[n,s]of this.videoSprites)if(n.id===e){s.parent&&s.parent.removeChild(s),s.destroy(),this.videoSprites.delete(n);break}for(const[n]of this.clipListeners)if(n.id===e){this.clipListeners.delete(n);break}};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 gc,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 Pe,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new Ze,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new Pe,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new Ze,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 Pe,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new Pe,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 Ze,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){(Array.isArray(e)?e:[e]).forEach(n=>this.clipCache.set(n.id,n)),this.beginHistoryGroup();try{return await this.timeline.addClip(e,t)}finally{this.endHistoryGroup()}}addTrack(e,t){return this.timeline.addTrack(e,t)}async setTracks(e){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()}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&&hee(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 E=this.spriteRenderers.get(o);E?.getRoot()&&(E.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 Ze,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 P=null,A=null;if(b){const E=Math.max(0,e-b.display.from),{video:_}=await b.getFrame(E);_ instanceof HTMLVideoElement?P=this.getVideoTexture(_):P=_,P&&(this.lastFromFrame=P)}if(T){const E=Math.max(0,e-T.display.from),{video:_}=await T.getFrame(E);_ instanceof HTMLVideoElement?A=this.getVideoTexture(_):A=_,A&&(this.lastToFrame=A)}if(P||(P=this.lastFromFrame),A||(A=this.lastToFrame),!P||!A)continue;if(P&&A&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const E=(e-f)/o?.transition?.duration;b&&P&&this.renderClipToTransitionTexture(b,P,this.transFromTexture),T&&A&&this.renderClipToTransitionTexture(T,A,this.transToTexture);let _=this.transitionRenderers.get(y);if(!_)try{_=c1({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:E});let I=this.transitionSprites.get(o.id);I||(I=new Je,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 U=this.spriteRenderers.get(b);U?.getRoot()&&(U.getRoot().visible=!1);const X=this.videoSprites.get(b);X&&(X.visible=!1)}if(T){const U=this.spriteRenderers.get(T);U?.getRoot()&&(U.getRoot().visible=!1);const X=this.videoSprites.get(T);X&&(X.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 Bl&&o.addEffect(s),o instanceof br&&o.addEffect(s),o instanceof Ki&&o.addEffect(s),o instanceof On&&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 br||i instanceof Bl)).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 Pe;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 Je(a);T.anchor.set(.5,.5);let P=[];if(o){const U=x*h,X=y*h,D=m*U,k=g*X;T.position.set(0,0),T.scale.set(U,X);const Y=[[D,0,-U,X],[-D,0,-U,X],[0,k,U,-X],[0,-k,U,-X],[D,k,-U,-X],[-D,k,-U,-X],[D,-k,-U,-X],[-D,-k,-U,-X]];for(const[H,$,K,we]of Y){const Ie=new Je(a);Ie.anchor.set(.5,.5),Ie.position.set(H,$),Ie.scale.set(K,we),P.push(Ie)}if(e.flip==="horizontal"){T.scale.x=-U;for(let H=0;H<8;H++)P[H].scale.x=-Y[H][2]}else if(e.flip==="vertical"){T.scale.y=-X;for(let H=0;H<8;H++)P[H].scale.y=-Y[H][3]}b.addChild(T);for(const H of P)b.addChild(H)}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 A=[];if(f>0){const U=new ys;U.strength=f,U.quality=4,U.repeatEdgePixels=!0,A.push(U)}if(p!==1){const U=new Ro;U.brightness(p,!1),A.push(U)}b.filters=A;const E=n.borderRadius||0;let _=null;E>0&&(_=new Ze,_.roundRect(-m/2,-g/2,m,g,Math.min(E,m/2,g/2)),_.fill({color:16777215,alpha:1}),T.addChild(_),T.mask=_);const S=n.stroke;let I=null;if(S&&S.width>0){I=new Ze;const U=yt(S.color)??16777215;if(I.setStrokeStyle({width:S.width,color:U,alignment:1}),E>0){const X=Math.min(E,m/2,g/2);I.roundRect(-m/2,-g/2,m,g,X)}else I.rect(-m/2,-g/2,m,g);I.stroke(),T.addChild(I)}const M=n.dropShadow;let O=null;if(M&&(M.blur>0||M.distance>0)){O=new Ze;const U=yt(M.color)??0,X=M.alpha??.5,D=M.distance??0,k=M.angle??0,Y=Math.cos(k)*D,H=Math.sin(k)*D;if(E>0){const $=Math.min(E,m/2,g/2);O.roundRect(-m/2+Y,-g/2+H,m,g,$)}else O.rect(-m/2+Y,-g/2+H,m,g);O.fill({color:U,alpha:X}),b.addChildAt(O,0)}this.pixiApp.renderer.render({container:b,target:i,clear:!0}),t instanceof Q||T.texture.destroy(!0),_&&_.destroy(),I&&I.destroy(),O&&O.destroy();for(const U of P)U.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 Qi&&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 Je(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 Qi)&&(m===-1||b>m)&&(this.moveClipToEffectContainer(y,!0),s.add(y.id))}let g=this.effectFilters.get(l);if(!g)try{if(g=await l1({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 Je(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($T),xe.mixin(Pe,eC),xe.add(Ox),xe.add(Ux),xe.add(Ly),xe.mixin(Pe,pP),xe.add(Oy),xe.add(yb),xe.add(kc),xe.add(_b),xe.add(Cb),xe.add(Ab),xe.add(Nb),xe.add(Lb),xe.add(Mb),xe.add(Ub),xe.add(Db),xe.add(kb),xe.add(Pb),xe.add(Ky),xe.add(Yy);const Ete=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Pte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));_e.ANIMATABLE_PROPERTIES=FL,_e.Audio=Jr,_e.Caption=On,_e.Compositor=gte,_e.DEFAULT_AUDIO_CONF=rt,_e.Effect=Qi,_e.GL_EFFECT_OPTIONS=bQ,_e.GL_TRANSITION_OPTIONS=pte,_e.Image=Bl,_e.KeyframeAnimation=B,_e.Log=Ue,_e.MP4Clip=br,_e.Placeholder=kl,_e.Studio=Ate,_e.Text=Ki,_e.Transition=Bi,_e.VALUES_FILTER_SPECIAL=a1,_e.VALUES_FILTER_SPECIAL_LIMITS=lee,_e.Video=br,_e.animationRegistry=z,_e.clipToJSON=Rl,_e.createChromakey=TL,_e.createSlowMo=iS,_e.easings=Su,_e.fastConcatMP4=Hk,_e.fixFMP4Duration=Bq,_e.fontManager=L4,_e.getAllEffects=jb,_e.getAllTransitions=qo,_e.getEasing=Y0,_e.getEffectOptions=Yk,_e.getPresetTemplate=V,_e.getTransitionOptions=D4,_e.jsonToClip=Xo,_e.makeEffect=l1,_e.makeTransition=c1,_e.mixinMP4AndAudio=Mq,_e.registerCustomEffect=vQ,_e.registerCustomTransition=dte,_e.renderTxt2ImgBitmap=kL,_e.unregisterCustomEffect=xQ,_e.unregisterCustomTransition=fte,Object.defineProperty(_e,Symbol.toStringTag,{value:"Module"})}));
14345
+ `,hte={radialSwipe:{label:"Radial Swipe",fragment:vee}},Ah={};function dte(r,e){Ah[r]=e}function fte(r){delete Ah[r]}function qo(){return{...Yo.reduce((r,e)=>(r[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:""},r),{}),...hte,...Ah}}qo();function D4(){const r=Object.keys(Ah);return Object.entries(qo()).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 pte=D4();function c1({name:r,renderer:e}){let t=Yo.find(G=>G.name===r);if(!t){const G=qo(),ne=Object.keys(G).find(oe=>oe.toLowerCase()===r.toLowerCase());ne&&(t=G[ne])}if(t||(t=Yo.find(G=>G.name.toLowerCase()===r.toLowerCase())),!t){const G=[r,r.toLowerCase(),r.charAt(0).toUpperCase()+r.slice(1).toLowerCase(),r.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),r.replace(/_/g,"")],ne=qo();for(const oe of G){if(t=Yo.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 G=Yo.length,ne=Yo.slice(0,5).map(be=>be.name).join(", "),oe=qo(),te=Object.keys(oe).slice(0,3).join(", ");throw console.error(`Transition not found: "${r}". Available in gl-transitions (${G} total):`,ne+"..."),console.error("Available locally:",te+"..."),new Error(`Transition "${r}" not found in gl-transitions library or local definitions`)}const i=new Je(Q.WHITE),n=Ot.create({width:e.width,height:e.height}),s=new jr({}),o=new jr({}),a=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",l=a?new jr({}):void 0;let u=null;if(a){u=document.createElement("canvas"),u.width=256,u.height=256;const G=u.getContext("2d");if(G){const ne=G.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}G.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={...st.basics,...st.custom(t)};Object.entries(h).forEach(([,G])=>{G.type==="int<f32>"&&(G.type="i32",typeof G.value=="number"&&(G.value=Math.trunc(G.value))),G.type==="ivec2<f32>"&&(G.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",P=t.name==="luma"||r.toLowerCase()==="luma"||t.label==="luma",A=t.name==="luminance_melt"||r.toLowerCase()==="luminance_melt"||r.toLowerCase()==="luminancemelt"||t.label==="luminance_melt",E=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",U=t.name==="circleopen"||r.toLowerCase()==="circleopen"||r.toLowerCase()==="circle_open"||t.label==="circleopen",X=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",Y=t.name==="CrossZoom"||r.toLowerCase()==="crosszoom"||t.label==="CrossZoom",H=t.name==="CrazyParametricFun"||r.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",$=t.name==="BowTieHorizontal"||r.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",K=t.name==="PolkaDotsCurtain"||r.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",we=t.name==="Pixelize"||r.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(c=xee,h={...st.basics,...yee}),f&&(c=bee,h={...st.basics,...M4}),p&&(c=_ee,h={...st.basics,...wee}),m&&(c=See,h={...st.basics,...Tee}),g&&(c=Cee,h={...st.basics,...Aee}),v&&(c=Eee,h={...st.basics,...Pee}),x&&(c=Iee,h={...st.basics,...Bee}),y&&(c=kee,h={...st.basics,...Ree}),b&&(c=Wk,h={...st.basics,...Vk}),T&&(c=Dee,h={...st.basics,...Oee}),P&&(c=Uee,h={...st.basics,...zee}),A&&(c=Lee,h={...st.basics,...Nee}),E&&(c=Gee,h={...st.basics,...Hee}),_&&(c=Wee,h={...st.basics,...Vee}),S&&(c=Xee,h={...st.basics,...Yee}),I&&(c=qee,h={...st.basics,...jee}),M&&(c=Kee,h={...st.basics,...Qee}),O&&(c=Zee,h={...st.basics,...Jee}),U&&(c=$ee,h={...st.basics,...M4}),X&&(c=ete,h={...st.basics,...tte}),D&&(c=rte,h={...st.basics,...ite}),k&&(c=nte),Y&&(c=ste,h={...st.basics,...ote}),H&&(c=ate,h={...st.basics,...lte}),$&&(c=ute),K&&(c=cte),we&&(c=Fee,h={...st.basics,...Mee});const Ie={from:s,to:o,uniforms:h};a&&l&&(Ie.displacementMap=l,u&&(l.resource=u,l.update()));const ve=new ge({glProgram:new ue({vertex:pee,fragment:gee(c)}),resources:Ie});return i.filters=[ve],{render({width:G,height:ne,from:oe,to:te,progress:be}){if((i.width!==G||i.height!==ne)&&(i.setSize({width:G,height:ne}),n.resize(G,ne)),oe instanceof Q?ve.resources.from=oe.source:(s.resource=oe,s.update(),ve.resources.from=s),te instanceof Q?ve.resources.to=te.source:(o.resource=te,o.update(),ve.resources.to=o),a&&l&&u){if(u.width!==G||u.height!==ne){u.width=G,u.height=ne;const Le=u.getContext("2d");if(Le){const ke=Le.createImageData(G,ne);for(let Ae=0;Ae<ke.data.length;Ae+=4){const je=Math.random();ke.data[Ae]=je*255,ke.data[Ae+1]=je*255,ke.data[Ae+2]=je*255,ke.data[Ae+3]=255}Le.putImageData(ke,0,0)}}l.resource=u,l.update()}return ve.resources.uniforms.uniforms.progress=be,e.render({container:i,target:n,clear:!0,width:G,height:ne}),n},destroy(){n.destroy(),i.destroy({children:!0})}}}let mte=0;async function O4(r){r()>50&&(await wu(15),await O4(r))}class gte extends X0{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 kk()).codec,sampleRate:rt.sampleRate,numberOfChannels:rt.channelCount})).supported)??!1}logger=Ue.create(`id:${mte++},`);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,kk().catch(n=>{this.logger.warn("Failed to detect audio codec:",n)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new gc,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 UO({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||rt.codecType,sampleRate:h||rt.sampleRate,channelCount:rt.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=vte({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=xte({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 wu(0),x(y,b,!0),y+=g,await O4(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=>Rl(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 br||s instanceof Bl)).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 Xo(t);await this.addSprite(i,{main:t.main||!1})}}}function vte(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 Ze().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),h=new Map,d=async(b,T,P)=>{const A=Math.max(0,Math.min(T-b.display.from,b.duration));b.animate(A*b.playbackRate);const{video:E}=await P(b,A);return E},f=(b,T,P)=>{if(!e)return;const A=b.style||{},{renderTransform:E}=b,_=(E?.mirror??0)>.5,S=T instanceof Q?T:Q.from(T),I=E?.x??0,M=E?.y??0,O=E?.angle??0,U=E?.scale??1,X=E?.scaleX??1,D=E?.scaleY??1,k=E?.opacity??1,Y=E?.blur??0,H=E?.brightness??1,$=S.width||1,K=S.height||1,we=b.type==="Caption",Ie=!we&&b.width&&b.width!==0?Math.abs(b.width)/$:1,ve=!we&&b.height&&b.height!==0?Math.abs(b.height)/K:1,G=Ie*U*X,ne=ve*U*D,oe=new Pe;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 Je(S);te.anchor.set(.5,.5);let be=[];if(_){const Re=G,nt=ne,Bt=$*Re,Vt=K*nt;te.position.set(0,0),te.scale.set(Re,nt);const Qe=[[Bt,0,-Re,nt],[-Bt,0,-Re,nt],[0,Vt,Re,-nt],[0,-Vt,Re,-nt],[Bt,Vt,-Re,-nt],[-Bt,Vt,-Re,-nt],[Bt,-Vt,-Re,-nt],[-Bt,-Vt,-Re,-nt]];for(const[Oe,Ri,As,Fl]of Qe){const Un=new Je(S);Un.anchor.set(.5,.5),Un.position.set(Oe,Ri),Un.scale.set(As,Fl),be.push(Un)}if(b.flip==="horizontal"){te.scale.x=-Re;for(let Oe=0;Oe<8;Oe++)be[Oe].scale.x=-Qe[Oe][2]}else if(b.flip==="vertical"){te.scale.y=-nt;for(let Oe=0;Oe<8;Oe++)be[Oe].scale.y=-Qe[Oe][3]}oe.addChild(te);for(const Oe of be)oe.addChild(Oe)}else b.flip==="horizontal"?(te.scale.x=-G,te.scale.y=ne):b.flip==="vertical"?(te.scale.x=G,te.scale.y=-ne):(te.scale.x=G,te.scale.y=ne),oe.addChild(te);const Le=[];if(Y>0){const Re=new ys;Re.strength=Y,Re.quality=4,Re.repeatEdgePixels=!0,Le.push(Re)}if(H!==1){const Re=new Ro;Re.brightness(H,!1),Le.push(Re)}if(b.chromaKey&&b.chromaKey.enabled){const Re=new ft({uKeyColor:{value:[0,1,0],type:"vec3<f32>"},uSimilarity:{value:.1,type:"f32"},uSpill:{value:0,type:"f32"}}),nt=Fk(b.chromaKey.color);nt&&(Re.uniforms.uKeyColor[0]=nt.r/255,Re.uniforms.uKeyColor[1]=nt.g/255,Re.uniforms.uKeyColor[2]=nt.b/255),Re.uniforms.uSimilarity=b.chromaKey.similarity,Re.uniforms.uSpill=b.chromaKey.spill;const Bt=new ge({glProgram:new ue({vertex:qb,fragment:Xk,name:"ChromaKeyShader"}),resources:{chromaUniforms:Re}});Le.push(Bt)}oe.filters=Le;const ke=A.borderRadius||0;let Ae=null;ke>0&&(Ae=new Ze,Ae.roundRect(-$/2,-K/2,$,K,Math.min(ke,$/2,K/2)),Ae.fill({color:16777215,alpha:1}),te.addChild(Ae),te.mask=Ae);const je=A.stroke;let Fe=null;if(je&&je.width>0){Fe=new Ze;const Re=yt(je.color)??16777215;if(Fe.setStrokeStyle({width:je.width,color:Re,alignment:1}),ke>0){const nt=Math.min(ke,$/2,K/2);Fe.roundRect(-$/2,-K/2,$,K,nt)}else Fe.rect(-$/2,-K/2,$,K);Fe.stroke(),te.addChild(Fe)}const at=A.dropShadow;let it=null;if(at&&(at.blur>0||at.distance>0)){it=new Ze;const Re=yt(at.color)??0,nt=at.alpha??.5,Bt=at.distance??0,Vt=at.angle??0,Qe=Math.cos(Vt)*Bt,Oe=Math.sin(Vt)*Bt;if(ke>0){const Ri=Math.min(ke,$/2,K/2);it.roundRect(-$/2+Qe,-K/2+Oe,$,K,Ri)}else it.rect(-$/2+Qe,-K/2+Oe,$,K);it.fill({color:Re,alpha:nt}),oe.addChildAt(it,0)}e.renderer.render({container:oe,target:P,clear:!0}),T instanceof Q||te.texture.destroy(!0),Fe&&Fe.destroy(),Ae&&Ae.destroy(),it&&it.destroy();for(const Re of be)Re.destroy();te.destroy(),oe.destroy()};let p=null,m=null,g=null;n&&e!=null&&(p=new Pe,m=new Pe,g=new Pe,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 P=!1,A=!1;const E=new Map,_=async(S,I)=>{if(E.has(S))return E.get(S);const M=await S.getFrame(I);return E.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:U,done:X}=await _(S,I);if(T.push(U),n&&e!=null&&m!=null){if(S instanceof Bi){const k=t.find(H=>H.id===S.fromClipId),Y=t.find(H=>H.id===S.toClipId);if(k&&Y){const H=b-S.display.from;if(H>=S.duration){S.expired=!0;const $=a.get(S.id);$&&($.visible=!1)}else{const $=await d(k,b,_),K=await d(Y,b,_);if($&&K){const we=Math.min(Math.max(H/S.duration,0),1);f(k,$,l),f(Y,K,u);let Ie=o.get(S.id);Ie||(Ie=c1({name:S.transitionEffect.key,renderer:e.renderer}),o.set(S.id,Ie));const ve=Ie.render({width:e.renderer.width,height:e.renderer.height,from:l,to:u,progress:we});let G=a.get(S.id);G||(G=new Je,G.label=`TransitionSprite_${S.id}`,a.set(S.id,G),m.addChild(G)),G.texture=ve,G.visible=!0,G.x=0,G.y=0,G.width=e.renderer.width,G.height=e.renderer.height,G.anchor.set(0,0),G.zIndex=S.zIndex,A=!0;const ne=s.get(k);if(ne){const te=ne.getRoot();te&&(te.visible=!1)}const oe=s.get(Y);if(oe){const te=oe.getRoot();te&&(te.visible=!1)}continue}}}}let D=s.get(S);if(D==null&&O!=null&&(D=new R4(e,S,m),s.set(S,D)),D!=null){const k=D.getRoot();O!=null?(A=!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||X){if(S.main&&(P=!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 Qi&&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 U=new Set,X=[];for(const D of S){const{key:k,startTime:Y,duration:H,id:$,zIndex:K}=D,we=b-Y,Ie=H>0?Math.min(Math.max(we/H,0),1):0,ve=t.some(G=>G.id===$&&G instanceof Qi);if(p.removeChildren(),O){const G=new Je(O);G.width=I,G.height=M,p.addChild(G)}for(const G of t){if(U.has(G.id))continue;let ne=!1;if(ve?ne=G.id!==$&&G.zIndex<K:ne=!!G.effects&&G.effects.some(oe=>oe.id===$),ne){const oe=s.get(G);if(oe){const be=oe.getRoot();be&&(be.parent&&be.parent.removeChild(be),p.addChild(be),U.add(G.id))}const te=a.get(G.id);te&&(te.parent&&te.parent.removeChild(te),p.addChild(te),U.add(G.id))}}if(p.children.length>0){let G=h.get($);if(!G)try{const ne=await l1({name:k,renderer:e.renderer,values:D.values});ne&&ne.filter&&(G={filter:ne.filter,render:ne.render},h.set($,G))}catch(ne){console.warn("Failed to create effect",k,ne)}if(G){const{filter:ne,render:oe}=G;ne.resources&&ne.resources.effectUniforms&&(ne.resources.effectUniforms.uniforms.uTime=Ie);const te=Ot.create({width:I,height:M});X.push(te),p.visible=!0,e.renderer.render({container:p,target:te,clear:!0}),p.visible=!1,oe&&(O=oe({canvasTexture:te,progress:Ie,width:I,height:M}))}}}if(O){const D=new Je(O);D.width=I,D.height=M,g.addChild(D)}for(const D of X)D.destroy(!0)}}return n&&e!=null&&e.render(),{audios:T,mainSprDone:P,hasVideo:A}},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 xte(r){const{canvas:e,outputAudio:t,muxer:i,hasVideoTrack:n,timeSlice:s}=r;let o=0;const a=Math.floor(3*r.fps),l=yte(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 yte(r){const e=r*rt.channelCount,t=new Float32Array(e*3);let i=0,n=0;const s=r/rt.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:rt.channelCount,numberOfFrames:r,sampleRate:rt.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:rt.channelCount,numberOfFrames:r,sampleRate:rt.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 bte extends Ze{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 Ji extends Ze{#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 sl(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 Eh{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=Eh.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=Eh.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 U4={delta:new ae};class z4 extends Pe{group;wireframe=new bte;selectionOutlines=new Ze;isDragging=!1;lastPointer=new me;activeHandle=null;#e;#l=new Map;#r=new me;#n=0;#u=0;#c=new he;#i=new me;#s=new he;#t=[new me,new me,new me,new me];#o=1;#a=1;#h;#d=new Ze;#m=new me;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static",this.#h=new Eh(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 Ji("tl","nwse-resize",t),tr:new Ji("tr","nesw-resize",t),bl:new Ji("bl","nesw-resize",t),br:new Ji("br","nwse-resize",t),ml:new Ji("ml","ew-resize",t),mr:new Ji("mr","ew-resize",t),mt:new Ji("mt","ns-resize",t),mb:new Ji("mb","ns-resize",t),rot:new Ji("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 me(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 me(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 Je)return u;for(const c of u.children)if(c instanceof Pe){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 me(u.x,u.y)),d=c.apply(new me(u.x+u.width,u.y)),f=c.apply(new me(u.x+u.width,u.y+u.height)),p=c.apply(new me(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 me(c.minX,c.minY)),d=e.toLocal(new me(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 me(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 me(i.position,i.start),s=new me(i.position,i.end)):(n=new me(i.start,i.position),s=new me(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 U4.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(i,n).rotate(t).translate(e.x,e.y)}#O(e,t){return U4.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 _te{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new me;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;init(e,t){this.selectionGraphics=new Ze,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 z4({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=this.getTopmostClipAtPoint(n.global);s&&this.selectClip(s,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 z4({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);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 Ki))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 Ki||e instanceof On)&&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 Ki||e instanceof On)&&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 wte{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 jo{static instance;fonts=new Map;constructor(){}static getInstance(){return jo.instance||(jo.instance=new jo),jo.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 L4=jo.getInstance();class Ste{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 Bi(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 s=this.studio.clipsNormalContainer,o=i.getRoot();o&&!o.parent&&s.addChild(o);return}const n=await e.ready;if(await this.setupPlaybackForClip(e,t),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 R4(this.studio.pixiApp,e,s);this.studio.spriteRenderers.set(e,a)}}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 Bi){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))}for(const c of s){const h=this.tracks.findIndex(d=>d.id===c);h!==-1&&this.tracks[h].clipIds.length===0&&(this.tracks.splice(h,1),this.studio.emit("track:removed",{trackId:c}))}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&&i&&this.isPlaybackCapable(e)&&(e.cleanupPlayback(l.element,l.objectUrl),this.studio.transport.playbackElements.delete(e));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 Bi){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&&t.permanent&&this.isPlaybackCapable(i)&&(i.cleanupPlayback(a.element,a.objectUrl),this.studio.transport.playbackElements.delete(i));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(){const e=this.clips.map(n=>Rl(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 Xo(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 Bi){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=Rl(n,!1),l=await Xo(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=Rl(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 Xo(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){this.tracks=JSON.parse(JSON.stringify(e)),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}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 L4.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 Je(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 Tte={Date:!0,RegExp:!0,String:!0,Number:!0};function N4(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&&!Tte[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!i.includes(l))?n.push.apply(n,N4(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 Cte{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=N4(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 Ate extends X0{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;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 _te(this),this.transport=new wte(this),this.timeline=new Ste(this),this.history=new Cte,this.resourceManager=new Lo,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.historyGroupDepth++,this.historyPaused=!0}endHistoryGroup(){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 Xo(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.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.processingHistory=!1}}}async redo(){if(!(!this.history.canRedo()||this.processingHistory)){this.processingHistory=!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.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 gc,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 Pe,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new Ze,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new Pe,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new Ze,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 Pe,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new Pe,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 Ze,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){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()}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&&hee(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 E=this.spriteRenderers.get(o);E?.getRoot()&&(E.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 Ze,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 P=null,A=null;if(b){const E=Math.max(0,e-b.display.from),{video:_}=await b.getFrame(E);_ instanceof HTMLVideoElement?P=this.getVideoTexture(_):P=_,P&&(this.lastFromFrame=P)}if(T){const E=Math.max(0,e-T.display.from),{video:_}=await T.getFrame(E);_ instanceof HTMLVideoElement?A=this.getVideoTexture(_):A=_,A&&(this.lastToFrame=A)}if(P||(P=this.lastFromFrame),A||(A=this.lastToFrame),!P||!A)continue;if(P&&A&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const E=(e-f)/o?.transition?.duration;b&&P&&this.renderClipToTransitionTexture(b,P,this.transFromTexture),T&&A&&this.renderClipToTransitionTexture(T,A,this.transToTexture);let _=this.transitionRenderers.get(y);if(!_)try{_=c1({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:E});let I=this.transitionSprites.get(o.id);I||(I=new Je,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 U=this.spriteRenderers.get(b);U?.getRoot()&&(U.getRoot().visible=!1);const X=this.videoSprites.get(b);X&&(X.visible=!1)}if(T){const U=this.spriteRenderers.get(T);U?.getRoot()&&(U.getRoot().visible=!1);const X=this.videoSprites.get(T);X&&(X.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 Bl&&o.addEffect(s),o instanceof br&&o.addEffect(s),o instanceof Ki&&o.addEffect(s),o instanceof On&&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 br||i instanceof Bl)).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 Pe;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 Je(a);T.anchor.set(.5,.5);let P=[];if(o){const U=x*h,X=y*h,D=m*U,k=g*X;T.position.set(0,0),T.scale.set(U,X);const Y=[[D,0,-U,X],[-D,0,-U,X],[0,k,U,-X],[0,-k,U,-X],[D,k,-U,-X],[-D,k,-U,-X],[D,-k,-U,-X],[-D,-k,-U,-X]];for(const[H,$,K,we]of Y){const Ie=new Je(a);Ie.anchor.set(.5,.5),Ie.position.set(H,$),Ie.scale.set(K,we),P.push(Ie)}if(e.flip==="horizontal"){T.scale.x=-U;for(let H=0;H<8;H++)P[H].scale.x=-Y[H][2]}else if(e.flip==="vertical"){T.scale.y=-X;for(let H=0;H<8;H++)P[H].scale.y=-Y[H][3]}b.addChild(T);for(const H of P)b.addChild(H)}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 A=[];if(f>0){const U=new ys;U.strength=f,U.quality=4,U.repeatEdgePixels=!0,A.push(U)}if(p!==1){const U=new Ro;U.brightness(p,!1),A.push(U)}b.filters=A;const E=n.borderRadius||0;let _=null;E>0&&(_=new Ze,_.roundRect(-m/2,-g/2,m,g,Math.min(E,m/2,g/2)),_.fill({color:16777215,alpha:1}),T.addChild(_),T.mask=_);const S=n.stroke;let I=null;if(S&&S.width>0){I=new Ze;const U=yt(S.color)??16777215;if(I.setStrokeStyle({width:S.width,color:U,alignment:1}),E>0){const X=Math.min(E,m/2,g/2);I.roundRect(-m/2,-g/2,m,g,X)}else I.rect(-m/2,-g/2,m,g);I.stroke(),T.addChild(I)}const M=n.dropShadow;let O=null;if(M&&(M.blur>0||M.distance>0)){O=new Ze;const U=yt(M.color)??0,X=M.alpha??.5,D=M.distance??0,k=M.angle??0,Y=Math.cos(k)*D,H=Math.sin(k)*D;if(E>0){const $=Math.min(E,m/2,g/2);O.roundRect(-m/2+Y,-g/2+H,m,g,$)}else O.rect(-m/2+Y,-g/2+H,m,g);O.fill({color:U,alpha:X}),b.addChildAt(O,0)}this.pixiApp.renderer.render({container:b,target:i,clear:!0}),t instanceof Q||T.texture.destroy(!0),_&&_.destroy(),I&&I.destroy(),O&&O.destroy();for(const U of P)U.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 Qi&&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 Je(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 Qi)&&(m===-1||b>m)&&(this.moveClipToEffectContainer(y,!0),s.add(y.id))}let g=this.effectFilters.get(l);if(!g)try{if(g=await l1({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 Je(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($T),xe.mixin(Pe,eC),xe.add(Ox),xe.add(Ux),xe.add(Ly),xe.mixin(Pe,pP),xe.add(Oy),xe.add(yb),xe.add(kc),xe.add(_b),xe.add(Cb),xe.add(Ab),xe.add(Nb),xe.add(Lb),xe.add(Mb),xe.add(Ub),xe.add(Db),xe.add(kb),xe.add(Pb),xe.add(Ky),xe.add(Yy);const Ete=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Pte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));_e.ANIMATABLE_PROPERTIES=FL,_e.Audio=Jr,_e.Caption=On,_e.Compositor=gte,_e.DEFAULT_AUDIO_CONF=rt,_e.Effect=Qi,_e.GL_EFFECT_OPTIONS=bQ,_e.GL_TRANSITION_OPTIONS=pte,_e.Image=Bl,_e.KeyframeAnimation=B,_e.Log=Ue,_e.MP4Clip=br,_e.Placeholder=kl,_e.Studio=Ate,_e.Text=Ki,_e.Transition=Bi,_e.VALUES_FILTER_SPECIAL=a1,_e.VALUES_FILTER_SPECIAL_LIMITS=lee,_e.Video=br,_e.animationRegistry=z,_e.clipToJSON=Rl,_e.createChromakey=TL,_e.createSlowMo=iS,_e.easings=Su,_e.fastConcatMP4=Hk,_e.fixFMP4Duration=Bq,_e.fontManager=L4,_e.getAllEffects=jb,_e.getAllTransitions=qo,_e.getEasing=Y0,_e.getEffectOptions=Yk,_e.getPresetTemplate=V,_e.getTransitionOptions=D4,_e.jsonToClip=Xo,_e.makeEffect=l1,_e.makeTransition=c1,_e.mixinMP4AndAudio=Mq,_e.registerCustomEffect=vQ,_e.registerCustomTransition=dte,_e.renderTxt2ImgBitmap=kL,_e.unregisterCustomEffect=xQ,_e.unregisterCustomTransition=fte,Object.defineProperty(_e,Symbol.toStringTag,{value:"Module"})}));