@diffusionstudio/core-v4
Version:
2D motion graphics and video rendering engine
1,329 lines (1,325 loc) • 422 kB
JavaScript
/*!
* @diffusionstudio/core-v4 v0.0.16
* (c) 2025 Diffusion Studio Inc.
*
* Licensed under the Diffusion Studio Non-Commercial License.
* You may NOT use this software for any commercial purposes.
*
* For commercial licensing, visit:
* https://diffusion.studio
*/
/*!
* Copyright (c) 2025-present, Vanilagy and contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
function m(e) {
if (!e)
throw new Error("Assertion failed.");
}
var Je = (e) => {
const t = (e % 360 + 360) % 360;
if (t === 0 || t === 90 || t === 180 || t === 270)
return t;
throw new Error(`Invalid rotation ${e}.`);
}, U = (e) => e && e[e.length - 1], Se = (e) => e >= 0 && e < 2 ** 32, le = class Or {
constructor(t) {
this.bytes = t, this.pos = 0;
}
seekToByte(t) {
this.pos = 8 * t;
}
readBit() {
const t = Math.floor(this.pos / 8), r = this.bytes[t] ?? 0, i = 7 - (this.pos & 7), s = (r & 1 << i) >> i;
return this.pos++, s;
}
readBits(t) {
let r = 0;
for (let i = 0; i < t; i++)
r <<= 1, r |= this.readBit();
return r;
}
readAlignedByte() {
if (this.pos % 8 !== 0)
throw new Error("Bitstream is not byte-aligned.");
const t = this.pos / 8, r = this.bytes[t] ?? 0;
return this.pos += 8, r;
}
skipBits(t) {
this.pos += t;
}
getBitsLeft() {
return this.bytes.length * 8 - this.pos;
}
clone() {
const t = new Or(this.bytes);
return t.pos = this.pos, t;
}
}, _ = (e) => {
let t = 0;
for (; e.readBit() === 0 && t < 32; )
t++;
if (t >= 32)
throw new Error("Invalid exponential-Golomb code.");
return (1 << t) - 1 + e.readBits(t);
}, ze = (e) => {
const t = _(e);
return t & 1 ? t + 1 >> 1 : -(t >> 1);
}, $i = (e, t, r, i) => {
for (let s = t; s < r; s++) {
const a = Math.floor(s / 8);
let n = e[a];
const o = 7 - (s & 7);
n &= ~(1 << o), n |= (i & 1 << r - s - 1) >> r - s - 1 << o, e[a] = n;
}
}, K = (e) => e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(e.buffer, e.byteOffset, e.byteLength), ue = (e) => e instanceof ArrayBuffer ? new DataView(e) : new DataView(e.buffer, e.byteOffset, e.byteLength), te = new TextEncoder(), Vt = (e) => Object.fromEntries(Object.entries(e).map(([t, r]) => [r, t])), _e = {
bt709: 1,
// ITU-R BT.709
bt470bg: 5,
// ITU-R BT.470BG
smpte170m: 6,
// ITU-R BT.601 525 - SMPTE 170M
bt2020: 9,
// ITU-R BT.202
smpte432: 12
// SMPTE EG 432-1
}, Ur = Vt(_e), xe = {
bt709: 1,
// ITU-R BT.709
smpte170m: 6,
// SMPTE 170M
linear: 8,
// Linear transfer characteristics
"iec61966-2-1": 13,
// IEC 61966-2-1
pg: 16,
// Rec. ITU-R BT.2100-2 perceptual quantization (PQ) system
hlg: 18
// Rec. ITU-R BT.2100-2 hybrid loggamma (HLG) system
}, Vr = Vt(xe), Ee = {
rgb: 0,
// Identity
bt709: 1,
// ITU-R BT.709
bt470bg: 5,
// ITU-R BT.470BG
smpte170m: 6,
// SMPTE 170M
"bt2020-ncl": 9
// ITU-R BT.2020-2 (non-constant luminance)
}, Dr = Vt(Ee), Lr = (e) => !!e && !!e.primaries && !!e.transfer && !!e.matrix && e.fullRange !== void 0, et = (e) => e instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && e instanceof SharedArrayBuffer || ArrayBuffer.isView(e) && !(e instanceof DataView), Ve = class {
constructor() {
this.currentPromise = Promise.resolve();
}
async acquire() {
let e;
const t = new Promise((i) => {
e = i;
}), r = this.currentPromise;
return this.currentPromise = t, await r, e;
}
}, ar = (e) => [...e].map((t) => t.toString(16).padStart(2, "0")).join(""), nr = (e) => (e = e >> 1 & 1431655765 | (e & 1431655765) << 1, e = e >> 2 & 858993459 | (e & 858993459) << 2, e = e >> 4 & 252645135 | (e & 252645135) << 4, e = e >> 8 & 16711935 | (e & 16711935) << 8, e = e >> 16 & 65535 | (e & 65535) << 16, e >>> 0), N = (e, t, r) => {
let i = 0, s = e.length - 1, a = -1;
for (; i <= s; ) {
const n = i + s >> 1, o = r(e[n]);
o === t ? (a = n, s = n - 1) : o < t ? i = n + 1 : s = n - 1;
}
return a;
}, M = (e, t, r) => {
let i = 0, s = e.length - 1, a = -1;
for (; i <= s; ) {
const n = i + (s - i + 1) / 2 | 0;
r(e[n]) <= t ? (a = n, i = n + 1) : s = n - 1;
}
return a;
}, W = () => {
let e, t;
return { promise: new Promise((i, s) => {
e = i, t = s;
}), resolve: e, reject: t };
}, Qi = (e, t) => {
const r = e.indexOf(t);
r !== -1 && e.splice(r, 1);
}, Wr = (e, t) => {
for (let r = e.length - 1; r >= 0; r--)
if (t(e[r]))
return e[r];
}, Nr = (e, t) => {
for (let r = e.length - 1; r >= 0; r--)
if (t(e[r]))
return r;
return -1;
}, qi = async function* (e) {
Symbol.iterator in e ? yield* e[Symbol.iterator]() : yield* e[Symbol.asyncIterator]();
}, ji = (e) => {
if (!(Symbol.iterator in e) && !(Symbol.asyncIterator in e))
throw new TypeError("Argument must be an iterable or async iterable.");
}, wt = (e) => {
throw new Error(`Unexpected value: ${e}`);
}, Hr = (e, t, r) => {
const i = e.getUint8(t), s = e.getUint8(t + 1), a = e.getUint8(t + 2);
return r ? i | s << 8 | a << 16 : i << 16 | s << 8 | a;
}, Ki = (e, t, r) => Hr(e, t, r) << 8 >> 8, $r = (e, t, r, i) => {
r = r >>> 0, r = r & 16777215, i ? (e.setUint8(t, r & 255), e.setUint8(t + 1, r >>> 8 & 255), e.setUint8(t + 2, r >>> 16 & 255)) : (e.setUint8(t, r >>> 16 & 255), e.setUint8(t + 1, r >>> 8 & 255), e.setUint8(t + 2, r & 255));
}, Gi = (e, t, r, i) => {
r = $(r, -8388608, 8388607), r < 0 && (r = r + 16777216 & 16777215), $r(e, t, r, i);
}, Xi = (e, t, r, i) => {
e.setUint32(t + 0, r, !0), e.setInt32(t + 4, Math.floor(r / 2 ** 32), !0);
}, Ge = (e, t) => ({
async next() {
const r = await e.next();
return r.done ? { value: void 0, done: !0 } : { value: t(r.value), done: !1 };
},
return() {
return e.return();
},
throw(r) {
return e.throw(r);
},
[Symbol.asyncIterator]() {
return this;
}
}), $ = (e, t, r) => Math.max(t, Math.min(r, e)), ie = "und", Dt = (e, t) => {
const r = 10 ** t;
return Math.round(e * r) / r;
}, kt = (e, t) => Math.round(e / t) * t, Yi = (e) => {
let t = 0;
for (; e; )
t++, e >>= 1;
return t;
}, Zi = /^[a-z]{3}$/, Lt = (e) => Zi.test(e), ce = 1e6 * (1 + Number.EPSILON), bt = (e, t) => {
const r = { ...e };
for (const i in t)
typeof e[i] == "object" && e[i] !== null && typeof t[i] == "object" && t[i] !== null ? r[i] = bt(
e[i],
t[i]
) : r[i] = t[i];
return r;
}, or = async (e, t, r) => {
let i = 0;
for (; ; )
try {
return await fetch(e, t);
} catch (s) {
console.error("Retrying failed fetch. Error:", s), i++;
const a = r(i);
if (a === null)
throw s;
if (!Number.isFinite(a) || a < 0)
throw new TypeError("Retry delay must be a non-negative finite number.");
a > 0 && await new Promise((n) => setTimeout(n, 1e3 * a));
}
}, Ji = (e, t) => {
const r = e < 0 ? -1 : 1;
e = Math.abs(e);
let i = 0, s = 1, a = 1, n = 0, o = e;
for (; ; ) {
const c = Math.floor(o), d = c * a + i, l = c * n + s;
if (l > t)
return {
numerator: r * a,
denominator: n
};
if (i = a, s = n, a = d, n = l, o = 1 / (o - c), !isFinite(o))
break;
}
return {
numerator: r * a,
denominator: n
};
}, tt = class {
constructor() {
this.currentPromise = Promise.resolve();
}
call(e) {
return this.currentPromise = this.currentPromise.then(e);
}
}, es = class {
/** Returns true iff the decoder can decode the given codec configuration. */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
static supports(e, t) {
return !1;
}
}, ts = class {
/** Returns true iff the decoder can decode the given codec configuration. */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
static supports(e, t) {
return !1;
}
}, rs = class {
/** Returns true iff the encoder can encode the given codec configuration. */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
static supports(e, t) {
return !1;
}
}, is = class {
/** Returns true iff the encoder can encode the given codec configuration. */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
static supports(e, t) {
return !1;
}
}, Wt = [], Nt = [], Xe = [], Ye = [], Yn = (e) => {
if (e.prototype instanceof es)
Wt.push(e);
else if (e.prototype instanceof ts)
Nt.push(e);
else
throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.");
}, Zn = (e) => {
if (e.prototype instanceof rs)
Xe.push(e);
else if (e.prototype instanceof is)
Ye.push(e);
else
throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.");
}, j = [
"avc",
"hevc",
"vp9",
"av1",
"vp8"
], D = [
"pcm-s16",
// We don't prefix 'le' so we're compatible with the WebCodecs-registered PCM codec strings
"pcm-s16be",
"pcm-s24",
"pcm-s24be",
"pcm-s32",
"pcm-s32be",
"pcm-f32",
"pcm-f32be",
"pcm-f64",
"pcm-f64be",
"pcm-u8",
"pcm-s8",
"ulaw",
"alaw"
], Te = [
"aac",
"opus",
"mp3",
"vorbis",
"flac"
], G = [
...Te,
...D
], se = [
"webvtt"
], cr = [
{ maxMacroblocks: 99, maxBitrate: 64e3, level: 10 },
// Level 1
{ maxMacroblocks: 396, maxBitrate: 192e3, level: 11 },
// Level 1.1
{ maxMacroblocks: 396, maxBitrate: 384e3, level: 12 },
// Level 1.2
{ maxMacroblocks: 396, maxBitrate: 768e3, level: 13 },
// Level 1.3
{ maxMacroblocks: 396, maxBitrate: 2e6, level: 20 },
// Level 2
{ maxMacroblocks: 792, maxBitrate: 4e6, level: 21 },
// Level 2.1
{ maxMacroblocks: 1620, maxBitrate: 4e6, level: 22 },
// Level 2.2
{ maxMacroblocks: 1620, maxBitrate: 1e7, level: 30 },
// Level 3
{ maxMacroblocks: 3600, maxBitrate: 14e6, level: 31 },
// Level 3.1
{ maxMacroblocks: 5120, maxBitrate: 2e7, level: 32 },
// Level 3.2
{ maxMacroblocks: 8192, maxBitrate: 2e7, level: 40 },
// Level 4
{ maxMacroblocks: 8192, maxBitrate: 5e7, level: 41 },
// Level 4.1
{ maxMacroblocks: 8704, maxBitrate: 5e7, level: 42 },
// Level 4.2
{ maxMacroblocks: 22080, maxBitrate: 135e6, level: 50 },
// Level 5
{ maxMacroblocks: 36864, maxBitrate: 24e7, level: 51 },
// Level 5.1
{ maxMacroblocks: 36864, maxBitrate: 24e7, level: 52 },
// Level 5.2
{ maxMacroblocks: 139264, maxBitrate: 24e7, level: 60 },
// Level 6
{ maxMacroblocks: 139264, maxBitrate: 48e7, level: 61 },
// Level 6.1
{ maxMacroblocks: 139264, maxBitrate: 8e8, level: 62 }
// Level 6.2
], dr = [
{ maxPictureSize: 36864, maxBitrate: 128e3, tier: "L", level: 30 },
// Level 1 (Low Tier)
{ maxPictureSize: 122880, maxBitrate: 15e5, tier: "L", level: 60 },
// Level 2 (Low Tier)
{ maxPictureSize: 245760, maxBitrate: 3e6, tier: "L", level: 63 },
// Level 2.1 (Low Tier)
{ maxPictureSize: 552960, maxBitrate: 6e6, tier: "L", level: 90 },
// Level 3 (Low Tier)
{ maxPictureSize: 983040, maxBitrate: 1e7, tier: "L", level: 93 },
// Level 3.1 (Low Tier)
{ maxPictureSize: 2228224, maxBitrate: 12e6, tier: "L", level: 120 },
// Level 4 (Low Tier)
{ maxPictureSize: 2228224, maxBitrate: 3e7, tier: "H", level: 120 },
// Level 4 (High Tier)
{ maxPictureSize: 2228224, maxBitrate: 2e7, tier: "L", level: 123 },
// Level 4.1 (Low Tier)
{ maxPictureSize: 2228224, maxBitrate: 5e7, tier: "H", level: 123 },
// Level 4.1 (High Tier)
{ maxPictureSize: 8912896, maxBitrate: 25e6, tier: "L", level: 150 },
// Level 5 (Low Tier)
{ maxPictureSize: 8912896, maxBitrate: 1e8, tier: "H", level: 150 },
// Level 5 (High Tier)
{ maxPictureSize: 8912896, maxBitrate: 4e7, tier: "L", level: 153 },
// Level 5.1 (Low Tier)
{ maxPictureSize: 8912896, maxBitrate: 16e7, tier: "H", level: 153 },
// Level 5.1 (High Tier)
{ maxPictureSize: 8912896, maxBitrate: 6e7, tier: "L", level: 156 },
// Level 5.2 (Low Tier)
{ maxPictureSize: 8912896, maxBitrate: 24e7, tier: "H", level: 156 },
// Level 5.2 (High Tier)
{ maxPictureSize: 35651584, maxBitrate: 6e7, tier: "L", level: 180 },
// Level 6 (Low Tier)
{ maxPictureSize: 35651584, maxBitrate: 24e7, tier: "H", level: 180 },
// Level 6 (High Tier)
{ maxPictureSize: 35651584, maxBitrate: 12e7, tier: "L", level: 183 },
// Level 6.1 (Low Tier)
{ maxPictureSize: 35651584, maxBitrate: 48e7, tier: "H", level: 183 },
// Level 6.1 (High Tier)
{ maxPictureSize: 35651584, maxBitrate: 24e7, tier: "L", level: 186 },
// Level 6.2 (Low Tier)
{ maxPictureSize: 35651584, maxBitrate: 8e8, tier: "H", level: 186 }
// Level 6.2 (High Tier)
], de = [
{ maxPictureSize: 36864, maxBitrate: 2e5, level: 10 },
// Level 1
{ maxPictureSize: 73728, maxBitrate: 8e5, level: 11 },
// Level 1.1
{ maxPictureSize: 122880, maxBitrate: 18e5, level: 20 },
// Level 2
{ maxPictureSize: 245760, maxBitrate: 36e5, level: 21 },
// Level 2.1
{ maxPictureSize: 552960, maxBitrate: 72e5, level: 30 },
// Level 3
{ maxPictureSize: 983040, maxBitrate: 12e6, level: 31 },
// Level 3.1
{ maxPictureSize: 2228224, maxBitrate: 18e6, level: 40 },
// Level 4
{ maxPictureSize: 2228224, maxBitrate: 3e7, level: 41 },
// Level 4.1
{ maxPictureSize: 8912896, maxBitrate: 6e7, level: 50 },
// Level 5
{ maxPictureSize: 8912896, maxBitrate: 12e7, level: 51 },
// Level 5.1
{ maxPictureSize: 8912896, maxBitrate: 18e7, level: 52 },
// Level 5.2
{ maxPictureSize: 35651584, maxBitrate: 18e7, level: 60 },
// Level 6
{ maxPictureSize: 35651584, maxBitrate: 24e7, level: 61 },
// Level 6.1
{ maxPictureSize: 35651584, maxBitrate: 48e7, level: 62 }
// Level 6.2
], lr = [
{ maxPictureSize: 147456, maxBitrate: 15e5, tier: "M", level: 0 },
// Level 2.0 (Main Tier)
{ maxPictureSize: 278784, maxBitrate: 3e6, tier: "M", level: 1 },
// Level 2.1 (Main Tier)
{ maxPictureSize: 665856, maxBitrate: 6e6, tier: "M", level: 4 },
// Level 3.0 (Main Tier)
{ maxPictureSize: 1065024, maxBitrate: 1e7, tier: "M", level: 5 },
// Level 3.1 (Main Tier)
{ maxPictureSize: 2359296, maxBitrate: 12e6, tier: "M", level: 8 },
// Level 4.0 (Main Tier)
{ maxPictureSize: 2359296, maxBitrate: 3e7, tier: "H", level: 8 },
// Level 4.0 (High Tier)
{ maxPictureSize: 2359296, maxBitrate: 2e7, tier: "M", level: 9 },
// Level 4.1 (Main Tier)
{ maxPictureSize: 2359296, maxBitrate: 5e7, tier: "H", level: 9 },
// Level 4.1 (High Tier)
{ maxPictureSize: 8912896, maxBitrate: 3e7, tier: "M", level: 12 },
// Level 5.0 (Main Tier)
{ maxPictureSize: 8912896, maxBitrate: 1e8, tier: "H", level: 12 },
// Level 5.0 (High Tier)
{ maxPictureSize: 8912896, maxBitrate: 4e7, tier: "M", level: 13 },
// Level 5.1 (Main Tier)
{ maxPictureSize: 8912896, maxBitrate: 16e7, tier: "H", level: 13 },
// Level 5.1 (High Tier)
{ maxPictureSize: 8912896, maxBitrate: 6e7, tier: "M", level: 14 },
// Level 5.2 (Main Tier)
{ maxPictureSize: 8912896, maxBitrate: 24e7, tier: "H", level: 14 },
// Level 5.2 (High Tier)
{ maxPictureSize: 35651584, maxBitrate: 6e7, tier: "M", level: 15 },
// Level 5.3 (Main Tier)
{ maxPictureSize: 35651584, maxBitrate: 24e7, tier: "H", level: 15 },
// Level 5.3 (High Tier)
{ maxPictureSize: 35651584, maxBitrate: 6e7, tier: "M", level: 16 },
// Level 6.0 (Main Tier)
{ maxPictureSize: 35651584, maxBitrate: 24e7, tier: "H", level: 16 },
// Level 6.0 (High Tier)
{ maxPictureSize: 35651584, maxBitrate: 1e8, tier: "M", level: 17 },
// Level 6.1 (Main Tier)
{ maxPictureSize: 35651584, maxBitrate: 48e7, tier: "H", level: 17 },
// Level 6.1 (High Tier)
{ maxPictureSize: 35651584, maxBitrate: 16e7, tier: "M", level: 18 },
// Level 6.2 (Main Tier)
{ maxPictureSize: 35651584, maxBitrate: 8e8, tier: "H", level: 18 },
// Level 6.2 (High Tier)
{ maxPictureSize: 35651584, maxBitrate: 16e7, tier: "M", level: 19 },
// Level 6.3 (Main Tier)
{ maxPictureSize: 35651584, maxBitrate: 8e8, tier: "H", level: 19 }
// Level 6.3 (High Tier)
], ur = ".01.01.01.01.00", hr = ".0.110.01.01.01.0", Tt = (e, t, r, i) => {
if (e === "avc") {
const a = Math.ceil(t / 16) * Math.ceil(r / 16), n = cr.find(
(h) => a <= h.maxMacroblocks && i <= h.maxBitrate
) ?? U(cr), o = n ? n.level : 0, c = "64".padStart(2, "0"), d = "00", l = o.toString(16).padStart(2, "0");
return `avc1.${c}${d}${l}`;
} else if (e === "hevc") {
const s = "", n = "6", o = t * r, c = dr.find(
(l) => o <= l.maxPictureSize && i <= l.maxBitrate
) ?? U(dr);
return `hev1.${s}1.${n}.${c.tier}${c.level}.B0`;
} else {
if (e === "vp8")
return "vp8";
if (e === "vp9") {
const s = "00", a = t * r, n = de.find(
(c) => a <= c.maxPictureSize && i <= c.maxBitrate
) ?? U(de);
return `vp09.${s}.${n.level.toString().padStart(2, "0")}.08`;
} else if (e === "av1") {
const a = t * r, n = lr.find(
(d) => a <= d.maxPictureSize && i <= d.maxBitrate
) ?? U(lr);
return `av01.0.${n.level.toString().padStart(2, "0")}${n.tier}.08`;
}
}
throw new TypeError(`Unhandled codec '${e}'.`);
}, ss = (e) => {
const t = e.split("."), r = Number(t[1]), i = Number(t[2]), s = Number(t[3]), a = t[4] ? Number(t[4]) : 1;
return [
1,
1,
r,
2,
1,
i,
3,
1,
s,
4,
1,
a
];
}, Qr = (e) => {
const t = e.split("."), s = (1 << 7) + 1, a = Number(t[1]), n = t[2], o = Number(n.slice(0, -1)), c = (a << 5) + o, d = n.slice(-1) === "H" ? 1 : 0, h = Number(t[3]) === 8 ? 0 : 1, u = 0, f = t[4] ? Number(t[4]) : 0, g = t[5] ? Number(t[5][0]) : 1, p = t[5] ? Number(t[5][1]) : 1, w = t[5] ? Number(t[5][2]) : 0, k = (d << 7) + (h << 6) + (u << 5) + (f << 4) + (g << 3) + (p << 2) + w;
return [s, c, k, 0];
}, qr = (e) => {
const { codec: t, codecDescription: r, colorSpace: i, avcCodecInfo: s, hevcCodecInfo: a, vp9CodecInfo: n, av1CodecInfo: o } = e;
if (t === "avc") {
if (s) {
const c = new Uint8Array([
s.avcProfileIndication,
s.profileCompatibility,
s.avcLevelIndication
]);
return `avc1.${ar(c)}`;
}
if (!r || r.byteLength < 4)
throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");
return `avc1.${ar(r.subarray(1, 4))}`;
} else if (t === "hevc") {
let c, d, l, h, u, f;
if (a)
c = a.generalProfileSpace, d = a.generalProfileIdc, l = nr(a.generalProfileCompatibilityFlags), h = a.generalTierFlag, u = a.generalLevelIdc, f = [...a.generalConstraintIndicatorFlags];
else {
if (!r || r.byteLength < 23)
throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");
const p = ue(r), w = p.getUint8(1);
c = w >> 6 & 3, d = w & 31, l = nr(p.getUint32(2)), h = w >> 5 & 1, u = p.getUint8(12), f = [];
for (let k = 0; k < 6; k++)
f.push(p.getUint8(6 + k));
}
let g = "hev1.";
for (g += ["", "A", "B", "C"][c] + d, g += ".", g += l.toString(16).toUpperCase(), g += ".", g += h === 0 ? "L" : "H", g += u; f.length > 0 && f[f.length - 1] === 0; )
f.pop();
return f.length > 0 && (g += ".", g += f.map((p) => p.toString(16).toUpperCase()).join(".")), g;
} else {
if (t === "vp8")
return "vp8";
if (t === "vp9") {
if (!n) {
const k = e.width * e.height;
let S = U(de).level;
for (const y of de)
if (k <= y.maxPictureSize) {
S = y.level;
break;
}
return `vp09.00.${S.toString().padStart(2, "0")}.08`;
}
const c = n.profile.toString().padStart(2, "0"), d = n.level.toString().padStart(2, "0"), l = n.bitDepth.toString().padStart(2, "0"), h = n.chromaSubsampling.toString().padStart(2, "0"), u = n.colourPrimaries.toString().padStart(2, "0"), f = n.transferCharacteristics.toString().padStart(2, "0"), g = n.matrixCoefficients.toString().padStart(2, "0"), p = n.videoFullRangeFlag.toString().padStart(2, "0");
let w = `vp09.${c}.${d}.${l}.${h}`;
return w += `.${u}.${f}.${g}.${p}`, w.endsWith(ur) && (w = w.slice(0, -ur.length)), w;
} else if (t === "av1") {
if (!o) {
const y = e.width * e.height;
let b = U(de).level;
for (const T of de)
if (y <= T.maxPictureSize) {
b = T.level;
break;
}
return `av01.0.${b.toString().padStart(2, "0")}M.08`;
}
const c = o.profile, d = o.level.toString().padStart(2, "0"), l = o.tier ? "H" : "M", h = o.bitDepth.toString().padStart(2, "0"), u = o.monochrome ? "1" : "0", f = 100 * o.chromaSubsamplingX + 10 * o.chromaSubsamplingY + 1 * (o.chromaSubsamplingX && o.chromaSubsamplingY ? o.chromaSamplePosition : 0), g = i?.primaries ? _e[i.primaries] : 1, p = i?.transfer ? xe[i.transfer] : 1, w = i?.matrix ? Ee[i.matrix] : 1, k = i?.fullRange ? 1 : 0;
let S = `av01.${c}.${d}${l}.${h}`;
return S += `.${u}.${f.toString().padStart(3, "0")}`, S += `.${g.toString().padStart(2, "0")}`, S += `.${p.toString().padStart(2, "0")}`, S += `.${w.toString().padStart(2, "0")}`, S += `.${k}`, S.endsWith(hr) && (S = S.slice(0, -hr.length)), S;
}
}
throw new TypeError(`Unhandled codec '${t}'.`);
}, yt = (e, t, r) => {
if (e === "aac")
return t >= 2 && r <= 24e3 ? "mp4a.40.29" : r <= 24e3 ? "mp4a.40.5" : "mp4a.40.2";
if (e === "mp3")
return "mp3";
if (e === "opus")
return "opus";
if (e === "vorbis")
return "vorbis";
if (e === "flac")
return "flac";
if (D.includes(e))
return e;
throw new TypeError(`Unhandled codec '${e}'.`);
}, jr = (e) => {
const { codec: t, codecDescription: r, aacCodecInfo: i } = e;
if (t === "aac") {
if (!i)
throw new TypeError("AAC codec info must be provided.");
return i.isMpeg2 ? "mp4a.67" : `mp4a.40.${Kr(r).objectType}`;
} else {
if (t === "mp3")
return "mp3";
if (t === "opus")
return "opus";
if (t === "vorbis")
return "vorbis";
if (t === "flac")
return "flac";
if (t && D.includes(t))
return t;
}
throw new TypeError(`Unhandled codec '${t}'.`);
}, Kr = (e) => {
if (!e || e.byteLength < 2)
throw new TypeError("AAC description must be at least 2 bytes long.");
const t = new le(e);
let r = t.readBits(5);
r === 31 && (r = 32 + t.readBits(6));
const i = t.readBits(4);
let s = null;
if (i === 15)
s = t.readBits(24);
else {
const o = [
96e3,
88200,
64e3,
48e3,
44100,
32e3,
24e3,
22050,
16e3,
12e3,
11025,
8e3,
7350
];
i < o.length && (s = o[i]);
}
const a = t.readBits(4);
let n = null;
return a >= 1 && a <= 7 && (n = {
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 8
}[a]), {
objectType: r,
frequencyIndex: i,
sampleRate: s,
channelConfiguration: a,
numberOfChannels: n
};
}, Ht = 48e3, Gr = /^pcm-([usf])(\d+)+(be)?$/, J = (e) => {
if (m(D.includes(e)), e === "ulaw")
return { dataType: "ulaw", sampleSize: 1, littleEndian: !0, silentValue: 255 };
if (e === "alaw")
return { dataType: "alaw", sampleSize: 1, littleEndian: !0, silentValue: 213 };
const t = Gr.exec(e);
m(t);
let r;
t[1] === "u" ? r = "unsigned" : t[1] === "s" ? r = "signed" : r = "float";
const i = Number(t[2]) / 8, s = t[3] !== "be", a = e === "pcm-u8" ? 2 ** 7 : 0;
return { dataType: r, sampleSize: i, littleEndian: s, silentValue: a };
}, Xr = (e) => e.startsWith("avc1") || e.startsWith("avc3") ? "avc" : e.startsWith("hev1") || e.startsWith("hvc1") ? "hevc" : e === "vp8" ? "vp8" : e.startsWith("vp09") ? "vp9" : e.startsWith("av01") ? "av1" : e.startsWith("mp4a.40") || e === "mp4a.67" ? "aac" : e === "mp3" || e === "mp4a.69" || e === "mp4a.6B" || e === "mp4a.6b" ? "mp3" : e === "opus" ? "opus" : e === "vorbis" ? "vorbis" : e === "flac" ? "flac" : e === "ulaw" ? "ulaw" : e === "alaw" ? "alaw" : Gr.test(e) ? e : e === "webvtt" ? "webvtt" : null, vt = (e) => e === "avc" ? {
avc: {
format: "avc"
// Ensure the format is not Annex B
}
} : e === "hevc" ? {
hevc: {
format: "hevc"
// Ensure the format is not Annex B
}
} : {}, St = (e) => e === "aac" ? {
aac: {
format: "aac"
// Ensure the format is not ADTS
}
} : e === "opus" ? {
opus: {
format: "opus"
}
} : {}, q = class {
/** @internal */
constructor(e) {
this._factor = e;
}
/** @internal */
_toVideoBitrate(e, t, r) {
const i = t * r, s = {
avc: 1,
// H.264/AVC (baseline)
hevc: 0.6,
// H.265/HEVC (~40% more efficient than AVC)
vp9: 0.6,
// Similar to HEVC
av1: 0.4,
// ~60% more efficient than AVC
vp8: 1.2
// Slightly less efficient than AVC
}, a = 1920 * 1080, n = 3e6, o = Math.pow(i / a, 0.95), l = n * o * s[e] * this._factor;
return Math.ceil(l / 1e3) * 1e3;
}
/** @internal */
_toAudioBitrate(e) {
if (D.includes(e) || e === "flac")
return;
const r = {
aac: 128e3,
// 128kbps base for AAC
opus: 64e3,
// 64kbps base for Opus
mp3: 16e4,
// 160kbps base for MP3
vorbis: 64e3
// 64kbps base for Vorbis
}[e];
if (!r)
throw new Error(`Unhandled codec: ${e}`);
let i = r * this._factor;
return e === "aac" ? i = [96e3, 128e3, 16e4, 192e3].reduce(
(a, n) => Math.abs(n - i) < Math.abs(a - i) ? n : a
) : e === "opus" || e === "vorbis" ? i = Math.max(6e3, i) : e === "mp3" && (i = [
8e3,
16e3,
24e3,
32e3,
4e4,
48e3,
64e3,
8e4,
96e3,
112e3,
128e3,
16e4,
192e3,
224e3,
256e3,
32e4
].reduce(
(a, n) => Math.abs(n - i) < Math.abs(a - i) ? n : a
)), Math.round(i / 1e3) * 1e3;
}
}, Jn = new q(0.3), eo = new q(0.6), to = new q(1), mr = new q(2), ro = new q(4), as = ["avc1", "avc3", "hev1", "hvc1", "vp8", "vp09", "av01"], ns = /^(avc1|avc3)\.[0-9a-fA-F]{6}$/, os = /^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/, cs = /^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/, ds = /^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/, Yr = (e) => {
if (!e)
throw new TypeError("Video chunk metadata must be provided.");
if (typeof e != "object")
throw new TypeError("Video chunk metadata must be an object.");
if (!e.decoderConfig)
throw new TypeError("Video chunk metadata must include a decoder configuration.");
if (typeof e.decoderConfig != "object")
throw new TypeError("Video chunk metadata decoder configuration must be an object.");
if (typeof e.decoderConfig.codec != "string")
throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");
if (!as.some((t) => e.decoderConfig.codec.startsWith(t)))
throw new TypeError(
"Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry."
);
if (!Number.isInteger(e.decoderConfig.codedWidth) || e.decoderConfig.codedWidth <= 0)
throw new TypeError(
"Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer)."
);
if (!Number.isInteger(e.decoderConfig.codedHeight) || e.decoderConfig.codedHeight <= 0)
throw new TypeError(
"Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer)."
);
if (e.decoderConfig.description !== void 0 && !et(e.decoderConfig.description))
throw new TypeError(
"Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view."
);
if (e.decoderConfig.colorSpace !== void 0) {
const { colorSpace: t } = e.decoderConfig;
if (typeof t != "object")
throw new TypeError(
"Video chunk metadata decoder configuration colorSpace, when provided, must be an object."
);
const r = Object.keys(_e);
if (t.primaries != null && !r.includes(t.primaries))
throw new TypeError(
`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`
);
const i = Object.keys(xe);
if (t.transfer != null && !i.includes(t.transfer))
throw new TypeError(
`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`
);
const s = Object.keys(Ee);
if (t.matrix != null && !s.includes(t.matrix))
throw new TypeError(
`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`
);
if (t.fullRange != null && typeof t.fullRange != "boolean")
throw new TypeError(
"Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean."
);
}
if (e.decoderConfig.codec.startsWith("avc1") || e.decoderConfig.codec.startsWith("avc3")) {
if (!ns.test(e.decoderConfig.codec))
throw new TypeError(
"Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381."
);
} else if (e.decoderConfig.codec.startsWith("hev1") || e.decoderConfig.codec.startsWith("hvc1")) {
if (!os.test(e.decoderConfig.codec))
throw new TypeError(
"Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15."
);
} else if (e.decoderConfig.codec.startsWith("vp8")) {
if (e.decoderConfig.codec !== "vp8")
throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".');
} else if (e.decoderConfig.codec.startsWith("vp09")) {
if (!cs.test(e.decoderConfig.codec))
throw new TypeError(
'Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.'
);
} else if (e.decoderConfig.codec.startsWith("av01") && !ds.test(e.decoderConfig.codec))
throw new TypeError(
'Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.'
);
}, ls = ["mp4a", "mp3", "opus", "vorbis", "flac", "ulaw", "alaw", "pcm"], rt = (e) => {
if (!e)
throw new TypeError("Audio chunk metadata must be provided.");
if (typeof e != "object")
throw new TypeError("Audio chunk metadata must be an object.");
if (!e.decoderConfig)
throw new TypeError("Audio chunk metadata must include a decoder configuration.");
if (typeof e.decoderConfig != "object")
throw new TypeError("Audio chunk metadata decoder configuration must be an object.");
if (typeof e.decoderConfig.codec != "string")
throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");
if (!ls.some((t) => e.decoderConfig.codec.startsWith(t)))
throw new TypeError(
"Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry."
);
if (!Number.isInteger(e.decoderConfig.sampleRate) || e.decoderConfig.sampleRate <= 0)
throw new TypeError(
"Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer)."
);
if (!Number.isInteger(e.decoderConfig.numberOfChannels) || e.decoderConfig.numberOfChannels <= 0)
throw new TypeError(
"Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer)."
);
if (e.decoderConfig.description !== void 0 && !et(e.decoderConfig.description))
throw new TypeError(
"Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view."
);
if (e.decoderConfig.codec.startsWith("mp4a") && e.decoderConfig.codec !== "mp4a.69" && e.decoderConfig.codec !== "mp4a.6B" && e.decoderConfig.codec !== "mp4a.6b") {
if (!["mp4a.40.2", "mp4a.40.02", "mp4a.40.5", "mp4a.40.05", "mp4a.40.29", "mp4a.67"].includes(e.decoderConfig.codec))
throw new TypeError(
"Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/."
);
if (!e.decoderConfig.description)
throw new TypeError(
"Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3."
);
} else if (e.decoderConfig.codec.startsWith("mp3") || e.decoderConfig.codec.startsWith("mp4a")) {
if (e.decoderConfig.codec !== "mp3" && e.decoderConfig.codec !== "mp4a.69" && e.decoderConfig.codec !== "mp4a.6B" && e.decoderConfig.codec !== "mp4a.6b")
throw new TypeError(
'Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".'
);
} else if (e.decoderConfig.codec.startsWith("opus")) {
if (e.decoderConfig.codec !== "opus")
throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');
if (e.decoderConfig.description && e.decoderConfig.description.byteLength < 18)
throw new TypeError(
"Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845."
);
} else if (e.decoderConfig.codec.startsWith("vorbis")) {
if (e.decoderConfig.codec !== "vorbis")
throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');
if (!e.decoderConfig.description)
throw new TypeError(
"Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/."
);
} else if (e.decoderConfig.codec.startsWith("flac")) {
if (e.decoderConfig.codec !== "flac")
throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');
if (!e.decoderConfig.description || e.decoderConfig.description.byteLength < 42)
throw new TypeError(
"Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/."
);
} else if ((e.decoderConfig.codec.startsWith("pcm") || e.decoderConfig.codec.startsWith("ulaw") || e.decoderConfig.codec.startsWith("alaw")) && !D.includes(e.decoderConfig.codec))
throw new TypeError(
`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${D.join(", ")}).`
);
}, Zr = (e) => {
if (!e)
throw new TypeError("Subtitle metadata must be provided.");
if (typeof e != "object")
throw new TypeError("Subtitle metadata must be an object.");
if (!e.config)
throw new TypeError("Subtitle metadata must include a config object.");
if (typeof e.config != "object")
throw new TypeError("Subtitle metadata config must be an object.");
if (typeof e.config.description != "string")
throw new TypeError("Subtitle metadata config description must be a string.");
}, io = (e) => {
if (j.includes(e))
return $t(e);
if (G.includes(e))
return Qt(e);
if (se.includes(e))
return qt(e);
throw new TypeError(`Unknown codec '${e}'.`);
}, $t = async (e, { width: t = 1280, height: r = 720, bitrate: i = 1e6 } = {}) => {
if (!j.includes(e))
return !1;
if (!Number.isInteger(t) || t <= 0)
throw new TypeError("width must be a positive integer.");
if (!Number.isInteger(r) || r <= 0)
throw new TypeError("height must be a positive integer.");
if (!(i instanceof q) && (!Number.isInteger(i) || i <= 0))
throw new TypeError("bitrate must be a positive integer or a quality.");
const s = i instanceof q ? i._toVideoBitrate(e, t, r) : i;
if (Xe.length > 0) {
const n = {
codec: Tt(
e,
t,
r,
s
),
width: t,
height: r,
bitrate: s,
...vt(e)
};
if (Xe.some((o) => o.supports(e, n)))
return !0;
}
return typeof VideoEncoder > "u" ? !1 : (await VideoEncoder.isConfigSupported({
codec: Tt(e, t, r, s),
width: t,
height: r,
bitrate: s,
...vt(e)
})).supported === !0;
}, Qt = async (e, { numberOfChannels: t = 2, sampleRate: r = 48e3, bitrate: i = 128e3 } = {}) => {
if (!G.includes(e))
return !1;
if (!Number.isInteger(t) || t <= 0)
throw new TypeError("numberOfChannels must be a positive integer.");
if (!Number.isInteger(r) || r <= 0)
throw new TypeError("sampleRate must be a positive integer.");
if (!(i instanceof q) && (!Number.isInteger(i) || i <= 0))
throw new TypeError("bitrate must be a positive integer.");
const s = i instanceof q ? i._toAudioBitrate(e) : i;
if (Ye.length > 0) {
const n = {
codec: yt(
e,
t,
r
),
numberOfChannels: t,
sampleRate: r,
bitrate: s,
...St(e)
};
if (Ye.some((o) => o.supports(e, n)))
return !0;
}
return D.includes(e) ? !0 : typeof AudioEncoder > "u" ? !1 : (await AudioEncoder.isConfigSupported({
codec: yt(e, t, r),
numberOfChannels: t,
sampleRate: r,
bitrate: s,
...St(e)
})).supported === !0;
}, qt = async (e) => !!se.includes(e), so = async () => {
const [e, t, r] = await Promise.all([
us(),
Ct(),
hs()
]);
return [...e, ...t, ...r];
}, us = async (e = j, t) => {
const r = await Promise.all(e.map((i) => $t(i, t)));
return e.filter((i, s) => r[s]);
}, Ct = async (e = G, t) => {
const r = await Promise.all(e.map((i) => Qt(i, t)));
return e.filter((i, s) => r[s]);
}, hs = async (e = se) => {
const t = await Promise.all(e.map(qt));
return e.filter((r, i) => t[i]);
}, ms = async (e, t) => {
for (const r of e)
if (await $t(r, t))
return r;
return null;
}, ao = async (e, t) => {
for (const r of e)
if (await Qt(r, t))
return r;
return null;
}, no = async (e) => {
for (const t of e)
if (await qt(t))
return t;
return null;
}, Re = /(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g, fs = /^WEBVTT(.|\n)*?\n{2}/, Ze = /<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g, ps = class {
constructor(e) {
this.preambleText = null, this.preambleEmitted = !1, this.options = e;
}
parse(e) {
e = e.replaceAll(`\r
`, `
`).replaceAll("\r", `
`), Re.lastIndex = 0;
let t;
if (!this.preambleText) {
if (!fs.test(e))
throw new Error("WebVTT preamble incorrect.");
t = Re.exec(e);
const r = e.slice(0, t?.index ?? e.length).trimEnd();
if (!r)
throw new Error("No WebVTT preamble provided.");
this.preambleText = r, t && (e = e.slice(t.index), Re.lastIndex = 0);
}
for (; t = Re.exec(e); ) {
const r = e.slice(0, t.index), i = t[1], s = t.index + t[0].length, a = e.indexOf(`
`, s) + 1, n = e.slice(s, a).trim();
let o = e.indexOf(`
`, s);
o === -1 && (o = e.length);
const c = _t(t[2]), l = _t(t[3]) - c, h = e.slice(a, o).trim();
e = e.slice(o).trimStart(), Re.lastIndex = 0;
const u = {
timestamp: c / 1e3,
duration: l / 1e3,
text: h,
identifier: i,
settings: n,
notes: r
}, f = {};
this.preambleEmitted || (f.config = {
description: this.preambleText
}, this.preambleEmitted = !0), this.options.output(u, f);
}
}
}, gs = /(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/, _t = (e) => {
const t = gs.exec(e);
if (!t) throw new Error("Expected match.");
return 60 * 60 * 1e3 * Number(t[1] || "0") + 60 * 1e3 * Number(t[2]) + 1e3 * Number(t[3]) + Number(t[4]);
}, Jr = (e) => {
const t = Math.floor(e / 36e5), r = Math.floor(e % (60 * 60 * 1e3) / (60 * 1e3)), i = Math.floor(e % (60 * 1e3) / 1e3), s = e % 1e3;
return t.toString().padStart(2, "0") + ":" + r.toString().padStart(2, "0") + ":" + i.toString().padStart(2, "0") + "." + s.toString().padStart(3, "0");
}, jt = (e) => {
const t = [];
let r = 0;
for (; r < e.length; ) {
let i = -1, s = 0;
for (let a = r; a < e.length - 3; a++) {
if (e[a] === 0 && e[a + 1] === 0 && e[a + 2] === 1) {
i = a, s = 3;
break;
}
if (a < e.length - 4 && e[a] === 0 && e[a + 1] === 0 && e[a + 2] === 0 && e[a + 3] === 1) {
i = a, s = 4;
break;
}
}
if (i === -1)
break;
if (r > 0 && i > r) {
const a = e.subarray(r, i);
a.length > 0 && t.push(a);
}
r = i + s;
}
if (r < e.length) {
const i = e.subarray(r);
i.length > 0 && t.push(i);
}
return t;
}, xt = (e) => {
const t = [], r = e.length;
for (let i = 0; i < r; i++)
i + 2 < r && e[i] === 0 && e[i + 1] === 0 && e[i + 2] === 3 ? (t.push(0, 0), i += 2) : t.push(e[i]);
return new Uint8Array(t);
}, ws = (e) => {
const r = jt(e);
if (r.length === 0)
return null;
let i = 0;
for (const o of r)
i += 4 + o.byteLength;
const s = new Uint8Array(i), a = new DataView(s.buffer);
let n = 0;
for (const o of r) {
const c = o.byteLength;
a.setUint32(n, c, !1), n += 4, s.set(o, n), n += o.byteLength;
}
return s;
}, at = (e) => e[0] & 31, ei = (e) => {
try {
const t = jt(e), r = t.filter((u) => at(u) === 7), i = t.filter((u) => at(u) === 8), s = t.filter((u) => at(u) === 13);
if (r.length === 0 || i.length === 0)
return null;
const a = r[0], n = new le(xt(a));
if (n.skipBits(1), n.skipBits(2), n.readBits(5) !== 7)
return console.error("Invalid SPS NAL unit type"), null;
const c = n.readAlignedByte(), d = n.readAlignedByte(), l = n.readAlignedByte(), h = {
configurationVersion: 1,
avcProfileIndication: c,
profileCompatibility: d,
avcLevelIndication: l,
lengthSizeMinusOne: 3,
// Typically 4 bytes for length field
sequenceParameterSets: r,
pictureParameterSets: i,
chromaFormat: null,
bitDepthLumaMinus8: null,
bitDepthChromaMinus8: null,
sequenceParameterSetExt: null
};
if (c === 100 || c === 110 || c === 122 || c === 144) {
_(n);
const u = _(n);
u === 3 && n.skipBits(1);
const f = _(n), g = _(n);
h.chromaFormat = u, h.bitDepthLumaMinus8 = f, h.bitDepthChromaMinus8 = g, h.sequenceParameterSetExt = s;
}
return h;
} catch (t) {
return console.error("Error building AVC Decoder Configuration Record:", t), null;
}
}, ks = (e) => {
const t = [];
t.push(e.configurationVersion), t.push(e.avcProfileIndication), t.push(e.profileCompatibility), t.push(e.avcLevelIndication), t.push(252 | e.lengthSizeMinusOne & 3), t.push(224 | e.sequenceParameterSets.length & 31);
for (const r of e.sequenceParameterSets) {
const i = r.byteLength;
t.push(i >> 8), t.push(i & 255);
for (let s = 0; s < i; s++)
t.push(r[s]);
}
t.push(e.pictureParameterSets.length);
for (const r of e.pictureParameterSets) {
const i = r.byteLength;
t.push(i >> 8), t.push(i & 255);
for (let s = 0; s < i; s++)
t.push(r[s]);
}
if (e.avcProfileIndication === 100 || e.avcProfileIndication === 110 || e.avcProfileIndication === 122 || e.avcProfileIndication === 144) {
m(e.chromaFormat !== null), m(e.bitDepthLumaMinus8 !== null), m(e.bitDepthChromaMinus8 !== null), m(e.sequenceParameterSetExt !== null), t.push(252 | e.chromaFormat & 3), t.push(248 | e.bitDepthLumaMinus8 & 7), t.push(248 | e.bitDepthChromaMinus8 & 7), t.push(e.sequenceParameterSetExt.length);
for (const r of e.sequenceParameterSetExt) {
const i = r.byteLength;
t.push(i >> 8), t.push(i & 255);
for (let s = 0; s < i; s++)
t.push(r[s]);
}
}
return new Uint8Array(t);
}, fr = 32, pr = 33, gr = 34, bs = 39, Ts = 40, ge = (e) => e[0] >> 1 & 63, ti = (e) => {
try {
const t = jt(e), r = t.filter((P) => ge(P) === fr), i = t.filter((P) => ge(P) === pr), s = t.filter((P) => ge(P) === gr), a = t.filter(
(P) => ge(P) === bs || ge(P) === Ts
);
if (i.length === 0 || s.length === 0) return null;
const n = i[0], o = new le(xt(n));
o.skipBits(16), o.readBits(4);
const c = o.readBits(3), d = o.readBits(1), {
general_profile_space: l,
general_tier_flag: h,
general_profile_idc: u,
general_profile_compatibility_flags: f,
general_constraint_indicator_flags: g,
general_level_idc: p
} = ys(o, c);
_(o);
const w = _(o);
w === 3 && o.skipBits(1), _(o), _(o), o.readBits(1) && (_(o), _(o), _(o), _(o));
const k = _(o), S = _(o);
_(o);
const b = o.readBits(1) ? 0 : c;
for (let P = b; P <= c; P++)
_(o), _(o), _(o);
_(o), _(o), _(o), _(o), _(o), _(o), o.readBits(1) && o.readBits(1) && vs(o), o.skipBits(1), o.skipBits(1), o.readBits(1) && (o.skipBits(4), o.skipBits(4), _(o), _(o), o.skipBits(1));
const T = _(o);
if (Ss(o, T), o.readBits(1)) {
const P = _(o);
for (let R = 0; R < P; R++)
_(o), o.skipBits(1);
}
o.skipBits(1), o.skipBits(1);
let v = 0;
o.readBits(1) && (v = _s(o, c));
let E = 0;
if (s.length > 0) {
const P = s[0], R = new le(xt(P));
R.skipBits(16), _(R), _(R), R.skipBits(1), R.skipBits(1), R.skipBits(3), R.skipBits(1), R.skipBits(1), _(R), _(R), ze(R), R.skipBits(1), R.skipBits(1), R.readBits(1) && _(R), ze(R), ze(R), R.skipBits(1), R.skipBits(1), R.skipBits(1), R.skipBits(1);
const L = R.readBits(1), me = R.readBits(1);
!L && !me ? E = 0 : L && !me ? E = 2 : !L && me ? E = 3 : E = 0;
}
const x = [
...r.length ? [
{
arrayCompleteness: 1,
nalUnitType: fr,
nalUnits: r
}
] : [],
...i.length ? [
{
arrayCompleteness: 1,
nalUnitType: pr,
nalUnits: i
}
] : [],
...s.length ? [
{
arrayCompleteness: 1,
nalUnitType: gr,
nalUnits: s
}
] : [],
...a.length ? [
{
arrayCompleteness: 1,
nalUnitType: ge(a[0]),
nalUnits: a
}
] : []
];
return {
configurationVersion: 1,
generalProfileSpace: l,
generalTierFlag: h,
generalProfileIdc: u,
generalProfileCompatibilityFlags: f,
generalConstraintIndicatorFlags: g,
generalLevelIdc: p,
minSpatialSegmentationIdc: v,
parallelismType: E,
chromaFormatIdc: w,
bitDepthLumaMinus8: k,
bitDepthChromaMinus8: S,
avgFrameRate: 0,
constantFrameRate: 0,
numTemporalLayers: c + 1,
temporalIdNested: d,
lengthSizeMinusOne: 3,
arrays: x
};
} catch (t) {
return console.error("Error building HEVC Decoder Configuration Record:", t), null;
}
}, ys = (e, t) => {
const r = e.readBits(2), i = e.readBits(1), s = e.readBits(5);
let a = 0;
for (let l = 0; l < 32; l++)
a = a << 1 | e.readBits(1);
const n = new Uint8Array(6);
for (let l = 0; l < 6; l++)
n[l] = e.readBits(8);
const o = e.readBits(8), c = [], d = [];
for (let l = 0; l < t; l++)
c.push(e.readBits(1)), d.push(e.readBits(1));
if (t > 0)
for (let l = t; l < 8; l++)
e.skipBits(2);
for (let l = 0; l < t; l++)
c[l] && e.skipBits(88), d[l] && e.skipBits(8);
return {
general_profile_space: r,
general_tier_flag: i,
general_profile_idc: s,
general_profile_compatibility_flags: a,
general_constraint_indicator_flags: n,
general_level_idc: o
};
}, vs = (e) => {
for (let t = 0; t < 4; t++)
for (let r = 0; r < (t === 3 ? 2 : 6); r++)
if (!e.readBits(1))
_(e);
else {
const s = Math.min(64, 1 << 4 + (t << 1));
t > 1 && ze(e);
for (let a = 0; a < s; a++)
ze(e);
}
}, Ss = (e, t) => {
const r = [];
for (let i = 0; i < t; i++)
r[i] = Cs(e, i, t, r);
}, Cs = (e, t, r, i) => {
let s = 0, a = 0, n = 0;
if (t !== 0 && (a = e.readBits(1)), a) {
if (t === r) {
const c = _(e);
n = t - (c + 1);
} else
n = t - 1;
e.readBits(1), _(e);
const o = i[n] ?? 0;
for (let c = 0; c <= o; c++)
e.readBits(1) || e.readBits(1);
s = i[n];
} else {
const o = _(e), c = _(e);
for (let d = 0; d < o; d++)
_(e), e.readBits(1);
for (let d = 0; d < c; d++)
_(e), e.readBits(1);
s = o + c;
}
return s;
}, _s = (e, t) => {
if (e.readBits(1) && e.readBits(8) === 255 && (e.readBits(16), e.readBits(16)), e.readBits(1) && e.readBits(1), e.readBits(1) && (e.readBits(3), e.readBits(1), e.readBits(1) && (e.readBits(8), e.readBits(8), e.readBits(8))), e.readBits(1) && (_(e), _(e)), e.readBits(1), e.readBits(1), e.readBits(1), e.readBits(1) && (_(e), _(e), _(e), _(e)), e.readBits(1) && (e.readBits(32), e.readBits(32), e.readBits(1) && _(e), e.readBits(1) && xs(e, !0, t)), e.readBits(1)) {
e.readBits(1), e.readBits(1), e.readBits(1);
const r = _(e);
return _(e), _(e), _(e), _(e), r;
}
return 0;
}, xs = (e, t, r) => {
let i = !1, s = !1, a = !1;
i = e.readBits(1) === 1, s = e.readBits(1) === 1, (i || s) && (a = e.readBits(1) === 1, a && (e.readBits(8), e.readBits(5), e.readBits(1), e.readBits(5)), e.readBits(4), e.readBits(4), a && e.readBits(4), e.readBits(5), e.readBits(5), e.readBits(5));
for (let n = 0; n <= r; n++) {
const o = e.readBits(1) === 1;
let c = !0;