openvideo 0.2.2 → 0.2.3

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.
@@ -1,5 +1,5 @@
1
- import { e as a, A as e, C as i, a as s, E as t, F as n, D as d } from "./index-BXuEu2AS.js";
2
- import "./webworkerAll-BPHrCidF.js";
1
+ import { e as a, A as e, C as i, a as s, E as t, F as n, D as d } from "./index-CZJxf7wC.js";
2
+ import "./webworkerAll-B5b1f-BT.js";
3
3
  a.add(e);
4
4
  a.mixin(i, s);
5
5
  a.add(t);
@@ -18384,7 +18384,7 @@ const zv = (r) => {
18384
18384
  },
18385
18385
  test: () => !0,
18386
18386
  load: async () => {
18387
- await import("./browserAll-Bki0HKJn.js");
18387
+ await import("./browserAll-fYnMYU5U.js");
18388
18388
  }
18389
18389
  }, mC = {
18390
18390
  extension: {
@@ -18394,7 +18394,7 @@ const zv = (r) => {
18394
18394
  },
18395
18395
  test: () => typeof self < "u" && self.WorkerGlobalScope !== void 0,
18396
18396
  load: async () => {
18397
- await import("./webworkerAll-BPHrCidF.js");
18397
+ await import("./webworkerAll-B5b1f-BT.js");
18398
18398
  }
18399
18399
  };
18400
18400
  class tt {
@@ -88339,7 +88339,7 @@ class Bte extends vy {
88339
88339
  */
88340
88340
  output(e = {}) {
88341
88341
  if (console.log("Compositor output", e), this.sprites.length === 0) throw Error("No sprite added");
88342
- 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) : 1 / 0);
88342
+ 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);
88343
88343
  if (s === 1 / 0 || s <= 0)
88344
88344
  throw Error(
88345
88345
  "Unable to determine the end time, please specify a main sprite, or limit the duration of Image, Audio"
@@ -88430,13 +88430,13 @@ class Bte extends vy {
88430
88430
  return;
88431
88431
  }
88432
88432
  o = y / t;
88433
- const { audios: b, mainSprDone: C, hasVideo: E } = await u.render(y);
88433
+ const { audios: b, mainSprDone: C } = await u.render(y);
88434
88434
  if (C) {
88435
88435
  h(), await n();
88436
88436
  return;
88437
88437
  }
88438
88438
  if (a.aborted) return;
88439
- this.hasVideoTrack && E && await new Promise((A) => requestAnimationFrame(A)), x(y, b, E), y += g, await QR(e.getEncodeQueueSize);
88439
+ this.hasVideoTrack && await new Promise((E) => requestAnimationFrame(E)), x(y, b, !0), y += g, await QR(e.getEncodeQueueSize);
88440
88440
  }
88441
88441
  }, h = () => {
88442
88442
  a.aborted || (a.aborted = !0, clearInterval(d), u?.cleanup(), this.sprites.forEach((f) => {
@@ -88710,11 +88710,14 @@ function Qee(r) {
88710
88710
  }
88711
88711
  }
88712
88712
  let D = s.get(S);
88713
- D == null && O != null && (D = new jR(
88713
+ if (D == null && O != null && (D = new jR(
88714
88714
  e,
88715
88715
  S,
88716
88716
  p
88717
- ), s.set(S, D)), D != null && (O != null ? (A = !0, await D.updateFrame(O)) : await D.updateFrame(null), D.updateTransforms());
88717
+ ), s.set(S, D)), D != null) {
88718
+ const F = D.getRoot();
88719
+ O != null ? (A = !0, F && (F.visible = !0), await D.updateFrame(O)) : (F && (F.visible = !1), await D.updateFrame(null)), D.updateTransforms();
88720
+ }
88718
88721
  }
88719
88722
  if (S.duration > 0 && I >= S.duration || q) {
88720
88723
  if (S.main && (E = !0), S.expired = !0, n) {
@@ -90999,8 +91002,10 @@ class kte extends vy {
90999
91002
  backgroundColor: this.hexToNumber(this.opts.bgColor),
91000
91003
  antialias: !0,
91001
91004
  resolution: window.devicePixelRatio || 1,
91002
- autoDensity: !0
91003
- }), this.pixiApp = t, 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 qe(), 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 qe(), 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 = It.create({
91005
+ autoDensity: !0,
91006
+ autoStart: !1
91007
+ // Prevent auto-rendering to avoid race conditions during async updates
91008
+ }), 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 qe(), 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 qe(), 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 = It.create({
91004
91009
  width: this.opts.width,
91005
91010
  height: this.opts.height
91006
91011
  }), this.transToTexture = It.create({
@@ -91031,7 +91036,7 @@ class kte extends vy {
91031
91036
  setBgColor(e) {
91032
91037
  this.opts.bgColor = e;
91033
91038
  const t = this.hexToNumber(e);
91034
- this.pixiApp && (this.pixiApp.renderer.background.color = t), this.updateFrame(this.currentTime);
91039
+ this.pixiApp && (this.pixiApp.renderer.background.color = t, this.pixiApp.render()), this.updateFrame(this.currentTime);
91035
91040
  }
91036
91041
  updateDimensions(e, t) {
91037
91042
  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);
@@ -91051,7 +91056,7 @@ class kte extends vy {
91051
91056
  0,
91052
91057
  n - a * 2
91053
91058
  ), c = l / s, h = u / o, d = Math.min(c, h);
91054
- this.artboard.scale.set(d), this.artboard.x = (i - s * d) / 2, this.artboard.y = (n - o * d) / 2;
91059
+ this.artboard.scale.set(d), this.artboard.x = (i - s * d) / 2, this.artboard.y = (n - o * d) / 2, this.pixiApp.render();
91055
91060
  } finally {
91056
91061
  this._isUpdatingLayout = !1;
91057
91062
  }
@@ -91377,9 +91382,11 @@ class kte extends vy {
91377
91382
  o.zIndex = l;
91378
91383
  const u = this.spriteRenderers.get(o);
91379
91384
  if (u) {
91380
- const c = u.getRoot();
91381
- c && (c.zIndex = l);
91385
+ const h = u.getRoot();
91386
+ h && (h.zIndex = l);
91382
91387
  }
91388
+ const c = this.videoSprites.get(o);
91389
+ c && (c.zIndex = l);
91383
91390
  }
91384
91391
  }
91385
91392
  const s = [...this.clips].sort((o, a) => o.zIndex - a.zIndex);
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a4 as t, p as e, q as i, w as o, v as n, t as r, Y as T, a2 as E, I as m, a9 as f, L as g, V as A, P as I, S as C, s as L, u as P, K as S, O as _, V as l, a8 as O, x as c, o as p, a6 as u, a5 as M, l as d, m as F, z as N, W as x, a0 as R, a7 as U, X as V, a3 as y, a1 as k, y as D, J as h, Z as w, n as B, Q as G, _ as J, r as K, U as j, $ as q } from "./index-BXuEu2AS.js";
1
+ import { a4 as t, p as e, q as i, w as o, v as n, t as r, Y as T, a2 as E, I as m, a9 as f, L as g, V as A, P as I, S as C, s as L, u as P, K as S, O as _, V as l, a8 as O, x as c, o as p, a6 as u, a5 as M, l as d, m as F, z as N, W as x, a0 as R, a7 as U, X as V, a3 as y, a1 as k, y as D, J as h, Z as w, n as B, Q as G, _ as J, r as K, U as j, $ as q } from "./index-CZJxf7wC.js";
2
2
  export {
3
3
  t as ANIMATABLE_PROPERTIES,
4
4
  e as Audio,
package/dist/index.umd.js CHANGED
@@ -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
- `,jee={radialSwipe:{label:"Radial Swipe",fragment:eee}},Sh={};function Kee(r,e){Sh[r]=e}function Qee(r){delete Sh[r]}function Xo(){return{...Vo.reduce((r,e)=>(r[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:""},r),{}),...jee,...Sh}}Xo();function Mk(){const r=Object.keys(Sh);return Object.entries(Xo()).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 Zee=Mk();function l1({name:r,renderer:e}){let t=Vo.find(X=>X.name===r);if(!t){const X=Xo(),ie=Object.keys(X).find(fe=>fe.toLowerCase()===r.toLowerCase());ie&&(t=X[ie])}if(t||(t=Vo.find(X=>X.name.toLowerCase()===r.toLowerCase())),!t){const X=[r,r.toLowerCase(),r.charAt(0).toUpperCase()+r.slice(1).toLowerCase(),r.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),r.replace(/_/g,"")],ie=Xo();for(const fe of X){if(t=Vo.find(ye=>ye.name.toLowerCase()===fe.toLowerCase()),t)break;const ae=Object.keys(ie).find(ye=>ye.toLowerCase()===fe.toLowerCase());if(ae){t=ie[ae];break}}}if(!t){const X=Vo.length,ie=Vo.slice(0,5).map(ye=>ye.name).join(", "),fe=Xo(),ae=Object.keys(fe).slice(0,3).join(", ");throw console.error(`Transition not found: "${r}". Available in gl-transitions (${X} total):`,ie+"..."),console.error("Available locally:",ae+"..."),new Error(`Transition "${r}" not found in gl-transitions library or local definitions`)}const i=new $e(Q.WHITE),n=Rt.create({width:e.width,height:e.height}),s=new Vr({}),o=new Vr({}),a=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",l=a?new Vr({}):void 0;let u=null;if(a){u=document.createElement("canvas"),u.width=256,u.height=256;const X=u.getContext("2d");if(X){const ie=X.createImageData(256,256);for(let fe=0;fe<ie.data.length;fe+=4){const ae=Math.random();ie.data[fe]=ae*255,ie.data[fe+1]=ae*255,ie.data[fe+2]=ae*255,ie.data[fe+3]=255}X.putImageData(ie,0,0)}}let c=t.glsl||t.fragment;if(!c)throw new Error(`Transition "${r}" has no glsl or fragment code`);let h={...et.basics,...et.custom(t)};Object.entries(h).forEach(([,X])=>{X.type==="int<f32>"&&(X.type="i32",typeof X.value=="number"&&(X.value=Math.trunc(X.value))),X.type==="ivec2<f32>"&&(X.type="vec2<f32>")});const d=t.name==="GridFlip"||r.toLowerCase()==="gridflip"||t.label==="gridflip",f=t.name==="circle"||r.toLowerCase()==="circle"||t.label==="circle",m=t.name==="directional"||r.toLowerCase()==="directional"||t.label==="directional",p=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",C=t.name==="perlin"||r.toLowerCase()==="perlin"||t.label==="perlin",E=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",P=t.name==="hexagonalize"||r.toLowerCase()==="hexagonalize"||t.label==="hexagonalize",_=t.name==="heart"||r.toLowerCase()==="heart"||t.label==="heart",S=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",I=t.name==="directionalwipe"||r.toLowerCase()==="directionalwipe"||r.toLowerCase()==="directional_wipe"||t.label==="directionalwipe",M=t.name==="directionalwarp"||r.toLowerCase()==="directionalwarp"||r.toLowerCase()==="directional_warp"||t.label==="directionalwarp",O=t.name==="crosshatch"||r.toLowerCase()==="crosshatch"||t.label==="crosshatch",z=t.name==="circleopen"||r.toLowerCase()==="circleopen"||r.toLowerCase()==="circle_open"||t.label==="circleopen",j=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",F=t.name==="GlitchDisplace"||r.toLowerCase()==="glitchDisplace"||t.label==="GlitchDisplace",Y=t.name==="CrossZoom"||r.toLowerCase()==="crosszoom"||t.label==="CrossZoom",W=t.name==="CrazyParametricFun"||r.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",re=t.name==="BowTieHorizontal"||r.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",K=t.name==="PolkaDotsCurtain"||r.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",Pe=t.name==="Pixelize"||r.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(c=tee,h={...et.basics,...ree}),f&&(c=iee,h={...et.basics,...Fk}),m&&(c=nee,h={...et.basics,...see}),p&&(c=oee,h={...et.basics,...aee}),g&&(c=lee,h={...et.basics,...uee}),v&&(c=cee,h={...et.basics,...hee}),x&&(c=dee,h={...et.basics,...fee}),y&&(c=pee,h={...et.basics,...mee}),b&&(c=H4,h={...et.basics,...W4}),C&&(c=xee,h={...et.basics,...yee}),E&&(c=bee,h={...et.basics,..._ee}),A&&(c=wee,h={...et.basics,...See}),P&&(c=Tee,h={...et.basics,...Cee}),_&&(c=Aee,h={...et.basics,...Eee}),S&&(c=Pee,h={...et.basics,...Iee}),I&&(c=Bee,h={...et.basics,...kee}),M&&(c=Ree,h={...et.basics,...Fee}),O&&(c=Mee,h={...et.basics,...Dee}),z&&(c=Oee,h={...et.basics,...Fk}),j&&(c=Uee,h={...et.basics,...zee}),D&&(c=Lee,h={...et.basics,...Nee}),F&&(c=Gee),Y&&(c=Hee,h={...et.basics,...Wee}),W&&(c=Vee,h={...et.basics,...Xee}),re&&(c=Yee),K&&(c=qee),Pe&&(c=gee,h={...et.basics,...vee});const ne={from:s,to:o,uniforms:h};a&&l&&(ne.displacementMap=l,u&&(l.resource=u,l.update()));const oe=new xe({glProgram:new ce({vertex:Z$,fragment:$$(c)}),resources:ne});return i.filters=[oe],{render({width:X,height:ie,from:fe,to:ae,progress:ye}){if((i.width!==X||i.height!==ie)&&(i.setSize({width:X,height:ie}),n.resize(X,ie)),fe instanceof Q?oe.resources.from=fe.source:(s.resource=fe,s.update(),oe.resources.from=s),ae instanceof Q?oe.resources.to=ae.source:(o.resource=ae,o.update(),oe.resources.to=o),a&&l&&u){if(u.width!==X||u.height!==ie){u.width=X,u.height=ie;const Xe=u.getContext("2d");if(Xe){const De=Xe.createImageData(X,ie);for(let we=0;we<De.data.length;we+=4){const Ye=Math.random();De.data[we]=Ye*255,De.data[we+1]=Ye*255,De.data[we+2]=Ye*255,De.data[we+3]=255}Xe.putImageData(De,0,0)}}l.resource=u,l.update()}return oe.resources.uniforms.uniforms.progress=ye,e.render({container:i,target:n,clear:!0,width:X,height:ie}),n},destroy(){n.destroy(),i.destroy({children:!0})}}}let Jee=0;async function Dk(r){r()>50&&(await H0(15),await Dk(r))}class $ee extends W0{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 B4()).codec,sampleRate:Je.sampleRate,numberOfChannels:Je.channelCount})).supported)??!1}logger=Fe.create(`id:${Jee++},`);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,B4().catch(n=>{this.logger.warn("Failed to detect audio codec:",n)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new pc,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(p=>p.width>0&&p.height>0),f=this.hasVideoTrack&&d;return DO({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||Je.codecType,sampleRate:h||Je.sampleRate,channelCount:Je.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):1/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:m,audio:p}=this.opts,g=Math.round(1e6/f),v=this.sprites.some(b=>b.width>0&&b.height>0);u=ete({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=tte({muxer:e,canvas:this.canvas,outputAudio:p,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:C,hasVideo:E}=await u.render(y);if(C){h(),await n();return}if(a.aborted)return;this.hasVideoTrack&&E&&await new Promise(A=>requestAnimationFrame(A)),x(y,b,E),y+=g,await Dk(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=>kl(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 gr||s instanceof Il)).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 Wo(t);await this.addSprite(i,{main:t.main||!1})}}}function ete(r){const{pixiApp:e,sprites:t,aborter:i}=r,n=e!=null,s=new Map,o=new Map,a=new Map,l=Rt.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),u=Rt.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),c=new je().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),h=new Map,d=async(b,C,E)=>{const A=Math.max(0,Math.min(C-b.display.from,b.duration));b.animate(A*b.playbackRate);const{video:P}=await E(b,A);return P},f=(b,C,E)=>{if(!e)return;const A=b.style||{},{renderTransform:P}=b,_=(P?.mirror??0)>.5;let S;_?(S=new Ai({texture:C instanceof Q?C:Q.from(C),width:1,height:1}),S.texture.source&&(S.texture.source.style.addressMode="mirror-repeat",S.texture.source.update())):S=new $e(C instanceof Q?C:Q.from(C));const I=P?.x??0,M=P?.y??0,O=P?.angle??0,z=P?.scale??1,j=P?.scaleX??1,D=P?.scaleY??1,F=P?.opacity??1,Y=P?.blur??0,W=P?.brightness??1;S.x=b.center.x+I,S.y=b.center.y+M,S.anchor.set(.5,.5);const re=S.texture.width||1,K=S.texture.height||1,Pe=b.type==="Caption",ne=!Pe&&b.width&&b.width!==0?Math.abs(b.width)/re:1,oe=!Pe&&b.height&&b.height!==0?Math.abs(b.height)/K:1;_&&S instanceof Ai&&(S.width=re*5,S.height=K*5,S.tilePosition.set((S.width-re)/2,(S.height-K)/2)),b.flip==="horizontal"?(S.scale.x=-ne*z*j,S.scale.y=oe*z*D):b.flip==="vertical"?(S.scale.x=ne*z*j,S.scale.y=-oe*z*D):(S.scale.x=ne*z*j,S.scale.y=oe*z*D),S.rotation=(b.flip==null?1:-1)*((b.angle+O)*Math.PI)/180,S.alpha=b.opacity*F;const X=[];if(Y>0){const we=new xs;we.strength=Y,we.quality=4,we.repeatEdgePixels=!0,X.push(we)}if(W!==1){const we=new Bo;we.brightness(W,!1),X.push(we)}if(b.chromaKey&&b.chromaKey.enabled){const we=new at({uKeyColor:{value:[0,1,0],type:"vec3<f32>"},uSimilarity:{value:.1,type:"f32"},uSpill:{value:0,type:"f32"}}),Ye=R4(b.chromaKey.color);Ye&&(we.uniforms.uKeyColor[0]=Ye.r/255,we.uniforms.uKeyColor[1]=Ye.g/255,we.uniforms.uKeyColor[2]=Ye.b/255),we.uniforms.uSimilarity=b.chromaKey.similarity,we.uniforms.uSpill=b.chromaKey.spill;const qe=new xe({glProgram:new ce({vertex:Xb,fragment:V4,name:"ChromaKeyShader"}),resources:{chromaUniforms:we}});X.push(qe)}S.filters=X;const ie=A.borderRadius||0;let fe=null;ie>0&&(fe=new je,fe.roundRect(-re/2,-K/2,re,K,Math.min(ie,re/2,K/2)),fe.fill({color:16777215,alpha:1}),S.addChild(fe),S.mask=fe);const ae=A.stroke;let ye=null;if(ae&&ae.width>0){ye=new je;const we=bt(ae.color)??16777215;if(ye.setStrokeStyle({width:ae.width,color:we,alignment:1}),ie>0){const Ye=Math.min(ie,re/2,K/2);ye.roundRect(-re/2,-K/2,re,K,Ye)}else ye.rect(-re/2,-K/2,re,K);ye.stroke(),S.addChild(ye)}const Xe=A.dropShadow;let De=null;if(Xe&&(Xe.blur>0||Xe.distance>0)){De=new je;const we=bt(Xe.color)??0,Ye=Xe.alpha??.5,qe=Xe.distance??0,Ht=Xe.angle??0,_t=Math.cos(Ht)*qe,Ii=Math.sin(Ht)*qe;if(ie>0){const Dn=Math.min(ie,re/2,K/2);De.roundRect(-re/2+_t,-K/2+Ii,re,K,Dn)}else De.rect(-re/2+_t,-K/2+Ii,re,K);De.fill({color:we,alpha:Ye}),S.addChildAt(De,0)}e.renderer.render({container:S,target:E,clear:!0}),C instanceof Q||S.texture.destroy(!0),ye&&ye.destroy(),fe&&fe.destroy(),De&&De.destroy(),S.destroy()};let m=null,p=null,g=null;n&&e!=null&&(m=new Be,p=new Be,g=new Be,p.sortableChildren=!0,g.sortableChildren=!0,e.stage.addChild(p),e.stage.addChild(g),m.visible=!1,e.stage.addChild(m));const v=[...t].sort((b,C)=>b.zIndex-C.zIndex);return{render:async b=>{const C=[];let E=!1,A=!1;const P=new Map,_=async(S,I)=>{if(P.has(S))return P.get(S);const M=await S.getFrame(I);return P.set(S,M),M};for(const S of a.values())S.visible=!1;for(const S of v){if(i.aborted)break;if(b<S.display.from||S.expired){if(n&&e!=null){const D=s.get(S);D&&await D.updateFrame(null)}continue}const I=b-S.display.from,M=I*S.playbackRate;S.animate(M);const{video:O,audio:z,done:j}=await _(S,I);if(C.push(z),n&&e!=null&&p!=null){if(S instanceof Ei){const F=t.find(W=>W.id===S.fromClipId),Y=t.find(W=>W.id===S.toClipId);if(F&&Y){const W=b-S.display.from;if(W>=S.duration){S.expired=!0;const re=a.get(S.id);re&&(re.visible=!1)}else{const re=await d(F,b,_),K=await d(Y,b,_);if(re&&K){const Pe=Math.min(Math.max(W/S.duration,0),1);f(F,re,l),f(Y,K,u);let ne=o.get(S.id);ne||(ne=l1({name:S.transitionEffect.key,renderer:e.renderer}),o.set(S.id,ne));const oe=ne.render({width:e.renderer.width,height:e.renderer.height,from:l,to:u,progress:Pe});let X=a.get(S.id);X||(X=new $e,X.label=`TransitionSprite_${S.id}`,a.set(S.id,X),p.addChild(X)),X.texture=oe,X.visible=!0,X.x=0,X.y=0,X.width=e.renderer.width,X.height=e.renderer.height,X.anchor.set(0,0),X.zIndex=S.zIndex,A=!0;const ie=s.get(F);if(ie){const ae=ie.getRoot();ae&&(ae.visible=!1)}const fe=s.get(Y);if(fe){const ae=fe.getRoot();ae&&(ae.visible=!1)}continue}}}}let D=s.get(S);D==null&&O!=null&&(D=new kk(e,S,p),s.set(S,D)),D!=null&&(O!=null?(A=!0,await D.updateFrame(O)):await D.updateFrame(null),D.updateTransforms())}if(S.duration>0&&I>=S.duration||j){if(S.main&&(E=!0),S.expired=!0,n){const D=s.get(S);if(D!=null){const F=D.getRoot();F&&(F.visible=!1)}}}else if(n){const D=s.get(S);D?.updateTransforms()}}if(n&&e!=null&&m!=null&&p!=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!==p&&(M.parent&&M.parent.removeChild(M),p.addChild(M))}if(S.length>0){const I=e.renderer.width,M=e.renderer.height;let O=null;const z=new Set,j=[];for(const D of S){const{key:F,startTime:Y,duration:W,id:re,zIndex:K}=D,Pe=b-Y,ne=W>0?Math.min(Math.max(Pe/W,0),1):0,oe=t.some(X=>X.id===re&&X instanceof qi);if(m.removeChildren(),O){const X=new $e(O);X.width=I,X.height=M,m.addChild(X)}for(const X of t){if(z.has(X.id))continue;let ie=!1;if(oe?ie=X.id!==re&&X.zIndex<K:ie=!!X.effects&&X.effects.some(fe=>fe.id===re),ie){const fe=s.get(X);if(fe){const ye=fe.getRoot();ye&&(ye.parent&&ye.parent.removeChild(ye),m.addChild(ye),z.add(X.id))}const ae=a.get(X.id);ae&&(ae.parent&&ae.parent.removeChild(ae),m.addChild(ae),z.add(X.id))}}if(m.children.length>0){let X=h.get(re);if(!X)try{const ie=await o1({name:F,renderer:e.renderer,values:D.values});ie&&ie.filter&&(X={filter:ie.filter,render:ie.render},h.set(re,X))}catch(ie){console.warn("Failed to create effect",F,ie)}if(X){const{filter:ie,render:fe}=X;ie.resources&&ie.resources.effectUniforms&&(ie.resources.effectUniforms.uniforms.uTime=ne);const ae=Rt.create({width:I,height:M});j.push(ae),m.visible=!0,e.renderer.render({container:m,target:ae,clear:!0}),m.visible=!1,fe&&(O=fe({canvasTexture:ae,progress:ne,width:I,height:M}))}}}if(O){const D=new $e(O);D.width=I,D.height=M,g.addChild(D)}for(const D of j)D.destroy(!0)}}return n&&e!=null&&e.render(),{audios:C,mainSprDone:E,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(),m&&m.destroy({children:!0}),p&&p.destroy({children:!0}),g&&g.destroy({children:!0}),s.forEach(b=>{b.destroy()}),s.clear()}}}function tte(r){const{canvas:e,outputAudio:t,muxer:i,hasVideoTrack:n,timeSlice:s}=r;let o=0;const a=Math.floor(3*r.fps),l=rte(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 rte(r){const e=r*Je.channelCount,t=new Float32Array(e*3);let i=0,n=0;const s=r/Je.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:Je.channelCount,numberOfFrames:r,sampleRate:Je.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:Je.channelCount,numberOfFrames:r,sampleRate:Je.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 m=0;m<u.length;m++){const p=u[m][0]?.[h]??0,g=u[m][1]?.[h]??p;d+=p,f+=g}t[i]=d,t[i+1]=f,i+=2}return a(l)}}class ite extends je{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(e,t=1){const n=1.5*t;this.clear(),this.setStrokeStyle({width:n,color:165063}).rect(e.x,e.y,e.width,e.height).stroke(),this.hitArea=e}}class Ki extends je{#e=!1;handle;cursor;callbacks;constructor(e,t,i){super(),this.handle=e,this.cursor=t,this.callbacks=i,this.eventMode="static",this.#l(),this.on("pointerdown",this.#r),this.on("globalpointermove",this.#n),this.on("pointerup",this.#u),this.on("pointerupoutside",this.#u)}#l(){this.clear();const e=165063;if(this.handle==="rot")this.circle(0,0,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-4),this.arc(0,0,4,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new nl(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 me(-15,-15,30,30)}else this.rect(-4,-4,8,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new me(-15,-15,30,30)}#r=e=>{this.#e=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,e.global),e.stopPropagation()};#n=e=>{this.#e&&(this.callbacks.updateDrag(this.handle,e.global),e.stopPropagation())};#u=e=>{this.#e&&(this.#e=!1,this.cursor="pointer",this.callbacks.endDrag(),e.stopPropagation())}}class Th{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=Th.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 m=d.value-f.value;if(Math.abs(m)<s){i=m,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 m=d.value-f.value;if(Math.abs(m)<s){n=m,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=Th.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 Ok={delta:new le};class nte extends Be{group;wireframe=new ite;selectionOutlines=new je;isDragging=!1;lastPointer=new ve;activeHandle=null;#e;#l=new Map;#r=new ve;#n=0;#u=0;#c=new me;#i=new ve;#s=new me;#t=[new ve,new ve,new ve,new ve];#o=1;#a=1;#h;#d=new je;#m=new ve;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static",this.#h=new Th(e.artboardWidth??1920,e.artboardHeight??1080),this.addChild(this.#d);const t={beginDrag:(i,n)=>this.#C(i,n),updateDrag:(i,n)=>this.#A(i,n),endDrag:()=>this.#v()};this.#e={tl:new Ki("tl","nwse-resize",t),tr:new Ki("tr","nesw-resize",t),bl:new Ki("bl","nesw-resize",t),br:new Ki("br","nwse-resize",t),ml:new Ki("ml","ew-resize",t),mr:new Ki("mr","ew-resize",t),mt:new Ki("mt","ns-resize",t),mb:new Ki("mb","ns-resize",t),rot:new Ki("rot","crosshair",{beginDrag:(i,n)=>this.#I(n),updateDrag:(i,n)=>this.#B(n),endDrag:()=>this.#v()})},this.addChild(this.selectionOutlines,this.wireframe,...Object.values(this.#e)),this.#_(),this.visible=!1,Pt.shared.addOnce(()=>{!this.destroyed&&this.parent&&(this.#f(),this.visible=!0)})}#_(){this.on("pointerdown",this.#w),this.on("pointerup",this.#x),this.on("pointerupoutside",this.#x),this.on("globalpointermove",this.#S)}#f(){if(this.group.length===1){const e=this.group[0];this.#n=e.rotation;const t=this.#g(e);let i,n;this.opts.clip?(i=this.opts.clip.width,n=this.opts.clip.height):(i=t.width,n=t.height);const s=e.toGlobal(new ve(0,0));this.#r.set(s.x,s.y),this.#s.copyFrom(new me(-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 me(-s/2,-o/2,s,o)),this.parent){const u=this.toGlobal(new ve(a,l));this.#r.set(u.x,u.y)}}this.#p()}#g(e){let t=null;const i=u=>{if(u.label==="MainSprite"&&u instanceof $e)return u;for(const c of u.children)if(c instanceof Be){const h=i(c);if(h)return h}return null};if(t=i(e),t){const u=t.getLocalBounds(),c=t.localTransform.clone(),h=c.apply(new ve(u.x,u.y)),d=c.apply(new ve(u.x+u.width,u.y)),f=c.apply(new ve(u.x+u.width,u.y+u.height)),m=c.apply(new ve(u.x,u.y+u.height)),p=Math.min(h.x,d.x,f.x,m.x),g=Math.max(h.x,d.x,f.x,m.x),v=Math.min(h.y,d.y,f.y,m.y),x=Math.max(h.y,d.y,f.y,m.y);return new me(p,v,g-p,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 me(c.minX,c.minY,c.maxX-c.minX,c.maxY-c.minY)}}for(const u of l){const c=u.getBounds(),h=e.toLocal(new ve(c.minX,c.minY)),d=e.toLocal(new ve(c.maxX,c.maxY));n=Math.min(n,h.x,d.x),s=Math.min(s,h.y,d.y),o=Math.max(o,h.x,d.x),a=Math.max(a,h.y,d.y)}if(n===1/0){const u=e.getLocalBounds();return new me(u.minX,u.minY,u.maxX-u.minX,u.maxY-u.minY)}return new me(n,s,o-n,a-s)}updateBounds(){this.#f()}#w=e=>{this.#f(),this.#m.copyFrom(this.#r),this.isDragging=!0,this.lastPointer.copyFrom(e.global),this.cursor="grabbing"};#x=()=>{this.isDragging&&this.#v(),this.cursor="default"};#S=e=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const{moveDx:t,moveDy:i,newPivotWorld:n}=this.#T(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")};#T(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 me(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.#y(u,t);const c=s.x+a,h=s.y+l,d=this.parent.toLocal(this.#r),f=c-d.x,m=h-d.y,p=this.parent.toGlobal(new ve(c,h));return{moveDx:f,moveDy:m,newPivotWorld:p}}#C(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.#R(e)}#A(e,t){this.#E(e,t)}async#E(e,t){const{proposed:i,sx:n,sy:s,pivotWorld:o}=await this.#P(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.#b(this.#M(o,this.#n,n,s)),this.#s.copyFrom(i),this.#p(),this.emit("transforming")}async#P(e,t){const i=this.#i,n=this.#F(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.#y(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}}#I(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)}#B(e){const i=Math.atan2(e.y-this.#r.y,e.x-this.#r.x)-this.#u,n=this.#n+i;this.#b(this.#D(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")}#y(e,t){if(this.#d.clear(),!(!e.length||!this.parent)){this.#d.stroke({width:1/t,color:4774907});for(const i of e){let n,s;i.type==="vertical"?(n=new ve(i.position,i.start),s=new ve(i.position,i.end)):(n=new ve(i.start,i.position),s=new ve(i.end,i.position)),this.toLocal(n,this.parent,n),this.toLocal(s,this.parent,s),this.#d.moveTo(n.x,n.y).lineTo(s.x,s.y).stroke({width:1/t,color:4774907})}}}#p(e=this.#n){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#r)),this.rotation=e;const i=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),n=this.#s;this.wireframe.draw(n,i);const s=n.x+n.width/2,o=n.y+n.height/2,a=this.opts.clip?.getVisibleHandles?.()??["tl","tr","bl","br","ml","mr","mt","mb","rot"],l=[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 u of l)u.scale.set(i);this.#e.tl.visible=a.includes("tl"),this.#e.tr.visible=a.includes("tr"),this.#e.bl.visible=a.includes("bl"),this.#e.br.visible=a.includes("br"),this.#e.ml.visible=a.includes("ml"),this.#e.mr.visible=a.includes("mr"),this.#e.mt.visible=a.includes("mt"),this.#e.mb.visible=a.includes("mb"),this.#e.rot.visible=a.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.#k(i)}#k(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)}}#R(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)}#F(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 me(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 me(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 me(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 me(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 me(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 me(s,n.y,i.x-s,n.height)}if(e==="mr"){const s=Math.max(t.x,i.x+this.#o);return new me(i.x,n.y,s-i.x,n.height)}if(e==="mt"){const s=Math.min(t.y,i.y-this.#a);return new me(n.x,s,n.width,i.y-s)}if(e==="mb"){const s=Math.max(t.y,i.y+this.#a);return new me(n.x,i.y,n.width,s-i.y)}return new me(i.x,i.y,this.#o,this.#a)}#M(e,t,i,n){return Ok.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(i,n).rotate(t).translate(e.x,e.y)}#D(e,t){return Ok.delta.identity().translate(-e.x,-e.y).rotate(t).translate(e.x,e.y)}#b(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 ste{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new ve;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;init(e,t){this.selectionGraphics=new je,this.selectionGraphics.visible=!1,this.selectionGraphics.zIndex=1e3,t.addChild(this.selectionGraphics),e.stage.eventMode="static",e.stage.hitArea=e.screen,e.stage.on("pointerdown",i=>this.onStagePointerDown(i)),e.stage.on("globalpointermove",i=>this.onStagePointerMove(i)),e.stage.on("pointerup",()=>this.onStagePointerUp()),e.stage.on("pointerupoutside",()=>this.onStagePointerUp())}onStagePointerDown(e){e.target===this.studio.pixiApp?.stage&&(e.shiftKey||this.deselectClip(),this.isDragSelecting=!0,this.studio.artboard?.toLocal(e.global,void 0,this.dragSelectionStart),this.selectionGraphics&&(this.selectionGraphics.clear(),this.selectionGraphics.visible=!0))}onStagePointerMove(e){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const t=this.studio.artboard.toLocal(e.global),i=Math.min(this.dragSelectionStart.x,t.x),n=Math.min(this.dragSelectionStart.y,t.y),s=Math.abs(t.x-this.dragSelectionStart.x),o=Math.abs(t.y-this.dragSelectionStart.y);this.selectionGraphics.clear(),this.selectionGraphics.rect(i,n,s,o).fill({color:703971,alpha:.3}),this.selectionGraphics.rect(i,n,s,o).stroke({width:2,color:703971})}}onStagePointerUp(){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const e=this.selectionGraphics.getBounds(),t=[],i=new me(e.x,e.y,e.width,e.height);if(i.width>2||i.height>2){for(const n of this.studio.clips){const s=this.studio.spriteRenderers.get(n);if(!s)continue;const o=s.getRoot();if(!o||!o.visible)continue;const a=o.getBounds();i.x<a.x+a.width&&i.x+i.width>a.x&&i.y<a.y+a.height&&i.y+i.height>a.y&&t.push(n)}if(t.length>0)for(const n of t)this.selectClip(n,!0)}this.selectionGraphics.clear(),this.selectionGraphics.visible=!1,this.isDragSelecting=!1}}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)});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)})}}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:[]})}}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})}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 n of this.selectedClips){const s=this.studio.spriteRenderers.get(n);if(s==null)continue;const o=s.getRoot();o!=null&&(e.push(o),this.selectedClips.size===1&&(t=n))}if(e.length===0){console.warn("Cannot create transformer: no sprites found");return}this.activeTransformer=new nte({group:e,clip:t,artboardWidth:this.studio.opts.width,artboardHeight:this.studio.opts.height});let i=null;this.activeTransformer.on("transforming",()=>{i===null&&(i=requestAnimationFrame(()=>{i=null,this.syncSelectedClipsTransformsRealtime()}))}),this.activeTransformer.on("textClipResize",n=>{this.textClipResizedWidth=n.newWidth,this.textClipResizeHandle=n.handle,this.textClipResizedSx=n.sx,this.textClipResizedSy=n.sy}),this.activeTransformer.on("transformEnd",async()=>{i!==null&&(cancelAnimationFrame(i),i=null),await this.syncSelectedClipsTransforms();for(const n of this.selectedClips)this.studio.emit("clip:updated",{clip:n})}),this.activeTransformer.on("pointerdown",n=>{const s=this.getTopmostClipAtPoint(n.global);s&&!this.selectedClips.has(s)&&(this.selectClip(s,n.shiftKey),n.stopPropagation())}),this.studio.artboard.addChild(this.activeTransformer)}async syncSelectedClipsTransformsRealtime(){if(!(this.selectedClips.size===0||this.activeTransformer==null)&&!this.isUpdatingTextRealtime){this.isUpdatingTextRealtime=!0;try{const e=this.activeTransformer.activeHandle;if(e!=="mr"&&e!=="ml")return;for(const t of this.selectedClips){if(!(t instanceof Yi))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 Yi||e instanceof Mn)&&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 Yi||e instanceof Mn)&&this.textClipResizedWidth!==null){const p={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,p.fontSize=d):["bl","tl"].includes(this.textClipResizeHandle)&&(f=e.left+u/2-(u-c),p.fontSize=d),await e.updateStyle(p);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 p=a,g=l;e.left=i.x-p/2,e.top=i.y-g/2,e.width=p,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 ote{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 Yo{static instance;fonts=new Map;constructor(){}static getInstance(){return Yo.instance||(Yo.instance=new Yo),Yo.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 Uk=Yo.getInstance();class ate{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 m=this.tracks.find(p=>p.id===h);if(m){const p=m.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 p)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 Ei(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 kk(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,n=this.clips.findIndex(c=>c===e);if(n===-1)return;if(e instanceof Ei){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){const n=this.clips.findIndex(u=>u===i);if(n===-1)continue;if(i instanceof Ei){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&&(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=>kl(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()!=="");await 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 Wo(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&&await Promise.all(this.clips.map(async 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),await i.ready,await this.setupClipVisuals(i)}));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 Ei){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);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=kl(n,!1),l=await Wo(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],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=kl(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 Wo(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],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 Uk.loadFonts(Array.from(t.values()))}catch(i){console.warn("Failed to load some fonts:",i)}}async recalculateMaxDuration(){let e=0;for(const t of this.clips){t.display.to===0&&t.duration!==1/0&&!isNaN(t.duration)&&t.duration>0;const i=t.duration>0?t.duration:0;if(i===1/0)continue;const n=t.display.to>0?t.display.to:t.display.from+i;n>e&&(e=n)}this.studio.maxDuration=e}async setupPlaybackForClip(e,t){if(this.studio.pixiApp!=null&&this.isPlaybackCapable(e))try{const i=e;if(e.type==="Audio"&&t&&typeof t!="string"){const o=URL.createObjectURL(t);e.src=o}const{element:n,objectUrl:s}=await i.createPlaybackElement();if(e.type==="Video"){const o=Q.from(n),a=new $e(o);a.visible=!1,this.studio.clipsNormalContainer&&this.studio.clipsNormalContainer.addChild(a),this.studio.videoSprites.set(e,a)}this.studio.transport.playbackElements.set(e,{element:n,objectUrl:s})}catch(i){console.warn(`Failed to setup playback for ${e.constructor.name}`,i)}}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async clear(){this.studio.selection.deselectClip(),this.studio.selection.interactiveClips.clear();for(const[e,t]of this.studio.clipListeners)e.off("propsChange",t);this.studio.clipListeners.clear(),this.studio.globalEffects.clear(),this.studio.effectFilters.clear(),this.studio.transitionRenderers.forEach(e=>e.destroy()),this.studio.transitionRenderers.clear(),this.studio.transitionSprites.forEach(e=>{e.parent&&e.parent.removeChild(e),e.destroy()}),this.studio.transitionSprites.clear(),this.studio.spriteRenderers.forEach(e=>e.destroy()),this.studio.spriteRenderers.clear();for(const[e,t]of this.studio.transport.playbackElements)this.isPlaybackCapable(e)&&e.cleanupPlayback(t.element,t.objectUrl);this.studio.transport.playbackElements.clear();for(const e of this.studio.videoSprites.values())e.destroy();this.studio.videoSprites.clear(),this.tracks=[],this.clips=[],this.studio.maxDuration=0,this.studio.currentTime=0,this.studio.emit("reset")}async rippleDelete(e,t){if(e>=t)return;const i=t-e,n=[...this.clips];for(const s of n){const o=s.display.from,a=s.display.to;if(!(a<=e)){if(o>=t){await this.updateClip(s.id,{display:{from:s.display.from-i,to:s.display.to-i}});continue}if(o>=e&&a<=t){await this.removeClip(s);continue}if(o<e&&a>t){const l=await s.clone();l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const u=e,c=e+(a-t),h=s.trim.from+(t-o)*s.playbackRate,d=s.trim.to,f=this.tracks.find(m=>m.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 lte={Date:!0,RegExp:!0,String:!0,Number:!0};function zk(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&&!lte[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!i.includes(l))?n.push.apply(n,zk(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 ute{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=zk(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 m=0;m<l.length-1;m++){if(h[l[m]]===void 0||h[l[m]]===null){d=!0;break}h=h[l[m]]}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 cte extends W0{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 ste(this),this.transport=new ote(this),this.timeline=new ate(this),this.history=new ute,this.resourceManager=new Uo,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 Wo(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 pc,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}),this.pixiApp=t,t.stage.eventMode="static",t.stage.hitArea=t.screen,this.artboard=new Be,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new je,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new Be,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new je,this.artboardMask.rect(0,0,this.opts.width,this.opts.height).fill({color:16777215}),this.clipContainer.addChild(this.artboardMask),this.clipContainer.mask=this.artboardMask,this.clipsEffectContainer=new Be,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new Be,this.clipsNormalContainer.label="ClipsNormal",this.clipsNormalContainer.zIndex=10,this.clipsNormalContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsNormalContainer),this.transFromTexture=Rt.create({width:this.opts.width,height:this.opts.height}),this.transToTexture=Rt.create({width:this.opts.width,height:this.opts.height}),this.transBgGraphics=new je,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}),this.clipContainer.sortableChildren=!0,this.updateArtboardLayout(),t.renderer.on("resize",()=>{this.handleResize()})}getOptions(){return this.opts}setSize(e,t){this.updateDimensions(e,t)}setBgColor(e){this.opts.bgColor=e;const t=this.hexToNumber(e);this.pixiApp&&(this.pixiApp.renderer.background.color=t),this.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}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 c=u.getRoot();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,m=o.transition?o.transition.end:0,p=d&&o.transition&&e>=f&&e<m;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=!p&&v>=0&&v<y,x.visible&&j$(o,x),!p)continue}}else continue}if(p){const v=o?.transition?.fromClipId,x=o?.transition?.toClipId,y=`${v}_${x}`;if(i.has(y)){const P=this.spriteRenderers.get(o);P?.getRoot()&&(P.getRoot().visible=!1);const _=this.videoSprites.get(o);_&&(_.visible=!1);continue}i.add(y),this.transFromTexture||(this.transFromTexture=Rt.create({width:this.opts.width,height:this.opts.height})),this.transToTexture||(this.transToTexture=Rt.create({width:this.opts.width,height:this.opts.height})),this.transBgGraphics||(this.transBgGraphics=new je,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}));const b=v?this.getClipById(v):null,C=x?this.getClipById(x):null;let E=null,A=null;if(b){const P=Math.max(0,e-b.display.from),{video:_}=await b.getFrame(P);_ instanceof HTMLVideoElement?E=this.getVideoTexture(_):E=_,E&&(this.lastFromFrame=E)}if(C){const P=Math.max(0,e-C.display.from),{video:_}=await C.getFrame(P);_ instanceof HTMLVideoElement?A=this.getVideoTexture(_):A=_,A&&(this.lastToFrame=A)}if(E||(E=this.lastFromFrame),A||(A=this.lastToFrame),!E||!A)continue;if(E&&A&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const P=(e-f)/o?.transition?.duration;b&&E&&this.renderClipToTransitionTexture(b,E,this.transFromTexture),C&&A&&this.renderClipToTransitionTexture(C,A,this.transToTexture);let _=this.transitionRenderers.get(y);if(!_)try{_=l1({name:o?.transition?.name,renderer:this.pixiApp.renderer}),this.transitionRenderers.set(y,_)}catch(S){console.error("[Studio] Failed to create transition renderer:",S)}if(_){const S=_.render({width:this.opts.width,height:this.opts.height,from:this.transFromTexture,to:this.transToTexture,progress:P});let I=this.transitionSprites.get(o.id);I||(I=new $e,I.label=`TransitionSprite_${o.id}`,this.transitionSprites.set(o.id,I),this.clipsNormalContainer&&this.clipsNormalContainer.addChild(I)),I.texture=S,I.visible=!0,I.x=0,I.y=0,I.width=this.opts.width,I.height=this.opts.height,I.anchor.set(0,0),I.zIndex=o.zIndex,t.add(o.id);const M=this.spriteRenderers.get(o);M?.getRoot()&&(M.getRoot().visible=!1);const O=this.videoSprites.get(o);if(O&&(O.visible=!1),b){const z=this.spriteRenderers.get(b);z?.getRoot()&&(z.getRoot().visible=!1);const j=this.videoSprites.get(b);j&&(j.visible=!1)}if(C){const z=this.spriteRenderers.get(C);z?.getRoot()&&(z.getRoot().visible=!1);const j=this.videoSprites.get(C);j&&(j.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 Il&&o.addEffect(s),o instanceof gr&&o.addEffect(s),o instanceof Yi&&o.addEffect(s),o instanceof Mn&&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 gr||i instanceof Il)).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;let a;o?(a=new Ai({texture:t instanceof Q?t:Q.from(t),width:1,height:1}),a.texture.source&&(a.texture.source.style.addressMode="mirror-repeat",a.texture.source.update())):a=new $e(t instanceof Q?t:Q.from(t));const l=s?.x??0,u=s?.y??0,c=s?.angle??0,h=s?.scale??1,d=s?.opacity??1,f=s?.blur??0,m=s?.brightness??1;a.x=e.center.x+l,a.y=e.center.y+u,a.anchor.set(.5,.5);const p=a.texture.width||1,g=a.texture.height||1,v=e.type==="Caption",x=!v&&e.width&&e.width!==0?Math.abs(e.width)/p:1,y=!v&&e.height&&e.height!==0?Math.abs(e.height)/g:1;o&&a instanceof Ai&&(a.width=p*5,a.height=g*5,a.tilePosition.set((a.width-p)/2,(a.height-g)/2)),e.flip==="horizontal"?(a.scale.x=-x*h,a.scale.y=y*h):e.flip==="vertical"?(a.scale.x=x*h,a.scale.y=-y*h):(a.scale.x=x*h,a.scale.y=y*h),a.rotation=(e.flip==null?1:-1)*((e.angle+c)*Math.PI)/180,a.alpha=e.opacity*d;const b=[];if(f>0){const I=new xs;I.strength=f,I.quality=4,I.repeatEdgePixels=!0,b.push(I)}if(m!==1){const I=new Bo;I.brightness(m,!1),b.push(I)}a.filters=b;const C=n.borderRadius||0;let E=null;C>0&&(E=new je,E.roundRect(-p/2,-g/2,p,g,Math.min(C,p/2,g/2)),E.fill({color:16777215,alpha:1}),a.addChild(E),a.mask=E);const A=n.stroke;let P=null;if(A&&A.width>0){P=new je;const I=bt(A.color)??16777215;if(P.setStrokeStyle({width:A.width,color:I,alignment:1}),C>0){const M=Math.min(C,p/2,g/2);P.roundRect(-p/2,-g/2,p,g,M)}else P.rect(-p/2,-g/2,p,g);P.stroke(),a.addChild(P)}const _=n.dropShadow;let S=null;if(_&&(_.blur>0||_.distance>0)){S=new je;const I=bt(_.color)??0,M=_.alpha??.5,O=_.distance??0,z=_.angle??0,j=Math.cos(z)*O,D=Math.sin(z)*O;if(C>0){const F=Math.min(C,p/2,g/2);S.roundRect(-p/2+j,-g/2+D,p,g,F)}else S.rect(-p/2+j,-g/2+D,p,g);S.fill({color:I,alpha:M}),a.addChildAt(S,0)}this.pixiApp.renderer.render({container:a,target:i,clear:!0}),t instanceof Q||a.texture.destroy(!0),E&&E.destroy(),P&&P.destroy(),S&&S.destroy(),a.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,m=Math.min(Math.max(f/c,0),1);if(m<0||m>=1)continue;if(this.clipsEffectContainer.visible=!0,this.clipsEffectContainer.removeChildren(),n){const y=new $e(n);y.label="PrevEffectResult",y.width=t,y.height=i,this.clipsEffectContainer.addChild(y)}const p=h??-1;for(const y of this.clips){if(s.has(y.id))continue;const b=this.getTrackIndex(y.id);!(y instanceof qi)&&(p===-1||b>p)&&(this.moveClipToEffectContainer(y,!0),s.add(y.id))}let g=this.effectFilters.get(l);if(!g)try{if(g=await o1({name:l,renderer:this.pixiApp.renderer,values:d}),g)this.effectFilters.set(l,g);else continue}catch(y){console.error(y);continue}const v=Rt.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:m,width:t,height:i,values:d});this.clipsEffectContainer.visible=!1,n=x}if(n){const a=new $e(n);a.x=0,a.y=0,a.width=t,a.height=i,a.scale.set(1),a.zIndex=5,this.clipContainer.addChild(a),this.currentGlobalEffectSprite=a}for(const a of o)a.destroy(!0)}destroy(){if(!this.destroyed){window.removeEventListener("resize",this.handleResize),this.destroyed=!0,this.stop(),this.clear(),this.transitionRenderers.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null);for(const e of this.transitionSprites.values())e.destroy();this.transitionSprites.clear(),this.pixiApp&&(this.pixiApp.destroy(!0,{children:!0,texture:!0}),this.pixiApp=null)}}selectClip(e,t=!1){this.selection.selectClip(e,t)}setSelection(e){this.selection.setSelection(e)}selectClipsByIds(e){this.selection.selectClipsByIds(e)}deselectClip(){this.selection.deselectClip()}exportToJSON(){return this.timeline.exportToJSON()}async loadFromJSON(e){return this.timeline.loadFromJSON(e)}}be.add($T),be.mixin(Be,eC),be.add(Mx),be.add(Dx),be.add(Uy),be.mixin(Be,pP),be.add(My),be.add(vb),be.add(Ic),be.add(yb),be.add(Sb),be.add(Tb),be.add(zb),be.add(Ub),be.add(Rb),be.add(Db),be.add(Fb),be.add(Ib),be.add(Ab),be.add(qy),be.add(Vy);const hte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),dte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));Se.ANIMATABLE_PROPERTIES=kL,Se.Audio=jr,Se.Caption=Mn,Se.Compositor=$ee,Se.DEFAULT_AUDIO_CONF=Je,Se.Effect=qi,Se.GL_EFFECT_OPTIONS=iQ,Se.GL_TRANSITION_OPTIONS=Zee,Se.Image=Il,Se.KeyframeAnimation=k,Se.Log=Fe,Se.MP4Clip=gr,Se.Placeholder=Bl,Se.Studio=cte,Se.Text=Yi,Se.Transition=Ei,Se.VALUES_FILTER_SPECIAL=s1,Se.VALUES_FILTER_SPECIAL_LIMITS=X$,Se.Video=gr,Se.animationRegistry=L,Se.clipToJSON=kl,Se.createChromakey=wL,Se.createSlowMo=iS,Se.easings=_u,Se.fastConcatMP4=G4,Se.fixFMP4Duration=fq,Se.fontManager=Uk,Se.getAllEffects=Yb,Se.getAllTransitions=Xo,Se.getEasing=V0,Se.getEffectOptions=X4,Se.getPresetTemplate=q,Se.getTransitionOptions=Mk,Se.jsonToClip=Wo,Se.makeEffect=o1,Se.makeTransition=l1,Se.mixinMP4AndAudio=vq,Se.registerCustomEffect=eQ,Se.registerCustomTransition=Kee,Se.renderTxt2ImgBitmap=IL,Se.unregisterCustomEffect=tQ,Se.unregisterCustomTransition=Qee,Object.defineProperty(Se,Symbol.toStringTag,{value:"Module"})}));
14345
+ `,jee={radialSwipe:{label:"Radial Swipe",fragment:eee}},Sh={};function Kee(r,e){Sh[r]=e}function Qee(r){delete Sh[r]}function Xo(){return{...Vo.reduce((r,e)=>(r[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:""},r),{}),...jee,...Sh}}Xo();function Mk(){const r=Object.keys(Sh);return Object.entries(Xo()).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 Zee=Mk();function l1({name:r,renderer:e}){let t=Vo.find(X=>X.name===r);if(!t){const X=Xo(),ie=Object.keys(X).find(fe=>fe.toLowerCase()===r.toLowerCase());ie&&(t=X[ie])}if(t||(t=Vo.find(X=>X.name.toLowerCase()===r.toLowerCase())),!t){const X=[r,r.toLowerCase(),r.charAt(0).toUpperCase()+r.slice(1).toLowerCase(),r.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),r.replace(/_/g,"")],ie=Xo();for(const fe of X){if(t=Vo.find(ye=>ye.name.toLowerCase()===fe.toLowerCase()),t)break;const ae=Object.keys(ie).find(ye=>ye.toLowerCase()===fe.toLowerCase());if(ae){t=ie[ae];break}}}if(!t){const X=Vo.length,ie=Vo.slice(0,5).map(ye=>ye.name).join(", "),fe=Xo(),ae=Object.keys(fe).slice(0,3).join(", ");throw console.error(`Transition not found: "${r}". Available in gl-transitions (${X} total):`,ie+"..."),console.error("Available locally:",ae+"..."),new Error(`Transition "${r}" not found in gl-transitions library or local definitions`)}const i=new $e(Q.WHITE),n=Rt.create({width:e.width,height:e.height}),s=new Vr({}),o=new Vr({}),a=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",l=a?new Vr({}):void 0;let u=null;if(a){u=document.createElement("canvas"),u.width=256,u.height=256;const X=u.getContext("2d");if(X){const ie=X.createImageData(256,256);for(let fe=0;fe<ie.data.length;fe+=4){const ae=Math.random();ie.data[fe]=ae*255,ie.data[fe+1]=ae*255,ie.data[fe+2]=ae*255,ie.data[fe+3]=255}X.putImageData(ie,0,0)}}let c=t.glsl||t.fragment;if(!c)throw new Error(`Transition "${r}" has no glsl or fragment code`);let h={...et.basics,...et.custom(t)};Object.entries(h).forEach(([,X])=>{X.type==="int<f32>"&&(X.type="i32",typeof X.value=="number"&&(X.value=Math.trunc(X.value))),X.type==="ivec2<f32>"&&(X.type="vec2<f32>")});const d=t.name==="GridFlip"||r.toLowerCase()==="gridflip"||t.label==="gridflip",f=t.name==="circle"||r.toLowerCase()==="circle"||t.label==="circle",m=t.name==="directional"||r.toLowerCase()==="directional"||t.label==="directional",p=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",C=t.name==="perlin"||r.toLowerCase()==="perlin"||t.label==="perlin",E=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",P=t.name==="hexagonalize"||r.toLowerCase()==="hexagonalize"||t.label==="hexagonalize",_=t.name==="heart"||r.toLowerCase()==="heart"||t.label==="heart",S=t.name==="displacement"||r.toLowerCase()==="displacement"||t.label==="displacement",I=t.name==="directionalwipe"||r.toLowerCase()==="directionalwipe"||r.toLowerCase()==="directional_wipe"||t.label==="directionalwipe",M=t.name==="directionalwarp"||r.toLowerCase()==="directionalwarp"||r.toLowerCase()==="directional_warp"||t.label==="directionalwarp",O=t.name==="crosshatch"||r.toLowerCase()==="crosshatch"||t.label==="crosshatch",z=t.name==="circleopen"||r.toLowerCase()==="circleopen"||r.toLowerCase()==="circle_open"||t.label==="circleopen",j=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",F=t.name==="GlitchDisplace"||r.toLowerCase()==="glitchDisplace"||t.label==="GlitchDisplace",Y=t.name==="CrossZoom"||r.toLowerCase()==="crosszoom"||t.label==="CrossZoom",W=t.name==="CrazyParametricFun"||r.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",re=t.name==="BowTieHorizontal"||r.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",K=t.name==="PolkaDotsCurtain"||r.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",Pe=t.name==="Pixelize"||r.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(c=tee,h={...et.basics,...ree}),f&&(c=iee,h={...et.basics,...Fk}),m&&(c=nee,h={...et.basics,...see}),p&&(c=oee,h={...et.basics,...aee}),g&&(c=lee,h={...et.basics,...uee}),v&&(c=cee,h={...et.basics,...hee}),x&&(c=dee,h={...et.basics,...fee}),y&&(c=pee,h={...et.basics,...mee}),b&&(c=H4,h={...et.basics,...W4}),C&&(c=xee,h={...et.basics,...yee}),E&&(c=bee,h={...et.basics,..._ee}),A&&(c=wee,h={...et.basics,...See}),P&&(c=Tee,h={...et.basics,...Cee}),_&&(c=Aee,h={...et.basics,...Eee}),S&&(c=Pee,h={...et.basics,...Iee}),I&&(c=Bee,h={...et.basics,...kee}),M&&(c=Ree,h={...et.basics,...Fee}),O&&(c=Mee,h={...et.basics,...Dee}),z&&(c=Oee,h={...et.basics,...Fk}),j&&(c=Uee,h={...et.basics,...zee}),D&&(c=Lee,h={...et.basics,...Nee}),F&&(c=Gee),Y&&(c=Hee,h={...et.basics,...Wee}),W&&(c=Vee,h={...et.basics,...Xee}),re&&(c=Yee),K&&(c=qee),Pe&&(c=gee,h={...et.basics,...vee});const ne={from:s,to:o,uniforms:h};a&&l&&(ne.displacementMap=l,u&&(l.resource=u,l.update()));const oe=new xe({glProgram:new ce({vertex:Z$,fragment:$$(c)}),resources:ne});return i.filters=[oe],{render({width:X,height:ie,from:fe,to:ae,progress:ye}){if((i.width!==X||i.height!==ie)&&(i.setSize({width:X,height:ie}),n.resize(X,ie)),fe instanceof Q?oe.resources.from=fe.source:(s.resource=fe,s.update(),oe.resources.from=s),ae instanceof Q?oe.resources.to=ae.source:(o.resource=ae,o.update(),oe.resources.to=o),a&&l&&u){if(u.width!==X||u.height!==ie){u.width=X,u.height=ie;const Xe=u.getContext("2d");if(Xe){const De=Xe.createImageData(X,ie);for(let we=0;we<De.data.length;we+=4){const Ye=Math.random();De.data[we]=Ye*255,De.data[we+1]=Ye*255,De.data[we+2]=Ye*255,De.data[we+3]=255}Xe.putImageData(De,0,0)}}l.resource=u,l.update()}return oe.resources.uniforms.uniforms.progress=ye,e.render({container:i,target:n,clear:!0,width:X,height:ie}),n},destroy(){n.destroy(),i.destroy({children:!0})}}}let Jee=0;async function Dk(r){r()>50&&(await H0(15),await Dk(r))}class $ee extends W0{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 B4()).codec,sampleRate:Je.sampleRate,numberOfChannels:Je.channelCount})).supported)??!1}logger=Fe.create(`id:${Jee++},`);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,B4().catch(n=>{this.logger.warn("Failed to detect audio codec:",n)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new pc,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(p=>p.width>0&&p.height>0),f=this.hasVideoTrack&&d;return DO({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||Je.codecType,sampleRate:h||Je.sampleRate,channelCount:Je.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:m,audio:p}=this.opts,g=Math.round(1e6/f),v=this.sprites.some(b=>b.width>0&&b.height>0);u=ete({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=tte({muxer:e,canvas:this.canvas,outputAudio:p,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:C}=await u.render(y);if(C){h(),await n();return}if(a.aborted)return;this.hasVideoTrack&&await new Promise(E=>requestAnimationFrame(E)),x(y,b,!0),y+=g,await Dk(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=>kl(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 gr||s instanceof Il)).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 Wo(t);await this.addSprite(i,{main:t.main||!1})}}}function ete(r){const{pixiApp:e,sprites:t,aborter:i}=r,n=e!=null,s=new Map,o=new Map,a=new Map,l=Rt.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),u=Rt.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),c=new je().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),h=new Map,d=async(b,C,E)=>{const A=Math.max(0,Math.min(C-b.display.from,b.duration));b.animate(A*b.playbackRate);const{video:P}=await E(b,A);return P},f=(b,C,E)=>{if(!e)return;const A=b.style||{},{renderTransform:P}=b,_=(P?.mirror??0)>.5;let S;_?(S=new Ai({texture:C instanceof Q?C:Q.from(C),width:1,height:1}),S.texture.source&&(S.texture.source.style.addressMode="mirror-repeat",S.texture.source.update())):S=new $e(C instanceof Q?C:Q.from(C));const I=P?.x??0,M=P?.y??0,O=P?.angle??0,z=P?.scale??1,j=P?.scaleX??1,D=P?.scaleY??1,F=P?.opacity??1,Y=P?.blur??0,W=P?.brightness??1;S.x=b.center.x+I,S.y=b.center.y+M,S.anchor.set(.5,.5);const re=S.texture.width||1,K=S.texture.height||1,Pe=b.type==="Caption",ne=!Pe&&b.width&&b.width!==0?Math.abs(b.width)/re:1,oe=!Pe&&b.height&&b.height!==0?Math.abs(b.height)/K:1;_&&S instanceof Ai&&(S.width=re*5,S.height=K*5,S.tilePosition.set((S.width-re)/2,(S.height-K)/2)),b.flip==="horizontal"?(S.scale.x=-ne*z*j,S.scale.y=oe*z*D):b.flip==="vertical"?(S.scale.x=ne*z*j,S.scale.y=-oe*z*D):(S.scale.x=ne*z*j,S.scale.y=oe*z*D),S.rotation=(b.flip==null?1:-1)*((b.angle+O)*Math.PI)/180,S.alpha=b.opacity*F;const X=[];if(Y>0){const we=new xs;we.strength=Y,we.quality=4,we.repeatEdgePixels=!0,X.push(we)}if(W!==1){const we=new Bo;we.brightness(W,!1),X.push(we)}if(b.chromaKey&&b.chromaKey.enabled){const we=new at({uKeyColor:{value:[0,1,0],type:"vec3<f32>"},uSimilarity:{value:.1,type:"f32"},uSpill:{value:0,type:"f32"}}),Ye=R4(b.chromaKey.color);Ye&&(we.uniforms.uKeyColor[0]=Ye.r/255,we.uniforms.uKeyColor[1]=Ye.g/255,we.uniforms.uKeyColor[2]=Ye.b/255),we.uniforms.uSimilarity=b.chromaKey.similarity,we.uniforms.uSpill=b.chromaKey.spill;const qe=new xe({glProgram:new ce({vertex:Xb,fragment:V4,name:"ChromaKeyShader"}),resources:{chromaUniforms:we}});X.push(qe)}S.filters=X;const ie=A.borderRadius||0;let fe=null;ie>0&&(fe=new je,fe.roundRect(-re/2,-K/2,re,K,Math.min(ie,re/2,K/2)),fe.fill({color:16777215,alpha:1}),S.addChild(fe),S.mask=fe);const ae=A.stroke;let ye=null;if(ae&&ae.width>0){ye=new je;const we=bt(ae.color)??16777215;if(ye.setStrokeStyle({width:ae.width,color:we,alignment:1}),ie>0){const Ye=Math.min(ie,re/2,K/2);ye.roundRect(-re/2,-K/2,re,K,Ye)}else ye.rect(-re/2,-K/2,re,K);ye.stroke(),S.addChild(ye)}const Xe=A.dropShadow;let De=null;if(Xe&&(Xe.blur>0||Xe.distance>0)){De=new je;const we=bt(Xe.color)??0,Ye=Xe.alpha??.5,qe=Xe.distance??0,Ht=Xe.angle??0,_t=Math.cos(Ht)*qe,Ii=Math.sin(Ht)*qe;if(ie>0){const Dn=Math.min(ie,re/2,K/2);De.roundRect(-re/2+_t,-K/2+Ii,re,K,Dn)}else De.rect(-re/2+_t,-K/2+Ii,re,K);De.fill({color:we,alpha:Ye}),S.addChildAt(De,0)}e.renderer.render({container:S,target:E,clear:!0}),C instanceof Q||S.texture.destroy(!0),ye&&ye.destroy(),fe&&fe.destroy(),De&&De.destroy(),S.destroy()};let m=null,p=null,g=null;n&&e!=null&&(m=new Be,p=new Be,g=new Be,p.sortableChildren=!0,g.sortableChildren=!0,e.stage.addChild(p),e.stage.addChild(g),m.visible=!1,e.stage.addChild(m));const v=[...t].sort((b,C)=>b.zIndex-C.zIndex);return{render:async b=>{const C=[];let E=!1,A=!1;const P=new Map,_=async(S,I)=>{if(P.has(S))return P.get(S);const M=await S.getFrame(I);return P.set(S,M),M};for(const S of a.values())S.visible=!1;for(const S of v){if(i.aborted)break;if(b<S.display.from||S.expired){if(n&&e!=null){const D=s.get(S);D&&await D.updateFrame(null)}continue}const I=b-S.display.from,M=I*S.playbackRate;S.animate(M);const{video:O,audio:z,done:j}=await _(S,I);if(C.push(z),n&&e!=null&&p!=null){if(S instanceof Ei){const F=t.find(W=>W.id===S.fromClipId),Y=t.find(W=>W.id===S.toClipId);if(F&&Y){const W=b-S.display.from;if(W>=S.duration){S.expired=!0;const re=a.get(S.id);re&&(re.visible=!1)}else{const re=await d(F,b,_),K=await d(Y,b,_);if(re&&K){const Pe=Math.min(Math.max(W/S.duration,0),1);f(F,re,l),f(Y,K,u);let ne=o.get(S.id);ne||(ne=l1({name:S.transitionEffect.key,renderer:e.renderer}),o.set(S.id,ne));const oe=ne.render({width:e.renderer.width,height:e.renderer.height,from:l,to:u,progress:Pe});let X=a.get(S.id);X||(X=new $e,X.label=`TransitionSprite_${S.id}`,a.set(S.id,X),p.addChild(X)),X.texture=oe,X.visible=!0,X.x=0,X.y=0,X.width=e.renderer.width,X.height=e.renderer.height,X.anchor.set(0,0),X.zIndex=S.zIndex,A=!0;const ie=s.get(F);if(ie){const ae=ie.getRoot();ae&&(ae.visible=!1)}const fe=s.get(Y);if(fe){const ae=fe.getRoot();ae&&(ae.visible=!1)}continue}}}}let D=s.get(S);if(D==null&&O!=null&&(D=new kk(e,S,p),s.set(S,D)),D!=null){const F=D.getRoot();O!=null?(A=!0,F&&(F.visible=!0),await D.updateFrame(O)):(F&&(F.visible=!1),await D.updateFrame(null)),D.updateTransforms()}}if(S.duration>0&&I>=S.duration||j){if(S.main&&(E=!0),S.expired=!0,n){const D=s.get(S);if(D!=null){const F=D.getRoot();F&&(F.visible=!1)}}}else if(n){const D=s.get(S);D?.updateTransforms()}}if(n&&e!=null&&m!=null&&p!=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!==p&&(M.parent&&M.parent.removeChild(M),p.addChild(M))}if(S.length>0){const I=e.renderer.width,M=e.renderer.height;let O=null;const z=new Set,j=[];for(const D of S){const{key:F,startTime:Y,duration:W,id:re,zIndex:K}=D,Pe=b-Y,ne=W>0?Math.min(Math.max(Pe/W,0),1):0,oe=t.some(X=>X.id===re&&X instanceof qi);if(m.removeChildren(),O){const X=new $e(O);X.width=I,X.height=M,m.addChild(X)}for(const X of t){if(z.has(X.id))continue;let ie=!1;if(oe?ie=X.id!==re&&X.zIndex<K:ie=!!X.effects&&X.effects.some(fe=>fe.id===re),ie){const fe=s.get(X);if(fe){const ye=fe.getRoot();ye&&(ye.parent&&ye.parent.removeChild(ye),m.addChild(ye),z.add(X.id))}const ae=a.get(X.id);ae&&(ae.parent&&ae.parent.removeChild(ae),m.addChild(ae),z.add(X.id))}}if(m.children.length>0){let X=h.get(re);if(!X)try{const ie=await o1({name:F,renderer:e.renderer,values:D.values});ie&&ie.filter&&(X={filter:ie.filter,render:ie.render},h.set(re,X))}catch(ie){console.warn("Failed to create effect",F,ie)}if(X){const{filter:ie,render:fe}=X;ie.resources&&ie.resources.effectUniforms&&(ie.resources.effectUniforms.uniforms.uTime=ne);const ae=Rt.create({width:I,height:M});j.push(ae),m.visible=!0,e.renderer.render({container:m,target:ae,clear:!0}),m.visible=!1,fe&&(O=fe({canvasTexture:ae,progress:ne,width:I,height:M}))}}}if(O){const D=new $e(O);D.width=I,D.height=M,g.addChild(D)}for(const D of j)D.destroy(!0)}}return n&&e!=null&&e.render(),{audios:C,mainSprDone:E,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(),m&&m.destroy({children:!0}),p&&p.destroy({children:!0}),g&&g.destroy({children:!0}),s.forEach(b=>{b.destroy()}),s.clear()}}}function tte(r){const{canvas:e,outputAudio:t,muxer:i,hasVideoTrack:n,timeSlice:s}=r;let o=0;const a=Math.floor(3*r.fps),l=rte(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 rte(r){const e=r*Je.channelCount,t=new Float32Array(e*3);let i=0,n=0;const s=r/Je.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:Je.channelCount,numberOfFrames:r,sampleRate:Je.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:Je.channelCount,numberOfFrames:r,sampleRate:Je.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 m=0;m<u.length;m++){const p=u[m][0]?.[h]??0,g=u[m][1]?.[h]??p;d+=p,f+=g}t[i]=d,t[i+1]=f,i+=2}return a(l)}}class ite extends je{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(e,t=1){const n=1.5*t;this.clear(),this.setStrokeStyle({width:n,color:165063}).rect(e.x,e.y,e.width,e.height).stroke(),this.hitArea=e}}class Ki extends je{#e=!1;handle;cursor;callbacks;constructor(e,t,i){super(),this.handle=e,this.cursor=t,this.callbacks=i,this.eventMode="static",this.#l(),this.on("pointerdown",this.#r),this.on("globalpointermove",this.#n),this.on("pointerup",this.#u),this.on("pointerupoutside",this.#u)}#l(){this.clear();const e=165063;if(this.handle==="rot")this.circle(0,0,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-4),this.arc(0,0,4,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new nl(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 me(-15,-15,30,30)}else this.rect(-4,-4,8,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new me(-15,-15,30,30)}#r=e=>{this.#e=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,e.global),e.stopPropagation()};#n=e=>{this.#e&&(this.callbacks.updateDrag(this.handle,e.global),e.stopPropagation())};#u=e=>{this.#e&&(this.#e=!1,this.cursor="pointer",this.callbacks.endDrag(),e.stopPropagation())}}class Th{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=Th.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 m=d.value-f.value;if(Math.abs(m)<s){i=m,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 m=d.value-f.value;if(Math.abs(m)<s){n=m,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=Th.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 Ok={delta:new le};class nte extends Be{group;wireframe=new ite;selectionOutlines=new je;isDragging=!1;lastPointer=new ve;activeHandle=null;#e;#l=new Map;#r=new ve;#n=0;#u=0;#c=new me;#i=new ve;#s=new me;#t=[new ve,new ve,new ve,new ve];#o=1;#a=1;#h;#d=new je;#m=new ve;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static",this.#h=new Th(e.artboardWidth??1920,e.artboardHeight??1080),this.addChild(this.#d);const t={beginDrag:(i,n)=>this.#C(i,n),updateDrag:(i,n)=>this.#A(i,n),endDrag:()=>this.#v()};this.#e={tl:new Ki("tl","nwse-resize",t),tr:new Ki("tr","nesw-resize",t),bl:new Ki("bl","nesw-resize",t),br:new Ki("br","nwse-resize",t),ml:new Ki("ml","ew-resize",t),mr:new Ki("mr","ew-resize",t),mt:new Ki("mt","ns-resize",t),mb:new Ki("mb","ns-resize",t),rot:new Ki("rot","crosshair",{beginDrag:(i,n)=>this.#I(n),updateDrag:(i,n)=>this.#B(n),endDrag:()=>this.#v()})},this.addChild(this.selectionOutlines,this.wireframe,...Object.values(this.#e)),this.#_(),this.visible=!1,Pt.shared.addOnce(()=>{!this.destroyed&&this.parent&&(this.#f(),this.visible=!0)})}#_(){this.on("pointerdown",this.#w),this.on("pointerup",this.#x),this.on("pointerupoutside",this.#x),this.on("globalpointermove",this.#S)}#f(){if(this.group.length===1){const e=this.group[0];this.#n=e.rotation;const t=this.#g(e);let i,n;this.opts.clip?(i=this.opts.clip.width,n=this.opts.clip.height):(i=t.width,n=t.height);const s=e.toGlobal(new ve(0,0));this.#r.set(s.x,s.y),this.#s.copyFrom(new me(-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 me(-s/2,-o/2,s,o)),this.parent){const u=this.toGlobal(new ve(a,l));this.#r.set(u.x,u.y)}}this.#p()}#g(e){let t=null;const i=u=>{if(u.label==="MainSprite"&&u instanceof $e)return u;for(const c of u.children)if(c instanceof Be){const h=i(c);if(h)return h}return null};if(t=i(e),t){const u=t.getLocalBounds(),c=t.localTransform.clone(),h=c.apply(new ve(u.x,u.y)),d=c.apply(new ve(u.x+u.width,u.y)),f=c.apply(new ve(u.x+u.width,u.y+u.height)),m=c.apply(new ve(u.x,u.y+u.height)),p=Math.min(h.x,d.x,f.x,m.x),g=Math.max(h.x,d.x,f.x,m.x),v=Math.min(h.y,d.y,f.y,m.y),x=Math.max(h.y,d.y,f.y,m.y);return new me(p,v,g-p,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 me(c.minX,c.minY,c.maxX-c.minX,c.maxY-c.minY)}}for(const u of l){const c=u.getBounds(),h=e.toLocal(new ve(c.minX,c.minY)),d=e.toLocal(new ve(c.maxX,c.maxY));n=Math.min(n,h.x,d.x),s=Math.min(s,h.y,d.y),o=Math.max(o,h.x,d.x),a=Math.max(a,h.y,d.y)}if(n===1/0){const u=e.getLocalBounds();return new me(u.minX,u.minY,u.maxX-u.minX,u.maxY-u.minY)}return new me(n,s,o-n,a-s)}updateBounds(){this.#f()}#w=e=>{this.#f(),this.#m.copyFrom(this.#r),this.isDragging=!0,this.lastPointer.copyFrom(e.global),this.cursor="grabbing"};#x=()=>{this.isDragging&&this.#v(),this.cursor="default"};#S=e=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const{moveDx:t,moveDy:i,newPivotWorld:n}=this.#T(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")};#T(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 me(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.#y(u,t);const c=s.x+a,h=s.y+l,d=this.parent.toLocal(this.#r),f=c-d.x,m=h-d.y,p=this.parent.toGlobal(new ve(c,h));return{moveDx:f,moveDy:m,newPivotWorld:p}}#C(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.#R(e)}#A(e,t){this.#E(e,t)}async#E(e,t){const{proposed:i,sx:n,sy:s,pivotWorld:o}=await this.#P(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.#b(this.#M(o,this.#n,n,s)),this.#s.copyFrom(i),this.#p(),this.emit("transforming")}async#P(e,t){const i=this.#i,n=this.#F(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.#y(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}}#I(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)}#B(e){const i=Math.atan2(e.y-this.#r.y,e.x-this.#r.x)-this.#u,n=this.#n+i;this.#b(this.#D(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")}#y(e,t){if(this.#d.clear(),!(!e.length||!this.parent)){this.#d.stroke({width:1/t,color:4774907});for(const i of e){let n,s;i.type==="vertical"?(n=new ve(i.position,i.start),s=new ve(i.position,i.end)):(n=new ve(i.start,i.position),s=new ve(i.end,i.position)),this.toLocal(n,this.parent,n),this.toLocal(s,this.parent,s),this.#d.moveTo(n.x,n.y).lineTo(s.x,s.y).stroke({width:1/t,color:4774907})}}}#p(e=this.#n){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#r)),this.rotation=e;const i=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),n=this.#s;this.wireframe.draw(n,i);const s=n.x+n.width/2,o=n.y+n.height/2,a=this.opts.clip?.getVisibleHandles?.()??["tl","tr","bl","br","ml","mr","mt","mb","rot"],l=[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 u of l)u.scale.set(i);this.#e.tl.visible=a.includes("tl"),this.#e.tr.visible=a.includes("tr"),this.#e.bl.visible=a.includes("bl"),this.#e.br.visible=a.includes("br"),this.#e.ml.visible=a.includes("ml"),this.#e.mr.visible=a.includes("mr"),this.#e.mt.visible=a.includes("mt"),this.#e.mb.visible=a.includes("mb"),this.#e.rot.visible=a.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.#k(i)}#k(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)}}#R(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)}#F(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 me(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 me(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 me(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 me(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 me(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 me(s,n.y,i.x-s,n.height)}if(e==="mr"){const s=Math.max(t.x,i.x+this.#o);return new me(i.x,n.y,s-i.x,n.height)}if(e==="mt"){const s=Math.min(t.y,i.y-this.#a);return new me(n.x,s,n.width,i.y-s)}if(e==="mb"){const s=Math.max(t.y,i.y+this.#a);return new me(n.x,i.y,n.width,s-i.y)}return new me(i.x,i.y,this.#o,this.#a)}#M(e,t,i,n){return Ok.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(i,n).rotate(t).translate(e.x,e.y)}#D(e,t){return Ok.delta.identity().translate(-e.x,-e.y).rotate(t).translate(e.x,e.y)}#b(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 ste{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new ve;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;init(e,t){this.selectionGraphics=new je,this.selectionGraphics.visible=!1,this.selectionGraphics.zIndex=1e3,t.addChild(this.selectionGraphics),e.stage.eventMode="static",e.stage.hitArea=e.screen,e.stage.on("pointerdown",i=>this.onStagePointerDown(i)),e.stage.on("globalpointermove",i=>this.onStagePointerMove(i)),e.stage.on("pointerup",()=>this.onStagePointerUp()),e.stage.on("pointerupoutside",()=>this.onStagePointerUp())}onStagePointerDown(e){e.target===this.studio.pixiApp?.stage&&(e.shiftKey||this.deselectClip(),this.isDragSelecting=!0,this.studio.artboard?.toLocal(e.global,void 0,this.dragSelectionStart),this.selectionGraphics&&(this.selectionGraphics.clear(),this.selectionGraphics.visible=!0))}onStagePointerMove(e){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const t=this.studio.artboard.toLocal(e.global),i=Math.min(this.dragSelectionStart.x,t.x),n=Math.min(this.dragSelectionStart.y,t.y),s=Math.abs(t.x-this.dragSelectionStart.x),o=Math.abs(t.y-this.dragSelectionStart.y);this.selectionGraphics.clear(),this.selectionGraphics.rect(i,n,s,o).fill({color:703971,alpha:.3}),this.selectionGraphics.rect(i,n,s,o).stroke({width:2,color:703971})}}onStagePointerUp(){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const e=this.selectionGraphics.getBounds(),t=[],i=new me(e.x,e.y,e.width,e.height);if(i.width>2||i.height>2){for(const n of this.studio.clips){const s=this.studio.spriteRenderers.get(n);if(!s)continue;const o=s.getRoot();if(!o||!o.visible)continue;const a=o.getBounds();i.x<a.x+a.width&&i.x+i.width>a.x&&i.y<a.y+a.height&&i.y+i.height>a.y&&t.push(n)}if(t.length>0)for(const n of t)this.selectClip(n,!0)}this.selectionGraphics.clear(),this.selectionGraphics.visible=!1,this.isDragSelecting=!1}}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)});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)})}}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:[]})}}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})}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 n of this.selectedClips){const s=this.studio.spriteRenderers.get(n);if(s==null)continue;const o=s.getRoot();o!=null&&(e.push(o),this.selectedClips.size===1&&(t=n))}if(e.length===0){console.warn("Cannot create transformer: no sprites found");return}this.activeTransformer=new nte({group:e,clip:t,artboardWidth:this.studio.opts.width,artboardHeight:this.studio.opts.height});let i=null;this.activeTransformer.on("transforming",()=>{i===null&&(i=requestAnimationFrame(()=>{i=null,this.syncSelectedClipsTransformsRealtime()}))}),this.activeTransformer.on("textClipResize",n=>{this.textClipResizedWidth=n.newWidth,this.textClipResizeHandle=n.handle,this.textClipResizedSx=n.sx,this.textClipResizedSy=n.sy}),this.activeTransformer.on("transformEnd",async()=>{i!==null&&(cancelAnimationFrame(i),i=null),await this.syncSelectedClipsTransforms();for(const n of this.selectedClips)this.studio.emit("clip:updated",{clip:n})}),this.activeTransformer.on("pointerdown",n=>{const s=this.getTopmostClipAtPoint(n.global);s&&!this.selectedClips.has(s)&&(this.selectClip(s,n.shiftKey),n.stopPropagation())}),this.studio.artboard.addChild(this.activeTransformer)}async syncSelectedClipsTransformsRealtime(){if(!(this.selectedClips.size===0||this.activeTransformer==null)&&!this.isUpdatingTextRealtime){this.isUpdatingTextRealtime=!0;try{const e=this.activeTransformer.activeHandle;if(e!=="mr"&&e!=="ml")return;for(const t of this.selectedClips){if(!(t instanceof Yi))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 Yi||e instanceof Mn)&&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 Yi||e instanceof Mn)&&this.textClipResizedWidth!==null){const p={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,p.fontSize=d):["bl","tl"].includes(this.textClipResizeHandle)&&(f=e.left+u/2-(u-c),p.fontSize=d),await e.updateStyle(p);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 p=a,g=l;e.left=i.x-p/2,e.top=i.y-g/2,e.width=p,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 ote{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 Yo{static instance;fonts=new Map;constructor(){}static getInstance(){return Yo.instance||(Yo.instance=new Yo),Yo.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 Uk=Yo.getInstance();class ate{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 m=this.tracks.find(p=>p.id===h);if(m){const p=m.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 p)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 Ei(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 kk(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,n=this.clips.findIndex(c=>c===e);if(n===-1)return;if(e instanceof Ei){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){const n=this.clips.findIndex(u=>u===i);if(n===-1)continue;if(i instanceof Ei){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&&(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=>kl(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()!=="");await 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 Wo(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&&await Promise.all(this.clips.map(async 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),await i.ready,await this.setupClipVisuals(i)}));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 Ei){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);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=kl(n,!1),l=await Wo(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],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=kl(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 Wo(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],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 Uk.loadFonts(Array.from(t.values()))}catch(i){console.warn("Failed to load some fonts:",i)}}async recalculateMaxDuration(){let e=0;for(const t of this.clips){t.display.to===0&&t.duration!==1/0&&!isNaN(t.duration)&&t.duration>0;const i=t.duration>0?t.duration:0;if(i===1/0)continue;const n=t.display.to>0?t.display.to:t.display.from+i;n>e&&(e=n)}this.studio.maxDuration=e}async setupPlaybackForClip(e,t){if(this.studio.pixiApp!=null&&this.isPlaybackCapable(e))try{const i=e;if(e.type==="Audio"&&t&&typeof t!="string"){const o=URL.createObjectURL(t);e.src=o}const{element:n,objectUrl:s}=await i.createPlaybackElement();if(e.type==="Video"){const o=Q.from(n),a=new $e(o);a.visible=!1,this.studio.clipsNormalContainer&&this.studio.clipsNormalContainer.addChild(a),this.studio.videoSprites.set(e,a)}this.studio.transport.playbackElements.set(e,{element:n,objectUrl:s})}catch(i){console.warn(`Failed to setup playback for ${e.constructor.name}`,i)}}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async clear(){this.studio.selection.deselectClip(),this.studio.selection.interactiveClips.clear();for(const[e,t]of this.studio.clipListeners)e.off("propsChange",t);this.studio.clipListeners.clear(),this.studio.globalEffects.clear(),this.studio.effectFilters.clear(),this.studio.transitionRenderers.forEach(e=>e.destroy()),this.studio.transitionRenderers.clear(),this.studio.transitionSprites.forEach(e=>{e.parent&&e.parent.removeChild(e),e.destroy()}),this.studio.transitionSprites.clear(),this.studio.spriteRenderers.forEach(e=>e.destroy()),this.studio.spriteRenderers.clear();for(const[e,t]of this.studio.transport.playbackElements)this.isPlaybackCapable(e)&&e.cleanupPlayback(t.element,t.objectUrl);this.studio.transport.playbackElements.clear();for(const e of this.studio.videoSprites.values())e.destroy();this.studio.videoSprites.clear(),this.tracks=[],this.clips=[],this.studio.maxDuration=0,this.studio.currentTime=0,this.studio.emit("reset")}async rippleDelete(e,t){if(e>=t)return;const i=t-e,n=[...this.clips];for(const s of n){const o=s.display.from,a=s.display.to;if(!(a<=e)){if(o>=t){await this.updateClip(s.id,{display:{from:s.display.from-i,to:s.display.to-i}});continue}if(o>=e&&a<=t){await this.removeClip(s);continue}if(o<e&&a>t){const l=await s.clone();l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const u=e,c=e+(a-t),h=s.trim.from+(t-o)*s.playbackRate,d=s.trim.to,f=this.tracks.find(m=>m.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 lte={Date:!0,RegExp:!0,String:!0,Number:!0};function zk(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&&!lte[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!i.includes(l))?n.push.apply(n,zk(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 ute{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=zk(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 m=0;m<l.length-1;m++){if(h[l[m]]===void 0||h[l[m]]===null){d=!0;break}h=h[l[m]]}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 cte extends W0{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 ste(this),this.transport=new ote(this),this.timeline=new ate(this),this.history=new ute,this.resourceManager=new Uo,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 Wo(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 pc,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 Be,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new je,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new Be,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new je,this.artboardMask.rect(0,0,this.opts.width,this.opts.height).fill({color:16777215}),this.clipContainer.addChild(this.artboardMask),this.clipContainer.mask=this.artboardMask,this.clipsEffectContainer=new Be,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new Be,this.clipsNormalContainer.label="ClipsNormal",this.clipsNormalContainer.zIndex=10,this.clipsNormalContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsNormalContainer),this.transFromTexture=Rt.create({width:this.opts.width,height:this.opts.height}),this.transToTexture=Rt.create({width:this.opts.width,height:this.opts.height}),this.transBgGraphics=new je,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}),this.clipContainer.sortableChildren=!0,this.updateArtboardLayout(),t.renderer.on("resize",()=>{this.handleResize()})}getOptions(){return this.opts}setSize(e,t){this.updateDimensions(e,t)}setBgColor(e){this.opts.bgColor=e;const t=this.hexToNumber(e);this.pixiApp&&(this.pixiApp.renderer.background.color=t,this.pixiApp.render()),this.updateFrame(this.currentTime)}updateDimensions(e,t){this.opts.width=e,this.opts.height=t,this.artboardBg&&this.artboardBg.clear().rect(0,0,e,t).fill({color:0}),this.artboardMask&&this.artboardMask.clear().rect(0,0,e,t).fill({color:16777215}),this.transFromTexture&&this.transFromTexture.resize(e,t),this.transToTexture&&this.transToTexture.resize(e,t),this.transBgGraphics&&this.transBgGraphics.clear().rect(0,0,e,t).fill({color:0,alpha:0}),this.updateArtboardLayout(),this.updateFrame(this.currentTime)}handleResize=()=>{this.destroyed||!this.pixiApp||this._isUpdatingLayout||this.updateArtboardLayout()};updateArtboardLayout(){if(!(!this.pixiApp||!this.artboard||this._isUpdatingLayout)){this._isUpdatingLayout=!0;try{this.pixiApp.resize();const t=this.pixiApp.canvas.parentElement,i=t?t.getBoundingClientRect().width:this.pixiApp.screen.width,n=t?t.getBoundingClientRect().height:this.pixiApp.screen.height,s=this.opts.width,o=this.opts.height,a=this.opts.spacing||0,l=Math.max(0,i-a*2),u=Math.max(0,n-a*2),c=l/s,h=u/o,d=Math.min(c,h);this.artboard.scale.set(d),this.artboard.x=(i-s*d)/2,this.artboard.y=(n-o*d)/2,this.pixiApp.render()}finally{this._isUpdatingLayout=!1}}}getCanvas(){if(this.opts.canvas)return this.opts.canvas;if(this.pixiApp?.canvas)return this.pixiApp.canvas;throw new Error("Canvas not initialized yet. Wait for initPixiApp to complete.")}async addTransition(e,t=2e6,i,n){return this.timeline.addTransition(e,t,i,n)}findTrackIdByClipId(e){return this.timeline.findTrackIdByClipId(e)}async addClip(e,t){(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,m=o.transition?o.transition.end:0,p=d&&o.transition&&e>=f&&e<m;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=!p&&v>=0&&v<y,x.visible&&j$(o,x),!p)continue}}else continue}if(p){const v=o?.transition?.fromClipId,x=o?.transition?.toClipId,y=`${v}_${x}`;if(i.has(y)){const P=this.spriteRenderers.get(o);P?.getRoot()&&(P.getRoot().visible=!1);const _=this.videoSprites.get(o);_&&(_.visible=!1);continue}i.add(y),this.transFromTexture||(this.transFromTexture=Rt.create({width:this.opts.width,height:this.opts.height})),this.transToTexture||(this.transToTexture=Rt.create({width:this.opts.width,height:this.opts.height})),this.transBgGraphics||(this.transBgGraphics=new je,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}));const b=v?this.getClipById(v):null,C=x?this.getClipById(x):null;let E=null,A=null;if(b){const P=Math.max(0,e-b.display.from),{video:_}=await b.getFrame(P);_ instanceof HTMLVideoElement?E=this.getVideoTexture(_):E=_,E&&(this.lastFromFrame=E)}if(C){const P=Math.max(0,e-C.display.from),{video:_}=await C.getFrame(P);_ instanceof HTMLVideoElement?A=this.getVideoTexture(_):A=_,A&&(this.lastToFrame=A)}if(E||(E=this.lastFromFrame),A||(A=this.lastToFrame),!E||!A)continue;if(E&&A&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const P=(e-f)/o?.transition?.duration;b&&E&&this.renderClipToTransitionTexture(b,E,this.transFromTexture),C&&A&&this.renderClipToTransitionTexture(C,A,this.transToTexture);let _=this.transitionRenderers.get(y);if(!_)try{_=l1({name:o?.transition?.name,renderer:this.pixiApp.renderer}),this.transitionRenderers.set(y,_)}catch(S){console.error("[Studio] Failed to create transition renderer:",S)}if(_){const S=_.render({width:this.opts.width,height:this.opts.height,from:this.transFromTexture,to:this.transToTexture,progress:P});let I=this.transitionSprites.get(o.id);I||(I=new $e,I.label=`TransitionSprite_${o.id}`,this.transitionSprites.set(o.id,I),this.clipsNormalContainer&&this.clipsNormalContainer.addChild(I)),I.texture=S,I.visible=!0,I.x=0,I.y=0,I.width=this.opts.width,I.height=this.opts.height,I.anchor.set(0,0),I.zIndex=o.zIndex,t.add(o.id);const M=this.spriteRenderers.get(o);M?.getRoot()&&(M.getRoot().visible=!1);const O=this.videoSprites.get(o);if(O&&(O.visible=!1),b){const z=this.spriteRenderers.get(b);z?.getRoot()&&(z.getRoot().visible=!1);const j=this.videoSprites.get(b);j&&(j.visible=!1)}if(C){const z=this.spriteRenderers.get(C);z?.getRoot()&&(z.getRoot().visible=!1);const j=this.videoSprites.get(C);j&&(j.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 Il&&o.addEffect(s),o instanceof gr&&o.addEffect(s),o instanceof Yi&&o.addEffect(s),o instanceof Mn&&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 gr||i instanceof Il)).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;let a;o?(a=new Ai({texture:t instanceof Q?t:Q.from(t),width:1,height:1}),a.texture.source&&(a.texture.source.style.addressMode="mirror-repeat",a.texture.source.update())):a=new $e(t instanceof Q?t:Q.from(t));const l=s?.x??0,u=s?.y??0,c=s?.angle??0,h=s?.scale??1,d=s?.opacity??1,f=s?.blur??0,m=s?.brightness??1;a.x=e.center.x+l,a.y=e.center.y+u,a.anchor.set(.5,.5);const p=a.texture.width||1,g=a.texture.height||1,v=e.type==="Caption",x=!v&&e.width&&e.width!==0?Math.abs(e.width)/p:1,y=!v&&e.height&&e.height!==0?Math.abs(e.height)/g:1;o&&a instanceof Ai&&(a.width=p*5,a.height=g*5,a.tilePosition.set((a.width-p)/2,(a.height-g)/2)),e.flip==="horizontal"?(a.scale.x=-x*h,a.scale.y=y*h):e.flip==="vertical"?(a.scale.x=x*h,a.scale.y=-y*h):(a.scale.x=x*h,a.scale.y=y*h),a.rotation=(e.flip==null?1:-1)*((e.angle+c)*Math.PI)/180,a.alpha=e.opacity*d;const b=[];if(f>0){const I=new xs;I.strength=f,I.quality=4,I.repeatEdgePixels=!0,b.push(I)}if(m!==1){const I=new Bo;I.brightness(m,!1),b.push(I)}a.filters=b;const C=n.borderRadius||0;let E=null;C>0&&(E=new je,E.roundRect(-p/2,-g/2,p,g,Math.min(C,p/2,g/2)),E.fill({color:16777215,alpha:1}),a.addChild(E),a.mask=E);const A=n.stroke;let P=null;if(A&&A.width>0){P=new je;const I=bt(A.color)??16777215;if(P.setStrokeStyle({width:A.width,color:I,alignment:1}),C>0){const M=Math.min(C,p/2,g/2);P.roundRect(-p/2,-g/2,p,g,M)}else P.rect(-p/2,-g/2,p,g);P.stroke(),a.addChild(P)}const _=n.dropShadow;let S=null;if(_&&(_.blur>0||_.distance>0)){S=new je;const I=bt(_.color)??0,M=_.alpha??.5,O=_.distance??0,z=_.angle??0,j=Math.cos(z)*O,D=Math.sin(z)*O;if(C>0){const F=Math.min(C,p/2,g/2);S.roundRect(-p/2+j,-g/2+D,p,g,F)}else S.rect(-p/2+j,-g/2+D,p,g);S.fill({color:I,alpha:M}),a.addChildAt(S,0)}this.pixiApp.renderer.render({container:a,target:i,clear:!0}),t instanceof Q||a.texture.destroy(!0),E&&E.destroy(),P&&P.destroy(),S&&S.destroy(),a.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,m=Math.min(Math.max(f/c,0),1);if(m<0||m>=1)continue;if(this.clipsEffectContainer.visible=!0,this.clipsEffectContainer.removeChildren(),n){const y=new $e(n);y.label="PrevEffectResult",y.width=t,y.height=i,this.clipsEffectContainer.addChild(y)}const p=h??-1;for(const y of this.clips){if(s.has(y.id))continue;const b=this.getTrackIndex(y.id);!(y instanceof qi)&&(p===-1||b>p)&&(this.moveClipToEffectContainer(y,!0),s.add(y.id))}let g=this.effectFilters.get(l);if(!g)try{if(g=await o1({name:l,renderer:this.pixiApp.renderer,values:d}),g)this.effectFilters.set(l,g);else continue}catch(y){console.error(y);continue}const v=Rt.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:m,width:t,height:i,values:d});this.clipsEffectContainer.visible=!1,n=x}if(n){const a=new $e(n);a.x=0,a.y=0,a.width=t,a.height=i,a.scale.set(1),a.zIndex=5,this.clipContainer.addChild(a),this.currentGlobalEffectSprite=a}for(const a of o)a.destroy(!0)}destroy(){if(!this.destroyed){window.removeEventListener("resize",this.handleResize),this.destroyed=!0,this.stop(),this.clear(),this.transitionRenderers.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null);for(const e of this.transitionSprites.values())e.destroy();this.transitionSprites.clear(),this.pixiApp&&(this.pixiApp.destroy(!0,{children:!0,texture:!0}),this.pixiApp=null)}}selectClip(e,t=!1){this.selection.selectClip(e,t)}setSelection(e){this.selection.setSelection(e)}selectClipsByIds(e){this.selection.selectClipsByIds(e)}deselectClip(){this.selection.deselectClip()}exportToJSON(){return this.timeline.exportToJSON()}async loadFromJSON(e){return this.timeline.loadFromJSON(e)}}be.add($T),be.mixin(Be,eC),be.add(Mx),be.add(Dx),be.add(Uy),be.mixin(Be,pP),be.add(My),be.add(vb),be.add(Ic),be.add(yb),be.add(Sb),be.add(Tb),be.add(zb),be.add(Ub),be.add(Rb),be.add(Db),be.add(Fb),be.add(Ib),be.add(Ab),be.add(qy),be.add(Vy);const hte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),dte=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));Se.ANIMATABLE_PROPERTIES=kL,Se.Audio=jr,Se.Caption=Mn,Se.Compositor=$ee,Se.DEFAULT_AUDIO_CONF=Je,Se.Effect=qi,Se.GL_EFFECT_OPTIONS=iQ,Se.GL_TRANSITION_OPTIONS=Zee,Se.Image=Il,Se.KeyframeAnimation=k,Se.Log=Fe,Se.MP4Clip=gr,Se.Placeholder=Bl,Se.Studio=cte,Se.Text=Yi,Se.Transition=Ei,Se.VALUES_FILTER_SPECIAL=s1,Se.VALUES_FILTER_SPECIAL_LIMITS=X$,Se.Video=gr,Se.animationRegistry=L,Se.clipToJSON=kl,Se.createChromakey=wL,Se.createSlowMo=iS,Se.easings=_u,Se.fastConcatMP4=G4,Se.fixFMP4Duration=fq,Se.fontManager=Uk,Se.getAllEffects=Yb,Se.getAllTransitions=Xo,Se.getEasing=V0,Se.getEffectOptions=X4,Se.getPresetTemplate=q,Se.getTransitionOptions=Mk,Se.jsonToClip=Wo,Se.makeEffect=o1,Se.makeTransition=l1,Se.mixinMP4AndAudio=vq,Se.registerCustomEffect=eQ,Se.registerCustomTransition=Kee,Se.renderTxt2ImgBitmap=IL,Se.unregisterCustomEffect=tQ,Se.unregisterCustomTransition=Qee,Object.defineProperty(Se,Symbol.toStringTag,{value:"Module"})}));
@@ -23,7 +23,7 @@ interface BaseClipJSON {
23
23
  angle: number;
24
24
  zIndex: number;
25
25
  opacity: number;
26
- flip: 'horizontal' | 'vertical' | null;
26
+ flip: "horizontal" | "vertical" | null;
27
27
  trim?: {
28
28
  from: number;
29
29
  to: number;
@@ -53,17 +53,17 @@ interface BaseClipJSON {
53
53
  main?: boolean;
54
54
  }
55
55
  export interface VideoJSON extends BaseClipJSON {
56
- type: 'Video';
56
+ type: "Video";
57
57
  audio?: boolean;
58
58
  volume?: number;
59
59
  }
60
60
  export interface AudioJSON extends BaseClipJSON {
61
- type: 'Audio';
61
+ type: "Audio";
62
62
  loop?: boolean;
63
63
  volume?: number;
64
64
  }
65
65
  export interface ImageJSON extends BaseClipJSON {
66
- type: 'Image';
66
+ type: "Image";
67
67
  }
68
68
  export interface TextStyleJSON {
69
69
  fontSize?: number;
@@ -71,7 +71,7 @@ export interface TextStyleJSON {
71
71
  fontWeight?: string | number;
72
72
  fontStyle?: string;
73
73
  color?: string | number | {
74
- type: 'gradient';
74
+ type: "gradient";
75
75
  x0: number;
76
76
  y0: number;
77
77
  x1: number;
@@ -81,13 +81,13 @@ export interface TextStyleJSON {
81
81
  color: string | number;
82
82
  }>;
83
83
  };
84
- align?: 'left' | 'center' | 'right';
84
+ align?: "left" | "center" | "right";
85
85
  fontUrl?: string;
86
86
  stroke?: {
87
87
  color: string | number;
88
88
  width: number;
89
- join?: 'miter' | 'round' | 'bevel';
90
- cap?: 'butt' | 'round' | 'square';
89
+ join?: "miter" | "round" | "bevel";
90
+ cap?: "butt" | "round" | "square";
91
91
  miterLimit?: number;
92
92
  };
93
93
  shadow?: {
@@ -101,19 +101,19 @@ export interface TextStyleJSON {
101
101
  wordWrapWidth?: number;
102
102
  lineHeight?: number;
103
103
  letterSpacing?: number;
104
- textCase?: 'none' | 'uppercase' | 'lowercase' | 'title';
105
- wordsPerLine?: 'single' | 'multiple';
106
- verticalAlign?: 'top' | 'center' | 'bottom';
104
+ textCase?: "none" | "uppercase" | "lowercase" | "title";
105
+ wordsPerLine?: "single" | "multiple";
106
+ verticalAlign?: "top" | "center" | "bottom";
107
107
  wordAnimation?: ICaptionWordAnimation;
108
108
  }
109
109
  export interface ICaptionWordAnimation {
110
- type: 'scale' | 'opacity';
111
- application: 'active' | 'keyword' | 'none';
110
+ type: "scale" | "opacity";
111
+ application: "active" | "keyword" | "none";
112
112
  value: number;
113
- mode?: 'static' | 'dynamic';
113
+ mode?: "static" | "dynamic";
114
114
  }
115
115
  export interface TextJSON extends BaseClipJSON {
116
- type: 'Text';
116
+ type: "Text";
117
117
  text: string;
118
118
  style?: TextStyleJSON;
119
119
  }
@@ -143,7 +143,7 @@ export interface CaptionDataJSON {
143
143
  wordAnimation?: ICaptionWordAnimation;
144
144
  }
145
145
  export interface CaptionJSON extends BaseClipJSON {
146
- type: 'Caption';
146
+ type: "Caption";
147
147
  text: string;
148
148
  style?: TextStyleJSON;
149
149
  caption?: CaptionDataJSON;
@@ -165,10 +165,10 @@ export interface CaptionJSON extends BaseClipJSON {
165
165
  videoHeight?: number;
166
166
  fontUrl?: string;
167
167
  mediaId?: string;
168
- wordsPerLine?: 'single' | 'multiple';
168
+ wordsPerLine?: "single" | "multiple";
169
169
  }
170
170
  export interface EffectJSON extends BaseClipJSON {
171
- type: 'Effect';
171
+ type: "Effect";
172
172
  effect: {
173
173
  id: string;
174
174
  key: string;
@@ -176,7 +176,7 @@ export interface EffectJSON extends BaseClipJSON {
176
176
  };
177
177
  }
178
178
  export interface TransitionJSON extends BaseClipJSON {
179
- type: 'Transition';
179
+ type: "Transition";
180
180
  transitionEffect: {
181
181
  id: string;
182
182
  key: string;
@@ -186,7 +186,7 @@ export interface TransitionJSON extends BaseClipJSON {
186
186
  toClipId: string | null;
187
187
  }
188
188
  export interface PlaceholderJSON extends BaseClipJSON {
189
- type: 'Placeholder';
189
+ type: "Placeholder";
190
190
  }
191
191
  export interface GlobalTransitionJSON {
192
192
  key: string;
@@ -1,4 +1,4 @@
1
- import { e as a, R as e, T as d, G as i, b as s, M as t, c as p, d as P, f as n, g as r, B as T, H as l, h as c, i as m, N as x, j as S, k as o } from "./index-BXuEu2AS.js";
1
+ import { e as a, R as e, T as d, G as i, b as s, M as t, c as p, d as P, f as n, g as r, B as T, H as l, h as c, i as m, N as x, j as S, k as o } from "./index-CZJxf7wC.js";
2
2
  a.add(e);
3
3
  a.add(d);
4
4
  a.add(i);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openvideo",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Video rendering and processing library",
5
5
  "type": "module",
6
6
  "publishConfig": {