@designcombo/video 0.1.0 → 0.1.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.
- package/dist/{SharedSystems-CQqgfMHK.js → SharedSystems-CaP5H7w0.js} +1 -1
- package/dist/{WebGLRenderer-ykSSlgbE.js → WebGLRenderer-BMj90BH-.js} +2 -2
- package/dist/{WebGPURenderer-CHHoT8My.js → WebGPURenderer-B7z3CK54.js} +2 -2
- package/dist/{browserAll-BdVABEgU.js → browserAll-DRgdBopC.js} +2 -2
- package/dist/{index-C2lxQ7Li.js → index-CDnMjIGb.js} +88 -79
- package/dist/index.es.js +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/{webworkerAll-BnqyxwPv.js → webworkerAll-D0RTOtmO.js} +1 -1
- package/package.json +3 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as Ie, u as Ee, l as se, M as v, G as De, v as Oe, S as Fe, x as ae, E as u, e as D, y as S, z as Le, H as O, I as b, R as F, J as ne, K as He, t as m, b as f, i as B, w as L, L as K, N as We, c as Y, B as y, j as U, O as ze, Q as C, k as M, V as w, W as Ve, a as Ne, X as ie, Y as oe, Z as le, _ as ue, C as P, $ as je, a0 as A, a1 as J, D as H, a2 as $e, a3 as qe, P as Ke, d as Ye, T as X, a4 as Q, a5 as Je, a6 as Xe, a7 as Qe } from "./index-
|
|
1
|
+
import { F as Ie, u as Ee, l as se, M as v, G as De, v as Oe, S as Fe, x as ae, E as u, e as D, y as S, z as Le, H as O, I as b, R as F, J as ne, K as He, t as m, b as f, i as B, w as L, L as K, N as We, c as Y, B as y, j as U, O as ze, Q as C, k as M, V as w, W as Ve, a as Ne, X as ie, Y as oe, Z as le, _ as ue, C as P, $ as je, a0 as A, a1 as J, D as H, a2 as $e, a3 as qe, P as Ke, d as Ye, T as X, a4 as Q, a5 as Je, a6 as Xe, a7 as Qe } from "./index-CDnMjIGb.js";
|
|
2
2
|
import { B as de, c as Ze } from "./colorToUniform-C2jGzNe1.js";
|
|
3
3
|
var et = `in vec2 vMaskCoord;
|
|
4
4
|
in vec2 vTextureCoord;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { S as G, E as d, B as v, w as m, D as S, L as j, v as ve, s as U, t as b, a8 as Be, k as K, a9 as Ae, b as p, V as L, j as B, i as A, l as F, M as $, aa as z, ab as Ne, ac as ye, ad as Y, ae as Ce, A as De, R as Ie, e as T } from "./index-
|
|
1
|
+
import { S as G, E as d, B as v, w as m, D as S, L as j, v as ve, s as U, t as b, a8 as Be, k as K, a9 as Ae, b as p, V as L, j as B, i as A, l as F, M as $, aa as z, ab as Ne, ac as ye, ad as Y, ae as Ce, A as De, R as Ie, e as T } from "./index-CDnMjIGb.js";
|
|
2
2
|
import { b as q } from "./colorToUniform-C2jGzNe1.js";
|
|
3
|
-
import { e as Ge, G as Ue, c as Fe, b as Oe, U as Pe, R as Me, B as Z, d as N, f as Le, S as He, a as we } from "./SharedSystems-
|
|
3
|
+
import { e as Ge, G as Ue, c as Fe, b as Oe, U as Pe, R as Me, B as Z, d as N, f as Le, S as He, a as we } from "./SharedSystems-CaP5H7w0.js";
|
|
4
4
|
class Q {
|
|
5
5
|
constructor() {
|
|
6
6
|
this._tempState = G.for2d(), this._didUploadHash = {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { S as E, g as A, E as p, f as ae, D as S, b as C, B as T, c as ue, d as L, h as M, w as v, i as x, j as ce, k as de, l as k, m as w, M as D, n as H, o as he, p as pe, q as z, s as F, t as R, A as le, R as fe, e as B } from "./index-
|
|
1
|
+
import { S as E, g as A, E as p, f as ae, D as S, b as C, B as T, c as ue, d as L, h as M, w as v, i as x, j as ce, k as de, l as k, m as w, M as D, n as H, o as he, p as pe, q as z, s as F, t as R, A as le, R as fe, e as B } from "./index-CDnMjIGb.js";
|
|
2
2
|
import { l as ge, a as me } from "./colorToUniform-C2jGzNe1.js";
|
|
3
|
-
import { c as _e, u as be, U as xe, B as ye, G as Ge, e as Se, R as Be, t as Pe, S as Te, a as Ce } from "./SharedSystems-
|
|
3
|
+
import { c as _e, u as be, U as xe, B as ye, G as Ge, e as Se, R as Be, t as Pe, S as Te, a as Ce } from "./SharedSystems-CaP5H7w0.js";
|
|
4
4
|
const y = E.for2d();
|
|
5
5
|
class O {
|
|
6
6
|
start(e, t, r) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { T as M, U as Z, P as m, r as te, E as y, a as ie, w as g, e as P, C as V } from "./index-
|
|
2
|
-
import "./webworkerAll-
|
|
1
|
+
import { T as M, U as Z, P as m, r as te, E as y, a as ie, w as g, e as P, C as V } from "./index-CDnMjIGb.js";
|
|
2
|
+
import "./webworkerAll-D0RTOtmO.js";
|
|
3
3
|
class q {
|
|
4
4
|
constructor(e) {
|
|
5
5
|
this._lastTransform = "", this._observer = null, this._tickerAttached = !1, this.updateTranslation = () => {
|
|
@@ -5569,7 +5569,7 @@ const rs = (s) => {
|
|
|
5569
5569
|
},
|
|
5570
5570
|
test: () => !0,
|
|
5571
5571
|
load: async () => {
|
|
5572
|
-
await import("./browserAll-
|
|
5572
|
+
await import("./browserAll-DRgdBopC.js");
|
|
5573
5573
|
}
|
|
5574
5574
|
}, Dc = {
|
|
5575
5575
|
extension: {
|
|
@@ -5579,7 +5579,7 @@ const rs = (s) => {
|
|
|
5579
5579
|
},
|
|
5580
5580
|
test: () => typeof self < "u" && self.WorkerGlobalScope !== void 0,
|
|
5581
5581
|
load: async () => {
|
|
5582
|
-
await import("./webworkerAll-
|
|
5582
|
+
await import("./webworkerAll-D0RTOtmO.js");
|
|
5583
5583
|
}
|
|
5584
5584
|
};
|
|
5585
5585
|
class mt {
|
|
@@ -14767,13 +14767,13 @@ async function Eu(s) {
|
|
|
14767
14767
|
for (let a = 0; a < t.length; a++) {
|
|
14768
14768
|
const h = t[a];
|
|
14769
14769
|
if (h === "webgpu" && await Iu()) {
|
|
14770
|
-
const { WebGPURenderer: l } = await import("./WebGPURenderer-
|
|
14770
|
+
const { WebGPURenderer: l } = await import("./WebGPURenderer-B7z3CK54.js");
|
|
14771
14771
|
e = l, r = { ...s, ...s.webgpu };
|
|
14772
14772
|
break;
|
|
14773
14773
|
} else if (h === "webgl" && Au(
|
|
14774
14774
|
s.failIfMajorPerformanceCaveat ?? Ba.defaultOptions.failIfMajorPerformanceCaveat
|
|
14775
14775
|
)) {
|
|
14776
|
-
const { WebGLRenderer: l } = await import("./WebGLRenderer-
|
|
14776
|
+
const { WebGLRenderer: l } = await import("./WebGLRenderer-BMj90BH-.js");
|
|
14777
14777
|
e = l, r = { ...s, ...s.webgl };
|
|
14778
14778
|
break;
|
|
14779
14779
|
} else if (h === "canvas")
|
|
@@ -24863,45 +24863,54 @@ class ye extends xe {
|
|
|
24863
24863
|
align: this.opts.align
|
|
24864
24864
|
};
|
|
24865
24865
|
if (e.fill && typeof e.fill == "object" && e.fill.type === "gradient") {
|
|
24866
|
-
const
|
|
24866
|
+
const l = new zt(
|
|
24867
24867
|
e.fill.x0,
|
|
24868
24868
|
e.fill.y0,
|
|
24869
24869
|
e.fill.x1,
|
|
24870
24870
|
e.fill.y1
|
|
24871
24871
|
);
|
|
24872
|
-
e.fill.colors.forEach(({ ratio:
|
|
24873
|
-
const
|
|
24874
|
-
|
|
24875
|
-
}), o.fill = { fill:
|
|
24872
|
+
e.fill.colors.forEach(({ ratio: d, color: p }) => {
|
|
24873
|
+
const m = typeof p == "number" ? p : dt(p) ?? 16777215;
|
|
24874
|
+
l.addColorStop(d, m);
|
|
24875
|
+
}), o.fill = { fill: l };
|
|
24876
24876
|
} else {
|
|
24877
|
-
const
|
|
24878
|
-
o.fill =
|
|
24877
|
+
const l = typeof e.fill == "string" || typeof e.fill == "number" ? dt(e.fill) : void 0;
|
|
24878
|
+
o.fill = l ?? 16777215;
|
|
24879
24879
|
}
|
|
24880
|
+
const a = (l) => l === "transparent";
|
|
24880
24881
|
if (e.stroke && typeof e.stroke == "object" && "color" in e.stroke) {
|
|
24881
|
-
|
|
24882
|
-
|
|
24883
|
-
|
|
24884
|
-
|
|
24885
|
-
|
|
24886
|
-
|
|
24882
|
+
if (!a(e.stroke.color)) {
|
|
24883
|
+
const l = dt(e.stroke.color);
|
|
24884
|
+
l !== void 0 && (o.stroke = {
|
|
24885
|
+
color: l,
|
|
24886
|
+
width: e.stroke.width
|
|
24887
|
+
}, e.stroke.join && (o.stroke.join = e.stroke.join));
|
|
24888
|
+
}
|
|
24889
|
+
} else if (!a(e.stroke)) {
|
|
24890
|
+
const l = dt(e.stroke);
|
|
24891
|
+
l !== void 0 ? o.stroke = {
|
|
24892
|
+
color: l,
|
|
24887
24893
|
width: this.opts.strokeWidth ?? 0
|
|
24888
|
-
} : this.opts.strokeWidth && this.opts.strokeWidth > 0 && (o.stroke = {
|
|
24894
|
+
} : this.opts.strokeWidth && this.opts.strokeWidth > 0 && (o.stroke = {
|
|
24895
|
+
color: 0,
|
|
24896
|
+
width: this.opts.strokeWidth
|
|
24897
|
+
});
|
|
24889
24898
|
}
|
|
24890
24899
|
if (e.dropShadow) {
|
|
24891
|
-
const
|
|
24892
|
-
|
|
24893
|
-
color:
|
|
24900
|
+
const l = dt(e.dropShadow.color);
|
|
24901
|
+
l !== void 0 && (o.dropShadow = {
|
|
24902
|
+
color: l,
|
|
24894
24903
|
alpha: e.dropShadow.alpha ?? 0.5,
|
|
24895
24904
|
blur: e.dropShadow.blur ?? 4,
|
|
24896
24905
|
angle: e.dropShadow.angle ?? Math.PI / 6,
|
|
24897
24906
|
distance: e.dropShadow.distance ?? 2
|
|
24898
24907
|
});
|
|
24899
24908
|
}
|
|
24900
|
-
const
|
|
24901
|
-
this.textStyle =
|
|
24909
|
+
const h = new Dt(o);
|
|
24910
|
+
this.textStyle = h, this.ready = (async () => {
|
|
24902
24911
|
await this.refreshCaptions();
|
|
24903
|
-
const
|
|
24904
|
-
return N.info("CaptionClip ready:",
|
|
24912
|
+
const l = { ...this._meta };
|
|
24913
|
+
return N.info("CaptionClip ready:", l), l;
|
|
24905
24914
|
})();
|
|
24906
24915
|
}
|
|
24907
24916
|
/**
|
|
@@ -24945,86 +24954,86 @@ class ye extends xe {
|
|
|
24945
24954
|
this.textStyle = new Dt(e), await this.refreshCaptions();
|
|
24946
24955
|
}
|
|
24947
24956
|
async refreshCaptions() {
|
|
24948
|
-
this.pixiTextContainer ? (this.pixiTextContainer.children.forEach((
|
|
24949
|
-
|
|
24957
|
+
this.pixiTextContainer ? (this.pixiTextContainer.children.forEach((f) => {
|
|
24958
|
+
f instanceof Tt && f.label;
|
|
24950
24959
|
}), this.pixiTextContainer.removeChildren()) : this.pixiTextContainer = new lt();
|
|
24951
24960
|
const t = this.textStyle;
|
|
24952
24961
|
let e = 0, r = 0, o = 0;
|
|
24953
24962
|
const a = this.opts.textCase;
|
|
24954
|
-
this.wordTexts = this.opts.words.map((
|
|
24955
|
-
let
|
|
24956
|
-
a === "uppercase" ?
|
|
24963
|
+
this.wordTexts = this.opts.words.map((f) => {
|
|
24964
|
+
let g = f.text;
|
|
24965
|
+
a === "uppercase" ? g = g.toUpperCase() : a === "lowercase" ? g = g.toLowerCase() : a === "title" && (g = g.replace(
|
|
24957
24966
|
/\w\S*/g,
|
|
24958
|
-
(
|
|
24967
|
+
(A) => A.charAt(0).toUpperCase() + A.substring(1).toLowerCase()
|
|
24959
24968
|
));
|
|
24960
|
-
const
|
|
24961
|
-
text:
|
|
24969
|
+
const x = new Rp({
|
|
24970
|
+
text: g,
|
|
24962
24971
|
style: t
|
|
24963
24972
|
});
|
|
24964
|
-
|
|
24965
|
-
const
|
|
24966
|
-
r = Math.max(r,
|
|
24967
|
-
const
|
|
24968
|
-
return
|
|
24973
|
+
x.x = e, x.y = 0;
|
|
24974
|
+
const b = x.getLocalBounds(), w = Math.ceil(b.width || x.width), T = Math.ceil(b.height || x.height);
|
|
24975
|
+
r = Math.max(r, T), e += w + 5, o = e - 5, this.pixiTextContainer.addChild(x);
|
|
24976
|
+
const S = dt(this.opts.fill);
|
|
24977
|
+
return x.tint = S ?? 16777215, x;
|
|
24969
24978
|
});
|
|
24970
24979
|
const h = o, l = r, d = new Tt();
|
|
24971
24980
|
d.label = "containerBackground";
|
|
24972
|
-
const p =
|
|
24981
|
+
const p = this.opts.background === "transparent", m = p ? 0 : dt(this.opts.background), v = p ? 0 : 1, y = 15;
|
|
24973
24982
|
d.roundRect(
|
|
24974
24983
|
0,
|
|
24975
24984
|
0,
|
|
24976
|
-
h +
|
|
24977
|
-
l +
|
|
24978
|
-
|
|
24979
|
-
), d.fill({ color:
|
|
24980
|
-
this.extraPadding = 0,
|
|
24985
|
+
h + y * 2,
|
|
24986
|
+
l + y * 2,
|
|
24987
|
+
10
|
|
24988
|
+
), d.fill({ color: m, alpha: v }), this.wordTexts.forEach((f) => {
|
|
24989
|
+
this.extraPadding = 0, f.pivot.y = 0, f.pivot.x = 0, f.y = y - this.extraPadding, f.x += y;
|
|
24981
24990
|
}), this.pixiTextContainer.addChildAt(d, 0), this.renderTexture && this.renderTexture.destroy(!0), this.renderTexture = bt.create({
|
|
24982
|
-
width: h +
|
|
24983
|
-
height: l +
|
|
24984
|
-
}), this._meta.width = h +
|
|
24985
|
-
const
|
|
24986
|
-
this.width = this.width === 0 ? this._meta.width : this.width, this.height = this.height === 0 ? this._meta.height : this.height, this.top =
|
|
24991
|
+
width: h + y * 2,
|
|
24992
|
+
height: l + y * 2
|
|
24993
|
+
}), this._meta.width = h + y * 2, this._meta.height = l + y * 2, this._meta.duration = 1 / 0;
|
|
24994
|
+
const n = this.opts.videoWidth, c = this.opts.videoHeight, u = this.opts.bottomOffset;
|
|
24995
|
+
this.width = this.width === 0 ? this._meta.width : this.width, this.height = this.height === 0 ? this._meta.height : this.height, this.top = c - this.height - u, this.left = (n - this.width) / 2;
|
|
24987
24996
|
}
|
|
24988
24997
|
lastLoggedTime = -1;
|
|
24989
24998
|
updateState(t) {
|
|
24990
24999
|
const e = t / 1e3, r = Math.floor(t / 1e6);
|
|
24991
25000
|
r !== this.lastLoggedTime && (this.lastLoggedTime = r), this.opts.words.forEach((o, a) => {
|
|
24992
|
-
const h = e >= o.from && e <= o.to, l = e > o.to;
|
|
24993
|
-
let
|
|
24994
|
-
o.isKeyWord && h
|
|
24995
|
-
const
|
|
24996
|
-
if (
|
|
24997
|
-
|
|
24998
|
-
|
|
25001
|
+
const h = e >= o.from && e <= o.to, l = e > o.to, d = o.isKeyWord && this.opts.keyword !== "transparent";
|
|
25002
|
+
let p;
|
|
25003
|
+
o.isKeyWord && h && d ? p = dt(this.opts.keyword) : h ? p = dt(this.opts.active) : l && this.opts.preserveKeywordColor && d ? p = dt(this.opts.keyword) : l ? p = dt(this.opts.appeared) : p = dt(this.opts.fill);
|
|
25004
|
+
const m = this.wordTexts[a];
|
|
25005
|
+
if (m) {
|
|
25006
|
+
m.children.forEach((y) => {
|
|
25007
|
+
y.label !== "bgRect" && (y.tint = p ?? 16777215);
|
|
24999
25008
|
});
|
|
25000
|
-
const
|
|
25009
|
+
const v = m.getChildByLabel("bgRect");
|
|
25001
25010
|
if (h)
|
|
25002
|
-
if (
|
|
25003
|
-
|
|
25004
|
-
const
|
|
25005
|
-
|
|
25006
|
-
const
|
|
25007
|
-
|
|
25008
|
-
|
|
25009
|
-
|
|
25010
|
-
|
|
25011
|
-
|
|
25011
|
+
if (v) {
|
|
25012
|
+
v.tint = 16777215;
|
|
25013
|
+
const y = dt(this.opts.activeFill) || 16753920;
|
|
25014
|
+
v.clear();
|
|
25015
|
+
const _ = 10, n = m.getLocalBounds();
|
|
25016
|
+
v.roundRect(
|
|
25017
|
+
n.x - _ / 2,
|
|
25018
|
+
n.y - _ / 2 + this.extraPadding,
|
|
25019
|
+
n.width + _,
|
|
25020
|
+
n.height + _,
|
|
25012
25021
|
16
|
|
25013
|
-
),
|
|
25022
|
+
), v.fill(y);
|
|
25014
25023
|
} else {
|
|
25015
|
-
const
|
|
25016
|
-
|
|
25017
|
-
const
|
|
25018
|
-
|
|
25019
|
-
|
|
25020
|
-
|
|
25021
|
-
|
|
25022
|
-
|
|
25023
|
-
|
|
25024
|
-
),
|
|
25024
|
+
const y = new Tt();
|
|
25025
|
+
y.label = "bgRect";
|
|
25026
|
+
const _ = 10, n = m.getLocalBounds(), c = 10, u = dt(this.opts.activeFill) || 16753920;
|
|
25027
|
+
y.roundRect(
|
|
25028
|
+
n.x - _ / 2,
|
|
25029
|
+
n.y - _ / 2 + this.extraPadding,
|
|
25030
|
+
n.width + _,
|
|
25031
|
+
n.height + _,
|
|
25032
|
+
c
|
|
25033
|
+
), y.fill(u), y.tint = 16777215, m.addChildAt(y, 0);
|
|
25025
25034
|
}
|
|
25026
25035
|
else
|
|
25027
|
-
|
|
25036
|
+
v && m.removeChild(v);
|
|
25028
25037
|
} else
|
|
25029
25038
|
console.log(
|
|
25030
25039
|
`¡WARNING: SplitBitmapText was not found for word "${o.text}"!`
|
package/dist/index.es.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { aw as i, ax as o, aD as t, aB as C, aK as e, aM as p, ay as n, aF as r, az as T, aE as l, aA as m, aC as f, az as I, aG as d, au as x, ar as M, as as O, aI as P, aH as c, aJ as u, aL as A, at as E, av as N } from "./index-
|
|
1
|
+
import { aw as i, ax as o, aD as t, aB as C, aK as e, aM as p, ay as n, aF as r, az as T, aE as l, aA as m, aC as f, az as I, aG as d, au as x, ar as M, as as O, aI as P, aH as c, aJ as u, aL as A, at as E, av as N } from "./index-CDnMjIGb.js";
|
|
2
2
|
export {
|
|
3
3
|
i as AudioClip,
|
|
4
4
|
o as CaptionClip,
|
package/dist/index.umd.js
CHANGED
|
@@ -1292,7 +1292,7 @@ fn mainFragment(
|
|
|
1292
1292
|
src: url('${t}');
|
|
1293
1293
|
}`}const bo=new Map;async function nx(s){const e=s.filter(t=>re.has(`${t}-and-url`)).map(t=>{if(!bo.has(t)){const{entries:r}=re.get(`${t}-and-url`),n=[];r.forEach(o=>{const c=o.url,d=o.faces.map(f=>({weight:f.weight,style:f.style}));n.push(...d.map(f=>sx({fontWeight:f.weight,fontStyle:f.style,fontFamily:t},c)))}),bo.set(t,Promise.all(n).then(o=>o.join(`
|
|
1294
1294
|
`)))}return bo.get(t)});return(await Promise.all(e)).join(`
|
|
1295
|
-
`)}function ox(s,e,t,r,n){const{domElement:o,styleElement:c,svgRoot:l}=n;o.innerHTML=`<style>${e.cssStyle}</style><div style='padding:0;'>${s}</div>`,o.setAttribute("style",`transform: scale(${t});transform-origin: top left; display: inline-block`),c.textContent=r;const{width:d,height:f}=n.image;return l.setAttribute("width",d.toString()),l.setAttribute("height",f.toString()),new XMLSerializer().serializeToString(l)}function ax(s,e){const t=xt.getOptimalCanvasAndContext(s.width,s.height,e),{context:r}=t;return r.clearRect(0,0,s.width,s.height),r.drawImage(s,0,0),t}function lx(s,e,t){return new Promise(async r=>{t&&await new Promise(n=>setTimeout(n,100)),s.onload=()=>{r()},s.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(e)}`,s.crossOrigin="anonymous"})}class Vu{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===tt.WEBGPU}getTexture(e){return this.getTexturePromise(e)}getManagedTexture(e){const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].promise;const r=this._buildTexturePromise(e).then(n=>(this._activeTextures[t].texture=n,n));return this._activeTextures[t]={texture:null,promise:r,usageCount:1},r}getReferenceCount(e){return this._activeTextures[e]?.usageCount??null}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t.texture):t.promise.then(r=>{t.texture=r,this._cleanUp(t.texture)}).catch(()=>{G("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[e]=null))}getTexturePromise(e){return this._buildTexturePromise(e)}async _buildTexturePromise(e){const{text:t,style:r,resolution:n,textureStyle:o}=e,c=me.get(rh),l=ix(t,r),d=await nx(l),f=zv(t,r,d,c),m=Math.ceil(Math.ceil(Math.max(1,f.width)+r.padding*2)*n),g=Math.ceil(Math.ceil(Math.max(1,f.height)+r.padding*2)*n),_=c.image,y=2;_.width=(m|0)+y,_.height=(g|0)+y;const a=ox(t,r,n,d,c);await lx(_,a,ex()&&l.length>0);const h=_;let u;this._createCanvas&&(u=ax(_,n));const p=Wu(u?u.canvas:h,_.width-y,_.height-y,n);return o&&(p.source.style=o),this._createCanvas&&(this._renderer.texture.initSource(p.source),xt.returnCanvasAndContext(u)),me.return(c),p}returnTexturePromise(e){e.then(t=>{this._cleanUp(t)}).catch(()=>{G("HTMLTextSystem: Failed to clean texture")})}_cleanUp(e){we.returnTexture(e,!0),e.source.resource=null,e.source.uploadMethodId="unknown"}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexturePromise(this._activeTextures[e].promise);this._activeTextures=null}}Vu.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"htmlText"};class cx extends ne{constructor(e){const{text:t,style:r,autoSplit:n,lineAnchor:o,wordAnchor:c,charAnchor:l,...d}=e;super(d),this._dirty=!1,this._canReuseChars=!1,this.chars=[],this.words=[],this.lines=[],this._originalText=t,this._autoSplit=n,this._lineAnchor=o,this._wordAnchor=c,this._charAnchor=l,this.style=r}split(){const e=this.splitFn();this.chars=e.chars,this.words=e.words,this.lines=e.lines,this.addChild(...this.lines),this.charAnchor=this._charAnchor,this.wordAnchor=this._wordAnchor,this.lineAnchor=this._lineAnchor,this._dirty=!1,this._canReuseChars=!0}get text(){return this._originalText}set text(e){this._originalText=e,this.lines.forEach(t=>t.destroy({children:!0})),this.lines.length=0,this.words.length=0,this.chars.length=0,this._canReuseChars=!1,this.onTextUpdate()}_setOrigin(e,t,r){let n;typeof e=="number"?n={x:e,y:e}:n={x:e.x,y:e.y},t.forEach(o=>{const c=o.getLocalBounds(),l=c.minX+c.width*n.x,d=c.minY+c.height*n.y;o.origin.set(l,d)}),this[r]=e}get lineAnchor(){return this._lineAnchor}set lineAnchor(e){this._setOrigin(e,this.lines,"_lineAnchor")}get wordAnchor(){return this._wordAnchor}set wordAnchor(e){this._setOrigin(e,this.words,"_wordAnchor")}get charAnchor(){return this._charAnchor}set charAnchor(e){this._setOrigin(e,this.chars,"_charAnchor")}get style(){return this._style}set style(e){e||(e={}),this._style=new Be(e),this.words.forEach(t=>t.destroy()),this.words.length=0,this.lines.forEach(t=>t.destroy()),this.lines.length=0,this._canReuseChars=!0,this.onTextUpdate()}onTextUpdate(){this._dirty=!0,this._autoSplit&&this.split()}destroy(e){super.destroy(e),this.chars=[],this.words=[],this.lines=[],(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._originalText=""}}const Yu=class cs extends cx{constructor(e){const t={...cs.defaultOptions,...e};super(t)}static from(e,t){const r={...cs.defaultOptions,...t,text:e.text,style:new Be(e.style)};return new cs({...r})}splitFn(){return Jy({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};Yu.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let hx=Yu;class ux extends ns{constructor(e){super(),this._renderer=e,e.runners.resolutionChange.add(this)}resolutionChange(){const e=this.renderable;e._autoResolution&&e.onViewUpdate()}destroy(){const{canvasText:e}=this._renderer;e.getReferenceCount(this.currentKey)>0?e.decreaseReferenceCount(this.currentKey):this.texture&&e.returnTexture(this.texture),this._renderer.runners.resolutionChange.remove(this),this._renderer=null}}class Xu{constructor(e){this._renderer=e}validateRenderable(e){const t=this._getGpuText(e),r=e.styleKey;return t.currentKey!==r?!0:e._didTextUpdate}addRenderable(e,t){const r=this._getGpuText(e);if(e._didTextUpdate){const n=e._autoResolution?this._renderer.resolution:e.resolution;(r.currentKey!==e.styleKey||e.resolution!==n)&&this._updateGpuText(e),e._didTextUpdate=!1,xo(r,e)}this._renderer.renderPipes.batch.addToBatch(r,t)}updateRenderable(e){const t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){const t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new ux(this._renderer);return t.currentKey="--",t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}Xu.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"text"};class $u{constructor(e){this._activeTextures={},this._renderer=e}getTexture(e,t,r,n){typeof e=="string"&&(H("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:r,resolution:t}),e.style instanceof Be||(e.style=new Be(e.style)),e.textureStyle instanceof at||(e.textureStyle=new at(e.textureStyle)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:o,style:c,textureStyle:l}=e,d=e.resolution??this._renderer.resolution,{frame:f,canvasAndContext:m}=tr.getCanvasAndContext({text:o,style:c,resolution:d}),g=Wu(m.canvas,f.width,f.height,d);if(l&&(g.source.style=l),c.trim&&(f.pad(c.padding),g.frame.copyFrom(f),g.frame.scale(1/d),g.updateUvs()),c.filters){const _=this._applyFilters(g,c.filters);return this.returnTexture(g),tr.returnCanvasAndContext(m),_}return this._renderer.texture.initSource(g._source),tr.returnCanvasAndContext(m),g}returnTexture(e){const t=e.source;t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",we.returnTexture(e,!0)}renderTextToCanvas(){H("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;const r=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle});return this._activeTextures[t]={texture:r,usageCount:1},r}decreaseReferenceCount(e){const t=this._activeTextures[e];t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null)}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const r=this._renderer.renderTarget.renderTarget,n=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind(r,!1),n}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}$u.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"canvasText"},L.add(Yf,Xf);function ye(s){if(s!=null){if(typeof s=="number")return s;if(typeof s=="string"){if(s.startsWith("#")){const t=parseInt(s.slice(1),16);if(!isNaN(t))return t}if(s.startsWith("0x")){const t=parseInt(s,16);if(!isNaN(t))return t}const e=parseInt(s,16);if(!isNaN(e))return e;try{return new se(s).toNumber()}catch{return}}}}class Ft extends kt{type="Caption";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}text;get style(){if(!this.originalOpts)return{};const e=this.originalOpts;return{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,color:e.fill,align:e.align,textCase:e.textCase,stroke:e.stroke?typeof e.stroke=="object"?{color:e.stroke.color,width:e.stroke.width}:{color:e.stroke,width:e.strokeWidth??0}:void 0,shadow:e.dropShadow?{color:e.dropShadow.color??"#000000",alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,distance:e.dropShadow.distance??0,angle:e.dropShadow.angle??0}:void 0}}bottomOffset;get textCase(){return this.originalOpts?.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];opts;pixiTextContainer=null;renderTexture=null;wordTexts=[];extraPadding=0;textStyle;externalRenderer=null;pixiApp=null;originalOpts=null;constructor(e,t={},r){super(),this.text=e,this.originalOpts={...t},this.externalRenderer=r??null,this.opts={fontSize:t.fontSize??30,fontFamily:t.fontFamily??"Arial",fontUrl:t.fontUrl??"",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",fill:t.fill??"#ffffff",strokeWidth:t.strokeWidth??0,align:t.align??"center",wordWrapWidth:t.wordWrapWidth??0,wordWrap:t.wordWrap??!1,lineHeight:t.lineHeight??1,letterSpacing:t.letterSpacing??0,textCase:t.textCase??"none",videoWidth:t.caption?.positioning?.videoWidth??t.videoWidth??1280,videoHeight:t.caption?.positioning?.videoHeight??t.videoHeight??720,bottomOffset:t.caption?.positioning?.bottomOffset??t.bottomOffset??30,keyword:t.caption?.colors?.keyword??t.colors?.keyword??"#ffff00",background:t.caption?.colors?.background??t.colors?.background??"#000000",active:t.caption?.colors?.active??t.colors?.active??"#ffffff",activeFill:t.caption?.colors?.activeFill??t.colors?.activeFill??"#00ff00",appeared:t.caption?.colors?.appeared??t.colors?.appeared??"#ffffff",words:t.caption?.words??t.words??[],preserveKeywordColor:t.caption?.preserveKeywordColor??t.preserveKeywordColor??!1};const n={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(t.fill&&typeof t.fill=="object"&&t.fill.type==="gradient"){const c=new Ke(t.fill.x0,t.fill.y0,t.fill.x1,t.fill.y1);t.fill.colors.forEach(({ratio:l,color:d})=>{const f=typeof d=="number"?d:ye(d)??16777215;c.addColorStop(l,f)}),n.fill={fill:c}}else{const c=typeof t.fill=="string"||typeof t.fill=="number"?ye(t.fill):void 0;n.fill=c??16777215}if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke){const c=ye(t.stroke.color);c!==void 0&&(n.stroke={color:c,width:t.stroke.width},t.stroke.join&&(n.stroke.join=t.stroke.join))}else{const c=ye(t.stroke);c!==void 0?n.stroke={color:c,width:this.opts.strokeWidth??0}:this.opts.strokeWidth&&this.opts.strokeWidth>0&&(n.stroke={color:0,width:this.opts.strokeWidth})}if(t.dropShadow){const c=ye(t.dropShadow.color);c!==void 0&&(n.dropShadow={color:c,alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,angle:t.dropShadow.angle??Math.PI/6,distance:t.dropShadow.distance??2})}const o=new Be(n);this.textStyle=o,this.ready=(async()=>{await this.refreshCaptions();const c={...this._meta};return W.info("CaptionClip ready:",c),c})()}async updateStyle(e){this.originalOpts||(this.originalOpts={}),this.originalOpts={...this.originalOpts,...e},e.fontSize!==void 0&&(this.opts.fontSize=e.fontSize),e.fontFamily!==void 0&&(this.opts.fontFamily=e.fontFamily),e.fontWeight!==void 0&&(this.opts.fontWeight=e.fontWeight),e.fontStyle!==void 0&&(this.opts.fontStyle=e.fontStyle),e.fill!==void 0&&(this.opts.fill=e.fill),e.align!==void 0&&(this.opts.align=e.align),e.letterSpacing!==void 0&&(this.opts.letterSpacing=e.letterSpacing),e.lineHeight!==void 0&&(this.opts.lineHeight=e.lineHeight),e.textCase!==void 0&&(this.opts.textCase=e.textCase);const t={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(this.opts.fill&&typeof this.opts.fill=="object"&&this.opts.fill.type==="gradient"){const r=new Ke(this.opts.fill.x0,this.opts.fill.y0,this.opts.fill.x1,this.opts.fill.y1);this.opts.fill.colors.forEach(({ratio:n,color:o})=>{const c=typeof o=="number"?o:ye(o)??16777215;r.addColorStop(n,c)}),t.fill={fill:r}}else{const r=typeof this.opts.fill=="string"||typeof this.opts.fill=="number"?ye(this.opts.fill):void 0;t.fill=r??16777215}if(e.stroke!==void 0||e.strokeWidth!==void 0)if(this.originalOpts.stroke&&typeof this.originalOpts.stroke=="object"&&"color"in this.originalOpts.stroke){const r=ye(this.originalOpts.stroke.color);r!==void 0&&(t.stroke={color:r,width:this.originalOpts.stroke.width},this.originalOpts.stroke.join&&(t.stroke.join=this.originalOpts.stroke.join))}else{const r=ye(this.originalOpts.stroke),n=e.strokeWidth??this.originalOpts.strokeWidth??0;r!==void 0?t.stroke={color:r,width:n}:n>0&&(t.stroke={color:0,width:n})}this.textStyle=new Be(t),await this.refreshCaptions()}async refreshCaptions(){this.pixiTextContainer?(this.pixiTextContainer.children.forEach(u=>{u instanceof Ae&&u.label}),this.pixiTextContainer.removeChildren()):this.pixiTextContainer=new ne;const e=this.textStyle;let t=0,r=0,n=0;const o=this.opts.textCase;this.wordTexts=this.opts.words.map(u=>{let p=u.text;o==="uppercase"?p=p.toUpperCase():o==="lowercase"?p=p.toLowerCase():o==="title"&&(p=p.replace(/\w\S*/g,S=>S.charAt(0).toUpperCase()+S.substring(1).toLowerCase()));const v=new hx({text:p,style:e});v.x=t,v.y=0;const x=v.getLocalBounds(),b=Math.ceil(x.width||v.width),T=Math.ceil(x.height||v.height);r=Math.max(r,T),t+=b+5,n=t-5,this.pixiTextContainer.addChild(v);const w=ye(this.opts.fill);return v.tint=w??16777215,v});const c=n,l=r,d=new Ae;d.label="containerBackground";const f=ye(this.opts.background)||0,m=15,g=10,_=1;d.roundRect(0,0,c+m*2,l+m*2,g),d.fill({color:f,alpha:_}),this.wordTexts.forEach(u=>{this.extraPadding=0,u.pivot.y=0,u.pivot.x=0,u.y=m-this.extraPadding,u.x+=m}),this.pixiTextContainer.addChildAt(d,0),this.renderTexture&&this.renderTexture.destroy(!0),this.renderTexture=Ee.create({width:c+m*2,height:l+m*2}),this._meta.width=c+m*2,this._meta.height=l+m*2,this._meta.duration=1/0;const y=this.opts.videoWidth,a=this.opts.videoHeight,h=this.opts.bottomOffset;this.width=this.width===0?this._meta.width:this.width,this.height=this.height===0?this._meta.height:this.height,this.top=a-this.height-h,this.left=(y-this.width)/2}lastLoggedTime=-1;updateState(e){const t=e/1e3,r=Math.floor(e/1e6);r!==this.lastLoggedTime&&(this.lastLoggedTime=r),this.opts.words.forEach((n,o)=>{const c=t>=n.from&&t<=n.to,l=t>n.to;let d;n.isKeyWord&&c?d=ye(this.opts.keyword):c?d=ye(this.opts.active):l&&this.opts.preserveKeywordColor&&n.isKeyWord?d=ye(this.opts.keyword):l?d=ye(this.opts.appeared):d=ye(this.opts.fill);const f=this.wordTexts[o];if(f){f.children.forEach(g=>{g.label!=="bgRect"&&(g.tint=d??16777215)});const m=f.getChildByLabel("bgRect");if(c)if(m){m.tint=16777215;const g=ye(this.opts.activeFill)||16753920;m.clear();const _=10,y=f.getLocalBounds();m.roundRect(y.x-_/2,y.y-_/2+this.extraPadding,y.width+_,y.height+_,16),m.fill(g)}else{const g=new Ae;g.label="bgRect";const _=10,y=f.getLocalBounds(),a=10,h=ye(this.opts.activeFill)||16753920;g.roundRect(y.x-_/2,y.y-_/2+this.extraPadding,y.width+_,y.height+_,a),g.fill(h),g.tint=16777215,f.addChildAt(g,0)}else m&&f.removeChild(m)}else console.log(`¡WARNING: SplitBitmapText was not found for word "${n.text}"!`)})}async getTexture(){if(this.pixiTextContainer==null||this.renderTexture==null)return console.log("[CaptionClip] getTexture returning null - container or texture not ready"),null;try{return(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture}catch(e){return console.error("[CaptionClip] Error in getTexture:",e),null}}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("CaptionClip: No renderer available. Provide a renderer via setRenderer().");return this.pixiApp.renderer}async tick(e){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("CaptionClip not initialized");this.updateState(e);const t=await this.getRenderer();t.render({container:this.pixiTextContainer,target:this.renderTexture});const r=this.renderTexture.source?.resource?.source;let n;if(r instanceof HTMLCanvasElement)n=await createImageBitmap(r);else if(r instanceof OffscreenCanvas)n=await createImageBitmap(r);else{const c=t.extract.canvas(this.renderTexture);if(c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas)n=await createImageBitmap(c);else throw new Error("Unable to extract canvas from render texture")}return{video:n,state:"success"}}async split(e){await this.ready;const t=await this.clone(),r=await this.clone();return[t,r]}addEffect(e){this.effects.push(e)}editEffect(e,t){const r=this.effects.find(n=>n.id===e);r&&Object.assign(r,t)}removeEffect(e){const t=this.effects.findIndex(r=>r.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.originalOpts||{},t=new Ft(this.text,e);return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){if(!this.destroyed){W.info("CaptionClip destroy");try{this.wordTexts.forEach(e=>{e!=null&&!e.destroyed&&e.destroy({children:!0})})}catch{}finally{this.wordTexts=[]}try{this.pixiTextContainer!=null&&this.pixiTextContainer.destroyed!==!0&&this.pixiTextContainer.destroy({children:!0})}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),r={};if(this.originalOpts){const g=this.originalOpts;g.fontSize!==void 0&&(r.fontSize=g.fontSize),g.fontFamily!==void 0&&(r.fontFamily=g.fontFamily),g.fontWeight!==void 0&&(r.fontWeight=g.fontWeight),g.fontStyle!==void 0&&(r.fontStyle=g.fontStyle),g.fill!==void 0&&(r.color=g.fill),g.align!==void 0&&(r.align=g.align),g.textCase!==void 0&&(r.textCase=g.textCase),g.fontUrl!==void 0&&(r.fontUrl=g.fontUrl),g.stroke&&(typeof g.stroke=="object"?r.stroke={color:g.stroke.color,width:g.stroke.width}:r.stroke={color:g.stroke,width:g.strokeWidth??0}),g.dropShadow&&(r.shadow={color:g.dropShadow.color??"#000000",alpha:g.dropShadow.alpha??.5,blur:g.dropShadow.blur??4,distance:g.dropShadow.distance??0,angle:g.dropShadow.angle??0})}const n={};this.opts.words&&this.opts.words.length>0&&(n.words=this.opts.words);const o={},c=this.originalOpts?.caption?.colors??this.originalOpts?.colors;c?.appeared!==void 0&&(o.appeared=c.appeared),c?.active!==void 0&&(o.active=c.active),c?.activeFill!==void 0&&(o.activeFill=c.activeFill),c?.background!==void 0&&(o.background=c.background),c?.keyword!==void 0&&(o.keyword=c.keyword);let l;this.originalOpts?.caption?.preserveKeywordColor!==void 0?l=this.originalOpts.caption.preserveKeywordColor:this.originalOpts?.preserveKeywordColor!==void 0&&(l=this.originalOpts.preserveKeywordColor),Object.keys(o).length>0&&(n.colors=o),l!==void 0&&(n.preserveKeywordColor=l);const d={};this.bottomOffset!==void 0&&(d.bottomOffset=this.bottomOffset);const f=this.originalOpts?.caption?.positioning?.videoWidth??this.originalOpts?.videoWidth,m=this.originalOpts?.caption?.positioning?.videoHeight??this.originalOpts?.videoHeight;return f!==void 0&&(d.videoWidth=f),m!==void 0&&(d.videoHeight=m),Object.keys(d).length>0&&(n.positioning=d),{...t,type:"Caption",text:this.text,style:r,caption:Object.keys(n).length>0?n:void 0,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Caption")throw new Error(`Expected Caption, got ${e.type}`);const t=e.text||"",r=e.style||{},n={};r.fontSize!==void 0&&(n.fontSize=r.fontSize),r.fontFamily!==void 0&&(n.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(n.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(n.fontStyle=r.fontStyle),r.color!==void 0&&(n.fill=r.color),r.align!==void 0&&(n.align=r.align),r.textCase!==void 0&&(n.textCase=r.textCase),r.fontUrl!==void 0?n.fontUrl=r.fontUrl:e.fontUrl!==void 0&&(n.fontUrl=e.fontUrl),r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow&&(n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:r.shadow.distance,angle:r.shadow.angle}),e.caption?n.caption=e.caption:(e.bottomOffset!==void 0&&(n.bottomOffset=e.bottomOffset),e.words!==void 0&&(n.words=e.words),(e.appearedColor!==void 0||e.activeColor!==void 0||e.activeFillColor!==void 0||e.backgroundColor!==void 0||e.isKeyWordColor!==void 0)&&(n.colors={},e.appearedColor!==void 0&&(n.colors.appeared=e.appearedColor),e.activeColor!==void 0&&(n.colors.active=e.activeColor),e.activeFillColor!==void 0&&(n.colors.activeFill=e.activeFillColor),e.backgroundColor!==void 0&&(n.colors.background=e.backgroundColor),e.isKeyWordColor!==void 0&&(n.colors.keyword=e.isKeyWordColor)),e.preservedColorKeyWord!==void 0&&(n.preserveKeywordColor=e.preservedColorKeyWord),e.videoWidth!==void 0&&(n.videoWidth=e.videoWidth),e.videoHeight!==void 0&&(n.videoHeight=e.videoHeight));const o=new Ft(t,n);return o.left=e.left,o.top=e.top,o.width=e.width,o.height=e.height,o.angle=e.angle,o.display.from=e.display.from,o.display.to=e.display.to,o.duration=e.duration,o.playbackRate=e.playbackRate,o.zIndex=e.zIndex,o.opacity=e.opacity,o.flip=e.flip,e.animation&&o.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(o.id=e.id),e.effects&&(o.effects=e.effects),await o.ready,o}}class ve extends kt{type="Image";ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t){const r=await Qi.load(e),n=r.source?.resource?.source;let o;try{if(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)o=await createImageBitmap(n);else if(n instanceof HTMLImageElement){const l=new OffscreenCanvas(n.width,n.height),d=l.getContext("2d");if(d==null)throw new Error("Failed to create 2d context");d.drawImage(n,0,0),o=await createImageBitmap(l)}else if(n instanceof ImageBitmap)o=await createImageBitmap(n);else{const l=await fetch(e);if(!l.ok)throw new Error(`Failed to fetch image: ${l.status} ${l.statusText}`);const d=await l.blob();o=await createImageBitmap(d)}}catch{const d=await fetch(e);if(!d.ok)throw new Error(`Failed to fetch image: ${d.status} ${d.statusText}`);const f=await d.blob();o=await createImageBitmap(f)}const c=new ve(o,t||e);return c.pixiTexture=r,c}getTexture(){return this.pixiTexture}constructor(e,t){super(),this.src=t!==void 0?t:"";const r=n=>{this.img=n,this._meta.width=n.width,this._meta.height=n.height,this._meta.duration=1/0;const o={...this._meta};return this.width=this.width===0?o.width:this.width,this.height=this.height===0?o.height:this.height,this.duration===0&&o.duration!==1/0&&(this.duration=o.duration,this.display.to=this.display.from+this.duration),o};if(e instanceof ReadableStream)this.ready=new Response(e).blob().then(n=>createImageBitmap(n)).then(r);else if(e instanceof ImageBitmap)this.ready=Promise.resolve(r(e));else if(Array.isArray(e)&&e.every(n=>n instanceof VideoFrame)){this.frames=e;const n=this.frames[0];if(n==null)throw Error("The frame count must be greater than 0");this._meta={width:n.displayWidth,height:n.displayHeight,duration:this.frames.reduce((c,l)=>c+(l.duration??0),0)};const o={...this._meta,duration:1/0};this.width=this.width===0?o.width:this.width,this.height=this.height===0?o.height:this.height,this.duration===0&&o.duration!==1/0&&(this.duration=o.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(o)}else if("type"in e)this.ready=this.initAnimateImg(e.stream,e.type).then(()=>{const n={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),n});else throw Error("Illegal arguments")}async initAnimateImg(e,t){this.frames=await Nf(e,t);const r=this.frames[0];if(r==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((n,o)=>n+(o.duration??0),0),width:r.codedWidth,height:r.codedHeight},W.info("ImageClip ready:",this._meta)}tickInterceptor=async(e,t)=>t;async tick(e){if(this.img!=null)return await this.tickInterceptor(e,{video:await createImageBitmap(this.img),state:"success"});const t=e%this._meta.duration;return await this.tickInterceptor(e,{video:(this.frames.find(r=>t>=r.timestamp&&t<=r.timestamp+(r.duration??0))??this.frames[0]).clone(),state:"success"})}async split(e){if(await this.ready,this.img!=null)return[new ve(await createImageBitmap(this.img),this.src),new ve(await createImageBitmap(this.img),this.src)];let t=-1;for(let o=0;o<this.frames.length;o++){const c=this.frames[o];if(!(e>c.timestamp)){t=o;break}}if(t===-1)throw Error("Not found frame by time");const r=this.frames.slice(0,t).map(o=>new VideoFrame(o)),n=this.frames.slice(t).map(o=>new VideoFrame(o,{timestamp:o.timestamp-e}));return[new ve(r,this.src),new ve(n,this.src)]}async clone(){await this.ready;const e=this.img==null?this.frames.map(r=>r.clone()):await createImageBitmap(this.img),t=new ve(e,this.src);return t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t.transition=this.transition,t}addEffect(e){this.effects.push(e)}editEffect(e,t){const r=this.effects.find(n=>n.id===e);r&&Object.assign(r,t)}removeEffect(e){const t=this.effects.findIndex(r=>r.id===e);t!==-1&&this.effects.splice(t,1)}destroy(){W.info("ImageClip destroy"),this.img?.close(),this.frames.forEach(e=>e.close()),this.pixiTexture=null,super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Image",id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Image")throw new Error(`Expected Image, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("ImageClip requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let t;try{const r=await fetch(e.src);if(!r.ok)throw new Error(`Failed to fetch image from ${e.src}: ${r.status} ${r.statusText}. Make sure the file exists in the public directory.`);const n=await r.blob();if(!n.type.startsWith("image/"))throw new Error(`Invalid image format: ${n.type}. Expected an image file.`);t=new ve(await createImageBitmap(n),e.src)}catch(r){throw r instanceof Error&&r.message.includes("could not be decoded")?new Error(`Failed to decode image from ${e.src}. The image may be corrupted, in an unsupported format, or there may be CORS issues.`):r}return await t.ready,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),e.effects&&(t.effects=e.effects),e.transition&&(t.transition=e.transition),t}async scaleToFit(e,t){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.min(e/r,t/n);this.width=r*o,this.height=n*o}async scaleToFill(e,t){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.max(e/r,t/n);this.width=r*o,this.height=n*o}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}}function To(s,e){const t=e.videoTracks[0],r={};if(t!=null){const o=dx(s.getTrackById(t.id))?.buffer,{descKey:c,type:l}=t.codec.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:t.codec.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:{descKey:"",type:""};c!==""&&(r.videoTrackConf={timescale:t.timescale,duration:t.duration,width:t.video.width,height:t.video.height,brands:e.brands,type:l,[c]:o}),r.videoDecoderConf={codec:t.codec,codedHeight:t.video.height,codedWidth:t.video.width,description:o}}const n=e.audioTracks[0];if(n!=null){const o=fx(s),c=o==null?{}:px(o);r.audioTrackConf={timescale:n.timescale,samplerate:c.sampleRate??n.audio.sample_rate,channel_count:c.numberOfChannels??n.audio.channel_count,hdlr:"soun",type:n.codec.startsWith("mp4a")?"mp4a":n.codec,description:o},r.audioDecoderConf={codec:c.codec??ae.codec,numberOfChannels:c.numberOfChannels??n.audio.channel_count,sampleRate:c.sampleRate??n.audio.sample_rate}}return r}function dx(s){for(const e of s.mdia.minf.stbl.stsd.entries){const t=e.avcC??e.hvcC??e.av1C??e.vpcC;if(t!=null){const r=new ke.DataStream(void 0,0,ke.DataStream.BIG_ENDIAN);return t.write(r),new Uint8Array(r.buffer.slice(8))}}}function fx(s,e="mp4a"){return s.moov?.traks.map(r=>r.mdia.minf.stbl.stsd.entries).flat().find(({type:r})=>r===e)?.esds}function px(s){let e="mp4a";const t=s.esd.descs[0];if(t==null)return{};e+="."+t.oti.toString(16);const r=t.descs[0];if(r==null)return e.endsWith("40")&&(e+=".2"),{codec:e};const n=(r.data[0]&248)>>3;e+="."+n;const[o,c]=r.data,l=((o&7)<<1)+(c>>7),d=(c&127)>>3;return{codec:e,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][l],numberOfChannels:d}}async function mx(s,e,t){const r=ke.createFile(!1);r.onReady=o=>{e({mp4boxFile:r,info:o});const c=o.videoTracks[0]?.id;c!=null&&r.setExtractionOptions(c,"video",{nbSamples:100});const l=o.audioTracks[0]?.id;l!=null&&r.setExtractionOptions(l,"audio",{nbSamples:100}),r.start()},r.onSamples=t,await n();async function n(){let o=0;const c=30*1024*1024;for(;;){const l=await s.read(c,{at:o});if(l.byteLength===0)break;l.fileStart=o;const d=r.appendBuffer(l);if(d==null)break;o=d}r.stop()}}function gx(s){if(s?.length!==9)return{};const e=new Int32Array(s.buffer),t=e[0]/65536,r=e[1]/65536,n=e[3]/65536,o=e[4]/65536,c=e[6]/65536,l=e[7]/65536,d=e[8]/(1<<30),f=Math.sqrt(t*t+n*n),m=Math.sqrt(r*r+o*o),g=Math.atan2(n,t),_=g*180/Math.PI;return{scaleX:f,scaleY:m,rotationRad:g,rotationDeg:_,translateX:c,translateY:l,perspective:d}}function vx(s,e,t){const r=(Math.round(t/90)*90+360)%360;if(r===0)return d=>d;const n=r===90||r===270?e:s,o=r===90||r===270?s:e,c=new OffscreenCanvas(n,o),l=c.getContext("2d");return l.translate(n/2,o/2),l.rotate(-r*Math.PI/180),l.translate(-s/2,-e/2),d=>{if(d==null)return null;l.drawImage(d,0,0);const f=new VideoFrame(c,{timestamp:d.timestamp,duration:d.duration??void 0});return d.close(),f}}let wo=0;function So(s){return s.kind==="file"&&s.createReader instanceof Function}class fe extends kt{type="Video";insId=wo++;logger=W.create(`VideoClip id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const e=await this.localFile.getOriginFile();if(e==null)throw Error("VideoClip localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:t,size:r})=>e.slice(t,t+r))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=e=>e;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t={}){const r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch video from ${e}: ${r.status} ${r.statusText}`);const n=new fe(r.body,{},e);return await n.ready,t.x!==void 0&&(n.left=t.x),t.y!==void 0&&(n.top=t.y),t.width!==void 0&&(n.width=t.width),t.height!==void 0&&(n.height=t.height),n}constructor(e,t={},r){if(super(),this.src=r!==void 0?r:"",!(e instanceof ReadableStream)&&!So(e)&&!Array.isArray(e.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...t},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof t.audio=="object"&&"volume"in t.audio?t.audio.volume:t.volume??1;const n=async o=>(await bi(this.localFile,o),this.localFile);this.localFile=So(e)?e:"localFile"in e?e.localFile:vs(),this.ready=(e instanceof ReadableStream?n(e).then(o=>qu(o,this.opts)):So(e)?qu(e,this.opts):Promise.resolve(e)).then(async({videoSamples:o,audioSamples:c,decoderConf:l,headerBoxPos:d,parsedMatrix:f})=>{this.videoSamples=o,this.audioSamples=c,this.decoderConf=l,this.headerBoxPos=d,this.parsedMatrix=f;const{videoFrameFinder:m,audioFrameFinder:g}=yx({video:l.video==null?null:{...l.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:l.audio},await this.localFile.createReader(),o,c,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=m,this.audioFrameFinder=g;const{codedWidth:_,codedHeight:y}=l.video??{};_&&y&&(this.vfRotater=vx(_,y,f.rotationDeg)),this._meta=_x(l,o,c,f.rotationDeg),this.logger.info("VideoClip meta:",this._meta);const a={...this._meta};this.width=this.width===0?a.width:this.width,this.height=this.height===0?a.height:this.height,this.trim.to=this.trim.to===0?a.duration:this.trim.to;const h=(this.trim.to-this.trim.from)/this.playbackRate;return this.duration=this.duration===0?h:this.duration,this.display.to=this.display.from+this.duration,this.on("propsChange",u=>{u.volume!==void 0&&this.audioFrameFinder&&this.audioFrameFinder.setVolume(u.volume)}),a})}tickInterceptor=async(e,t)=>t;async tick(e){const t=e+this.trim.from;if(t>=this.trim.to||t>=this._meta.duration)return await this.tickInterceptor(e,{audio:await this.audioFrameFinder?.find(t)??[],state:"done"});const[r,n]=await Promise.all([this.audioFrameFinder?.find(t)??[],this.videoFrameFinder?.find(t).then(this.vfRotater)]);return n==null?await this.tickInterceptor(e,{audio:r,state:"success"}):await this.tickInterceptor(e,{video:n,audio:r,state:"success"})}async split(e){if(await this.ready,e<=0||e>=this._meta.duration)throw Error("time out of bounds");const[t,r]=Ax(this.videoSamples,e),[n,o]=Ex(this.audioSamples,e),c=new fe({localFile:this.localFile,videoSamples:t??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),l=new fe({localFile:this.localFile,videoSamples:r??[],audioSamples:o??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await Promise.all([c.ready,l.ready]),[c,l]}addEffect(e){this.effects.push(e)}editEffect(e,t){const r=this.effects.find(n=>n.id===e);r&&Object.assign(r,t)}removeEffect(e){const t=this.effects.findIndex(r=>r.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=new fe({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await e.ready,e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e.id=this.id,e.effects=[...this.effects],e}async splitTrack(){await this.ready;const e=[];if(this.videoSamples.length>0){const t=new fe({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[],decoderConf:{video:this.decoderConf.video,audio:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}if(this.audioSamples.length>0){const t=new fe({localFile:this.localFile,videoSamples:[],audioSamples:[...this.audioSamples],decoderConf:{audio:this.decoderConf.audio,video:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}return e}destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("VideoClip destroy"),super.destroy(),this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(e=!1){return{...super.toJSON(e),type:"Video",audio:this.audio,volume:this.volume,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Video")throw new Error(`Expected Video, got ${e.type}`);const t=await fetch(e.src);if(!t.ok)throw new Error(`Failed to fetch video from ${e.src}: ${t.status} ${t.statusText}. Make sure the file exists in the public directory.`);const r=e.audio!==void 0?{audio:e.audio,volume:e.volume}:{volume:e.volume},n=new fe(t.body,r,e.src);return await n.ready,n.left=e.left,n.top=e.top,n.width=e.width,n.height=e.height,n.angle=e.angle,n.display.from=e.display.from,n.display.to=e.display.to,n.duration=e.duration,n.playbackRate=e.playbackRate,n.zIndex=e.zIndex,n.opacity=e.opacity,n.flip=e.flip,e.animation&&n.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(n.id=e.id),e.effects&&(n.effects=e.effects),e.transition&&(n.transition=e.transition),e.trim&&(n.trim.from=e.trim.from<1e6?e.trim.from*1e6:e.trim.from,n.trim.to=e.trim.to<1e6?e.trim.to*1e6:e.trim.to),e.volume!==void 0&&(n.volume=e.volume),n}async createPlaybackElement(){await this.ready;const t=this.localFile;if(!t||typeof t.getOriginFile!="function")throw new Error("VideoClip does not have a local file for playback");const r=await t.getOriginFile();if(!r)throw new Error("Failed to get origin file from VideoClip");const n=URL.createObjectURL(r),o=document.createElement("video");return o.crossOrigin="anonymous",o.muted=!0,o.autoplay=!1,o.playsInline=!0,o.preload="auto",o.loop=!1,o.src=n,await new Promise((c,l)=>{const d=()=>{o.removeEventListener("loadeddata",d),o.removeEventListener("error",f),o.pause(),o.currentTime=0,c()},f=()=>{o.removeEventListener("loadeddata",d),o.removeEventListener("error",f),l(new Error("Failed to load video"))};o.addEventListener("loadeddata",d,{once:!0}),o.addEventListener("error",f,{once:!0}),o.load()}),{element:o,objectUrl:n}}async play(e,t){const r=e,n=t+this.trim.from/1e6;if(Math.abs(r.currentTime-n)>.1&&(r.currentTime=n),r.muted=!1,r.paused)try{await r.play()}catch{try{await r.play()}catch(c){console.warn("Failed to play video:",c)}}}pause(e){const t=e;t.pause(),t.muted=!0}async seek(e,t){const r=e,n=t+this.trim.from/1e6;return r.pause(),r.currentTime=n,new Promise(o=>{if(Math.abs(r.currentTime-t)<.01){o();return}const c=()=>{r.removeEventListener("seeked",c),o()};r.addEventListener("seeked",c,{once:!0}),setTimeout(()=>{r.removeEventListener("seeked",c),o()},500)})}syncPlayback(e,t,r){const n=e,o=(this.trim.to-this.trim.from)/1e6,c=r>=0&&r<o,l=r+this.trim.from/1e6;n.volume=this.volume,t&&c?n.paused?this.play(n,r).catch(console.warn):(n.muted&&(n.muted=!1),(n.ended||n.currentTime>=this.trim.to/1e6)&&(n.currentTime=l,n.play().catch(console.warn))):(n.paused||n.pause(),n.muted=!0,c&&Math.abs(n.currentTime-l)>.1&&(n.currentTime=l))}cleanupPlayback(e,t){const r=e;r.pause(),r.removeAttribute("src"),r.load(),t&&URL.revokeObjectURL(t)}async scaleToFit(e,t){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.min(e/r,t/n);this.width=r*o,this.height=n*o}async scaleToFill(e,t){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.max(e/r,t/n);this.width=r*o,this.height=n*o}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}}function _x(s,e,t,r){const n={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(s.video!=null&&e.length>0){n.width=s.video.codedWidth??0,n.height=s.video.codedHeight??0;const l=(Math.round(r/90)*90+360)%360;(l===90||l===270)&&([n.width,n.height]=[n.height,n.width])}s.audio!=null&&t.length>0&&(n.audioSampleRate=ae.sampleRate,n.audioChanCount=ae.channelCount);let o=0,c=0;if(e.length>0)for(let l=e.length-1;l>=0;l--){const d=e[l];if(!d.deleted){o=d.cts+d.duration;break}}if(t.length>0){const l=t.at(-1);c=l.cts+l.duration}return n.duration=Math.max(o,c),n}function yx(s,e,t,r,n){return{audioFrameFinder:n===0||s.audio==null||r.length===0?null:new Tx(e,r,s.audio,{volume:n,targetSampleRate:ae.sampleRate}),videoFrameFinder:s.video==null||t.length===0?null:new xx(e,t,s.video)}}async function qu(s,e={}){let t=null;const r={video:null,audio:null};let n=[],o=[],c=[];const l={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let d=-1,f=-1;const m=await s.createReader();await mx(m,async _=>{t=_.info;const y=_.mp4boxFile.ftyp;c.push({start:y.start,size:y.size});const a=_.mp4boxFile.moov;c.push({start:a.start,size:a.size}),Object.assign(l,gx(t.videoTracks[0]?.matrix));let{videoDecoderConf:h,audioDecoderConf:u}=To(_.mp4boxFile,_.info);if(r.video=h??null,r.audio=u??null,h==null&&u==null&&W.error("VideoClip no video and audio track"),u!=null){const{supported:p}=await AudioDecoder.isConfigSupported(u);p||W.error(`VideoClip audio codec is not supported: ${u.codec}`)}if(h!=null){const{supported:p}=await VideoDecoder.isConfigSupported(h);p||W.error(`VideoClip video codec is not supported: ${h.codec}`)}W.info("mp4BoxFile moov ready",{..._.info,tracks:null,videoTracks:null,audioTracks:null},r)},(_,y,a)=>{if(y==="video"){d===-1&&(d=a[0].dts);for(const h of a)n.push(Ku(h,d,"video"))}else if(y==="audio"&&e.audio){f===-1&&(f=a[0].dts);for(const h of a)o.push(Ku(h,f,"audio"))}}),await m.close();const g=n.at(-1)??o.at(-1);if(t==null)throw Error("VideoClip stream is done, but not emit ready");if(g==null)throw Error("VideoClip stream not contain any sample");return Co(n),W.info("mp4 stream parsed"),{videoSamples:n,audioSamples:o,decoderConf:r,headerBoxPos:c,parsedMatrix:l}}function Ku(s,e=0,t){let r=s.offset;const n=t==="video"&&s.is_sync?Px(s.data,s.description.type):-1;let o=s.size;return n>0&&(r+=n,o-=n),{...s,is_idr:n>=0,offset:r,size:o,cts:(s.cts-e)/s.timescale*1e6,dts:(s.dts-e)/s.timescale*1e6,duration:s.duration/s.timescale*1e6,timescale:1e6,data:t==="video"?null:s.data}}class xx{constructor(e,t,r){this.localFileReader=e,this.samples=t,this.conf=r}decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async e=>{(this.decoder==null||this.decoder.state==="closed"||e<=this.timestamp||e-this.timestamp>3e6)&&this.reset(e),this.curAborter.abort=!0,this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const t=await this.parseFrame(e,this.decoder,this.curAborter);return this.sleepCnt=0,t};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;parseFrame=async(e,t,r)=>{if(t==null||t.state==="closed"||r.abort)return null;if(this.videoFrames.length>0){const n=this.videoFrames[0];return e<n.timestamp?null:(this.videoFrames.shift(),e>n.timestamp+(n.duration??0)?(n.close(),await this.parseFrame(e,t,r)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(t).catch(o=>{throw this.predecodeErr=!0,this.reset(e),o}),n))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&t.decodeQueueSize>0){if(performance.now()-r.st>6e3)throw Error(`VideoClip.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await ws(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(t)}catch(n){throw this.reset(e),n}}return await this.parseFrame(e,t,r)};decoding=!1;startDecode=async e=>{if(this.decoding||e.decodeQueueSize>600)return;let t=this.videoDecCursorIdx+1;if(t>this.samples.length)return;this.decoding=!0;let r=!1;for(;t<this.samples.length;t++){const n=this.samples[t];if(!r&&!n.deleted&&(r=!0),n.is_idr)break}if(r){const n=this.samples.slice(this.videoDecCursorIdx,t);if(n[0]?.is_idr!==!0)W.warn("First sample not idr frame");else{const o=performance.now(),c=await Cx(n,this.localFileReader),l=performance.now()-o;if(l>1e3){const d=n[0],f=n.at(-1),m=f.offset+f.size-d.offset;W.warn(`Read video samples time cost: ${Math.round(l)}ms, file chunk size: ${m}`)}if(e.state==="closed")return;this.lastVfDur=c[0]?.duration??0,Ix(e,c,{onDecodingError:d=>{if(this.downgradeSoftDecode)throw d;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,W.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=c.length}}this.videoDecCursorIdx=t,this.decoding=!1};reset=e=>{if(this.decoding=!1,this.videoFrames.forEach(r=>r.close()),this.videoFrames=[],e==null||e===0)this.videoDecCursorIdx=0;else{let r=0;for(let n=0;n<this.samples.length;n++){const o=this.samples[n];if(o.is_idr&&(r=n),!(o.cts<e)){this.videoDecCursorIdx=r;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const t={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:r=>{if(this.outputFrameCnt+=1,r.timestamp===-1){r.close();return}let n=r;r.duration==null&&(n=new VideoFrame(r,{duration:this.lastVfDur}),r.close()),this.videoFrames.push(n)},error:r=>{if(r.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,W.warn(r.message);return}const n=`VideoFinder VideoDecoder err: ${r.message}, config: ${JSON.stringify(t)}, state: ${JSON.stringify(this.getState())}`;throw W.error(n),Error(n)}}),this.decoder.configure(t)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:wo,sleepCnt:this.sleepCnt,memInfo:Zu()});destroy=()=>{this.decoder?.state!=="closed"&&this.decoder?.close(),this.decoder=null,this.curAborter.abort=!0,this.videoFrames.forEach(e=>e.close()),this.videoFrames=[],this.localFileReader.close()}}function bx(s,e){for(let t=0;t<e.length;t++){const r=e[t];if(s>=r.cts&&s<r.cts+r.duration)return t;if(r.cts>s)break}return 0}class Tx{constructor(e,t,r,n){this.localFileReader=e,this.samples=t,this.conf=r,this.volume=n.volume,this.sampleRate=n.targetSampleRate}volume=1;sampleRate;setVolume(e){this.volume=e,this.reset()}decoder=null;curAborter={abort:!1,st:performance.now()};find=async e=>{const t=e<=this.timestamp||e-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||t)&&this.reset(),t&&(this.timestamp=e,this.decCursorIdx=bx(e,this.samples)),this.curAborter.abort=!0;const r=e-this.timestamp;this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const n=await this.parseFrame(Math.ceil(r*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,n};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(e,t=null,r)=>{if(t==null||r.abort||t.state==="closed"||e===0)return[];const n=this.pcmData.frameCnt-e;if(n>0)return n<ae.sampleRate/10&&this.startDecode(t),ju(this.pcmData,e);if(t.decoding){if(performance.now()-r.st>3e3)throw r.abort=!0,Error(`VideoClip.tick audio timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await ws(15)}else{if(this.decCursorIdx>=this.samples.length-1)return ju(this.pcmData,this.pcmData.frameCnt);this.startDecode(t)}return this.parseFrame(e,t,r)};startDecode=e=>{if(e.decodeQueueSize>10)return;const r=[];let n=this.decCursorIdx;for(;n<this.samples.length;){const o=this.samples[n];if(n+=1,!o.deleted&&(r.push(o),r.length>=10))break}this.decCursorIdx=n,e.decode(r.map(o=>new EncodedAudioChunk({type:"key",timestamp:o.cts,duration:o.duration,data:o.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=wx(this.conf,{resampleRate:ae.sampleRate,volume:this.volume},e=>{this.pcmData.data.push(e),this.pcmData.frameCnt+=e[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:wo,sleepCnt:this.sleepCnt,memInfo:Zu()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function wx(s,e,t){let r=0,n=0;const o=m=>{if(n+=1,m.length!==0){if(e.volume!==1)for(const g of m)for(let _=0;_<g.length;_++)g[_]*=e.volume;m.length===1&&(m=[m[0],m[0]]),t(m)}},c=Sx(o),l=e.resampleRate!==s.sampleRate;let d=new AudioDecoder({output:m=>{const g=ia(m);l?c(()=>xf(g,m.sampleRate,{rate:e.resampleRate,chanCount:m.numberOfChannels})):o(g),m.close()},error:m=>{m.message.includes("Codec reclaimed due to inactivity")||f("VideoClip AudioDecoder err",m)}});d.configure(s);function f(m,g){const _=`${m}: ${g.message}, state: ${JSON.stringify({qSize:d.decodeQueueSize,state:d.state,inputCnt:r,outputCnt:n})}`;throw W.error(_),Error(_)}return{decode(m){r+=m.length;try{for(const g of m)d.decode(g)}catch(g){f("decode audio chunk error",g)}},close(){d.state!=="closed"&&d.close()},get decoding(){return r>n&&d.decodeQueueSize>0},get state(){return d.state},get decodeQueueSize(){return d.decodeQueueSize}}}function Sx(s){const e=[];let t=0;function r(c,l){e[l]=c,n()}function n(){const c=e[t];c!=null&&(s(c),t+=1,n())}let o=0;return c=>{const l=o;o+=1,c().then(d=>r(d,l)).catch(d=>r(d,l))}}function ju(s,e){const t=[new Float32Array(e),new Float32Array(e)];let r=0,n=0;for(;n<s.data.length;){const[o,c]=s.data[n];if(r+o.length>e){const l=e-r;t[0].set(o.subarray(0,l),r),t[1].set(c.subarray(0,l),r),s.data[n][0]=o.subarray(l,o.length),s.data[n][1]=c.subarray(l,c.length);break}else t[0].set(o,r),t[1].set(c,r),r+=o.length,n++}return s.data=s.data.slice(n),s.frameCnt-=e,t}async function Cx(s,e){const t=s[0],r=s.at(-1);if(r==null)return[];const n=r.offset+r.size-t.offset;if(n<3e7){const o=new Uint8Array(await e.read(n,{at:t.offset}));return s.map(c=>{const l=c.offset-t.offset;return new EncodedVideoChunk({type:c.is_sync?"key":"delta",timestamp:c.cts,duration:c.duration,data:o.subarray(l,l+c.size)})})}return await Promise.all(s.map(async o=>new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:await e.read(o.size,{at:o.offset})})))}function Ax(s,e){if(s.length===0)return[];let t=0,r=0,n=-1;for(let d=0;d<s.length;d++){const f=s[d];if(n===-1&&e<f.cts&&(n=d-1),f.is_idr)if(n===-1)t=d;else{r=d;break}}const o=s[n];if(o==null)throw Error("Not found video sample by time");const c=s.slice(0,r===0?s.length:r).map(d=>({...d}));for(let d=t;d<c.length;d++){const f=c[d];e<f.cts&&(f.deleted=!0,f.cts=-1)}Co(c);const l=s.slice(o.is_idr?n:t).map(d=>({...d,cts:d.cts-e}));for(const d of l)d.cts<0&&(d.deleted=!0,d.cts=-1);return Co(l),[c,l]}function Ex(s,e){if(s.length===0)return[];let t=-1;for(let o=0;o<s.length;o++){const c=s[o];if(!(e>c.cts)){t=o;break}}if(t===-1)throw Error("Not found audio sample by time");const r=s.slice(0,t).map(o=>({...o})),n=s.slice(t).map(o=>({...o,cts:o.cts-e}));return[r,n]}function Ix(s,e,t){if(s.state==="configured"){for(let r=0;r<e.length;r++)s.decode(e[r]);s.flush().catch(r=>{if(!(r instanceof Error))throw r;if(r.message.includes("Decoding error")&&t.onDecodingError!=null){t.onDecodingError(r);return}if(!r.message.includes("Aborted due to close"))throw r})}}function Px(s,e){if(e!=="avc1"&&e!=="hvc1")return 0;const t=new DataView(s.buffer);for(let r=0;r<s.byteLength-4;){if(e==="avc1"){const n=t.getUint8(r+4)&31;if(n===5||n===7||n===8)return r}else if(e==="hvc1"){const n=t.getUint8(r+4)>>1&63;if(n===19||n===20||n===32||n===33||n===34)return r}r+=t.getUint32(r)+4}return-1}function Co(s){let e=0,t=null;for(const r of s)if(!r.deleted){if(r.is_sync&&(e+=1),e>=2)break;(t==null||r.cts<t.cts)&&(t=r)}t!=null&&t.cts<2e5&&(t.duration+=t.cts,t.cts=0)}function Zu(){try{const s=performance.memory;return{jsHeapSizeLimit:s.jsHeapSizeLimit,totalJSHeapSize:s.totalJSHeapSize,usedJSHeapSize:s.usedJSHeapSize,percentUsed:(s.usedJSHeapSize/s.jsHeapSizeLimit).toFixed(3),percentTotal:(s.totalJSHeapSize/s.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}function nr(s){if(s!=null){if(typeof s=="number")return s;if(typeof s=="string"){if(s.startsWith("#")){const t=parseInt(s.slice(1),16);if(!isNaN(t))return t}if(s.startsWith("0x")){const t=parseInt(s,16);if(!isNaN(t))return t}const e=parseInt(s,16);if(!isNaN(e))return e;try{return new se(s).toNumber()}catch{return}}}}class Ze extends kt{type="Text";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}get width(){return this._width}set width(e){this.width!==e&&(this._width=e,this.refreshText(),this.emit("propsChange",{width:e}))}get height(){return this._height}set height(e){this.height!==e&&(this._height=e,this.refreshText(),this.emit("propsChange",{height:e}))}_text="";get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this.originalOpts&&this.textStyle&&this.refreshText())}get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,fill:this.originalOpts.fill,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,dropShadow:this.originalOpts.dropShadow?{color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing,textCase:this.originalOpts.textCase,textDecoration:this.originalOpts.textDecoration}}set style(e){this.updateStyle(e)}get textAlign(){return this.originalOpts.align||this.originalOpts.textAlign||"left"}set textAlign(e){this.updateStyle({align:e})}get verticalAlign(){return this.originalOpts.verticalAlign||this.originalOpts.textDecoration||"top"}set verticalAlign(e){["underline","overline","strikethrough","line-through"].includes(e)?(this.updateStyle({textDecoration:e==="strikethrough"?"line-through":e}),this.originalOpts.verticalAlign=e):this.updateStyle({verticalAlign:e})}get textCase(){return this.originalOpts.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}pixiText=null;textStyle;renderTexture=null;externalRenderer=null;pixiApp=null;originalOpts;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];constructor(e,t={},r){super(),this.originalOpts={...t},this.text=e,this.externalRenderer=r??null,console.log("[TextClip] Constructor:",{opts:t});const n=this.createStyleFromOpts(t),o=new Be(n);this.textStyle=o,this.ready=(async()=>{await this.refreshText();const c={...this._meta};return W.info("TextClip ready:",c),c})()}setRenderer(e){this.externalRenderer=e,console.log("SET RENDERER",e)}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("TextClip: Failed to create renderer. Please provide a renderer via constructor or setRenderer() method.");return this.pixiApp.renderer}async getTexture(){return this.pixiText==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture}),this.renderTexture)}async tick(e){if(await this.ready,this.pixiText==null||this.renderTexture==null)throw new Error("TextClip not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);(await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture});const r=this.renderTexture.source?.resource?.source;let n;if(r instanceof HTMLCanvasElement)n=await createImageBitmap(r);else if(r instanceof OffscreenCanvas)n=await createImageBitmap(r);else{const l=(await this.getRenderer()).extract.canvas(this.renderTexture);if(l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas)n=await createImageBitmap(l);else{const d=this.renderTexture.width,f=this.renderTexture.height;throw new OffscreenCanvas(d,f).getContext("2d")==null?new Error("Failed to create 2d context for fallback rendering"):new Error("Unable to extract canvas from render texture")}}return{video:n,state:"success"}}async split(e){await this.ready;const t=await this.clone(),r=await this.clone();return[t,r]}addEffect(e){this.effects.push(e)}editEffect(e,t){const r=this.effects.find(n=>n.id===e);r&&Object.assign(r,t)}removeEffect(e){const t=this.effects.findIndex(r=>r.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.textStyle,t=this.originalOpts||{},r=c=>{if(c!=null){if(typeof c=="number")return c;if(c instanceof se)return c.toNumber()}},n={fontSize:t.fontSize??e.fontSize,fontFamily:t.fontFamily??(Array.isArray(e.fontFamily)?e.fontFamily[0]:typeof e.fontFamily=="string"?e.fontFamily:"Roboto"),fontWeight:t.fontWeight??e.fontWeight,fontStyle:t.fontStyle??e.fontStyle,align:t.align??(e.align==="justify"?"left":e.align),textCase:t.textCase,textDecoration:t.textDecoration};if(t.fill&&typeof t.fill=="object"&&"type"in t.fill&&t.fill.type==="gradient")n.fill=t.fill;else{const c=r(e.fill);n.fill=c??16777215}if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke)n.stroke=t.stroke;else{const c=r(e.stroke);c!==void 0&&(n.stroke=c),n.strokeWidth=t.strokeWidth??e.strokeThickness??0}if(t.dropShadow)n.dropShadow=t.dropShadow;else if(e.dropShadow){const c=e.dropShadow,l=r(c.color);l!==void 0&&(n.dropShadow={color:l,alpha:c.alpha,blur:c.blur,angle:c.angle,distance:c.distance})}if(t.wordWrap!==void 0?(n.wordWrap=t.wordWrap,n.wordWrapWidth=t.wordWrapWidth):e.wordWrap&&(n.wordWrap=e.wordWrap,n.wordWrapWidth=e.wordWrapWidth),t.lineHeight!==void 0)n.lineHeight=t.lineHeight;else if(e.lineHeight!==void 0){const c=n.fontSize??e.fontSize??40;n.lineHeight=e.lineHeight/c}t.letterSpacing!==void 0?n.letterSpacing=t.letterSpacing:e.letterSpacing!==void 0&&(n.letterSpacing=e.letterSpacing);const o=new Ze(this.text,n);return await o.ready,this.copyStateTo(o),o.id=this.id,o.effects=[...this.effects],o}async updateStyle(e){this.originalOpts={...this.originalOpts,...e};const t=this.createStyleFromOpts(this.originalOpts),r=new Be(t);this.textStyle=r,await this.refreshText()}async refreshText(){const e=this.textStyle;let t=this.text;const r=this.originalOpts.textCase;r==="uppercase"?t=t.toUpperCase():r==="lowercase"?t=t.toLowerCase():r==="title"&&(t=t.replace(/\w\S*/g,y=>y.charAt(0).toUpperCase()+y.substring(1).toLowerCase())),this.pixiText?(this.pixiText.text=t,this.pixiText.style=e,this.pixiText.children.forEach(y=>{y instanceof Ae&&y.destroy()}),this.pixiText.removeChildren()):this.pixiText=new Lv({text:t,style:e});const n=this.originalOpts.textDecoration||this.originalOpts.verticalAlign;if(n&&n!=="none"&&["underline","overline","strikethrough","line-through"].includes(n)){const y=n==="strikethrough"?"line-through":n,a=He.measureText(t,e),h=e.fontSize??40,u=Math.max(1,h/12);let p=16777215;typeof e.fill=="number"?p=e.fill:e.fill&&typeof e.fill=="object"&&"fill"in e.fill&&(p=16777215);const v=new Ae,x=e.lineHeight??a.lineHeight;for(let b=0;b<a.lines.length;b++){const T=a.lineWidths[b];let w=0;e.align==="center"?w=(a.maxLineWidth-T)/2:e.align==="right"&&(w=a.maxLineWidth-T);const S=b*x;let E=0;y==="underline"?E=x:y==="line-through"?E=x/2:y==="overline"&&(E=0);const A=S+E;v.rect(w,A,T,u),v.fill(p)}this.pixiText.addChild(v)}const o=this.pixiText.getLocalBounds(),c=Math.ceil(o.width||this.pixiText.width||1),l=Math.ceil(o.height||this.pixiText.height||1);let d=Math.max(1,c);e.wordWrap&&e.wordWrapWidth>0&&(d=Math.max(d,e.wordWrapWidth));const f=Math.max(d,this.width||0),m=Math.max(l,this.height||0),g=this.textAlign;g==="center"?this.pixiText.x=(f-c)/2:g==="right"?this.pixiText.x=f-c:this.pixiText.x=0;const _=this.originalOpts.verticalAlign||"top";_==="center"?this.pixiText.y=(m-l)/2:_==="bottom"?this.pixiText.y=m-l:this.pixiText.y=0,this.renderTexture&&this.renderTexture.destroy(!0),this.renderTexture=Ee.create({width:f,height:m}),this._meta.width=f,this._meta.height=m,this._width=f,this._height=m,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration)}createStyleFromOpts(e){const t=e.fontSize??40,r=e.lineHeight??1,n={fontSize:t,fontFamily:e.fontFamily??"Roboto",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",align:e.align??"left",wordWrap:e.wordWrap??!1,wordWrapWidth:e.wordWrapWidth??100,lineHeight:t*r,letterSpacing:e.letterSpacing??0};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const o=new Ke(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:c,color:l})=>{const d=typeof l=="number"?l:nr(l)??16777215;o.addColorStop(c,d)}),n.fill={fill:o}}else{const o=typeof e.fill=="string"||typeof e.fill=="number"?nr(e.fill):void 0;n.fill=o??16777215}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const o=nr(e.stroke.color);o!==void 0&&(n.stroke={color:o,width:e.stroke.width},e.stroke.join&&(n.stroke.join=e.stroke.join),e.stroke.cap&&(n.stroke.cap=e.stroke.cap),e.stroke.miterLimit&&(n.stroke.miterLimit=e.stroke.miterLimit))}else{const o=nr(e.stroke),c=e.strokeWidth??0;o!==void 0&&c>0?n.stroke={color:o,width:c}:e.strokeWidth&&e.strokeWidth>0&&(n.stroke={color:0,width:e.strokeWidth})}if(e.dropShadow){const o=nr(e.dropShadow.color);o!==void 0&&(n.dropShadow={color:o,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}return n}destroy(){if(!this.destroyed){W.info("TextClip destroy");try{this.pixiText!=null&&this.pixiText.destroyed!==!0&&this.pixiText.destroy({children:!0})}catch{}finally{this.pixiText=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),r={};return this.originalOpts.fontSize!==void 0&&(r.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(r.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontWeight!==void 0&&(r.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(r.fontStyle=this.originalOpts.fontStyle),this.originalOpts.fill!==void 0&&(r.color=this.originalOpts.fill),this.originalOpts.align!==void 0&&(r.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(r.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(r.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(r.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(r.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?r.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}:r.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.dropShadow&&(r.shadow={color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}),{...t,type:"Text",text:this.text,style:r,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Text")throw new Error(`Expected Text, got ${e.type}`);const t=e.text||"",r=e.style||{},n={};r.fontSize!==void 0&&(n.fontSize=r.fontSize),r.fontFamily!==void 0&&(n.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(n.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(n.fontStyle=r.fontStyle),r.color!==void 0&&(n.fill=r.color),r.align!==void 0&&(n.align=r.align),r.wordWrap!==void 0&&(n.wordWrap=r.wordWrap),r.wordWrapWidth!==void 0&&(n.wordWrapWidth=r.wordWrapWidth),r.lineHeight!==void 0&&(n.lineHeight=r.lineHeight),r.letterSpacing!==void 0&&(n.letterSpacing=r.letterSpacing),r.stroke&&(r.stroke.join||r.stroke.cap||r.stroke.miterLimit!==void 0?n.stroke={color:r.stroke.color,width:r.stroke.width,join:r.stroke.join,cap:r.stroke.cap,miterLimit:r.stroke.miterLimit}:(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width)),r.shadow&&(n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:r.shadow.distance,angle:r.shadow.angle});const o=new Ze(t,n);return o.left=e.left,o.top=e.top,o.width=e.width,o.height=e.height,o.angle=e.angle,o.display.from=e.display.from,o.display.to=e.display.to,o.duration=e.duration,o.playbackRate=e.playbackRate,o.zIndex=e.zIndex,o.opacity=e.opacity,o.flip=e.flip,e.animation&&o.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(o.id=e.id),e.effects&&(o.effects=e.effects),await o.ready,o}}class Je extends kt{type="Effect";ready;_meta={duration:5e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effect;constructor(e){super(),this.effect={id:`eff_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Je(this.effect.key);return this.copyStateTo(e),e.id=this.id,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),r=await this.clone();return[t,r]}toJSON(e=!1){return{...super.toJSON(e),type:"Effect",effect:this.effect,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Effect")throw new Error(`Expected Effect, got ${e.type}`);const t=new Je(e.effect.key);return t.effect=e.effect,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}class fi extends kt{type="Transition";ready;_meta={duration:2e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;transitionEffect;fromClipId=null;toClipId=null;constructor(e){super(),this.transitionEffect={id:`trans_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new fi(this.transitionEffect.key);return this.copyStateTo(e),e.fromClipId=this.fromClipId,e.toClipId=this.toClipId,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),r=await this.clone();return[t,r]}toJSON(e=!1){return{...super.toJSON(e),type:"Transition",transitionEffect:this.transitionEffect,fromClipId:this.fromClipId,toClipId:this.toClipId,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Transition")throw new Error(`Expected Transition, got ${e.type}`);const t=new fi(e.transitionEffect.key);return t.transitionEffect=e.transitionEffect,t.fromClipId=e.fromClipId||null,t.toClipId=e.toClipId||null,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}class Ju{readable;writable;inputBufOffset=0;constructor(){const e=ke.createFile();let t=!1;this.readable=new ReadableStream({start:r=>{e.onReady=o=>{const c=o.videoTracks[0]?.id;c!=null&&e.setExtractionOptions(c,"video",{nbSamples:100});const l=o.audioTracks[0]?.id;l!=null&&e.setExtractionOptions(l,"audio",{nbSamples:100}),r.enqueue({chunkType:"ready",data:{info:o,file:e}}),e.start()};const n={};e.onSamples=(o,c,l)=>{r.enqueue({chunkType:"samples",data:{id:o,type:c,samples:l.map(d=>({...d}))}}),n[o]=(n[o]??0)+l.length,e.releaseUsedSamples(o,n[o])},e.onFlush=()=>{r.close()}},cancel:()=>{e.stop(),t=!0}},{highWaterMark:50}),this.writable=new WritableStream({write:async r=>{if(t){this.writable.abort();return}const n=r.buffer;n.fileStart=this.inputBufOffset,this.inputBufOffset+=n.byteLength,e.appendBuffer(n)},close:()=>{e.flush(),e.stop(),e.onFlush?.()}})}}function Rx(s){let e=0;const t=s.boxes,r=[];let n=0;async function o(){const a=y(t,e);e=t.length,r.forEach(({track:h,id:u})=>{const p=h.samples.at(-1);p!=null&&(n=Math.max(n,p.cts+p.duration)),s.releaseUsedSamples(u,h.samples.length),h.samples=[]}),s.mdats=[],s.moofs=[],a!=null&&await m?.write(a)}let c=[];function l(){if(c.length>0)return!0;const a=t.findIndex(h=>h.type==="moov");if(a===-1)return!1;if(c=t.slice(0,a+1),e=a+1,r.length===0)for(let h=1;;h+=1){const u=s.getTrackById(h);if(u==null)break;r.push({track:u,id:h})}return!0}let d=0;const f=vs();let m=null;const g=(async()=>{m=await f.createWriter(),d=self.setInterval(()=>{l()&&o()},100)})();let _=!1;return async()=>{if(_)throw Error("File exported");if(_=!0,await g,clearInterval(d),!l()||m==null)return null;s.flush(),await o(),await m?.close();const a=c.find(p=>p.type==="moov");if(a==null)return null;a.mvhd.duration=n;const h=vs(),u=y(c,0);return await bi(h,u.slice()),await bi(h,f,{overwrite:!1}),await h.stream()};function y(a,h){if(h>=a.length)return null;const u=new ke.DataStream;u.endianness=ke.DataStream.BIG_ENDIAN;for(let p=h;p<a.length;p++)a[p]!==null&&(a[p].write(u),delete a[p]);return new Uint8Array(u.buffer).slice()}}function Mx(s){const e=new ArrayBuffer(s.byteLength);s.copyTo(e);const t=s.timestamp;return{duration:s.duration??0,dts:t,cts:t,is_sync:s.type==="key",data:e}}async function Qu(s){const e=ke.createFile(),t=Rx(e);await Fx(s,e);const r=await t();if(r==null)throw Error("Can not generate file from streams");return r}async function Fx(s,e){let t=0,r=0,n=0,o=0,c=0,l=0,d=null,f=null;for(const m of s){let g=null,_=null,y=null,a=null;if(await new Promise(async h=>{Zo(m.pipeThrough(new Ju),{onDone:h,onChunk:async({chunkType:u,data:p})=>{if(u==="ready"){const{videoTrackConf:v,audioTrackConf:x}=To(p.file,p.info);t===0&&v!=null&&(t=e.addTrack(v)),o===0&&x!=null&&(o=e.addTrack(x))}else if(u==="samples"){const{type:v,samples:x}=p,b=v==="video"?t:o,T=v==="video"?r:c,w=v==="video"?n:l;x.forEach(E=>{let A,P;v==="video"?(g===null&&(g=E.dts,_=E.cts),A=E.dts-g,P=E.cts-(_??0)):(y===null&&(y=E.dts,a=E.cts),A=E.dts-y,P=E.cts-(a??0)),e.addSample(b,E.data,{duration:E.duration,dts:A+T,cts:P+w,is_sync:E.is_sync})});const S=x.at(-1);if(S==null)return;v==="video"?d=S:v==="audio"&&(f=S)}}})}),d!=null&&g!==null&&_!==null){const h=d.dts-g+d.duration,u=d.cts-_+d.duration;r+=h,n+=u}if(f!=null&&d!=null){const h=f.timescale/d.timescale;c=Math.round(r*h),l=Math.round(n*h)}}}async function Ux(s){return await Qu([s])}function kx(s){let e=[];const t=new AudioDecoder({output:r=>{e.push(r)},error:W.error});return t.configure(s),{decode:async r=>{r.forEach(o=>{t.decode(new EncodedAudioChunk({type:o.is_sync?"key":"delta",timestamp:1e6*o.cts/o.timescale,duration:1e6*o.duration/o.timescale,data:o.data}))}),await t.flush();const n=e;return e=[],n},close:()=>{t.close()}}}function Bx(s,e){const t={codec:s.codec,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels},r=new AudioEncoder({output:c=>{e(Mx(c))},error:c=>{W.error("AudioEncoder error:",c,", config:",t)}});r.configure(t);let n=null;function o(c,l){return new AudioData({timestamp:l,numberOfChannels:s.numberOfChannels,numberOfFrames:c.length/s.numberOfChannels,sampleRate:s.sampleRate,format:"f32-planar",data:new Float32Array(c)})}return{encode:async(c,l)=>{n!=null&&r.encode(o(n.data,n.ts)),n={data:c,ts:l}},stop:async()=>{n!=null&&(Dx(n.data,s.numberOfChannels,s.sampleRate),r.encode(o(n.data,n.ts)),n=null),await r.flush(),r.close()}}}function Dx(s,e,t){const r=s.length-1,n=Math.min(t/2,r);for(let o=0;o<n;o++)for(let c=1;c<=e;c++)s[Math.floor(r/c)-o]*=o/n}function Ox(s,e){W.info("mixinMP4AndAudio, opts:",{volume:e.volume,loop:e.loop});const t=ke.createFile(),{stream:r,stop:n}=Jo(t,500);let o=null,c=null,l=[],d=0,f=0,m=0,g=!0,_=ae.sampleRate;Zo(s.pipeThrough(new Ju),{onDone:async()=>{await c?.stop(),o?.close(),n()},onChunk:async({chunkType:u,data:p})=>{if(u==="ready"){const{videoTrackConf:v,audioTrackConf:x,audioDecoderConf:b}=To(p.file,p.info);d===0&&v!=null&&(d=t.addTrack(v));const T=x??{timescale:1e6,samplerate:_,channel_count:ae.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};f===0&&(f=t.addTrack(T),_=x?.samplerate??_,g=x!=null);const w=new AudioContext({sampleRate:_});l=bs(await w.decodeAudioData(await new Response(e.stream).arrayBuffer())),b!=null&&(o=kx(b)),c=Bx(b??{codec:T.type==="mp4a"?ae.codec:T.type,numberOfChannels:T.channel_count,sampleRate:T.samplerate},S=>t.addSample(f,S.data,S))}else if(u==="samples"){const{id:v,type:x,samples:b}=p;if(x==="video"){b.forEach(T=>t.addSample(v,T.data,T)),g||await a(b);return}x==="audio"&&await h(b)}}});function y(u){const p=l.map(v=>e.loop?Ts(v,m,m+u):v.slice(m,m+u));if(m+=u,e.volume!==1)for(const v of p)for(let x=0;x<v.length;x++)v[x]*=e.volume;return p}async function a(u){const p=u[0],v=u[u.length-1],x=Math.floor((v.cts+v.duration-p.cts)/p.timescale*_),b=ra([y(x)]);b.length!==0&&c?.encode(b,p.cts/p.timescale*1e6)}async function h(u){if(o==null)return;const p=(await o.decode(u)).map(ia),v=ta(p),x=y(v[0].length),b=u[0];c?.encode(ra([v,x]),b.cts/b.timescale*1e6)}return r}const Gx=`
|
|
1295
|
+
`)}function ox(s,e,t,r,n){const{domElement:o,styleElement:c,svgRoot:l}=n;o.innerHTML=`<style>${e.cssStyle}</style><div style='padding:0;'>${s}</div>`,o.setAttribute("style",`transform: scale(${t});transform-origin: top left; display: inline-block`),c.textContent=r;const{width:d,height:f}=n.image;return l.setAttribute("width",d.toString()),l.setAttribute("height",f.toString()),new XMLSerializer().serializeToString(l)}function ax(s,e){const t=xt.getOptimalCanvasAndContext(s.width,s.height,e),{context:r}=t;return r.clearRect(0,0,s.width,s.height),r.drawImage(s,0,0),t}function lx(s,e,t){return new Promise(async r=>{t&&await new Promise(n=>setTimeout(n,100)),s.onload=()=>{r()},s.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(e)}`,s.crossOrigin="anonymous"})}class Vu{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===tt.WEBGPU}getTexture(e){return this.getTexturePromise(e)}getManagedTexture(e){const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].promise;const r=this._buildTexturePromise(e).then(n=>(this._activeTextures[t].texture=n,n));return this._activeTextures[t]={texture:null,promise:r,usageCount:1},r}getReferenceCount(e){return this._activeTextures[e]?.usageCount??null}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t.texture):t.promise.then(r=>{t.texture=r,this._cleanUp(t.texture)}).catch(()=>{G("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[e]=null))}getTexturePromise(e){return this._buildTexturePromise(e)}async _buildTexturePromise(e){const{text:t,style:r,resolution:n,textureStyle:o}=e,c=me.get(rh),l=ix(t,r),d=await nx(l),f=zv(t,r,d,c),m=Math.ceil(Math.ceil(Math.max(1,f.width)+r.padding*2)*n),g=Math.ceil(Math.ceil(Math.max(1,f.height)+r.padding*2)*n),_=c.image,y=2;_.width=(m|0)+y,_.height=(g|0)+y;const a=ox(t,r,n,d,c);await lx(_,a,ex()&&l.length>0);const h=_;let u;this._createCanvas&&(u=ax(_,n));const p=Wu(u?u.canvas:h,_.width-y,_.height-y,n);return o&&(p.source.style=o),this._createCanvas&&(this._renderer.texture.initSource(p.source),xt.returnCanvasAndContext(u)),me.return(c),p}returnTexturePromise(e){e.then(t=>{this._cleanUp(t)}).catch(()=>{G("HTMLTextSystem: Failed to clean texture")})}_cleanUp(e){we.returnTexture(e,!0),e.source.resource=null,e.source.uploadMethodId="unknown"}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexturePromise(this._activeTextures[e].promise);this._activeTextures=null}}Vu.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"htmlText"};class cx extends ne{constructor(e){const{text:t,style:r,autoSplit:n,lineAnchor:o,wordAnchor:c,charAnchor:l,...d}=e;super(d),this._dirty=!1,this._canReuseChars=!1,this.chars=[],this.words=[],this.lines=[],this._originalText=t,this._autoSplit=n,this._lineAnchor=o,this._wordAnchor=c,this._charAnchor=l,this.style=r}split(){const e=this.splitFn();this.chars=e.chars,this.words=e.words,this.lines=e.lines,this.addChild(...this.lines),this.charAnchor=this._charAnchor,this.wordAnchor=this._wordAnchor,this.lineAnchor=this._lineAnchor,this._dirty=!1,this._canReuseChars=!0}get text(){return this._originalText}set text(e){this._originalText=e,this.lines.forEach(t=>t.destroy({children:!0})),this.lines.length=0,this.words.length=0,this.chars.length=0,this._canReuseChars=!1,this.onTextUpdate()}_setOrigin(e,t,r){let n;typeof e=="number"?n={x:e,y:e}:n={x:e.x,y:e.y},t.forEach(o=>{const c=o.getLocalBounds(),l=c.minX+c.width*n.x,d=c.minY+c.height*n.y;o.origin.set(l,d)}),this[r]=e}get lineAnchor(){return this._lineAnchor}set lineAnchor(e){this._setOrigin(e,this.lines,"_lineAnchor")}get wordAnchor(){return this._wordAnchor}set wordAnchor(e){this._setOrigin(e,this.words,"_wordAnchor")}get charAnchor(){return this._charAnchor}set charAnchor(e){this._setOrigin(e,this.chars,"_charAnchor")}get style(){return this._style}set style(e){e||(e={}),this._style=new Be(e),this.words.forEach(t=>t.destroy()),this.words.length=0,this.lines.forEach(t=>t.destroy()),this.lines.length=0,this._canReuseChars=!0,this.onTextUpdate()}onTextUpdate(){this._dirty=!0,this._autoSplit&&this.split()}destroy(e){super.destroy(e),this.chars=[],this.words=[],this.lines=[],(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._originalText=""}}const Yu=class cs extends cx{constructor(e){const t={...cs.defaultOptions,...e};super(t)}static from(e,t){const r={...cs.defaultOptions,...t,text:e.text,style:new Be(e.style)};return new cs({...r})}splitFn(){return Jy({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};Yu.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let hx=Yu;class ux extends ns{constructor(e){super(),this._renderer=e,e.runners.resolutionChange.add(this)}resolutionChange(){const e=this.renderable;e._autoResolution&&e.onViewUpdate()}destroy(){const{canvasText:e}=this._renderer;e.getReferenceCount(this.currentKey)>0?e.decreaseReferenceCount(this.currentKey):this.texture&&e.returnTexture(this.texture),this._renderer.runners.resolutionChange.remove(this),this._renderer=null}}class Xu{constructor(e){this._renderer=e}validateRenderable(e){const t=this._getGpuText(e),r=e.styleKey;return t.currentKey!==r?!0:e._didTextUpdate}addRenderable(e,t){const r=this._getGpuText(e);if(e._didTextUpdate){const n=e._autoResolution?this._renderer.resolution:e.resolution;(r.currentKey!==e.styleKey||e.resolution!==n)&&this._updateGpuText(e),e._didTextUpdate=!1,xo(r,e)}this._renderer.renderPipes.batch.addToBatch(r,t)}updateRenderable(e){const t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){const t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new ux(this._renderer);return t.currentKey="--",t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}Xu.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"text"};class $u{constructor(e){this._activeTextures={},this._renderer=e}getTexture(e,t,r,n){typeof e=="string"&&(H("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:r,resolution:t}),e.style instanceof Be||(e.style=new Be(e.style)),e.textureStyle instanceof at||(e.textureStyle=new at(e.textureStyle)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:o,style:c,textureStyle:l}=e,d=e.resolution??this._renderer.resolution,{frame:f,canvasAndContext:m}=tr.getCanvasAndContext({text:o,style:c,resolution:d}),g=Wu(m.canvas,f.width,f.height,d);if(l&&(g.source.style=l),c.trim&&(f.pad(c.padding),g.frame.copyFrom(f),g.frame.scale(1/d),g.updateUvs()),c.filters){const _=this._applyFilters(g,c.filters);return this.returnTexture(g),tr.returnCanvasAndContext(m),_}return this._renderer.texture.initSource(g._source),tr.returnCanvasAndContext(m),g}returnTexture(e){const t=e.source;t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",we.returnTexture(e,!0)}renderTextToCanvas(){H("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;const r=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle});return this._activeTextures[t]={texture:r,usageCount:1},r}decreaseReferenceCount(e){const t=this._activeTextures[e];t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null)}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const r=this._renderer.renderTarget.renderTarget,n=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind(r,!1),n}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}$u.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"canvasText"},L.add(Yf,Xf);function ye(s){if(s!=null){if(typeof s=="number")return s;if(typeof s=="string"){if(s.startsWith("#")){const t=parseInt(s.slice(1),16);if(!isNaN(t))return t}if(s.startsWith("0x")){const t=parseInt(s,16);if(!isNaN(t))return t}const e=parseInt(s,16);if(!isNaN(e))return e;try{return new se(s).toNumber()}catch{return}}}}class Ft extends kt{type="Caption";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}text;get style(){if(!this.originalOpts)return{};const e=this.originalOpts;return{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,color:e.fill,align:e.align,textCase:e.textCase,stroke:e.stroke?typeof e.stroke=="object"?{color:e.stroke.color,width:e.stroke.width}:{color:e.stroke,width:e.strokeWidth??0}:void 0,shadow:e.dropShadow?{color:e.dropShadow.color??"#000000",alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,distance:e.dropShadow.distance??0,angle:e.dropShadow.angle??0}:void 0}}bottomOffset;get textCase(){return this.originalOpts?.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];opts;pixiTextContainer=null;renderTexture=null;wordTexts=[];extraPadding=0;textStyle;externalRenderer=null;pixiApp=null;originalOpts=null;constructor(e,t={},r){super(),this.text=e,this.originalOpts={...t},this.externalRenderer=r??null,this.opts={fontSize:t.fontSize??30,fontFamily:t.fontFamily??"Arial",fontUrl:t.fontUrl??"",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",fill:t.fill??"#ffffff",strokeWidth:t.strokeWidth??0,align:t.align??"center",wordWrapWidth:t.wordWrapWidth??0,wordWrap:t.wordWrap??!1,lineHeight:t.lineHeight??1,letterSpacing:t.letterSpacing??0,textCase:t.textCase??"none",videoWidth:t.caption?.positioning?.videoWidth??t.videoWidth??1280,videoHeight:t.caption?.positioning?.videoHeight??t.videoHeight??720,bottomOffset:t.caption?.positioning?.bottomOffset??t.bottomOffset??30,keyword:t.caption?.colors?.keyword??t.colors?.keyword??"#ffff00",background:t.caption?.colors?.background??t.colors?.background??"#000000",active:t.caption?.colors?.active??t.colors?.active??"#ffffff",activeFill:t.caption?.colors?.activeFill??t.colors?.activeFill??"#00ff00",appeared:t.caption?.colors?.appeared??t.colors?.appeared??"#ffffff",words:t.caption?.words??t.words??[],preserveKeywordColor:t.caption?.preserveKeywordColor??t.preserveKeywordColor??!1};const n={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(t.fill&&typeof t.fill=="object"&&t.fill.type==="gradient"){const l=new Ke(t.fill.x0,t.fill.y0,t.fill.x1,t.fill.y1);t.fill.colors.forEach(({ratio:d,color:f})=>{const m=typeof f=="number"?f:ye(f)??16777215;l.addColorStop(d,m)}),n.fill={fill:l}}else{const l=typeof t.fill=="string"||typeof t.fill=="number"?ye(t.fill):void 0;n.fill=l??16777215}const o=l=>l==="transparent";if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke){if(!o(t.stroke.color)){const l=ye(t.stroke.color);l!==void 0&&(n.stroke={color:l,width:t.stroke.width},t.stroke.join&&(n.stroke.join=t.stroke.join))}}else if(!o(t.stroke)){const l=ye(t.stroke);l!==void 0?n.stroke={color:l,width:this.opts.strokeWidth??0}:this.opts.strokeWidth&&this.opts.strokeWidth>0&&(n.stroke={color:0,width:this.opts.strokeWidth})}if(t.dropShadow){const l=ye(t.dropShadow.color);l!==void 0&&(n.dropShadow={color:l,alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,angle:t.dropShadow.angle??Math.PI/6,distance:t.dropShadow.distance??2})}const c=new Be(n);this.textStyle=c,this.ready=(async()=>{await this.refreshCaptions();const l={...this._meta};return W.info("CaptionClip ready:",l),l})()}async updateStyle(e){this.originalOpts||(this.originalOpts={}),this.originalOpts={...this.originalOpts,...e},e.fontSize!==void 0&&(this.opts.fontSize=e.fontSize),e.fontFamily!==void 0&&(this.opts.fontFamily=e.fontFamily),e.fontWeight!==void 0&&(this.opts.fontWeight=e.fontWeight),e.fontStyle!==void 0&&(this.opts.fontStyle=e.fontStyle),e.fill!==void 0&&(this.opts.fill=e.fill),e.align!==void 0&&(this.opts.align=e.align),e.letterSpacing!==void 0&&(this.opts.letterSpacing=e.letterSpacing),e.lineHeight!==void 0&&(this.opts.lineHeight=e.lineHeight),e.textCase!==void 0&&(this.opts.textCase=e.textCase);const t={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(this.opts.fill&&typeof this.opts.fill=="object"&&this.opts.fill.type==="gradient"){const r=new Ke(this.opts.fill.x0,this.opts.fill.y0,this.opts.fill.x1,this.opts.fill.y1);this.opts.fill.colors.forEach(({ratio:n,color:o})=>{const c=typeof o=="number"?o:ye(o)??16777215;r.addColorStop(n,c)}),t.fill={fill:r}}else{const r=typeof this.opts.fill=="string"||typeof this.opts.fill=="number"?ye(this.opts.fill):void 0;t.fill=r??16777215}if(e.stroke!==void 0||e.strokeWidth!==void 0)if(this.originalOpts.stroke&&typeof this.originalOpts.stroke=="object"&&"color"in this.originalOpts.stroke){const r=ye(this.originalOpts.stroke.color);r!==void 0&&(t.stroke={color:r,width:this.originalOpts.stroke.width},this.originalOpts.stroke.join&&(t.stroke.join=this.originalOpts.stroke.join))}else{const r=ye(this.originalOpts.stroke),n=e.strokeWidth??this.originalOpts.strokeWidth??0;r!==void 0?t.stroke={color:r,width:n}:n>0&&(t.stroke={color:0,width:n})}this.textStyle=new Be(t),await this.refreshCaptions()}async refreshCaptions(){this.pixiTextContainer?(this.pixiTextContainer.children.forEach(p=>{p instanceof Ae&&p.label}),this.pixiTextContainer.removeChildren()):this.pixiTextContainer=new ne;const e=this.textStyle;let t=0,r=0,n=0;const o=this.opts.textCase;this.wordTexts=this.opts.words.map(p=>{let v=p.text;o==="uppercase"?v=v.toUpperCase():o==="lowercase"?v=v.toLowerCase():o==="title"&&(v=v.replace(/\w\S*/g,E=>E.charAt(0).toUpperCase()+E.substring(1).toLowerCase()));const x=new hx({text:v,style:e});x.x=t,x.y=0;const b=x.getLocalBounds(),T=Math.ceil(b.width||x.width),w=Math.ceil(b.height||x.height);r=Math.max(r,w),t+=T+5,n=t-5,this.pixiTextContainer.addChild(x);const S=ye(this.opts.fill);return x.tint=S??16777215,x});const c=n,l=r,d=new Ae;d.label="containerBackground";const f=this.opts.background==="transparent",m=f?0:ye(this.opts.background),g=f?0:1,_=15;d.roundRect(0,0,c+_*2,l+_*2,10),d.fill({color:m,alpha:g}),this.wordTexts.forEach(p=>{this.extraPadding=0,p.pivot.y=0,p.pivot.x=0,p.y=_-this.extraPadding,p.x+=_}),this.pixiTextContainer.addChildAt(d,0),this.renderTexture&&this.renderTexture.destroy(!0),this.renderTexture=Ee.create({width:c+_*2,height:l+_*2}),this._meta.width=c+_*2,this._meta.height=l+_*2,this._meta.duration=1/0;const a=this.opts.videoWidth,h=this.opts.videoHeight,u=this.opts.bottomOffset;this.width=this.width===0?this._meta.width:this.width,this.height=this.height===0?this._meta.height:this.height,this.top=h-this.height-u,this.left=(a-this.width)/2}lastLoggedTime=-1;updateState(e){const t=e/1e3,r=Math.floor(e/1e6);r!==this.lastLoggedTime&&(this.lastLoggedTime=r),this.opts.words.forEach((n,o)=>{const c=t>=n.from&&t<=n.to,l=t>n.to,d=n.isKeyWord&&this.opts.keyword!=="transparent";let f;n.isKeyWord&&c&&d?f=ye(this.opts.keyword):c?f=ye(this.opts.active):l&&this.opts.preserveKeywordColor&&d?f=ye(this.opts.keyword):l?f=ye(this.opts.appeared):f=ye(this.opts.fill);const m=this.wordTexts[o];if(m){m.children.forEach(_=>{_.label!=="bgRect"&&(_.tint=f??16777215)});const g=m.getChildByLabel("bgRect");if(c)if(g){g.tint=16777215;const _=ye(this.opts.activeFill)||16753920;g.clear();const y=10,a=m.getLocalBounds();g.roundRect(a.x-y/2,a.y-y/2+this.extraPadding,a.width+y,a.height+y,16),g.fill(_)}else{const _=new Ae;_.label="bgRect";const y=10,a=m.getLocalBounds(),h=10,u=ye(this.opts.activeFill)||16753920;_.roundRect(a.x-y/2,a.y-y/2+this.extraPadding,a.width+y,a.height+y,h),_.fill(u),_.tint=16777215,m.addChildAt(_,0)}else g&&m.removeChild(g)}else console.log(`¡WARNING: SplitBitmapText was not found for word "${n.text}"!`)})}async getTexture(){if(this.pixiTextContainer==null||this.renderTexture==null)return console.log("[CaptionClip] getTexture returning null - container or texture not ready"),null;try{return(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture}catch(e){return console.error("[CaptionClip] Error in getTexture:",e),null}}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("CaptionClip: No renderer available. Provide a renderer via setRenderer().");return this.pixiApp.renderer}async tick(e){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("CaptionClip not initialized");this.updateState(e);const t=await this.getRenderer();t.render({container:this.pixiTextContainer,target:this.renderTexture});const r=this.renderTexture.source?.resource?.source;let n;if(r instanceof HTMLCanvasElement)n=await createImageBitmap(r);else if(r instanceof OffscreenCanvas)n=await createImageBitmap(r);else{const c=t.extract.canvas(this.renderTexture);if(c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas)n=await createImageBitmap(c);else throw new Error("Unable to extract canvas from render texture")}return{video:n,state:"success"}}async split(e){await this.ready;const t=await this.clone(),r=await this.clone();return[t,r]}addEffect(e){this.effects.push(e)}editEffect(e,t){const r=this.effects.find(n=>n.id===e);r&&Object.assign(r,t)}removeEffect(e){const t=this.effects.findIndex(r=>r.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.originalOpts||{},t=new Ft(this.text,e);return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){if(!this.destroyed){W.info("CaptionClip destroy");try{this.wordTexts.forEach(e=>{e!=null&&!e.destroyed&&e.destroy({children:!0})})}catch{}finally{this.wordTexts=[]}try{this.pixiTextContainer!=null&&this.pixiTextContainer.destroyed!==!0&&this.pixiTextContainer.destroy({children:!0})}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),r={};if(this.originalOpts){const g=this.originalOpts;g.fontSize!==void 0&&(r.fontSize=g.fontSize),g.fontFamily!==void 0&&(r.fontFamily=g.fontFamily),g.fontWeight!==void 0&&(r.fontWeight=g.fontWeight),g.fontStyle!==void 0&&(r.fontStyle=g.fontStyle),g.fill!==void 0&&(r.color=g.fill),g.align!==void 0&&(r.align=g.align),g.textCase!==void 0&&(r.textCase=g.textCase),g.fontUrl!==void 0&&(r.fontUrl=g.fontUrl),g.stroke&&(typeof g.stroke=="object"?r.stroke={color:g.stroke.color,width:g.stroke.width}:r.stroke={color:g.stroke,width:g.strokeWidth??0}),g.dropShadow&&(r.shadow={color:g.dropShadow.color??"#000000",alpha:g.dropShadow.alpha??.5,blur:g.dropShadow.blur??4,distance:g.dropShadow.distance??0,angle:g.dropShadow.angle??0})}const n={};this.opts.words&&this.opts.words.length>0&&(n.words=this.opts.words);const o={},c=this.originalOpts?.caption?.colors??this.originalOpts?.colors;c?.appeared!==void 0&&(o.appeared=c.appeared),c?.active!==void 0&&(o.active=c.active),c?.activeFill!==void 0&&(o.activeFill=c.activeFill),c?.background!==void 0&&(o.background=c.background),c?.keyword!==void 0&&(o.keyword=c.keyword);let l;this.originalOpts?.caption?.preserveKeywordColor!==void 0?l=this.originalOpts.caption.preserveKeywordColor:this.originalOpts?.preserveKeywordColor!==void 0&&(l=this.originalOpts.preserveKeywordColor),Object.keys(o).length>0&&(n.colors=o),l!==void 0&&(n.preserveKeywordColor=l);const d={};this.bottomOffset!==void 0&&(d.bottomOffset=this.bottomOffset);const f=this.originalOpts?.caption?.positioning?.videoWidth??this.originalOpts?.videoWidth,m=this.originalOpts?.caption?.positioning?.videoHeight??this.originalOpts?.videoHeight;return f!==void 0&&(d.videoWidth=f),m!==void 0&&(d.videoHeight=m),Object.keys(d).length>0&&(n.positioning=d),{...t,type:"Caption",text:this.text,style:r,caption:Object.keys(n).length>0?n:void 0,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Caption")throw new Error(`Expected Caption, got ${e.type}`);const t=e.text||"",r=e.style||{},n={};r.fontSize!==void 0&&(n.fontSize=r.fontSize),r.fontFamily!==void 0&&(n.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(n.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(n.fontStyle=r.fontStyle),r.color!==void 0&&(n.fill=r.color),r.align!==void 0&&(n.align=r.align),r.textCase!==void 0&&(n.textCase=r.textCase),r.fontUrl!==void 0?n.fontUrl=r.fontUrl:e.fontUrl!==void 0&&(n.fontUrl=e.fontUrl),r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow&&(n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:r.shadow.distance,angle:r.shadow.angle}),e.caption?n.caption=e.caption:(e.bottomOffset!==void 0&&(n.bottomOffset=e.bottomOffset),e.words!==void 0&&(n.words=e.words),(e.appearedColor!==void 0||e.activeColor!==void 0||e.activeFillColor!==void 0||e.backgroundColor!==void 0||e.isKeyWordColor!==void 0)&&(n.colors={},e.appearedColor!==void 0&&(n.colors.appeared=e.appearedColor),e.activeColor!==void 0&&(n.colors.active=e.activeColor),e.activeFillColor!==void 0&&(n.colors.activeFill=e.activeFillColor),e.backgroundColor!==void 0&&(n.colors.background=e.backgroundColor),e.isKeyWordColor!==void 0&&(n.colors.keyword=e.isKeyWordColor)),e.preservedColorKeyWord!==void 0&&(n.preserveKeywordColor=e.preservedColorKeyWord),e.videoWidth!==void 0&&(n.videoWidth=e.videoWidth),e.videoHeight!==void 0&&(n.videoHeight=e.videoHeight));const o=new Ft(t,n);return o.left=e.left,o.top=e.top,o.width=e.width,o.height=e.height,o.angle=e.angle,o.display.from=e.display.from,o.display.to=e.display.to,o.duration=e.duration,o.playbackRate=e.playbackRate,o.zIndex=e.zIndex,o.opacity=e.opacity,o.flip=e.flip,e.animation&&o.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(o.id=e.id),e.effects&&(o.effects=e.effects),await o.ready,o}}class ve extends kt{type="Image";ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t){const r=await Qi.load(e),n=r.source?.resource?.source;let o;try{if(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)o=await createImageBitmap(n);else if(n instanceof HTMLImageElement){const l=new OffscreenCanvas(n.width,n.height),d=l.getContext("2d");if(d==null)throw new Error("Failed to create 2d context");d.drawImage(n,0,0),o=await createImageBitmap(l)}else if(n instanceof ImageBitmap)o=await createImageBitmap(n);else{const l=await fetch(e);if(!l.ok)throw new Error(`Failed to fetch image: ${l.status} ${l.statusText}`);const d=await l.blob();o=await createImageBitmap(d)}}catch{const d=await fetch(e);if(!d.ok)throw new Error(`Failed to fetch image: ${d.status} ${d.statusText}`);const f=await d.blob();o=await createImageBitmap(f)}const c=new ve(o,t||e);return c.pixiTexture=r,c}getTexture(){return this.pixiTexture}constructor(e,t){super(),this.src=t!==void 0?t:"";const r=n=>{this.img=n,this._meta.width=n.width,this._meta.height=n.height,this._meta.duration=1/0;const o={...this._meta};return this.width=this.width===0?o.width:this.width,this.height=this.height===0?o.height:this.height,this.duration===0&&o.duration!==1/0&&(this.duration=o.duration,this.display.to=this.display.from+this.duration),o};if(e instanceof ReadableStream)this.ready=new Response(e).blob().then(n=>createImageBitmap(n)).then(r);else if(e instanceof ImageBitmap)this.ready=Promise.resolve(r(e));else if(Array.isArray(e)&&e.every(n=>n instanceof VideoFrame)){this.frames=e;const n=this.frames[0];if(n==null)throw Error("The frame count must be greater than 0");this._meta={width:n.displayWidth,height:n.displayHeight,duration:this.frames.reduce((c,l)=>c+(l.duration??0),0)};const o={...this._meta,duration:1/0};this.width=this.width===0?o.width:this.width,this.height=this.height===0?o.height:this.height,this.duration===0&&o.duration!==1/0&&(this.duration=o.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(o)}else if("type"in e)this.ready=this.initAnimateImg(e.stream,e.type).then(()=>{const n={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),n});else throw Error("Illegal arguments")}async initAnimateImg(e,t){this.frames=await Nf(e,t);const r=this.frames[0];if(r==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((n,o)=>n+(o.duration??0),0),width:r.codedWidth,height:r.codedHeight},W.info("ImageClip ready:",this._meta)}tickInterceptor=async(e,t)=>t;async tick(e){if(this.img!=null)return await this.tickInterceptor(e,{video:await createImageBitmap(this.img),state:"success"});const t=e%this._meta.duration;return await this.tickInterceptor(e,{video:(this.frames.find(r=>t>=r.timestamp&&t<=r.timestamp+(r.duration??0))??this.frames[0]).clone(),state:"success"})}async split(e){if(await this.ready,this.img!=null)return[new ve(await createImageBitmap(this.img),this.src),new ve(await createImageBitmap(this.img),this.src)];let t=-1;for(let o=0;o<this.frames.length;o++){const c=this.frames[o];if(!(e>c.timestamp)){t=o;break}}if(t===-1)throw Error("Not found frame by time");const r=this.frames.slice(0,t).map(o=>new VideoFrame(o)),n=this.frames.slice(t).map(o=>new VideoFrame(o,{timestamp:o.timestamp-e}));return[new ve(r,this.src),new ve(n,this.src)]}async clone(){await this.ready;const e=this.img==null?this.frames.map(r=>r.clone()):await createImageBitmap(this.img),t=new ve(e,this.src);return t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t.transition=this.transition,t}addEffect(e){this.effects.push(e)}editEffect(e,t){const r=this.effects.find(n=>n.id===e);r&&Object.assign(r,t)}removeEffect(e){const t=this.effects.findIndex(r=>r.id===e);t!==-1&&this.effects.splice(t,1)}destroy(){W.info("ImageClip destroy"),this.img?.close(),this.frames.forEach(e=>e.close()),this.pixiTexture=null,super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Image",id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Image")throw new Error(`Expected Image, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("ImageClip requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let t;try{const r=await fetch(e.src);if(!r.ok)throw new Error(`Failed to fetch image from ${e.src}: ${r.status} ${r.statusText}. Make sure the file exists in the public directory.`);const n=await r.blob();if(!n.type.startsWith("image/"))throw new Error(`Invalid image format: ${n.type}. Expected an image file.`);t=new ve(await createImageBitmap(n),e.src)}catch(r){throw r instanceof Error&&r.message.includes("could not be decoded")?new Error(`Failed to decode image from ${e.src}. The image may be corrupted, in an unsupported format, or there may be CORS issues.`):r}return await t.ready,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),e.effects&&(t.effects=e.effects),e.transition&&(t.transition=e.transition),t}async scaleToFit(e,t){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.min(e/r,t/n);this.width=r*o,this.height=n*o}async scaleToFill(e,t){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.max(e/r,t/n);this.width=r*o,this.height=n*o}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}}function To(s,e){const t=e.videoTracks[0],r={};if(t!=null){const o=dx(s.getTrackById(t.id))?.buffer,{descKey:c,type:l}=t.codec.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:t.codec.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:{descKey:"",type:""};c!==""&&(r.videoTrackConf={timescale:t.timescale,duration:t.duration,width:t.video.width,height:t.video.height,brands:e.brands,type:l,[c]:o}),r.videoDecoderConf={codec:t.codec,codedHeight:t.video.height,codedWidth:t.video.width,description:o}}const n=e.audioTracks[0];if(n!=null){const o=fx(s),c=o==null?{}:px(o);r.audioTrackConf={timescale:n.timescale,samplerate:c.sampleRate??n.audio.sample_rate,channel_count:c.numberOfChannels??n.audio.channel_count,hdlr:"soun",type:n.codec.startsWith("mp4a")?"mp4a":n.codec,description:o},r.audioDecoderConf={codec:c.codec??ae.codec,numberOfChannels:c.numberOfChannels??n.audio.channel_count,sampleRate:c.sampleRate??n.audio.sample_rate}}return r}function dx(s){for(const e of s.mdia.minf.stbl.stsd.entries){const t=e.avcC??e.hvcC??e.av1C??e.vpcC;if(t!=null){const r=new ke.DataStream(void 0,0,ke.DataStream.BIG_ENDIAN);return t.write(r),new Uint8Array(r.buffer.slice(8))}}}function fx(s,e="mp4a"){return s.moov?.traks.map(r=>r.mdia.minf.stbl.stsd.entries).flat().find(({type:r})=>r===e)?.esds}function px(s){let e="mp4a";const t=s.esd.descs[0];if(t==null)return{};e+="."+t.oti.toString(16);const r=t.descs[0];if(r==null)return e.endsWith("40")&&(e+=".2"),{codec:e};const n=(r.data[0]&248)>>3;e+="."+n;const[o,c]=r.data,l=((o&7)<<1)+(c>>7),d=(c&127)>>3;return{codec:e,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][l],numberOfChannels:d}}async function mx(s,e,t){const r=ke.createFile(!1);r.onReady=o=>{e({mp4boxFile:r,info:o});const c=o.videoTracks[0]?.id;c!=null&&r.setExtractionOptions(c,"video",{nbSamples:100});const l=o.audioTracks[0]?.id;l!=null&&r.setExtractionOptions(l,"audio",{nbSamples:100}),r.start()},r.onSamples=t,await n();async function n(){let o=0;const c=30*1024*1024;for(;;){const l=await s.read(c,{at:o});if(l.byteLength===0)break;l.fileStart=o;const d=r.appendBuffer(l);if(d==null)break;o=d}r.stop()}}function gx(s){if(s?.length!==9)return{};const e=new Int32Array(s.buffer),t=e[0]/65536,r=e[1]/65536,n=e[3]/65536,o=e[4]/65536,c=e[6]/65536,l=e[7]/65536,d=e[8]/(1<<30),f=Math.sqrt(t*t+n*n),m=Math.sqrt(r*r+o*o),g=Math.atan2(n,t),_=g*180/Math.PI;return{scaleX:f,scaleY:m,rotationRad:g,rotationDeg:_,translateX:c,translateY:l,perspective:d}}function vx(s,e,t){const r=(Math.round(t/90)*90+360)%360;if(r===0)return d=>d;const n=r===90||r===270?e:s,o=r===90||r===270?s:e,c=new OffscreenCanvas(n,o),l=c.getContext("2d");return l.translate(n/2,o/2),l.rotate(-r*Math.PI/180),l.translate(-s/2,-e/2),d=>{if(d==null)return null;l.drawImage(d,0,0);const f=new VideoFrame(c,{timestamp:d.timestamp,duration:d.duration??void 0});return d.close(),f}}let wo=0;function So(s){return s.kind==="file"&&s.createReader instanceof Function}class fe extends kt{type="Video";insId=wo++;logger=W.create(`VideoClip id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const e=await this.localFile.getOriginFile();if(e==null)throw Error("VideoClip localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:t,size:r})=>e.slice(t,t+r))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=e=>e;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t={}){const r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch video from ${e}: ${r.status} ${r.statusText}`);const n=new fe(r.body,{},e);return await n.ready,t.x!==void 0&&(n.left=t.x),t.y!==void 0&&(n.top=t.y),t.width!==void 0&&(n.width=t.width),t.height!==void 0&&(n.height=t.height),n}constructor(e,t={},r){if(super(),this.src=r!==void 0?r:"",!(e instanceof ReadableStream)&&!So(e)&&!Array.isArray(e.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...t},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof t.audio=="object"&&"volume"in t.audio?t.audio.volume:t.volume??1;const n=async o=>(await bi(this.localFile,o),this.localFile);this.localFile=So(e)?e:"localFile"in e?e.localFile:vs(),this.ready=(e instanceof ReadableStream?n(e).then(o=>qu(o,this.opts)):So(e)?qu(e,this.opts):Promise.resolve(e)).then(async({videoSamples:o,audioSamples:c,decoderConf:l,headerBoxPos:d,parsedMatrix:f})=>{this.videoSamples=o,this.audioSamples=c,this.decoderConf=l,this.headerBoxPos=d,this.parsedMatrix=f;const{videoFrameFinder:m,audioFrameFinder:g}=yx({video:l.video==null?null:{...l.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:l.audio},await this.localFile.createReader(),o,c,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=m,this.audioFrameFinder=g;const{codedWidth:_,codedHeight:y}=l.video??{};_&&y&&(this.vfRotater=vx(_,y,f.rotationDeg)),this._meta=_x(l,o,c,f.rotationDeg),this.logger.info("VideoClip meta:",this._meta);const a={...this._meta};this.width=this.width===0?a.width:this.width,this.height=this.height===0?a.height:this.height,this.trim.to=this.trim.to===0?a.duration:this.trim.to;const h=(this.trim.to-this.trim.from)/this.playbackRate;return this.duration=this.duration===0?h:this.duration,this.display.to=this.display.from+this.duration,this.on("propsChange",u=>{u.volume!==void 0&&this.audioFrameFinder&&this.audioFrameFinder.setVolume(u.volume)}),a})}tickInterceptor=async(e,t)=>t;async tick(e){const t=e+this.trim.from;if(t>=this.trim.to||t>=this._meta.duration)return await this.tickInterceptor(e,{audio:await this.audioFrameFinder?.find(t)??[],state:"done"});const[r,n]=await Promise.all([this.audioFrameFinder?.find(t)??[],this.videoFrameFinder?.find(t).then(this.vfRotater)]);return n==null?await this.tickInterceptor(e,{audio:r,state:"success"}):await this.tickInterceptor(e,{video:n,audio:r,state:"success"})}async split(e){if(await this.ready,e<=0||e>=this._meta.duration)throw Error("time out of bounds");const[t,r]=Ax(this.videoSamples,e),[n,o]=Ex(this.audioSamples,e),c=new fe({localFile:this.localFile,videoSamples:t??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),l=new fe({localFile:this.localFile,videoSamples:r??[],audioSamples:o??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await Promise.all([c.ready,l.ready]),[c,l]}addEffect(e){this.effects.push(e)}editEffect(e,t){const r=this.effects.find(n=>n.id===e);r&&Object.assign(r,t)}removeEffect(e){const t=this.effects.findIndex(r=>r.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=new fe({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await e.ready,e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e.id=this.id,e.effects=[...this.effects],e}async splitTrack(){await this.ready;const e=[];if(this.videoSamples.length>0){const t=new fe({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[],decoderConf:{video:this.decoderConf.video,audio:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}if(this.audioSamples.length>0){const t=new fe({localFile:this.localFile,videoSamples:[],audioSamples:[...this.audioSamples],decoderConf:{audio:this.decoderConf.audio,video:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}return e}destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("VideoClip destroy"),super.destroy(),this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(e=!1){return{...super.toJSON(e),type:"Video",audio:this.audio,volume:this.volume,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Video")throw new Error(`Expected Video, got ${e.type}`);const t=await fetch(e.src);if(!t.ok)throw new Error(`Failed to fetch video from ${e.src}: ${t.status} ${t.statusText}. Make sure the file exists in the public directory.`);const r=e.audio!==void 0?{audio:e.audio,volume:e.volume}:{volume:e.volume},n=new fe(t.body,r,e.src);return await n.ready,n.left=e.left,n.top=e.top,n.width=e.width,n.height=e.height,n.angle=e.angle,n.display.from=e.display.from,n.display.to=e.display.to,n.duration=e.duration,n.playbackRate=e.playbackRate,n.zIndex=e.zIndex,n.opacity=e.opacity,n.flip=e.flip,e.animation&&n.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(n.id=e.id),e.effects&&(n.effects=e.effects),e.transition&&(n.transition=e.transition),e.trim&&(n.trim.from=e.trim.from<1e6?e.trim.from*1e6:e.trim.from,n.trim.to=e.trim.to<1e6?e.trim.to*1e6:e.trim.to),e.volume!==void 0&&(n.volume=e.volume),n}async createPlaybackElement(){await this.ready;const t=this.localFile;if(!t||typeof t.getOriginFile!="function")throw new Error("VideoClip does not have a local file for playback");const r=await t.getOriginFile();if(!r)throw new Error("Failed to get origin file from VideoClip");const n=URL.createObjectURL(r),o=document.createElement("video");return o.crossOrigin="anonymous",o.muted=!0,o.autoplay=!1,o.playsInline=!0,o.preload="auto",o.loop=!1,o.src=n,await new Promise((c,l)=>{const d=()=>{o.removeEventListener("loadeddata",d),o.removeEventListener("error",f),o.pause(),o.currentTime=0,c()},f=()=>{o.removeEventListener("loadeddata",d),o.removeEventListener("error",f),l(new Error("Failed to load video"))};o.addEventListener("loadeddata",d,{once:!0}),o.addEventListener("error",f,{once:!0}),o.load()}),{element:o,objectUrl:n}}async play(e,t){const r=e,n=t+this.trim.from/1e6;if(Math.abs(r.currentTime-n)>.1&&(r.currentTime=n),r.muted=!1,r.paused)try{await r.play()}catch{try{await r.play()}catch(c){console.warn("Failed to play video:",c)}}}pause(e){const t=e;t.pause(),t.muted=!0}async seek(e,t){const r=e,n=t+this.trim.from/1e6;return r.pause(),r.currentTime=n,new Promise(o=>{if(Math.abs(r.currentTime-t)<.01){o();return}const c=()=>{r.removeEventListener("seeked",c),o()};r.addEventListener("seeked",c,{once:!0}),setTimeout(()=>{r.removeEventListener("seeked",c),o()},500)})}syncPlayback(e,t,r){const n=e,o=(this.trim.to-this.trim.from)/1e6,c=r>=0&&r<o,l=r+this.trim.from/1e6;n.volume=this.volume,t&&c?n.paused?this.play(n,r).catch(console.warn):(n.muted&&(n.muted=!1),(n.ended||n.currentTime>=this.trim.to/1e6)&&(n.currentTime=l,n.play().catch(console.warn))):(n.paused||n.pause(),n.muted=!0,c&&Math.abs(n.currentTime-l)>.1&&(n.currentTime=l))}cleanupPlayback(e,t){const r=e;r.pause(),r.removeAttribute("src"),r.load(),t&&URL.revokeObjectURL(t)}async scaleToFit(e,t){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.min(e/r,t/n);this.width=r*o,this.height=n*o}async scaleToFill(e,t){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.max(e/r,t/n);this.width=r*o,this.height=n*o}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}}function _x(s,e,t,r){const n={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(s.video!=null&&e.length>0){n.width=s.video.codedWidth??0,n.height=s.video.codedHeight??0;const l=(Math.round(r/90)*90+360)%360;(l===90||l===270)&&([n.width,n.height]=[n.height,n.width])}s.audio!=null&&t.length>0&&(n.audioSampleRate=ae.sampleRate,n.audioChanCount=ae.channelCount);let o=0,c=0;if(e.length>0)for(let l=e.length-1;l>=0;l--){const d=e[l];if(!d.deleted){o=d.cts+d.duration;break}}if(t.length>0){const l=t.at(-1);c=l.cts+l.duration}return n.duration=Math.max(o,c),n}function yx(s,e,t,r,n){return{audioFrameFinder:n===0||s.audio==null||r.length===0?null:new Tx(e,r,s.audio,{volume:n,targetSampleRate:ae.sampleRate}),videoFrameFinder:s.video==null||t.length===0?null:new xx(e,t,s.video)}}async function qu(s,e={}){let t=null;const r={video:null,audio:null};let n=[],o=[],c=[];const l={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let d=-1,f=-1;const m=await s.createReader();await mx(m,async _=>{t=_.info;const y=_.mp4boxFile.ftyp;c.push({start:y.start,size:y.size});const a=_.mp4boxFile.moov;c.push({start:a.start,size:a.size}),Object.assign(l,gx(t.videoTracks[0]?.matrix));let{videoDecoderConf:h,audioDecoderConf:u}=To(_.mp4boxFile,_.info);if(r.video=h??null,r.audio=u??null,h==null&&u==null&&W.error("VideoClip no video and audio track"),u!=null){const{supported:p}=await AudioDecoder.isConfigSupported(u);p||W.error(`VideoClip audio codec is not supported: ${u.codec}`)}if(h!=null){const{supported:p}=await VideoDecoder.isConfigSupported(h);p||W.error(`VideoClip video codec is not supported: ${h.codec}`)}W.info("mp4BoxFile moov ready",{..._.info,tracks:null,videoTracks:null,audioTracks:null},r)},(_,y,a)=>{if(y==="video"){d===-1&&(d=a[0].dts);for(const h of a)n.push(Ku(h,d,"video"))}else if(y==="audio"&&e.audio){f===-1&&(f=a[0].dts);for(const h of a)o.push(Ku(h,f,"audio"))}}),await m.close();const g=n.at(-1)??o.at(-1);if(t==null)throw Error("VideoClip stream is done, but not emit ready");if(g==null)throw Error("VideoClip stream not contain any sample");return Co(n),W.info("mp4 stream parsed"),{videoSamples:n,audioSamples:o,decoderConf:r,headerBoxPos:c,parsedMatrix:l}}function Ku(s,e=0,t){let r=s.offset;const n=t==="video"&&s.is_sync?Px(s.data,s.description.type):-1;let o=s.size;return n>0&&(r+=n,o-=n),{...s,is_idr:n>=0,offset:r,size:o,cts:(s.cts-e)/s.timescale*1e6,dts:(s.dts-e)/s.timescale*1e6,duration:s.duration/s.timescale*1e6,timescale:1e6,data:t==="video"?null:s.data}}class xx{constructor(e,t,r){this.localFileReader=e,this.samples=t,this.conf=r}decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async e=>{(this.decoder==null||this.decoder.state==="closed"||e<=this.timestamp||e-this.timestamp>3e6)&&this.reset(e),this.curAborter.abort=!0,this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const t=await this.parseFrame(e,this.decoder,this.curAborter);return this.sleepCnt=0,t};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;parseFrame=async(e,t,r)=>{if(t==null||t.state==="closed"||r.abort)return null;if(this.videoFrames.length>0){const n=this.videoFrames[0];return e<n.timestamp?null:(this.videoFrames.shift(),e>n.timestamp+(n.duration??0)?(n.close(),await this.parseFrame(e,t,r)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(t).catch(o=>{throw this.predecodeErr=!0,this.reset(e),o}),n))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&t.decodeQueueSize>0){if(performance.now()-r.st>6e3)throw Error(`VideoClip.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await ws(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(t)}catch(n){throw this.reset(e),n}}return await this.parseFrame(e,t,r)};decoding=!1;startDecode=async e=>{if(this.decoding||e.decodeQueueSize>600)return;let t=this.videoDecCursorIdx+1;if(t>this.samples.length)return;this.decoding=!0;let r=!1;for(;t<this.samples.length;t++){const n=this.samples[t];if(!r&&!n.deleted&&(r=!0),n.is_idr)break}if(r){const n=this.samples.slice(this.videoDecCursorIdx,t);if(n[0]?.is_idr!==!0)W.warn("First sample not idr frame");else{const o=performance.now(),c=await Cx(n,this.localFileReader),l=performance.now()-o;if(l>1e3){const d=n[0],f=n.at(-1),m=f.offset+f.size-d.offset;W.warn(`Read video samples time cost: ${Math.round(l)}ms, file chunk size: ${m}`)}if(e.state==="closed")return;this.lastVfDur=c[0]?.duration??0,Ix(e,c,{onDecodingError:d=>{if(this.downgradeSoftDecode)throw d;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,W.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=c.length}}this.videoDecCursorIdx=t,this.decoding=!1};reset=e=>{if(this.decoding=!1,this.videoFrames.forEach(r=>r.close()),this.videoFrames=[],e==null||e===0)this.videoDecCursorIdx=0;else{let r=0;for(let n=0;n<this.samples.length;n++){const o=this.samples[n];if(o.is_idr&&(r=n),!(o.cts<e)){this.videoDecCursorIdx=r;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const t={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:r=>{if(this.outputFrameCnt+=1,r.timestamp===-1){r.close();return}let n=r;r.duration==null&&(n=new VideoFrame(r,{duration:this.lastVfDur}),r.close()),this.videoFrames.push(n)},error:r=>{if(r.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,W.warn(r.message);return}const n=`VideoFinder VideoDecoder err: ${r.message}, config: ${JSON.stringify(t)}, state: ${JSON.stringify(this.getState())}`;throw W.error(n),Error(n)}}),this.decoder.configure(t)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:wo,sleepCnt:this.sleepCnt,memInfo:Zu()});destroy=()=>{this.decoder?.state!=="closed"&&this.decoder?.close(),this.decoder=null,this.curAborter.abort=!0,this.videoFrames.forEach(e=>e.close()),this.videoFrames=[],this.localFileReader.close()}}function bx(s,e){for(let t=0;t<e.length;t++){const r=e[t];if(s>=r.cts&&s<r.cts+r.duration)return t;if(r.cts>s)break}return 0}class Tx{constructor(e,t,r,n){this.localFileReader=e,this.samples=t,this.conf=r,this.volume=n.volume,this.sampleRate=n.targetSampleRate}volume=1;sampleRate;setVolume(e){this.volume=e,this.reset()}decoder=null;curAborter={abort:!1,st:performance.now()};find=async e=>{const t=e<=this.timestamp||e-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||t)&&this.reset(),t&&(this.timestamp=e,this.decCursorIdx=bx(e,this.samples)),this.curAborter.abort=!0;const r=e-this.timestamp;this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const n=await this.parseFrame(Math.ceil(r*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,n};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(e,t=null,r)=>{if(t==null||r.abort||t.state==="closed"||e===0)return[];const n=this.pcmData.frameCnt-e;if(n>0)return n<ae.sampleRate/10&&this.startDecode(t),ju(this.pcmData,e);if(t.decoding){if(performance.now()-r.st>3e3)throw r.abort=!0,Error(`VideoClip.tick audio timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await ws(15)}else{if(this.decCursorIdx>=this.samples.length-1)return ju(this.pcmData,this.pcmData.frameCnt);this.startDecode(t)}return this.parseFrame(e,t,r)};startDecode=e=>{if(e.decodeQueueSize>10)return;const r=[];let n=this.decCursorIdx;for(;n<this.samples.length;){const o=this.samples[n];if(n+=1,!o.deleted&&(r.push(o),r.length>=10))break}this.decCursorIdx=n,e.decode(r.map(o=>new EncodedAudioChunk({type:"key",timestamp:o.cts,duration:o.duration,data:o.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=wx(this.conf,{resampleRate:ae.sampleRate,volume:this.volume},e=>{this.pcmData.data.push(e),this.pcmData.frameCnt+=e[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:wo,sleepCnt:this.sleepCnt,memInfo:Zu()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function wx(s,e,t){let r=0,n=0;const o=m=>{if(n+=1,m.length!==0){if(e.volume!==1)for(const g of m)for(let _=0;_<g.length;_++)g[_]*=e.volume;m.length===1&&(m=[m[0],m[0]]),t(m)}},c=Sx(o),l=e.resampleRate!==s.sampleRate;let d=new AudioDecoder({output:m=>{const g=ia(m);l?c(()=>xf(g,m.sampleRate,{rate:e.resampleRate,chanCount:m.numberOfChannels})):o(g),m.close()},error:m=>{m.message.includes("Codec reclaimed due to inactivity")||f("VideoClip AudioDecoder err",m)}});d.configure(s);function f(m,g){const _=`${m}: ${g.message}, state: ${JSON.stringify({qSize:d.decodeQueueSize,state:d.state,inputCnt:r,outputCnt:n})}`;throw W.error(_),Error(_)}return{decode(m){r+=m.length;try{for(const g of m)d.decode(g)}catch(g){f("decode audio chunk error",g)}},close(){d.state!=="closed"&&d.close()},get decoding(){return r>n&&d.decodeQueueSize>0},get state(){return d.state},get decodeQueueSize(){return d.decodeQueueSize}}}function Sx(s){const e=[];let t=0;function r(c,l){e[l]=c,n()}function n(){const c=e[t];c!=null&&(s(c),t+=1,n())}let o=0;return c=>{const l=o;o+=1,c().then(d=>r(d,l)).catch(d=>r(d,l))}}function ju(s,e){const t=[new Float32Array(e),new Float32Array(e)];let r=0,n=0;for(;n<s.data.length;){const[o,c]=s.data[n];if(r+o.length>e){const l=e-r;t[0].set(o.subarray(0,l),r),t[1].set(c.subarray(0,l),r),s.data[n][0]=o.subarray(l,o.length),s.data[n][1]=c.subarray(l,c.length);break}else t[0].set(o,r),t[1].set(c,r),r+=o.length,n++}return s.data=s.data.slice(n),s.frameCnt-=e,t}async function Cx(s,e){const t=s[0],r=s.at(-1);if(r==null)return[];const n=r.offset+r.size-t.offset;if(n<3e7){const o=new Uint8Array(await e.read(n,{at:t.offset}));return s.map(c=>{const l=c.offset-t.offset;return new EncodedVideoChunk({type:c.is_sync?"key":"delta",timestamp:c.cts,duration:c.duration,data:o.subarray(l,l+c.size)})})}return await Promise.all(s.map(async o=>new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:await e.read(o.size,{at:o.offset})})))}function Ax(s,e){if(s.length===0)return[];let t=0,r=0,n=-1;for(let d=0;d<s.length;d++){const f=s[d];if(n===-1&&e<f.cts&&(n=d-1),f.is_idr)if(n===-1)t=d;else{r=d;break}}const o=s[n];if(o==null)throw Error("Not found video sample by time");const c=s.slice(0,r===0?s.length:r).map(d=>({...d}));for(let d=t;d<c.length;d++){const f=c[d];e<f.cts&&(f.deleted=!0,f.cts=-1)}Co(c);const l=s.slice(o.is_idr?n:t).map(d=>({...d,cts:d.cts-e}));for(const d of l)d.cts<0&&(d.deleted=!0,d.cts=-1);return Co(l),[c,l]}function Ex(s,e){if(s.length===0)return[];let t=-1;for(let o=0;o<s.length;o++){const c=s[o];if(!(e>c.cts)){t=o;break}}if(t===-1)throw Error("Not found audio sample by time");const r=s.slice(0,t).map(o=>({...o})),n=s.slice(t).map(o=>({...o,cts:o.cts-e}));return[r,n]}function Ix(s,e,t){if(s.state==="configured"){for(let r=0;r<e.length;r++)s.decode(e[r]);s.flush().catch(r=>{if(!(r instanceof Error))throw r;if(r.message.includes("Decoding error")&&t.onDecodingError!=null){t.onDecodingError(r);return}if(!r.message.includes("Aborted due to close"))throw r})}}function Px(s,e){if(e!=="avc1"&&e!=="hvc1")return 0;const t=new DataView(s.buffer);for(let r=0;r<s.byteLength-4;){if(e==="avc1"){const n=t.getUint8(r+4)&31;if(n===5||n===7||n===8)return r}else if(e==="hvc1"){const n=t.getUint8(r+4)>>1&63;if(n===19||n===20||n===32||n===33||n===34)return r}r+=t.getUint32(r)+4}return-1}function Co(s){let e=0,t=null;for(const r of s)if(!r.deleted){if(r.is_sync&&(e+=1),e>=2)break;(t==null||r.cts<t.cts)&&(t=r)}t!=null&&t.cts<2e5&&(t.duration+=t.cts,t.cts=0)}function Zu(){try{const s=performance.memory;return{jsHeapSizeLimit:s.jsHeapSizeLimit,totalJSHeapSize:s.totalJSHeapSize,usedJSHeapSize:s.usedJSHeapSize,percentUsed:(s.usedJSHeapSize/s.jsHeapSizeLimit).toFixed(3),percentTotal:(s.totalJSHeapSize/s.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}function nr(s){if(s!=null){if(typeof s=="number")return s;if(typeof s=="string"){if(s.startsWith("#")){const t=parseInt(s.slice(1),16);if(!isNaN(t))return t}if(s.startsWith("0x")){const t=parseInt(s,16);if(!isNaN(t))return t}const e=parseInt(s,16);if(!isNaN(e))return e;try{return new se(s).toNumber()}catch{return}}}}class Ze extends kt{type="Text";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}get width(){return this._width}set width(e){this.width!==e&&(this._width=e,this.refreshText(),this.emit("propsChange",{width:e}))}get height(){return this._height}set height(e){this.height!==e&&(this._height=e,this.refreshText(),this.emit("propsChange",{height:e}))}_text="";get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this.originalOpts&&this.textStyle&&this.refreshText())}get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,fill:this.originalOpts.fill,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,dropShadow:this.originalOpts.dropShadow?{color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing,textCase:this.originalOpts.textCase,textDecoration:this.originalOpts.textDecoration}}set style(e){this.updateStyle(e)}get textAlign(){return this.originalOpts.align||this.originalOpts.textAlign||"left"}set textAlign(e){this.updateStyle({align:e})}get verticalAlign(){return this.originalOpts.verticalAlign||this.originalOpts.textDecoration||"top"}set verticalAlign(e){["underline","overline","strikethrough","line-through"].includes(e)?(this.updateStyle({textDecoration:e==="strikethrough"?"line-through":e}),this.originalOpts.verticalAlign=e):this.updateStyle({verticalAlign:e})}get textCase(){return this.originalOpts.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}pixiText=null;textStyle;renderTexture=null;externalRenderer=null;pixiApp=null;originalOpts;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];constructor(e,t={},r){super(),this.originalOpts={...t},this.text=e,this.externalRenderer=r??null,console.log("[TextClip] Constructor:",{opts:t});const n=this.createStyleFromOpts(t),o=new Be(n);this.textStyle=o,this.ready=(async()=>{await this.refreshText();const c={...this._meta};return W.info("TextClip ready:",c),c})()}setRenderer(e){this.externalRenderer=e,console.log("SET RENDERER",e)}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("TextClip: Failed to create renderer. Please provide a renderer via constructor or setRenderer() method.");return this.pixiApp.renderer}async getTexture(){return this.pixiText==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture}),this.renderTexture)}async tick(e){if(await this.ready,this.pixiText==null||this.renderTexture==null)throw new Error("TextClip not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);(await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture});const r=this.renderTexture.source?.resource?.source;let n;if(r instanceof HTMLCanvasElement)n=await createImageBitmap(r);else if(r instanceof OffscreenCanvas)n=await createImageBitmap(r);else{const l=(await this.getRenderer()).extract.canvas(this.renderTexture);if(l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas)n=await createImageBitmap(l);else{const d=this.renderTexture.width,f=this.renderTexture.height;throw new OffscreenCanvas(d,f).getContext("2d")==null?new Error("Failed to create 2d context for fallback rendering"):new Error("Unable to extract canvas from render texture")}}return{video:n,state:"success"}}async split(e){await this.ready;const t=await this.clone(),r=await this.clone();return[t,r]}addEffect(e){this.effects.push(e)}editEffect(e,t){const r=this.effects.find(n=>n.id===e);r&&Object.assign(r,t)}removeEffect(e){const t=this.effects.findIndex(r=>r.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.textStyle,t=this.originalOpts||{},r=c=>{if(c!=null){if(typeof c=="number")return c;if(c instanceof se)return c.toNumber()}},n={fontSize:t.fontSize??e.fontSize,fontFamily:t.fontFamily??(Array.isArray(e.fontFamily)?e.fontFamily[0]:typeof e.fontFamily=="string"?e.fontFamily:"Roboto"),fontWeight:t.fontWeight??e.fontWeight,fontStyle:t.fontStyle??e.fontStyle,align:t.align??(e.align==="justify"?"left":e.align),textCase:t.textCase,textDecoration:t.textDecoration};if(t.fill&&typeof t.fill=="object"&&"type"in t.fill&&t.fill.type==="gradient")n.fill=t.fill;else{const c=r(e.fill);n.fill=c??16777215}if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke)n.stroke=t.stroke;else{const c=r(e.stroke);c!==void 0&&(n.stroke=c),n.strokeWidth=t.strokeWidth??e.strokeThickness??0}if(t.dropShadow)n.dropShadow=t.dropShadow;else if(e.dropShadow){const c=e.dropShadow,l=r(c.color);l!==void 0&&(n.dropShadow={color:l,alpha:c.alpha,blur:c.blur,angle:c.angle,distance:c.distance})}if(t.wordWrap!==void 0?(n.wordWrap=t.wordWrap,n.wordWrapWidth=t.wordWrapWidth):e.wordWrap&&(n.wordWrap=e.wordWrap,n.wordWrapWidth=e.wordWrapWidth),t.lineHeight!==void 0)n.lineHeight=t.lineHeight;else if(e.lineHeight!==void 0){const c=n.fontSize??e.fontSize??40;n.lineHeight=e.lineHeight/c}t.letterSpacing!==void 0?n.letterSpacing=t.letterSpacing:e.letterSpacing!==void 0&&(n.letterSpacing=e.letterSpacing);const o=new Ze(this.text,n);return await o.ready,this.copyStateTo(o),o.id=this.id,o.effects=[...this.effects],o}async updateStyle(e){this.originalOpts={...this.originalOpts,...e};const t=this.createStyleFromOpts(this.originalOpts),r=new Be(t);this.textStyle=r,await this.refreshText()}async refreshText(){const e=this.textStyle;let t=this.text;const r=this.originalOpts.textCase;r==="uppercase"?t=t.toUpperCase():r==="lowercase"?t=t.toLowerCase():r==="title"&&(t=t.replace(/\w\S*/g,y=>y.charAt(0).toUpperCase()+y.substring(1).toLowerCase())),this.pixiText?(this.pixiText.text=t,this.pixiText.style=e,this.pixiText.children.forEach(y=>{y instanceof Ae&&y.destroy()}),this.pixiText.removeChildren()):this.pixiText=new Lv({text:t,style:e});const n=this.originalOpts.textDecoration||this.originalOpts.verticalAlign;if(n&&n!=="none"&&["underline","overline","strikethrough","line-through"].includes(n)){const y=n==="strikethrough"?"line-through":n,a=He.measureText(t,e),h=e.fontSize??40,u=Math.max(1,h/12);let p=16777215;typeof e.fill=="number"?p=e.fill:e.fill&&typeof e.fill=="object"&&"fill"in e.fill&&(p=16777215);const v=new Ae,x=e.lineHeight??a.lineHeight;for(let b=0;b<a.lines.length;b++){const T=a.lineWidths[b];let w=0;e.align==="center"?w=(a.maxLineWidth-T)/2:e.align==="right"&&(w=a.maxLineWidth-T);const S=b*x;let E=0;y==="underline"?E=x:y==="line-through"?E=x/2:y==="overline"&&(E=0);const A=S+E;v.rect(w,A,T,u),v.fill(p)}this.pixiText.addChild(v)}const o=this.pixiText.getLocalBounds(),c=Math.ceil(o.width||this.pixiText.width||1),l=Math.ceil(o.height||this.pixiText.height||1);let d=Math.max(1,c);e.wordWrap&&e.wordWrapWidth>0&&(d=Math.max(d,e.wordWrapWidth));const f=Math.max(d,this.width||0),m=Math.max(l,this.height||0),g=this.textAlign;g==="center"?this.pixiText.x=(f-c)/2:g==="right"?this.pixiText.x=f-c:this.pixiText.x=0;const _=this.originalOpts.verticalAlign||"top";_==="center"?this.pixiText.y=(m-l)/2:_==="bottom"?this.pixiText.y=m-l:this.pixiText.y=0,this.renderTexture&&this.renderTexture.destroy(!0),this.renderTexture=Ee.create({width:f,height:m}),this._meta.width=f,this._meta.height=m,this._width=f,this._height=m,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration)}createStyleFromOpts(e){const t=e.fontSize??40,r=e.lineHeight??1,n={fontSize:t,fontFamily:e.fontFamily??"Roboto",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",align:e.align??"left",wordWrap:e.wordWrap??!1,wordWrapWidth:e.wordWrapWidth??100,lineHeight:t*r,letterSpacing:e.letterSpacing??0};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const o=new Ke(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:c,color:l})=>{const d=typeof l=="number"?l:nr(l)??16777215;o.addColorStop(c,d)}),n.fill={fill:o}}else{const o=typeof e.fill=="string"||typeof e.fill=="number"?nr(e.fill):void 0;n.fill=o??16777215}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const o=nr(e.stroke.color);o!==void 0&&(n.stroke={color:o,width:e.stroke.width},e.stroke.join&&(n.stroke.join=e.stroke.join),e.stroke.cap&&(n.stroke.cap=e.stroke.cap),e.stroke.miterLimit&&(n.stroke.miterLimit=e.stroke.miterLimit))}else{const o=nr(e.stroke),c=e.strokeWidth??0;o!==void 0&&c>0?n.stroke={color:o,width:c}:e.strokeWidth&&e.strokeWidth>0&&(n.stroke={color:0,width:e.strokeWidth})}if(e.dropShadow){const o=nr(e.dropShadow.color);o!==void 0&&(n.dropShadow={color:o,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}return n}destroy(){if(!this.destroyed){W.info("TextClip destroy");try{this.pixiText!=null&&this.pixiText.destroyed!==!0&&this.pixiText.destroy({children:!0})}catch{}finally{this.pixiText=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),r={};return this.originalOpts.fontSize!==void 0&&(r.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(r.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontWeight!==void 0&&(r.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(r.fontStyle=this.originalOpts.fontStyle),this.originalOpts.fill!==void 0&&(r.color=this.originalOpts.fill),this.originalOpts.align!==void 0&&(r.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(r.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(r.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(r.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(r.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?r.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}:r.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.dropShadow&&(r.shadow={color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}),{...t,type:"Text",text:this.text,style:r,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Text")throw new Error(`Expected Text, got ${e.type}`);const t=e.text||"",r=e.style||{},n={};r.fontSize!==void 0&&(n.fontSize=r.fontSize),r.fontFamily!==void 0&&(n.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(n.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(n.fontStyle=r.fontStyle),r.color!==void 0&&(n.fill=r.color),r.align!==void 0&&(n.align=r.align),r.wordWrap!==void 0&&(n.wordWrap=r.wordWrap),r.wordWrapWidth!==void 0&&(n.wordWrapWidth=r.wordWrapWidth),r.lineHeight!==void 0&&(n.lineHeight=r.lineHeight),r.letterSpacing!==void 0&&(n.letterSpacing=r.letterSpacing),r.stroke&&(r.stroke.join||r.stroke.cap||r.stroke.miterLimit!==void 0?n.stroke={color:r.stroke.color,width:r.stroke.width,join:r.stroke.join,cap:r.stroke.cap,miterLimit:r.stroke.miterLimit}:(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width)),r.shadow&&(n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:r.shadow.distance,angle:r.shadow.angle});const o=new Ze(t,n);return o.left=e.left,o.top=e.top,o.width=e.width,o.height=e.height,o.angle=e.angle,o.display.from=e.display.from,o.display.to=e.display.to,o.duration=e.duration,o.playbackRate=e.playbackRate,o.zIndex=e.zIndex,o.opacity=e.opacity,o.flip=e.flip,e.animation&&o.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(o.id=e.id),e.effects&&(o.effects=e.effects),await o.ready,o}}class Je extends kt{type="Effect";ready;_meta={duration:5e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effect;constructor(e){super(),this.effect={id:`eff_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Je(this.effect.key);return this.copyStateTo(e),e.id=this.id,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),r=await this.clone();return[t,r]}toJSON(e=!1){return{...super.toJSON(e),type:"Effect",effect:this.effect,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Effect")throw new Error(`Expected Effect, got ${e.type}`);const t=new Je(e.effect.key);return t.effect=e.effect,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}class fi extends kt{type="Transition";ready;_meta={duration:2e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;transitionEffect;fromClipId=null;toClipId=null;constructor(e){super(),this.transitionEffect={id:`trans_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new fi(this.transitionEffect.key);return this.copyStateTo(e),e.fromClipId=this.fromClipId,e.toClipId=this.toClipId,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),r=await this.clone();return[t,r]}toJSON(e=!1){return{...super.toJSON(e),type:"Transition",transitionEffect:this.transitionEffect,fromClipId:this.fromClipId,toClipId:this.toClipId,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Transition")throw new Error(`Expected Transition, got ${e.type}`);const t=new fi(e.transitionEffect.key);return t.transitionEffect=e.transitionEffect,t.fromClipId=e.fromClipId||null,t.toClipId=e.toClipId||null,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}class Ju{readable;writable;inputBufOffset=0;constructor(){const e=ke.createFile();let t=!1;this.readable=new ReadableStream({start:r=>{e.onReady=o=>{const c=o.videoTracks[0]?.id;c!=null&&e.setExtractionOptions(c,"video",{nbSamples:100});const l=o.audioTracks[0]?.id;l!=null&&e.setExtractionOptions(l,"audio",{nbSamples:100}),r.enqueue({chunkType:"ready",data:{info:o,file:e}}),e.start()};const n={};e.onSamples=(o,c,l)=>{r.enqueue({chunkType:"samples",data:{id:o,type:c,samples:l.map(d=>({...d}))}}),n[o]=(n[o]??0)+l.length,e.releaseUsedSamples(o,n[o])},e.onFlush=()=>{r.close()}},cancel:()=>{e.stop(),t=!0}},{highWaterMark:50}),this.writable=new WritableStream({write:async r=>{if(t){this.writable.abort();return}const n=r.buffer;n.fileStart=this.inputBufOffset,this.inputBufOffset+=n.byteLength,e.appendBuffer(n)},close:()=>{e.flush(),e.stop(),e.onFlush?.()}})}}function Rx(s){let e=0;const t=s.boxes,r=[];let n=0;async function o(){const a=y(t,e);e=t.length,r.forEach(({track:h,id:u})=>{const p=h.samples.at(-1);p!=null&&(n=Math.max(n,p.cts+p.duration)),s.releaseUsedSamples(u,h.samples.length),h.samples=[]}),s.mdats=[],s.moofs=[],a!=null&&await m?.write(a)}let c=[];function l(){if(c.length>0)return!0;const a=t.findIndex(h=>h.type==="moov");if(a===-1)return!1;if(c=t.slice(0,a+1),e=a+1,r.length===0)for(let h=1;;h+=1){const u=s.getTrackById(h);if(u==null)break;r.push({track:u,id:h})}return!0}let d=0;const f=vs();let m=null;const g=(async()=>{m=await f.createWriter(),d=self.setInterval(()=>{l()&&o()},100)})();let _=!1;return async()=>{if(_)throw Error("File exported");if(_=!0,await g,clearInterval(d),!l()||m==null)return null;s.flush(),await o(),await m?.close();const a=c.find(p=>p.type==="moov");if(a==null)return null;a.mvhd.duration=n;const h=vs(),u=y(c,0);return await bi(h,u.slice()),await bi(h,f,{overwrite:!1}),await h.stream()};function y(a,h){if(h>=a.length)return null;const u=new ke.DataStream;u.endianness=ke.DataStream.BIG_ENDIAN;for(let p=h;p<a.length;p++)a[p]!==null&&(a[p].write(u),delete a[p]);return new Uint8Array(u.buffer).slice()}}function Mx(s){const e=new ArrayBuffer(s.byteLength);s.copyTo(e);const t=s.timestamp;return{duration:s.duration??0,dts:t,cts:t,is_sync:s.type==="key",data:e}}async function Qu(s){const e=ke.createFile(),t=Rx(e);await Fx(s,e);const r=await t();if(r==null)throw Error("Can not generate file from streams");return r}async function Fx(s,e){let t=0,r=0,n=0,o=0,c=0,l=0,d=null,f=null;for(const m of s){let g=null,_=null,y=null,a=null;if(await new Promise(async h=>{Zo(m.pipeThrough(new Ju),{onDone:h,onChunk:async({chunkType:u,data:p})=>{if(u==="ready"){const{videoTrackConf:v,audioTrackConf:x}=To(p.file,p.info);t===0&&v!=null&&(t=e.addTrack(v)),o===0&&x!=null&&(o=e.addTrack(x))}else if(u==="samples"){const{type:v,samples:x}=p,b=v==="video"?t:o,T=v==="video"?r:c,w=v==="video"?n:l;x.forEach(E=>{let A,P;v==="video"?(g===null&&(g=E.dts,_=E.cts),A=E.dts-g,P=E.cts-(_??0)):(y===null&&(y=E.dts,a=E.cts),A=E.dts-y,P=E.cts-(a??0)),e.addSample(b,E.data,{duration:E.duration,dts:A+T,cts:P+w,is_sync:E.is_sync})});const S=x.at(-1);if(S==null)return;v==="video"?d=S:v==="audio"&&(f=S)}}})}),d!=null&&g!==null&&_!==null){const h=d.dts-g+d.duration,u=d.cts-_+d.duration;r+=h,n+=u}if(f!=null&&d!=null){const h=f.timescale/d.timescale;c=Math.round(r*h),l=Math.round(n*h)}}}async function Ux(s){return await Qu([s])}function kx(s){let e=[];const t=new AudioDecoder({output:r=>{e.push(r)},error:W.error});return t.configure(s),{decode:async r=>{r.forEach(o=>{t.decode(new EncodedAudioChunk({type:o.is_sync?"key":"delta",timestamp:1e6*o.cts/o.timescale,duration:1e6*o.duration/o.timescale,data:o.data}))}),await t.flush();const n=e;return e=[],n},close:()=>{t.close()}}}function Bx(s,e){const t={codec:s.codec,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels},r=new AudioEncoder({output:c=>{e(Mx(c))},error:c=>{W.error("AudioEncoder error:",c,", config:",t)}});r.configure(t);let n=null;function o(c,l){return new AudioData({timestamp:l,numberOfChannels:s.numberOfChannels,numberOfFrames:c.length/s.numberOfChannels,sampleRate:s.sampleRate,format:"f32-planar",data:new Float32Array(c)})}return{encode:async(c,l)=>{n!=null&&r.encode(o(n.data,n.ts)),n={data:c,ts:l}},stop:async()=>{n!=null&&(Dx(n.data,s.numberOfChannels,s.sampleRate),r.encode(o(n.data,n.ts)),n=null),await r.flush(),r.close()}}}function Dx(s,e,t){const r=s.length-1,n=Math.min(t/2,r);for(let o=0;o<n;o++)for(let c=1;c<=e;c++)s[Math.floor(r/c)-o]*=o/n}function Ox(s,e){W.info("mixinMP4AndAudio, opts:",{volume:e.volume,loop:e.loop});const t=ke.createFile(),{stream:r,stop:n}=Jo(t,500);let o=null,c=null,l=[],d=0,f=0,m=0,g=!0,_=ae.sampleRate;Zo(s.pipeThrough(new Ju),{onDone:async()=>{await c?.stop(),o?.close(),n()},onChunk:async({chunkType:u,data:p})=>{if(u==="ready"){const{videoTrackConf:v,audioTrackConf:x,audioDecoderConf:b}=To(p.file,p.info);d===0&&v!=null&&(d=t.addTrack(v));const T=x??{timescale:1e6,samplerate:_,channel_count:ae.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};f===0&&(f=t.addTrack(T),_=x?.samplerate??_,g=x!=null);const w=new AudioContext({sampleRate:_});l=bs(await w.decodeAudioData(await new Response(e.stream).arrayBuffer())),b!=null&&(o=kx(b)),c=Bx(b??{codec:T.type==="mp4a"?ae.codec:T.type,numberOfChannels:T.channel_count,sampleRate:T.samplerate},S=>t.addSample(f,S.data,S))}else if(u==="samples"){const{id:v,type:x,samples:b}=p;if(x==="video"){b.forEach(T=>t.addSample(v,T.data,T)),g||await a(b);return}x==="audio"&&await h(b)}}});function y(u){const p=l.map(v=>e.loop?Ts(v,m,m+u):v.slice(m,m+u));if(m+=u,e.volume!==1)for(const v of p)for(let x=0;x<v.length;x++)v[x]*=e.volume;return p}async function a(u){const p=u[0],v=u[u.length-1],x=Math.floor((v.cts+v.duration-p.cts)/p.timescale*_),b=ra([y(x)]);b.length!==0&&c?.encode(b,p.cts/p.timescale*1e6)}async function h(u){if(o==null)return;const p=(await o.decode(u)).map(ia),v=ta(p),x=y(v[0].length),b=u[0];c?.encode(ra([v,x]),b.cts/b.timescale*1e6)}return r}const Gx=`
|
|
1296
1296
|
in vec2 aPosition;
|
|
1297
1297
|
out vec2 vTextureCoord;
|
|
1298
1298
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as p, U as Ne, T as ee, F as je, G as he, v as fe, M as P, l as C, d as pe, I as v, t as w, a8 as $, R as N, w as L, H as me, a5 as G, a6 as ge, c as F, B as T, D as j, S as M, y as D, af as qe, ag as q, L as Y, ah as U, s as Q, a0 as Qe, $ as X, n as xe, q as _e, aa as be, ad as ye, o as Je, p as Ze, ab as et, ac as tt, ae as rt, ai as nt, aj as st, ak as it, al as H, am as at, an as ot, m as ve, ao as te, ap as k, e as b, aq as ut } from "./index-
|
|
1
|
+
import { E as p, U as Ne, T as ee, F as je, G as he, v as fe, M as P, l as C, d as pe, I as v, t as w, a8 as $, R as N, w as L, H as me, a5 as G, a6 as ge, c as F, B as T, D as j, S as M, y as D, af as qe, ag as q, L as Y, ah as U, s as Q, a0 as Qe, $ as X, n as xe, q as _e, aa as be, ad as ye, o as Je, p as Ze, ab as et, ac as tt, ae as rt, ai as nt, aj as st, ak as it, al as H, am as at, an as ot, m as ve, ao as te, ap as k, e as b, aq as ut } from "./index-CDnMjIGb.js";
|
|
2
2
|
import { c as z, a as lt, b as ct, B as Te } from "./colorToUniform-C2jGzNe1.js";
|
|
3
3
|
class Pe {
|
|
4
4
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@designcombo/video",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Video rendering and processing library",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"files": [
|
|
23
23
|
"dist"
|
|
24
24
|
],
|
|
25
|
-
|
|
25
|
+
|
|
26
|
+
"main": "dist/index.umd.js",
|
|
26
27
|
"module": "dist/index.es.js",
|
|
27
28
|
"types": "dist/index.d.ts",
|
|
28
29
|
"exports": {
|