@designcombo/video 0.1.13 → 0.1.14

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,4 +1,4 @@
1
- import { F as Ie, u as Ee, l as se, M as v, G as De, v as Oe, S as Fe, x as ae, E as u, e as D, y as S, z as Le, H as O, I as b, R as F, J as ne, K as He, t as m, b as f, i as B, w as L, L as K, N as We, c as Y, B as y, j as U, O as ze, Q as C, k as M, V as w, W as Ve, a as Ne, X as ie, Y as oe, Z as le, _ as ue, C as P, $ as je, a0 as A, a1 as J, D as H, a2 as $e, a3 as qe, P as Ke, d as Ye, T as X, a4 as Q, a5 as Je, a6 as Xe, a7 as Qe } from "./index-DSnnNrXJ.js";
1
+ import { F as Ie, u as Ee, l as se, M as v, G as De, v as Oe, S as Fe, x as ae, E as u, e as D, y as S, z as Le, H as O, I as b, R as F, J as ne, K as He, t as m, b as f, i as B, w as L, L as K, N as We, c as Y, B as y, j as U, O as ze, Q as C, k as M, V as w, W as Ve, a as Ne, X as ie, Y as oe, Z as le, _ as ue, C as P, $ as je, a0 as A, a1 as J, D as H, a2 as $e, a3 as qe, P as Ke, d as Ye, T as X, a4 as Q, a5 as Je, a6 as Xe, a7 as Qe } from "./index-D8oGyWjX.js";
2
2
  import { B as de, c as Ze } from "./colorToUniform-C2jGzNe1.js";
