@agrhub/engine-pixi 1.4.0 → 1.4.1

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.
@@ -181,7 +181,7 @@ fn mainFragment(@location(0) uv: vec2<f32>) -> @location(0) vec4<f32> {
181
181
  let outline = vec4<f32>(outlineUniforms.uBorderColor * outlineAlpha, outlineAlpha);
182
182
  return content + outline;
183
183
  }
184
- `,cs={thickness:1,borderColor:0};class hs extends m.Filter{constructor(t){const{thickness:e,borderColor:i}={...cs,...t},s=m.GpuProgram.from({vertex:{source:je,entryPoint:"mainVertex"},fragment:{source:je,entryPoint:"mainFragment"}}),r=m.GlProgram.from({vertex:ls,fragment:as,name:"outline-filter"});super({gpuProgram:s,glProgram:r,padding:e*4,resources:{outlineUniforms:new m.UniformGroup({uThickness:{value:e,type:"f32"},uBorderColor:{value:new m.Color(i),type:"vec3<f32>"}})}})}get thickness(){return this.resources.outlineUniforms.uniforms.uThickness}set thickness(t){const e=this.resources.outlineUniforms.uniforms;e.uThickness=t}}const Je=Symbol.for("agrhub.engine.fontManager");class pt{static instance;fonts=new Map;loading=new Map;warnedConflicts=new Set;constructor(){}static getInstance(){const t=globalThis;return pt.instance||(pt.instance=t[Je]??new pt),t[Je]=pt.instance,pt.instance}async addFont(t){const e=this.fonts.get(t.name);if(e){this.warnOnConflict(t,e.url);return}const i=this.loading.get(t.name);if(i)return i;const s=(async()=>{try{const o=await new FontFace(t.name,`url(${t.url})`).load();document.fonts.add(o),this.fonts.set(t.name,{face:o,url:t.url}),m.CanvasTextMetrics.clearMetrics()}catch(r){console.error(`Failed to load font ${t.name}:`,r)}finally{this.loading.delete(t.name)}})();return this.loading.set(t.name,s),s}warnOnConflict(t,e){!t.url||t.url===e||this.warnedConflicts.has(t.name)||(this.warnedConflicts.add(t.name),console.warn(`[FontManager] Font "${t.name}" is already loaded from ${e}; ignoring different URL ${t.url}`))}async loadFonts(t){await Promise.all(t.map(e=>this.addFont(e)))}removeFont(t){const e=this.fonts.get(t);e&&(document.fonts.delete(e.face),this.fonts.delete(t))}clear(){this.fonts.forEach(({face:t})=>{document.fonts.delete(t)}),this.fonts.clear()}getLoadedFonts(){return Array.from(this.fonts.keys())}}const jt=pt.getInstance();function ds(l){if(typeof document>"u"||!document.fonts?.check)return!0;const t=String(l.fontFamily||"Roboto").split(",")[0].trim().replace(/^["']|["']$/g,""),e=Number(l.fontSize)||30,i=`${l.fontStyle||"normal"} ${l.fontWeight||"normal"} ${e}px "${t}"`;try{return document.fonts.check(i)}catch{return!0}}function Ze(l){const t=[];t.push(l.fontFamily||"Roboto"),t.push(String(l.fontSize||30)),t.push(String(l.fontWeight||"normal")),t.push(String(l.fontStyle||"normal")),l.fill!==void 0&&(typeof l.fill=="number"?t.push(`f_${l.fill}`):t.push("f_obj")),l.stroke&&(typeof l.stroke=="object"?t.push(`s_${l.stroke.color}_${l.stroke.width}_${l.stroke.join||""}`):t.push(`s_${l.stroke}`)),l.dropShadow&&t.push(`ds_${l.dropShadow.color}_${l.dropShadow.alpha}_${l.dropShadow.blur}_${l.dropShadow.angle}_${l.dropShadow.distance}`),ds(l)||t.push("pending");const e="installed_font_"+t.join("_").replace(/[^a-zA-Z0-9_]/g,"_");return!m.Cache.has(e)&&!m.Cache.has(e+"-bitmap")&&m.BitmapFont.install({name:e,style:l}),e}class Ke extends X{_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}pixiTextContainer=null;wordTexts=[];textStyle;textStyleBase;renderTexture=null;outlineFilter=null;dropShadowFilter=null;_refreshing=!1;_needsRefresh=!1;_refreshPromise=null;_spaceWidth=0;_text="";externalRenderer=null;pixiApp=null;originalOpts;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];setRenderer(t){this.externalRenderer=t}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("BaseTextClip: No renderer. Provide one via constructor or setRenderer().");return this.pixiApp.renderer}async getTexture(){return this._refreshPromise&&await this._refreshPromise.catch(()=>{}),this.pixiTextContainer==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture)}async tick(t){if(await this.ready,this._refreshPromise&&await this._refreshPromise.catch(()=>{}),this.pixiTextContainer==null||this.renderTexture==null)throw new Error("BaseTextClip not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);const e=await this.getRenderer();e.render({container:this.pixiTextContainer,target:this.renderTexture});const i=this.renderTexture.source?.resource?.source;let s;if(i instanceof HTMLCanvasElement||i instanceof OffscreenCanvas)s=await createImageBitmap(i);else{const o=e.extract.canvas(this.renderTexture);if(o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas)s=await createImageBitmap(o);else throw new Error("Unable to extract canvas from render texture")}return{video:s,state:"success"}}async split(t){await this.ready;const e=await this.clone(),i=await this.clone();return[e,i]}_hasMaskAnim(t){return t.some(e=>e?.params?.mask===!0)}get animations(){return super.animations}set animations(t){const e=this._hasMaskAnim(this.animations);super.animations=t;const i=this._hasMaskAnim(this.animations);e!==i&&this.originalOpts&&this.textStyle&&this.refreshText()}animate(t){super.animate(t,this.pixiTextContainer)}addEffect(t){this.effects.push(t)}editEffect(t,e){const i=this.effects.find(s=>s.id===t);i&&Object.assign(i,e)}removeEffect(t){const e=this.effects.findIndex(i=>i.id===t);e!==-1&&this.effects.splice(e,1)}refreshText(){return this._refreshing&&this._refreshPromise?(this._needsRefresh=!0,this._refreshPromise):(this._refreshing=!0,this._refreshPromise=(async()=>{try{do this._needsRefresh=!1,await this._doRefreshText();while(this._needsRefresh)}finally{this._refreshing=!1,this._refreshPromise=null}})(),this._refreshPromise)}async _doRefreshText(){const t=this._targetWidth??0,e=this.originalOpts.wordWrap,i=this.originalOpts.wordWrapWidth,s=this.originalOpts.background;if(this.originalOpts.fontUrl&&this.originalOpts.fontFamily)try{await jt.addFont({name:this.originalOpts.fontFamily,url:this.originalOpts.fontUrl})}catch(E){console.warn("[BaseTextClip] Failed to load font:",E)}typeof document<"u"&&await document.fonts.ready,this._buildTextStyles();const r=this.textStyle,o=this._applyTextCase(this.text);if(!this.pixiTextContainer)this.pixiTextContainer=new m.Container,this.pixiTextContainer.__clip=this;else{this.pixiTextContainer.__clip=this,this.animations.forEach(E=>{E&&typeof E.destroy=="function"&&E.destroy()});for(const E of this.pixiTextContainer.children)if(E&&!E.destroyed){const P=R=>{if(R&&(ht.killTweensOf(R),R.children))for(const B of R.children)P(B)};if(P(E),E.children)for(const R of E.children)R&&R.label==="LineContainer"&&(R.mask=null);E.destroy({children:!0})}this.pixiTextContainer.removeChildren()}const{textOnlyContainer:a,words:n}=this._buildWordObjects(o),c=this._applyStrokeFilter();this._applyShadowFilter(a),this.pixiTextContainer.addChild(a);const{spaceWidth:h,measuredTextHeight:d}=await this._measureSpaceAndHeight();this._spaceWidth=h;const f=this.originalOpts.lineHeight??1,u=r.fontSize??40,p=u*f;let g;if(e)if(t>0){const E=s?.paddingX??8;g=Math.max(1,t-E*2)}else g=i??100;else g=1e5;const v=this._breakIntoLines(g,p),x=this.originalOpts.background?.color,w=this.originalOpts.background?.opacity??1,T=this.originalOpts.background?.borderRadius??4,y=this.originalOpts.background?.paddingX??8,C=this.originalOpts.background?.paddingY??4,{containerWidth:k,containerHeight:O,contentHeight:F}=this._calculateDimensions(v,d,t,e,i,s,y,C),b=this._positionWords(v,k,O,F,d,y,a),S=this._drawDecoration(v,k,y);S&&this.pixiTextContainer.addChild(S);const A=this._buildBackground(b,x,w,T);A&&this.pixiTextContainer.addChildAt(A,0),this._lineRects=b,this._createRenderTexture(k,O,c),this._meta.width=k,this._meta.height=O,this._width=k,this._height=O,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration),this._onAfterRefresh(n,a,h,d,f,u)}_onAfterRefresh(t,e,i,s,r,o){}_applyTextCase(t){const e=this.originalOpts.textCase;return e==="uppercase"?t.toUpperCase():e==="lowercase"?t.toLowerCase():e==="title"?t.replace(/\w\S*/g,i=>i.charAt(0).toUpperCase()+i.substring(1).toLowerCase()):t}_buildTextStyles(){const t=this.createStyleFromOpts(this.originalOpts),{wordWrap:e,wordWrapWidth:i,lineHeight:s,letterSpacing:r,fill:o,...a}=t,n=Ze(t);this.textStyle=new m.TextStyle({...t,fontFamily:n});const c=Ze(a);return this.textStyleBase=new m.TextStyle({...a,fontFamily:c}),{fontName:n,baseFontName:c}}_buildWordObjects(t){const e=t.split(/\s+/).filter(s=>s.length>0),i=new m.Container;return i.label="TextOnlyContainer",this.wordTexts.forEach(s=>{s&&!s.destroyed&&s.destroy()}),this.wordTexts=e.map(s=>{const r=new m.SplitBitmapText({text:s,style:this.textStyle});return i.addChild(r),r}),{textOnlyContainer:i,words:e}}_applyStrokeFilter(){const t=this.originalOpts.stroke,e=(t!==null&&typeof t=="object"&&"width"in t?t.width:void 0)??this.originalOpts.strokeWidth??0,i=t!=null&&e>0;if(i){let s=0;if(typeof t=="object"&&"color"in t){const r=$(t.color);r!==void 0&&(s=r)}else if(typeof t=="string"||typeof t=="number"){const r=$(t);r!==void 0&&(s=r)}if(this.outlineFilter){this.outlineFilter.thickness=e,this.outlineFilter.padding=e*4;const r=this.outlineFilter.resources.outlineUniforms.uniforms;r.uBorderColor=new m.Color(s)}else this.outlineFilter=new hs({thickness:e,borderColor:s});this.wordTexts.forEach(r=>{r.filters=[this.outlineFilter]})}else this.outlineFilter&&(this.wordTexts.forEach(s=>{s.filters=[]}),this.outlineFilter=null);return i?e:0}_applyShadowFilter(t){const e=this.originalOpts.shadow;if(e){const i=e.offsetX??0,s=e.offsetY??0,r=$(e.color??"#000000"),o=e.alpha??1,a=e.blur??4,n=Math.ceil(a*2.5+Math.max(Math.abs(i),Math.abs(s)));r!==void 0&&(this.dropShadowFilter?(this.dropShadowFilter.color=r,this.dropShadowFilter.alpha=o,this.dropShadowFilter.blur=a,this.dropShadowFilter.offset={x:i,y:s},this.dropShadowFilter.padding=n):(this.dropShadowFilter=new j.DropShadowFilter({color:r,alpha:o,blur:a,offset:{x:i,y:s}}),this.dropShadowFilter.padding=n),t.filters=[this.dropShadowFilter])}else this.dropShadowFilter&&(t.filters=[],this.dropShadowFilter=null)}async _measureSpaceAndHeight(){const t=this.originalOpts.fontSize||40,e=this.originalOpts.fontFamily||"Arial",i=String(this.originalOpts.fontWeight||"normal"),s=this.originalOpts.fontStyle||"normal",r=`${s} ${i} ${t}px "${e}"`;if(typeof document<"u")try{await document.fonts.load(r)}catch{}const o=new m.TextStyle({fontFamily:e,fontSize:t,fontWeight:i,fontStyle:s}),a=m.CanvasTextMetrics.measureText(" ",o),n=new m.TextStyle({fontFamily:e,fontSize:t,fontWeight:i,fontStyle:s}),h=m.CanvasTextMetrics.measureText("Hg",n).fontProperties,d=h&&h.ascent>0?Math.ceil(h.ascent+h.descent):t,f=new m.SplitBitmapText({text:" ",style:this.textStyleBase}),u=Math.ceil(f.getLocalBounds().width||f.width||a.width||t*.25);return f.destroy(),{spaceWidth:u,measuredTextHeight:d}}_breakIntoLines(t,e){const i=[];let s=[],r=0,o=0;return this.wordTexts.forEach(a=>{const n=a.getLocalBounds(),c=Math.ceil(n.width||a.width),h=Math.ceil(n.height||a.height),d=r+(r>0?this._spaceWidth:0)+c;d<=t||s.length===0?(s.push(a),r=d,o=Math.max(o,h)):(s.length>0&&i.push({words:s,width:r,height:Math.max(o,e)}),s=[a],r=c,o=h)}),s.length>0&&i.push({words:s,width:r,height:Math.max(o,e)}),i}_calculateDimensions(t,e,i,s,r,o,a,n){const c=e+n*2;t.forEach(T=>{T.height=Math.max(T.height,c)});let h=0,d=0;t.forEach(T=>{h=Math.max(h,T.width),d+=T.height});let f=h;if(s&&i>0){const T=o?.paddingX??8,y=i-T*2;f=Math.max(f,y)}else s&&r!=null&&r>0&&(f=Math.max(f,r));const u=d;f+=a*2;const p=i>0?i:this._width,g=p===0,v=!this._explicitHeight||this.height===0,x=g?f:Math.max(f,p),w=v?u:Math.max(u,this.height||0);return{containerWidth:x,containerHeight:w,contentWidth:f,contentHeight:u}}_positionWords(t,e,i,s,r,o,a){const n=this.originalOpts.verticalAlign||"top";let c=0;n==="center"?c=(i-s)/2:n==="bottom"&&(c=i-s);let h=c;const d=[];return t.forEach(f=>{let u=0;const p=this.textAlign;p==="center"?u=(e-f.width)/2:p==="right"?u=e-f.width-o*2:u=o;const g=u,v=new m.Container;if(v.label="LineContainer",v.x=0,v.y=0,this.animations.some(w=>w?.params?.mask===!0)){const w=new m.Graphics;w.label="LineMask",w.rect(0,h,e,f.height),w.fill(16777215),v.mask=w,a.addChild(w)}a.addChild(v),f.words.forEach((w,T)=>{w.x=Math.round(u),w.y=Math.round(h+(f.height-r)/2-9),u+=(w.getLocalBounds().width||w.width)+(T<f.words.length-1?this._spaceWidth:0),v.addChild(w)}),d.push({x:g-o,y:h,w:f.width+o*2,h:f.height}),h+=f.height}),d}_drawDecoration(t,e,i){const s=this.originalOpts.textDecoration||this.originalOpts.verticalAlign;if(!s||s==="none"||!["underline","overline","strikethrough","line-through"].includes(s))return null;const r=this.textStyle,o=r.fontSize??40,a=s==="strikethrough"?"line-through":s,n=Math.max(1,o/12);let c=16777215;typeof r.fill=="number"&&(c=r.fill);const h=new m.Graphics;let d=0;return t.forEach(f=>{let u=i;const p=this.textAlign;p==="center"?u=(e-f.width)/2:p==="right"&&(u=e-f.width-i*2);let g=0;a==="underline"?g=f.height:a==="line-through"&&(g=f.height/2),h.rect(u,d+g,f.width,n),h.fill(c),d+=f.height}),h}_buildBackground(t,e,i,s){if(!t.length||!e||e==="transparent"||e==="")return null;const r=$(e),o=new m.Graphics;return this.drawRoundedMultilinePath(o,t,s,r??0,i),o}_createRenderTexture(t,e,i){const r=i>0?i*2.1:0;let o=0;if(this.dropShadowFilter){const h=this.dropShadowFilter.blur??0,d=this.dropShadowFilter.offset,f=d?Math.sqrt(d.x**2+d.y**2):0;o=h+f}const a=300+r+o,n=t+a*2,c=e+a*2;this.pixiTextContainer&&(this.pixiTextContainer.x=a,this.pixiTextContainer.y=a),this.renderTexture&&this.renderTexture.destroy(),this.renderTexture=m.RenderTexture.create({width:n,height:c}),this.renderTexturePadding=a}_normalizeStyleOpts(t){let e={...t};e.style&&(e={...e,...e.style},delete e.style),e.fill!==void 0&&(e.color=e.fill,delete e.fill),e.dropShadow!==void 0&&(e.shadow=e.dropShadow,delete e.dropShadow),e.textAlign!==void 0&&(e.align=e.textAlign,delete e.textAlign);const i=e.underline,s=e.overline,r=e.linethrough;return(i!==void 0||s!==void 0||r!==void 0)&&(i?e.textDecoration="underline":s?e.textDecoration="overline":r?e.textDecoration="line-through":e.textDecoration="none",delete e.underline,delete e.overline,delete e.linethrough),e}_cloneColorOpts(t){const e=this.originalOpts;return e.color&&typeof e.color=="object"&&"type"in e.color&&e.color.type==="gradient"?e.color:t(this.textStyle.fill)??16777215}_cloneStrokeOpts(t){const e=this.originalOpts,i=this.textStyle;if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke)return{stroke:e.stroke,strokeWidth:0};const s=t(i.stroke),r=e.strokeWidth??i.strokeThickness??0;return{stroke:s!==void 0?s:void 0,strokeWidth:r}}_cloneShadowOpts(t){const e=this.originalOpts,i=this.textStyle;if(e.shadow)return e.shadow;if(i.dropShadow){const s=i.dropShadow,r=t(s.color);if(r!==void 0){const o=s.angle??0,a=s.distance??0;return{color:r,alpha:s.alpha,blur:s.blur,offsetX:Math.cos(o)*a,offsetY:Math.sin(o)*a}}}}createStyleFromOpts(t){const e=t.fontSize??40,i=t.lineHeight??1,s={fontSize:e,fontFamily:t.fontFamily??"Roboto",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",align:t.align??"left",wordWrap:t.wordWrap??!1,wordWrapWidth:t.wordWrapWidth??100,lineHeight:e*i,letterSpacing:t.letterSpacing??0},r=t.color??"#ffffff";if(r&&typeof r=="object"&&"type"in r&&r.type==="gradient"){const o=new m.FillGradient(r.x0,r.y0,r.x1,r.y1);r.colors.forEach(({ratio:a,color:n})=>{const c=typeof n=="number"?n:$(n)??16777215;o.addColorStop(a,c)}),s.fill={fill:o}}else{const{color:o,alpha:a}=Ft(r);s.fill=o,a<1&&(s.fillAlpha=a)}return s}drawRoundedMultilinePath(t,e,i,s,r=1){if(e.length===0)return;const o=Math.max(i*.8,15);let a=!0,n=0;for(;a&&n<5;){a=!1,n++;for(let f=0;f<e.length;f++)for(let u=f+1;u<e.length;u++){const p=e[f].x+e[f].w,g=e[u].x+e[u].w;if(Math.abs(p-g)>.1&&Math.abs(p-g)<o){const v=Math.max(p,g);e[f].w=v-e[f].x,e[u].w=v-e[u].x,a=!0}if(Math.abs(e[f].x-e[u].x)>.1&&Math.abs(e[f].x-e[u].x)<o){const v=Math.min(e[f].x,e[u].x);e[f].w+=e[f].x-v,e[f].x=v,e[u].w+=e[u].x-v,e[u].x=v,a=!0}}}const c=[];c.push({x:e[0].x,y:e[0].y}),c.push({x:e[0].x+e[0].w,y:e[0].y});for(let f=0;f<e.length-1;f++){const u=e[f],p=e[f+1];if(Math.abs(u.x+u.w-(p.x+p.w))>.1){const g=(u.y+u.h+p.y)/2;c.push({x:u.x+u.w,y:g}),c.push({x:p.x+p.w,y:g})}}c.push({x:e[e.length-1].x+e[e.length-1].w,y:e[e.length-1].y+e[e.length-1].h}),c.push({x:e[e.length-1].x,y:e[e.length-1].y+e[e.length-1].h});for(let f=e.length-1;f>0;f--){const u=e[f],p=e[f-1];if(Math.abs(u.x-p.x)>.1){const g=(u.y+p.y+p.h)/2;c.push({x:u.x,y:g}),c.push({x:p.x,y:g})}}t.clear();const h=c[c.length-1],d=c[0];t.moveTo((h.x+d.x)/2,(h.y+d.y)/2);for(let f=0;f<c.length;f++){const u=c[f],p=c[(f+1)%c.length];t.arcTo(u.x,u.y,(u.x+p.x)/2,(u.y+p.y)/2,i)}t.fill({color:s,alpha:r})}destroy(){if(!this.destroyed){Q.info(`${this.constructor.name} destroy`);try{if(this.pixiTextContainer!=null&&!this.pixiTextContainer.destroyed){for(const t of this.pixiTextContainer.children)if(t&&!t.destroyed){const e=i=>{if(i&&(ht.killTweensOf(i),i.children))for(const s of i.children)e(s)};if(e(t),t.children)for(const i of t.children)i&&i.label==="LineContainer"&&(i.mask=null)}this.pixiTextContainer.destroy({children:!0})}}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&!this.renderTexture.destroyed&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const t=this.pixiApp;t.destroyed!==!0&&t.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(t=!1){const e=super.toJSON(t),{chromaKey:i,colorAdjustment:s,...r}=e;return r}}class mt extends Ke{type="Caption";_lastTickTime=0;_isWidthConstrained=!1;_words=[];_activeStyle={};_futureStyle={};_keywordColor="";_keywordPreserveAfterSpoken=!1;_wordAnimation={type:"scale",application:"none",value:1};_wordsPerLine="multiple";_videoWidth=1280;_videoHeight=720;_bottomOffset=100;get text(){return this._text}set text(t){if(this._text===t)return;const e=this._text;this._text=t,e!==""&&this._words.length>0&&(this._words=xe.redistributeCaptionWords(t,this._words,this.duration||5e6)),this.originalOpts&&this.textStyle&&this.refreshText().then(()=>this.emit("propsChange",{text:t}))}get textAlign(){return this.originalOpts?.align??"left"}get caption(){const t=this.originalOpts??{};return{words:this._words,colors:{active:t.activeStyle,future:t.futureStyle,keyword:t.keywordColor?{color:t.keywordColor,preserveAfterSpoken:t.keywordPreserveAfterSpoken}:void 0},wordAnimation:t.wordAnimation,positioning:{videoWidth:this._videoWidth,videoHeight:this._videoHeight,bottomOffset:this._bottomOffset}}}set caption(t){t&&(t.words&&(this._words=t.words,this.originalOpts&&(this.originalOpts.words=t.words)),t.colors&&("active"in t.colors&&(this.originalOpts.activeStyle=t.colors.active??void 0),"future"in t.colors&&(this.originalOpts.futureStyle=t.colors.future??void 0),"keyword"in t.colors&&(t.colors.keyword!=null?(this.originalOpts.keywordColor=t.colors.keyword.color,this.originalOpts.keywordPreserveAfterSpoken=t.colors.keyword.preserveAfterSpoken):(this.originalOpts.keywordColor=void 0,this.originalOpts.keywordPreserveAfterSpoken=void 0))),t.wordAnimation!==void 0&&(this.originalOpts.wordAnimation=t.wordAnimation),t.positioning&&(t.positioning.videoWidth!==void 0&&(this._videoWidth=t.positioning.videoWidth),t.positioning.videoHeight!==void 0&&(this._videoHeight=t.positioning.videoHeight),t.positioning.bottomOffset!==void 0&&(this._bottomOffset=t.positioning.bottomOffset)),this._syncOpts())}get words(){return this._words}set words(t){this._words=t,this.originalOpts&&(this.originalOpts.words=t),this.refreshText().then(()=>this.emit("propsChange",{style:this.style}))}get mediaId(){return this.originalOpts?.mediaId}set mediaId(t){this.originalOpts&&(this.originalOpts.mediaId=t)}get wordsPerLine(){return this._wordsPerLine}set wordsPerLine(t){this._wordsPerLine=t,this.originalOpts&&(this.originalOpts.wordsPerLine=t),this.refreshText()}get style(){const t=this.originalOpts??{};return{fontSize:t.fontSize,fontFamily:t.fontFamily,fontWeight:t.fontWeight,fontStyle:t.fontStyle,color:t.color,align:t.align,stroke:t.stroke,shadow:t.shadow,wordWrap:t.wordWrap,wordWrapWidth:t.wordWrapWidth,lineHeight:t.lineHeight,letterSpacing:t.letterSpacing,textCase:t.textCase}}set style(t){this.updateStyle(t)}async updateStyle(t){const e=this._normalizeStyleOpts(t);this.originalOpts={...this.originalOpts,...e},e.words!==void 0&&(this._words=e.words),this._syncOpts(),this._buildTextStyles(),await this.refreshText(),this.emit("propsChange",t)}get width(){return this._width}set width(t){Math.abs(this.width-t)<.1||(this._width=t,t>0&&(this._isWidthConstrained=!0),this.refreshText())}get height(){return this._height}set height(t){Math.abs(this.height-t)<.1||(this._height=t,this.refreshText())}animate(t){this._lastTickTime=t,super.animate(t)}constructor(t,e={},i){if(super(),this.originalOpts={...e},this._text=t,i&&this.setRenderer(i),e.caption){e.caption.words&&(this._words=e.caption.words);const s=e.caption;s.colors&&"active"in s.colors&&(this.originalOpts.activeStyle=s.colors.active??void 0),s.colors&&"future"in s.colors&&(this.originalOpts.futureStyle=s.colors.future??void 0),s.colors&&"keyword"in s.colors&&(s.colors.keyword!=null?(this.originalOpts.keywordColor=s.colors.keyword.color,this.originalOpts.keywordPreserveAfterSpoken=s.colors.keyword.preserveAfterSpoken):(this.originalOpts.keywordColor=void 0,this.originalOpts.keywordPreserveAfterSpoken=void 0)),s.wordAnimation!==void 0&&(this.originalOpts.wordAnimation=s.wordAnimation),s.positioning?.videoWidth!==void 0&&(this.originalOpts.videoWidth=s.positioning.videoWidth),s.positioning?.videoHeight!==void 0&&(this.originalOpts.videoHeight=s.positioning.videoHeight),s.positioning?.bottomOffset!==void 0&&(this.originalOpts.bottomOffset=s.positioning.bottomOffset)}e.words&&(this._words=e.words),e.initialLayoutApplied,this._syncOpts(),this._buildTextStyles(),this.ready=(async()=>(await this.refreshText(),{...this.meta}))()}createStyleFromOpts(t){const e=super.createStyleFromOpts(t);return e.fill=16777215,e}_syncOpts(){const t=this.originalOpts??{};this._activeStyle=t.activeStyle??{},this._futureStyle=t.futureStyle??{},this._keywordColor=t.keywordColor??"",this._keywordPreserveAfterSpoken=t.keywordPreserveAfterSpoken??!1,this._wordAnimation=t.wordAnimation??{type:"scale",application:"none",value:1},this._wordsPerLine=t.wordsPerLine??"multiple",this._videoWidth=t.videoWidth??1280,this._videoHeight=t.videoHeight??720,this._bottomOffset=t.bottomOffset??100}_buildWordObjects(t){const e=new m.Container;e.label="TextOnlyContainer",this.wordTexts.forEach(o=>o.destroy()),this.wordTexts=[];const i=[],s=this.originalOpts?.textCase,r=(o,a)=>{const n=new m.SplitBitmapText({text:o,style:this.textStyle});n.segmentIndex=a;const c=this.originalOpts?.color,h=typeof c=="object"&&c!==null&&"type"in c?16777215:c,d=$(h);return n.tint=d??16777215,n};return this._words.length>0?this._words.forEach((o,a)=>{let n=o.text||"";s==="uppercase"?n=n.toUpperCase():s==="lowercase"?n=n.toLowerCase():s==="title"&&(n=n.replace(/\w\S*/g,h=>h.charAt(0).toUpperCase()+h.substring(1).toLowerCase())),n.split(/\s+/).filter(h=>h.length>0).forEach(h=>{const d=r(h,a);e.addChild(d),this.wordTexts.push(d),i.push(h)})}):t.split(/\s+/).filter(o=>o.length>0).forEach((o,a)=>{const n=r(o,a);e.addChild(n),this.wordTexts.push(n),i.push(o)}),{textOnlyContainer:e,words:i}}_onAfterRefresh(){this.updateState(this._lastTickTime)}async tick(t){return this.updateState(t),super.tick(t)}updateState(t){this._lastTickTime=t;const e=t/1e3;this.wordTexts.forEach(i=>{const s=this._words[i.segmentIndex];if(!s)return;i.scale.set(1,1);const r=e>=s.from&&e<s.to,o=e>=s.to,a=!r&&!o,n=this._wordAnimation;let c=0,h=!1;if(n&&n.application!=="none"&&((n.application==="active"&&r||n.application==="keyword"&&s.isKeyWord)&&(h=!0),h)){if(n.mode==="dynamic"&&r){const y=s.to-s.from;if(y>0){const C=Math.max(0,Math.min(1,(e-s.from)/y));c=n.value<1?C:Math.sin(C*Math.PI)}else c=1}else c=1;if(n.type==="scale"){const y=n.value<1&&n.mode==="dynamic"&&r?n.value+(1-n.value)*c:1+(n.value-1)*c;i.scale.set(y,y)}}let d=16777215,f=1;if(s.isKeyWord&&!Dt(this._keywordColor)&&(r||o&&this._keywordPreserveAfterSpoken))({color:d,alpha:f}=Ft(this._keywordColor,16776960));else if(r){const y=this._activeStyle.color;y&&!Dt(y)?{color:d,alpha:f}=Ft(y,16777215):(d=16777215,f=1)}else if(a){const y=this._futureStyle.color;y&&!Dt(y)?{color:d,alpha:f}=Ft(y,16777215):(d=16777215,f=1)}else{const y=this.originalOpts?.color,C=typeof y=="object"&&y!==null&&"type"in y?16777215:y;({color:d,alpha:f}=Ft(C))}if(h&&n?.type==="opacity"){const y=n.value<1&&n.mode==="dynamic"&&r?n.value+(1-n.value)*c:1+(n.value-1)*c;f*=y}i.tint=d;const p=y=>{y.label==="bgRect"||y.label==="tiktokBackground"||y.label==="containerBackground"||typeof y.label=="string"&&y.label.startsWith("bgRect_")||("alpha"in y&&(y.alpha=f),y.children&&y.children.forEach(p))};i.children.forEach(p);const g=i.parent,v=`bgRect_${i.segmentIndex}`,x=g?g.getChildByLabel(v):null,w=r?this._activeStyle.background??"":"";if(r&&!!w&&!Dt(w)&&w!=="none"&&g){const{color:y,alpha:C}=Ft(w,16753920),k=15,O=40,F=i.scale.x,b=(i.getLocalBounds().width||i.width)*F,S=(this.originalOpts?.fontSize??40)*F,A=i.x,E=i.y+9,P=x??new m.Graphics;P.label=v,P.clear(),P.roundRect(A-O/2,E-k/2,b+O,S+k,10),P.fill({color:y,alpha:C}),P.tint=16777215,x||g.addChildAt(P,0)}else x&&g&&(g.removeChild(x),x.destroy())})}async clone(){await this.ready;const t=new mt(this.text,{...this.originalOpts,words:[...this._words]});return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}toJSON(t=!1){const e=super.toJSON(t),i=this.originalOpts??{},s={};i.fontSize!==void 0&&(s.fontSize=i.fontSize),i.fontFamily!==void 0&&(s.fontFamily=i.fontFamily),i.fontWeight!==void 0&&(s.fontWeight=i.fontWeight),i.fontStyle!==void 0&&(s.fontStyle=i.fontStyle),i.color!==void 0&&(s.color=i.color),i.align!==void 0&&(s.align=i.align),i.textCase!==void 0&&(s.textCase=i.textCase),i.fontUrl!==void 0&&(s.fontUrl=i.fontUrl),i.verticalAlign!==void 0&&(s.verticalAlign=i.verticalAlign),i.wordWrapWidth!==void 0&&(s.wordWrapWidth=i.wordWrapWidth),i.wordWrap!==void 0&&(s.wordWrap=i.wordWrap),i.wordAnimation!==void 0&&(s.wordAnimation=i.wordAnimation),i.stroke&&(typeof i.stroke=="object"?s.stroke={color:i.stroke.color,width:i.stroke.width}:s.stroke={color:i.stroke,width:i.strokeWidth??0}),i.shadow&&(s.shadow={color:i.shadow.color??"#000000",alpha:i.shadow.alpha??.5,blur:i.shadow.blur??4,offsetX:i.shadow.offsetX??0,offsetY:i.shadow.offsetY??0});const r={};this._words.length>0&&(r.words=this._words);const o={};i.activeStyle&&(o.active=i.activeStyle),i.futureStyle&&(o.future=i.futureStyle),i.keywordColor&&(o.keyword={color:i.keywordColor,preserveAfterSpoken:i.keywordPreserveAfterSpoken}),Object.keys(o).length>0&&(r.colors=o),i.wordAnimation!==void 0&&(r.wordAnimation=i.wordAnimation);const a={};return i.videoWidth!==void 0&&(a.videoWidth=i.videoWidth),i.videoHeight!==void 0&&(a.videoHeight=i.videoHeight),i.bottomOffset!==void 0&&(a.bottomOffset=i.bottomOffset),Object.keys(a).length>0&&(r.positioning=a),{...e,type:"Caption",text:this.text,style:s,caption:Object.keys(r).length>0?r:void 0,id:this.id,effects:this.effects,mediaId:this.mediaId,wordsPerLine:this.wordsPerLine,fontUrl:i.fontUrl}}static async fromObject(t,e){if(t.type!=="Caption")throw new Error(`Expected Caption, got ${t.type}`);const i=e?.captionConfig,s=t.text||"",r={...i?.style??{},...t.style??{}},o={};r.fontSize!==void 0&&(o.fontSize=r.fontSize),r.fontFamily!==void 0&&(o.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(o.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(o.fontStyle=r.fontStyle),r.color!==void 0?o.color=r.color:r.fill!==void 0&&(o.color=r.fill),r.align!==void 0&&(o.align=r.align),r.textCase!==void 0&&(o.textCase=r.textCase),r.verticalAlign!==void 0&&(o.verticalAlign=r.verticalAlign),r.wordWrapWidth!==void 0&&(o.wordWrapWidth=r.wordWrapWidth),r.wordWrap!==void 0&&(o.wordWrap=r.wordWrap),r.wordAnimation!==void 0&&(o.wordAnimation=r.wordAnimation),r.fontUrl!==void 0?o.fontUrl=r.fontUrl:t.fontUrl!==void 0&&(o.fontUrl=t.fontUrl);const a=h=>h!=null&&h!=="";a(r.wordsPerLine)?o.wordsPerLine=r.wordsPerLine:a(t.wordsPerLine)&&(o.wordsPerLine=t.wordsPerLine);const n=r;if(n.lineHeight!==void 0&&(o.lineHeight=n.lineHeight),n.letterSpacing!==void 0&&(o.letterSpacing=n.letterSpacing),o.textCase===void 0&&t.textCase!==void 0&&(o.textCase=t.textCase),n.background&&typeof n.background=="object")o.background={...n.background};else if(a(n.backgroundColor)&&n.backgroundColor!=="transparent"){const h=Number(n.padding);o.background={color:n.backgroundColor,opacity:n.backgroundOpacity??.7,borderRadius:n.borderRadius??8,paddingX:Number.isFinite(h)?h:10,paddingY:Number.isFinite(h)?Math.round(h*.6):6}}if(t.mediaId&&(o.mediaId=t.mediaId),r.stroke&&(o.stroke=r.stroke.color,o.strokeWidth=r.stroke.width),r.shadow&&(o.shadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,offsetX:r.shadow.offsetX??0,offsetY:r.shadow.offsetY??0}),t.caption){const h={...t.caption};!h.colors&&i?.colors&&(h.colors=i.colors),!h.positioning&&i?.positioning&&(h.positioning=i.positioning),o.caption=h,t.caption.wordAnimation&&(o.wordAnimation=t.caption.wordAnimation)}else i&&(o.caption={colors:i.colors,positioning:i.positioning});o.initialLayoutApplied=!0;const c=new mt(s,o);return X.deserializeBaseProperties(c,t),c.wordsPerLine=(a(t.wordsPerLine)?t.wordsPerLine:void 0)??i?.wordsPerLine??"multiple",t.effects&&(c.effects=t.effects),await c.ready,c}getVisibleHandles(){return["mr","mb","br","rot"]}}let It=class vt extends X{type="Image";ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];getVisibleHandles(){return["tl","tr","bl","br","rot"]}static async fromUrl(t,e){let i=null,s;if(t.startsWith("blob:"))try{const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch image: ${o.status} ${o.statusText}`);const a=await o.blob();s=await createImageBitmap(a);try{i=m.Texture.from(s)}catch(n){Q.warn("Failed to create Pixi texture from bitmap:",n)}}catch(o){throw Q.error(`Failed to load blob image from ${t}`,o),o}else s=await yt.getImageBitmap(t);if(!s)throw new Error(`Failed to load image from ${t}`);const r=new vt(s,e||t);return i&&(r.pixiTexture=i),r}getTexture(){return this.pixiTexture}constructor(t,e){super(),this.src=e!==void 0?e:"";const i=s=>{this.img=s,this._meta.width=s.width,this._meta.height=s.height,this._meta.duration=1/0;const r={...this._meta};return this.width=this.width===0?r.width:this.width,this.height=this.height===0?r.height:this.height,this.duration===0&&r.duration!==1/0&&(this.duration=r.duration,this.display.to=this.display.from+this.duration),r};if(t instanceof ReadableStream)this.ready=new Response(t).blob().then(s=>createImageBitmap(s)).then(i);else if(t instanceof ImageBitmap)this.ready=Promise.resolve(i(t));else if(Array.isArray(t)&&t.every(s=>s instanceof VideoFrame)){this.frames=t;const s=this.frames[0];if(s==null)throw Error("The frame count must be greater than 0");this._meta={width:s.displayWidth,height:s.displayHeight,duration:this.frames.reduce((o,a)=>o+(a.duration??0),0)};const r={...this._meta,duration:1/0};this.width=this.width===0?r.width:this.width,this.height=this.height===0?r.height:this.height,this.duration===0&&r.duration!==1/0&&(this.duration=r.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(r)}else if("type"in t)this.ready=this.initAnimateImg(t.stream,t.type).then(()=>{const s={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?s.width:this.width,this.height=this.height===0?s.height:this.height,this.duration===0&&s.duration!==1/0&&(this.duration=s.duration,this.display.to=this.display.from+this.duration),s});else throw Error("Illegal arguments")}async initAnimateImg(t,e){this.frames=await _i(t,e);const i=this.frames[0];if(i==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((s,r)=>s+(r.duration??0),0),width:i.codedWidth,height:i.codedHeight},Q.info("Image ready:",this._meta)}tickInterceptor=async(t,e)=>e;async tick(t){if(this.img!=null)return await this.tickInterceptor(t,{video:await createImageBitmap(this.img),state:"success"});const e=t%this._meta.duration;return await this.tickInterceptor(t,{video:(this.frames.find(i=>e>=i.timestamp&&e<=i.timestamp+(i.duration??0))??this.frames[0]).clone(),state:"success"})}async split(t){if(await this.ready,this.img!=null)return[new vt(await createImageBitmap(this.img),this.src),new vt(await createImageBitmap(this.img),this.src)];let e=-1;for(let r=0;r<this.frames.length;r++){const o=this.frames[r];if(!(t>o.timestamp)){e=r;break}}if(e===-1)throw Error("Not found frame by time");const i=this.frames.slice(0,e).map(r=>new VideoFrame(r)),s=this.frames.slice(e).map(r=>new VideoFrame(r,{timestamp:r.timestamp-t}));return[new vt(i,this.src),new vt(s,this.src)]}async clone(){await this.ready;const t=this.img==null?this.frames.map(i=>i.clone()):await createImageBitmap(this.img),e=new vt(t,this.src);return e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e.id=this.id,e.effects=[...this.effects],e.transition=this.transition,e}addEffect(t){this.effects.push(t)}editEffect(t,e){const i=this.effects.find(s=>s.id===t);i&&Object.assign(i,e)}removeEffect(t){const e=this.effects.findIndex(i=>i.id===t);e!==-1&&this.effects.splice(e,1)}destroy(){Q.info("Image destroy"),this.img?.close(),this.frames.forEach(t=>t.close()),this.pixiTexture=null,super.destroy()}toJSON(t=!1){return{...super.toJSON(t),type:"Image",id:this.id,effects:this.effects}}static async fromObject(t){if(t.type!=="Image")throw new Error(`Expected Image, got ${t.type}`);if(!t.src||t.src.trim()==="")throw new Error("Image requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let e;try{const i=await yt.getImageBitmap(t.src);e=new vt(i,t.src)}catch(i){throw i instanceof Error&&i.message.includes("could not be decoded")?new Error(`Failed to decode image from ${t.src}. The image may be decoded, in an unsupported format, or there may be CORS issues.`):i}return X.deserializeBaseProperties(e,t),t.effects&&(e.effects=t.effects),e}};function oe(l,t){const e={},i=t.videoTracks[0];if(i!=null){const r=fs(l.getTrackById(i.id))?.buffer,o=us(i.codec);o&&(e.videoTrackConf={timescale:i.timescale,duration:i.duration,width:i.video.width,height:i.video.height,brands:t.brands,type:o.type,[o.descKey]:r}),e.videoDecoderConf={codec:i.codec,codedHeight:i.video.height,codedWidth:i.video.width,description:r}}const s=t.audioTracks[0];if(s!=null){const r=ps(l),o=r?ms(r):{};e.audioTrackConf={timescale:s.timescale,samplerate:o.sampleRate??s.audio.sample_rate,channel_count:o.numberOfChannels??s.audio.channel_count,hdlr:"soun",type:s.codec.startsWith("mp4a")?"mp4a":s.codec,description:r};const a=s.codec.startsWith("mp4a")?s.codec:o.codec??(s.codec==="Opus"||s.codec==="opus"?"opus":s.codec);e.audioDecoderConf={codec:a,numberOfChannels:o.numberOfChannels??s.audio.channel_count,sampleRate:o.sampleRate??s.audio.sample_rate,...o.description?{description:o.description}:{}}}return e}function us(l){return l.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:l.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:null}function fs(l){for(const t of l.mdia.minf.stbl.stsd.entries){const e=t.avcC??t.hvcC??t.av1C??t.vpcC;if(e!=null){const i=new et.mp4box.DataStream(void 0,0,void 0);return e.write(i),new Uint8Array(i.buffer.slice(8))}}}function ps(l,t="mp4a"){const e=l.moov?.traks.flatMap(i=>i.mdia.minf.stbl.stsd.entries).find(i=>i.type===t);return e?.esds??e}function ms(l){const t=l.esd?.descs?.[0];if(!t)return{};let e=`mp4a.${t.oti.toString(16)}`;const i=t.descs?.[0];if(!i)return e.endsWith(".40")&&(e+=".2"),{codec:e};const s=i.data;if(!s)return{codec:e};const r=(s[0]&248)>>3;e+=`.${r}`;const o=(s[0]&7)<<1|s[1]>>7,a=(s[1]&120)>>3;return{codec:e,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][o],numberOfChannels:a,description:s}}async function gs(l,t,e){const i=et.mp4box.createFile(!1);i.onReady=o=>{t({mp4boxFile:i,info:o}),[o.videoTracks[0],o.audioTracks[0]].forEach(a=>{if(a){const n=a.video?"video":"audio";i.setExtractionOptions(a.id,n,{nbSamples:100})}}),i.start()},i.onSamples=e;let s=0;const r=30*1024*1024;for(;;){const o=await l.read(r,{at:s});if(o.byteLength===0)break;o.fileStart=s;const a=i.appendBuffer(o);if(a==null)break;s=a}i.stop()}function vs(l){if(l?.length!==9)return{};const t=new Int32Array(l.buffer),e=h=>h/65536,i=e(t[0]),s=e(t[1]),r=e(t[3]),o=e(t[4]),a=e(t[6]),n=e(t[7]),c=t[8]/(1<<30);return{scaleX:Math.sqrt(i*i+r*r),scaleY:Math.sqrt(s*s+o*o),rotationRad:Math.atan2(r,i),rotationDeg:Math.atan2(r,i)*180/Math.PI,translateX:a,translateY:n,perspective:c}}function ys(l,t,e){const i=(Math.round(e/90)*90+360)%360;if(i===0)return c=>c;const s=i===90||i===270,r=s?t:l,o=s?l:t,a=new OffscreenCanvas(r,o),n=a.getContext("2d");return n.translate(r/2,o/2),n.rotate(-i*Math.PI/180),n.translate(-l/2,-t/2),c=>{if(!c)return null;n.drawImage(c,0,0);const h=new VideoFrame(a,{timestamp:c.timestamp,duration:c.duration??void 0});return c.close(),h}}let ne=0;function ae(l){return l.kind==="file"&&l.createReader instanceof Function}class nt extends X{type="Video";insId=ne++;logger=Q.create(`Video id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const t=await this.localFile.getOriginFile();if(t==null)throw Error("Video localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:e,size:i})=>t.slice(e,e+i))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=t=>t;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;onEffectiveVolumeChange(){this.audioFrameFinder?.setVolume(this.effectiveVolume)}decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];getVisibleHandles(){return["tl","tr","bl","br","rot"]}static async fromUrl(t,e={}){const i=await yt.getReadableStream(t),s=new nt(i,{},t);return await s.ready,e.x!==void 0&&(s.left=e.x),e.y!==void 0&&(s.top=e.y),e.width!==void 0&&(s.width=e.width),e.height!==void 0&&(s.height=e.height),s}constructor(t,e={},i){if(super(),this.src=i!==void 0?i:"",!(t instanceof ReadableStream)&&!ae(t)&&!Array.isArray(t.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...e},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof e.audio=="object"&&"volume"in e.audio?e.audio.volume:e.volume??1;const s=async r=>(await it.write(this.localFile,r),this.localFile);this.localFile=ae(t)?t:"localFile"in t?t.localFile:it.tmpfile(),this.ready=(t instanceof ReadableStream?s(t).then(r=>Xe(r,this.opts)):ae(t)?Xe(t,this.opts):Promise.resolve(t)).then(async({videoSamples:r,audioSamples:o,decoderConf:a,headerBoxPos:n,parsedMatrix:c})=>{this.videoSamples=r,this.audioSamples=o,this.decoderConf=a,this.headerBoxPos=n,this.parsedMatrix=c;const{videoFrameFinder:h,audioFrameFinder:d}=ws({video:a.video==null?null:{...a.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:a.audio},await this.localFile.createReader(),r,o,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=h,this.audioFrameFinder=d,this.effectiveVolume!==this.volume&&this.audioFrameFinder?.setVolume(this.effectiveVolume);const{codedWidth:f,codedHeight:u}=a.video??{};f&&u&&(this.vfRotater=ys(f,u,c.rotationDeg)),this._meta=xs(a,r,o,c.rotationDeg),this.logger.info("Video meta:",this._meta);const p={...this._meta};this.width=this.width===0?p.width:this.width,this.height=this.height===0?p.height:this.height,this.trim.to=this.trim.to===0?p.duration:Math.min(this.trim.to,p.duration),this.trim.from=Math.min(this.trim.from,this.trim.to);const g=(this.trim.to-this.trim.from)/this.playbackRate;return this.duration=this.duration===0?g:this.duration,Math.abs(this.duration-g)>1&&(this.duration=g),this.display.to=this.display.from+this.duration,this.on("propsChange",v=>{(v.volume!==void 0||v.muted!==void 0)&&this.audioFrameFinder&&this.audioFrameFinder.setVolume(this.effectiveVolume)}),p})}tickInterceptor=async(t,e)=>e;async tick(t){const e=t+this.trim.from;if(e>this.trim.to||e>this._meta.duration)return await this.tickInterceptor(t,{audio:await this.audioFrameFinder?.find(e)??[],state:"done"});const[i,s]=await Promise.all([this.audioFrameFinder?.find(e)??[],this.videoFrameFinder?.find(e).then(this.vfRotater)]);return s==null?await this.tickInterceptor(t,{audio:i,state:"success"}):await this.tickInterceptor(t,{video:s,audio:i,state:"success"})}addEffect(t){this.effects.push(t)}editEffect(t,e){const i=this.effects.find(s=>s.id===t);i&&Object.assign(i,e)}removeEffect(t){const e=this.effects.findIndex(i=>i.id===t);e!==-1&&this.effects.splice(e,1)}async split(t){throw new Error("Video.split is not implemented - use core state instead")}async clone(){await this.ready;const t=new nt({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await t.ready,t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("Video destroy"),super.destroy(),this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(t=!1){return{...super.toJSON(t),type:"Video",audio:this.audio,volume:this.volume,id:this.id,effects:this.effects}}static async fromObject(t){if(t.type!=="Video")throw new Error(`Expected Video, got ${t.type}`);const e=t.audio!==void 0?{audio:t.audio,volume:t.volume}:{volume:t.volume},i=await yt.getReadableStream(t.src),s=new nt(i,e,t.src);return X.deserializeBaseProperties(s,t),t.effects&&(s.effects=t.effects),t.volume!==void 0&&(s.volume=t.volume),s}async createPlaybackElement(){await this.ready;const e=this.localFile;if(!e||typeof e.getOriginFile!="function")throw new Error("Video does not have a local file for playback");const i=await e.getOriginFile();if(!i)throw new Error("Failed to get origin file from VideoClip");const s=URL.createObjectURL(i),r=document.createElement("video");return r.crossOrigin="anonymous",r.muted=!0,r.autoplay=!1,r.playsInline=!0,r.preload="auto",r.loop=!1,r.src=s,await new Promise((o,a)=>{const n=()=>{r.removeEventListener("loadeddata",n),r.removeEventListener("error",c),r.pause(),r.currentTime=0,o()},c=()=>{r.removeEventListener("loadeddata",n),r.removeEventListener("error",c),a(new Error("Failed to load video"))};r.addEventListener("loadeddata",n,{once:!0}),r.addEventListener("error",c,{once:!0}),r.load()}),{element:r,objectUrl:s}}async play(t,e){const i=t,s=e+this.trim.from/1e6;if(Math.abs(i.currentTime-s)>.1&&(i.currentTime=s),i.muted=!1,i.paused)try{await i.play()}catch{try{await i.play()}catch(o){console.warn("Failed to play video:",o)}}}pause(t){const e=t;e.pause(),e.muted=!0}async seek(t,e){const i=t,s=e+this.trim.from/1e6;i.pause(),i.currentTime=s,i.addEventListener("seeked",()=>{i.__pendingRender?.()},{once:!0})}syncPlayback(t,e,i){const s=t,r=this.duration&&this.duration!==1/0?this.duration/1e6:(this.display.to-this.display.from)/1e6,o=i>=0&&i<r,a=i+this.trim.from/1e6,n=r*1e3,c=i*1e3;let h=1;if(this.timing.fadeIn&&this.timing.fadeIn.duration>0&&c<this.timing.fadeIn.duration&&(h*=Ct(c/this.timing.fadeIn.duration,this.timing.fadeIn.curve)),this.timing.fadeOut&&this.timing.fadeOut.duration>0){const d=n-this.timing.fadeOut.duration;if(c>=d){const f=1-(c-d)/this.timing.fadeOut.duration;h*=Ct(f,this.timing.fadeOut.curve)}}s.volume=Math.max(0,Math.min(1,this.effectiveVolume*h)),e&&o?s.paused?this.play(s,i).catch(console.warn):(s.muted&&(s.muted=!1),(s.ended||s.currentTime>=this.trim.to/1e6)&&(s.currentTime=a,s.play().catch(console.warn))):(s.paused||s.pause(),s.muted=!0,o&&Math.abs(s.currentTime-a)>.1&&(s.currentTime=a))}cleanupPlayback(t,e){const i=t;i.pause(),i.removeAttribute("src"),i.load(),e&&URL.revokeObjectURL(e)}async scaleToFit(t,e){await this.ready;const{width:i,height:s}=this.meta;if(i===0||s===0)return;const r=Math.min(t/i,e/s);this.width=i*r,this.height=s*r}async scaleToFill(t,e){await this.ready;const{width:i,height:s}=this.meta;if(i===0||s===0)return;const r=Math.max(t/i,e/s);this.width=i*r,this.height=s*r}centerInScene(t,e){this.left=(t-this.width)/2,this.top=(e-this.height)/2}}function xs(l,t,e,i){const s={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(l.video!=null&&t.length>0){s.width=l.video.codedWidth??0,s.height=l.video.codedHeight??0;const a=(Math.round(i/90)*90+360)%360;(a===90||a===270)&&([s.width,s.height]=[s.height,s.width])}l.audio!=null&&e.length>0&&(s.audioSampleRate=L.sampleRate,s.audioChanCount=L.channelCount);let r=0,o=0;if(t.length>0)for(let a=t.length-1;a>=0;a--){const n=t[a];if(!n.deleted){r=n.cts+n.duration;break}}if(e.length>0){const a=e.at(-1);o=a.cts+a.duration}return s.duration=Math.max(r,o),s}function ws(l,t,e,i,s){return{audioFrameFinder:s===0||l.audio==null||i.length===0?null:new Ts(t,i,l.audio,{volume:s,targetSampleRate:L.sampleRate}),videoFrameFinder:l.video==null||e.length===0?null:new bs(t,e,l.video)}}async function Xe(l,t={}){let e=null;const i={video:null,audio:null};let s=[],r=[],o=[];const a={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let n=-1,c=-1;const h=await l.createReader();await gs(h,async f=>{e=f.info;const u=f.mp4boxFile.ftyp;o.push({start:u.start,size:u.size});const p=f.mp4boxFile.moov;o.push({start:p.start,size:p.size}),Object.assign(a,vs(e.videoTracks[0]?.matrix));let{videoDecoderConf:g,audioDecoderConf:v}=oe(f.mp4boxFile,f.info);if(i.video=g??null,i.audio=v??null,g==null&&v==null&&Q.error("Video no video and audio track"),v!=null){const{supported:x}=await AudioDecoder.isConfigSupported(v);x||Q.error(`Video audio codec is not supported: ${v.codec}`)}if(g!=null){const{supported:x}=await VideoDecoder.isConfigSupported(g);x||Q.error(`Video video codec is not supported: ${g.codec}`)}Q.info("mp4BoxFile moov ready",{...f.info,tracks:null,videoTracks:null,audioTracks:null},i)},(f,u,p)=>{if(u==="video"){n===-1&&(n=p[0].dts);for(const g of p)s.push(qe(g,n,"video"))}else if(u==="audio"&&t.audio){c===-1&&(c=p[0].dts);for(const g of p)r.push(qe(g,c,"audio"))}}),await h.close();const d=s.at(-1)??r.at(-1);if(e==null)throw Error("Video stream is done, but not emit ready");if(d==null)throw Error("Video stream not contain any sample");return Os(s),Q.info("mp4 stream parsed"),{videoSamples:s,audioSamples:r,decoderConf:i,headerBoxPos:o,parsedMatrix:a}}function qe(l,t=0,e){let i=l.offset;const s=e==="video"&&l.is_sync?Rs(l.data,l.description.type):-1;let r=l.size;return s>0&&(i+=s,r-=s),{...l,is_idr:s>=0,offset:i,size:r,cts:(l.cts-t)/l.timescale*1e6,dts:(l.dts-t)/l.timescale*1e6,duration:l.duration/l.timescale*1e6,timescale:1e6,data:e==="video"?null:l.data}}class bs{constructor(t,e,i){this.localFileReader=t,this.samples=e,this.conf=i}localFileReader;samples;conf;decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async t=>{(this.decoder==null||this.decoder.state==="closed"||t<this.timestamp||t-this.timestamp>3e6)&&this.reset(t),this.curAborter.abort=!0,this.timestamp=t,this.curAborter={abort:!1,st:performance.now()};const e=await this.parseFrame(t,this.decoder,this.curAborter);return this.sleepCnt=0,e};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;_firstPresentableTs=null;firstPresentableTs(){if(this._firstPresentableTs!=null)return this._firstPresentableTs;let t=this.samples.findIndex(i=>i.is_idr&&!i.deleted);t<0&&(t=0);let e=1/0;for(let i=t;i<this.samples.length;i++){const s=this.samples[i];if(i>t&&s.is_idr)break;!s.deleted&&s.cts<e&&(e=s.cts)}return this._firstPresentableTs=Number.isFinite(e)?e:0,this._firstPresentableTs}parseFrame=async(t,e,i)=>{if(e==null||e.state==="closed"||i.abort)return null;if(this.videoFrames.length>0){const s=this.videoFrames[0];return t<s.timestamp?t<=0||s.timestamp<=this.firstPresentableTs()?new VideoFrame(s):null:(this.videoFrames.shift(),t>s.timestamp+(s.duration??0)?(s.close(),await this.parseFrame(t,e,i)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(e).catch(r=>{throw this.predecodeErr=!0,this.reset(t),r}),s))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&e.decodeQueueSize>0){if(performance.now()-i.st>6e3)throw Error(`Video.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await Ae(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(e)}catch(s){throw this.reset(t),s}}return await this.parseFrame(t,e,i)};decoding=!1;startDecode=async t=>{if(this.decoding||t.decodeQueueSize>600)return;let e=this.videoDecCursorIdx+1;if(e>this.samples.length)return;this.decoding=!0;let i=!1;for(;e<this.samples.length;e++){const s=this.samples[e];if(!i&&!s.deleted&&(i=!0),s.is_idr)break}if(i){const s=this.samples.slice(this.videoDecCursorIdx,e);if(s[0]?.is_idr!==!0)Q.warn("First sample not idr frame");else{const r=performance.now(),o=await ks(s,this.localFileReader),a=performance.now()-r;if(a>1e3){const n=s[0],c=s.at(-1),h=c.offset+c.size-n.offset;Q.warn(`Read video samples time cost: ${Math.round(a)}ms, file chunk size: ${h}`)}if(t.state==="closed")return;this.lastVfDur=o[0]?.duration??0,Fs(t,o,{onDecodingError:n=>{if(this.downgradeSoftDecode)throw n;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,Q.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=o.length}}this.videoDecCursorIdx=e,this.decoding=!1};reset=t=>{if(this.decoding=!1,this.videoFrames.forEach(i=>i.close()),this.videoFrames=[],t==null||t===0)this.videoDecCursorIdx=0;else{let i=0;for(let s=0;s<this.samples.length;s++){const r=this.samples[s];if(r.is_idr&&(i=s),!(r.cts<t)){this.videoDecCursorIdx=i;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const e={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:i=>{if(this.outputFrameCnt+=1,i.timestamp===-1){i.close();return}let s=i;i.duration==null&&(s=new VideoFrame(i,{duration:this.lastVfDur}),i.close()),this.videoFrames.push(s)},error:i=>{if(i.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,Q.warn(i.message);return}const s=`VideoFinder VideoDecoder err: ${i.message}, config: ${JSON.stringify(e)}, state: ${JSON.stringify(this.getState())}`;throw Q.error(s),Error(s)}}),this.decoder.configure(e)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:ne,sleepCnt:this.sleepCnt,memInfo:_e()});destroy=async()=>{if(this.curAborter.abort=!0,this.videoFrames.forEach(t=>t.close()),this.videoFrames=[],this.decoder&&this.decoder.state!=="closed")try{this.decoder.close()}catch{}this.decoder=null,this.localFileReader.close()}}function Cs(l,t){for(let e=0;e<t.length;e++){const i=t[e];if(l>=i.cts&&l<i.cts+i.duration)return e;if(i.cts>l)break}return 0}class Ts{constructor(t,e,i,s){this.localFileReader=t,this.samples=e,this.conf=i,this.volume=s.volume,this.sampleRate=s.targetSampleRate}localFileReader;samples;conf;volume=1;sampleRate;setVolume(t){this.volume=t,this.reset()}decoder=null;curAborter={abort:!1,st:performance.now()};find=async t=>{const e=t<=this.timestamp||t-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||e)&&this.reset(),e&&(this.timestamp=t,this.decCursorIdx=Cs(t,this.samples)),this.curAborter.abort=!0;const i=t-this.timestamp;this.timestamp=t,this.curAborter={abort:!1,st:performance.now()};const s=await this.parseFrame(Math.ceil(i*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,s};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(t,e=null,i)=>{if(e==null||i.abort||e.state==="closed"||t===0)return[];const s=this.pcmData.frameCnt-t;if(s>0)return s<L.sampleRate/10&&this.startDecode(e),le(this.pcmData,t);if(e.decoding){if(performance.now()-i.st>6e4)return console.warn("[Video.tick] Audio decode wait exceeded 60s, using the PCM decoded so far",this.getState()),this.pcmData.frameCnt>0?le(this.pcmData,this.pcmData.frameCnt):[];this.sleepCnt+=1,await Ae(15)}else{if(this.decCursorIdx>=this.samples.length-1)return le(this.pcmData,this.pcmData.frameCnt);this.startDecode(e)}return this.parseFrame(t,e,i)};startDecode=t=>{if(t.decodeQueueSize>10)return;const i=[];let s=this.decCursorIdx;for(;s<this.samples.length;){const r=this.samples[s];if(s+=1,!r.deleted&&(i.push(r),i.length>=10))break}this.decCursorIdx=s,t.decode(i.map(r=>new EncodedAudioChunk({type:"key",timestamp:r.cts,duration:r.duration,data:r.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=Ss(this.conf,{resampleRate:L.sampleRate,volume:this.volume},t=>{this.pcmData.data.push(t),this.pcmData.frameCnt+=t[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:ne,sleepCnt:this.sleepCnt,memInfo:_e()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function Ss(l,t,e){let i=0,s=0;const r=h=>{if(s+=1,h.length!==0){if(t.volume!==1)for(const d of h)for(let f=0;f<d.length;f++)d[f]*=t.volume;h.length===1&&(h=[h[0],h[0]]),e(h)}},o=As(r),a=t.resampleRate!==l.sampleRate;let n=new AudioDecoder({output:h=>{const d=be(h);a?o(()=>Fi(d,h.sampleRate,{rate:t.resampleRate,chanCount:h.numberOfChannels})):r(d),h.close()},error:h=>{h.message.includes("Codec reclaimed due to inactivity")||c("Video AudioDecoder err",h)}});n.configure(l);function c(h,d){const f=`${h}: ${d.message}, state: ${JSON.stringify({qSize:n.decodeQueueSize,state:n.state,inputCnt:i,outputCnt:s,decoderConf:l,opts:t})}`;throw Q.error(f),Error(f)}return{decode(h){i+=h.length;try{for(const d of h)n.decode(d)}catch(d){c("decode audio chunk error",d)}},close(){n.state!=="closed"&&n.close()},get decoding(){return i>s&&n.decodeQueueSize>0},get state(){return n.state},get decodeQueueSize(){return n.decodeQueueSize}}}function As(l){const t=[];let e=0;function i(o,a){t[a]=o,s()}function s(){const o=t[e];o!=null&&(l(o),e+=1,s())}let r=0;return o=>{const a=r;r+=1,o().then(n=>i(n,a)).catch(n=>i(n,a))}}function le(l,t){const e=[new Float32Array(t),new Float32Array(t)];let i=0,s=0;for(;s<l.data.length;){const[r,o]=l.data[s];if(i+r.length>t){const a=t-i;e[0].set(r.subarray(0,a),i),e[1].set(o.subarray(0,a),i),l.data[s][0]=r.subarray(a,r.length),l.data[s][1]=o.subarray(a,o.length);break}else e[0].set(r,i),e[1].set(o,i),i+=r.length,s++}return l.data=l.data.slice(s),l.frameCnt-=t,e}async function ks(l,t){const e=l[0],i=l.at(-1);if(i==null)return[];const s=i.offset+i.size-e.offset;if(s<3e7){const r=new Uint8Array(await t.read(s,{at:e.offset}));return l.map(o=>{const a=o.offset-e.offset;return new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:r.subarray(a,a+o.size)})})}return await Promise.all(l.map(async r=>new EncodedVideoChunk({type:r.is_sync?"key":"delta",timestamp:r.cts,duration:r.duration,data:await t.read(r.size,{at:r.offset})})))}function Fs(l,t,e){if(l.state==="configured"){for(let i=0;i<t.length;i++)l.decode(t[i]);l.flush().catch(i=>{if(!(i instanceof Error))throw i;if(i.message.includes("Decoding error")&&e.onDecodingError!=null){e.onDecodingError(i);return}if(!i.message.includes("Aborted due to close"))throw i})}}function Rs(l,t){if(t!=="avc1"&&t!=="hvc1")return 0;const e=new DataView(l.buffer);for(let i=0;i<l.byteLength-4;){if(t==="avc1"){const s=e.getUint8(i+4)&31;if(s===5||s===7||s===8)return i}else if(t==="hvc1"){const s=e.getUint8(i+4)>>1&63;if(s===19||s===20||s===32||s===33||s===34)return i}i+=e.getUint32(i)+4}return-1}const Ms=2e5;function Os(l){let t=null,e=0;for(const i of l)if(!i.deleted){if(i.is_sync&&e++,e>=2)break;i.is_sync&&(t==null||i.cts<t.cts)&&(t=i)}t!=null&&t.cts<Ms&&(t.duration+=t.cts,t.cts=0)}function _e(){try{const l=performance.memory;return{jsHeapSizeLimit:l.jsHeapSizeLimit,totalJSHeapSize:l.totalJSHeapSize,usedJSHeapSize:l.usedJSHeapSize,percentUsed:(l.usedJSHeapSize/l.jsHeapSizeLimit).toFixed(3),percentTotal:(l.totalJSHeapSize/l.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}class at extends Ke{type="Text";get width(){return this._width}set width(t){Math.abs(this.width-t)<.1||(this._width=t,this._targetWidth=t,this.refreshText().then(()=>{this._explicitHeight?this.emit("propsChange",{width:t}):this.emit("propsChange",{width:t,height:this.height})}))}get height(){return this._height}_explicitHeight=!1;get isExplicitHeight(){return this._explicitHeight}resetHeightToAuto(){this._explicitHeight=!1,this._height=0,this.refreshText().then(()=>{this.emit("propsChange",{height:this.height})})}set height(t){if(Math.abs(this.height-t)<.1)return;const e=t;this._height=t,this.refreshText().then(()=>{const i=this.meta.height,r=e-i<-5;this._explicitHeight=e>0&&(r||this._explicitHeight),this.emit("propsChange",{height:this.height})})}get text(){return this._text}set text(t){this._text!==t&&(this._text=t,this.originalOpts&&this.textStyle&&this.refreshText().then(()=>{this.emit("propsChange",{text:t})}))}get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontUrl:this.originalOpts.fontUrl,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,color:this.originalOpts.color,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,shadow:this.originalOpts.shadow?{color:this.originalOpts.shadow.color??"#000000",alpha:this.originalOpts.shadow.alpha??.5,blur:this.originalOpts.shadow.blur??4,offsetX:this.originalOpts.shadow.offsetX??0,offsetY:this.originalOpts.shadow.offsetY??0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing,textCase:this.originalOpts.textCase,textDecoration:this.originalOpts.textDecoration,background:this.originalOpts.background}}set style(t){this.updateStyle(t)}get textAlign(){return this.originalOpts.align||this.originalOpts.textAlign||"left"}set textAlign(t){this.updateStyle({align:t})}get verticalAlign(){return this.originalOpts.verticalAlign||this.originalOpts.textDecoration||"top"}set verticalAlign(t){["underline","overline","strikethrough","line-through"].includes(t)?(this.updateStyle({textDecoration:t==="strikethrough"?"line-through":t}),this.originalOpts.verticalAlign=t):this.updateStyle({verticalAlign:t})}get textCase(){return this.originalOpts.textCase||"none"}set textCase(t){this.updateStyle({textCase:t})}get underline(){return this.originalOpts.textDecoration==="underline"}set underline(t){this.updateStyle({textDecoration:t?"underline":"none"})}get overline(){return this.originalOpts.textDecoration==="overline"}set overline(t){this.updateStyle({textDecoration:t?"overline":"none"})}get linethrough(){return this.originalOpts.textDecoration==="line-through"}set linethrough(t){this.updateStyle({textDecoration:t?"line-through":"none"})}_targetWidth=0;_wordCache=[];_measuredTextHeight=0;_lineHeightMultiplier=1;_fontSize=40;_textOnlyContainer=null;constructor(t,e={},i){super(),this.originalOpts={...e},this._text=t,i&&this.setRenderer(i),this._buildTextStyles(),this.ready=(async()=>(await this.refreshText(),{...this.meta}))()}_onAfterRefresh(t,e,i,s,r,o){this._populateWordCache(t,e,i,s,r,o)}async clone(){await this.ready;const t=this.textStyle,e=this.originalOpts||{},i=n=>{if(n!=null){if(typeof n=="number")return n;if(n instanceof m.Color)return n.toNumber()}},{stroke:s,strokeWidth:r}=this._cloneStrokeOpts(i),o={fontSize:e.fontSize??t.fontSize,fontFamily:e.fontFamily??(Array.isArray(t.fontFamily)?t.fontFamily[0]:typeof t.fontFamily=="string"?t.fontFamily:"Roboto"),fontUrl:e.fontUrl,fontWeight:e.fontWeight??t.fontWeight,fontStyle:e.fontStyle??t.fontStyle,align:e.align??(t.align==="justify"?"left":t.align),textCase:e.textCase,textDecoration:e.textDecoration,color:this._cloneColorOpts(i),stroke:s,strokeWidth:r,shadow:this._cloneShadowOpts(i)};if(e.wordWrap!==void 0?(o.wordWrap=e.wordWrap,o.wordWrapWidth=e.wordWrapWidth):t.wordWrap&&(o.wordWrap=t.wordWrap,o.wordWrapWidth=t.wordWrapWidth),e.background!==void 0&&(o.background=e.background),e.lineHeight!==void 0)o.lineHeight=e.lineHeight;else if(t.lineHeight!==void 0){const n=o.fontSize??t.fontSize??40;o.lineHeight=t.lineHeight/n}e.letterSpacing!==void 0?o.letterSpacing=e.letterSpacing:t.letterSpacing!==void 0&&(o.letterSpacing=t.letterSpacing);const a=new at(this.text,o);return await a.ready,this.copyStateTo(a),a.id=this.id,a.effects=[...this.effects],a}async updateStyle(t){const e=this._normalizeStyleOpts(t);this.originalOpts={...this.originalOpts,...e},this._buildTextStyles(),await this.refreshText(),this.emit("propsChange",t)}_populateWordCache(t,e,i,s,r,o){this._wordCache=this.wordTexts.map((a,n)=>({text:t[n],width:Math.ceil(a.getLocalBounds().width||a.width),height:Math.ceil(a.getLocalBounds().height||a.height),textObj:a})),this._spaceWidth=i,this._measuredTextHeight=s,this._lineHeightMultiplier=r,this._fontSize=o,this._textOnlyContainer=e}updateLayoutForWidth(t){if(!this._wordCache.length||!this._textOnlyContainer||!this.pixiTextContainer)return this._targetWidth=t,this.refreshText(),{width:this.width,height:this.height};const e=this.originalOpts.background?.paddingX??8,i=this.originalOpts.background?.paddingY??4,s=this._lineHeightMultiplier,o=this._fontSize*s,a=this._measuredTextHeight,n=this._spaceWidth,c=Math.max(1,t-e*2),h=[];let d=[],f=0,u=0;for(let A=0;A<this._wordCache.length;A++){const E=this._wordCache[A],P=E.width,R=E.height,B=f+(f>0?n:0)+P;B<=c||d.length===0?(d.push(A),f=B,u=Math.max(u,R)):(d.length>0&&h.push({wordIndices:d,width:f,height:Math.max(u,o)}),d=[A],f=P,u=R)}d.length>0&&h.push({wordIndices:d,width:f,height:Math.max(u,o)});const p=a+i*2;h.forEach(A=>{A.height=Math.max(A.height,p)});let g=0,v=0;h.forEach(A=>{g=Math.max(g,A.width),v+=A.height});const x=g+e*2,w=v,T=Math.max(x,t),y=w,C=this.textAlign,k=this.originalOpts.verticalAlign||"top";let O=0;k==="center"?O=(y-w)/2:k==="bottom"&&(O=y-w);let F=O;h.forEach(A=>{let E=0;C==="center"?E=(T-A.width)/2:C==="right"?E=T-A.width-e*2:E=e,A.wordIndices.forEach((P,R)=>{const B=this._wordCache[P];B.textObj&&(B.textObj.x=Math.round(E),B.textObj.y=Math.round(F+(A.height-a)/2-9)),E+=B.width+(R<A.wordIndices.length-1?n:0)}),F+=A.height}),this._meta.width=T,this._meta.height=y,this._width=T,this._height=y,this._targetWidth=T;const b=T+(this.renderTexturePadding??0)*2,S=y+(this.renderTexturePadding??0)*2;return this.renderTexture&&(Math.abs(this.renderTexture.width-b)>10||Math.abs(this.renderTexture.height-S)>10)&&this.getTexture(),{width:T,height:y}}toJSON(t=!1){const e=super.toJSON(t),i={};return this.originalOpts.fontSize!==void 0&&(i.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(i.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontUrl!==void 0&&(i.fontUrl=this.originalOpts.fontUrl),this.originalOpts.fontWeight!==void 0&&(i.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(i.fontStyle=this.originalOpts.fontStyle),this.originalOpts.color!==void 0&&(i.color=this.originalOpts.color),this.originalOpts.align!==void 0&&(i.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(i.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(i.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(i.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(i.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.background!==void 0&&(i.background=this.originalOpts.background),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?i.stroke={color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:i.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.shadow&&(i.shadow={color:this.originalOpts.shadow.color??"#000000",alpha:this.originalOpts.shadow.alpha??.5,blur:this.originalOpts.shadow.blur??4,offsetX:this.originalOpts.shadow.offsetX??0,offsetY:this.originalOpts.shadow.offsetY??0}),{...e,type:"Text",text:this.text,style:i,id:this.id,effects:this.effects}}static async fromObject(t){if(t.type!=="Text")throw new Error(`Expected Text, got ${t.type}`);const e=t.text||"",i=t.style||{},s={};i.fontSize!==void 0&&(s.fontSize=i.fontSize),i.fontFamily!==void 0&&(s.fontFamily=i.fontFamily),i.fontUrl!==void 0&&(s.fontUrl=i.fontUrl),i.fontWeight!==void 0&&(s.fontWeight=i.fontWeight),i.fontStyle!==void 0&&(s.fontStyle=i.fontStyle),i.color!==void 0&&(s.color=i.color),i.align!==void 0&&(s.align=i.align),i.wordWrap!==void 0&&(s.wordWrap=i.wordWrap),i.wordWrapWidth!==void 0&&(s.wordWrapWidth=i.wordWrapWidth),i.lineHeight!==void 0&&(s.lineHeight=i.lineHeight),i.letterSpacing!==void 0&&(s.letterSpacing=i.letterSpacing),i.background!==void 0&&(s.background=i.background),i.stroke&&(i.stroke.join||i.stroke.cap||i.stroke.miterLimit!==void 0?s.stroke={color:i.stroke.color,width:i.stroke.width,join:i.stroke.join,cap:i.stroke.cap,miterLimit:i.stroke.miterLimit}:(s.stroke=i.stroke.color,s.strokeWidth=i.stroke.width)),i.shadow&&(s.shadow={color:i.shadow.color,alpha:i.shadow.alpha,blur:i.shadow.blur,offsetX:i.shadow.offsetX??0,offsetY:i.shadow.offsetY??0});const r=new at(e,s);return X.deserializeBaseProperties(r,t),t.effects&&(r.effects=t.effects),await r.ready,r}getVisibleHandles(){return["mr","mb","br","rot"]}}function Es(l){return l.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,t=>t.toUpperCase())}class lt extends X{type="Effect";ready;_meta={duration:5e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effectKey;values={};constructor(t){super(),this.effectKey=t,this.name=Es(t),this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const t=new lt(this.effectKey);return this.copyStateTo(t),t.values={...this.values},t}async tick(t){return{video:void 0,state:"success"}}async split(t){const e=await this.clone(),i=await this.clone();return[e,i]}toJSON(t=!1){return{id:this.id,type:"Effect",name:this.name,timing:{display:{from:this.timing.display.from,to:this.timing.display.to},trim:{from:this.timing.trim.from,to:this.timing.trim.to},duration:this.timing.duration,playbackRate:this.timing.playbackRate},effectKey:this.effectKey,values:this.values}}static async fromObject(t){if(t.type!=="Effect")throw new Error(`Expected Effect, got ${t.type}`);const e=t.effectKey;if(!e)throw new Error("Missing effectKey in Effect JSON");const i=new lt(e);return i.values=t.values||{},X.deserializeBaseProperties(i,t),await i.ready,i}}class Bt extends X{type="Placeholder";meta={width:0,height:0,duration:0};constructor(t,e={},i="Placeholder"){super(),this.type=i,this.src=t,this.meta={width:e.width||1280,height:e.height||720,duration:e.duration||5e6},this.width=this.meta.width,this.height=this.meta.height,this.duration=this.meta.duration,this.trim.to=this.duration,this.display.to=this.display.from+this.duration,this.ready=Promise.resolve(this.meta)}canvas=null;ctx=null;animationRafId=null;renderPending=!1;async tick(t){this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.width=this.meta.width,this.canvas.height=this.meta.height,this.ctx=this.canvas.getContext("2d"));const{canvas:e,ctx:i}=this;if(i){const{width:r,height:o}=e;if(r>0&&o>0){i.fillStyle="#1e1e1e",i.fillRect(0,0,r,o);const a=r/2,n=o/2,c=100,h=c/4,d=performance.now()/2e3*Math.PI*2;i.save();const f=i.createConicGradient(d,a,n);f.addColorStop(0,"#ffffff"),f.addColorStop(.2,"#ffffff"),f.addColorStop(.5,"rgba(255, 255, 255, 0.4)"),f.addColorStop(.8,"rgba(255, 255, 255, 0.1)"),f.addColorStop(1,"rgba(255, 255, 255, 0)"),i.strokeStyle=f,i.lineWidth=h,i.lineCap="round",i.beginPath(),i.arc(a,n,c,d,d+Math.PI*1.5),i.stroke(),i.restore(),i.strokeStyle="#333333",i.lineWidth=10,i.strokeRect(0,0,r,o)}}if(this.renderPending=!1,this.animationRafId===null){const r=()=>{if(this.destroyed){this.animationRafId=null;return}this.renderPending||(this.renderPending=!0,this.emit("request-render")),this.animationRafId=requestAnimationFrame(r)};this.animationRafId=requestAnimationFrame(r)}return{video:e.width>0&&e.height>0?await createImageBitmap(e):null,state:"success",audio:[]}}async clone(){const t=new Bt(this.src,this.meta);return this.copyStateTo(t),t.id=this.id,t}async split(t){const e=await this.clone(),i=await this.clone();return e.trim.to=t+this.trim.from,i.trim.from=t+this.trim.from,e.duration=e.trim.to-e.trim.from,i.duration=i.trim.to-i.trim.from,e.display.to=e.display.from+e.duration,i.display.from=e.display.to,i.display.to=i.display.from+i.duration,[e,i]}static async fromObject(t){if(t.type!=="Placeholder")throw new Error(`Expected Placeholder, got ${t.type}`);const e=t.timing||{display:t.display||{},trim:t.trim||{},duration:t.duration??0,playbackRate:t.playbackRate??1},i=t.transform?.width??t.width??0,s=t.transform?.height??t.height??0,r=new Bt(t.src,{width:i,height:s,duration:e.duration});return X.deserializeBaseProperties(r,t),await r.ready,r}}class tt extends X{type="Transition";ready;_meta={duration:2e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;transitionKey;fromClipId=null;toClipId=null;values={};constructor(t){super(),this.transitionKey=t,this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const t=new tt(this.transitionKey);return this.copyStateTo(t),t.fromClipId=this.fromClipId,t.toClipId=this.toClipId,t.values=JSON.parse(JSON.stringify(this.values)),t}async tick(t){return{video:void 0,state:"success"}}async split(t){const e=await this.clone(),i=await this.clone();return[e,i]}toJSON(t=!1){return{id:this.id,type:"Transition",name:this.name,timing:{display:{from:this.timing.display.from,to:this.timing.display.to},trim:{from:this.timing.trim.from,to:this.timing.trim.to},duration:this.timing.duration,playbackRate:this.timing.playbackRate},transitionKey:this.transitionKey,fromClipId:this.fromClipId,toClipId:this.toClipId,...Object.keys(this.values).length>0&&{values:this.values}}}static async fromObject(t){if(t.type!=="Transition")throw new Error(`Expected Transition, got ${t.type}`);const e=t.transitionKey;if(!e)throw new Error("Missing transitionKey in Transition JSON");const i=new tt(e);return i.fromClipId=t.fromClipId||null,i.toClipId=t.toClipId||null,i.values=t.values||{},X.deserializeBaseProperties(i,t),await i.ready,i}}class Nt extends X{type="Shape";shapeType;graphics;_meta;renderTexture=null;externalRenderer=null;constructor(t){super(),this.shapeType=t.shapeType,this.id=qt.nanoid(),this.name=`${t.shapeType} Shape`,this.src=`shape://${t.shapeType}`,this.externalRenderer=t.renderer??null,this.width=t.width??200,this.height=t.height??200,this.graphics=new m.Graphics,this._meta={width:this.width,height:this.height,duration:0},this.style={fill:t.fill??"#3b82f6",fillOpacity:t.fillOpacity??1,stroke:t.stroke??{color:"#1e40af",width:2},borderRadius:t.borderRadius??0},this.ready=Promise.resolve(this._meta)}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;throw new Error("ShapeClip: No renderer available. Provide a renderer via options.renderer or setRenderer().")}setRenderer(t){this.externalRenderer=t}async getRenderTexture(){return this.renderTexture==null&&(this.renderTexture=m.RenderTexture.create({width:Math.ceil(this.width),height:Math.ceil(this.height)})),(this.renderTexture.width!==Math.ceil(this.width)||this.renderTexture.height!==Math.ceil(this.height))&&this.renderTexture.resize(Math.ceil(this.width),Math.ceil(this.height)),this.renderTexture}get meta(){return this._meta}drawShape(){const t=this.style;if(this.graphics.clear(),this.drawRectangle(t),t.fill){const e=this.hexToNumber(t.fill);this.graphics.fill({color:e,alpha:t.fillOpacity??1})}if(t.stroke){const e=this.hexToNumber(t.stroke.color);this.graphics.stroke({color:e,width:t.stroke.width,alpha:1})}}drawRectangle(t){const e=t.borderRadius??0;e>0?this.graphics.roundRect(-this.width/2,-this.height/2,this.width,this.height,e):this.graphics.rect(-this.width/2,-this.height/2,this.width,this.height)}hexToNumber(t){const e=t.startsWith("#")?t.slice(1):t;return parseInt(e,16)}async tick(t){await this.ready;const e=await this.getRenderTexture();this.drawShape();const i=await this.getRenderer();this.graphics.x=this.width/2,this.graphics.y=this.height/2,i.render({container:this.graphics,target:e});const s=e.source?.resource?.source;let r;if(s instanceof HTMLCanvasElement||s instanceof OffscreenCanvas)r=await createImageBitmap(s);else{const a=i.extract.canvas(e);if(a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas)r=await createImageBitmap(a);else throw new Error("Unable to extract canvas from render texture")}return{video:r,state:"success"}}async clone(){const t=new Nt({shapeType:this.shapeType,width:this.width,height:this.height,fill:this.style.fill,fillOpacity:this.style.fillOpacity,stroke:this.style.stroke,borderRadius:this.style.borderRadius});return t.left=this.left,t.top=this.top,t.angle=this.angle,t.opacity=this.opacity,t.zIndex=this.zIndex,t.display={...this.display},t.duration=this.duration,t.timing={...this.timing},t}async split(t){const e=await this.clone(),i=await this.clone();return[e,i]}toJSON(t=!1){return{...super.toJSON(t),shapeType:this.shapeType}}set style(t){super.style=t,this.graphics&&this.drawShape()}get style(){return super.style}set width(t){super.width=t,this.graphics&&this.drawShape(),this.renderTexture&&this.renderTexture.resize(Math.ceil(this.width),Math.ceil(this.height))}get width(){return super.width}set height(t){super.height=t,this.graphics&&this.drawShape(),this.renderTexture&&this.renderTexture.resize(Math.ceil(this.width),Math.ceil(this.height))}get height(){return super.height}static async fromObject(t){const e=new Nt({shapeType:t.shapeType,width:t.transform?.width,height:t.transform?.height,fill:t.style?.fill,fillOpacity:t.style?.fillOpacity,stroke:t.style?.stroke,borderRadius:t.style?.borderRadius});return X.deserializeBaseProperties(e,t),e}}const Ds=["#6A5AF9","#B14EFF","#FF7A7A"];class zt extends X{type="Backdrop";backdropType;container;_meta;renderTexture=null;externalRenderer=null;bgGraphics=null;meshContainer=null;meshCircles=[];blobsContainer=null;blobCircles=[];noiseSprite=null;noiseTexture=null;constructor(t){super(),this.backdropType=t.backdropType,this.id=qt.nanoid(),this.name=`${t.backdropType} Backdrop`,this.src=`backdrop://${t.backdropType}`,this.externalRenderer=t.renderer??null,this.width=t.width??1280,this.height=t.height??720,this.container=new m.Container,this.container.label="BackdropContainer",this._meta={width:this.width,height:this.height,duration:1/0},this.style={backdropType:t.backdropType,colors:t.colors??Ds,gradientType:t.gradientType??"linear",speed:t.speed??1,scale:t.scale??1,density:t.density??8},this.ready=Promise.resolve(this._meta),this.rebuildBackdrop()}setRenderer(t){this.externalRenderer=t}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;throw new Error("BackdropClip: No renderer available. Provide a renderer via options.renderer or setRenderer().")}async getRenderTexture(){const t=Math.max(1,Math.ceil(this.width)),e=Math.max(1,Math.ceil(this.height));return this.renderTexture==null&&(this.renderTexture=m.RenderTexture.create({width:t,height:e})),(this.renderTexture.width!==t||this.renderTexture.height!==e)&&this.renderTexture.resize(t,e),this.renderTexture}get meta(){return this._meta}rebuildBackdrop(){this.container.removeChildren(),this.bgGraphics=null,this.meshContainer=null,this.meshCircles=[],this.blobsContainer=null,this.blobCircles=[],this.noiseSprite=null;const t=this.style,e=t.backdropType||this.backdropType;this.backdropType=e;const i=t.colors||["#6A5AF9"],s=i.map(o=>$(o)??16777215),r=()=>{this.bgGraphics=new m.Graphics,this.bgGraphics.rect(0,0,this.width,this.height).fill({color:s[0]}),this.container.addChild(this.bgGraphics)};if(e==="solid")r();else if(e==="gradient")if((t.gradientType??"linear")==="radial"){const o=document.createElement("canvas");o.width=Math.max(1,Math.ceil(this.width)),o.height=Math.max(1,Math.ceil(this.height));const a=o.getContext("2d"),n=this.width/2,c=this.height/2,h=Math.min(this.width,this.height)/2,d=a.createRadialGradient(n,c,0,n,c,h);i.forEach((f,u)=>d.addColorStop(u/Math.max(1,i.length-1),f)),a.fillStyle=d,a.fillRect(0,0,this.width,this.height),this.container.addChild(new m.Sprite(m.Texture.from(o)))}else{this.bgGraphics=new m.Graphics;const o=new m.FillGradient(0,0,this.width,this.height);s.forEach((a,n)=>o.addColorStop(n/Math.max(1,s.length-1),a)),this.bgGraphics.rect(0,0,this.width,this.height).fill(o),this.container.addChild(this.bgGraphics)}else if(e==="meshGradient"){r(),this.meshContainer=new m.Container,this.meshContainer.label="MeshContainer";const o=Math.max(3,s.length),a=Math.max(this.width,this.height)*.35;this.meshContainer.filters=[new m.BlurFilter({strength:a})];for(let n=0;n<o;n++){const c=new m.Graphics,h=Math.max(this.width,this.height)*(.35+Math.random()*.15);c.circle(0,0,h).fill({color:s[n%s.length],alpha:.8});const d={graphics:c,baseX:this.width*(.2+Math.random()*.6),baseY:this.height*(.2+Math.random()*.6),phase:Math.random()*Math.PI*2,speedX:.3+Math.random()*.4,speedY:.3+Math.random()*.4,radius:h};c.x=d.baseX,c.y=d.baseY,this.meshContainer.addChild(c),this.meshCircles.push(d)}this.container.addChild(this.meshContainer)}else if(e==="floatingBlobs"){r(),this.blobsContainer=new m.Container,this.blobsContainer.label="BlobsContainer";const o=Math.max(4,t.density??8),a=s.slice(1).length>0?s.slice(1):s,n=Math.max(this.width,this.height)*.08;this.blobsContainer.filters=[new m.BlurFilter({strength:n})];for(let c=0;c<o;c++){const h=new m.Graphics,d=Math.max(this.width,this.height)*(.1+Math.random()*.12);h.circle(0,0,d).fill({color:a[c%a.length],alpha:.6});const f={graphics:h,baseX:this.width*Math.random(),baseY:this.height*Math.random(),phase:Math.random()*Math.PI*2,speedX:.2+Math.random()*.3,speedY:.2+Math.random()*.3,radius:d};h.x=f.baseX,h.y=f.baseY,this.blobsContainer.addChild(h),this.blobCircles.push(f)}this.container.addChild(this.blobsContainer)}else if(e==="noise"){if(r(),!this.noiseTexture){const o=document.createElement("canvas");o.width=256,o.height=256;const a=o.getContext("2d"),n=a.createImageData(256,256),c=n.data;for(let h=0;h<c.length;h+=4){const d=Math.floor(Math.random()*255);c[h]=d,c[h+1]=d,c[h+2]=d,c[h+3]=18}a.putImageData(n,0,0),this.noiseTexture=m.Texture.from(o)}this.noiseSprite=new m.TilingSprite({texture:this.noiseTexture,width:this.width,height:this.height}),this.noiseSprite.tileScale.set(t.scale??1),this.container.addChild(this.noiseSprite)}}async tick(t){await this.ready;const e=await this.getRenderTexture(),i=await this.getRenderer(),s=t/1e6*(this.style.speed??1);if(this.backdropType==="meshGradient"&&this.meshCircles.length>0){const a=this.style.scale??1;for(const n of this.meshCircles){const c=s*n.speedX+n.phase,h=s*n.speedY+n.phase*1.5;n.graphics.x=n.baseX+Math.cos(c)*(this.width*.25*a),n.graphics.y=n.baseY+Math.sin(h)*(this.height*.25*a)}}if(this.backdropType==="floatingBlobs"&&this.blobCircles.length>0){const a=this.style.scale??1;for(const n of this.blobCircles){const c=s*n.speedX+n.phase,h=s*n.speedY+n.phase*1.3;n.graphics.x=(n.baseX+Math.sin(c)*(this.width*.35*a)+this.width)%this.width,n.graphics.y=(n.baseY+Math.cos(h)*(this.height*.35*a)+this.height)%this.height}}this.backdropType==="noise"&&this.noiseSprite&&(this.noiseSprite.tilePosition.x=Math.random()*256,this.noiseSprite.tilePosition.y=Math.random()*256),i.render({container:this.container,target:e});const r=e.source?.resource?.source;let o;if(r instanceof HTMLCanvasElement||r instanceof OffscreenCanvas)o=await createImageBitmap(r);else{const a=i.extract.canvas(e);if(a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas)o=await createImageBitmap(a);else throw new Error("Unable to extract canvas from render texture")}return{video:o,state:"success"}}async clone(){const t=new zt({backdropType:this.backdropType,width:this.width,height:this.height,colors:this.style.colors,gradientType:this.style.gradientType,speed:this.style.speed,scale:this.style.scale,density:this.style.density});return t.left=this.left,t.top=this.top,t.angle=this.angle,t.opacity=this.opacity,t.zIndex=this.zIndex,t.display={...this.display},t.duration=this.duration,t.timing={...this.timing},t}async split(t){return[await this.clone(),await this.clone()]}toJSON(t=!1){return{...super.toJSON(t),backdropType:this.backdropType}}set style(t){super.style=t,this.container&&this.rebuildBackdrop()}get style(){return super.style}set width(t){super.width=t,this.container&&this.rebuildBackdrop(),this.renderTexture?.resize(Math.max(1,Math.ceil(this.width)),Math.max(1,Math.ceil(this.height)))}get width(){return super.width}set height(t){super.height=t,this.container&&this.rebuildBackdrop(),this.renderTexture?.resize(Math.max(1,Math.ceil(this.width)),Math.max(1,Math.ceil(this.height)))}get height(){return super.height}static async fromObject(t){const e=new zt({backdropType:t.backdropType,width:t.transform?.width,height:t.transform?.height,colors:t.style?.colors,gradientType:t.style?.gradientType,speed:t.style?.speed,scale:t.style?.scale,density:t.style?.density});return X.deserializeBaseProperties(e,t),e}}class st{static registry=new Map;static register(t,e){this.registry.set(t,e)}static get(t){return this.registry.get(t)}static getRegisteredTypes(){return Array.from(this.registry.keys())}}st.register("Video",nt),st.register("Audio",ut),st.register("Image",It),st.register("Text",at),st.register("Caption",mt),st.register("Effect",lt),st.register("Transition",tt),st.register("Placeholder",Bt),st.register("Shape",Nt),st.register("Backdrop",zt);function $e(l,t){let e=!1;async function i(){const s=l.getReader();for(;!e;){const{value:r,done:o}=await s.read();if(o){t.onDone();return}await t.onChunk(r)}s.releaseLock(),await l.cancel()}return i().catch(console.error),()=>{e=!0}}class ti{readable;writable;inputBufOffset=0;isStreamCancelled=!1;constructor(){const t=et.mp4box.createFile();this.readable=new ReadableStream({start:e=>this.initMP4Box(t,e),cancel:()=>{this.isStreamCancelled=!0,t.stop()}},{highWaterMark:50}),this.writable=new WritableStream({write:async e=>{if(this.isStreamCancelled)throw new Error("Stream cancelled");const i=e.buffer;i.fileStart=this.inputBufOffset,this.inputBufOffset+=i.byteLength,t.appendBuffer(i)},close:()=>{t.flush(),t.stop(),t.onFlush?.()},abort:e=>{Ps.error("SampleTransform writable aborted:",e),t.stop()}})}initMP4Box(t,e){t.onReady=s=>{[s.videoTracks[0],s.audioTracks[0]].forEach(r=>{r&&t.setExtractionOptions(r.id,r.video?"video":"audio",{nbSamples:100})}),e.enqueue({chunkType:"ready",data:{info:s,file:t}}),t.start()};const i={};t.onSamples=(s,r,o)=>{const a=o.map(n=>({...n}));e.enqueue({chunkType:"samples",data:{id:s,type:r,samples:a}}),i[s]=(i[s]??0)+o.length,t.releaseUsedSamples(s,i[s])},t.onFlush=()=>{e.close()},t.onError=s=>{e.error(new Error(`mp4box error: ${s}`))}}}const Ps={error:(...l)=>console.error("[SampleTransform]",...l)};function Is(l){let t=0;const e=l.boxes,i=[];let s=0;async function r(){const p=u(e,t);t=e.length,i.forEach(({track:g,id:v})=>{const x=g.samples.at(-1);x!=null&&(s=Math.max(s,x.cts+x.duration)),l.releaseUsedSamples(v,g.samples.length),g.samples=[]}),l.mdats=[],l.moofs=[],p!=null&&await h?.write(p)}let o=[];function a(){if(o.length>0)return!0;const p=e.findIndex(g=>g.type==="moov");if(p===-1)return!1;if(o=e.slice(0,p+1),t=p+1,i.length===0)for(let g=1;;g+=1){const v=l.getTrackById(g);if(v==null)break;i.push({track:v,id:g})}return!0}let n=0;const c=it.tmpfile();let h=null;const d=(async()=>{h=await c.createWriter(),n=self.setInterval(()=>{a()&&r()},100)})();let f=!1;return async()=>{if(f)throw Error("File exported");if(f=!0,await d,clearInterval(n),!a()||h==null)return null;l.flush(),await r(),await h?.close();const p=o.find(x=>x.type==="moov");if(p==null)return null;p.mvhd.duration=s;const g=it.tmpfile(),v=u(o,0);return await it.write(g,v.slice()),await it.write(g,c,{overwrite:!1}),await g.stream()};function u(p,g){if(g>=p.length)return null;const v=new et.mp4box.DataStream;for(let x=g;x<p.length;x++)p[x]!==null&&(p[x].write(v),delete p[x]);return new Uint8Array(v.buffer).slice()}}function Bs(l){const t=new ArrayBuffer(l.byteLength);l.copyTo(t);const e=l.timestamp;return{duration:l.duration??0,dts:e,cts:e,is_sync:l.type==="key",data:t}}async function ei(l){const t=et.mp4box.createFile(),e=Is(t);await Ns(l,t);const i=await e();if(i==null)throw Error("Can not generate file from streams");return i}async function Ns(l,t){let e=0,i=0,s=0,r=0,o=0,a=0,n=null,c=null;for(const h of l){let d=null,f=null,u=null,p=null;if(await new Promise(async g=>{$e(h.pipeThrough(new ti),{onDone:g,onChunk:async({chunkType:v,data:x})=>{if(v==="ready"){const{videoTrackConf:w,audioTrackConf:T}=oe(x.file,x.info);e===0&&w!=null&&(e=t.addTrack(w)),r===0&&T!=null&&(r=t.addTrack(T))}else if(v==="samples"){const{type:w,samples:T}=x,y=w==="video"?e:r,C=w==="video"?i:o,k=w==="video"?s:a;T.forEach(F=>{let b,S;w==="video"?(d===null&&(d=F.dts,f=F.cts),b=F.dts-d,S=F.cts-(f??0)):(u===null&&(u=F.dts,p=F.cts),b=F.dts-u,S=F.cts-(p??0)),t.addSample(y,new Uint8Array(F.data),{duration:F.duration,dts:b+C,cts:S+k,is_sync:F.is_sync})});const O=T.at(-1);if(O==null)return;w==="video"?n=O:w==="audio"&&(c=O)}}})}),n!=null&&d!==null&&f!==null){const g=n.dts-d+n.duration,v=n.cts-f+n.duration;i+=g,s+=v}if(c!=null&&n!=null){const g=c.timescale/n.timescale;o=Math.round(i*g),a=Math.round(s*g)}}}async function zs(l){return await ei([l])}function Ls(l){let t=[];const e=new AudioDecoder({output:i=>{t.push(i)},error:Q.error});return e.configure(l),{decode:async i=>{i.forEach(r=>{e.decode(new EncodedAudioChunk({type:r.is_sync?"key":"delta",timestamp:1e6*r.cts/r.timescale,duration:1e6*r.duration/r.timescale,data:r.data}))}),await e.flush();const s=t;return t=[],s},close:()=>{e.close()}}}function Hs(l,t){const e={codec:l.codec,sampleRate:l.sampleRate,numberOfChannels:l.numberOfChannels},i=new AudioEncoder({output:o=>{t(Bs(o))},error:o=>{Q.error("AudioEncoder error:",o,", config:",e)}});i.configure(e);let s=null;function r(o,a){return new AudioData({timestamp:a,numberOfChannels:l.numberOfChannels,numberOfFrames:o.length/l.numberOfChannels,sampleRate:l.sampleRate,format:"f32-planar",data:new Float32Array(o)})}return{encode:async(o,a)=>{s!=null&&i.encode(r(s.data,s.ts)),s={data:o,ts:a}},stop:async()=>{s!=null&&(Gs(s.data,l.numberOfChannels,l.sampleRate),i.encode(r(s.data,s.ts)),s=null),await i.flush(),i.close()}}}function Gs(l,t,e){const i=l.length-1,s=Math.min(e/2,i);for(let r=0;r<s;r++)for(let o=1;o<=t;o++)l[Math.floor(i/o)-r]*=r/s}function Us(l,t){Q.info("mixinMP4AndAudio, opts:",{volume:t.volume,loop:t.loop});const e=et.mp4box.createFile();let i,s=0,r=0;const o=e.boxes;let a=!1;const n=()=>{if(!a)if(o.find(A=>A.type==="moof")!=null)a=!0;else return null;if(r>=o.length)return null;const F=new et.mp4box.DataStream;let b=r;try{for(;b<o.length;)o[b].write(F),delete o[b],b+=1}catch(A){throw A}if(e.moov!=null){for(var S=0;S<e.moov.traks.length;S++)e.moov.traks[S].samples=[];e.mdats=[],e.moofs=[]}return r=o.length,new Uint8Array(F.buffer)};let c=!1,h=!1,d=null;i=new ReadableStream({start(F){s=self.setInterval(()=>{const b=n();b!=null&&!h&&F.enqueue(b)},500),d=b=>{if(clearInterval(s),e.flush(),b!=null){F.error(b);return}const S=n();S!=null&&!h&&F.enqueue(S),h||F.close()}},cancel(){h=!0,clearInterval(s)}});const f=F=>{c||(c=!0,d?.(F))};let u=null,p=null,g=[],v=0,x=0,w=0,T=!0,y=L.sampleRate;$e(l.pipeThrough(new ti),{onDone:async()=>{await p?.stop(),u?.close(),f()},onChunk:async({chunkType:F,data:b})=>{if(F==="ready"){const{videoTrackConf:S,audioTrackConf:A,audioDecoderConf:E}=oe(b.file,b.info);v===0&&S!=null&&(v=e.addTrack(S));const P=A??{timescale:1e6,samplerate:y,channel_count:L.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};x===0&&(x=e.addTrack(P),y=A?.samplerate??y,T=A!=null);const R=new AudioContext({sampleRate:y});g=_t(await R.decodeAudioData(await new Response(t.stream).arrayBuffer())),E!=null&&(u=Ls(E)),p=Hs(E??{codec:P.type==="mp4a"?L.codec:P.type,numberOfChannels:P.channel_count,sampleRate:P.samplerate},B=>e.addSample(x,new Uint8Array(B.data),B))}else if(F==="samples"){const{id:S,type:A,samples:E}=b;if(A==="video"){E.forEach(P=>e.addSample(S,new Uint8Array(P.data),P)),T||await k(E);return}A==="audio"&&await O(E)}}});function C(F){const b=g.map(S=>t.loop?$t(S,w,w+F):S.slice(w,w+F));if(w+=F,t.volume!==1)for(const S of b)for(let A=0;A<S.length;A++)S[A]*=t.volume;return b}async function k(F){const b=F[0],S=F[F.length-1],A=Math.floor((S.cts+S.duration-b.cts)/b.timescale*y),E=Ce([C(A)]);E.length!==0&&p?.encode(E,b.cts/b.timescale*1e6)}async function O(F){if(u==null)return;const b=(await u.decode(F)).map(be),S=Si(b),A=C(S[0].length),E=F[0];p?.encode(Ce([S,A]),E.cts/E.timescale*1e6)}return i}function Ws(l){const t={...l};if(t.timing?t.timing={display:t.timing.display||{from:0,to:0},trim:t.timing.trim||{from:0,to:0},duration:t.timing.duration??0,playbackRate:t.timing.playbackRate??1,fadeIn:t.timing.fadeIn??l.fadeIn,fadeOut:t.timing.fadeOut??l.fadeOut}:t.timing={display:l.display||{from:0,to:0},trim:l.trim||{from:0,to:0},duration:l.duration??0,playbackRate:l.playbackRate??1,fadeIn:l.fadeIn,fadeOut:l.fadeOut},delete t.fadeIn,delete t.fadeOut,t.transform)t.transform={x:t.transform.x??0,y:t.transform.y??0,width:t.transform.width??0,height:t.transform.height??0,angle:t.transform.angle??0,opacity:t.transform.opacity??1,zIndex:t.transform.zIndex??0,flip:t.transform.flip||null};else{const e=l;t.transform={x:e.left??0,y:e.top??0,width:e.width??0,height:e.height??0,angle:e.angle??0,opacity:e.opacity??1,zIndex:e.zIndex??0,flip:e.flip||null}}return t.style&&(t.style=Vs(t.style,l.type)),t}function Vs(l,t){if(!l)return l;const e={...l};if(e.dropShadow&&(e.shadow=e.dropShadow,delete e.dropShadow),e.shadow){const i={...e.shadow},s=i.offsetX!==void 0||i.offsetY!==void 0;if((i.distance!==void 0||i.angle!==void 0)&&!s){const o=i.distance??0,a=i.angle??0;i.offsetX=Math.cos(a)*o,i.offsetY=Math.sin(a)*o}delete i.distance,delete i.angle,e.shadow=i}return(t==="Text"||t==="Caption")&&e.fill!==void 0&&(e.color=e.fill,delete e.fill),e}function Lt(l,t=!1){return l.toJSON(t)}async function xt(l,t){const e=Ws(l);let i;const s=st.get(e.type);if(s&&typeof s.fromObject=="function")i=await s.fromObject(e,t);else throw new Error(`Unsupported clip type or missing fromObject: ${e.type}`);if(e.animations&&Array.isArray(e.animations)){i.clearAnimations();for(const r of e.animations)i.addAnimation(r.type,r.options,r.params)}return e.id&&(i.id=e.id),e.name&&(i.name=e.name),e.metadata&&(i.metadata=e.metadata),i}const ii=new MessageChannel;function si(){return new Promise(l=>{ii.port1.onmessage=()=>l(),ii.port2.postMessage(null)})}const Ys=20;async function Qs(l){for(;l()>Ys;)await si()}const js=`
184
+ `,cs={thickness:1,borderColor:0};class hs extends m.Filter{constructor(t){const{thickness:e,borderColor:i}={...cs,...t},s=m.GpuProgram.from({vertex:{source:je,entryPoint:"mainVertex"},fragment:{source:je,entryPoint:"mainFragment"}}),r=m.GlProgram.from({vertex:ls,fragment:as,name:"outline-filter"});super({gpuProgram:s,glProgram:r,padding:e*4,resources:{outlineUniforms:new m.UniformGroup({uThickness:{value:e,type:"f32"},uBorderColor:{value:new m.Color(i),type:"vec3<f32>"}})}})}get thickness(){return this.resources.outlineUniforms.uniforms.uThickness}set thickness(t){const e=this.resources.outlineUniforms.uniforms;e.uThickness=t}}const Je=Symbol.for("agrhub.engine.fontManager");class pt{static instance;fonts=new Map;loading=new Map;warnedConflicts=new Set;constructor(){}static getInstance(){const t=globalThis;return pt.instance||(pt.instance=t[Je]??new pt),t[Je]=pt.instance,pt.instance}async addFont(t){const e=this.fonts.get(t.name);if(e){this.warnOnConflict(t,e.url);return}const i=this.loading.get(t.name);if(i)return i;const s=(async()=>{try{const o=await new FontFace(t.name,`url(${t.url})`).load();document.fonts.add(o),this.fonts.set(t.name,{face:o,url:t.url}),m.CanvasTextMetrics.clearMetrics()}catch(r){console.error(`Failed to load font ${t.name}:`,r)}finally{this.loading.delete(t.name)}})();return this.loading.set(t.name,s),s}warnOnConflict(t,e){!t.url||t.url===e||this.warnedConflicts.has(t.name)||(this.warnedConflicts.add(t.name),console.warn(`[FontManager] Font "${t.name}" is already loaded from ${e}; ignoring different URL ${t.url}`))}async loadFonts(t){await Promise.all(t.map(e=>this.addFont(e)))}removeFont(t){const e=this.fonts.get(t);e&&(document.fonts.delete(e.face),this.fonts.delete(t))}clear(){this.fonts.forEach(({face:t})=>{document.fonts.delete(t)}),this.fonts.clear()}getLoadedFonts(){return Array.from(this.fonts.keys())}}const jt=pt.getInstance();function ds(l){if(typeof document>"u"||!document.fonts?.check)return!0;const t=String(l.fontFamily||"Roboto").split(",")[0].trim().replace(/^["']|["']$/g,""),e=Number(l.fontSize)||30,i=`${l.fontStyle||"normal"} ${l.fontWeight||"normal"} ${e}px "${t}"`;try{return document.fonts.check(i)}catch{return!0}}function Ze(l){const t=[];t.push(l.fontFamily||"Roboto"),t.push(String(l.fontSize||30)),t.push(String(l.fontWeight||"normal")),t.push(String(l.fontStyle||"normal")),l.fill!==void 0&&(typeof l.fill=="number"?t.push(`f_${l.fill}`):t.push("f_obj")),l.stroke&&(typeof l.stroke=="object"?t.push(`s_${l.stroke.color}_${l.stroke.width}_${l.stroke.join||""}`):t.push(`s_${l.stroke}`)),l.dropShadow&&t.push(`ds_${l.dropShadow.color}_${l.dropShadow.alpha}_${l.dropShadow.blur}_${l.dropShadow.angle}_${l.dropShadow.distance}`),ds(l)||t.push("pending");const e="installed_font_"+t.join("_").replace(/[^a-zA-Z0-9_]/g,"_");return!m.Cache.has(e)&&!m.Cache.has(e+"-bitmap")&&m.BitmapFont.install({name:e,style:l}),e}class Ke extends X{_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}pixiTextContainer=null;wordTexts=[];textStyle;textStyleBase;renderTexture=null;outlineFilter=null;dropShadowFilter=null;_refreshing=!1;_needsRefresh=!1;_refreshPromise=null;_spaceWidth=0;_text="";externalRenderer=null;pixiApp=null;originalOpts;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];setRenderer(t){this.externalRenderer=t}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("BaseTextClip: No renderer. Provide one via constructor or setRenderer().");return this.pixiApp.renderer}async getTexture(){return this._refreshPromise&&await this._refreshPromise.catch(()=>{}),this.pixiTextContainer==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture)}async tick(t){if(await this.ready,this._refreshPromise&&await this._refreshPromise.catch(()=>{}),this.pixiTextContainer==null||this.renderTexture==null)throw new Error("BaseTextClip not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);const e=await this.getRenderer();e.render({container:this.pixiTextContainer,target:this.renderTexture});const i=this.renderTexture.source?.resource?.source;let s;if(i instanceof HTMLCanvasElement||i instanceof OffscreenCanvas)s=await createImageBitmap(i);else{const o=e.extract.canvas(this.renderTexture);if(o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas)s=await createImageBitmap(o);else throw new Error("Unable to extract canvas from render texture")}return{video:s,state:"success"}}async split(t){await this.ready;const e=await this.clone(),i=await this.clone();return[e,i]}_hasMaskAnim(t){return t.some(e=>e?.params?.mask===!0)}get animations(){return super.animations}set animations(t){const e=this._hasMaskAnim(this.animations);super.animations=t;const i=this._hasMaskAnim(this.animations);e!==i&&this.originalOpts&&this.textStyle&&this.refreshText()}animate(t){super.animate(t,this.pixiTextContainer)}addEffect(t){this.effects.push(t)}editEffect(t,e){const i=this.effects.find(s=>s.id===t);i&&Object.assign(i,e)}removeEffect(t){const e=this.effects.findIndex(i=>i.id===t);e!==-1&&this.effects.splice(e,1)}refreshText(){return this._refreshing&&this._refreshPromise?(this._needsRefresh=!0,this._refreshPromise):(this._refreshing=!0,this._refreshPromise=(async()=>{try{do this._needsRefresh=!1,await this._doRefreshText();while(this._needsRefresh)}finally{this._refreshing=!1,this._refreshPromise=null}})(),this._refreshPromise)}async _doRefreshText(){const t=this._targetWidth??0,e=this.originalOpts.wordWrap,i=this.originalOpts.wordWrapWidth,s=this.originalOpts.background;if(this.originalOpts.fontUrl&&this.originalOpts.fontFamily)try{await jt.addFont({name:this.originalOpts.fontFamily,url:this.originalOpts.fontUrl})}catch(E){console.warn("[BaseTextClip] Failed to load font:",E)}typeof document<"u"&&await document.fonts.ready,this._buildTextStyles();const r=this.textStyle,o=this._applyTextCase(this.text);if(!this.pixiTextContainer)this.pixiTextContainer=new m.Container,this.pixiTextContainer.__clip=this;else{this.pixiTextContainer.__clip=this,this.animations.forEach(E=>{E&&typeof E.destroy=="function"&&E.destroy()});for(const E of this.pixiTextContainer.children)if(E&&!E.destroyed){const P=R=>{if(R&&(ht.killTweensOf(R),R.children))for(const B of R.children)P(B)};if(P(E),E.children)for(const R of E.children)R&&R.label==="LineContainer"&&(R.mask=null);E.destroy({children:!0})}this.pixiTextContainer.removeChildren()}const{textOnlyContainer:a,words:n}=this._buildWordObjects(o),c=this._applyStrokeFilter();this._applyShadowFilter(a),this.pixiTextContainer.addChild(a);const{spaceWidth:h,measuredTextHeight:d}=await this._measureSpaceAndHeight();this._spaceWidth=h;const f=this.originalOpts.lineHeight??1,u=r.fontSize??40,p=u*f;let g;if(e)if(t>0){const E=s?.paddingX??8;g=Math.max(1,t-E*2)}else g=i??100;else g=1e5;const v=this._breakIntoLines(g,p),x=this.originalOpts.background?.color,w=this.originalOpts.background?.opacity??1,T=this.originalOpts.background?.borderRadius??4,y=this.originalOpts.background?.paddingX??8,C=this.originalOpts.background?.paddingY??4,{containerWidth:k,containerHeight:O,contentHeight:F}=this._calculateDimensions(v,d,t,e,i,s,y,C),b=this._positionWords(v,k,O,F,d,y,a),S=this._drawDecoration(v,k,y);S&&this.pixiTextContainer.addChild(S);const A=this._buildBackground(b,x,w,T);A&&this.pixiTextContainer.addChildAt(A,0),this._lineRects=b,this._createRenderTexture(k,O,c),this._meta.width=k,this._meta.height=O,this._width=k,this._height=O,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration),this._onAfterRefresh(n,a,h,d,f,u)}_onAfterRefresh(t,e,i,s,r,o){}_applyTextCase(t){const e=this.originalOpts.textCase;return e==="uppercase"?t.toUpperCase():e==="lowercase"?t.toLowerCase():e==="title"?t.replace(/\w\S*/g,i=>i.charAt(0).toUpperCase()+i.substring(1).toLowerCase()):t}_buildTextStyles(){const t=this.createStyleFromOpts(this.originalOpts),{wordWrap:e,wordWrapWidth:i,lineHeight:s,letterSpacing:r,fill:o,...a}=t,n=Ze(t);this.textStyle=new m.TextStyle({...t,fontFamily:n});const c=Ze(a);return this.textStyleBase=new m.TextStyle({...a,fontFamily:c}),{fontName:n,baseFontName:c}}_buildWordObjects(t){const e=t.split(/\s+/).filter(s=>s.length>0),i=new m.Container;return i.label="TextOnlyContainer",this.wordTexts.forEach(s=>{s&&!s.destroyed&&s.destroy()}),this.wordTexts=e.map(s=>{const r=new m.SplitBitmapText({text:s,style:this.textStyle});return i.addChild(r),r}),{textOnlyContainer:i,words:e}}_applyStrokeFilter(){const t=this.originalOpts.stroke,e=(t!==null&&typeof t=="object"&&"width"in t?t.width:void 0)??this.originalOpts.strokeWidth??0,i=t!=null&&e>0;if(i){let s=0;if(typeof t=="object"&&"color"in t){const r=$(t.color);r!==void 0&&(s=r)}else if(typeof t=="string"||typeof t=="number"){const r=$(t);r!==void 0&&(s=r)}if(this.outlineFilter){this.outlineFilter.thickness=e,this.outlineFilter.padding=e*4;const r=this.outlineFilter.resources.outlineUniforms.uniforms;r.uBorderColor=new m.Color(s)}else this.outlineFilter=new hs({thickness:e,borderColor:s});this.wordTexts.forEach(r=>{r.filters=[this.outlineFilter]})}else this.outlineFilter&&(this.wordTexts.forEach(s=>{s.filters=[]}),this.outlineFilter=null);return i?e:0}_applyShadowFilter(t){const e=this.originalOpts.shadow;if(e){const i=e.offsetX??0,s=e.offsetY??0,r=$(e.color??"#000000"),o=e.alpha??1,a=e.blur??4,n=Math.ceil(a*2.5+Math.max(Math.abs(i),Math.abs(s)));r!==void 0&&(this.dropShadowFilter?(this.dropShadowFilter.color=r,this.dropShadowFilter.alpha=o,this.dropShadowFilter.blur=a,this.dropShadowFilter.offset={x:i,y:s},this.dropShadowFilter.padding=n):(this.dropShadowFilter=new j.DropShadowFilter({color:r,alpha:o,blur:a,offset:{x:i,y:s}}),this.dropShadowFilter.padding=n),t.filters=[this.dropShadowFilter])}else this.dropShadowFilter&&(t.filters=[],this.dropShadowFilter=null)}async _measureSpaceAndHeight(){const t=this.originalOpts.fontSize||40,e=this.originalOpts.fontFamily||"Arial",i=String(this.originalOpts.fontWeight||"normal"),s=this.originalOpts.fontStyle||"normal",r=`${s} ${i} ${t}px "${e}"`;if(typeof document<"u")try{await document.fonts.load(r)}catch{}const o=new m.TextStyle({fontFamily:e,fontSize:t,fontWeight:i,fontStyle:s}),a=m.CanvasTextMetrics.measureText(" ",o),n=new m.TextStyle({fontFamily:e,fontSize:t,fontWeight:i,fontStyle:s}),h=m.CanvasTextMetrics.measureText("Hg",n).fontProperties,d=h&&h.ascent>0?Math.ceil(h.ascent+h.descent):t,f=new m.SplitBitmapText({text:" ",style:this.textStyleBase}),u=Math.ceil(f.getLocalBounds().width||f.width||a.width||t*.25);return f.destroy(),{spaceWidth:u,measuredTextHeight:d}}_breakIntoLines(t,e){const i=[];let s=[],r=0,o=0;return this.wordTexts.forEach(a=>{const n=a.getLocalBounds(),c=Math.ceil(n.width||a.width),h=Math.ceil(n.height||a.height),d=r+(r>0?this._spaceWidth:0)+c;d<=t||s.length===0?(s.push(a),r=d,o=Math.max(o,h)):(s.length>0&&i.push({words:s,width:r,height:Math.max(o,e)}),s=[a],r=c,o=h)}),s.length>0&&i.push({words:s,width:r,height:Math.max(o,e)}),i}_calculateDimensions(t,e,i,s,r,o,a,n){const c=e+n*2;t.forEach(T=>{T.height=Math.max(T.height,c)});let h=0,d=0;t.forEach(T=>{h=Math.max(h,T.width),d+=T.height});let f=h;if(s&&i>0){const T=o?.paddingX??8,y=i-T*2;f=Math.max(f,y)}else s&&r!=null&&r>0&&(f=Math.max(f,r));const u=d;f+=a*2;const p=i>0?i:this._width,g=p===0,v=!this._explicitHeight||this.height===0,x=g?f:Math.max(f,p),w=v?u:Math.max(u,this.height||0);return{containerWidth:x,containerHeight:w,contentWidth:f,contentHeight:u}}_positionWords(t,e,i,s,r,o,a){const n=this.originalOpts.verticalAlign||"top";let c=0;n==="center"?c=(i-s)/2:n==="bottom"&&(c=i-s);let h=c;const d=[];return t.forEach(f=>{let u=0;const p=this.textAlign;p==="center"?u=(e-f.width)/2:p==="right"?u=e-f.width-o*2:u=o;const g=u,v=new m.Container;if(v.label="LineContainer",v.x=0,v.y=0,this.animations.some(w=>w?.params?.mask===!0)){const w=new m.Graphics;w.label="LineMask",w.rect(0,h,e,f.height),w.fill(16777215),v.mask=w,a.addChild(w)}a.addChild(v),f.words.forEach((w,T)=>{w.x=Math.round(u),w.y=Math.round(h+(f.height-r)/2-9),u+=(w.getLocalBounds().width||w.width)+(T<f.words.length-1?this._spaceWidth:0),v.addChild(w)}),d.push({x:g-o,y:h,w:f.width+o*2,h:f.height}),h+=f.height}),d}_drawDecoration(t,e,i){const s=this.originalOpts.textDecoration||this.originalOpts.verticalAlign;if(!s||s==="none"||!["underline","overline","strikethrough","line-through"].includes(s))return null;const r=this.textStyle,o=r.fontSize??40,a=s==="strikethrough"?"line-through":s,n=Math.max(1,o/12);let c=16777215;typeof r.fill=="number"&&(c=r.fill);const h=new m.Graphics;let d=0;return t.forEach(f=>{let u=i;const p=this.textAlign;p==="center"?u=(e-f.width)/2:p==="right"&&(u=e-f.width-i*2);let g=0;a==="underline"?g=f.height:a==="line-through"&&(g=f.height/2),h.rect(u,d+g,f.width,n),h.fill(c),d+=f.height}),h}_buildBackground(t,e,i,s){if(!t.length||!e||e==="transparent"||e==="")return null;const r=$(e),o=new m.Graphics;return this.drawRoundedMultilinePath(o,t,s,r??0,i),o}_createRenderTexture(t,e,i){const r=i>0?i*2.1:0;let o=0;if(this.dropShadowFilter){const h=this.dropShadowFilter.blur??0,d=this.dropShadowFilter.offset,f=d?Math.sqrt(d.x**2+d.y**2):0;o=h+f}const a=300+r+o,n=t+a*2,c=e+a*2;this.pixiTextContainer&&(this.pixiTextContainer.x=a,this.pixiTextContainer.y=a),this.renderTexture&&this.renderTexture.destroy(),this.renderTexture=m.RenderTexture.create({width:n,height:c}),this.renderTexturePadding=a}_normalizeStyleOpts(t){let e={...t};e.style&&(e={...e,...e.style},delete e.style),e.fill!==void 0&&(e.color=e.fill,delete e.fill),e.dropShadow!==void 0&&(e.shadow=e.dropShadow,delete e.dropShadow),e.textAlign!==void 0&&(e.align=e.textAlign,delete e.textAlign);const i=e.underline,s=e.overline,r=e.linethrough;return(i!==void 0||s!==void 0||r!==void 0)&&(i?e.textDecoration="underline":s?e.textDecoration="overline":r?e.textDecoration="line-through":e.textDecoration="none",delete e.underline,delete e.overline,delete e.linethrough),e}_cloneColorOpts(t){const e=this.originalOpts;return e.color&&typeof e.color=="object"&&"type"in e.color&&e.color.type==="gradient"?e.color:t(this.textStyle.fill)??16777215}_cloneStrokeOpts(t){const e=this.originalOpts,i=this.textStyle;if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke)return{stroke:e.stroke,strokeWidth:0};const s=t(i.stroke),r=e.strokeWidth??i.strokeThickness??0;return{stroke:s!==void 0?s:void 0,strokeWidth:r}}_cloneShadowOpts(t){const e=this.originalOpts,i=this.textStyle;if(e.shadow)return e.shadow;if(i.dropShadow){const s=i.dropShadow,r=t(s.color);if(r!==void 0){const o=s.angle??0,a=s.distance??0;return{color:r,alpha:s.alpha,blur:s.blur,offsetX:Math.cos(o)*a,offsetY:Math.sin(o)*a}}}}createStyleFromOpts(t){const e=t.fontSize??40,i=t.lineHeight??1,s={fontSize:e,fontFamily:t.fontFamily??"Roboto",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",align:t.align??"left",wordWrap:t.wordWrap??!1,wordWrapWidth:t.wordWrapWidth??100,lineHeight:e*i,letterSpacing:t.letterSpacing??0},r=t.color??"#ffffff";if(r&&typeof r=="object"&&"type"in r&&r.type==="gradient"){const o=new m.FillGradient(r.x0,r.y0,r.x1,r.y1);r.colors.forEach(({ratio:a,color:n})=>{const c=typeof n=="number"?n:$(n)??16777215;o.addColorStop(a,c)}),s.fill={fill:o}}else{const{color:o,alpha:a}=Ft(r);s.fill=o,a<1&&(s.fillAlpha=a)}return s}drawRoundedMultilinePath(t,e,i,s,r=1){if(e.length===0)return;const o=Math.max(i*.8,15);let a=!0,n=0;for(;a&&n<5;){a=!1,n++;for(let f=0;f<e.length;f++)for(let u=f+1;u<e.length;u++){const p=e[f].x+e[f].w,g=e[u].x+e[u].w;if(Math.abs(p-g)>.1&&Math.abs(p-g)<o){const v=Math.max(p,g);e[f].w=v-e[f].x,e[u].w=v-e[u].x,a=!0}if(Math.abs(e[f].x-e[u].x)>.1&&Math.abs(e[f].x-e[u].x)<o){const v=Math.min(e[f].x,e[u].x);e[f].w+=e[f].x-v,e[f].x=v,e[u].w+=e[u].x-v,e[u].x=v,a=!0}}}const c=[];c.push({x:e[0].x,y:e[0].y}),c.push({x:e[0].x+e[0].w,y:e[0].y});for(let f=0;f<e.length-1;f++){const u=e[f],p=e[f+1];if(Math.abs(u.x+u.w-(p.x+p.w))>.1){const g=(u.y+u.h+p.y)/2;c.push({x:u.x+u.w,y:g}),c.push({x:p.x+p.w,y:g})}}c.push({x:e[e.length-1].x+e[e.length-1].w,y:e[e.length-1].y+e[e.length-1].h}),c.push({x:e[e.length-1].x,y:e[e.length-1].y+e[e.length-1].h});for(let f=e.length-1;f>0;f--){const u=e[f],p=e[f-1];if(Math.abs(u.x-p.x)>.1){const g=(u.y+p.y+p.h)/2;c.push({x:u.x,y:g}),c.push({x:p.x,y:g})}}t.clear();const h=c[c.length-1],d=c[0];t.moveTo((h.x+d.x)/2,(h.y+d.y)/2);for(let f=0;f<c.length;f++){const u=c[f],p=c[(f+1)%c.length];t.arcTo(u.x,u.y,(u.x+p.x)/2,(u.y+p.y)/2,i)}t.fill({color:s,alpha:r})}destroy(){if(!this.destroyed){Q.info(`${this.constructor.name} destroy`);try{if(this.pixiTextContainer!=null&&!this.pixiTextContainer.destroyed){for(const t of this.pixiTextContainer.children)if(t&&!t.destroyed){const e=i=>{if(i&&(ht.killTweensOf(i),i.children))for(const s of i.children)e(s)};if(e(t),t.children)for(const i of t.children)i&&i.label==="LineContainer"&&(i.mask=null)}this.pixiTextContainer.destroy({children:!0})}}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&!this.renderTexture.destroyed&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const t=this.pixiApp;t.destroyed!==!0&&t.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(t=!1){const e=super.toJSON(t),{chromaKey:i,colorAdjustment:s,...r}=e;return r}}class mt extends Ke{type="Caption";_lastTickTime=0;_isWidthConstrained=!1;_words=[];_activeStyle={};_futureStyle={};_keywordColor="";_keywordPreserveAfterSpoken=!1;_wordAnimation={type:"scale",application:"none",value:1};_wordsPerLine="multiple";_trackCaptionColors;_videoWidth=1280;_videoHeight=720;_bottomOffset=100;get text(){return this._text}set text(t){if(this._text===t)return;const e=this._text;this._text=t,e!==""&&this._words.length>0&&(this._words=xe.redistributeCaptionWords(t,this._words,this.duration||5e6)),this.originalOpts&&this.textStyle&&this.refreshText().then(()=>this.emit("propsChange",{text:t}))}get textAlign(){return this.originalOpts?.align??"left"}get caption(){const t=this.originalOpts??{};return{words:this._words,colors:{active:t.activeStyle,future:t.futureStyle,keyword:t.keywordColor?{color:t.keywordColor,preserveAfterSpoken:t.keywordPreserveAfterSpoken}:void 0},wordAnimation:t.wordAnimation,positioning:{videoWidth:this._videoWidth,videoHeight:this._videoHeight,bottomOffset:this._bottomOffset}}}set caption(t){if(!t)return;t.words&&(this._words=t.words,this.originalOpts&&(this.originalOpts.words=t.words));const e=Array.isArray(t.words),i=t.colors??(e?this._trackCaptionColors??{}:void 0),s=!t.colors&&e;i&&(("active"in i||s)&&(this.originalOpts.activeStyle=i.active??void 0),("future"in i||s)&&(this.originalOpts.futureStyle=i.future??void 0),("keyword"in i||s)&&(i.keyword!=null?(this.originalOpts.keywordColor=i.keyword.color,this.originalOpts.keywordPreserveAfterSpoken=i.keyword.preserveAfterSpoken):(this.originalOpts.keywordColor=void 0,this.originalOpts.keywordPreserveAfterSpoken=void 0))),t.wordAnimation!==void 0&&(this.originalOpts.wordAnimation=t.wordAnimation),t.positioning&&(t.positioning.videoWidth!==void 0&&(this._videoWidth=t.positioning.videoWidth),t.positioning.videoHeight!==void 0&&(this._videoHeight=t.positioning.videoHeight),t.positioning.bottomOffset!==void 0&&(this._bottomOffset=t.positioning.bottomOffset)),this._syncOpts(),(i||t.wordAnimation!==void 0||t.words)&&(this._buildTextStyles(),this.refreshText().then(()=>this.emit("propsChange",{caption:t})))}get words(){return this._words}set words(t){this._words=t,this.originalOpts&&(this.originalOpts.words=t),this.refreshText().then(()=>this.emit("propsChange",{style:this.style}))}get mediaId(){return this.originalOpts?.mediaId}set mediaId(t){this.originalOpts&&(this.originalOpts.mediaId=t)}get wordsPerLine(){return this._wordsPerLine}set wordsPerLine(t){t&&(this._wordsPerLine=t,this.originalOpts&&(this.originalOpts.wordsPerLine=t),this.refreshText())}get style(){const t=this.originalOpts??{};return{fontSize:t.fontSize,fontFamily:t.fontFamily,fontWeight:t.fontWeight,fontStyle:t.fontStyle,color:t.color,align:t.align,stroke:t.stroke,shadow:t.shadow,wordWrap:t.wordWrap,wordWrapWidth:t.wordWrapWidth,lineHeight:t.lineHeight,letterSpacing:t.letterSpacing,textCase:t.textCase}}set style(t){this.updateStyle(t)}async updateStyle(t){const e=this._normalizeStyleOpts(t);this.originalOpts={...this.originalOpts,...e},e.words!==void 0&&(this._words=e.words),this._syncOpts(),this._buildTextStyles(),await this.refreshText(),this.emit("propsChange",t)}get width(){return this._width}set width(t){Math.abs(this.width-t)<.1||(this._width=t,t>0&&(this._isWidthConstrained=!0),this.refreshText())}get height(){return this._height}set height(t){Math.abs(this.height-t)<.1||(this._height=t,this.refreshText())}animate(t){this._lastTickTime=t,super.animate(t)}constructor(t,e={},i){if(super(),this.originalOpts={...e},this._text=t,i&&this.setRenderer(i),e.caption){e.caption.words&&(this._words=e.caption.words);const s=e.caption;s.colors&&"active"in s.colors&&(this.originalOpts.activeStyle=s.colors.active??void 0),s.colors&&"future"in s.colors&&(this.originalOpts.futureStyle=s.colors.future??void 0),s.colors&&"keyword"in s.colors&&(s.colors.keyword!=null?(this.originalOpts.keywordColor=s.colors.keyword.color,this.originalOpts.keywordPreserveAfterSpoken=s.colors.keyword.preserveAfterSpoken):(this.originalOpts.keywordColor=void 0,this.originalOpts.keywordPreserveAfterSpoken=void 0)),s.wordAnimation!==void 0&&(this.originalOpts.wordAnimation=s.wordAnimation),s.positioning?.videoWidth!==void 0&&(this.originalOpts.videoWidth=s.positioning.videoWidth),s.positioning?.videoHeight!==void 0&&(this.originalOpts.videoHeight=s.positioning.videoHeight),s.positioning?.bottomOffset!==void 0&&(this.originalOpts.bottomOffset=s.positioning.bottomOffset)}e.words&&(this._words=e.words),e.initialLayoutApplied,this._syncOpts(),this._buildTextStyles(),this.ready=(async()=>(await this.refreshText(),{...this.meta}))()}createStyleFromOpts(t){const e=super.createStyleFromOpts(t);return e.fill=16777215,e}_syncOpts(){const t=this.originalOpts??{};this._activeStyle=t.activeStyle??{},this._futureStyle=t.futureStyle??{},this._keywordColor=t.keywordColor??"",this._keywordPreserveAfterSpoken=t.keywordPreserveAfterSpoken??!1,this._wordAnimation=t.wordAnimation??{type:"scale",application:"none",value:1},this._wordsPerLine=t.wordsPerLine??"multiple",this._videoWidth=t.videoWidth??1280,this._videoHeight=t.videoHeight??720,this._bottomOffset=t.bottomOffset??100}_buildWordObjects(t){const e=new m.Container;e.label="TextOnlyContainer",this.wordTexts.forEach(o=>o.destroy()),this.wordTexts=[];const i=[],s=this.originalOpts?.textCase,r=(o,a)=>{const n=new m.SplitBitmapText({text:o,style:this.textStyle});n.segmentIndex=a;const c=this.originalOpts?.color,h=typeof c=="object"&&c!==null&&"type"in c?16777215:c,d=$(h);return n.tint=d??16777215,n};return this._words.length>0?this._words.forEach((o,a)=>{let n=o.text||"";s==="uppercase"?n=n.toUpperCase():s==="lowercase"?n=n.toLowerCase():s==="title"&&(n=n.replace(/\w\S*/g,h=>h.charAt(0).toUpperCase()+h.substring(1).toLowerCase())),n.split(/\s+/).filter(h=>h.length>0).forEach(h=>{const d=r(h,a);e.addChild(d),this.wordTexts.push(d),i.push(h)})}):t.split(/\s+/).filter(o=>o.length>0).forEach((o,a)=>{const n=r(o,a);e.addChild(n),this.wordTexts.push(n),i.push(o)}),{textOnlyContainer:e,words:i}}_onAfterRefresh(){this.updateState(this._lastTickTime)}async tick(t){return this.updateState(t),super.tick(t)}updateState(t){this._lastTickTime=t;const e=t/1e3;this.wordTexts.forEach(i=>{const s=this._words[i.segmentIndex];if(!s)return;i.scale.set(1,1);const r=e>=s.from&&e<s.to,o=e>=s.to,a=!r&&!o,n=this._wordAnimation;let c=0,h=!1;if(n&&n.application!=="none"&&((n.application==="active"&&r||n.application==="keyword"&&s.isKeyWord)&&(h=!0),h)){if(n.mode==="dynamic"&&r){const y=s.to-s.from;if(y>0){const C=Math.max(0,Math.min(1,(e-s.from)/y));c=n.value<1?C:Math.sin(C*Math.PI)}else c=1}else c=1;if(n.type==="scale"){const y=n.value<1&&n.mode==="dynamic"&&r?n.value+(1-n.value)*c:1+(n.value-1)*c;i.scale.set(y,y)}}let d=16777215,f=1;if(s.isKeyWord&&!Dt(this._keywordColor)&&(r||o&&this._keywordPreserveAfterSpoken))({color:d,alpha:f}=Ft(this._keywordColor,16776960));else if(r){const y=this._activeStyle.color;y&&!Dt(y)?{color:d,alpha:f}=Ft(y,16777215):(d=16777215,f=1)}else if(a){const y=this._futureStyle.color;y&&!Dt(y)?{color:d,alpha:f}=Ft(y,16777215):(d=16777215,f=1)}else{const y=this.originalOpts?.color,C=typeof y=="object"&&y!==null&&"type"in y?16777215:y;({color:d,alpha:f}=Ft(C))}if(h&&n?.type==="opacity"){const y=n.value<1&&n.mode==="dynamic"&&r?n.value+(1-n.value)*c:1+(n.value-1)*c;f*=y}i.tint=d;const p=y=>{y.label==="bgRect"||y.label==="tiktokBackground"||y.label==="containerBackground"||typeof y.label=="string"&&y.label.startsWith("bgRect_")||("alpha"in y&&(y.alpha=f),y.children&&y.children.forEach(p))};i.children.forEach(p);const g=i.parent,v=`bgRect_${i.segmentIndex}`,x=g?g.getChildByLabel(v):null,w=r?this._activeStyle.background??"":"";if(r&&!!w&&!Dt(w)&&w!=="none"&&g){const{color:y,alpha:C}=Ft(w,16753920),k=15,O=40,F=i.scale.x,b=(i.getLocalBounds().width||i.width)*F,S=(this.originalOpts?.fontSize??40)*F,A=i.x,E=i.y+9,P=x??new m.Graphics;P.label=v,P.clear(),P.roundRect(A-O/2,E-k/2,b+O,S+k,10),P.fill({color:y,alpha:C}),P.tint=16777215,x||g.addChildAt(P,0)}else x&&g&&(g.removeChild(x),x.destroy())})}async clone(){await this.ready;const t=new mt(this.text,{...this.originalOpts,words:[...this._words]});return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}toJSON(t=!1){const e=super.toJSON(t),i=this.originalOpts??{},s={};i.fontSize!==void 0&&(s.fontSize=i.fontSize),i.fontFamily!==void 0&&(s.fontFamily=i.fontFamily),i.fontWeight!==void 0&&(s.fontWeight=i.fontWeight),i.fontStyle!==void 0&&(s.fontStyle=i.fontStyle),i.color!==void 0&&(s.color=i.color),i.align!==void 0&&(s.align=i.align),i.textCase!==void 0&&(s.textCase=i.textCase),i.fontUrl!==void 0&&(s.fontUrl=i.fontUrl),i.verticalAlign!==void 0&&(s.verticalAlign=i.verticalAlign),i.wordWrapWidth!==void 0&&(s.wordWrapWidth=i.wordWrapWidth),i.wordWrap!==void 0&&(s.wordWrap=i.wordWrap),i.wordAnimation!==void 0&&(s.wordAnimation=i.wordAnimation),i.stroke&&(typeof i.stroke=="object"?s.stroke={color:i.stroke.color,width:i.stroke.width}:s.stroke={color:i.stroke,width:i.strokeWidth??0}),i.shadow&&(s.shadow={color:i.shadow.color??"#000000",alpha:i.shadow.alpha??.5,blur:i.shadow.blur??4,offsetX:i.shadow.offsetX??0,offsetY:i.shadow.offsetY??0});const r={};this._words.length>0&&(r.words=this._words);const o={};i.activeStyle&&(o.active=i.activeStyle),i.futureStyle&&(o.future=i.futureStyle),i.keywordColor&&(o.keyword={color:i.keywordColor,preserveAfterSpoken:i.keywordPreserveAfterSpoken}),Object.keys(o).length>0&&(r.colors=o),i.wordAnimation!==void 0&&(r.wordAnimation=i.wordAnimation);const a={};return i.videoWidth!==void 0&&(a.videoWidth=i.videoWidth),i.videoHeight!==void 0&&(a.videoHeight=i.videoHeight),i.bottomOffset!==void 0&&(a.bottomOffset=i.bottomOffset),Object.keys(a).length>0&&(r.positioning=a),{...e,type:"Caption",text:this.text,style:s,caption:Object.keys(r).length>0?r:void 0,id:this.id,effects:this.effects,mediaId:this.mediaId,wordsPerLine:this.wordsPerLine,fontUrl:i.fontUrl}}static async fromObject(t,e){if(t.type!=="Caption")throw new Error(`Expected Caption, got ${t.type}`);const i=e?.captionConfig,s=t.text||"",r={...i?.style??{},...t.style??{}},o={};r.fontSize!==void 0&&(o.fontSize=r.fontSize),r.fontFamily!==void 0&&(o.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(o.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(o.fontStyle=r.fontStyle),r.color!==void 0?o.color=r.color:r.fill!==void 0&&(o.color=r.fill),r.align!==void 0&&(o.align=r.align),r.textCase!==void 0&&(o.textCase=r.textCase),r.verticalAlign!==void 0&&(o.verticalAlign=r.verticalAlign),r.wordWrapWidth!==void 0&&(o.wordWrapWidth=r.wordWrapWidth),r.wordWrap!==void 0&&(o.wordWrap=r.wordWrap),r.wordAnimation!==void 0&&(o.wordAnimation=r.wordAnimation),r.fontUrl!==void 0?o.fontUrl=r.fontUrl:t.fontUrl!==void 0&&(o.fontUrl=t.fontUrl);const a=h=>h!=null&&h!=="";a(r.wordsPerLine)?o.wordsPerLine=r.wordsPerLine:a(t.wordsPerLine)&&(o.wordsPerLine=t.wordsPerLine);const n=r;if(n.lineHeight!==void 0&&(o.lineHeight=n.lineHeight),n.letterSpacing!==void 0&&(o.letterSpacing=n.letterSpacing),o.textCase===void 0&&t.textCase!==void 0&&(o.textCase=t.textCase),n.background&&typeof n.background=="object")o.background={...n.background};else if(a(n.backgroundColor)&&n.backgroundColor!=="transparent"){const h=Number(n.padding);o.background={color:n.backgroundColor,opacity:n.backgroundOpacity??.7,borderRadius:n.borderRadius??8,paddingX:Number.isFinite(h)?h:10,paddingY:Number.isFinite(h)?Math.round(h*.6):6}}if(t.mediaId&&(o.mediaId=t.mediaId),r.stroke&&(o.stroke=r.stroke.color,o.strokeWidth=r.stroke.width),r.shadow&&(o.shadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,offsetX:r.shadow.offsetX??0,offsetY:r.shadow.offsetY??0}),t.caption){const h={...t.caption};!h.colors&&i?.colors&&(h.colors=i.colors),!h.positioning&&i?.positioning&&(h.positioning=i.positioning),o.caption=h,t.caption.wordAnimation&&(o.wordAnimation=t.caption.wordAnimation)}else i&&(o.caption={colors:i.colors,positioning:i.positioning});o.initialLayoutApplied=!0;const c=new mt(s,o);return c._trackCaptionColors=i?.colors,X.deserializeBaseProperties(c,t),c.wordsPerLine=(a(t.wordsPerLine)?t.wordsPerLine:void 0)??i?.wordsPerLine??"multiple",t.effects&&(c.effects=t.effects),await c.ready,c}getVisibleHandles(){return["mr","mb","br","rot"]}}let It=class vt extends X{type="Image";ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];getVisibleHandles(){return["tl","tr","bl","br","rot"]}static async fromUrl(t,e){let i=null,s;if(t.startsWith("blob:"))try{const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch image: ${o.status} ${o.statusText}`);const a=await o.blob();s=await createImageBitmap(a);try{i=m.Texture.from(s)}catch(n){Q.warn("Failed to create Pixi texture from bitmap:",n)}}catch(o){throw Q.error(`Failed to load blob image from ${t}`,o),o}else s=await yt.getImageBitmap(t);if(!s)throw new Error(`Failed to load image from ${t}`);const r=new vt(s,e||t);return i&&(r.pixiTexture=i),r}getTexture(){return this.pixiTexture}constructor(t,e){super(),this.src=e!==void 0?e:"";const i=s=>{this.img=s,this._meta.width=s.width,this._meta.height=s.height,this._meta.duration=1/0;const r={...this._meta};return this.width=this.width===0?r.width:this.width,this.height=this.height===0?r.height:this.height,this.duration===0&&r.duration!==1/0&&(this.duration=r.duration,this.display.to=this.display.from+this.duration),r};if(t instanceof ReadableStream)this.ready=new Response(t).blob().then(s=>createImageBitmap(s)).then(i);else if(t instanceof ImageBitmap)this.ready=Promise.resolve(i(t));else if(Array.isArray(t)&&t.every(s=>s instanceof VideoFrame)){this.frames=t;const s=this.frames[0];if(s==null)throw Error("The frame count must be greater than 0");this._meta={width:s.displayWidth,height:s.displayHeight,duration:this.frames.reduce((o,a)=>o+(a.duration??0),0)};const r={...this._meta,duration:1/0};this.width=this.width===0?r.width:this.width,this.height=this.height===0?r.height:this.height,this.duration===0&&r.duration!==1/0&&(this.duration=r.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(r)}else if("type"in t)this.ready=this.initAnimateImg(t.stream,t.type).then(()=>{const s={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?s.width:this.width,this.height=this.height===0?s.height:this.height,this.duration===0&&s.duration!==1/0&&(this.duration=s.duration,this.display.to=this.display.from+this.duration),s});else throw Error("Illegal arguments")}async initAnimateImg(t,e){this.frames=await _i(t,e);const i=this.frames[0];if(i==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((s,r)=>s+(r.duration??0),0),width:i.codedWidth,height:i.codedHeight},Q.info("Image ready:",this._meta)}tickInterceptor=async(t,e)=>e;async tick(t){if(this.img!=null)return await this.tickInterceptor(t,{video:await createImageBitmap(this.img),state:"success"});const e=t%this._meta.duration;return await this.tickInterceptor(t,{video:(this.frames.find(i=>e>=i.timestamp&&e<=i.timestamp+(i.duration??0))??this.frames[0]).clone(),state:"success"})}async split(t){if(await this.ready,this.img!=null)return[new vt(await createImageBitmap(this.img),this.src),new vt(await createImageBitmap(this.img),this.src)];let e=-1;for(let r=0;r<this.frames.length;r++){const o=this.frames[r];if(!(t>o.timestamp)){e=r;break}}if(e===-1)throw Error("Not found frame by time");const i=this.frames.slice(0,e).map(r=>new VideoFrame(r)),s=this.frames.slice(e).map(r=>new VideoFrame(r,{timestamp:r.timestamp-t}));return[new vt(i,this.src),new vt(s,this.src)]}async clone(){await this.ready;const t=this.img==null?this.frames.map(i=>i.clone()):await createImageBitmap(this.img),e=new vt(t,this.src);return e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e.id=this.id,e.effects=[...this.effects],e.transition=this.transition,e}addEffect(t){this.effects.push(t)}editEffect(t,e){const i=this.effects.find(s=>s.id===t);i&&Object.assign(i,e)}removeEffect(t){const e=this.effects.findIndex(i=>i.id===t);e!==-1&&this.effects.splice(e,1)}destroy(){Q.info("Image destroy"),this.img?.close(),this.frames.forEach(t=>t.close()),this.pixiTexture=null,super.destroy()}toJSON(t=!1){return{...super.toJSON(t),type:"Image",id:this.id,effects:this.effects}}static async fromObject(t){if(t.type!=="Image")throw new Error(`Expected Image, got ${t.type}`);if(!t.src||t.src.trim()==="")throw new Error("Image requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let e;try{const i=await yt.getImageBitmap(t.src);e=new vt(i,t.src)}catch(i){throw i instanceof Error&&i.message.includes("could not be decoded")?new Error(`Failed to decode image from ${t.src}. The image may be decoded, in an unsupported format, or there may be CORS issues.`):i}return X.deserializeBaseProperties(e,t),t.effects&&(e.effects=t.effects),e}};function oe(l,t){const e={},i=t.videoTracks[0];if(i!=null){const r=fs(l.getTrackById(i.id))?.buffer,o=us(i.codec);o&&(e.videoTrackConf={timescale:i.timescale,duration:i.duration,width:i.video.width,height:i.video.height,brands:t.brands,type:o.type,[o.descKey]:r}),e.videoDecoderConf={codec:i.codec,codedHeight:i.video.height,codedWidth:i.video.width,description:r}}const s=t.audioTracks[0];if(s!=null){const r=ps(l),o=r?ms(r):{};e.audioTrackConf={timescale:s.timescale,samplerate:o.sampleRate??s.audio.sample_rate,channel_count:o.numberOfChannels??s.audio.channel_count,hdlr:"soun",type:s.codec.startsWith("mp4a")?"mp4a":s.codec,description:r};const a=s.codec.startsWith("mp4a")?s.codec:o.codec??(s.codec==="Opus"||s.codec==="opus"?"opus":s.codec);e.audioDecoderConf={codec:a,numberOfChannels:o.numberOfChannels??s.audio.channel_count,sampleRate:o.sampleRate??s.audio.sample_rate,...o.description?{description:o.description}:{}}}return e}function us(l){return l.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:l.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:null}function fs(l){for(const t of l.mdia.minf.stbl.stsd.entries){const e=t.avcC??t.hvcC??t.av1C??t.vpcC;if(e!=null){const i=new et.mp4box.DataStream(void 0,0,void 0);return e.write(i),new Uint8Array(i.buffer.slice(8))}}}function ps(l,t="mp4a"){const e=l.moov?.traks.flatMap(i=>i.mdia.minf.stbl.stsd.entries).find(i=>i.type===t);return e?.esds??e}function ms(l){const t=l.esd?.descs?.[0];if(!t)return{};let e=`mp4a.${t.oti.toString(16)}`;const i=t.descs?.[0];if(!i)return e.endsWith(".40")&&(e+=".2"),{codec:e};const s=i.data;if(!s)return{codec:e};const r=(s[0]&248)>>3;e+=`.${r}`;const o=(s[0]&7)<<1|s[1]>>7,a=(s[1]&120)>>3;return{codec:e,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][o],numberOfChannels:a,description:s}}async function gs(l,t,e){const i=et.mp4box.createFile(!1);i.onReady=o=>{t({mp4boxFile:i,info:o}),[o.videoTracks[0],o.audioTracks[0]].forEach(a=>{if(a){const n=a.video?"video":"audio";i.setExtractionOptions(a.id,n,{nbSamples:100})}}),i.start()},i.onSamples=e;let s=0;const r=30*1024*1024;for(;;){const o=await l.read(r,{at:s});if(o.byteLength===0)break;o.fileStart=s;const a=i.appendBuffer(o);if(a==null)break;s=a}i.stop()}function vs(l){if(l?.length!==9)return{};const t=new Int32Array(l.buffer),e=h=>h/65536,i=e(t[0]),s=e(t[1]),r=e(t[3]),o=e(t[4]),a=e(t[6]),n=e(t[7]),c=t[8]/(1<<30);return{scaleX:Math.sqrt(i*i+r*r),scaleY:Math.sqrt(s*s+o*o),rotationRad:Math.atan2(r,i),rotationDeg:Math.atan2(r,i)*180/Math.PI,translateX:a,translateY:n,perspective:c}}function ys(l,t,e){const i=(Math.round(e/90)*90+360)%360;if(i===0)return c=>c;const s=i===90||i===270,r=s?t:l,o=s?l:t,a=new OffscreenCanvas(r,o),n=a.getContext("2d");return n.translate(r/2,o/2),n.rotate(-i*Math.PI/180),n.translate(-l/2,-t/2),c=>{if(!c)return null;n.drawImage(c,0,0);const h=new VideoFrame(a,{timestamp:c.timestamp,duration:c.duration??void 0});return c.close(),h}}let ne=0;function ae(l){return l.kind==="file"&&l.createReader instanceof Function}class nt extends X{type="Video";insId=ne++;logger=Q.create(`Video id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const t=await this.localFile.getOriginFile();if(t==null)throw Error("Video localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:e,size:i})=>t.slice(e,e+i))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=t=>t;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;onEffectiveVolumeChange(){this.audioFrameFinder?.setVolume(this.effectiveVolume)}decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];getVisibleHandles(){return["tl","tr","bl","br","rot"]}static async fromUrl(t,e={}){const i=await yt.getReadableStream(t),s=new nt(i,{},t);return await s.ready,e.x!==void 0&&(s.left=e.x),e.y!==void 0&&(s.top=e.y),e.width!==void 0&&(s.width=e.width),e.height!==void 0&&(s.height=e.height),s}constructor(t,e={},i){if(super(),this.src=i!==void 0?i:"",!(t instanceof ReadableStream)&&!ae(t)&&!Array.isArray(t.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...e},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof e.audio=="object"&&"volume"in e.audio?e.audio.volume:e.volume??1;const s=async r=>(await it.write(this.localFile,r),this.localFile);this.localFile=ae(t)?t:"localFile"in t?t.localFile:it.tmpfile(),this.ready=(t instanceof ReadableStream?s(t).then(r=>Xe(r,this.opts)):ae(t)?Xe(t,this.opts):Promise.resolve(t)).then(async({videoSamples:r,audioSamples:o,decoderConf:a,headerBoxPos:n,parsedMatrix:c})=>{this.videoSamples=r,this.audioSamples=o,this.decoderConf=a,this.headerBoxPos=n,this.parsedMatrix=c;const{videoFrameFinder:h,audioFrameFinder:d}=ws({video:a.video==null?null:{...a.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:a.audio},await this.localFile.createReader(),r,o,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=h,this.audioFrameFinder=d,this.effectiveVolume!==this.volume&&this.audioFrameFinder?.setVolume(this.effectiveVolume);const{codedWidth:f,codedHeight:u}=a.video??{};f&&u&&(this.vfRotater=ys(f,u,c.rotationDeg)),this._meta=xs(a,r,o,c.rotationDeg),this.logger.info("Video meta:",this._meta);const p={...this._meta};this.width=this.width===0?p.width:this.width,this.height=this.height===0?p.height:this.height,this.trim.to=this.trim.to===0?p.duration:Math.min(this.trim.to,p.duration),this.trim.from=Math.min(this.trim.from,this.trim.to);const g=(this.trim.to-this.trim.from)/this.playbackRate;return this.duration=this.duration===0?g:this.duration,Math.abs(this.duration-g)>1&&(this.duration=g),this.display.to=this.display.from+this.duration,this.on("propsChange",v=>{(v.volume!==void 0||v.muted!==void 0)&&this.audioFrameFinder&&this.audioFrameFinder.setVolume(this.effectiveVolume)}),p})}tickInterceptor=async(t,e)=>e;async tick(t){const e=t+this.trim.from;if(e>this.trim.to||e>this._meta.duration)return await this.tickInterceptor(t,{audio:await this.audioFrameFinder?.find(e)??[],state:"done"});const[i,s]=await Promise.all([this.audioFrameFinder?.find(e)??[],this.videoFrameFinder?.find(e).then(this.vfRotater)]);return s==null?await this.tickInterceptor(t,{audio:i,state:"success"}):await this.tickInterceptor(t,{video:s,audio:i,state:"success"})}addEffect(t){this.effects.push(t)}editEffect(t,e){const i=this.effects.find(s=>s.id===t);i&&Object.assign(i,e)}removeEffect(t){const e=this.effects.findIndex(i=>i.id===t);e!==-1&&this.effects.splice(e,1)}async split(t){throw new Error("Video.split is not implemented - use core state instead")}async clone(){await this.ready;const t=new nt({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await t.ready,t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("Video destroy"),super.destroy(),this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(t=!1){return{...super.toJSON(t),type:"Video",audio:this.audio,volume:this.volume,id:this.id,effects:this.effects}}static async fromObject(t){if(t.type!=="Video")throw new Error(`Expected Video, got ${t.type}`);const e=t.audio!==void 0?{audio:t.audio,volume:t.volume}:{volume:t.volume},i=await yt.getReadableStream(t.src),s=new nt(i,e,t.src);return X.deserializeBaseProperties(s,t),t.effects&&(s.effects=t.effects),t.volume!==void 0&&(s.volume=t.volume),s}async createPlaybackElement(){await this.ready;const e=this.localFile;if(!e||typeof e.getOriginFile!="function")throw new Error("Video does not have a local file for playback");const i=await e.getOriginFile();if(!i)throw new Error("Failed to get origin file from VideoClip");const s=URL.createObjectURL(i),r=document.createElement("video");return r.crossOrigin="anonymous",r.muted=!0,r.autoplay=!1,r.playsInline=!0,r.preload="auto",r.loop=!1,r.src=s,await new Promise((o,a)=>{const n=()=>{r.removeEventListener("loadeddata",n),r.removeEventListener("error",c),r.pause(),r.currentTime=0,o()},c=()=>{r.removeEventListener("loadeddata",n),r.removeEventListener("error",c),a(new Error("Failed to load video"))};r.addEventListener("loadeddata",n,{once:!0}),r.addEventListener("error",c,{once:!0}),r.load()}),{element:r,objectUrl:s}}async play(t,e){const i=t,s=e+this.trim.from/1e6;if(Math.abs(i.currentTime-s)>.1&&(i.currentTime=s),i.muted=!1,i.paused)try{await i.play()}catch{try{await i.play()}catch(o){console.warn("Failed to play video:",o)}}}pause(t){const e=t;e.pause(),e.muted=!0}async seek(t,e){const i=t,s=e+this.trim.from/1e6;i.pause(),i.currentTime=s,i.addEventListener("seeked",()=>{i.__pendingRender?.()},{once:!0})}syncPlayback(t,e,i){const s=t,r=this.duration&&this.duration!==1/0?this.duration/1e6:(this.display.to-this.display.from)/1e6,o=i>=0&&i<r,a=i+this.trim.from/1e6,n=r*1e3,c=i*1e3;let h=1;if(this.timing.fadeIn&&this.timing.fadeIn.duration>0&&c<this.timing.fadeIn.duration&&(h*=Ct(c/this.timing.fadeIn.duration,this.timing.fadeIn.curve)),this.timing.fadeOut&&this.timing.fadeOut.duration>0){const d=n-this.timing.fadeOut.duration;if(c>=d){const f=1-(c-d)/this.timing.fadeOut.duration;h*=Ct(f,this.timing.fadeOut.curve)}}s.volume=Math.max(0,Math.min(1,this.effectiveVolume*h)),e&&o?s.paused?this.play(s,i).catch(console.warn):(s.muted&&(s.muted=!1),(s.ended||s.currentTime>=this.trim.to/1e6)&&(s.currentTime=a,s.play().catch(console.warn))):(s.paused||s.pause(),s.muted=!0,o&&Math.abs(s.currentTime-a)>.1&&(s.currentTime=a))}cleanupPlayback(t,e){const i=t;i.pause(),i.removeAttribute("src"),i.load(),e&&URL.revokeObjectURL(e)}async scaleToFit(t,e){await this.ready;const{width:i,height:s}=this.meta;if(i===0||s===0)return;const r=Math.min(t/i,e/s);this.width=i*r,this.height=s*r}async scaleToFill(t,e){await this.ready;const{width:i,height:s}=this.meta;if(i===0||s===0)return;const r=Math.max(t/i,e/s);this.width=i*r,this.height=s*r}centerInScene(t,e){this.left=(t-this.width)/2,this.top=(e-this.height)/2}}function xs(l,t,e,i){const s={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(l.video!=null&&t.length>0){s.width=l.video.codedWidth??0,s.height=l.video.codedHeight??0;const a=(Math.round(i/90)*90+360)%360;(a===90||a===270)&&([s.width,s.height]=[s.height,s.width])}l.audio!=null&&e.length>0&&(s.audioSampleRate=L.sampleRate,s.audioChanCount=L.channelCount);let r=0,o=0;if(t.length>0)for(let a=t.length-1;a>=0;a--){const n=t[a];if(!n.deleted){r=n.cts+n.duration;break}}if(e.length>0){const a=e.at(-1);o=a.cts+a.duration}return s.duration=Math.max(r,o),s}function ws(l,t,e,i,s){return{audioFrameFinder:s===0||l.audio==null||i.length===0?null:new Ts(t,i,l.audio,{volume:s,targetSampleRate:L.sampleRate}),videoFrameFinder:l.video==null||e.length===0?null:new bs(t,e,l.video)}}async function Xe(l,t={}){let e=null;const i={video:null,audio:null};let s=[],r=[],o=[];const a={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let n=-1,c=-1;const h=await l.createReader();await gs(h,async f=>{e=f.info;const u=f.mp4boxFile.ftyp;o.push({start:u.start,size:u.size});const p=f.mp4boxFile.moov;o.push({start:p.start,size:p.size}),Object.assign(a,vs(e.videoTracks[0]?.matrix));let{videoDecoderConf:g,audioDecoderConf:v}=oe(f.mp4boxFile,f.info);if(i.video=g??null,i.audio=v??null,g==null&&v==null&&Q.error("Video no video and audio track"),v!=null){const{supported:x}=await AudioDecoder.isConfigSupported(v);x||Q.error(`Video audio codec is not supported: ${v.codec}`)}if(g!=null){const{supported:x}=await VideoDecoder.isConfigSupported(g);x||Q.error(`Video video codec is not supported: ${g.codec}`)}Q.info("mp4BoxFile moov ready",{...f.info,tracks:null,videoTracks:null,audioTracks:null},i)},(f,u,p)=>{if(u==="video"){n===-1&&(n=p[0].dts);for(const g of p)s.push(qe(g,n,"video"))}else if(u==="audio"&&t.audio){c===-1&&(c=p[0].dts);for(const g of p)r.push(qe(g,c,"audio"))}}),await h.close();const d=s.at(-1)??r.at(-1);if(e==null)throw Error("Video stream is done, but not emit ready");if(d==null)throw Error("Video stream not contain any sample");return Os(s),Q.info("mp4 stream parsed"),{videoSamples:s,audioSamples:r,decoderConf:i,headerBoxPos:o,parsedMatrix:a}}function qe(l,t=0,e){let i=l.offset;const s=e==="video"&&l.is_sync?Rs(l.data,l.description.type):-1;let r=l.size;return s>0&&(i+=s,r-=s),{...l,is_idr:s>=0,offset:i,size:r,cts:(l.cts-t)/l.timescale*1e6,dts:(l.dts-t)/l.timescale*1e6,duration:l.duration/l.timescale*1e6,timescale:1e6,data:e==="video"?null:l.data}}class bs{constructor(t,e,i){this.localFileReader=t,this.samples=e,this.conf=i}localFileReader;samples;conf;decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async t=>{(this.decoder==null||this.decoder.state==="closed"||t<this.timestamp||t-this.timestamp>3e6)&&this.reset(t),this.curAborter.abort=!0,this.timestamp=t,this.curAborter={abort:!1,st:performance.now()};const e=await this.parseFrame(t,this.decoder,this.curAborter);return this.sleepCnt=0,e};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;_firstPresentableTs=null;firstPresentableTs(){if(this._firstPresentableTs!=null)return this._firstPresentableTs;let t=this.samples.findIndex(i=>i.is_idr&&!i.deleted);t<0&&(t=0);let e=1/0;for(let i=t;i<this.samples.length;i++){const s=this.samples[i];if(i>t&&s.is_idr)break;!s.deleted&&s.cts<e&&(e=s.cts)}return this._firstPresentableTs=Number.isFinite(e)?e:0,this._firstPresentableTs}parseFrame=async(t,e,i)=>{if(e==null||e.state==="closed"||i.abort)return null;if(this.videoFrames.length>0){const s=this.videoFrames[0];return t<s.timestamp?t<=0||s.timestamp<=this.firstPresentableTs()?new VideoFrame(s):null:(this.videoFrames.shift(),t>s.timestamp+(s.duration??0)?(s.close(),await this.parseFrame(t,e,i)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(e).catch(r=>{throw this.predecodeErr=!0,this.reset(t),r}),s))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&e.decodeQueueSize>0){if(performance.now()-i.st>6e3)throw Error(`Video.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await Ae(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(e)}catch(s){throw this.reset(t),s}}return await this.parseFrame(t,e,i)};decoding=!1;startDecode=async t=>{if(this.decoding||t.decodeQueueSize>600)return;let e=this.videoDecCursorIdx+1;if(e>this.samples.length)return;this.decoding=!0;let i=!1;for(;e<this.samples.length;e++){const s=this.samples[e];if(!i&&!s.deleted&&(i=!0),s.is_idr)break}if(i){const s=this.samples.slice(this.videoDecCursorIdx,e);if(s[0]?.is_idr!==!0)Q.warn("First sample not idr frame");else{const r=performance.now(),o=await ks(s,this.localFileReader),a=performance.now()-r;if(a>1e3){const n=s[0],c=s.at(-1),h=c.offset+c.size-n.offset;Q.warn(`Read video samples time cost: ${Math.round(a)}ms, file chunk size: ${h}`)}if(t.state==="closed")return;this.lastVfDur=o[0]?.duration??0,Fs(t,o,{onDecodingError:n=>{if(this.downgradeSoftDecode)throw n;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,Q.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=o.length}}this.videoDecCursorIdx=e,this.decoding=!1};reset=t=>{if(this.decoding=!1,this.videoFrames.forEach(i=>i.close()),this.videoFrames=[],t==null||t===0)this.videoDecCursorIdx=0;else{let i=0;for(let s=0;s<this.samples.length;s++){const r=this.samples[s];if(r.is_idr&&(i=s),!(r.cts<t)){this.videoDecCursorIdx=i;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const e={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:i=>{if(this.outputFrameCnt+=1,i.timestamp===-1){i.close();return}let s=i;i.duration==null&&(s=new VideoFrame(i,{duration:this.lastVfDur}),i.close()),this.videoFrames.push(s)},error:i=>{if(i.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,Q.warn(i.message);return}const s=`VideoFinder VideoDecoder err: ${i.message}, config: ${JSON.stringify(e)}, state: ${JSON.stringify(this.getState())}`;throw Q.error(s),Error(s)}}),this.decoder.configure(e)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:ne,sleepCnt:this.sleepCnt,memInfo:_e()});destroy=async()=>{if(this.curAborter.abort=!0,this.videoFrames.forEach(t=>t.close()),this.videoFrames=[],this.decoder&&this.decoder.state!=="closed")try{this.decoder.close()}catch{}this.decoder=null,this.localFileReader.close()}}function Cs(l,t){for(let e=0;e<t.length;e++){const i=t[e];if(l>=i.cts&&l<i.cts+i.duration)return e;if(i.cts>l)break}return 0}class Ts{constructor(t,e,i,s){this.localFileReader=t,this.samples=e,this.conf=i,this.volume=s.volume,this.sampleRate=s.targetSampleRate}localFileReader;samples;conf;volume=1;sampleRate;setVolume(t){this.volume=t,this.reset()}decoder=null;curAborter={abort:!1,st:performance.now()};find=async t=>{const e=t<=this.timestamp||t-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||e)&&this.reset(),e&&(this.timestamp=t,this.decCursorIdx=Cs(t,this.samples)),this.curAborter.abort=!0;const i=t-this.timestamp;this.timestamp=t,this.curAborter={abort:!1,st:performance.now()};const s=await this.parseFrame(Math.ceil(i*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,s};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(t,e=null,i)=>{if(e==null||i.abort||e.state==="closed"||t===0)return[];const s=this.pcmData.frameCnt-t;if(s>0)return s<L.sampleRate/10&&this.startDecode(e),le(this.pcmData,t);if(e.decoding){if(performance.now()-i.st>6e4)return console.warn("[Video.tick] Audio decode wait exceeded 60s, using the PCM decoded so far",this.getState()),this.pcmData.frameCnt>0?le(this.pcmData,this.pcmData.frameCnt):[];this.sleepCnt+=1,await Ae(15)}else{if(this.decCursorIdx>=this.samples.length-1)return le(this.pcmData,this.pcmData.frameCnt);this.startDecode(e)}return this.parseFrame(t,e,i)};startDecode=t=>{if(t.decodeQueueSize>10)return;const i=[];let s=this.decCursorIdx;for(;s<this.samples.length;){const r=this.samples[s];if(s+=1,!r.deleted&&(i.push(r),i.length>=10))break}this.decCursorIdx=s,t.decode(i.map(r=>new EncodedAudioChunk({type:"key",timestamp:r.cts,duration:r.duration,data:r.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=Ss(this.conf,{resampleRate:L.sampleRate,volume:this.volume},t=>{this.pcmData.data.push(t),this.pcmData.frameCnt+=t[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:ne,sleepCnt:this.sleepCnt,memInfo:_e()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function Ss(l,t,e){let i=0,s=0;const r=h=>{if(s+=1,h.length!==0){if(t.volume!==1)for(const d of h)for(let f=0;f<d.length;f++)d[f]*=t.volume;h.length===1&&(h=[h[0],h[0]]),e(h)}},o=As(r),a=t.resampleRate!==l.sampleRate;let n=new AudioDecoder({output:h=>{const d=be(h);a?o(()=>Fi(d,h.sampleRate,{rate:t.resampleRate,chanCount:h.numberOfChannels})):r(d),h.close()},error:h=>{h.message.includes("Codec reclaimed due to inactivity")||c("Video AudioDecoder err",h)}});n.configure(l);function c(h,d){const f=`${h}: ${d.message}, state: ${JSON.stringify({qSize:n.decodeQueueSize,state:n.state,inputCnt:i,outputCnt:s,decoderConf:l,opts:t})}`;throw Q.error(f),Error(f)}return{decode(h){i+=h.length;try{for(const d of h)n.decode(d)}catch(d){c("decode audio chunk error",d)}},close(){n.state!=="closed"&&n.close()},get decoding(){return i>s&&n.decodeQueueSize>0},get state(){return n.state},get decodeQueueSize(){return n.decodeQueueSize}}}function As(l){const t=[];let e=0;function i(o,a){t[a]=o,s()}function s(){const o=t[e];o!=null&&(l(o),e+=1,s())}let r=0;return o=>{const a=r;r+=1,o().then(n=>i(n,a)).catch(n=>i(n,a))}}function le(l,t){const e=[new Float32Array(t),new Float32Array(t)];let i=0,s=0;for(;s<l.data.length;){const[r,o]=l.data[s];if(i+r.length>t){const a=t-i;e[0].set(r.subarray(0,a),i),e[1].set(o.subarray(0,a),i),l.data[s][0]=r.subarray(a,r.length),l.data[s][1]=o.subarray(a,o.length);break}else e[0].set(r,i),e[1].set(o,i),i+=r.length,s++}return l.data=l.data.slice(s),l.frameCnt-=t,e}async function ks(l,t){const e=l[0],i=l.at(-1);if(i==null)return[];const s=i.offset+i.size-e.offset;if(s<3e7){const r=new Uint8Array(await t.read(s,{at:e.offset}));return l.map(o=>{const a=o.offset-e.offset;return new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:r.subarray(a,a+o.size)})})}return await Promise.all(l.map(async r=>new EncodedVideoChunk({type:r.is_sync?"key":"delta",timestamp:r.cts,duration:r.duration,data:await t.read(r.size,{at:r.offset})})))}function Fs(l,t,e){if(l.state==="configured"){for(let i=0;i<t.length;i++)l.decode(t[i]);l.flush().catch(i=>{if(!(i instanceof Error))throw i;if(i.message.includes("Decoding error")&&e.onDecodingError!=null){e.onDecodingError(i);return}if(!i.message.includes("Aborted due to close"))throw i})}}function Rs(l,t){if(t!=="avc1"&&t!=="hvc1")return 0;const e=new DataView(l.buffer);for(let i=0;i<l.byteLength-4;){if(t==="avc1"){const s=e.getUint8(i+4)&31;if(s===5||s===7||s===8)return i}else if(t==="hvc1"){const s=e.getUint8(i+4)>>1&63;if(s===19||s===20||s===32||s===33||s===34)return i}i+=e.getUint32(i)+4}return-1}const Ms=2e5;function Os(l){let t=null,e=0;for(const i of l)if(!i.deleted){if(i.is_sync&&e++,e>=2)break;i.is_sync&&(t==null||i.cts<t.cts)&&(t=i)}t!=null&&t.cts<Ms&&(t.duration+=t.cts,t.cts=0)}function _e(){try{const l=performance.memory;return{jsHeapSizeLimit:l.jsHeapSizeLimit,totalJSHeapSize:l.totalJSHeapSize,usedJSHeapSize:l.usedJSHeapSize,percentUsed:(l.usedJSHeapSize/l.jsHeapSizeLimit).toFixed(3),percentTotal:(l.totalJSHeapSize/l.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}class at extends Ke{type="Text";get width(){return this._width}set width(t){Math.abs(this.width-t)<.1||(this._width=t,this._targetWidth=t,this.refreshText().then(()=>{this._explicitHeight?this.emit("propsChange",{width:t}):this.emit("propsChange",{width:t,height:this.height})}))}get height(){return this._height}_explicitHeight=!1;get isExplicitHeight(){return this._explicitHeight}resetHeightToAuto(){this._explicitHeight=!1,this._height=0,this.refreshText().then(()=>{this.emit("propsChange",{height:this.height})})}set height(t){if(Math.abs(this.height-t)<.1)return;const e=t;this._height=t,this.refreshText().then(()=>{const i=this.meta.height,r=e-i<-5;this._explicitHeight=e>0&&(r||this._explicitHeight),this.emit("propsChange",{height:this.height})})}get text(){return this._text}set text(t){this._text!==t&&(this._text=t,this.originalOpts&&this.textStyle&&this.refreshText().then(()=>{this.emit("propsChange",{text:t})}))}get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontUrl:this.originalOpts.fontUrl,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,color:this.originalOpts.color,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,shadow:this.originalOpts.shadow?{color:this.originalOpts.shadow.color??"#000000",alpha:this.originalOpts.shadow.alpha??.5,blur:this.originalOpts.shadow.blur??4,offsetX:this.originalOpts.shadow.offsetX??0,offsetY:this.originalOpts.shadow.offsetY??0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing,textCase:this.originalOpts.textCase,textDecoration:this.originalOpts.textDecoration,background:this.originalOpts.background}}set style(t){this.updateStyle(t)}get textAlign(){return this.originalOpts.align||this.originalOpts.textAlign||"left"}set textAlign(t){this.updateStyle({align:t})}get verticalAlign(){return this.originalOpts.verticalAlign||this.originalOpts.textDecoration||"top"}set verticalAlign(t){["underline","overline","strikethrough","line-through"].includes(t)?(this.updateStyle({textDecoration:t==="strikethrough"?"line-through":t}),this.originalOpts.verticalAlign=t):this.updateStyle({verticalAlign:t})}get textCase(){return this.originalOpts.textCase||"none"}set textCase(t){this.updateStyle({textCase:t})}get underline(){return this.originalOpts.textDecoration==="underline"}set underline(t){this.updateStyle({textDecoration:t?"underline":"none"})}get overline(){return this.originalOpts.textDecoration==="overline"}set overline(t){this.updateStyle({textDecoration:t?"overline":"none"})}get linethrough(){return this.originalOpts.textDecoration==="line-through"}set linethrough(t){this.updateStyle({textDecoration:t?"line-through":"none"})}_targetWidth=0;_wordCache=[];_measuredTextHeight=0;_lineHeightMultiplier=1;_fontSize=40;_textOnlyContainer=null;constructor(t,e={},i){super(),this.originalOpts={...e},this._text=t,i&&this.setRenderer(i),this._buildTextStyles(),this.ready=(async()=>(await this.refreshText(),{...this.meta}))()}_onAfterRefresh(t,e,i,s,r,o){this._populateWordCache(t,e,i,s,r,o)}async clone(){await this.ready;const t=this.textStyle,e=this.originalOpts||{},i=n=>{if(n!=null){if(typeof n=="number")return n;if(n instanceof m.Color)return n.toNumber()}},{stroke:s,strokeWidth:r}=this._cloneStrokeOpts(i),o={fontSize:e.fontSize??t.fontSize,fontFamily:e.fontFamily??(Array.isArray(t.fontFamily)?t.fontFamily[0]:typeof t.fontFamily=="string"?t.fontFamily:"Roboto"),fontUrl:e.fontUrl,fontWeight:e.fontWeight??t.fontWeight,fontStyle:e.fontStyle??t.fontStyle,align:e.align??(t.align==="justify"?"left":t.align),textCase:e.textCase,textDecoration:e.textDecoration,color:this._cloneColorOpts(i),stroke:s,strokeWidth:r,shadow:this._cloneShadowOpts(i)};if(e.wordWrap!==void 0?(o.wordWrap=e.wordWrap,o.wordWrapWidth=e.wordWrapWidth):t.wordWrap&&(o.wordWrap=t.wordWrap,o.wordWrapWidth=t.wordWrapWidth),e.background!==void 0&&(o.background=e.background),e.lineHeight!==void 0)o.lineHeight=e.lineHeight;else if(t.lineHeight!==void 0){const n=o.fontSize??t.fontSize??40;o.lineHeight=t.lineHeight/n}e.letterSpacing!==void 0?o.letterSpacing=e.letterSpacing:t.letterSpacing!==void 0&&(o.letterSpacing=t.letterSpacing);const a=new at(this.text,o);return await a.ready,this.copyStateTo(a),a.id=this.id,a.effects=[...this.effects],a}async updateStyle(t){const e=this._normalizeStyleOpts(t);this.originalOpts={...this.originalOpts,...e},this._buildTextStyles(),await this.refreshText(),this.emit("propsChange",t)}_populateWordCache(t,e,i,s,r,o){this._wordCache=this.wordTexts.map((a,n)=>({text:t[n],width:Math.ceil(a.getLocalBounds().width||a.width),height:Math.ceil(a.getLocalBounds().height||a.height),textObj:a})),this._spaceWidth=i,this._measuredTextHeight=s,this._lineHeightMultiplier=r,this._fontSize=o,this._textOnlyContainer=e}updateLayoutForWidth(t){if(!this._wordCache.length||!this._textOnlyContainer||!this.pixiTextContainer)return this._targetWidth=t,this.refreshText(),{width:this.width,height:this.height};const e=this.originalOpts.background?.paddingX??8,i=this.originalOpts.background?.paddingY??4,s=this._lineHeightMultiplier,o=this._fontSize*s,a=this._measuredTextHeight,n=this._spaceWidth,c=Math.max(1,t-e*2),h=[];let d=[],f=0,u=0;for(let A=0;A<this._wordCache.length;A++){const E=this._wordCache[A],P=E.width,R=E.height,B=f+(f>0?n:0)+P;B<=c||d.length===0?(d.push(A),f=B,u=Math.max(u,R)):(d.length>0&&h.push({wordIndices:d,width:f,height:Math.max(u,o)}),d=[A],f=P,u=R)}d.length>0&&h.push({wordIndices:d,width:f,height:Math.max(u,o)});const p=a+i*2;h.forEach(A=>{A.height=Math.max(A.height,p)});let g=0,v=0;h.forEach(A=>{g=Math.max(g,A.width),v+=A.height});const x=g+e*2,w=v,T=Math.max(x,t),y=w,C=this.textAlign,k=this.originalOpts.verticalAlign||"top";let O=0;k==="center"?O=(y-w)/2:k==="bottom"&&(O=y-w);let F=O;h.forEach(A=>{let E=0;C==="center"?E=(T-A.width)/2:C==="right"?E=T-A.width-e*2:E=e,A.wordIndices.forEach((P,R)=>{const B=this._wordCache[P];B.textObj&&(B.textObj.x=Math.round(E),B.textObj.y=Math.round(F+(A.height-a)/2-9)),E+=B.width+(R<A.wordIndices.length-1?n:0)}),F+=A.height}),this._meta.width=T,this._meta.height=y,this._width=T,this._height=y,this._targetWidth=T;const b=T+(this.renderTexturePadding??0)*2,S=y+(this.renderTexturePadding??0)*2;return this.renderTexture&&(Math.abs(this.renderTexture.width-b)>10||Math.abs(this.renderTexture.height-S)>10)&&this.getTexture(),{width:T,height:y}}toJSON(t=!1){const e=super.toJSON(t),i={};return this.originalOpts.fontSize!==void 0&&(i.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(i.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontUrl!==void 0&&(i.fontUrl=this.originalOpts.fontUrl),this.originalOpts.fontWeight!==void 0&&(i.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(i.fontStyle=this.originalOpts.fontStyle),this.originalOpts.color!==void 0&&(i.color=this.originalOpts.color),this.originalOpts.align!==void 0&&(i.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(i.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(i.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(i.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(i.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.background!==void 0&&(i.background=this.originalOpts.background),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?i.stroke={color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:i.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.shadow&&(i.shadow={color:this.originalOpts.shadow.color??"#000000",alpha:this.originalOpts.shadow.alpha??.5,blur:this.originalOpts.shadow.blur??4,offsetX:this.originalOpts.shadow.offsetX??0,offsetY:this.originalOpts.shadow.offsetY??0}),{...e,type:"Text",text:this.text,style:i,id:this.id,effects:this.effects}}static async fromObject(t){if(t.type!=="Text")throw new Error(`Expected Text, got ${t.type}`);const e=t.text||"",i=t.style||{},s={};i.fontSize!==void 0&&(s.fontSize=i.fontSize),i.fontFamily!==void 0&&(s.fontFamily=i.fontFamily),i.fontUrl!==void 0&&(s.fontUrl=i.fontUrl),i.fontWeight!==void 0&&(s.fontWeight=i.fontWeight),i.fontStyle!==void 0&&(s.fontStyle=i.fontStyle),i.color!==void 0&&(s.color=i.color),i.align!==void 0&&(s.align=i.align),i.wordWrap!==void 0&&(s.wordWrap=i.wordWrap),i.wordWrapWidth!==void 0&&(s.wordWrapWidth=i.wordWrapWidth),i.lineHeight!==void 0&&(s.lineHeight=i.lineHeight),i.letterSpacing!==void 0&&(s.letterSpacing=i.letterSpacing),i.background!==void 0&&(s.background=i.background),i.stroke&&(i.stroke.join||i.stroke.cap||i.stroke.miterLimit!==void 0?s.stroke={color:i.stroke.color,width:i.stroke.width,join:i.stroke.join,cap:i.stroke.cap,miterLimit:i.stroke.miterLimit}:(s.stroke=i.stroke.color,s.strokeWidth=i.stroke.width)),i.shadow&&(s.shadow={color:i.shadow.color,alpha:i.shadow.alpha,blur:i.shadow.blur,offsetX:i.shadow.offsetX??0,offsetY:i.shadow.offsetY??0});const r=new at(e,s);return X.deserializeBaseProperties(r,t),t.effects&&(r.effects=t.effects),await r.ready,r}getVisibleHandles(){return["mr","mb","br","rot"]}}function Es(l){return l.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,t=>t.toUpperCase())}class lt extends X{type="Effect";ready;_meta={duration:5e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effectKey;values={};constructor(t){super(),this.effectKey=t,this.name=Es(t),this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const t=new lt(this.effectKey);return this.copyStateTo(t),t.values={...this.values},t}async tick(t){return{video:void 0,state:"success"}}async split(t){const e=await this.clone(),i=await this.clone();return[e,i]}toJSON(t=!1){return{id:this.id,type:"Effect",name:this.name,timing:{display:{from:this.timing.display.from,to:this.timing.display.to},trim:{from:this.timing.trim.from,to:this.timing.trim.to},duration:this.timing.duration,playbackRate:this.timing.playbackRate},effectKey:this.effectKey,values:this.values}}static async fromObject(t){if(t.type!=="Effect")throw new Error(`Expected Effect, got ${t.type}`);const e=t.effectKey;if(!e)throw new Error("Missing effectKey in Effect JSON");const i=new lt(e);return i.values=t.values||{},X.deserializeBaseProperties(i,t),await i.ready,i}}class Bt extends X{type="Placeholder";meta={width:0,height:0,duration:0};constructor(t,e={},i="Placeholder"){super(),this.type=i,this.src=t,this.meta={width:e.width||1280,height:e.height||720,duration:e.duration||5e6},this.width=this.meta.width,this.height=this.meta.height,this.duration=this.meta.duration,this.trim.to=this.duration,this.display.to=this.display.from+this.duration,this.ready=Promise.resolve(this.meta)}canvas=null;ctx=null;animationRafId=null;renderPending=!1;async tick(t){this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.width=this.meta.width,this.canvas.height=this.meta.height,this.ctx=this.canvas.getContext("2d"));const{canvas:e,ctx:i}=this;if(i){const{width:r,height:o}=e;if(r>0&&o>0){i.fillStyle="#1e1e1e",i.fillRect(0,0,r,o);const a=r/2,n=o/2,c=100,h=c/4,d=performance.now()/2e3*Math.PI*2;i.save();const f=i.createConicGradient(d,a,n);f.addColorStop(0,"#ffffff"),f.addColorStop(.2,"#ffffff"),f.addColorStop(.5,"rgba(255, 255, 255, 0.4)"),f.addColorStop(.8,"rgba(255, 255, 255, 0.1)"),f.addColorStop(1,"rgba(255, 255, 255, 0)"),i.strokeStyle=f,i.lineWidth=h,i.lineCap="round",i.beginPath(),i.arc(a,n,c,d,d+Math.PI*1.5),i.stroke(),i.restore(),i.strokeStyle="#333333",i.lineWidth=10,i.strokeRect(0,0,r,o)}}if(this.renderPending=!1,this.animationRafId===null){const r=()=>{if(this.destroyed){this.animationRafId=null;return}this.renderPending||(this.renderPending=!0,this.emit("request-render")),this.animationRafId=requestAnimationFrame(r)};this.animationRafId=requestAnimationFrame(r)}return{video:e.width>0&&e.height>0?await createImageBitmap(e):null,state:"success",audio:[]}}async clone(){const t=new Bt(this.src,this.meta);return this.copyStateTo(t),t.id=this.id,t}async split(t){const e=await this.clone(),i=await this.clone();return e.trim.to=t+this.trim.from,i.trim.from=t+this.trim.from,e.duration=e.trim.to-e.trim.from,i.duration=i.trim.to-i.trim.from,e.display.to=e.display.from+e.duration,i.display.from=e.display.to,i.display.to=i.display.from+i.duration,[e,i]}static async fromObject(t){if(t.type!=="Placeholder")throw new Error(`Expected Placeholder, got ${t.type}`);const e=t.timing||{display:t.display||{},trim:t.trim||{},duration:t.duration??0,playbackRate:t.playbackRate??1},i=t.transform?.width??t.width??0,s=t.transform?.height??t.height??0,r=new Bt(t.src,{width:i,height:s,duration:e.duration});return X.deserializeBaseProperties(r,t),await r.ready,r}}class tt extends X{type="Transition";ready;_meta={duration:2e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;transitionKey;fromClipId=null;toClipId=null;values={};constructor(t){super(),this.transitionKey=t,this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const t=new tt(this.transitionKey);return this.copyStateTo(t),t.fromClipId=this.fromClipId,t.toClipId=this.toClipId,t.values=JSON.parse(JSON.stringify(this.values)),t}async tick(t){return{video:void 0,state:"success"}}async split(t){const e=await this.clone(),i=await this.clone();return[e,i]}toJSON(t=!1){return{id:this.id,type:"Transition",name:this.name,timing:{display:{from:this.timing.display.from,to:this.timing.display.to},trim:{from:this.timing.trim.from,to:this.timing.trim.to},duration:this.timing.duration,playbackRate:this.timing.playbackRate},transitionKey:this.transitionKey,fromClipId:this.fromClipId,toClipId:this.toClipId,...Object.keys(this.values).length>0&&{values:this.values}}}static async fromObject(t){if(t.type!=="Transition")throw new Error(`Expected Transition, got ${t.type}`);const e=t.transitionKey;if(!e)throw new Error("Missing transitionKey in Transition JSON");const i=new tt(e);return i.fromClipId=t.fromClipId||null,i.toClipId=t.toClipId||null,i.values=t.values||{},X.deserializeBaseProperties(i,t),await i.ready,i}}class Nt extends X{type="Shape";shapeType;graphics;_meta;renderTexture=null;externalRenderer=null;constructor(t){super(),this.shapeType=t.shapeType,this.id=qt.nanoid(),this.name=`${t.shapeType} Shape`,this.src=`shape://${t.shapeType}`,this.externalRenderer=t.renderer??null,this.width=t.width??200,this.height=t.height??200,this.graphics=new m.Graphics,this._meta={width:this.width,height:this.height,duration:0},this.style={fill:t.fill??"#3b82f6",fillOpacity:t.fillOpacity??1,stroke:t.stroke??{color:"#1e40af",width:2},borderRadius:t.borderRadius??0},this.ready=Promise.resolve(this._meta)}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;throw new Error("ShapeClip: No renderer available. Provide a renderer via options.renderer or setRenderer().")}setRenderer(t){this.externalRenderer=t}async getRenderTexture(){return this.renderTexture==null&&(this.renderTexture=m.RenderTexture.create({width:Math.ceil(this.width),height:Math.ceil(this.height)})),(this.renderTexture.width!==Math.ceil(this.width)||this.renderTexture.height!==Math.ceil(this.height))&&this.renderTexture.resize(Math.ceil(this.width),Math.ceil(this.height)),this.renderTexture}get meta(){return this._meta}drawShape(){const t=this.style;if(this.graphics.clear(),this.drawRectangle(t),t.fill){const e=this.hexToNumber(t.fill);this.graphics.fill({color:e,alpha:t.fillOpacity??1})}if(t.stroke){const e=this.hexToNumber(t.stroke.color);this.graphics.stroke({color:e,width:t.stroke.width,alpha:1})}}drawRectangle(t){const e=t.borderRadius??0;e>0?this.graphics.roundRect(-this.width/2,-this.height/2,this.width,this.height,e):this.graphics.rect(-this.width/2,-this.height/2,this.width,this.height)}hexToNumber(t){const e=t.startsWith("#")?t.slice(1):t;return parseInt(e,16)}async tick(t){await this.ready;const e=await this.getRenderTexture();this.drawShape();const i=await this.getRenderer();this.graphics.x=this.width/2,this.graphics.y=this.height/2,i.render({container:this.graphics,target:e});const s=e.source?.resource?.source;let r;if(s instanceof HTMLCanvasElement||s instanceof OffscreenCanvas)r=await createImageBitmap(s);else{const a=i.extract.canvas(e);if(a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas)r=await createImageBitmap(a);else throw new Error("Unable to extract canvas from render texture")}return{video:r,state:"success"}}async clone(){const t=new Nt({shapeType:this.shapeType,width:this.width,height:this.height,fill:this.style.fill,fillOpacity:this.style.fillOpacity,stroke:this.style.stroke,borderRadius:this.style.borderRadius});return t.left=this.left,t.top=this.top,t.angle=this.angle,t.opacity=this.opacity,t.zIndex=this.zIndex,t.display={...this.display},t.duration=this.duration,t.timing={...this.timing},t}async split(t){const e=await this.clone(),i=await this.clone();return[e,i]}toJSON(t=!1){return{...super.toJSON(t),shapeType:this.shapeType}}set style(t){super.style=t,this.graphics&&this.drawShape()}get style(){return super.style}set width(t){super.width=t,this.graphics&&this.drawShape(),this.renderTexture&&this.renderTexture.resize(Math.ceil(this.width),Math.ceil(this.height))}get width(){return super.width}set height(t){super.height=t,this.graphics&&this.drawShape(),this.renderTexture&&this.renderTexture.resize(Math.ceil(this.width),Math.ceil(this.height))}get height(){return super.height}static async fromObject(t){const e=new Nt({shapeType:t.shapeType,width:t.transform?.width,height:t.transform?.height,fill:t.style?.fill,fillOpacity:t.style?.fillOpacity,stroke:t.style?.stroke,borderRadius:t.style?.borderRadius});return X.deserializeBaseProperties(e,t),e}}const Ds=["#6A5AF9","#B14EFF","#FF7A7A"];class zt extends X{type="Backdrop";backdropType;container;_meta;renderTexture=null;externalRenderer=null;bgGraphics=null;meshContainer=null;meshCircles=[];blobsContainer=null;blobCircles=[];noiseSprite=null;noiseTexture=null;constructor(t){super(),this.backdropType=t.backdropType,this.id=qt.nanoid(),this.name=`${t.backdropType} Backdrop`,this.src=`backdrop://${t.backdropType}`,this.externalRenderer=t.renderer??null,this.width=t.width??1280,this.height=t.height??720,this.container=new m.Container,this.container.label="BackdropContainer",this._meta={width:this.width,height:this.height,duration:1/0},this.style={backdropType:t.backdropType,colors:t.colors??Ds,gradientType:t.gradientType??"linear",speed:t.speed??1,scale:t.scale??1,density:t.density??8},this.ready=Promise.resolve(this._meta),this.rebuildBackdrop()}setRenderer(t){this.externalRenderer=t}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;throw new Error("BackdropClip: No renderer available. Provide a renderer via options.renderer or setRenderer().")}async getRenderTexture(){const t=Math.max(1,Math.ceil(this.width)),e=Math.max(1,Math.ceil(this.height));return this.renderTexture==null&&(this.renderTexture=m.RenderTexture.create({width:t,height:e})),(this.renderTexture.width!==t||this.renderTexture.height!==e)&&this.renderTexture.resize(t,e),this.renderTexture}get meta(){return this._meta}rebuildBackdrop(){this.container.removeChildren(),this.bgGraphics=null,this.meshContainer=null,this.meshCircles=[],this.blobsContainer=null,this.blobCircles=[],this.noiseSprite=null;const t=this.style,e=t.backdropType||this.backdropType;this.backdropType=e;const i=t.colors||["#6A5AF9"],s=i.map(o=>$(o)??16777215),r=()=>{this.bgGraphics=new m.Graphics,this.bgGraphics.rect(0,0,this.width,this.height).fill({color:s[0]}),this.container.addChild(this.bgGraphics)};if(e==="solid")r();else if(e==="gradient")if((t.gradientType??"linear")==="radial"){const o=document.createElement("canvas");o.width=Math.max(1,Math.ceil(this.width)),o.height=Math.max(1,Math.ceil(this.height));const a=o.getContext("2d"),n=this.width/2,c=this.height/2,h=Math.min(this.width,this.height)/2,d=a.createRadialGradient(n,c,0,n,c,h);i.forEach((f,u)=>d.addColorStop(u/Math.max(1,i.length-1),f)),a.fillStyle=d,a.fillRect(0,0,this.width,this.height),this.container.addChild(new m.Sprite(m.Texture.from(o)))}else{this.bgGraphics=new m.Graphics;const o=new m.FillGradient(0,0,this.width,this.height);s.forEach((a,n)=>o.addColorStop(n/Math.max(1,s.length-1),a)),this.bgGraphics.rect(0,0,this.width,this.height).fill(o),this.container.addChild(this.bgGraphics)}else if(e==="meshGradient"){r(),this.meshContainer=new m.Container,this.meshContainer.label="MeshContainer";const o=Math.max(3,s.length),a=Math.max(this.width,this.height)*.35;this.meshContainer.filters=[new m.BlurFilter({strength:a})];for(let n=0;n<o;n++){const c=new m.Graphics,h=Math.max(this.width,this.height)*(.35+Math.random()*.15);c.circle(0,0,h).fill({color:s[n%s.length],alpha:.8});const d={graphics:c,baseX:this.width*(.2+Math.random()*.6),baseY:this.height*(.2+Math.random()*.6),phase:Math.random()*Math.PI*2,speedX:.3+Math.random()*.4,speedY:.3+Math.random()*.4,radius:h};c.x=d.baseX,c.y=d.baseY,this.meshContainer.addChild(c),this.meshCircles.push(d)}this.container.addChild(this.meshContainer)}else if(e==="floatingBlobs"){r(),this.blobsContainer=new m.Container,this.blobsContainer.label="BlobsContainer";const o=Math.max(4,t.density??8),a=s.slice(1).length>0?s.slice(1):s,n=Math.max(this.width,this.height)*.08;this.blobsContainer.filters=[new m.BlurFilter({strength:n})];for(let c=0;c<o;c++){const h=new m.Graphics,d=Math.max(this.width,this.height)*(.1+Math.random()*.12);h.circle(0,0,d).fill({color:a[c%a.length],alpha:.6});const f={graphics:h,baseX:this.width*Math.random(),baseY:this.height*Math.random(),phase:Math.random()*Math.PI*2,speedX:.2+Math.random()*.3,speedY:.2+Math.random()*.3,radius:d};h.x=f.baseX,h.y=f.baseY,this.blobsContainer.addChild(h),this.blobCircles.push(f)}this.container.addChild(this.blobsContainer)}else if(e==="noise"){if(r(),!this.noiseTexture){const o=document.createElement("canvas");o.width=256,o.height=256;const a=o.getContext("2d"),n=a.createImageData(256,256),c=n.data;for(let h=0;h<c.length;h+=4){const d=Math.floor(Math.random()*255);c[h]=d,c[h+1]=d,c[h+2]=d,c[h+3]=18}a.putImageData(n,0,0),this.noiseTexture=m.Texture.from(o)}this.noiseSprite=new m.TilingSprite({texture:this.noiseTexture,width:this.width,height:this.height}),this.noiseSprite.tileScale.set(t.scale??1),this.container.addChild(this.noiseSprite)}}async tick(t){await this.ready;const e=await this.getRenderTexture(),i=await this.getRenderer(),s=t/1e6*(this.style.speed??1);if(this.backdropType==="meshGradient"&&this.meshCircles.length>0){const a=this.style.scale??1;for(const n of this.meshCircles){const c=s*n.speedX+n.phase,h=s*n.speedY+n.phase*1.5;n.graphics.x=n.baseX+Math.cos(c)*(this.width*.25*a),n.graphics.y=n.baseY+Math.sin(h)*(this.height*.25*a)}}if(this.backdropType==="floatingBlobs"&&this.blobCircles.length>0){const a=this.style.scale??1;for(const n of this.blobCircles){const c=s*n.speedX+n.phase,h=s*n.speedY+n.phase*1.3;n.graphics.x=(n.baseX+Math.sin(c)*(this.width*.35*a)+this.width)%this.width,n.graphics.y=(n.baseY+Math.cos(h)*(this.height*.35*a)+this.height)%this.height}}this.backdropType==="noise"&&this.noiseSprite&&(this.noiseSprite.tilePosition.x=Math.random()*256,this.noiseSprite.tilePosition.y=Math.random()*256),i.render({container:this.container,target:e});const r=e.source?.resource?.source;let o;if(r instanceof HTMLCanvasElement||r instanceof OffscreenCanvas)o=await createImageBitmap(r);else{const a=i.extract.canvas(e);if(a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas)o=await createImageBitmap(a);else throw new Error("Unable to extract canvas from render texture")}return{video:o,state:"success"}}async clone(){const t=new zt({backdropType:this.backdropType,width:this.width,height:this.height,colors:this.style.colors,gradientType:this.style.gradientType,speed:this.style.speed,scale:this.style.scale,density:this.style.density});return t.left=this.left,t.top=this.top,t.angle=this.angle,t.opacity=this.opacity,t.zIndex=this.zIndex,t.display={...this.display},t.duration=this.duration,t.timing={...this.timing},t}async split(t){return[await this.clone(),await this.clone()]}toJSON(t=!1){return{...super.toJSON(t),backdropType:this.backdropType}}set style(t){super.style=t,this.container&&this.rebuildBackdrop()}get style(){return super.style}set width(t){super.width=t,this.container&&this.rebuildBackdrop(),this.renderTexture?.resize(Math.max(1,Math.ceil(this.width)),Math.max(1,Math.ceil(this.height)))}get width(){return super.width}set height(t){super.height=t,this.container&&this.rebuildBackdrop(),this.renderTexture?.resize(Math.max(1,Math.ceil(this.width)),Math.max(1,Math.ceil(this.height)))}get height(){return super.height}static async fromObject(t){const e=new zt({backdropType:t.backdropType,width:t.transform?.width,height:t.transform?.height,colors:t.style?.colors,gradientType:t.style?.gradientType,speed:t.style?.speed,scale:t.style?.scale,density:t.style?.density});return X.deserializeBaseProperties(e,t),e}}class st{static registry=new Map;static register(t,e){this.registry.set(t,e)}static get(t){return this.registry.get(t)}static getRegisteredTypes(){return Array.from(this.registry.keys())}}st.register("Video",nt),st.register("Audio",ut),st.register("Image",It),st.register("Text",at),st.register("Caption",mt),st.register("Effect",lt),st.register("Transition",tt),st.register("Placeholder",Bt),st.register("Shape",Nt),st.register("Backdrop",zt);function $e(l,t){let e=!1;async function i(){const s=l.getReader();for(;!e;){const{value:r,done:o}=await s.read();if(o){t.onDone();return}await t.onChunk(r)}s.releaseLock(),await l.cancel()}return i().catch(console.error),()=>{e=!0}}class ti{readable;writable;inputBufOffset=0;isStreamCancelled=!1;constructor(){const t=et.mp4box.createFile();this.readable=new ReadableStream({start:e=>this.initMP4Box(t,e),cancel:()=>{this.isStreamCancelled=!0,t.stop()}},{highWaterMark:50}),this.writable=new WritableStream({write:async e=>{if(this.isStreamCancelled)throw new Error("Stream cancelled");const i=e.buffer;i.fileStart=this.inputBufOffset,this.inputBufOffset+=i.byteLength,t.appendBuffer(i)},close:()=>{t.flush(),t.stop(),t.onFlush?.()},abort:e=>{Ps.error("SampleTransform writable aborted:",e),t.stop()}})}initMP4Box(t,e){t.onReady=s=>{[s.videoTracks[0],s.audioTracks[0]].forEach(r=>{r&&t.setExtractionOptions(r.id,r.video?"video":"audio",{nbSamples:100})}),e.enqueue({chunkType:"ready",data:{info:s,file:t}}),t.start()};const i={};t.onSamples=(s,r,o)=>{const a=o.map(n=>({...n}));e.enqueue({chunkType:"samples",data:{id:s,type:r,samples:a}}),i[s]=(i[s]??0)+o.length,t.releaseUsedSamples(s,i[s])},t.onFlush=()=>{e.close()},t.onError=s=>{e.error(new Error(`mp4box error: ${s}`))}}}const Ps={error:(...l)=>console.error("[SampleTransform]",...l)};function Is(l){let t=0;const e=l.boxes,i=[];let s=0;async function r(){const p=u(e,t);t=e.length,i.forEach(({track:g,id:v})=>{const x=g.samples.at(-1);x!=null&&(s=Math.max(s,x.cts+x.duration)),l.releaseUsedSamples(v,g.samples.length),g.samples=[]}),l.mdats=[],l.moofs=[],p!=null&&await h?.write(p)}let o=[];function a(){if(o.length>0)return!0;const p=e.findIndex(g=>g.type==="moov");if(p===-1)return!1;if(o=e.slice(0,p+1),t=p+1,i.length===0)for(let g=1;;g+=1){const v=l.getTrackById(g);if(v==null)break;i.push({track:v,id:g})}return!0}let n=0;const c=it.tmpfile();let h=null;const d=(async()=>{h=await c.createWriter(),n=self.setInterval(()=>{a()&&r()},100)})();let f=!1;return async()=>{if(f)throw Error("File exported");if(f=!0,await d,clearInterval(n),!a()||h==null)return null;l.flush(),await r(),await h?.close();const p=o.find(x=>x.type==="moov");if(p==null)return null;p.mvhd.duration=s;const g=it.tmpfile(),v=u(o,0);return await it.write(g,v.slice()),await it.write(g,c,{overwrite:!1}),await g.stream()};function u(p,g){if(g>=p.length)return null;const v=new et.mp4box.DataStream;for(let x=g;x<p.length;x++)p[x]!==null&&(p[x].write(v),delete p[x]);return new Uint8Array(v.buffer).slice()}}function Bs(l){const t=new ArrayBuffer(l.byteLength);l.copyTo(t);const e=l.timestamp;return{duration:l.duration??0,dts:e,cts:e,is_sync:l.type==="key",data:t}}async function ei(l){const t=et.mp4box.createFile(),e=Is(t);await Ns(l,t);const i=await e();if(i==null)throw Error("Can not generate file from streams");return i}async function Ns(l,t){let e=0,i=0,s=0,r=0,o=0,a=0,n=null,c=null;for(const h of l){let d=null,f=null,u=null,p=null;if(await new Promise(async g=>{$e(h.pipeThrough(new ti),{onDone:g,onChunk:async({chunkType:v,data:x})=>{if(v==="ready"){const{videoTrackConf:w,audioTrackConf:T}=oe(x.file,x.info);e===0&&w!=null&&(e=t.addTrack(w)),r===0&&T!=null&&(r=t.addTrack(T))}else if(v==="samples"){const{type:w,samples:T}=x,y=w==="video"?e:r,C=w==="video"?i:o,k=w==="video"?s:a;T.forEach(F=>{let b,S;w==="video"?(d===null&&(d=F.dts,f=F.cts),b=F.dts-d,S=F.cts-(f??0)):(u===null&&(u=F.dts,p=F.cts),b=F.dts-u,S=F.cts-(p??0)),t.addSample(y,new Uint8Array(F.data),{duration:F.duration,dts:b+C,cts:S+k,is_sync:F.is_sync})});const O=T.at(-1);if(O==null)return;w==="video"?n=O:w==="audio"&&(c=O)}}})}),n!=null&&d!==null&&f!==null){const g=n.dts-d+n.duration,v=n.cts-f+n.duration;i+=g,s+=v}if(c!=null&&n!=null){const g=c.timescale/n.timescale;o=Math.round(i*g),a=Math.round(s*g)}}}async function zs(l){return await ei([l])}function Ls(l){let t=[];const e=new AudioDecoder({output:i=>{t.push(i)},error:Q.error});return e.configure(l),{decode:async i=>{i.forEach(r=>{e.decode(new EncodedAudioChunk({type:r.is_sync?"key":"delta",timestamp:1e6*r.cts/r.timescale,duration:1e6*r.duration/r.timescale,data:r.data}))}),await e.flush();const s=t;return t=[],s},close:()=>{e.close()}}}function Hs(l,t){const e={codec:l.codec,sampleRate:l.sampleRate,numberOfChannels:l.numberOfChannels},i=new AudioEncoder({output:o=>{t(Bs(o))},error:o=>{Q.error("AudioEncoder error:",o,", config:",e)}});i.configure(e);let s=null;function r(o,a){return new AudioData({timestamp:a,numberOfChannels:l.numberOfChannels,numberOfFrames:o.length/l.numberOfChannels,sampleRate:l.sampleRate,format:"f32-planar",data:new Float32Array(o)})}return{encode:async(o,a)=>{s!=null&&i.encode(r(s.data,s.ts)),s={data:o,ts:a}},stop:async()=>{s!=null&&(Gs(s.data,l.numberOfChannels,l.sampleRate),i.encode(r(s.data,s.ts)),s=null),await i.flush(),i.close()}}}function Gs(l,t,e){const i=l.length-1,s=Math.min(e/2,i);for(let r=0;r<s;r++)for(let o=1;o<=t;o++)l[Math.floor(i/o)-r]*=r/s}function Us(l,t){Q.info("mixinMP4AndAudio, opts:",{volume:t.volume,loop:t.loop});const e=et.mp4box.createFile();let i,s=0,r=0;const o=e.boxes;let a=!1;const n=()=>{if(!a)if(o.find(A=>A.type==="moof")!=null)a=!0;else return null;if(r>=o.length)return null;const F=new et.mp4box.DataStream;let b=r;try{for(;b<o.length;)o[b].write(F),delete o[b],b+=1}catch(A){throw A}if(e.moov!=null){for(var S=0;S<e.moov.traks.length;S++)e.moov.traks[S].samples=[];e.mdats=[],e.moofs=[]}return r=o.length,new Uint8Array(F.buffer)};let c=!1,h=!1,d=null;i=new ReadableStream({start(F){s=self.setInterval(()=>{const b=n();b!=null&&!h&&F.enqueue(b)},500),d=b=>{if(clearInterval(s),e.flush(),b!=null){F.error(b);return}const S=n();S!=null&&!h&&F.enqueue(S),h||F.close()}},cancel(){h=!0,clearInterval(s)}});const f=F=>{c||(c=!0,d?.(F))};let u=null,p=null,g=[],v=0,x=0,w=0,T=!0,y=L.sampleRate;$e(l.pipeThrough(new ti),{onDone:async()=>{await p?.stop(),u?.close(),f()},onChunk:async({chunkType:F,data:b})=>{if(F==="ready"){const{videoTrackConf:S,audioTrackConf:A,audioDecoderConf:E}=oe(b.file,b.info);v===0&&S!=null&&(v=e.addTrack(S));const P=A??{timescale:1e6,samplerate:y,channel_count:L.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};x===0&&(x=e.addTrack(P),y=A?.samplerate??y,T=A!=null);const R=new AudioContext({sampleRate:y});g=_t(await R.decodeAudioData(await new Response(t.stream).arrayBuffer())),E!=null&&(u=Ls(E)),p=Hs(E??{codec:P.type==="mp4a"?L.codec:P.type,numberOfChannels:P.channel_count,sampleRate:P.samplerate},B=>e.addSample(x,new Uint8Array(B.data),B))}else if(F==="samples"){const{id:S,type:A,samples:E}=b;if(A==="video"){E.forEach(P=>e.addSample(S,new Uint8Array(P.data),P)),T||await k(E);return}A==="audio"&&await O(E)}}});function C(F){const b=g.map(S=>t.loop?$t(S,w,w+F):S.slice(w,w+F));if(w+=F,t.volume!==1)for(const S of b)for(let A=0;A<S.length;A++)S[A]*=t.volume;return b}async function k(F){const b=F[0],S=F[F.length-1],A=Math.floor((S.cts+S.duration-b.cts)/b.timescale*y),E=Ce([C(A)]);E.length!==0&&p?.encode(E,b.cts/b.timescale*1e6)}async function O(F){if(u==null)return;const b=(await u.decode(F)).map(be),S=Si(b),A=C(S[0].length),E=F[0];p?.encode(Ce([S,A]),E.cts/E.timescale*1e6)}return i}function Ws(l){const t={...l};if(t.timing?t.timing={display:t.timing.display||{from:0,to:0},trim:t.timing.trim||{from:0,to:0},duration:t.timing.duration??0,playbackRate:t.timing.playbackRate??1,fadeIn:t.timing.fadeIn??l.fadeIn,fadeOut:t.timing.fadeOut??l.fadeOut}:t.timing={display:l.display||{from:0,to:0},trim:l.trim||{from:0,to:0},duration:l.duration??0,playbackRate:l.playbackRate??1,fadeIn:l.fadeIn,fadeOut:l.fadeOut},delete t.fadeIn,delete t.fadeOut,t.transform)t.transform={x:t.transform.x??0,y:t.transform.y??0,width:t.transform.width??0,height:t.transform.height??0,angle:t.transform.angle??0,opacity:t.transform.opacity??1,zIndex:t.transform.zIndex??0,flip:t.transform.flip||null};else{const e=l;t.transform={x:e.left??0,y:e.top??0,width:e.width??0,height:e.height??0,angle:e.angle??0,opacity:e.opacity??1,zIndex:e.zIndex??0,flip:e.flip||null}}return t.style&&(t.style=Vs(t.style,l.type)),t}function Vs(l,t){if(!l)return l;const e={...l};if(e.dropShadow&&(e.shadow=e.dropShadow,delete e.dropShadow),e.shadow){const i={...e.shadow},s=i.offsetX!==void 0||i.offsetY!==void 0;if((i.distance!==void 0||i.angle!==void 0)&&!s){const o=i.distance??0,a=i.angle??0;i.offsetX=Math.cos(a)*o,i.offsetY=Math.sin(a)*o}delete i.distance,delete i.angle,e.shadow=i}return(t==="Text"||t==="Caption")&&e.fill!==void 0&&(e.color=e.fill,delete e.fill),e}function Lt(l,t=!1){return l.toJSON(t)}async function xt(l,t){const e=Ws(l);let i;const s=st.get(e.type);if(s&&typeof s.fromObject=="function")i=await s.fromObject(e,t);else throw new Error(`Unsupported clip type or missing fromObject: ${e.type}`);if(e.animations&&Array.isArray(e.animations)){i.clearAnimations();for(const r of e.animations)i.addAnimation(r.type,r.options,r.params)}return e.id&&(i.id=e.id),e.name&&(i.name=e.name),e.metadata&&(i.metadata=e.metadata),i}const ii=new MessageChannel;function si(){return new Promise(l=>{ii.port1.onmessage=()=>l(),ii.port2.postMessage(null)})}const Ys=20;async function Qs(l){for(;l()>Ys;)await si()}const js=`
185
185
  in vec2 vTextureCoord;
186
186
  in vec4 vColor;
187
187