3
3
  var et = `in vec2 vMaskCoord;
4
4
  in vec2 vTextureCoord;
@@ -1,6 +1,6 @@
1
- import { S as G, E as d, B as v, w as m, D as S, L as j, v as ve, s as U, t as b, a8 as Be, k as K, a9 as Ae, b as p, V as L, j as B, i as A, l as F, M as $, aa as z, ab as Ne, ac as ye, ad as Y, ae as Ce, A as De, R as Ie, e as T } from "./index-DSnnNrXJ.js";
1
+ import { S as G, E as d, B as v, w as m, D as S, L as j, v as ve, s as U, t as b, a8 as Be, k as K, a9 as Ae, b as p, V as L, j as B, i as A, l as F, M as $, aa as z, ab as Ne, ac as ye, ad as Y, ae as Ce, A as De, R as Ie, e as T } from "./index-D8oGyWjX.js";
2
2
  import { b as q } from "./colorToUniform-C2jGzNe1.js";
3
- import { e as Ge, G as Ue, c as Fe, b as Oe, U as Pe, R as Me, B as Z, d as N, f as Le, S as He, a as we } from "./SharedSystems-CG7UWab9.js";
3
+ import { e as Ge, G as Ue, c as Fe, b as Oe, U as Pe, R as Me, B as Z, d as N, f as Le, S as He, a as we } from "./SharedSystems-G3yTQS7R.js";
4
4
  class Q {
5
5
  constructor() {
6
6
  this._tempState = G.for2d(), this._didUploadHash = {};
@@ -1,6 +1,6 @@
1
- import { S as E, g as A, E as p, f as ae, D as S, b as C, B as T, c as ue, d as L, h as M, w as v, i as x, j as ce, k as de, l as k, m as w, M as D, n as H, o as he, p as pe, q as z, s as F, t as R, A as le, R as fe, e as B } from "./index-DSnnNrXJ.js";
1
+ import { S as E, g as A, E as p, f as ae, D as S, b as C, B as T, c as ue, d as L, h as M, w as v, i as x, j as ce, k as de, l as k, m as w, M as D, n as H, o as he, p as pe, q as z, s as F, t as R, A as le, R as fe, e as B } from "./index-D8oGyWjX.js";
2
2
  import { l as ge, a as me } from "./colorToUniform-C2jGzNe1.js";
3
- import { c as _e, u as be, U as xe, B as ye, G as Ge, e as Se, R as Be, t as Pe, S as Te, a as Ce } from "./SharedSystems-CG7UWab9.js";
3
+ import { c as _e, u as be, U as xe, B as ye, G as Ge, e as Se, R as Be, t as Pe, S as Te, a as Ce } from "./SharedSystems-G3yTQS7R.js";
4
4
  const y = E.for2d();
5
5
  class O {
6
6
  start(e, t, r) {
@@ -1,5 +1,5 @@
1
- import { T as M, U as Z, P as m, r as te, E as y, a as ie, w as g, e as P, C as V } from "./index-DSnnNrXJ.js";
2
- import "./webworkerAll-CmuBF-4y.js";
1
+ import { T as M, U as Z, P as m, r as te, E as y, a as ie, w as g, e as P, C as V } from "./index-D8oGyWjX.js";
2
+ import "./webworkerAll-AI9nt7c5.js";
3
3
  class q {
4
4
  constructor(e) {
5
5
  this._lastTransform = "", this._observer = null, this._tickerAttached = !1, this.updateTranslation = () => {
@@ -9475,7 +9475,7 @@ const kh = (i) => {
9475
9475
  },
9476
9476
  test: () => !0,
9477
9477
  load: async () => {
9478
- await import("./browserAll-DGNNH8t5.js");
9478
+ await import("./browserAll-CY6fP_g4.js");
9479
9479
  }
9480
9480
  }, Fb = {
9481
9481
  extension: {
@@ -9485,7 +9485,7 @@ const kh = (i) => {
9485
9485
  },
9486
9486
  test: () => typeof self < "u" && self.WorkerGlobalScope !== void 0,
9487
9487
  load: async () => {
9488
- await import("./webworkerAll-CmuBF-4y.js");
9488
+ await import("./webworkerAll-AI9nt7c5.js");
9489
9489
  }
9490
9490
  };
9491
9491
  class Se {
@@ -18676,13 +18676,13 @@ async function _w(i) {
18676
18676
  for (let n = 0; n < e.length; n++) {
18677
18677
  const o = e[n];
18678
18678
  if (o === "webgpu" && await vw()) {
18679
- const { WebGPURenderer: a } = await import("./WebGPURenderer-B0u9us9-.js");
18679
+ const { WebGPURenderer: a } = await import("./WebGPURenderer-DwcNXLNH.js");
18680
18680
  t = a, s = { ...i, ...i.webgpu };
18681
18681
  break;
18682
18682
  } else if (o === "webgl" && yw(
18683
18683
  i.failIfMajorPerformanceCaveat ?? um.defaultOptions.failIfMajorPerformanceCaveat
18684
18684
  )) {
18685
- const { WebGLRenderer: a } = await import("./WebGLRenderer-Dgo-s22r.js");
18685
+ const { WebGLRenderer: a } = await import("./WebGLRenderer-6R3JtiJK.js");
18686
18686
  t = a, s = { ...i, ...i.webgl };
18687
18687
  break;
18688
18688
  } else if (o === "canvas")
@@ -41328,13 +41328,14 @@ class ek {
41328
41328
  async addTransition(e, t = 2e6, s, r) {
41329
41329
  if (this.studio.destroyed) return;
41330
41330
  let n = null, o = null;
41331
- if (s && r && (n = this.getClipById(s) ?? null, o = this.getClipById(r) ?? null), !n || !o) {
41331
+ if (console.log("[Studio] addTransition", { fromClipId: s, toClipId: r }), s && r && (n = this.getClipById(s) ?? null, o = this.getClipById(r) ?? null, console.log("[Studio] Found clips", { clipA: n, clipB: o })), !n || !o) {
41332
41332
  console.warn("[Studio] Invalid fromClipId or toClipId", {
41333
41333
  fromClipId: s,
41334
41334
  toClipId: r
41335
41335
  });
41336
41336
  return;
41337
41337
  }
41338
+ await Promise.all([n.ready, o.ready]);
41338
41339
  const a = t, l = o.display.from - a / 2, c = l + a, h = {
41339
41340
  key: e,
41340
41341
  name: e,
@@ -41389,12 +41390,13 @@ class ek {
41389
41390
  return { trackId: s, audioSource: t };
41390
41391
  }
41391
41392
  async prepareClipForTimeline(e, t) {
41393
+ 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);
41392
41394
  const s = async () => {
41393
41395
  await this.studio.updateFrame(this.studio.currentTime);
41394
41396
  const r = this.studio.selection;
41395
41397
  r.activeTransformer != null && r.selectedClips.has(e) && typeof r.activeTransformer.updateBounds == "function" && r.activeTransformer.updateBounds();
41396
41398
  };
41397
- e.on("propsChange", s), this.studio.clipListeners.set(e, s), this.studio.pixiApp != null && typeof e.setRenderer == "function" && e.setRenderer(this.studio.pixiApp.renderer), await e.ready, 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);
41399
+ e.on("propsChange", s), this.studio.clipListeners.set(e, s), this.studio.pixiApp != null && typeof e.setRenderer == "function" && e.setRenderer(this.studio.pixiApp.renderer), await e.ready;
41398
41400
  }
41399
41401
  addClipToTrack(e, t) {
41400
41402
  if (t) {
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { aw as o, ax as i, aF as t, aE as e, aB as n, aM as r, aO as T, ay as m, aH as C, az as O, aD as f, aG as I, aA as d, aC as p, az as A, aI as N, au as P, ar as c, as as x, aK as E, aJ as F, aL as M, aN as _, at as l, av as u } from "./index-DSnnNrXJ.js";
1
+ import { aw as o, ax as i, aF as t, aE as e, aB as n, aM as r, aO as T, ay as m, aH as C, az as O, aD as f, aG as I, aA as d, aC as p, az as A, aI as N, au as P, ar as c, as as x, aK as E, aJ as F, aL as M, aN as _, at as l, av as u } from "./index-D8oGyWjX.js";
2
2
  export {
3
3
  o as Audio,
4
4
  i as Caption,
package/dist/index.umd.js CHANGED
@@ -7788,4 +7788,4 @@ vec4 transition(vec2 uv) {
7788
7788
  bool nextImage = distance(fract(uv * dots), vec2(0.5, 0.5)) < ( progress / distance(uv, center));
7789
7789
  return nextImage ? getToColor(uv) : getFromColor(uv);
7790
7790
  }
7791
- `,tk={radialSwipe:{label:"Radial Swipe",fragment:aM}},Zi={...ji.reduce((i,e)=>(i[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:`transition: ${e.name}`},i),{}),...tk},ik=Object.entries(Zi).map(([i,e])=>({key:i,label:e.label,previewStatic:`https://cdn.subgen.co/previews/static/transition_${i}_static.webp`,previewDynamic:`https://cdn.subgen.co/previews/dynamic/transition_${i}_dynamic.webp`}));function nf({name:i,renderer:e}){let t=ji.find(N=>N.name===i);if(!t){const N=Object.keys(Zi).find(q=>q.toLowerCase()===i.toLowerCase());N&&(t=Zi[N])}if(t||(t=ji.find(N=>N.name.toLowerCase()===i.toLowerCase())),!t){const N=[i,i.toLowerCase(),i.charAt(0).toUpperCase()+i.slice(1).toLowerCase(),i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),i.replace(/_/g,"")];for(const q of N){if(t=ji.find(Ie=>Ie.name.toLowerCase()===q.toLowerCase()),t)break;const me=Object.keys(Zi).find(Ie=>Ie.toLowerCase()===q.toLowerCase());if(me){t=Zi[me];break}}}if(!t){const N=ji.length,q=ji.slice(0,5).map(Ie=>Ie.name).join(", "),me=Object.keys(Zi).slice(0,3).join(", ");throw console.error(`Transition not found: "${i}". Available in gl-transitions (${N} total):`,q+"..."),console.error("Available locally:",me+"..."),new Error(`Transition "${i}" not found in gl-transitions library or local definitions`)}const s=new Ue(M.WHITE),r=Ge.create({width:e.width,height:e.height}),n=new Ct({}),o=new Ct({}),a=t.name==="displacement"||i.toLowerCase()==="displacement"||t.label==="displacement",l=a?new Ct({}):void 0;let c=null;if(a){c=document.createElement("canvas"),c.width=256,c.height=256;const N=c.getContext("2d");if(N){const q=N.createImageData(256,256);for(let me=0;me<q.data.length;me+=4){const Ie=Math.random();q.data[me]=Ie*255,q.data[me+1]=Ie*255,q.data[me+2]=Ie*255,q.data[me+3]=255}N.putImageData(q,0,0)}}let h=t.glsl||t.fragment;if(!h)throw new Error(`Transition "${i}" has no glsl or fragment code`);let u={...de.basics,...de.custom(t)};Object.entries(u).forEach(([,N])=>{N.type==="int<f32>"&&(N.type="i32",typeof N.value=="number"&&(N.value=Math.trunc(N.value))),N.type==="ivec2<f32>"&&(N.type="vec2<f32>")});const d=t.name==="GridFlip"||i.toLowerCase()==="gridflip"||t.label==="gridflip",f=t.name==="circle"||i.toLowerCase()==="circle"||t.label==="circle",p=t.name==="directional"||i.toLowerCase()==="directional"||t.label==="directional",g=t.name==="UndulatingBurnOut"||i.toLowerCase()==="undulatingburnout"||t.label==="undulatingBurnOut",m=t.name==="SquaresWire"||i.toLowerCase()==="squareswire"||t.label==="squaresWire",_=t.name==="rotate_scale_fade"||i.toLowerCase()==="rotatescalefade"||t.label==="rotateScaleFade",x=t.name==="RandomSquares"||i.toLowerCase()==="randomsquares"||t.label==="randomSquares",y=t.name==="polar_function"||i.toLowerCase()==="polar_function"||t.label==="polar_function",v=t.name==="pixelate"||i.toLowerCase()==="pixelate"||t.label==="pixelate",T=t.name==="perlin"||i.toLowerCase()==="perlin"||t.label==="perlin",S=t.name==="luma"||i.toLowerCase()==="luma"||t.label==="luma",w=t.name==="luminance_melt"||i.toLowerCase()==="luminance_melt"||i.toLowerCase()==="luminancemelt"||t.label==="luminance_melt",E=t.name==="hexagonalize"||i.toLowerCase()==="hexagonalize"||t.label==="hexagonalize",P=t.name==="heart"||i.toLowerCase()==="heart"||t.label==="heart",C=t.name==="displacement"||i.toLowerCase()==="displacement"||t.label==="displacement",A=t.name==="directionalwipe"||i.toLowerCase()==="directionalwipe"||i.toLowerCase()==="directional_wipe"||t.label==="directionalwipe",U=t.name==="directionalwarp"||i.toLowerCase()==="directionalwarp"||i.toLowerCase()==="directional_warp"||t.label==="directionalwarp",D=t.name==="crosshatch"||i.toLowerCase()==="crosshatch"||t.label==="crosshatch",$=t.name==="circleopen"||i.toLowerCase()==="circleopen"||i.toLowerCase()==="circle_open"||t.label==="circleopen",pe=t.name==="cannabisleaf"||i.toLowerCase()==="cannabisleaf"||i.toLowerCase()==="cannabis_leaf"||t.label==="cannabisleaf",k=t.name==="StereoViewer"||i.toLowerCase()==="stereoviewer"||i.toLowerCase()==="stereo_viewer"||t.label==="StereoViewer",F=t.name==="GlitchDisplace"||i.toLowerCase()==="glitchDisplace"||t.label==="GlitchDisplace",ne=t.name==="CrossZoom"||i.toLowerCase()==="crosszoom"||t.label==="CrossZoom",G=t.name==="CrazyParametricFun"||i.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",ie=t.name==="BowTieHorizontal"||i.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",we=t.name==="PolkaDotsCurtain"||i.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",ce=t.name==="Pixelize"||i.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(h=lM,u={...de.basics,...cM}),f&&(h=hM,u={...de.basics,...zx}),p&&(h=uM,u={...de.basics,...dM}),g&&(h=fM,u={...de.basics,...pM}),m&&(h=mM,u={...de.basics,...gM}),_&&(h=_M,u={...de.basics,...xM}),x&&(h=yM,u={...de.basics,...vM}),y&&(h=bM,u={...de.basics,...TM}),v&&(h=Ox,u={...de.basics,...Dx}),T&&(h=CM,u={...de.basics,...AM}),S&&(h=EM,u={...de.basics,...IM}),w&&(h=PM,u={...de.basics,...RM}),E&&(h=MM,u={...de.basics,...kM}),P&&(h=FM,u={...de.basics,...BM}),C&&(h=UM,u={...de.basics,...OM}),A&&(h=DM,u={...de.basics,...GM}),U&&(h=zM,u={...de.basics,...NM}),D&&(h=LM,u={...de.basics,...HM}),$&&(h=WM,u={...de.basics,...zx}),pe&&(h=VM,u={...de.basics,...$M}),k&&(h=XM,u={...de.basics,...YM}),F&&(h=qM),ne&&(h=KM,u={...de.basics,...jM}),G&&(h=ZM,u={...de.basics,...JM}),ie&&(h=QM),we&&(h=ek),ce&&(h=wM,u={...de.basics,...SM});const Ce={from:n,to:o,uniforms:u};a&&l&&(Ce.displacementMap=l,c&&(l.resource=c,l.update()));const Oe=new Gi({glProgram:new At({vertex:rM,fragment:oM(h)}),resources:Ce});return s.filters=[Oe],{render({width:N,height:q,from:me,to:Ie,progress:Qi}){if((s.width!==N||s.height!==q)&&(s.setSize({width:N,height:q}),r.resize(N,q)),me instanceof M?Oe.resources.from=me.source:(n.resource=me,n.update(),Oe.resources.from=n),Ie instanceof M?Oe.resources.to=Ie.source:(o.resource=Ie,o.update(),Oe.resources.to=o),a&&l&&c){if(c.width!==N||c.height!==q){c.width=N,c.height=q;const ti=c.getContext("2d");if(ti){const Et=ti.createImageData(N,q);for(let qe=0;qe<Et.data.length;qe+=4){const _t=Math.random();Et.data[qe]=_t*255,Et.data[qe+1]=_t*255,Et.data[qe+2]=_t*255,Et.data[qe+3]=255}ti.putImageData(Et,0,0)}}l.resource=c,l.update()}return Oe.resources.uniforms.uniforms.progress=Qi,e.render({container:s,target:r,clear:!1,width:N,height:q}),r},destroy(){r.destroy(),s.destroy({children:!0})}}}let sk=0;async function Nx(i){i()>50&&(await jh(15),await Nx(i))}class rk extends Zh{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 Bp()).codec,sampleRate:le.sampleRate,numberOfChannels:le.channelCount})).supported)??!1}logger=K.create(`id:${sk++},`);destroyed=!1;sprites=[];canvas;pixiApp=null;stopOutput=null;opts;hasVideoTrack;constructor(e={}){super();const{width:t=0,height:s=0}=e;this.canvas=new OffscreenCanvas(t,s),this.opts=Object.assign({bgColor:"#000",width:0,height:0,videoCodec:"avc1.42E032",audio:!0,bitrate:5e6,fps:30,metaDataTags:null},e),this.hasVideoTrack=t*s>0,Bp().catch(r=>{this.logger.warn("Failed to detect audio codec:",r)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new Lu,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 s=this.pixiApp;s.ticker&&typeof s.ticker.stop=="function"&&s.ticker.stop()}catch{}}async addSprite(e,t={}){const s={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",s);const r=await e.clone();this.pixiApp!=null&&this.pixiApp.renderer!=null&&typeof r.setRenderer=="function"&&r.setRenderer(this.pixiApp.renderer),this.logger.info("Compositor add clip ready"),this.sprites.push(Object.assign(r,{main:t.main??!1,expired:!1})),this.sprites.sort((n,o)=>n.zIndex-o.zIndex)}initMuxer(e){const{fps:t,width:s,height:r,videoCodec:n,bitrate:o,audio:a,metaDataTags:l}=this.opts,c=this.sprites.some(d=>d.width>0&&d.height>0),h=this.hasVideoTrack&&c;return Bw({video:h?{width:s,height:r,expectFPS:t,codec:n,bitrate:o,__unsafe_hardwareAcceleration__:this.opts.__unsafe_hardwareAcceleration__}:null,audio:a===!1?null:{codec:le.codecType,sampleRate:le.sampleRate,channelCount:le.channelCount},duration:e,metaDataTags:l})}output(e={}){if(this.sprites.length===0)throw Error("No sprite added");const t=this.sprites.find(u=>u.main),r=this.sprites.map(u=>u.display.from+u.duration).filter(u=>u!==1/0),n=e.maxTime??(t!=null?t.display.from+t.duration:r.length>0?Math.max(...r):1/0);if(n===1/0||n<=0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of Image, Audio");n===-1&&this.logger.warn("Unable to determine the end time, process value don't update"),this.logger.info(`start combinate video, maxTime:${n}`);const o=this.initMuxer(n);let a=performance.now();const l=this.runEncoding(o,n,{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),h(u),this.destroy()}});this.stopOutput=()=>{l(),o.close(),h()};const{stream:c,stop:h}=Fx(o.mp4file,500,this.destroy);return c}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:s,onEnded:r,onError:n}){let o=0;const a={aborted:!1};let l=null,c=null;const h=async()=>{const{fps:f,bgColor:p,audio:g}=this.opts,m=Math.round(1e6/f),_=this.sprites.some(v=>v.width>0&&v.height>0);c=nk({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=ok({muxer:e,canvas:this.canvas,outputAudio:g,hasVideoTrack:this.hasVideoTrack&&_,timeSlice:m,fps:f});let y=0;for(;;){if(l!=null)return;if(a.aborted||t!==-1&&y>t||this.sprites.length===0){u(),await r();return}o=y/t;const{audios:v,mainSprDone:T,hasVideo:S}=await c.render(y);if(T){u(),await r();return}if(a.aborted)return;this.hasVideoTrack&&S&&await new Promise(w=>requestAnimationFrame(w)),x(y,v,S),y+=m,await Nx(e.getEncodeQueueSize)}},u=()=>{a.aborted||(a.aborted=!0,clearInterval(d),c?.cleanup(),this.sprites.forEach(f=>{f.destroy()}))};h().catch(f=>{l=f,this.logger.error(f),u(),n(f)});const d=setInterval(()=>{s(o)},500);return u}exportToJSON(){const e=this.sprites.map(s=>Ys(s,s.main)),t=[];return this.sprites.forEach(s=>{if(s.transition){const r=this.sprites.filter(n=>n.id!==s.id&&n.zIndex===s.zIndex&&n.display.from<s.display.from&&(n instanceof Me||n instanceof xi)).sort((n,o)=>o.display.to-n.display.to)[0];r&&t.push({key:s.transition.name,duration:s.transition.duration,clips:[r.id,s.id]})}}),{clips:e,settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor,videoCodec:this.opts.videoCodec,bitrate:this.opts.bitrate,audio:this.opts.audio,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.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.metaDataTags!==void 0&&(this.opts.metaDataTags=e.settings.metaDataTags));for(const t of e.clips){const s=await Ki(t);if(await this.addSprite(s,{main:t.main||!1}),t.type==="Transition"){const r=t.toClipId,n=this.sprites.find(o=>o.id===r);n?n.transition={name:t.transitionEffect.key,duration:t.duration,prevClipId:t.fromClipId||""}:console.warn(`[Compositor] Could not find target clip ${r} for transition ${t.transitionEffect.key}`)}}}}function nk(i){const{pixiApp:e,sprites:t,aborter:s}=i,r=e!=null,n=new Map,o=new Map,a=new Map,l=Ge.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),c=Ge.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),h=new _e().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),u=new Map,d=T=>t.filter(S=>S.id!==T.id&&S.zIndex===T.zIndex&&S.display.from<T.display.from&&(S instanceof Me||S instanceof xi)).sort((S,w)=>w.display.to-S.display.to)[0]||null,f=async(T,S,w)=>{let E=null;if(T.transition?.prevClipId&&(E=t.find(U=>U.id===T.transition.prevClipId)||null),E||(E=d(T)),!E)return null;const P=E.duration>0?E.duration:0,C=Math.max(0,Math.min(S-E.display.from,P)),{video:A}=await w(E,C);return A},p=(T,S,w)=>{if(!e)return;e.renderer.render({container:h,target:w,clear:!0});const E=new Ue(S instanceof M?S:M.from(S));E.x=T.center.x,E.y=T.center.y,E.anchor.set(.5,.5);const P=E.texture.width||1,C=E.texture.height||1,A=T.width&&T.width!==0?Math.abs(T.width)/P:1,U=T.height&&T.height!==0?Math.abs(T.height)/C:1;T.flip==="horizontal"?(E.scale.x=-A,E.scale.y=U):T.flip==="vertical"?(E.scale.x=A,E.scale.y=-U):(E.scale.x=A,E.scale.y=U),E.rotation=(T.flip==null?1:-1)*T.angle,E.alpha=T.opacity;const D=T.style||{},$=D.borderRadius||0;let pe=null;$>0&&(pe=new _e,pe.roundRect(-P/2,-C/2,P,C,Math.min($,P/2,C/2)),pe.fill({color:16777215,alpha:1}),E.addChild(pe),E.mask=pe);const k=D.stroke;let F=null;if(k&&k.width>0){F=new _e;const ie=Te(k.color)??16777215,we=k.width;if(F.setStrokeStyle({width:we,color:ie,alignment:1}),$>0){const ce=Math.min($,P/2,C/2);F.roundRect(-P/2,-C/2,P,C,ce)}else F.rect(-P/2,-C/2,P,C);F.stroke(),E.addChild(F)}const ne=D.dropShadow;let G=null;if(ne&&(ne.blur>0||ne.distance>0)){G=new _e;const ie=Te(ne.color)??0,we=ne.alpha??.5,ce=ne.distance??0,Ce=ne.angle??0,Oe=Math.cos(Ce)*ce,N=Math.sin(Ce)*ce;if($>0){const q=Math.min($,P/2,C/2);G.roundRect(-P/2+Oe,-C/2+N,P,C,q)}else G.rect(-P/2+Oe,-C/2+N,P,C);G.fill({color:ie,alpha:we}),E.addChildAt(G,0)}e.renderer.render({container:E,target:w,clear:!1}),S instanceof M||E.texture.destroy(!0),F&&F.destroy(),pe&&pe.destroy(),G&&G.destroy(),E.destroy()};let g=null,m=null,_=null;r&&e!=null&&(g=new re,m=new re,_=new re,m.sortableChildren=!0,_.sortableChildren=!0,e.stage.addChild(m),e.stage.addChild(_),g.visible=!1,e.stage.addChild(g));const x=[...t].sort((T,S)=>T.zIndex-S.zIndex);return{render:async T=>{const S=[];let w=!1,E=!1;const P=new Map,C=async(A,U)=>{const D=`${A.id}_${U}`;if(P.has(D))return P.get(D);const $=await A.getFrame(U);return P.set(D,$),$};for(const A of a.values())A.visible=!1;for(const A of x){if(s.aborted)break;if(T<A.display.from||A.expired){if(r&&e!=null){const F=n.get(A);F&&await F.updateFrame(null)}continue}const U=T-A.display.from,D=U*A.playbackRate;A.animate(D);const{video:$,audio:pe,done:k}=await C(A,U);if(S.push(pe),r&&e!=null&&m!=null){if((A instanceof Me||A instanceof xi)&&A.transition&&U>=0&&U<=A.transition.duration){const G=await f(A,T,C),ie=$;if(G&&ie){const we=U/A.transition.duration,ce=d(A);ce?p(ce,G,l):e.renderer.render({container:h,target:l,clear:!0}),p(A,ie,c);let Ce=o.get(A.id);Ce||(Ce=nf({name:A.transition.name,renderer:e.renderer}),o.set(A.id,Ce));const Oe=Ce.render({width:e.renderer.width,height:e.renderer.height,from:l,to:c,progress:we});let N=a.get(A.id);N||(N=new Ue,N.label=`TransitionSprite_${A.id}`,a.set(A.id,N),m.addChild(N)),N.texture=Oe,N.visible=!0,N.x=0,N.y=0,N.width=e.renderer.width,N.height=e.renderer.height,N.anchor.set(0,0),N.zIndex=A.zIndex,E=!0;const q=n.get(A);if(q){const me=q.getRoot();me&&(me.visible=!1)}if(ce){const me=n.get(ce);if(me){const Ie=me.getRoot();Ie&&(Ie.visible=!1)}}continue}}let ne=n.get(A);ne==null&&$!=null&&(ne=new gn(e,A,m),n.set(A,ne)),ne!=null&&($!=null?(E=!0,await ne.updateFrame($)):await ne.updateFrame(null)),ne?.updateTransforms()}if(A.duration>0&&T>A.display.from+A.duration||k){if(A.main&&(w=!0),A.expired=!0,r){const F=n.get(A);if(F!=null){const ne=F.getRoot();ne&&(ne.visible=!1)}}}else if(r){const F=n.get(A);F?.updateTransforms()}}if(r&&e!=null&&g!=null&&m!=null&&_!=null){let A=null;for(const U of t)if(U instanceof ct&&T>=U.display.from&&T<U.display.from+U.duration){A={id:U.id,key:U.effect.key,startTime:U.display.from,duration:U.duration};break}if(!A)for(const U of t){if(U.effects&&U.effects.length>0){for(const D of U.effects)if(T>=D.startTime&&T<D.startTime+D.duration){A=D;break}}if(A)break}_.removeChildren();for(const U of n.values()){const D=U.getRoot();D&&D.parent!==m&&(D.parent&&D.parent.removeChild(D),m.addChild(D))}if(A){const{key:U,startTime:D,duration:$,id:pe}=A,k=T-D,F=$>0?Math.min(Math.max(k/$,0),1):0,ne=t.some(G=>G.id===pe&&G instanceof ct);for(const G of t){let ie=!1;if(ne?ie=G.id!==pe&&!(G instanceof ct):ie=!!G.effects&&G.effects.some(we=>we.id===pe),ie){const we=n.get(G);if(we){const ce=we.getRoot();ce&&(ce.parent&&ce.parent.removeChild(ce),g.addChild(ce))}}}if(g.children.length>0){let G=u.get(pe);if(!G)try{const ie=sf({name:U,renderer:e.renderer});ie&&ie.filter&&(G={filter:ie.filter,render:ie.render},u.set(pe,G))}catch(ie){console.warn("Failed to create effect",U,ie)}if(G){const{filter:ie,render:we}=G;ie.resources&&ie.resources.effectUniforms&&(ie.resources.effectUniforms.uniforms.uTime=F);const ce=e.renderer.width,Ce=e.renderer.height,Oe=Ge.create({width:ce,height:Ce});if(g.visible=!0,e.renderer.render({container:g,target:Oe,clear:!0}),g.visible=!1,we){const N=we({canvasTexture:Oe,progress:F,width:ce,height:Ce}),q=new Ue(N);q.width=ce,q.height=Ce,_.addChild(q)}}}}}return r&&e!=null&&e.render(),{audios:S,mainSprDone:w,hasVideo:E}},cleanup:()=>{l&&l.destroy(!0),c&&c.destroy(!0),h&&h.destroy(!0);for(const T of a.values())T.destroy();a.clear(),o.clear(),g&&g.destroy({children:!0}),m&&m.destroy({children:!0}),_&&_.destroy({children:!0}),n.forEach(T=>{T.destroy()}),n.clear()}}}function ok(i){const{canvas:e,outputAudio:t,muxer:s,hasVideoTrack:r,timeSlice:n}=i;let o=0;const a=Math.floor(3*i.fps),l=ak(1024);return(c,h,u)=>{if(t!==!1)for(const d of l(c,h))s.encodeAudio(d);if(r&&u)try{const d=new VideoFrame(e,{duration:n,timestamp:c});s.encodeVideo(d,{keyFrame:o%a===0}),o+=1}catch(d){console.warn("Failed to create VideoFrame from canvas, skipping frame:",d)}}}function ak(i){const e=i*le.channelCount,t=new Float32Array(e*3);let s=0,r=0;const n=i/le.sampleRate*1e6,o=new Float32Array(e),a=l=>{let c=0;const h=Math.floor(s/e),u=[];for(let d=0;d<h;d++)u.push(new AudioData({timestamp:r,numberOfChannels:le.channelCount,numberOfFrames:i,sampleRate:le.sampleRate,format:"f32",data:t.subarray(c,c+e)})),c+=e,r+=n;for(t.set(t.subarray(c,s),0),s-=c;l-r>n;)u.push(new AudioData({timestamp:r,numberOfChannels:le.channelCount,numberOfFrames:i,sampleRate:le.sampleRate,format:"f32",data:o})),r+=n;return u};return(l,c)=>{const h=Math.max(...c.map(u=>u[0]?.length??0));for(let u=0;u<h;u++){let d=0,f=0;for(let p=0;p<c.length;p++){const g=c[p][0]?.[u]??0,m=c[p][1]?.[u]??g;d+=g,f+=m}t[s]=d,t[s+1]=f,s+=2}return a(l)}}class lk extends _e{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(e,t=1){const r=1.5*t;this.clear(),this.setStrokeStyle({width:r,color:165063}).rect(e.x,e.y,e.width,e.height).stroke(),this.hitArea=e}}class Ht extends _e{#e=!1;handle;cursor;callbacks;constructor(e,t,s){super(),this.handle=e,this.cursor=t,this.callbacks=s,this.eventMode="static",this.#a(),this.on("pointerdown",this.#i),this.on("globalpointermove",this.#r),this.on("pointerup",this.#l),this.on("pointerupoutside",this.#l)}#a(){this.clear();const e=165063;if(this.handle==="rot")this.circle(0,0,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-4),this.arc(0,0,4,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new Zr(0,0,24);else if(["ml","mr","mt","mb"].includes(this.handle)){const t=this.handle==="ml"||this.handle==="mr",s=t?6:24,r=t?24:6;this.roundRect(-s/2,-r/2,s,r,3),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new H(-15,-15,30,30)}else this.rect(-4,-4,8,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new H(-15,-15,30,30)}#i=e=>{this.#e=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,e.global),e.stopPropagation()};#r=e=>{this.#e&&(this.callbacks.updateDrag(this.handle,e.global),e.stopPropagation())};#l=e=>{this.#e&&(this.#e=!1,this.cursor="pointer",this.callbacks.endDrag(),e.stopPropagation())}}const Lx={delta:new O};class ck extends re{group;wireframe=new lk;selectionOutlines=new _e;isDragging=!1;lastPointer=new X;activeHandle=null;#e;#a=new Map;#i=new X;#r=0;#l=0;#c=new H;#s=new X;#h=new H;#t=[new X,new X,new X,new X];#n=1;#o=1;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static";const t={beginDrag:(s,r)=>this.#v(s,r),updateDrag:(s,r)=>this.#b(s,r),endDrag:()=>this.#m()};this.#e={tl:new Ht("tl","nwse-resize",t),tr:new Ht("tr","nesw-resize",t),bl:new Ht("bl","nesw-resize",t),br:new Ht("br","nwse-resize",t),ml:new Ht("ml","ew-resize",t),mr:new Ht("mr","ew-resize",t),mt:new Ht("mt","ns-resize",t),mb:new Ht("mb","ns-resize",t),rot:new Ht("rot","crosshair",{beginDrag:(s,r)=>this.#w(r),updateDrag:(s,r)=>this.#S(r),endDrag:()=>this.#m()})},this.addChild(this.selectionOutlines,this.wireframe,...Object.values(this.#e)),this.#_(),this.visible=!1,Ze.shared.addOnce(()=>{!this.destroyed&&this.parent&&(this.#u(),this.visible=!0)})}#_(){this.on("pointerdown",this.#x),this.on("pointerup",this.#p),this.on("pointerupoutside",this.#p),this.on("globalpointermove",this.#y)}#u(){if(this.group.length===1){const e=this.group[0];this.#r=e.rotation;const t=this.#f(e);let s,r;this.opts.clip?(s=this.opts.clip.width,r=this.opts.clip.height):(s=t.width,r=t.height);const n=e.toGlobal(new X(0,0));this.#i.set(n.x,n.y),this.#h.copyFrom(new H(-s/2,-r/2,s,r))}else{let e=1/0,t=1/0,s=-1/0,r=-1/0;if(this.parent)for(const c of this.group){const h=this.#f(c);this.#t[0].set(h.x,h.y),this.#t[1].set(h.x+h.width,h.y),this.#t[2].set(h.x+h.width,h.y+h.height),this.#t[3].set(h.x,h.y+h.height);for(const u of this.#t)c.toGlobal(u,u),this.toLocal(u,void 0,u),e=Math.min(e,u.x),t=Math.min(t,u.y),s=Math.max(s,u.x),r=Math.max(r,u.y)}const n=s-e,o=r-t,a=e+n/2,l=t+o/2;if(this.#h.copyFrom(new H(-n/2,-o/2,n,o)),this.parent){const c=this.toGlobal(new X(a,l));this.#i.set(c.x,c.y)}}this.#d()}#f(e){const t=e.children.filter(l=>l.label!=="ShadowContainer");if(t.length===0){const l=e.getLocalBounds();return new H(l.minX,l.minY,l.maxX-l.minX,l.maxY-l.minY)}const s=t.find(l=>l.label==="MainSprite");if(s){const l=s.getLocalBounds(),c=s.localTransform,h=c.apply(new X(l.x,l.y)),u=c.apply(new X(l.x+l.width,l.y)),d=c.apply(new X(l.x+l.width,l.y+l.height)),f=c.apply(new X(l.x,l.y+l.height)),p=Math.min(h.x,u.x,d.x,f.x),g=Math.max(h.x,u.x,d.x,f.x),m=Math.min(h.y,u.y,d.y,f.y),_=Math.max(h.y,u.y,d.y,f.y);return new H(p,m,g-p,_-m)}let r=1/0,n=1/0,o=-1/0,a=-1/0;for(const l of t){const c=l.getBounds(),h=e.toLocal(new X(c.minX,c.minY)),u=e.toLocal(new X(c.maxX,c.maxY));r=Math.min(r,h.x,u.x),n=Math.min(n,h.y,u.y),o=Math.max(o,h.x,u.x),a=Math.max(a,h.y,u.y)}return new H(r,n,o-r,a-n)}updateBounds(){this.#u()}#x=e=>{this.#u(),this.isDragging=!0,this.lastPointer.copyFrom(e.global),this.cursor="grabbing"};#p=()=>{this.isDragging&&this.emit("transformEnd"),this.isDragging=!1,this.activeHandle=null,this.cursor="default"};#y=e=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const t=this.parent.toLocal(this.lastPointer),s=this.parent.toLocal(e.global),r=s.x-t.x,n=s.y-t.y;for(const l of this.group)l.x+=r,l.y+=n;const o=e.global.x-this.lastPointer.x,a=e.global.y-this.lastPointer.y;this.#i.x+=o,this.#i.y+=a,this.lastPointer.copyFrom(e.global),this.#d(),this.emit("transforming")};#v(e,t){this.#u(),this.isDragging=!0,this.activeHandle=e,this.#a.clear();for(const s of this.group)this.#a.set(s,s.localTransform.clone());this.rotation=this.#r,this.#c.copyFrom(this.#h),this.#A(e)}#b(e,t){this.#T(e,t)}async#T(e,t){const s=this.#s,r=this.#E(e,this.toLocal(t),s),n=r.width/this.#c.width,o=r.height/this.#c.height,a=this.toGlobal(s);if(this.opts.clip&&this.opts.clip.type==="Text"){const c=r.width;this.emit("textClipResize",{handle:e,newWidth:c,newHeight:r.height,pivotWorld:a,proposed:r,sx:n,sy:o})}else this.#g(this.#I(a,this.#r,n,o));this.#h.copyFrom(r),this.#d(),this.emit("transforming")}#w(e){this.#u(),this.isDragging=!0,this.activeHandle="rot",this.#a.clear();for(const t of this.group)this.#a.set(t,t.localTransform.clone());this.#l=Math.atan2(e.y-this.#i.y,e.x-this.#i.x)}#S(e){const s=Math.atan2(e.y-this.#i.y,e.x-this.#i.x)-this.#l,r=this.#r+s;this.#g(this.#P(this.#i,s)),this.rotation=r,this.#d(r),this.emit("transforming")}#m(){this.isDragging=!1,this.#r=this.rotation,this.activeHandle=null,this.#d(this.#r),this.emit("transformEnd")}#d(e=this.#r){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#i)),this.rotation=e;const s=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),r=this.#h;this.wireframe.draw(r,s);const n=r.x+r.width/2,o=r.y+r.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 c of l)c.scale.set(s);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(r.x,r.y),this.#e.tr.position.set(r.x+r.width,r.y),this.#e.bl.position.set(r.x,r.y+r.height),this.#e.br.position.set(r.x+r.width,r.y+r.height),this.#e.ml.position.set(r.x,o),this.#e.mr.position.set(r.x+r.width,o),this.#e.mt.position.set(n,r.y),this.#e.mb.position.set(n,r.y+r.height),this.#e.rot.position.set(n,r.y-30*s),this.#C(s)}#C(e){if(this.selectionOutlines.clear(),this.group.length<=1||!this.parent)return;const t={width:1*e,color:43775,alpha:1};for(const s of this.group){const r=this.#f(s);this.#t[0].set(r.x,r.y),this.#t[1].set(r.x+r.width,r.y),this.#t[2].set(r.x+r.width,r.y+r.height),this.#t[3].set(r.x,r.y+r.height);for(const n of this.#t)s.toGlobal(n,n),this.toLocal(n,void 0,n);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)}}#A(e){const t=this.#c;if(this.opts.centeredScaling){this.#s.set(t.x+t.width/2,t.y+t.height/2);return}e==="tl"?this.#s.set(t.x+t.width,t.y+t.height):e==="tr"?this.#s.set(t.x,t.y+t.height):e==="bl"?this.#s.set(t.x+t.width,t.y):e==="br"?this.#s.set(t.x,t.y):e==="ml"?this.#s.set(t.x+t.width,t.y+t.height/2):e==="mr"?this.#s.set(t.x,t.y+t.height/2):e==="mt"?this.#s.set(t.x+t.width/2,t.y+t.height):e==="mb"&&this.#s.set(t.x+t.width/2,t.y)}#E(e,t,s){if(this.opts.centeredScaling){const n=Math.max(this.#n,Math.abs(t.x-s.x)*2),o=Math.max(this.#o,Math.abs(t.y-s.y)*2);return new H(s.x-n/2,s.y-o/2,n,o)}if(e==="tl"){const n=Math.min(t.x,s.x-this.#n),o=Math.min(t.y,s.y-this.#o);return new H(n,o,s.x-n,s.y-o)}if(e==="tr"){const n=Math.max(t.x,s.x+this.#n),o=Math.min(t.y,s.y-this.#o);return new H(s.x,o,n-s.x,s.y-o)}if(e==="bl"){const n=Math.min(t.x,s.x-this.#n),o=Math.max(t.y,s.y+this.#o);return new H(n,s.y,s.x-n,o-s.y)}if(e==="br"){const n=Math.max(t.x,s.x+this.#n),o=Math.max(t.y,s.y+this.#o);return new H(s.x,s.y,n-s.x,o-s.y)}const r=this.#c;if(e==="ml"){const n=Math.min(t.x,s.x-this.#n);return new H(n,r.y,s.x-n,r.height)}if(e==="mr"){const n=Math.max(t.x,s.x+this.#n);return new H(s.x,r.y,n-s.x,r.height)}if(e==="mt"){const n=Math.min(t.y,s.y-this.#o);return new H(r.x,n,r.width,s.y-n)}if(e==="mb"){const n=Math.max(t.y,s.y+this.#o);return new H(r.x,s.y,r.width,n-s.y)}return new H(s.x,s.y,this.#n,this.#o)}#I(e,t,s,r){return Lx.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(s,r).rotate(t).translate(e.x,e.y)}#P(e,t){return Lx.delta.identity().translate(-e.x,-e.y).rotate(t).translate(e.x,e.y)}#g(e){for(const t of this.group){const s=this.#a.get(t),r=t.parent;if(!s||!r)continue;const n=r.worldTransform.clone().invert(),o=r.worldTransform.clone().append(s),a=e.clone().append(o),l=n.clone().append(a);t.setFromMatrix(l)}}}class hk{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new X;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;init(e,t){this.selectionGraphics=new _e,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",s=>this.onStagePointerDown(s)),e.stage.on("globalpointermove",s=>this.onStagePointerMove(s)),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),s=Math.min(this.dragSelectionStart.x,t.x),r=Math.min(this.dragSelectionStart.y,t.y),n=Math.abs(t.x-this.dragSelectionStart.x),o=Math.abs(t.y-this.dragSelectionStart.y);this.selectionGraphics.clear(),this.selectionGraphics.rect(s,r,n,o).fill({color:703971,alpha:.3}),this.selectionGraphics.rect(s,r,n,o).stroke({width:2,color:703971})}}onStagePointerUp(){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const e=this.selectionGraphics.getBounds(),t=[],s=new H(e.x,e.y,e.width,e.height);if(s.width>2||s.height>2){for(const r of this.studio.clips){const n=this.studio.spriteRenderers.get(r);if(!n)continue;const o=n.getRoot();if(!o||!o.visible)continue;const a=o.getBounds();s.x<a.x+a.width&&s.x+s.width>a.x&&s.y<a.y+a.height&&s.y+s.height>a.y&&t.push(r)}if(t.length>0)for(const r of t)this.selectClip(r,!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 s=t.getRoot();s!=null&&(s.eventMode="static",s.cursor="pointer",s.on("pointerdown",r=>{const n=this.getTopmostClipAtPoint(r.global);n&&this.selectClip(n,r.shiftKey)}),this.interactiveClips.add(e))}getTopmostClipAtPoint(e){if(!this.studio.pixiApp)return null;let t=null,s=-1/0;for(const r of this.interactiveClips){const n=this.studio.spriteRenderers.get(r);if(!n)continue;const o=n.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&&r.zIndex>s&&(s=r.zIndex,t=r)}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(s=>e.includes(s.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})}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 r of this.selectedClips){const n=this.studio.spriteRenderers.get(r);if(n==null)continue;const o=n.getRoot();o!=null&&(e.push(o),this.selectedClips.size===1&&(t=r))}if(e.length===0){console.warn("Cannot create transformer: no sprites found");return}this.activeTransformer=new ck({group:e,clip:t});let s=null;this.activeTransformer.on("transforming",()=>{s===null&&(s=requestAnimationFrame(()=>{s=null,this.syncSelectedClipsTransformsRealtime()}))}),this.activeTransformer.on("textClipResize",r=>{this.textClipResizedWidth=r.newWidth,this.textClipResizeHandle=r.handle,this.textClipResizedSx=r.sx,this.textClipResizedSy=r.sy}),this.activeTransformer.on("transformEnd",async()=>{s!==null&&(cancelAnimationFrame(s),s=null),await this.syncSelectedClipsTransforms();for(const r of this.selectedClips)this.studio.emit("clip:updated",{clip:r})}),this.activeTransformer.on("pointerdown",r=>{const n=this.getTopmostClipAtPoint(r.global);n&&!this.selectedClips.has(n)&&(this.selectClip(n,r.shiftKey),r.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 gt))continue;const s=this.studio.spriteRenderers.get(t);if(s==null)continue;const r=s.getRoot(),n=s.getSprite();if(r==null||n==null||n.texture==null)continue;const o=Math.abs(r.scale.x*n.scale.x);if(o===1)continue;const a=t.left,l=t.top,c=t.width,h=n.texture.width,u=o*h;await t.updateStyle({wordWrap:!0,wordWrapWidth:u});const d=await t.getTexture();d&&(await s.updateFrame(d),n.scale.set(1,1),r.scale.set(1,1),e==="ml"?t.left=a+c-t.width:t.left=a,t.top=l,r.x=t.left+t.width/2,r.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 s=t.getRoot(),r=t.getSprite();if(s==null||r==null||r.texture==null)continue;const n=r.texture.width,o=r.texture.height,a=Math.abs(s.scale.x*r.scale.x)*n,l=Math.abs(s.scale.y*r.scale.y)*o,c=(e instanceof gt||e instanceof ei)&&this.textClipResizedWidth!==null?this.textClipResizedWidth:a,h=e.width,d=(e.style?.fontSize??16)*Math.max(this.textClipResizedSx||1,this.textClipResizedSy||1);let f=s.x;const p=s.y-l/2,g=s.x-c/2;if(e instanceof gt&&this.textClipResizedWidth!==null){const _={wordWrap:!0,wordWrapWidth:c};this.textClipResizeHandle==="mr"?(f=e.left+c/2,s.x=f):this.textClipResizeHandle==="ml"?(f=e.left+c/2-(c-h),s.x=f):["br","tr"].includes(this.textClipResizeHandle)?(f=e.left+c/2,_.fontSize=d):["bl","tl"].includes(this.textClipResizeHandle)&&(f=e.left+c/2-(c-h),_.fontSize=d),await e.updateStyle(_);const x=await e.getTexture();x&&(await t.updateFrame(x),e.width=c,e.height=x.height,this.textClipResizedWidth=null,e.left=f-e.width/2,e.top=s.y-e.height/2,r.scale.set(1,1),s.scale.set(1,1))}else{e.left=g,e.top=p,e.width=a,e.height=l;const _=e.flip==null?1:-1;e.angle=_*s.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 s=t.getRoot(),r=t.getSprite();if(s!=null&&r!=null&&r.texture!=null){const n=r.texture.width,o=r.texture.height,a=Math.abs(s.scale.x*r.scale.x)*n,l=Math.abs(s.scale.y*r.scale.y)*o,c=s.x-a/2,h=s.y-l/2;e.left=c,e.top=h,e.width=a,e.height=l;const u=e.flip==null?1:-1;e.angle=u*s.angle,t.updateTransforms(),this.studio.emit("clip:updated",{clip:e})}}}async deleteSelected(){return this.studio.deleteSelected()}}class uk{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 r=(this.currentTime-e.display.from)/1e6;this.isPlaybackCapable(e)&&await e.play(t,r)}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[s,{element:r}]of this.playbackElements.entries()){if(!(this.currentTime>=s.display.from&&(s.display.to===0||this.currentTime<=s.display.to))){this.isPlaybackCapable(s)&&s.pause(r);continue}const o=(this.currentTime-s.display.from)/1e6;this.isPlaybackCapable(s)&&await s.seek(r,o)}if(await this.studio.updateFrame(this.currentTime),this.studio.emit("currentTime",{currentTime:this.currentTime}),t){this.isPlaying=!0;for(const[s,{element:r}]of this.playbackElements.entries()){if(!(this.currentTime>=s.display.from&&(s.display.to===0||this.currentTime<=s.display.to)))continue;const o=(this.currentTime-s.display.from)/1e6;this.isPlaybackCapable(s)&&await s.play(r,o)}}}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 s=(performance.now()-this.playStartTimestamp)*1e3;this.currentTime=Math.min(this.playStartTime+s,this.maxDuration),this.studio.emit("currentTime",{currentTime:this.currentTime});try{await this.studio.updateFrame(this.currentTime)}catch(r){console.warn("Error updating frame:",r)}this.isPlaying&&(this.rafId=requestAnimationFrame(e))};e()}isPlaybackCapable(e){return"play"in e&&"pause"in e&&"seek"in e}}class Ji{static instance;fonts=new Map;constructor(){}static getInstance(){return Ji.instance||(Ji.instance=new Ji),Ji.instance}async addFont(e){if(!this.fonts.has(e.name))try{const s=await new FontFace(e.name,`url(${e.url})`).load();document.fonts.add(s),this.fonts.set(e.name,s)}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 Hx=Ji.getInstance();class dk{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){const t={id:e.id||`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:e.name,type:e.type,clipIds:[]};return this.tracks.push(t),this.studio.emit("track:added",{track:t}),t}async removeTrack(e){const t=this.tracks.findIndex(n=>n.id===e);if(t===-1)return;const r=[...this.tracks[t].clipIds];for(const n of r)await this.removeClipById(n);this.tracks.splice(t,1),this.studio.emit("track:removed",{trackId:e})}async addTransition(e,t=2e6,s,r){if(this.studio.destroyed)return;let n=null,o=null;if(s&&r&&(n=this.getClipById(s)??null,o=this.getClipById(r)??null),!n||!o){console.warn("[Studio] Invalid fromClipId or toClipId",{fromClipId:s,toClipId:r});return}const a=t,l=o.display.from-a/2,c=l+a,h={key:e,name:e,duration:a,fromClipId:n.id,toClipId:o.id,start:Math.max(0,l),end:c},u=this.findTrackIdByClipId(o.id);if(u){const f=this.tracks.find(p=>p.id===u);if(f){const p=f.clipIds.map(g=>this.getClipById(g)).filter(g=>{if(!g||g.type!=="Transition")return!1;const m=g;return m.fromClipId===n.id&&m.toClipId===o.id});for(const g of p)await this.removeClip(g)}}this.studio.transitionRenderers.has(n.id)&&(this.studio.transitionRenderers.get(n.id)?.destroy(),this.studio.transitionRenderers.delete(n.id)),this.studio.transitionRenderers.has(o.id)&&(this.studio.transitionRenderers.get(o.id)?.destroy(),this.studio.transitionRenderers.delete(o.id)),n.transition={...h},o.transition={...h};const d=new Lt(e);d.duration=a,d.fromClipId=Math.max(0,l)===0?null:n.id,d.toClipId=o.id,d.fromClipId===null&&n&&(d.fromClipId=n.id),d.display.from=Math.max(0,l),d.display.to=c,await this.addClip(d,{trackId:u}),this.studio.seek(this.studio.currentTime)}async addClip(e,t){const s=Array.isArray(e)?e:[e];if(s.length===0)return;const{trackId:r,audioSource:n}=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 s)await this.prepareClipForTimeline(a,r),o.push(a);await this.recalculateMaxDuration();for(const a of o)await this.setupClipVisuals(a,n);await this.studio.updateFrame(this.studio.currentTime),this.emitAddClipEvents(o,r)}normalizeAddClipOptions(e){let t,s;if(e&&(typeof e=="string"||e instanceof File||e instanceof Blob))t=e;else if(typeof e=="object"&&e!==null&&!("size"in e)){const r=e;t=r.audioSource,s=r.trackId}return{trackId:s,audioSource:t}}async prepareClipForTimeline(e,t){const s=async()=>{await this.studio.updateFrame(this.studio.currentTime);const r=this.studio.selection;r.activeTransformer!=null&&r.selectedClips.has(e)&&typeof r.activeTransformer.updateBounds=="function"&&r.activeTransformer.updateBounds()};e.on("propsChange",s),this.studio.clipListeners.set(e,s),this.studio.pixiApp!=null&&typeof e.setRenderer=="function"&&e.setRenderer(this.studio.pixiApp.renderer),await e.ready,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)}addClipToTrack(e,t){if(t){const s=this.tracks.find(r=>r.id===t);if(s)s.clipIds.includes(e.id)||s.clipIds.push(e.id);else{const r={id:t,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(r),this.studio.emit("track:added",{track:r})}}else{const r={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(r),this.studio.emit("track:added",{track:r})}}async setupClipVisuals(e,t){const s=this.studio.spriteRenderers.get(e);if(s){const n=this.studio.clipsNormalContainer,o=s.getRoot();o&&!o.parent&&n.addChild(o);return}const r=await e.ready;if(await this.setupPlaybackForClip(e,t),r.width>0&&r.height>0){const n=this.studio.clipsNormalContainer,o=e.type==="Video"&&this.isPlaybackCapable(e);if(!o||o&&e.tickInterceptor!=null){const a=new gn(this.studio.pixiApp,e,n);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 s=e[0],r=t||this.tracks.find(n=>n.clipIds.includes(s.id))?.id||"";this.studio.emit("clip:added",{clip:s,trackId:r})}else this.studio.emit("clips:added",{clips:e,trackId:t})}async removeClip(e,t={permanent:!0}){const{permanent:s}=t,r=this.clips.findIndex(h=>h===e);if(r===-1)return;if(e instanceof Lt){if(e.fromClipId){const h=this.getClipById(e.fromClipId);h&&"transition"in h&&delete h.transition}if(e.toClipId){const h=this.getClipById(e.toClipId);h&&"transition"in h&&delete h.transition}}this.studio.selection.selectedClips.has(e)&&this.studio.selection.deselectClip(),this.clips.splice(r,1);const n=[];for(const h of this.tracks){const u=h.clipIds.indexOf(e.id);u!==-1&&(h.clipIds.splice(u,1),n.push(h.id))}for(const h of n){const u=this.tracks.findIndex(d=>d.id===h);u!==-1&&this.tracks[u].clipIds.length===0&&(this.tracks.splice(u,1),this.studio.emit("track:removed",{trackId:h}))}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(s)a.destroy(),this.studio.spriteRenderers.delete(e);else{const h=a.getRoot();h&&h.parent&&h.parent.removeChild(h)}const l=this.studio.transport.playbackElements.get(e);l!=null&&s&&this.isPlaybackCapable(e)&&(e.cleanupPlayback(l.element,l.objectUrl),this.studio.transport.playbackElements.delete(e));const c=this.studio.videoSprites.get(e);c!=null&&this.studio.pixiApp!=null&&(c.parent&&c.parent.removeChild(c),s&&(c.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 s of e){const r=this.clips.findIndex(c=>c===s);if(r===-1)continue;if(s instanceof Lt){if(s.fromClipId){const c=this.getClipById(s.fromClipId);c&&"transition"in c&&delete c.transition}if(s.toClipId){const c=this.getClipById(s.toClipId);c&&"transition"in c&&delete c.transition}}this.studio.selection.selectedClips.has(s)&&this.studio.selection.deselectClip(),this.clips.splice(r,1);for(const c of this.tracks){const h=c.clipIds.indexOf(s.id);h!==-1&&c.clipIds.splice(h,1)}this.studio.selection.interactiveClips.delete(s);const n=this.studio.clipListeners.get(s);n&&(s.off("propsChange",n),this.studio.clipListeners.delete(s));const o=this.studio.spriteRenderers.get(s);if(o!=null)if(t.permanent)o.destroy(),this.studio.spriteRenderers.delete(s);else{const c=o.getRoot();c&&c.parent&&c.parent.removeChild(c)}const a=this.studio.transport.playbackElements.get(s);a!=null&&t.permanent&&this.isPlaybackCapable(s)&&(s.cleanupPlayback(a.element,a.objectUrl),this.studio.transport.playbackElements.delete(s));const l=this.studio.videoSprites.get(s);l!=null&&this.studio.pixiApp!=null&&(l.parent&&l.parent.removeChild(l),t.permanent&&(l.destroy(),this.studio.videoSprites.delete(s)))}for(let s=this.tracks.length-1;s>=0;s--)if(this.tracks[s].clipIds.length===0){const r=this.tracks[s].id;this.tracks.splice(s,1),this.studio.emit("track:removed",{trackId:r})}await this.recalculateMaxDuration(),this.studio.emit("clips:removed",{clipIds:e.map(s=>s.id)})}}async removeClipById(e){const t=this.clips.find(s=>s.id===e);t&&await this.removeClip(t)}async updateClip(e,t){const s=this.clips.find(r=>r.id===e);s&&(await this.applyClipUpdate(s,t),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(s),this.studio.emit("clip:updated",{clip:s}))}async updateClips(e){const t=[];for(const{id:s,updates:r}of e){const n=this.clips.find(o=>o.id===s);n&&(await this.applyClipUpdate(n,r),t.push(n))}if(t.length!==0){await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime);for(const s of t)this.updateTransformer(s),this.studio.emit("clip:updated",{clip:s})}}async replaceClipsBySource(e,t){const s=this.clips.filter(r=>r.src===e);if(s.length!==0){this.studio.suspendRendering();for(const r of s){if(!this.clips.includes(r))continue;const n=this.findTrackIdByClipId(r.id);if(!n)continue;const o=this.getTrackById(n);if(!o)continue;const a=await t(r),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 c=this.clips.indexOf(r);c!==-1&&(this.clips[c]=a);const h=o.clipIds.indexOf(r.id);h!==-1&&(o.clipIds[h]=a.id),await this.setupClipVisuals(a);const u=this.studio.spriteRenderers.get(r);u&&(u.destroy(),this.studio.spriteRenderers.delete(r));const d=this.studio.videoSprites.get(r);d&&(d.parent&&d.parent.removeChild(d),d.destroy(),this.studio.videoSprites.delete(r));const f=this.studio.clipListeners.get(r);f&&(r.off("propsChange",f),this.studio.clipListeners.delete(r)),this.studio.selection.selectedClips.has(r)&&(this.studio.selection.selectedClips.delete(r),this.studio.selection.selectedClips.add(a)),this.studio.emit("clip:replaced",{oldClip:r,newClip:a,trackId:n})}await this.recalculateMaxDuration(),this.studio.resumeRendering(),await this.studio.updateFrame(this.studio.currentTime)}}async applyClipUpdate(e,t){if(e instanceof gt&&(await e.updateStyle(t),"style"in t&&delete t.style),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 s=t.display.to-t.display.from;s!==t.duration&&(e.duration=s)}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(r=>Ys(r,!1)),t=this.tracks.map(r=>({id:r.id,name:r.name,type:r.type,clipIds:[...r.clipIds]})),s=[];return this.clips.forEach(r=>{if(r.transition){const n=this.tracks.find(o=>o.clipIds.includes(r.id));if(n){const o=n.clipIds.indexOf(r.id);if(o>0){const a=n.clipIds[o-1];s.push({key:r.transition.name,duration:r.transition.duration,clips:[a,r.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 s=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),s&&this.studio.pixiApp!=null){const r=this.studio.opts.width,n=this.studio.opts.height;this.studio.pixiApp.renderer.resize(r,n),this.studio.opts.canvas&&(this.studio.opts.canvas.width=r,this.studio.opts.canvas.height=n)}}const t=[];if(e.clips){await this.ensureFontsForClips(e.clips);const s=new Map;if(e.tracks){for(const n of e.tracks)if(n.clipIds)for(const o of n.clipIds)s.set(o,n.id)}if(e.tracks)for(const n of e.tracks)this.tracks.push({id:n.id,name:n.name,type:n.type,clipIds:[]});for(const n of e.clips)t.push((async()=>{try{let o=n.id?s.get(n.id):void 0;if(n.type==="Transition"){const l=n,c=l.toClipId||l.fromClipId;c&&(o=s.get(c))}if(n.type!=="Text"&&n.type!=="Caption"&&n.type!=="Effect"&&n.type!=="Transition"&&(!n.src||n.src.trim()===""))return console.warn(`Skipping clip ${n.type} with empty source`,n),{clip:null};const a=await Ki(n);return(a.type==="Video"||a.type==="Image")&&(!n.width||!n.height)&&this.studio.opts.width&&this.studio.opts.height&&(typeof a.scaleToFit=="function"&&await a.scaleToFit(this.studio.opts.width,this.studio.opts.height),typeof a.centerInScene=="function"&&a.centerInScene(this.studio.opts.width,this.studio.opts.height)),{clip:a,intendedTrackId:o}}catch(o){return console.error(`Failed to load clip ${n.id||"unknown"}:`,o),{clip:null}}})());const r=await Promise.all(t);for(const{clip:n,intendedTrackId:o}of r)n&&(n.id||(n.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.push(n),this.addClipToTrack(n,o))}this.studio.pixiApp&&await Promise.all(this.clips.map(async s=>{const r=async()=>{await this.studio.updateFrame(this.studio.currentTime);const n=this.studio.selection;n.activeTransformer!=null&&n.selectedClips.has(s)&&typeof n.activeTransformer.updateBounds=="function"&&n.activeTransformer.updateBounds()};s.on("propsChange",r),this.studio.clipListeners.set(s,r),typeof s.setRenderer=="function"&&s.setRenderer(this.studio.pixiApp.renderer),await s.ready,await this.setupClipVisuals(s)}));for(const s of this.clips){const r=s.effects;if(Array.isArray(r))for(const n of r)this.studio.globalEffects.has(n.id)||this.studio.globalEffects.set(n.id,{id:n.id,key:n.key,startTime:n.startTime,duration:n.duration})}for(const s of this.clips)if(s instanceof Lt){const r={name:s.transitionEffect.key,key:s.transitionEffect.key,duration:s.duration,fromClipId:s.fromClipId,toClipId:s.toClipId,start:s.display.from,end:s.display.to};if(s.fromClipId){const n=this.getClipById(s.fromClipId);n&&(n.transition={...r})}if(s.toClipId){const n=this.getClipById(s.toClipId);n&&(n.transition={...r})}}await this.recalculateMaxDuration();try{await this.studio.updateFrame(this.studio.currentTime)}catch(s){console.error("[Studio] Failed to update initial frame:",s)}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 s of t)await this.removeClip(s)}async duplicateSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e);if(t.length===0)return;const s=[];for(const r of t){const n=this.findTrackIdByClipId(r.id);if(!n)continue;const o=this.tracks.find(u=>u.id===n);if(!o)continue;const a=Ys(r,!1),l=await Ki(a);l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const c=`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=`${o.name} (Copy)`;this.addTrack({id:c,name:h,type:o.type}),await this.addClip(l,{trackId:c}),s.push(l.id)}s.length>0&&this.studio.selection.selectClipsByIds(s)}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 s=t[0],r=e??this.studio.currentTime;if(r<=s.display.from||s.display.to>0&&r>=s.display.to){console.warn("[Studio] Split time is outside clip bounds");return}const n=Ys(s,!1),o=r-s.display.from,a=s.playbackRate||1,l=o*a,c={duration:o,display:{from:s.display.from,to:r}};s.trim&&(c.trim={from:s.trim.from,to:s.trim.from+l}),await this.updateClip(s.id,c);const h={...n};h.display={from:r,to:n.display.to},h.duration=n.duration-o,h.trim&&(h.trim={from:h.trim.from+l,to:h.trim.to});const u=await Ki(h);u.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const d=this.findTrackIdByClipId(s.id);d&&(await this.addClip(u,{trackId:d}),this.studio.selection.selectClipsByIds([u.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 s=t[0],r=e*1e6,n=s.playbackRate||1,o=r*n;if(r>=s.duration){console.warn("[Studio] Trim amount exceeds clip duration");return}const a=s.duration-r,l=s.display.from+r,c=s.display.to,h={duration:a,display:{from:l,to:c}};if(s.trim)h.trim={from:s.trim.from+o,to:s.trim.to};else{const u=s.sourceDuration||s.duration;h.trim={from:o,to:u}}await this.updateClip(s.id,h)}async updateSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==0)for(const s of t)await this.updateClip(s.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 s of e){if(s.type==="Text"){const r=s.style?.fontUrl||s.fontUrl;r&&t.set(r,{name:s.style?.fontFamily||s.fontFamily||"CustomFont",url:r})}if(s.type==="Caption"){const r=s.style?.fontUrl||s.fontUrl;r&&t.set(r,{name:s.style?.fontFamily||s.fontFamily||"CustomFont",url:r})}}if(t.size>0)try{await Hx.loadFonts(Array.from(t.values()))}catch(s){console.warn("Failed to load some fonts:",s)}}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 s=t.duration>0?t.duration:0;if(s===1/0)continue;const r=t.display.to>0?t.display.to:t.display.from+s;r>e&&(e=r)}this.studio.maxDuration=e}async setupPlaybackForClip(e,t){if(this.studio.pixiApp!=null){if(!this.isPlaybackCapable(e)){if(this.studio.pixiApp!=null&&(await e.ready).width>0&&(await e.ready).height>0){const s=new gn(this.studio.pixiApp,e,this.studio.clipsNormalContainer);this.studio.spriteRenderers.set(e,s)}return}try{const s=e;if(e.type==="Audio"&&t&&typeof t!="string"){const o=URL.createObjectURL(t);e.src=o}const{element:r,objectUrl:n}=await s.createPlaybackElement();if(e.type==="Video"){const o=M.from(r),a=new Ue(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:r,objectUrl:n})}catch(s){if(console.warn(`Failed to setup playback for ${e.constructor.name}`,s),this.studio.pixiApp!=null&&(await e.ready).width>0&&(await e.ready).height>0){const r=new gn(this.studio.pixiApp,e,this.studio.artboard);this.studio.spriteRenderers.set(e,r)}}}}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 s=t-e,r=[...this.clips];for(const n of r){const o=n.display.from,a=n.display.to;if(!(a<=e)){if(o>=t){await this.updateClip(n.id,{display:{from:n.display.from-s,to:n.display.to-s}});continue}if(o>=e&&a<=t){await this.removeClip(n);continue}if(o<e&&a>t){const l=await n.clone();l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const c=e,h=e+(a-t),u=n.trim.from+(t-o)*n.playbackRate,d=n.trim.to,f=this.tracks.find(p=>p.clipIds.includes(n.id));f&&(await this.addClip(l,{trackId:f.id}),await this.updateClip(l.id,{display:{from:c,to:h},trim:{from:u,to:d}})),await this.updateClip(n.id,{display:{from:n.display.from,to:e},trim:{from:n.trim.from,to:n.trim.from+(e-o)*n.playbackRate}});continue}if(o<e&&a<=t){await this.updateClip(n.id,{display:{from:n.display.from,to:e},trim:{from:n.trim.from,to:n.trim.from+(e-o)*n.playbackRate}});continue}if(o>=e&&a>t){await this.updateClip(n.id,{display:{from:e,to:e+(a-t)},trim:{from:n.trim.from+(t-o)*n.playbackRate,to:n.trim.to}});continue}}}await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}}const fk={Date:!0,RegExp:!0,String:!0,Number:!0};function Wx(i,e,t={cyclesFix:!0},s=[]){let r=[];const n=Array.isArray(i);for(const a in i){const l=i[a],c=n?+a:a;if(!(a in e)){r.push({type:"REMOVE",path:[c],oldValue:i[a]});continue}const h=e[a],u=typeof l=="object"&&typeof h=="object"&&Array.isArray(l)===Array.isArray(h);l&&h&&u&&!fk[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!s.includes(l))?r.push.apply(r,Wx(l,h,t,t.cyclesFix?s.concat([l]):[]).map(d=>(d.path.unshift(c),d))):l!==h&&!(Number.isNaN(l)&&Number.isNaN(h))&&!(u&&(isNaN(l)?l+""==h+"":+l==+h))&&r.push({path:[c],type:"CHANGE",value:h,oldValue:l})}const o=Array.isArray(e);for(const a in e)a in i||r.push({type:"CREATE",path:[o?+a:a],value:e[a]});return r}class pk{past=[];future=[];lastState=null;maxSize;constructor(e={}){this.maxSize=e.maxSize||50}projectToHistoryState(e){const t={},s=JSON.parse(JSON.stringify(e.tracks||[]));return e.clips.forEach(r=>{r.id&&(t[r.id]=JSON.parse(JSON.stringify(r)))}),{clips:t,tracks:s,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))),s=Wx(this.lastState,t);s.length!==0&&(this.past.push(s),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 s=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),r=this.applyPatches(s,t,!0);return this.future.push(t),this.lastState=r,{patches:t,state:r}}redo(e){const t=this.future.pop();if(!t)return null;const s=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),r=this.applyPatches(s,t,!1);return this.past.push(t),this.lastState=r,{patches:t,state:r}}applyPatches(e,t,s){const r=JSON.parse(JSON.stringify(e)),n=s?[...t].reverse():t;for(const o of n){const{type:a,path:l}=o,c=o.value,h=o.oldValue;let u=r,d=!1;for(let p=0;p<l.length-1;p++){if(u[l[p]]===void 0||u[l[p]]===null){d=!0;break}u=u[l[p]]}if(d)continue;const f=l[l.length-1];if(s)switch(a){case"CREATE":Array.isArray(u)?u.splice(f,1):delete u[f];break;case"REMOVE":u[f]=h&&typeof h=="object"?JSON.parse(JSON.stringify(h)):h;break;case"CHANGE":u[f]=h&&typeof h=="object"?JSON.parse(JSON.stringify(h)):h;break}else switch(a){case"CREATE":u[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break;case"REMOVE":Array.isArray(u)?u.splice(f,1):delete u[f];break;case"CHANGE":u[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break}}return r}canUndo(){return this.past.length>0}canRedo(){return this.future.length>0}}class mk extends Zh{selection;transport;timeline;history;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;globalEffects=new Map;activeGlobalEffect=null;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 hk(this),this.transport=new uk(this),this.timeline=new dk(this),this.history=new pk,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,s){let r=e;for(let n=0;n<t.length-1;n++){const o=t[n];r[o]||(r[o]=typeof t[n+1]=="number"?[]:{}),r=r[o]}r[t[t.length-1]]=s}async applyHistoryPatches(e,t,s){const r=new Map,n=new Map,o=new Set;for(const a of e){const{type:l,path:c}=a,h=a.value,u=a.oldValue;if(c[0]==="clips"){const d=c[1];s?l==="CREATE"?o.add(d):l==="REMOVE"?n.set(d,u):l==="CHANGE"&&(r.has(d)||r.set(d,{}),this.setPath(r.get(d),c.slice(2),u)):l==="CREATE"?n.set(d,h):l==="REMOVE"?o.add(d):l==="CHANGE"&&(r.has(d)||r.set(d,{}),this.setPath(r.get(d),c.slice(2),h))}else c[0]==="settings"&&(s?this.setPath(this.opts,c.slice(1),u):this.setPath(this.opts,c.slice(1),h))}for(const a of o){const l=this.timeline.getClipById(a);l&&await this.removeClip(l)}for(const[a,l]of n){let c=this.clipCache.get(a);c||(c=await Ki(l),this.clipCache.set(a,c));let h;for(const u of t.tracks)if(u.clipIds.includes(a)){h=u.id;break}await this.addClip(c,{trackId:h})}for(const[a,l]of r)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[r,n]of this.spriteRenderers)if(r.id===e){const o=n.getRoot();o&&o.parent&&o.parent.removeChild(o),n.destroy(),this.spriteRenderers.delete(r);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[r,n]of this.videoSprites)if(r.id===e){n.parent&&n.parent.removeChild(n),n.destroy(),this.videoSprites.delete(r);break}for(const[r]of this.clipListeners)if(r.id===e){this.clipListeners.delete(r);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 Lu,s=e.parentElement||window;await t.init({canvas:e,resizeTo:s,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 re,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new _e,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new re,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new _e,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 re,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new re,this.clipsNormalContainer.label="ClipsNormal",this.clipsNormalContainer.zIndex=10,this.clipsNormalContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsNormalContainer),this.transFromTexture=Ge.create({width:this.opts.width,height:this.opts.height}),this.transToTexture=Ge.create({width:this.opts.width,height:this.opts.height}),this.transBgGraphics=new _e,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}updateDimensions(e,t){this.opts.width=e,this.opts.height=t,this.artboardBg&&this.artboardBg.clear().rect(0,0,e,t).fill({color:3355443}),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.updateArtboardLayout()};updateArtboardLayout(){if(!this.pixiApp||!this.artboard)return;const e=this.pixiApp.canvas.width,t=this.pixiApp.canvas.height,s=this.opts.width,r=this.opts.height,n=this.pixiApp.canvas.parentElement?.clientWidth||e,o=this.pixiApp.canvas.parentElement?.clientHeight||t,a=this.opts.spacing||0,l=Math.max(0,n-a*2),c=Math.max(0,o-a*2),h=l/s,u=c/r,d=Math.min(h,u);this.artboard.scale.set(d),this.artboard.x=(n-s*d)/2,this.artboard.y=(o-r*d)/2}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,s,r){return this.timeline.addTransition(e,t,s,r)}findTrackIdByClipId(e){return this.timeline.findTrackIdByClipId(e)}async addClip(e,t){(Array.isArray(e)?e:[e]).forEach(r=>this.clipCache.set(r.id,r)),this.beginHistoryGroup();try{return await this.timeline.addClip(e,t)}finally{this.endHistoryGroup()}}addTrack(e){return this.timeline.addTrack(e)}async setTracks(e){return this.timeline.setTracks(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 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)}setupSpriteInteractivity(e){this.selection.setupSpriteInteractivity(e)}async removeClip(e){this.beginHistoryGroup();try{return this.clipCache.set(e.id,e),this.timeline.removeClip(e,{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(s=>this.timeline.getClipById(s)).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.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)}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=M.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,s=this.tracks.length;for(const n of this.clips){const o=this.getTrackIndex(n.id);if(o!==-1){const a=(s-o)*10;n.zIndex=a;const l=this.spriteRenderers.get(n);if(l){const c=l.getRoot();c&&(c.zIndex=a)}}}const r=[...this.clips].sort((n,o)=>n.zIndex-o.zIndex);for(const n of r){if(e<n.display.from){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}if(n.display.to>0&&e>=n.display.to){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}const o=e-n.display.from,a=o*n.playbackRate;n.animate(a);const l=await n.ready,c=n.duration||l.duration;if(c>0&&o>=c){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}const h=this.playbackElements.get(n),u=n.type==="Video"||n.type==="Image",d=n.transition?n.transition.start:0,f=n.transition?n.transition.end:0,p=u&&n.transition&&e>=d&&e<f;if(h!=null&&this.isPlaybackCapable(n)){const m=o/1e6;if(n.syncPlayback(h.element,this.isPlaying,m),n.type==="Video"&&this.isPlaybackCapable(n)){const _=this.videoSprites.get(n);if(_!=null){const x=n.meta.duration/1e6;if(this.spriteRenderers.has(n))_.visible=!1;else if(_.visible=!p&&m>=0&&m<x,_.visible&&tM(n,_),!p)continue}}else continue}if(p){this.transFromTexture||(this.transFromTexture=Ge.create({width:this.opts.width,height:this.opts.height})),this.transToTexture||(this.transToTexture=Ge.create({width:this.opts.width,height:this.opts.height})),this.transBgGraphics||(this.transBgGraphics=new _e,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}));const m=this.getClipById(n?.transition?.fromClipId),_=this.getClipById(n?.transition?.toClipId);let x=null,y=null;if(m){const v=Math.max(0,e-m.display.from),{video:T}=await m.getFrame(v);T instanceof HTMLVideoElement?x=this.getVideoTexture(T):x=T,x&&(this.lastFromFrame=x)}if(_){const v=Math.max(0,e-_.display.from),{video:T}=await _.getFrame(v);T instanceof HTMLVideoElement?y=this.getVideoTexture(T):y=T,y&&(this.lastToFrame=y)}if(x||(x=this.lastFromFrame),y||(y=this.lastToFrame),!x||!y)continue;if(x&&y&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const v=(e-d)/n?.transition?.duration;m&&x&&this.renderClipToTransitionTexture(m,x,this.transFromTexture),_&&y&&this.renderClipToTransitionTexture(_,y,this.transToTexture);let T=this.transitionRenderers.get(n.id);if(!T)try{T=nf({name:n?.transition?.name,renderer:this.pixiApp.renderer}),this.transitionRenderers.set(n.id,T)}catch(S){console.error("[Studio] Failed to create transition renderer:",S)}if(T){const S=T.render({width:this.opts.width,height:this.opts.height,from:this.transFromTexture,to:this.transToTexture,progress:v});let w=this.transitionSprites.get(n.id);w||(w=new Ue,w.label=`TransitionSprite_${n.id}`,this.transitionSprites.set(n.id,w),this.clipsNormalContainer&&this.clipsNormalContainer.addChild(w)),w.texture=S,w.visible=!0,w.x=0,w.y=0,w.width=this.opts.width,w.height=this.opts.height,w.anchor.set(0,0),w.zIndex=n.zIndex,t.add(n.id);const E=this.spriteRenderers.get(n);E?.getRoot()&&(E.getRoot().visible=!1);const P=this.videoSprites.get(n);if(P&&(P.visible=!1),m){const C=this.spriteRenderers.get(m);C?.getRoot()&&(C.getRoot().visible=!1);const A=this.videoSprites.get(m);A&&(A.visible=!1)}continue}}}const g=this.spriteRenderers.get(n);if(g!=null){const m=this.selectedClips.has(n);if(n.type!=="Text"&&n.type!=="Caption"&&typeof n.getTexture=="function"&&n.getTexture()!=null){const x=n.getTexture();if(x!=null){await g.updateFrame(x),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}if(n.type==="Text"){const x=n;this.pixiApp?.renderer&&typeof x.setRenderer=="function"&&x.setRenderer(this.pixiApp.renderer);const y=await x.getTexture();if(y!=null){await g.updateFrame(y),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}if(n.type==="Caption"){n.updateState(o);const x=n;this.pixiApp?.renderer&&typeof x.setRenderer=="function"&&x.setRenderer(this.pixiApp.renderer);const y=await x.getTexture();if(y!=null){await g.updateFrame(y),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}const{video:_}=await n.getFrame(o);await g.updateFrame(_),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n)}}if(this.activeGlobalEffect&&this.clipsNormalContainer&&this.clipsEffectContainer){const{startTime:n,duration:o}=this.activeGlobalEffect,a=e-n,l=Math.min(Math.max(a/o,0),1);if(l>0&&l<1){try{for(const h of this.clips)this.moveClipToEffectContainer(h,!1);const c=this.clips.some(h=>h.id===this.activeGlobalEffect.id&&h instanceof ct);for(const h of this.clips){let u=!1;if(c){const d=this.activeGlobalEffect.trackIndex??-1,f=this.getTrackIndex(h.id);u=h.id!==this.activeGlobalEffect.id&&!(h instanceof ct)&&f>d}else{const d=h.effects;u=Array.isArray(d)&&d.some(f=>f&&f.id===this.activeGlobalEffect.id)}u&&this.moveClipToEffectContainer(h,!0)}}catch(c){console.warn("Failed to reparent clips for effect; falling back to full-scene render",c)}this.clipsNormalContainer.visible=!0,await this.applyGlobalEffectIfNeeded(e)}else{for(const c of this.clips)try{this.moveClipToEffectContainer(c,!1)}catch{}this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}}else if(this.clipsNormalContainer){for(const n of this.clips)try{this.moveClipToEffectContainer(n,!1)}catch{}this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}for(const[n,o]of this.transitionSprites.entries())t.has(n)||(o.visible=!1);this.pixiApp!=null&&this.pixiApp.render()}moveClipToEffectContainer(e,t=!0){if(!this.clipsNormalContainer||!this.clipsEffectContainer)return;const s=t?this.clipsEffectContainer:this.clipsNormalContainer,r=this.spriteRenderers.get(e);if(r){const o=r.getRoot();if(o&&o.parent!==s){try{o.parent&&o.parent.removeChild&&o.parent.removeChild(o)}catch(a){console.warn("moveClipToEffectContainer: could not remove root from parent",a)}s.addChild(o)}}const n=this.transitionSprites.get(e.id);if(n&&n.parent!==s){try{n.parent&&n.parent.removeChild&&n.parent.removeChild(n)}catch(o){console.warn("moveClipToEffectContainer: could not remove transSprite from parent",o)}s.addChild(n)}}applyGlobalEffect(e,t,s){const r=t.id||`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={id:r,key:e,startTime:t.startTime,duration:t.duration??1e6};for(const o of s)o instanceof xi&&o.addEffect(n),o instanceof Me&&o.addEffect(n),o instanceof gt&&o.addEffect(n),o instanceof ei&&o.addEffect(n);return this.globalEffects.set(r,n),r}getTrackIndex(e){return this.tracks.findIndex(t=>t.clipIds.includes(e))}async getTransitionFromFrame(e,t){let s=null;if(e.transition?.prevClipId&&(s=this.clips.find(a=>a.id===e.transition.prevClipId)||null),s||(s=this.getPreviousClipOnTrack(e)),!s)return null;const r=s.duration>0?s.duration:0,n=Math.max(0,Math.min(t-s.display.from,r)),{video:o}=await s.getFrame(n);return o}getPreviousClipOnTrack(e){const t=this.getTrackIndex(e.id);return t===-1?null:this.clips.filter(s=>s.id!==e.id&&this.getTrackIndex(s.id)===t&&s.display.from<e.display.from&&(s instanceof Me||s instanceof xi)).sort((s,r)=>r.display.to-s.display.to)[0]||null}renderClipToTransitionTexture(e,t,s){if(!this.pixiApp||!this.transBgGraphics)return;const r=this.pixiApp.renderer.background.alpha;this.pixiApp.renderer.background.alpha=0,this.pixiApp.renderer.render({container:this.transBgGraphics,target:s,clear:!0}),this.pixiApp.renderer.background.alpha=r;const n=new Ue(t instanceof M?t:M.from(t));n.x=e.center.x,n.y=e.center.y,n.anchor.set(.5,.5);const o=n.texture.width||1,a=n.texture.height||1,l=e.width&&e.width!==0?Math.abs(e.width)/o:1,c=e.height&&e.height!==0?Math.abs(e.height)/a:1;e.flip==="horizontal"?(n.scale.x=-l,n.scale.y=c):e.flip==="vertical"?(n.scale.x=l,n.scale.y=-c):(n.scale.x=l,n.scale.y=c),n.rotation=(e.flip==null?1:-1)*e.angle,n.alpha=e.opacity,this.pixiApp.renderer.render({container:n,target:s,clear:!1}),t instanceof M||n.texture.destroy(!0),n.destroy()}removeGlobalEffect(e){this.globalEffects.delete(e)}clearGlobalEffects(){this.globalEffects.clear()}updateActiveGlobalEffect(e){let t=null;for(const s of this.clips)if(s instanceof ct&&e>=s.display.from&&(s.display.to===0||e<s.display.to)){t={id:s.id,key:s.effect.key,startTime:s.display.from,duration:s.duration>0?s.duration:s.display.to-s.display.from,trackIndex:this.getTrackIndex(s.id)};break}if(!t)for(const s of this.globalEffects.values()){const r=s.startTime+s.duration;if(e>=s.startTime&&e<r){t={id:s.id,key:s.key,startTime:s.startTime,duration:s.duration,trackIndex:-1};break}}this.activeGlobalEffect=t}async applyGlobalEffectIfNeeded(e){if(this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null),!this.activeGlobalEffect||!this.pixiApp||!this.clipContainer||!this.artboard||!this.clipsNormalContainer||!this.clipsEffectContainer)return;const{key:t,startTime:s,duration:r}=this.activeGlobalEffect,n=e-s,o=Math.min(Math.max(n/r,0),1);if(o<=0||o>=1)return;this.clipsEffectContainer.visible=!0;let a=this.effectFilters.get(t);if(!a)try{if(a=sf({name:t.toLowerCase(),renderer:this.pixiApp.renderer}),a)this.effectFilters.set(t,a);else return}catch(f){console.error(f);return}const l=this.opts.width,c=this.opts.height,h=Ge.create({width:l,height:c});this.pixiApp.renderer.render({container:this.clipsEffectContainer,target:h,clear:!0}),this.clipsEffectContainer.visible=!1;const u=a.render({canvasTexture:h,progress:o,width:l,height:c}),d=new Ue(u);d.x=0,d.y=0,d.width=l,d.height=c,d.scale.set(1),d.zIndex=5,this.clipContainer.addChild(d),this.currentGlobalEffectSprite=d,h.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)}}V.add(VS),V.mixin(re,$S),V.add(lg),V.add(cg),V.add(g0),V.mixin(re,xI),V.add(m0),V.add(sx),V.add(od),V.add(ox),V.add(ux),V.add(dx),V.add(wx),V.add(Tx),V.add(gx),V.add(vx),V.add(xx),V.add(mx),V.add(px),V.add(w0),V.add(b0);const gk=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),_k=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));se.Audio=Ke,se.Caption=ei,se.Compositor=rk,se.DEFAULT_AUDIO_CONF=le,se.Effect=ct,se.GL_EFFECT_OPTIONS=eM,se.GL_TRANSITION_OPTIONS=ik,se.Image=xi,se.Log=K,se.MP4Clip=Me,se.Placeholder=mn,se.Studio=mk,se.Text=gt,se.Transition=Lt,se.Video=Me,se.clipToJSON=Ys,se.createChromakey=S1,se.fastConcatMP4=Ux,se.fixFMP4Duration=BR,se.fontManager=Hx,se.jsonToClip=Ki,se.makeEffect=sf,se.makeTransition=nf,se.mixinMP4AndAudio=GR,se.renderTxt2ImgBitmap=M1,Object.defineProperty(se,Symbol.toStringTag,{value:"Module"})}));
7791
+ `,tk={radialSwipe:{label:"Radial Swipe",fragment:aM}},Zi={...ji.reduce((i,e)=>(i[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:`transition: ${e.name}`},i),{}),...tk},ik=Object.entries(Zi).map(([i,e])=>({key:i,label:e.label,previewStatic:`https://cdn.subgen.co/previews/static/transition_${i}_static.webp`,previewDynamic:`https://cdn.subgen.co/previews/dynamic/transition_${i}_dynamic.webp`}));function nf({name:i,renderer:e}){let t=ji.find(N=>N.name===i);if(!t){const N=Object.keys(Zi).find(q=>q.toLowerCase()===i.toLowerCase());N&&(t=Zi[N])}if(t||(t=ji.find(N=>N.name.toLowerCase()===i.toLowerCase())),!t){const N=[i,i.toLowerCase(),i.charAt(0).toUpperCase()+i.slice(1).toLowerCase(),i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),i.replace(/_/g,"")];for(const q of N){if(t=ji.find(Ie=>Ie.name.toLowerCase()===q.toLowerCase()),t)break;const me=Object.keys(Zi).find(Ie=>Ie.toLowerCase()===q.toLowerCase());if(me){t=Zi[me];break}}}if(!t){const N=ji.length,q=ji.slice(0,5).map(Ie=>Ie.name).join(", "),me=Object.keys(Zi).slice(0,3).join(", ");throw console.error(`Transition not found: "${i}". Available in gl-transitions (${N} total):`,q+"..."),console.error("Available locally:",me+"..."),new Error(`Transition "${i}" not found in gl-transitions library or local definitions`)}const s=new Ue(M.WHITE),r=Ge.create({width:e.width,height:e.height}),n=new Ct({}),o=new Ct({}),a=t.name==="displacement"||i.toLowerCase()==="displacement"||t.label==="displacement",l=a?new Ct({}):void 0;let c=null;if(a){c=document.createElement("canvas"),c.width=256,c.height=256;const N=c.getContext("2d");if(N){const q=N.createImageData(256,256);for(let me=0;me<q.data.length;me+=4){const Ie=Math.random();q.data[me]=Ie*255,q.data[me+1]=Ie*255,q.data[me+2]=Ie*255,q.data[me+3]=255}N.putImageData(q,0,0)}}let h=t.glsl||t.fragment;if(!h)throw new Error(`Transition "${i}" has no glsl or fragment code`);let u={...de.basics,...de.custom(t)};Object.entries(u).forEach(([,N])=>{N.type==="int<f32>"&&(N.type="i32",typeof N.value=="number"&&(N.value=Math.trunc(N.value))),N.type==="ivec2<f32>"&&(N.type="vec2<f32>")});const d=t.name==="GridFlip"||i.toLowerCase()==="gridflip"||t.label==="gridflip",f=t.name==="circle"||i.toLowerCase()==="circle"||t.label==="circle",p=t.name==="directional"||i.toLowerCase()==="directional"||t.label==="directional",g=t.name==="UndulatingBurnOut"||i.toLowerCase()==="undulatingburnout"||t.label==="undulatingBurnOut",m=t.name==="SquaresWire"||i.toLowerCase()==="squareswire"||t.label==="squaresWire",_=t.name==="rotate_scale_fade"||i.toLowerCase()==="rotatescalefade"||t.label==="rotateScaleFade",x=t.name==="RandomSquares"||i.toLowerCase()==="randomsquares"||t.label==="randomSquares",y=t.name==="polar_function"||i.toLowerCase()==="polar_function"||t.label==="polar_function",v=t.name==="pixelate"||i.toLowerCase()==="pixelate"||t.label==="pixelate",T=t.name==="perlin"||i.toLowerCase()==="perlin"||t.label==="perlin",S=t.name==="luma"||i.toLowerCase()==="luma"||t.label==="luma",w=t.name==="luminance_melt"||i.toLowerCase()==="luminance_melt"||i.toLowerCase()==="luminancemelt"||t.label==="luminance_melt",E=t.name==="hexagonalize"||i.toLowerCase()==="hexagonalize"||t.label==="hexagonalize",P=t.name==="heart"||i.toLowerCase()==="heart"||t.label==="heart",C=t.name==="displacement"||i.toLowerCase()==="displacement"||t.label==="displacement",A=t.name==="directionalwipe"||i.toLowerCase()==="directionalwipe"||i.toLowerCase()==="directional_wipe"||t.label==="directionalwipe",U=t.name==="directionalwarp"||i.toLowerCase()==="directionalwarp"||i.toLowerCase()==="directional_warp"||t.label==="directionalwarp",D=t.name==="crosshatch"||i.toLowerCase()==="crosshatch"||t.label==="crosshatch",$=t.name==="circleopen"||i.toLowerCase()==="circleopen"||i.toLowerCase()==="circle_open"||t.label==="circleopen",pe=t.name==="cannabisleaf"||i.toLowerCase()==="cannabisleaf"||i.toLowerCase()==="cannabis_leaf"||t.label==="cannabisleaf",k=t.name==="StereoViewer"||i.toLowerCase()==="stereoviewer"||i.toLowerCase()==="stereo_viewer"||t.label==="StereoViewer",F=t.name==="GlitchDisplace"||i.toLowerCase()==="glitchDisplace"||t.label==="GlitchDisplace",ne=t.name==="CrossZoom"||i.toLowerCase()==="crosszoom"||t.label==="CrossZoom",G=t.name==="CrazyParametricFun"||i.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",ie=t.name==="BowTieHorizontal"||i.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",we=t.name==="PolkaDotsCurtain"||i.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",ce=t.name==="Pixelize"||i.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(h=lM,u={...de.basics,...cM}),f&&(h=hM,u={...de.basics,...zx}),p&&(h=uM,u={...de.basics,...dM}),g&&(h=fM,u={...de.basics,...pM}),m&&(h=mM,u={...de.basics,...gM}),_&&(h=_M,u={...de.basics,...xM}),x&&(h=yM,u={...de.basics,...vM}),y&&(h=bM,u={...de.basics,...TM}),v&&(h=Ox,u={...de.basics,...Dx}),T&&(h=CM,u={...de.basics,...AM}),S&&(h=EM,u={...de.basics,...IM}),w&&(h=PM,u={...de.basics,...RM}),E&&(h=MM,u={...de.basics,...kM}),P&&(h=FM,u={...de.basics,...BM}),C&&(h=UM,u={...de.basics,...OM}),A&&(h=DM,u={...de.basics,...GM}),U&&(h=zM,u={...de.basics,...NM}),D&&(h=LM,u={...de.basics,...HM}),$&&(h=WM,u={...de.basics,...zx}),pe&&(h=VM,u={...de.basics,...$M}),k&&(h=XM,u={...de.basics,...YM}),F&&(h=qM),ne&&(h=KM,u={...de.basics,...jM}),G&&(h=ZM,u={...de.basics,...JM}),ie&&(h=QM),we&&(h=ek),ce&&(h=wM,u={...de.basics,...SM});const Ce={from:n,to:o,uniforms:u};a&&l&&(Ce.displacementMap=l,c&&(l.resource=c,l.update()));const Oe=new Gi({glProgram:new At({vertex:rM,fragment:oM(h)}),resources:Ce});return s.filters=[Oe],{render({width:N,height:q,from:me,to:Ie,progress:Qi}){if((s.width!==N||s.height!==q)&&(s.setSize({width:N,height:q}),r.resize(N,q)),me instanceof M?Oe.resources.from=me.source:(n.resource=me,n.update(),Oe.resources.from=n),Ie instanceof M?Oe.resources.to=Ie.source:(o.resource=Ie,o.update(),Oe.resources.to=o),a&&l&&c){if(c.width!==N||c.height!==q){c.width=N,c.height=q;const ti=c.getContext("2d");if(ti){const Et=ti.createImageData(N,q);for(let qe=0;qe<Et.data.length;qe+=4){const _t=Math.random();Et.data[qe]=_t*255,Et.data[qe+1]=_t*255,Et.data[qe+2]=_t*255,Et.data[qe+3]=255}ti.putImageData(Et,0,0)}}l.resource=c,l.update()}return Oe.resources.uniforms.uniforms.progress=Qi,e.render({container:s,target:r,clear:!1,width:N,height:q}),r},destroy(){r.destroy(),s.destroy({children:!0})}}}let sk=0;async function Nx(i){i()>50&&(await jh(15),await Nx(i))}class rk extends Zh{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 Bp()).codec,sampleRate:le.sampleRate,numberOfChannels:le.channelCount})).supported)??!1}logger=K.create(`id:${sk++},`);destroyed=!1;sprites=[];canvas;pixiApp=null;stopOutput=null;opts;hasVideoTrack;constructor(e={}){super();const{width:t=0,height:s=0}=e;this.canvas=new OffscreenCanvas(t,s),this.opts=Object.assign({bgColor:"#000",width:0,height:0,videoCodec:"avc1.42E032",audio:!0,bitrate:5e6,fps:30,metaDataTags:null},e),this.hasVideoTrack=t*s>0,Bp().catch(r=>{this.logger.warn("Failed to detect audio codec:",r)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new Lu,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 s=this.pixiApp;s.ticker&&typeof s.ticker.stop=="function"&&s.ticker.stop()}catch{}}async addSprite(e,t={}){const s={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",s);const r=await e.clone();this.pixiApp!=null&&this.pixiApp.renderer!=null&&typeof r.setRenderer=="function"&&r.setRenderer(this.pixiApp.renderer),this.logger.info("Compositor add clip ready"),this.sprites.push(Object.assign(r,{main:t.main??!1,expired:!1})),this.sprites.sort((n,o)=>n.zIndex-o.zIndex)}initMuxer(e){const{fps:t,width:s,height:r,videoCodec:n,bitrate:o,audio:a,metaDataTags:l}=this.opts,c=this.sprites.some(d=>d.width>0&&d.height>0),h=this.hasVideoTrack&&c;return Bw({video:h?{width:s,height:r,expectFPS:t,codec:n,bitrate:o,__unsafe_hardwareAcceleration__:this.opts.__unsafe_hardwareAcceleration__}:null,audio:a===!1?null:{codec:le.codecType,sampleRate:le.sampleRate,channelCount:le.channelCount},duration:e,metaDataTags:l})}output(e={}){if(this.sprites.length===0)throw Error("No sprite added");const t=this.sprites.find(u=>u.main),r=this.sprites.map(u=>u.display.from+u.duration).filter(u=>u!==1/0),n=e.maxTime??(t!=null?t.display.from+t.duration:r.length>0?Math.max(...r):1/0);if(n===1/0||n<=0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of Image, Audio");n===-1&&this.logger.warn("Unable to determine the end time, process value don't update"),this.logger.info(`start combinate video, maxTime:${n}`);const o=this.initMuxer(n);let a=performance.now();const l=this.runEncoding(o,n,{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),h(u),this.destroy()}});this.stopOutput=()=>{l(),o.close(),h()};const{stream:c,stop:h}=Fx(o.mp4file,500,this.destroy);return c}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:s,onEnded:r,onError:n}){let o=0;const a={aborted:!1};let l=null,c=null;const h=async()=>{const{fps:f,bgColor:p,audio:g}=this.opts,m=Math.round(1e6/f),_=this.sprites.some(v=>v.width>0&&v.height>0);c=nk({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=ok({muxer:e,canvas:this.canvas,outputAudio:g,hasVideoTrack:this.hasVideoTrack&&_,timeSlice:m,fps:f});let y=0;for(;;){if(l!=null)return;if(a.aborted||t!==-1&&y>t||this.sprites.length===0){u(),await r();return}o=y/t;const{audios:v,mainSprDone:T,hasVideo:S}=await c.render(y);if(T){u(),await r();return}if(a.aborted)return;this.hasVideoTrack&&S&&await new Promise(w=>requestAnimationFrame(w)),x(y,v,S),y+=m,await Nx(e.getEncodeQueueSize)}},u=()=>{a.aborted||(a.aborted=!0,clearInterval(d),c?.cleanup(),this.sprites.forEach(f=>{f.destroy()}))};h().catch(f=>{l=f,this.logger.error(f),u(),n(f)});const d=setInterval(()=>{s(o)},500);return u}exportToJSON(){const e=this.sprites.map(s=>Ys(s,s.main)),t=[];return this.sprites.forEach(s=>{if(s.transition){const r=this.sprites.filter(n=>n.id!==s.id&&n.zIndex===s.zIndex&&n.display.from<s.display.from&&(n instanceof Me||n instanceof xi)).sort((n,o)=>o.display.to-n.display.to)[0];r&&t.push({key:s.transition.name,duration:s.transition.duration,clips:[r.id,s.id]})}}),{clips:e,settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor,videoCodec:this.opts.videoCodec,bitrate:this.opts.bitrate,audio:this.opts.audio,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.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.metaDataTags!==void 0&&(this.opts.metaDataTags=e.settings.metaDataTags));for(const t of e.clips){const s=await Ki(t);if(await this.addSprite(s,{main:t.main||!1}),t.type==="Transition"){const r=t.toClipId,n=this.sprites.find(o=>o.id===r);n?n.transition={name:t.transitionEffect.key,duration:t.duration,prevClipId:t.fromClipId||""}:console.warn(`[Compositor] Could not find target clip ${r} for transition ${t.transitionEffect.key}`)}}}}function nk(i){const{pixiApp:e,sprites:t,aborter:s}=i,r=e!=null,n=new Map,o=new Map,a=new Map,l=Ge.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),c=Ge.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),h=new _e().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),u=new Map,d=T=>t.filter(S=>S.id!==T.id&&S.zIndex===T.zIndex&&S.display.from<T.display.from&&(S instanceof Me||S instanceof xi)).sort((S,w)=>w.display.to-S.display.to)[0]||null,f=async(T,S,w)=>{let E=null;if(T.transition?.prevClipId&&(E=t.find(U=>U.id===T.transition.prevClipId)||null),E||(E=d(T)),!E)return null;const P=E.duration>0?E.duration:0,C=Math.max(0,Math.min(S-E.display.from,P)),{video:A}=await w(E,C);return A},p=(T,S,w)=>{if(!e)return;e.renderer.render({container:h,target:w,clear:!0});const E=new Ue(S instanceof M?S:M.from(S));E.x=T.center.x,E.y=T.center.y,E.anchor.set(.5,.5);const P=E.texture.width||1,C=E.texture.height||1,A=T.width&&T.width!==0?Math.abs(T.width)/P:1,U=T.height&&T.height!==0?Math.abs(T.height)/C:1;T.flip==="horizontal"?(E.scale.x=-A,E.scale.y=U):T.flip==="vertical"?(E.scale.x=A,E.scale.y=-U):(E.scale.x=A,E.scale.y=U),E.rotation=(T.flip==null?1:-1)*T.angle,E.alpha=T.opacity;const D=T.style||{},$=D.borderRadius||0;let pe=null;$>0&&(pe=new _e,pe.roundRect(-P/2,-C/2,P,C,Math.min($,P/2,C/2)),pe.fill({color:16777215,alpha:1}),E.addChild(pe),E.mask=pe);const k=D.stroke;let F=null;if(k&&k.width>0){F=new _e;const ie=Te(k.color)??16777215,we=k.width;if(F.setStrokeStyle({width:we,color:ie,alignment:1}),$>0){const ce=Math.min($,P/2,C/2);F.roundRect(-P/2,-C/2,P,C,ce)}else F.rect(-P/2,-C/2,P,C);F.stroke(),E.addChild(F)}const ne=D.dropShadow;let G=null;if(ne&&(ne.blur>0||ne.distance>0)){G=new _e;const ie=Te(ne.color)??0,we=ne.alpha??.5,ce=ne.distance??0,Ce=ne.angle??0,Oe=Math.cos(Ce)*ce,N=Math.sin(Ce)*ce;if($>0){const q=Math.min($,P/2,C/2);G.roundRect(-P/2+Oe,-C/2+N,P,C,q)}else G.rect(-P/2+Oe,-C/2+N,P,C);G.fill({color:ie,alpha:we}),E.addChildAt(G,0)}e.renderer.render({container:E,target:w,clear:!1}),S instanceof M||E.texture.destroy(!0),F&&F.destroy(),pe&&pe.destroy(),G&&G.destroy(),E.destroy()};let g=null,m=null,_=null;r&&e!=null&&(g=new re,m=new re,_=new re,m.sortableChildren=!0,_.sortableChildren=!0,e.stage.addChild(m),e.stage.addChild(_),g.visible=!1,e.stage.addChild(g));const x=[...t].sort((T,S)=>T.zIndex-S.zIndex);return{render:async T=>{const S=[];let w=!1,E=!1;const P=new Map,C=async(A,U)=>{const D=`${A.id}_${U}`;if(P.has(D))return P.get(D);const $=await A.getFrame(U);return P.set(D,$),$};for(const A of a.values())A.visible=!1;for(const A of x){if(s.aborted)break;if(T<A.display.from||A.expired){if(r&&e!=null){const F=n.get(A);F&&await F.updateFrame(null)}continue}const U=T-A.display.from,D=U*A.playbackRate;A.animate(D);const{video:$,audio:pe,done:k}=await C(A,U);if(S.push(pe),r&&e!=null&&m!=null){if((A instanceof Me||A instanceof xi)&&A.transition&&U>=0&&U<=A.transition.duration){const G=await f(A,T,C),ie=$;if(G&&ie){const we=U/A.transition.duration,ce=d(A);ce?p(ce,G,l):e.renderer.render({container:h,target:l,clear:!0}),p(A,ie,c);let Ce=o.get(A.id);Ce||(Ce=nf({name:A.transition.name,renderer:e.renderer}),o.set(A.id,Ce));const Oe=Ce.render({width:e.renderer.width,height:e.renderer.height,from:l,to:c,progress:we});let N=a.get(A.id);N||(N=new Ue,N.label=`TransitionSprite_${A.id}`,a.set(A.id,N),m.addChild(N)),N.texture=Oe,N.visible=!0,N.x=0,N.y=0,N.width=e.renderer.width,N.height=e.renderer.height,N.anchor.set(0,0),N.zIndex=A.zIndex,E=!0;const q=n.get(A);if(q){const me=q.getRoot();me&&(me.visible=!1)}if(ce){const me=n.get(ce);if(me){const Ie=me.getRoot();Ie&&(Ie.visible=!1)}}continue}}let ne=n.get(A);ne==null&&$!=null&&(ne=new gn(e,A,m),n.set(A,ne)),ne!=null&&($!=null?(E=!0,await ne.updateFrame($)):await ne.updateFrame(null)),ne?.updateTransforms()}if(A.duration>0&&T>A.display.from+A.duration||k){if(A.main&&(w=!0),A.expired=!0,r){const F=n.get(A);if(F!=null){const ne=F.getRoot();ne&&(ne.visible=!1)}}}else if(r){const F=n.get(A);F?.updateTransforms()}}if(r&&e!=null&&g!=null&&m!=null&&_!=null){let A=null;for(const U of t)if(U instanceof ct&&T>=U.display.from&&T<U.display.from+U.duration){A={id:U.id,key:U.effect.key,startTime:U.display.from,duration:U.duration};break}if(!A)for(const U of t){if(U.effects&&U.effects.length>0){for(const D of U.effects)if(T>=D.startTime&&T<D.startTime+D.duration){A=D;break}}if(A)break}_.removeChildren();for(const U of n.values()){const D=U.getRoot();D&&D.parent!==m&&(D.parent&&D.parent.removeChild(D),m.addChild(D))}if(A){const{key:U,startTime:D,duration:$,id:pe}=A,k=T-D,F=$>0?Math.min(Math.max(k/$,0),1):0,ne=t.some(G=>G.id===pe&&G instanceof ct);for(const G of t){let ie=!1;if(ne?ie=G.id!==pe&&!(G instanceof ct):ie=!!G.effects&&G.effects.some(we=>we.id===pe),ie){const we=n.get(G);if(we){const ce=we.getRoot();ce&&(ce.parent&&ce.parent.removeChild(ce),g.addChild(ce))}}}if(g.children.length>0){let G=u.get(pe);if(!G)try{const ie=sf({name:U,renderer:e.renderer});ie&&ie.filter&&(G={filter:ie.filter,render:ie.render},u.set(pe,G))}catch(ie){console.warn("Failed to create effect",U,ie)}if(G){const{filter:ie,render:we}=G;ie.resources&&ie.resources.effectUniforms&&(ie.resources.effectUniforms.uniforms.uTime=F);const ce=e.renderer.width,Ce=e.renderer.height,Oe=Ge.create({width:ce,height:Ce});if(g.visible=!0,e.renderer.render({container:g,target:Oe,clear:!0}),g.visible=!1,we){const N=we({canvasTexture:Oe,progress:F,width:ce,height:Ce}),q=new Ue(N);q.width=ce,q.height=Ce,_.addChild(q)}}}}}return r&&e!=null&&e.render(),{audios:S,mainSprDone:w,hasVideo:E}},cleanup:()=>{l&&l.destroy(!0),c&&c.destroy(!0),h&&h.destroy(!0);for(const T of a.values())T.destroy();a.clear(),o.clear(),g&&g.destroy({children:!0}),m&&m.destroy({children:!0}),_&&_.destroy({children:!0}),n.forEach(T=>{T.destroy()}),n.clear()}}}function ok(i){const{canvas:e,outputAudio:t,muxer:s,hasVideoTrack:r,timeSlice:n}=i;let o=0;const a=Math.floor(3*i.fps),l=ak(1024);return(c,h,u)=>{if(t!==!1)for(const d of l(c,h))s.encodeAudio(d);if(r&&u)try{const d=new VideoFrame(e,{duration:n,timestamp:c});s.encodeVideo(d,{keyFrame:o%a===0}),o+=1}catch(d){console.warn("Failed to create VideoFrame from canvas, skipping frame:",d)}}}function ak(i){const e=i*le.channelCount,t=new Float32Array(e*3);let s=0,r=0;const n=i/le.sampleRate*1e6,o=new Float32Array(e),a=l=>{let c=0;const h=Math.floor(s/e),u=[];for(let d=0;d<h;d++)u.push(new AudioData({timestamp:r,numberOfChannels:le.channelCount,numberOfFrames:i,sampleRate:le.sampleRate,format:"f32",data:t.subarray(c,c+e)})),c+=e,r+=n;for(t.set(t.subarray(c,s),0),s-=c;l-r>n;)u.push(new AudioData({timestamp:r,numberOfChannels:le.channelCount,numberOfFrames:i,sampleRate:le.sampleRate,format:"f32",data:o})),r+=n;return u};return(l,c)=>{const h=Math.max(...c.map(u=>u[0]?.length??0));for(let u=0;u<h;u++){let d=0,f=0;for(let p=0;p<c.length;p++){const g=c[p][0]?.[u]??0,m=c[p][1]?.[u]??g;d+=g,f+=m}t[s]=d,t[s+1]=f,s+=2}return a(l)}}class lk extends _e{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(e,t=1){const r=1.5*t;this.clear(),this.setStrokeStyle({width:r,color:165063}).rect(e.x,e.y,e.width,e.height).stroke(),this.hitArea=e}}class Ht extends _e{#e=!1;handle;cursor;callbacks;constructor(e,t,s){super(),this.handle=e,this.cursor=t,this.callbacks=s,this.eventMode="static",this.#a(),this.on("pointerdown",this.#i),this.on("globalpointermove",this.#r),this.on("pointerup",this.#l),this.on("pointerupoutside",this.#l)}#a(){this.clear();const e=165063;if(this.handle==="rot")this.circle(0,0,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-4),this.arc(0,0,4,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new Zr(0,0,24);else if(["ml","mr","mt","mb"].includes(this.handle)){const t=this.handle==="ml"||this.handle==="mr",s=t?6:24,r=t?24:6;this.roundRect(-s/2,-r/2,s,r,3),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new H(-15,-15,30,30)}else this.rect(-4,-4,8,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new H(-15,-15,30,30)}#i=e=>{this.#e=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,e.global),e.stopPropagation()};#r=e=>{this.#e&&(this.callbacks.updateDrag(this.handle,e.global),e.stopPropagation())};#l=e=>{this.#e&&(this.#e=!1,this.cursor="pointer",this.callbacks.endDrag(),e.stopPropagation())}}const Lx={delta:new O};class ck extends re{group;wireframe=new lk;selectionOutlines=new _e;isDragging=!1;lastPointer=new X;activeHandle=null;#e;#a=new Map;#i=new X;#r=0;#l=0;#c=new H;#s=new X;#h=new H;#t=[new X,new X,new X,new X];#n=1;#o=1;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static";const t={beginDrag:(s,r)=>this.#v(s,r),updateDrag:(s,r)=>this.#b(s,r),endDrag:()=>this.#m()};this.#e={tl:new Ht("tl","nwse-resize",t),tr:new Ht("tr","nesw-resize",t),bl:new Ht("bl","nesw-resize",t),br:new Ht("br","nwse-resize",t),ml:new Ht("ml","ew-resize",t),mr:new Ht("mr","ew-resize",t),mt:new Ht("mt","ns-resize",t),mb:new Ht("mb","ns-resize",t),rot:new Ht("rot","crosshair",{beginDrag:(s,r)=>this.#w(r),updateDrag:(s,r)=>this.#S(r),endDrag:()=>this.#m()})},this.addChild(this.selectionOutlines,this.wireframe,...Object.values(this.#e)),this.#_(),this.visible=!1,Ze.shared.addOnce(()=>{!this.destroyed&&this.parent&&(this.#u(),this.visible=!0)})}#_(){this.on("pointerdown",this.#x),this.on("pointerup",this.#p),this.on("pointerupoutside",this.#p),this.on("globalpointermove",this.#y)}#u(){if(this.group.length===1){const e=this.group[0];this.#r=e.rotation;const t=this.#f(e);let s,r;this.opts.clip?(s=this.opts.clip.width,r=this.opts.clip.height):(s=t.width,r=t.height);const n=e.toGlobal(new X(0,0));this.#i.set(n.x,n.y),this.#h.copyFrom(new H(-s/2,-r/2,s,r))}else{let e=1/0,t=1/0,s=-1/0,r=-1/0;if(this.parent)for(const c of this.group){const h=this.#f(c);this.#t[0].set(h.x,h.y),this.#t[1].set(h.x+h.width,h.y),this.#t[2].set(h.x+h.width,h.y+h.height),this.#t[3].set(h.x,h.y+h.height);for(const u of this.#t)c.toGlobal(u,u),this.toLocal(u,void 0,u),e=Math.min(e,u.x),t=Math.min(t,u.y),s=Math.max(s,u.x),r=Math.max(r,u.y)}const n=s-e,o=r-t,a=e+n/2,l=t+o/2;if(this.#h.copyFrom(new H(-n/2,-o/2,n,o)),this.parent){const c=this.toGlobal(new X(a,l));this.#i.set(c.x,c.y)}}this.#d()}#f(e){const t=e.children.filter(l=>l.label!=="ShadowContainer");if(t.length===0){const l=e.getLocalBounds();return new H(l.minX,l.minY,l.maxX-l.minX,l.maxY-l.minY)}const s=t.find(l=>l.label==="MainSprite");if(s){const l=s.getLocalBounds(),c=s.localTransform,h=c.apply(new X(l.x,l.y)),u=c.apply(new X(l.x+l.width,l.y)),d=c.apply(new X(l.x+l.width,l.y+l.height)),f=c.apply(new X(l.x,l.y+l.height)),p=Math.min(h.x,u.x,d.x,f.x),g=Math.max(h.x,u.x,d.x,f.x),m=Math.min(h.y,u.y,d.y,f.y),_=Math.max(h.y,u.y,d.y,f.y);return new H(p,m,g-p,_-m)}let r=1/0,n=1/0,o=-1/0,a=-1/0;for(const l of t){const c=l.getBounds(),h=e.toLocal(new X(c.minX,c.minY)),u=e.toLocal(new X(c.maxX,c.maxY));r=Math.min(r,h.x,u.x),n=Math.min(n,h.y,u.y),o=Math.max(o,h.x,u.x),a=Math.max(a,h.y,u.y)}return new H(r,n,o-r,a-n)}updateBounds(){this.#u()}#x=e=>{this.#u(),this.isDragging=!0,this.lastPointer.copyFrom(e.global),this.cursor="grabbing"};#p=()=>{this.isDragging&&this.emit("transformEnd"),this.isDragging=!1,this.activeHandle=null,this.cursor="default"};#y=e=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const t=this.parent.toLocal(this.lastPointer),s=this.parent.toLocal(e.global),r=s.x-t.x,n=s.y-t.y;for(const l of this.group)l.x+=r,l.y+=n;const o=e.global.x-this.lastPointer.x,a=e.global.y-this.lastPointer.y;this.#i.x+=o,this.#i.y+=a,this.lastPointer.copyFrom(e.global),this.#d(),this.emit("transforming")};#v(e,t){this.#u(),this.isDragging=!0,this.activeHandle=e,this.#a.clear();for(const s of this.group)this.#a.set(s,s.localTransform.clone());this.rotation=this.#r,this.#c.copyFrom(this.#h),this.#A(e)}#b(e,t){this.#T(e,t)}async#T(e,t){const s=this.#s,r=this.#E(e,this.toLocal(t),s),n=r.width/this.#c.width,o=r.height/this.#c.height,a=this.toGlobal(s);if(this.opts.clip&&this.opts.clip.type==="Text"){const c=r.width;this.emit("textClipResize",{handle:e,newWidth:c,newHeight:r.height,pivotWorld:a,proposed:r,sx:n,sy:o})}else this.#g(this.#I(a,this.#r,n,o));this.#h.copyFrom(r),this.#d(),this.emit("transforming")}#w(e){this.#u(),this.isDragging=!0,this.activeHandle="rot",this.#a.clear();for(const t of this.group)this.#a.set(t,t.localTransform.clone());this.#l=Math.atan2(e.y-this.#i.y,e.x-this.#i.x)}#S(e){const s=Math.atan2(e.y-this.#i.y,e.x-this.#i.x)-this.#l,r=this.#r+s;this.#g(this.#P(this.#i,s)),this.rotation=r,this.#d(r),this.emit("transforming")}#m(){this.isDragging=!1,this.#r=this.rotation,this.activeHandle=null,this.#d(this.#r),this.emit("transformEnd")}#d(e=this.#r){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#i)),this.rotation=e;const s=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),r=this.#h;this.wireframe.draw(r,s);const n=r.x+r.width/2,o=r.y+r.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 c of l)c.scale.set(s);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(r.x,r.y),this.#e.tr.position.set(r.x+r.width,r.y),this.#e.bl.position.set(r.x,r.y+r.height),this.#e.br.position.set(r.x+r.width,r.y+r.height),this.#e.ml.position.set(r.x,o),this.#e.mr.position.set(r.x+r.width,o),this.#e.mt.position.set(n,r.y),this.#e.mb.position.set(n,r.y+r.height),this.#e.rot.position.set(n,r.y-30*s),this.#C(s)}#C(e){if(this.selectionOutlines.clear(),this.group.length<=1||!this.parent)return;const t={width:1*e,color:43775,alpha:1};for(const s of this.group){const r=this.#f(s);this.#t[0].set(r.x,r.y),this.#t[1].set(r.x+r.width,r.y),this.#t[2].set(r.x+r.width,r.y+r.height),this.#t[3].set(r.x,r.y+r.height);for(const n of this.#t)s.toGlobal(n,n),this.toLocal(n,void 0,n);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)}}#A(e){const t=this.#c;if(this.opts.centeredScaling){this.#s.set(t.x+t.width/2,t.y+t.height/2);return}e==="tl"?this.#s.set(t.x+t.width,t.y+t.height):e==="tr"?this.#s.set(t.x,t.y+t.height):e==="bl"?this.#s.set(t.x+t.width,t.y):e==="br"?this.#s.set(t.x,t.y):e==="ml"?this.#s.set(t.x+t.width,t.y+t.height/2):e==="mr"?this.#s.set(t.x,t.y+t.height/2):e==="mt"?this.#s.set(t.x+t.width/2,t.y+t.height):e==="mb"&&this.#s.set(t.x+t.width/2,t.y)}#E(e,t,s){if(this.opts.centeredScaling){const n=Math.max(this.#n,Math.abs(t.x-s.x)*2),o=Math.max(this.#o,Math.abs(t.y-s.y)*2);return new H(s.x-n/2,s.y-o/2,n,o)}if(e==="tl"){const n=Math.min(t.x,s.x-this.#n),o=Math.min(t.y,s.y-this.#o);return new H(n,o,s.x-n,s.y-o)}if(e==="tr"){const n=Math.max(t.x,s.x+this.#n),o=Math.min(t.y,s.y-this.#o);return new H(s.x,o,n-s.x,s.y-o)}if(e==="bl"){const n=Math.min(t.x,s.x-this.#n),o=Math.max(t.y,s.y+this.#o);return new H(n,s.y,s.x-n,o-s.y)}if(e==="br"){const n=Math.max(t.x,s.x+this.#n),o=Math.max(t.y,s.y+this.#o);return new H(s.x,s.y,n-s.x,o-s.y)}const r=this.#c;if(e==="ml"){const n=Math.min(t.x,s.x-this.#n);return new H(n,r.y,s.x-n,r.height)}if(e==="mr"){const n=Math.max(t.x,s.x+this.#n);return new H(s.x,r.y,n-s.x,r.height)}if(e==="mt"){const n=Math.min(t.y,s.y-this.#o);return new H(r.x,n,r.width,s.y-n)}if(e==="mb"){const n=Math.max(t.y,s.y+this.#o);return new H(r.x,s.y,r.width,n-s.y)}return new H(s.x,s.y,this.#n,this.#o)}#I(e,t,s,r){return Lx.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(s,r).rotate(t).translate(e.x,e.y)}#P(e,t){return Lx.delta.identity().translate(-e.x,-e.y).rotate(t).translate(e.x,e.y)}#g(e){for(const t of this.group){const s=this.#a.get(t),r=t.parent;if(!s||!r)continue;const n=r.worldTransform.clone().invert(),o=r.worldTransform.clone().append(s),a=e.clone().append(o),l=n.clone().append(a);t.setFromMatrix(l)}}}class hk{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new X;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;init(e,t){this.selectionGraphics=new _e,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",s=>this.onStagePointerDown(s)),e.stage.on("globalpointermove",s=>this.onStagePointerMove(s)),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),s=Math.min(this.dragSelectionStart.x,t.x),r=Math.min(this.dragSelectionStart.y,t.y),n=Math.abs(t.x-this.dragSelectionStart.x),o=Math.abs(t.y-this.dragSelectionStart.y);this.selectionGraphics.clear(),this.selectionGraphics.rect(s,r,n,o).fill({color:703971,alpha:.3}),this.selectionGraphics.rect(s,r,n,o).stroke({width:2,color:703971})}}onStagePointerUp(){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const e=this.selectionGraphics.getBounds(),t=[],s=new H(e.x,e.y,e.width,e.height);if(s.width>2||s.height>2){for(const r of this.studio.clips){const n=this.studio.spriteRenderers.get(r);if(!n)continue;const o=n.getRoot();if(!o||!o.visible)continue;const a=o.getBounds();s.x<a.x+a.width&&s.x+s.width>a.x&&s.y<a.y+a.height&&s.y+s.height>a.y&&t.push(r)}if(t.length>0)for(const r of t)this.selectClip(r,!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 s=t.getRoot();s!=null&&(s.eventMode="static",s.cursor="pointer",s.on("pointerdown",r=>{const n=this.getTopmostClipAtPoint(r.global);n&&this.selectClip(n,r.shiftKey)}),this.interactiveClips.add(e))}getTopmostClipAtPoint(e){if(!this.studio.pixiApp)return null;let t=null,s=-1/0;for(const r of this.interactiveClips){const n=this.studio.spriteRenderers.get(r);if(!n)continue;const o=n.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&&r.zIndex>s&&(s=r.zIndex,t=r)}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(s=>e.includes(s.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})}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 r of this.selectedClips){const n=this.studio.spriteRenderers.get(r);if(n==null)continue;const o=n.getRoot();o!=null&&(e.push(o),this.selectedClips.size===1&&(t=r))}if(e.length===0){console.warn("Cannot create transformer: no sprites found");return}this.activeTransformer=new ck({group:e,clip:t});let s=null;this.activeTransformer.on("transforming",()=>{s===null&&(s=requestAnimationFrame(()=>{s=null,this.syncSelectedClipsTransformsRealtime()}))}),this.activeTransformer.on("textClipResize",r=>{this.textClipResizedWidth=r.newWidth,this.textClipResizeHandle=r.handle,this.textClipResizedSx=r.sx,this.textClipResizedSy=r.sy}),this.activeTransformer.on("transformEnd",async()=>{s!==null&&(cancelAnimationFrame(s),s=null),await this.syncSelectedClipsTransforms();for(const r of this.selectedClips)this.studio.emit("clip:updated",{clip:r})}),this.activeTransformer.on("pointerdown",r=>{const n=this.getTopmostClipAtPoint(r.global);n&&!this.selectedClips.has(n)&&(this.selectClip(n,r.shiftKey),r.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 gt))continue;const s=this.studio.spriteRenderers.get(t);if(s==null)continue;const r=s.getRoot(),n=s.getSprite();if(r==null||n==null||n.texture==null)continue;const o=Math.abs(r.scale.x*n.scale.x);if(o===1)continue;const a=t.left,l=t.top,c=t.width,h=n.texture.width,u=o*h;await t.updateStyle({wordWrap:!0,wordWrapWidth:u});const d=await t.getTexture();d&&(await s.updateFrame(d),n.scale.set(1,1),r.scale.set(1,1),e==="ml"?t.left=a+c-t.width:t.left=a,t.top=l,r.x=t.left+t.width/2,r.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 s=t.getRoot(),r=t.getSprite();if(s==null||r==null||r.texture==null)continue;const n=r.texture.width,o=r.texture.height,a=Math.abs(s.scale.x*r.scale.x)*n,l=Math.abs(s.scale.y*r.scale.y)*o,c=(e instanceof gt||e instanceof ei)&&this.textClipResizedWidth!==null?this.textClipResizedWidth:a,h=e.width,d=(e.style?.fontSize??16)*Math.max(this.textClipResizedSx||1,this.textClipResizedSy||1);let f=s.x;const p=s.y-l/2,g=s.x-c/2;if(e instanceof gt&&this.textClipResizedWidth!==null){const _={wordWrap:!0,wordWrapWidth:c};this.textClipResizeHandle==="mr"?(f=e.left+c/2,s.x=f):this.textClipResizeHandle==="ml"?(f=e.left+c/2-(c-h),s.x=f):["br","tr"].includes(this.textClipResizeHandle)?(f=e.left+c/2,_.fontSize=d):["bl","tl"].includes(this.textClipResizeHandle)&&(f=e.left+c/2-(c-h),_.fontSize=d),await e.updateStyle(_);const x=await e.getTexture();x&&(await t.updateFrame(x),e.width=c,e.height=x.height,this.textClipResizedWidth=null,e.left=f-e.width/2,e.top=s.y-e.height/2,r.scale.set(1,1),s.scale.set(1,1))}else{e.left=g,e.top=p,e.width=a,e.height=l;const _=e.flip==null?1:-1;e.angle=_*s.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 s=t.getRoot(),r=t.getSprite();if(s!=null&&r!=null&&r.texture!=null){const n=r.texture.width,o=r.texture.height,a=Math.abs(s.scale.x*r.scale.x)*n,l=Math.abs(s.scale.y*r.scale.y)*o,c=s.x-a/2,h=s.y-l/2;e.left=c,e.top=h,e.width=a,e.height=l;const u=e.flip==null?1:-1;e.angle=u*s.angle,t.updateTransforms(),this.studio.emit("clip:updated",{clip:e})}}}async deleteSelected(){return this.studio.deleteSelected()}}class uk{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 r=(this.currentTime-e.display.from)/1e6;this.isPlaybackCapable(e)&&await e.play(t,r)}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[s,{element:r}]of this.playbackElements.entries()){if(!(this.currentTime>=s.display.from&&(s.display.to===0||this.currentTime<=s.display.to))){this.isPlaybackCapable(s)&&s.pause(r);continue}const o=(this.currentTime-s.display.from)/1e6;this.isPlaybackCapable(s)&&await s.seek(r,o)}if(await this.studio.updateFrame(this.currentTime),this.studio.emit("currentTime",{currentTime:this.currentTime}),t){this.isPlaying=!0;for(const[s,{element:r}]of this.playbackElements.entries()){if(!(this.currentTime>=s.display.from&&(s.display.to===0||this.currentTime<=s.display.to)))continue;const o=(this.currentTime-s.display.from)/1e6;this.isPlaybackCapable(s)&&await s.play(r,o)}}}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 s=(performance.now()-this.playStartTimestamp)*1e3;this.currentTime=Math.min(this.playStartTime+s,this.maxDuration),this.studio.emit("currentTime",{currentTime:this.currentTime});try{await this.studio.updateFrame(this.currentTime)}catch(r){console.warn("Error updating frame:",r)}this.isPlaying&&(this.rafId=requestAnimationFrame(e))};e()}isPlaybackCapable(e){return"play"in e&&"pause"in e&&"seek"in e}}class Ji{static instance;fonts=new Map;constructor(){}static getInstance(){return Ji.instance||(Ji.instance=new Ji),Ji.instance}async addFont(e){if(!this.fonts.has(e.name))try{const s=await new FontFace(e.name,`url(${e.url})`).load();document.fonts.add(s),this.fonts.set(e.name,s)}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 Hx=Ji.getInstance();class dk{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){const t={id:e.id||`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:e.name,type:e.type,clipIds:[]};return this.tracks.push(t),this.studio.emit("track:added",{track:t}),t}async removeTrack(e){const t=this.tracks.findIndex(n=>n.id===e);if(t===-1)return;const r=[...this.tracks[t].clipIds];for(const n of r)await this.removeClipById(n);this.tracks.splice(t,1),this.studio.emit("track:removed",{trackId:e})}async addTransition(e,t=2e6,s,r){if(this.studio.destroyed)return;let n=null,o=null;if(console.log("[Studio] addTransition",{fromClipId:s,toClipId:r}),s&&r&&(n=this.getClipById(s)??null,o=this.getClipById(r)??null,console.log("[Studio] Found clips",{clipA:n,clipB:o})),!n||!o){console.warn("[Studio] Invalid fromClipId or toClipId",{fromClipId:s,toClipId:r});return}await Promise.all([n.ready,o.ready]);const a=t,l=o.display.from-a/2,c=l+a,h={key:e,name:e,duration:a,fromClipId:n.id,toClipId:o.id,start:Math.max(0,l),end:c},u=this.findTrackIdByClipId(o.id);if(u){const f=this.tracks.find(p=>p.id===u);if(f){const p=f.clipIds.map(g=>this.getClipById(g)).filter(g=>{if(!g||g.type!=="Transition")return!1;const m=g;return m.fromClipId===n.id&&m.toClipId===o.id});for(const g of p)await this.removeClip(g)}}this.studio.transitionRenderers.has(n.id)&&(this.studio.transitionRenderers.get(n.id)?.destroy(),this.studio.transitionRenderers.delete(n.id)),this.studio.transitionRenderers.has(o.id)&&(this.studio.transitionRenderers.get(o.id)?.destroy(),this.studio.transitionRenderers.delete(o.id)),n.transition={...h},o.transition={...h};const d=new Lt(e);d.duration=a,d.fromClipId=Math.max(0,l)===0?null:n.id,d.toClipId=o.id,d.fromClipId===null&&n&&(d.fromClipId=n.id),d.display.from=Math.max(0,l),d.display.to=c,await this.addClip(d,{trackId:u}),this.studio.seek(this.studio.currentTime)}async addClip(e,t){const s=Array.isArray(e)?e:[e];if(s.length===0)return;const{trackId:r,audioSource:n}=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 s)await this.prepareClipForTimeline(a,r),o.push(a);await this.recalculateMaxDuration();for(const a of o)await this.setupClipVisuals(a,n);await this.studio.updateFrame(this.studio.currentTime),this.emitAddClipEvents(o,r)}normalizeAddClipOptions(e){let t,s;if(e&&(typeof e=="string"||e instanceof File||e instanceof Blob))t=e;else if(typeof e=="object"&&e!==null&&!("size"in e)){const r=e;t=r.audioSource,s=r.trackId}return{trackId:s,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 s=async()=>{await this.studio.updateFrame(this.studio.currentTime);const r=this.studio.selection;r.activeTransformer!=null&&r.selectedClips.has(e)&&typeof r.activeTransformer.updateBounds=="function"&&r.activeTransformer.updateBounds()};e.on("propsChange",s),this.studio.clipListeners.set(e,s),this.studio.pixiApp!=null&&typeof e.setRenderer=="function"&&e.setRenderer(this.studio.pixiApp.renderer),await e.ready}addClipToTrack(e,t){if(t){const s=this.tracks.find(r=>r.id===t);if(s)s.clipIds.includes(e.id)||s.clipIds.push(e.id);else{const r={id:t,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(r),this.studio.emit("track:added",{track:r})}}else{const r={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(r),this.studio.emit("track:added",{track:r})}}async setupClipVisuals(e,t){const s=this.studio.spriteRenderers.get(e);if(s){const n=this.studio.clipsNormalContainer,o=s.getRoot();o&&!o.parent&&n.addChild(o);return}const r=await e.ready;if(await this.setupPlaybackForClip(e,t),r.width>0&&r.height>0){const n=this.studio.clipsNormalContainer,o=e.type==="Video"&&this.isPlaybackCapable(e);if(!o||o&&e.tickInterceptor!=null){const a=new gn(this.studio.pixiApp,e,n);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 s=e[0],r=t||this.tracks.find(n=>n.clipIds.includes(s.id))?.id||"";this.studio.emit("clip:added",{clip:s,trackId:r})}else this.studio.emit("clips:added",{clips:e,trackId:t})}async removeClip(e,t={permanent:!0}){const{permanent:s}=t,r=this.clips.findIndex(h=>h===e);if(r===-1)return;if(e instanceof Lt){if(e.fromClipId){const h=this.getClipById(e.fromClipId);h&&"transition"in h&&delete h.transition}if(e.toClipId){const h=this.getClipById(e.toClipId);h&&"transition"in h&&delete h.transition}}this.studio.selection.selectedClips.has(e)&&this.studio.selection.deselectClip(),this.clips.splice(r,1);const n=[];for(const h of this.tracks){const u=h.clipIds.indexOf(e.id);u!==-1&&(h.clipIds.splice(u,1),n.push(h.id))}for(const h of n){const u=this.tracks.findIndex(d=>d.id===h);u!==-1&&this.tracks[u].clipIds.length===0&&(this.tracks.splice(u,1),this.studio.emit("track:removed",{trackId:h}))}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(s)a.destroy(),this.studio.spriteRenderers.delete(e);else{const h=a.getRoot();h&&h.parent&&h.parent.removeChild(h)}const l=this.studio.transport.playbackElements.get(e);l!=null&&s&&this.isPlaybackCapable(e)&&(e.cleanupPlayback(l.element,l.objectUrl),this.studio.transport.playbackElements.delete(e));const c=this.studio.videoSprites.get(e);c!=null&&this.studio.pixiApp!=null&&(c.parent&&c.parent.removeChild(c),s&&(c.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 s of e){const r=this.clips.findIndex(c=>c===s);if(r===-1)continue;if(s instanceof Lt){if(s.fromClipId){const c=this.getClipById(s.fromClipId);c&&"transition"in c&&delete c.transition}if(s.toClipId){const c=this.getClipById(s.toClipId);c&&"transition"in c&&delete c.transition}}this.studio.selection.selectedClips.has(s)&&this.studio.selection.deselectClip(),this.clips.splice(r,1);for(const c of this.tracks){const h=c.clipIds.indexOf(s.id);h!==-1&&c.clipIds.splice(h,1)}this.studio.selection.interactiveClips.delete(s);const n=this.studio.clipListeners.get(s);n&&(s.off("propsChange",n),this.studio.clipListeners.delete(s));const o=this.studio.spriteRenderers.get(s);if(o!=null)if(t.permanent)o.destroy(),this.studio.spriteRenderers.delete(s);else{const c=o.getRoot();c&&c.parent&&c.parent.removeChild(c)}const a=this.studio.transport.playbackElements.get(s);a!=null&&t.permanent&&this.isPlaybackCapable(s)&&(s.cleanupPlayback(a.element,a.objectUrl),this.studio.transport.playbackElements.delete(s));const l=this.studio.videoSprites.get(s);l!=null&&this.studio.pixiApp!=null&&(l.parent&&l.parent.removeChild(l),t.permanent&&(l.destroy(),this.studio.videoSprites.delete(s)))}for(let s=this.tracks.length-1;s>=0;s--)if(this.tracks[s].clipIds.length===0){const r=this.tracks[s].id;this.tracks.splice(s,1),this.studio.emit("track:removed",{trackId:r})}await this.recalculateMaxDuration(),this.studio.emit("clips:removed",{clipIds:e.map(s=>s.id)})}}async removeClipById(e){const t=this.clips.find(s=>s.id===e);t&&await this.removeClip(t)}async updateClip(e,t){const s=this.clips.find(r=>r.id===e);s&&(await this.applyClipUpdate(s,t),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(s),this.studio.emit("clip:updated",{clip:s}))}async updateClips(e){const t=[];for(const{id:s,updates:r}of e){const n=this.clips.find(o=>o.id===s);n&&(await this.applyClipUpdate(n,r),t.push(n))}if(t.length!==0){await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime);for(const s of t)this.updateTransformer(s),this.studio.emit("clip:updated",{clip:s})}}async replaceClipsBySource(e,t){const s=this.clips.filter(r=>r.src===e);if(s.length!==0){this.studio.suspendRendering();for(const r of s){if(!this.clips.includes(r))continue;const n=this.findTrackIdByClipId(r.id);if(!n)continue;const o=this.getTrackById(n);if(!o)continue;const a=await t(r),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 c=this.clips.indexOf(r);c!==-1&&(this.clips[c]=a);const h=o.clipIds.indexOf(r.id);h!==-1&&(o.clipIds[h]=a.id),await this.setupClipVisuals(a);const u=this.studio.spriteRenderers.get(r);u&&(u.destroy(),this.studio.spriteRenderers.delete(r));const d=this.studio.videoSprites.get(r);d&&(d.parent&&d.parent.removeChild(d),d.destroy(),this.studio.videoSprites.delete(r));const f=this.studio.clipListeners.get(r);f&&(r.off("propsChange",f),this.studio.clipListeners.delete(r)),this.studio.selection.selectedClips.has(r)&&(this.studio.selection.selectedClips.delete(r),this.studio.selection.selectedClips.add(a)),this.studio.emit("clip:replaced",{oldClip:r,newClip:a,trackId:n})}await this.recalculateMaxDuration(),this.studio.resumeRendering(),await this.studio.updateFrame(this.studio.currentTime)}}async applyClipUpdate(e,t){if(e instanceof gt&&(await e.updateStyle(t),"style"in t&&delete t.style),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 s=t.display.to-t.display.from;s!==t.duration&&(e.duration=s)}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(r=>Ys(r,!1)),t=this.tracks.map(r=>({id:r.id,name:r.name,type:r.type,clipIds:[...r.clipIds]})),s=[];return this.clips.forEach(r=>{if(r.transition){const n=this.tracks.find(o=>o.clipIds.includes(r.id));if(n){const o=n.clipIds.indexOf(r.id);if(o>0){const a=n.clipIds[o-1];s.push({key:r.transition.name,duration:r.transition.duration,clips:[a,r.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 s=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),s&&this.studio.pixiApp!=null){const r=this.studio.opts.width,n=this.studio.opts.height;this.studio.pixiApp.renderer.resize(r,n),this.studio.opts.canvas&&(this.studio.opts.canvas.width=r,this.studio.opts.canvas.height=n)}}const t=[];if(e.clips){await this.ensureFontsForClips(e.clips);const s=new Map;if(e.tracks){for(const n of e.tracks)if(n.clipIds)for(const o of n.clipIds)s.set(o,n.id)}if(e.tracks)for(const n of e.tracks)this.tracks.push({id:n.id,name:n.name,type:n.type,clipIds:[]});for(const n of e.clips)t.push((async()=>{try{let o=n.id?s.get(n.id):void 0;if(n.type==="Transition"){const l=n,c=l.toClipId||l.fromClipId;c&&(o=s.get(c))}if(n.type!=="Text"&&n.type!=="Caption"&&n.type!=="Effect"&&n.type!=="Transition"&&(!n.src||n.src.trim()===""))return console.warn(`Skipping clip ${n.type} with empty source`,n),{clip:null};const a=await Ki(n);return(a.type==="Video"||a.type==="Image")&&(!n.width||!n.height)&&this.studio.opts.width&&this.studio.opts.height&&(typeof a.scaleToFit=="function"&&await a.scaleToFit(this.studio.opts.width,this.studio.opts.height),typeof a.centerInScene=="function"&&a.centerInScene(this.studio.opts.width,this.studio.opts.height)),{clip:a,intendedTrackId:o}}catch(o){return console.error(`Failed to load clip ${n.id||"unknown"}:`,o),{clip:null}}})());const r=await Promise.all(t);for(const{clip:n,intendedTrackId:o}of r)n&&(n.id||(n.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.push(n),this.addClipToTrack(n,o))}this.studio.pixiApp&&await Promise.all(this.clips.map(async s=>{const r=async()=>{await this.studio.updateFrame(this.studio.currentTime);const n=this.studio.selection;n.activeTransformer!=null&&n.selectedClips.has(s)&&typeof n.activeTransformer.updateBounds=="function"&&n.activeTransformer.updateBounds()};s.on("propsChange",r),this.studio.clipListeners.set(s,r),typeof s.setRenderer=="function"&&s.setRenderer(this.studio.pixiApp.renderer),await s.ready,await this.setupClipVisuals(s)}));for(const s of this.clips){const r=s.effects;if(Array.isArray(r))for(const n of r)this.studio.globalEffects.has(n.id)||this.studio.globalEffects.set(n.id,{id:n.id,key:n.key,startTime:n.startTime,duration:n.duration})}for(const s of this.clips)if(s instanceof Lt){const r={name:s.transitionEffect.key,key:s.transitionEffect.key,duration:s.duration,fromClipId:s.fromClipId,toClipId:s.toClipId,start:s.display.from,end:s.display.to};if(s.fromClipId){const n=this.getClipById(s.fromClipId);n&&(n.transition={...r})}if(s.toClipId){const n=this.getClipById(s.toClipId);n&&(n.transition={...r})}}await this.recalculateMaxDuration();try{await this.studio.updateFrame(this.studio.currentTime)}catch(s){console.error("[Studio] Failed to update initial frame:",s)}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 s of t)await this.removeClip(s)}async duplicateSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e);if(t.length===0)return;const s=[];for(const r of t){const n=this.findTrackIdByClipId(r.id);if(!n)continue;const o=this.tracks.find(u=>u.id===n);if(!o)continue;const a=Ys(r,!1),l=await Ki(a);l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const c=`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=`${o.name} (Copy)`;this.addTrack({id:c,name:h,type:o.type}),await this.addClip(l,{trackId:c}),s.push(l.id)}s.length>0&&this.studio.selection.selectClipsByIds(s)}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 s=t[0],r=e??this.studio.currentTime;if(r<=s.display.from||s.display.to>0&&r>=s.display.to){console.warn("[Studio] Split time is outside clip bounds");return}const n=Ys(s,!1),o=r-s.display.from,a=s.playbackRate||1,l=o*a,c={duration:o,display:{from:s.display.from,to:r}};s.trim&&(c.trim={from:s.trim.from,to:s.trim.from+l}),await this.updateClip(s.id,c);const h={...n};h.display={from:r,to:n.display.to},h.duration=n.duration-o,h.trim&&(h.trim={from:h.trim.from+l,to:h.trim.to});const u=await Ki(h);u.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const d=this.findTrackIdByClipId(s.id);d&&(await this.addClip(u,{trackId:d}),this.studio.selection.selectClipsByIds([u.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 s=t[0],r=e*1e6,n=s.playbackRate||1,o=r*n;if(r>=s.duration){console.warn("[Studio] Trim amount exceeds clip duration");return}const a=s.duration-r,l=s.display.from+r,c=s.display.to,h={duration:a,display:{from:l,to:c}};if(s.trim)h.trim={from:s.trim.from+o,to:s.trim.to};else{const u=s.sourceDuration||s.duration;h.trim={from:o,to:u}}await this.updateClip(s.id,h)}async updateSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==0)for(const s of t)await this.updateClip(s.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 s of e){if(s.type==="Text"){const r=s.style?.fontUrl||s.fontUrl;r&&t.set(r,{name:s.style?.fontFamily||s.fontFamily||"CustomFont",url:r})}if(s.type==="Caption"){const r=s.style?.fontUrl||s.fontUrl;r&&t.set(r,{name:s.style?.fontFamily||s.fontFamily||"CustomFont",url:r})}}if(t.size>0)try{await Hx.loadFonts(Array.from(t.values()))}catch(s){console.warn("Failed to load some fonts:",s)}}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 s=t.duration>0?t.duration:0;if(s===1/0)continue;const r=t.display.to>0?t.display.to:t.display.from+s;r>e&&(e=r)}this.studio.maxDuration=e}async setupPlaybackForClip(e,t){if(this.studio.pixiApp!=null){if(!this.isPlaybackCapable(e)){if(this.studio.pixiApp!=null&&(await e.ready).width>0&&(await e.ready).height>0){const s=new gn(this.studio.pixiApp,e,this.studio.clipsNormalContainer);this.studio.spriteRenderers.set(e,s)}return}try{const s=e;if(e.type==="Audio"&&t&&typeof t!="string"){const o=URL.createObjectURL(t);e.src=o}const{element:r,objectUrl:n}=await s.createPlaybackElement();if(e.type==="Video"){const o=M.from(r),a=new Ue(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:r,objectUrl:n})}catch(s){if(console.warn(`Failed to setup playback for ${e.constructor.name}`,s),this.studio.pixiApp!=null&&(await e.ready).width>0&&(await e.ready).height>0){const r=new gn(this.studio.pixiApp,e,this.studio.artboard);this.studio.spriteRenderers.set(e,r)}}}}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 s=t-e,r=[...this.clips];for(const n of r){const o=n.display.from,a=n.display.to;if(!(a<=e)){if(o>=t){await this.updateClip(n.id,{display:{from:n.display.from-s,to:n.display.to-s}});continue}if(o>=e&&a<=t){await this.removeClip(n);continue}if(o<e&&a>t){const l=await n.clone();l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const c=e,h=e+(a-t),u=n.trim.from+(t-o)*n.playbackRate,d=n.trim.to,f=this.tracks.find(p=>p.clipIds.includes(n.id));f&&(await this.addClip(l,{trackId:f.id}),await this.updateClip(l.id,{display:{from:c,to:h},trim:{from:u,to:d}})),await this.updateClip(n.id,{display:{from:n.display.from,to:e},trim:{from:n.trim.from,to:n.trim.from+(e-o)*n.playbackRate}});continue}if(o<e&&a<=t){await this.updateClip(n.id,{display:{from:n.display.from,to:e},trim:{from:n.trim.from,to:n.trim.from+(e-o)*n.playbackRate}});continue}if(o>=e&&a>t){await this.updateClip(n.id,{display:{from:e,to:e+(a-t)},trim:{from:n.trim.from+(t-o)*n.playbackRate,to:n.trim.to}});continue}}}await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}}const fk={Date:!0,RegExp:!0,String:!0,Number:!0};function Wx(i,e,t={cyclesFix:!0},s=[]){let r=[];const n=Array.isArray(i);for(const a in i){const l=i[a],c=n?+a:a;if(!(a in e)){r.push({type:"REMOVE",path:[c],oldValue:i[a]});continue}const h=e[a],u=typeof l=="object"&&typeof h=="object"&&Array.isArray(l)===Array.isArray(h);l&&h&&u&&!fk[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!s.includes(l))?r.push.apply(r,Wx(l,h,t,t.cyclesFix?s.concat([l]):[]).map(d=>(d.path.unshift(c),d))):l!==h&&!(Number.isNaN(l)&&Number.isNaN(h))&&!(u&&(isNaN(l)?l+""==h+"":+l==+h))&&r.push({path:[c],type:"CHANGE",value:h,oldValue:l})}const o=Array.isArray(e);for(const a in e)a in i||r.push({type:"CREATE",path:[o?+a:a],value:e[a]});return r}class pk{past=[];future=[];lastState=null;maxSize;constructor(e={}){this.maxSize=e.maxSize||50}projectToHistoryState(e){const t={},s=JSON.parse(JSON.stringify(e.tracks||[]));return e.clips.forEach(r=>{r.id&&(t[r.id]=JSON.parse(JSON.stringify(r)))}),{clips:t,tracks:s,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))),s=Wx(this.lastState,t);s.length!==0&&(this.past.push(s),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 s=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),r=this.applyPatches(s,t,!0);return this.future.push(t),this.lastState=r,{patches:t,state:r}}redo(e){const t=this.future.pop();if(!t)return null;const s=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),r=this.applyPatches(s,t,!1);return this.past.push(t),this.lastState=r,{patches:t,state:r}}applyPatches(e,t,s){const r=JSON.parse(JSON.stringify(e)),n=s?[...t].reverse():t;for(const o of n){const{type:a,path:l}=o,c=o.value,h=o.oldValue;let u=r,d=!1;for(let p=0;p<l.length-1;p++){if(u[l[p]]===void 0||u[l[p]]===null){d=!0;break}u=u[l[p]]}if(d)continue;const f=l[l.length-1];if(s)switch(a){case"CREATE":Array.isArray(u)?u.splice(f,1):delete u[f];break;case"REMOVE":u[f]=h&&typeof h=="object"?JSON.parse(JSON.stringify(h)):h;break;case"CHANGE":u[f]=h&&typeof h=="object"?JSON.parse(JSON.stringify(h)):h;break}else switch(a){case"CREATE":u[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break;case"REMOVE":Array.isArray(u)?u.splice(f,1):delete u[f];break;case"CHANGE":u[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break}}return r}canUndo(){return this.past.length>0}canRedo(){return this.future.length>0}}class mk extends Zh{selection;transport;timeline;history;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;globalEffects=new Map;activeGlobalEffect=null;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 hk(this),this.transport=new uk(this),this.timeline=new dk(this),this.history=new pk,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,s){let r=e;for(let n=0;n<t.length-1;n++){const o=t[n];r[o]||(r[o]=typeof t[n+1]=="number"?[]:{}),r=r[o]}r[t[t.length-1]]=s}async applyHistoryPatches(e,t,s){const r=new Map,n=new Map,o=new Set;for(const a of e){const{type:l,path:c}=a,h=a.value,u=a.oldValue;if(c[0]==="clips"){const d=c[1];s?l==="CREATE"?o.add(d):l==="REMOVE"?n.set(d,u):l==="CHANGE"&&(r.has(d)||r.set(d,{}),this.setPath(r.get(d),c.slice(2),u)):l==="CREATE"?n.set(d,h):l==="REMOVE"?o.add(d):l==="CHANGE"&&(r.has(d)||r.set(d,{}),this.setPath(r.get(d),c.slice(2),h))}else c[0]==="settings"&&(s?this.setPath(this.opts,c.slice(1),u):this.setPath(this.opts,c.slice(1),h))}for(const a of o){const l=this.timeline.getClipById(a);l&&await this.removeClip(l)}for(const[a,l]of n){let c=this.clipCache.get(a);c||(c=await Ki(l),this.clipCache.set(a,c));let h;for(const u of t.tracks)if(u.clipIds.includes(a)){h=u.id;break}await this.addClip(c,{trackId:h})}for(const[a,l]of r)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[r,n]of this.spriteRenderers)if(r.id===e){const o=n.getRoot();o&&o.parent&&o.parent.removeChild(o),n.destroy(),this.spriteRenderers.delete(r);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[r,n]of this.videoSprites)if(r.id===e){n.parent&&n.parent.removeChild(n),n.destroy(),this.videoSprites.delete(r);break}for(const[r]of this.clipListeners)if(r.id===e){this.clipListeners.delete(r);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 Lu,s=e.parentElement||window;await t.init({canvas:e,resizeTo:s,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 re,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new _e,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new re,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new _e,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 re,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new re,this.clipsNormalContainer.label="ClipsNormal",this.clipsNormalContainer.zIndex=10,this.clipsNormalContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsNormalContainer),this.transFromTexture=Ge.create({width:this.opts.width,height:this.opts.height}),this.transToTexture=Ge.create({width:this.opts.width,height:this.opts.height}),this.transBgGraphics=new _e,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}updateDimensions(e,t){this.opts.width=e,this.opts.height=t,this.artboardBg&&this.artboardBg.clear().rect(0,0,e,t).fill({color:3355443}),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.updateArtboardLayout()};updateArtboardLayout(){if(!this.pixiApp||!this.artboard)return;const e=this.pixiApp.canvas.width,t=this.pixiApp.canvas.height,s=this.opts.width,r=this.opts.height,n=this.pixiApp.canvas.parentElement?.clientWidth||e,o=this.pixiApp.canvas.parentElement?.clientHeight||t,a=this.opts.spacing||0,l=Math.max(0,n-a*2),c=Math.max(0,o-a*2),h=l/s,u=c/r,d=Math.min(h,u);this.artboard.scale.set(d),this.artboard.x=(n-s*d)/2,this.artboard.y=(o-r*d)/2}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,s,r){return this.timeline.addTransition(e,t,s,r)}findTrackIdByClipId(e){return this.timeline.findTrackIdByClipId(e)}async addClip(e,t){(Array.isArray(e)?e:[e]).forEach(r=>this.clipCache.set(r.id,r)),this.beginHistoryGroup();try{return await this.timeline.addClip(e,t)}finally{this.endHistoryGroup()}}addTrack(e){return this.timeline.addTrack(e)}async setTracks(e){return this.timeline.setTracks(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 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)}setupSpriteInteractivity(e){this.selection.setupSpriteInteractivity(e)}async removeClip(e){this.beginHistoryGroup();try{return this.clipCache.set(e.id,e),this.timeline.removeClip(e,{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(s=>this.timeline.getClipById(s)).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.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)}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=M.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,s=this.tracks.length;for(const n of this.clips){const o=this.getTrackIndex(n.id);if(o!==-1){const a=(s-o)*10;n.zIndex=a;const l=this.spriteRenderers.get(n);if(l){const c=l.getRoot();c&&(c.zIndex=a)}}}const r=[...this.clips].sort((n,o)=>n.zIndex-o.zIndex);for(const n of r){if(e<n.display.from){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}if(n.display.to>0&&e>=n.display.to){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}const o=e-n.display.from,a=o*n.playbackRate;n.animate(a);const l=await n.ready,c=n.duration||l.duration;if(c>0&&o>=c){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}const h=this.playbackElements.get(n),u=n.type==="Video"||n.type==="Image",d=n.transition?n.transition.start:0,f=n.transition?n.transition.end:0,p=u&&n.transition&&e>=d&&e<f;if(h!=null&&this.isPlaybackCapable(n)){const m=o/1e6;if(n.syncPlayback(h.element,this.isPlaying,m),n.type==="Video"&&this.isPlaybackCapable(n)){const _=this.videoSprites.get(n);if(_!=null){const x=n.meta.duration/1e6;if(this.spriteRenderers.has(n))_.visible=!1;else if(_.visible=!p&&m>=0&&m<x,_.visible&&tM(n,_),!p)continue}}else continue}if(p){this.transFromTexture||(this.transFromTexture=Ge.create({width:this.opts.width,height:this.opts.height})),this.transToTexture||(this.transToTexture=Ge.create({width:this.opts.width,height:this.opts.height})),this.transBgGraphics||(this.transBgGraphics=new _e,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}));const m=this.getClipById(n?.transition?.fromClipId),_=this.getClipById(n?.transition?.toClipId);let x=null,y=null;if(m){const v=Math.max(0,e-m.display.from),{video:T}=await m.getFrame(v);T instanceof HTMLVideoElement?x=this.getVideoTexture(T):x=T,x&&(this.lastFromFrame=x)}if(_){const v=Math.max(0,e-_.display.from),{video:T}=await _.getFrame(v);T instanceof HTMLVideoElement?y=this.getVideoTexture(T):y=T,y&&(this.lastToFrame=y)}if(x||(x=this.lastFromFrame),y||(y=this.lastToFrame),!x||!y)continue;if(x&&y&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const v=(e-d)/n?.transition?.duration;m&&x&&this.renderClipToTransitionTexture(m,x,this.transFromTexture),_&&y&&this.renderClipToTransitionTexture(_,y,this.transToTexture);let T=this.transitionRenderers.get(n.id);if(!T)try{T=nf({name:n?.transition?.name,renderer:this.pixiApp.renderer}),this.transitionRenderers.set(n.id,T)}catch(S){console.error("[Studio] Failed to create transition renderer:",S)}if(T){const S=T.render({width:this.opts.width,height:this.opts.height,from:this.transFromTexture,to:this.transToTexture,progress:v});let w=this.transitionSprites.get(n.id);w||(w=new Ue,w.label=`TransitionSprite_${n.id}`,this.transitionSprites.set(n.id,w),this.clipsNormalContainer&&this.clipsNormalContainer.addChild(w)),w.texture=S,w.visible=!0,w.x=0,w.y=0,w.width=this.opts.width,w.height=this.opts.height,w.anchor.set(0,0),w.zIndex=n.zIndex,t.add(n.id);const E=this.spriteRenderers.get(n);E?.getRoot()&&(E.getRoot().visible=!1);const P=this.videoSprites.get(n);if(P&&(P.visible=!1),m){const C=this.spriteRenderers.get(m);C?.getRoot()&&(C.getRoot().visible=!1);const A=this.videoSprites.get(m);A&&(A.visible=!1)}continue}}}const g=this.spriteRenderers.get(n);if(g!=null){const m=this.selectedClips.has(n);if(n.type!=="Text"&&n.type!=="Caption"&&typeof n.getTexture=="function"&&n.getTexture()!=null){const x=n.getTexture();if(x!=null){await g.updateFrame(x),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}if(n.type==="Text"){const x=n;this.pixiApp?.renderer&&typeof x.setRenderer=="function"&&x.setRenderer(this.pixiApp.renderer);const y=await x.getTexture();if(y!=null){await g.updateFrame(y),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}if(n.type==="Caption"){n.updateState(o);const x=n;this.pixiApp?.renderer&&typeof x.setRenderer=="function"&&x.setRenderer(this.pixiApp.renderer);const y=await x.getTexture();if(y!=null){await g.updateFrame(y),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}const{video:_}=await n.getFrame(o);await g.updateFrame(_),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n)}}if(this.activeGlobalEffect&&this.clipsNormalContainer&&this.clipsEffectContainer){const{startTime:n,duration:o}=this.activeGlobalEffect,a=e-n,l=Math.min(Math.max(a/o,0),1);if(l>0&&l<1){try{for(const h of this.clips)this.moveClipToEffectContainer(h,!1);const c=this.clips.some(h=>h.id===this.activeGlobalEffect.id&&h instanceof ct);for(const h of this.clips){let u=!1;if(c){const d=this.activeGlobalEffect.trackIndex??-1,f=this.getTrackIndex(h.id);u=h.id!==this.activeGlobalEffect.id&&!(h instanceof ct)&&f>d}else{const d=h.effects;u=Array.isArray(d)&&d.some(f=>f&&f.id===this.activeGlobalEffect.id)}u&&this.moveClipToEffectContainer(h,!0)}}catch(c){console.warn("Failed to reparent clips for effect; falling back to full-scene render",c)}this.clipsNormalContainer.visible=!0,await this.applyGlobalEffectIfNeeded(e)}else{for(const c of this.clips)try{this.moveClipToEffectContainer(c,!1)}catch{}this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}}else if(this.clipsNormalContainer){for(const n of this.clips)try{this.moveClipToEffectContainer(n,!1)}catch{}this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}for(const[n,o]of this.transitionSprites.entries())t.has(n)||(o.visible=!1);this.pixiApp!=null&&this.pixiApp.render()}moveClipToEffectContainer(e,t=!0){if(!this.clipsNormalContainer||!this.clipsEffectContainer)return;const s=t?this.clipsEffectContainer:this.clipsNormalContainer,r=this.spriteRenderers.get(e);if(r){const o=r.getRoot();if(o&&o.parent!==s){try{o.parent&&o.parent.removeChild&&o.parent.removeChild(o)}catch(a){console.warn("moveClipToEffectContainer: could not remove root from parent",a)}s.addChild(o)}}const n=this.transitionSprites.get(e.id);if(n&&n.parent!==s){try{n.parent&&n.parent.removeChild&&n.parent.removeChild(n)}catch(o){console.warn("moveClipToEffectContainer: could not remove transSprite from parent",o)}s.addChild(n)}}applyGlobalEffect(e,t,s){const r=t.id||`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={id:r,key:e,startTime:t.startTime,duration:t.duration??1e6};for(const o of s)o instanceof xi&&o.addEffect(n),o instanceof Me&&o.addEffect(n),o instanceof gt&&o.addEffect(n),o instanceof ei&&o.addEffect(n);return this.globalEffects.set(r,n),r}getTrackIndex(e){return this.tracks.findIndex(t=>t.clipIds.includes(e))}async getTransitionFromFrame(e,t){let s=null;if(e.transition?.prevClipId&&(s=this.clips.find(a=>a.id===e.transition.prevClipId)||null),s||(s=this.getPreviousClipOnTrack(e)),!s)return null;const r=s.duration>0?s.duration:0,n=Math.max(0,Math.min(t-s.display.from,r)),{video:o}=await s.getFrame(n);return o}getPreviousClipOnTrack(e){const t=this.getTrackIndex(e.id);return t===-1?null:this.clips.filter(s=>s.id!==e.id&&this.getTrackIndex(s.id)===t&&s.display.from<e.display.from&&(s instanceof Me||s instanceof xi)).sort((s,r)=>r.display.to-s.display.to)[0]||null}renderClipToTransitionTexture(e,t,s){if(!this.pixiApp||!this.transBgGraphics)return;const r=this.pixiApp.renderer.background.alpha;this.pixiApp.renderer.background.alpha=0,this.pixiApp.renderer.render({container:this.transBgGraphics,target:s,clear:!0}),this.pixiApp.renderer.background.alpha=r;const n=new Ue(t instanceof M?t:M.from(t));n.x=e.center.x,n.y=e.center.y,n.anchor.set(.5,.5);const o=n.texture.width||1,a=n.texture.height||1,l=e.width&&e.width!==0?Math.abs(e.width)/o:1,c=e.height&&e.height!==0?Math.abs(e.height)/a:1;e.flip==="horizontal"?(n.scale.x=-l,n.scale.y=c):e.flip==="vertical"?(n.scale.x=l,n.scale.y=-c):(n.scale.x=l,n.scale.y=c),n.rotation=(e.flip==null?1:-1)*e.angle,n.alpha=e.opacity,this.pixiApp.renderer.render({container:n,target:s,clear:!1}),t instanceof M||n.texture.destroy(!0),n.destroy()}removeGlobalEffect(e){this.globalEffects.delete(e)}clearGlobalEffects(){this.globalEffects.clear()}updateActiveGlobalEffect(e){let t=null;for(const s of this.clips)if(s instanceof ct&&e>=s.display.from&&(s.display.to===0||e<s.display.to)){t={id:s.id,key:s.effect.key,startTime:s.display.from,duration:s.duration>0?s.duration:s.display.to-s.display.from,trackIndex:this.getTrackIndex(s.id)};break}if(!t)for(const s of this.globalEffects.values()){const r=s.startTime+s.duration;if(e>=s.startTime&&e<r){t={id:s.id,key:s.key,startTime:s.startTime,duration:s.duration,trackIndex:-1};break}}this.activeGlobalEffect=t}async applyGlobalEffectIfNeeded(e){if(this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null),!this.activeGlobalEffect||!this.pixiApp||!this.clipContainer||!this.artboard||!this.clipsNormalContainer||!this.clipsEffectContainer)return;const{key:t,startTime:s,duration:r}=this.activeGlobalEffect,n=e-s,o=Math.min(Math.max(n/r,0),1);if(o<=0||o>=1)return;this.clipsEffectContainer.visible=!0;let a=this.effectFilters.get(t);if(!a)try{if(a=sf({name:t.toLowerCase(),renderer:this.pixiApp.renderer}),a)this.effectFilters.set(t,a);else return}catch(f){console.error(f);return}const l=this.opts.width,c=this.opts.height,h=Ge.create({width:l,height:c});this.pixiApp.renderer.render({container:this.clipsEffectContainer,target:h,clear:!0}),this.clipsEffectContainer.visible=!1;const u=a.render({canvasTexture:h,progress:o,width:l,height:c}),d=new Ue(u);d.x=0,d.y=0,d.width=l,d.height=c,d.scale.set(1),d.zIndex=5,this.clipContainer.addChild(d),this.currentGlobalEffectSprite=d,h.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)}}V.add(VS),V.mixin(re,$S),V.add(lg),V.add(cg),V.add(g0),V.mixin(re,xI),V.add(m0),V.add(sx),V.add(od),V.add(ox),V.add(ux),V.add(dx),V.add(wx),V.add(Tx),V.add(gx),V.add(vx),V.add(xx),V.add(mx),V.add(px),V.add(w0),V.add(b0);const gk=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),_k=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));se.Audio=Ke,se.Caption=ei,se.Compositor=rk,se.DEFAULT_AUDIO_CONF=le,se.Effect=ct,se.GL_EFFECT_OPTIONS=eM,se.GL_TRANSITION_OPTIONS=ik,se.Image=xi,se.Log=K,se.MP4Clip=Me,se.Placeholder=mn,se.Studio=mk,se.Text=gt,se.Transition=Lt,se.Video=Me,se.clipToJSON=Ys,se.createChromakey=S1,se.fastConcatMP4=Ux,se.fixFMP4Duration=BR,se.fontManager=Hx,se.jsonToClip=Ki,se.makeEffect=sf,se.makeTransition=nf,se.mixinMP4AndAudio=GR,se.renderTxt2ImgBitmap=M1,Object.defineProperty(se,Symbol.toStringTag,{value:"Module"})}));
@@ -1,4 +1,4 @@
1
- import { E as p, U as Ne, T as ee, F as je, G as he, v as fe, M as P, l as C, d as pe, I as v, t as w, a8 as $, R as N, w as L, H as me, a5 as G, a6 as ge, c as F, B as T, D as j, S as M, y as D, af as qe, ag as q, L as Y, ah as U, s as Q, a0 as Qe, $ as X, n as xe, q as _e, aa as be, ad as ye, o as Je, p as Ze, ab as et, ac as tt, ae as rt, ai as nt, aj as st, ak as it, al as H, am as at, an as ot, m as ve, ao as te, ap as k, e as b, aq as ut } from "./index-DSnnNrXJ.js";
1
+ import { E as p, U as Ne, T as ee, F as je, G as he, v as fe, M as P, l as C, d as pe, I as v, t as w, a8 as $, R as N, w as L, H as me, a5 as G, a6 as ge, c as F, B as T, D as j, S as M, y as D, af as qe, ag as q, L as Y, ah as U, s as Q, a0 as Qe, $ as X, n as xe, q as _e, aa as be, ad as ye, o as Je, p as Ze, ab as et, ac as tt, ae as rt, ai as nt, aj as st, ak as it, al as H, am as at, an as ot, m as ve, ao as te, ap as k, e as b, aq as ut } from "./index-D8oGyWjX.js";
2
2
  import { c as z, a as lt, b as ct, B as Te } from "./colorToUniform-C2jGzNe1.js";
3
3
  class Pe {
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@designcombo/video",
3
- "version": "0.1.13",
3
+ "version": "0.1.14",
4
4
  "description": "Video rendering and processing library",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -21,16 +21,10 @@
21
21
  "files": [
22
22
  "dist"
23
23
  ],
24
- "main": "dist/index.umd.js",
25
- "module": "dist/index.es.js",
26
- "types": "dist/index.d.ts",
27
- "exports": {
28
- ".": {
29
- "types": "./dist/index.d.ts",
30
- "import": "./dist/index.es.js",
31
- "require": "./dist/index.umd.js"
32
- }
33
- },
24
+ "main": "src/index.ts",
25
+ "module": "src/index.ts",
26
+ "types": "src/index.ts",
27
+
34
28
  "scripts": {
35
29
  "dev": "vite",
36
30
  "build": "tsc && vite build"
package/src/index.ts ADDED
@@ -0,0 +1,47 @@
1
+ export { fastConcatMP4, fixFMP4Duration, mixinMP4AndAudio } from './mp4-utils';
2
+ export { createChromakey } from './utils/chromakey';
3
+ export { renderTxt2ImgBitmap } from './utils/dom';
4
+
5
+ export {
6
+ Audio,
7
+ Caption,
8
+ Image,
9
+ Video,
10
+ Text,
11
+ Effect,
12
+ Transition,
13
+ Placeholder,
14
+ } from './clips';
15
+
16
+ // Export types
17
+ export type { IClip, IMP4ClipOpts } from './clips';
18
+
19
+ // Constants
20
+ export { DEFAULT_AUDIO_CONF } from './clips/iclip';
21
+
22
+ // Keep MP4Clip as alias for backward compatibility
23
+ export { Video as MP4Clip } from './clips';
24
+ export { Compositor } from './compositor';
25
+ export type { ICompositorOpts } from './compositor';
26
+ export { Studio } from './studio';
27
+ export type { IStudioOpts } from './studio';
28
+
29
+ export { Log } from './utils/log';
30
+ export {
31
+ clipToJSON,
32
+ jsonToClip,
33
+ type ClipJSON,
34
+ type ProjectJSON,
35
+ } from './json-serialization';
36
+
37
+ export { fontManager } from './utils/fonts';
38
+
39
+ // Effects
40
+ export { makeEffect } from './effect/effect';
41
+ export type { EffectKey } from './effect/glsl/gl-effect';
42
+ export { GL_EFFECT_OPTIONS } from './effect/glsl/gl-effect';
43
+
44
+ // Transitions
45
+ export { makeTransition } from './transition/transition';
46
+ export type { TransitionKey } from './transition/glsl/gl-transition';
47
+ export { GL_TRANSITION_OPTIONS } from './transition/glsl/gl-transition';