Socket
Socket
Sign inDemoInstall

@vonage/media-processor

Package Overview
Dependencies
Maintainers
52
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vonage/media-processor - npm Package Compare versions

Comparing version 2.0.3 to 2.0.4

797

dist/media-processor.es.js

@@ -1,7 +0,6 @@

var V = Object.defineProperty;
var Y = (t, e, r) => e in t ? V(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
var a = (t, e, r) => (Y(t, typeof e != "symbol" ? e + "" : e, r), r);
function ve() {
function Ie() {
return new Promise((t, e) => {
typeof MediaStreamTrackProcessor > "u" || typeof MediaStreamTrackGenerator > "u" ? e("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media.") : t();
typeof MediaStreamTrackProcessor > "u" || typeof MediaStreamTrackGenerator > "u" ? e(
"Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."
) : t();
});

@@ -11,6 +10,7 @@ }

}
a(l, "updates", {
l.updates = {
transformer_new: "New transformer",
transformer_null: "Null transformer"
}), a(l, "errors", {
};
l.errors = {
transformer_none: "No transformers provided",

@@ -22,39 +22,42 @@ transformer_start: "Cannot start transformer",

writable_null: "Writable is null"
});
const h = /* @__PURE__ */ new WeakMap(), E = /* @__PURE__ */ new WeakMap(), y = /* @__PURE__ */ new WeakMap(), O = Symbol("anyProducer"), U = Promise.resolve(), k = Symbol("listenerAdded"), A = Symbol("listenerRemoved");
let x = !1;
function g(t) {
};
function j(t) {
return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
}
const f = /* @__PURE__ */ new WeakMap(), T = /* @__PURE__ */ new WeakMap(), g = /* @__PURE__ */ new WeakMap(), C = Symbol("anyProducer"), U = Promise.resolve(), S = Symbol("listenerAdded"), R = Symbol("listenerRemoved");
let A = !1;
function p(t) {
if (typeof t != "string" && typeof t != "symbol")
throw new TypeError("eventName must be a string or a symbol");
}
function T(t) {
function b(t) {
if (typeof t != "function")
throw new TypeError("listener must be a function");
}
function _(t, e) {
const r = E.get(t);
function m(t, e) {
const r = T.get(t);
return r.has(e) || r.set(e, /* @__PURE__ */ new Set()), r.get(e);
}
function b(t, e) {
const r = typeof e == "string" || typeof e == "symbol" ? e : O, s = y.get(t);
function _(t, e) {
const r = typeof e == "string" || typeof e == "symbol" ? e : C, s = g.get(t);
return s.has(r) || s.set(r, /* @__PURE__ */ new Set()), s.get(r);
}
function q(t, e, r) {
const s = y.get(t);
function B(t, e, r) {
const s = g.get(t);
if (s.has(e))
for (const o of s.get(e))
o.enqueue(r);
if (s.has(O)) {
const o = Promise.all([e, r]);
for (const i of s.get(O))
i.enqueue(o);
for (const i of s.get(e))
i.enqueue(r);
if (s.has(C)) {
const i = Promise.all([e, r]);
for (const n of s.get(C))
n.enqueue(i);
}
}
function $(t, e) {
function D(t, e) {
e = Array.isArray(e) ? e : [e];
let r = !1, s = () => {
}, o = [];
const i = {
enqueue(n) {
o.push(n), s();
}, i = [];
const n = {
enqueue(o) {
i.push(o), s();
},

@@ -65,18 +68,18 @@ finish() {

};
for (const n of e)
b(t, n).add(i);
for (const o of e)
_(t, o).add(n);
return {
async next() {
return o ? o.length === 0 ? r ? (o = void 0, this.next()) : (await new Promise((n) => {
s = n;
return i ? i.length === 0 ? r ? (i = void 0, this.next()) : (await new Promise((o) => {
s = o;
}), this.next()) : {
done: !1,
value: await o.shift()
value: await i.shift()
} : { done: !0 };
},
async return(n) {
o = void 0;
for (const c of e)
b(t, c).delete(i);
return s(), arguments.length > 0 ? { done: !0, value: await n } : { done: !0 };
async return(o) {
i = void 0;
for (const a of e)
_(t, a).delete(n);
return s(), arguments.length > 0 ? { done: !0, value: await o } : { done: !0 };
},

@@ -88,25 +91,25 @@ [Symbol.asyncIterator]() {

}
function H(t) {
function $(t) {
if (t === void 0)
return Q;
return G;
if (!Array.isArray(t))
throw new TypeError("`methodNames` must be an array of strings");
for (const e of t)
if (!Q.includes(e))
if (!G.includes(e))
throw typeof e != "string" ? new TypeError("`methodNames` element must be a string") : new Error(`${e} is not Emittery method`);
return t;
}
const I = (t) => t === k || t === A;
class m {
const M = (t) => t === S || t === R;
class d {
static mixin(e, r) {
return r = H(r), (s) => {
return r = $(r), (s) => {
if (typeof s != "function")
throw new TypeError("`target` must be function");
for (const n of r)
if (s.prototype[n] !== void 0)
throw new Error(`The property \`${n}\` already exists on \`target\``);
function o() {
for (const o of r)
if (s.prototype[o] !== void 0)
throw new Error(`The property \`${o}\` already exists on \`target\``);
function i() {
return Object.defineProperty(this, e, {
enumerable: !1,
value: new m()
value: new d()
}), this[e];

@@ -116,11 +119,11 @@ }

enumerable: !1,
get: o
get: i
});
const i = (n) => function(...c) {
return this[e][n](...c);
const n = (o) => function(...a) {
return this[e][o](...a);
};
for (const n of r)
Object.defineProperty(s.prototype, n, {
for (const o of r)
Object.defineProperty(s.prototype, o, {
enumerable: !1,
value: i(n)
value: n(o)
});

@@ -132,40 +135,40 @@ return s;

if (typeof process != "object")
return x;
return A;
const { env: e } = process || { env: {} };
return e.DEBUG === "emittery" || e.DEBUG === "*" || x;
return e.DEBUG === "emittery" || e.DEBUG === "*" || A;
}
static set isDebugEnabled(e) {
x = e;
A = e;
}
constructor(e = {}) {
h.set(this, /* @__PURE__ */ new Set()), E.set(this, /* @__PURE__ */ new Map()), y.set(this, /* @__PURE__ */ new Map()), this.debug = e.debug || {}, this.debug.enabled === void 0 && (this.debug.enabled = !1), this.debug.logger || (this.debug.logger = (r, s, o, i) => {
f.set(this, /* @__PURE__ */ new Set()), T.set(this, /* @__PURE__ */ new Map()), g.set(this, /* @__PURE__ */ new Map()), this.debug = e.debug || {}, this.debug.enabled === void 0 && (this.debug.enabled = !1), this.debug.logger || (this.debug.logger = (r, s, i, n) => {
try {
i = JSON.stringify(i);
n = JSON.stringify(n);
} catch {
i = `Object with the following keys failed to stringify: ${Object.keys(i).join(",")}`;
n = `Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`;
}
typeof o == "symbol" && (o = o.toString());
const n = new Date(), c = `${n.getHours()}:${n.getMinutes()}:${n.getSeconds()}.${n.getMilliseconds()}`;
console.log(`[${c}][emittery:${r}][${s}] Event Name: ${o}
data: ${i}`);
typeof i == "symbol" && (i = i.toString());
const o = /* @__PURE__ */ new Date(), a = `${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;
console.log(`[${a}][emittery:${r}][${s}] Event Name: ${i}
data: ${n}`);
});
}
logIfDebugEnabled(e, r, s) {
(m.isDebugEnabled || this.debug.enabled) && this.debug.logger(e, this.debug.name, r, s);
(d.isDebugEnabled || this.debug.enabled) && this.debug.logger(e, this.debug.name, r, s);
}
on(e, r) {
T(r), e = Array.isArray(e) ? e : [e];
b(r), e = Array.isArray(e) ? e : [e];
for (const s of e)
g(s), _(this, s).add(r), this.logIfDebugEnabled("subscribe", s, void 0), I(s) || this.emit(k, { eventName: s, listener: r });
p(s), m(this, s).add(r), this.logIfDebugEnabled("subscribe", s, void 0), M(s) || this.emit(S, { eventName: s, listener: r });
return this.off.bind(this, e, r);
}
off(e, r) {
T(r), e = Array.isArray(e) ? e : [e];
b(r), e = Array.isArray(e) ? e : [e];
for (const s of e)
g(s), _(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(A, { eventName: s, listener: r });
p(s), m(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), M(s) || this.emit(R, { eventName: s, listener: r });
}
once(e) {
return new Promise((r) => {
const s = this.on(e, (o) => {
s(), r(o);
const s = this.on(e, (i) => {
s(), r(i);
});

@@ -177,16 +180,16 @@ });

for (const r of e)
g(r);
return $(this, e);
p(r);
return D(this, e);
}
async emit(e, r) {
g(e), this.logIfDebugEnabled("emit", e, r), q(this, e, r);
const s = _(this, e), o = h.get(this), i = [...s], n = I(e) ? [] : [...o];
p(e), this.logIfDebugEnabled("emit", e, r), B(this, e, r);
const s = m(this, e), i = f.get(this), n = [...s], o = M(e) ? [] : [...i];
await U, await Promise.all([
...i.map(async (c) => {
if (s.has(c))
return c(r);
...n.map(async (a) => {
if (s.has(a))
return a(r);
}),
...n.map(async (c) => {
if (o.has(c))
return c(e, r);
...o.map(async (a) => {
if (i.has(a))
return a(e, r);
})

@@ -196,18 +199,18 @@ ]);

async emitSerial(e, r) {
g(e), this.logIfDebugEnabled("emitSerial", e, r);
const s = _(this, e), o = h.get(this), i = [...s], n = [...o];
p(e), this.logIfDebugEnabled("emitSerial", e, r);
const s = m(this, e), i = f.get(this), n = [...s], o = [...i];
await U;
for (const c of i)
s.has(c) && await c(r);
for (const c of n)
o.has(c) && await c(e, r);
for (const a of n)
s.has(a) && await a(r);
for (const a of o)
i.has(a) && await a(e, r);
}
onAny(e) {
return T(e), this.logIfDebugEnabled("subscribeAny", void 0, void 0), h.get(this).add(e), this.emit(k, { listener: e }), this.offAny.bind(this, e);
return b(e), this.logIfDebugEnabled("subscribeAny", void 0, void 0), f.get(this).add(e), this.emit(S, { listener: e }), this.offAny.bind(this, e);
}
anyEvent() {
return $(this);
return D(this);
}
offAny(e) {
T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(A, { listener: e }), h.get(this).delete(e);
b(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(R, { listener: e }), f.get(this).delete(e);
}

@@ -218,14 +221,14 @@ clearListeners(e) {

if (this.logIfDebugEnabled("clear", r, void 0), typeof r == "string" || typeof r == "symbol") {
_(this, r).clear();
const s = b(this, r);
for (const o of s)
o.finish();
m(this, r).clear();
const s = _(this, r);
for (const i of s)
i.finish();
s.clear();
} else {
h.get(this).clear();
for (const s of E.get(this).values())
f.get(this).clear();
for (const s of T.get(this).values())
s.clear();
for (const s of y.get(this).values()) {
for (const o of s)
o.finish();
for (const s of g.get(this).values()) {
for (const i of s)
i.finish();
s.clear();

@@ -240,10 +243,10 @@ }

if (typeof s == "string") {
r += h.get(this).size + _(this, s).size + b(this, s).size + b(this).size;
r += f.get(this).size + m(this, s).size + _(this, s).size + _(this).size;
continue;
}
typeof s < "u" && g(s), r += h.get(this).size;
for (const o of E.get(this).values())
r += o.size;
for (const o of y.get(this).values())
r += o.size;
typeof s < "u" && p(s), r += f.get(this).size;
for (const i of T.get(this).values())
r += i.size;
for (const i of g.get(this).values())
r += i.size;
}

@@ -255,3 +258,3 @@ return r;

throw new TypeError("`target` must be an object");
r = H(r);
r = $(r);
for (const s of r) {

@@ -267,5 +270,5 @@ if (e[s] !== void 0)

}
const Q = Object.getOwnPropertyNames(m.prototype).filter((t) => t !== "constructor");
Object.defineProperty(m, "listenerAdded", {
value: k,
const G = Object.getOwnPropertyNames(d.prototype).filter((t) => t !== "constructor");
Object.defineProperty(d, "listenerAdded", {
value: S,
writable: !1,

@@ -275,4 +278,4 @@ enumerable: !0,

});
Object.defineProperty(m, "listenerRemoved", {
value: A,
Object.defineProperty(d, "listenerRemoved", {
value: R,
writable: !1,

@@ -282,8 +285,9 @@ enumerable: !0,

});
var L = m;
function J(t) {
var Y = d;
const v = /* @__PURE__ */ j(Y);
function q(t) {
return typeof t == "object" && t !== null && "message" in t && typeof t.message == "string";
}
function X(t) {
if (J(t))
function J(t) {
if (q(t))
return t;

@@ -296,26 +300,26 @@ try {

}
function v(t) {
return X(t).message;
function I(t) {
return J(t).message;
}
var Z = Object.defineProperty, K = (t, e, r) => e in t ? Z(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r, N = (t, e, r) => (K(t, typeof e != "symbol" ? e + "" : e, r), r), ee = /* @__PURE__ */ ((t) => (t.automation = "automation", t.test = "test", t.vbc = "vbc", t.video = "video", t.voice = "voice", t))(ee || {});
const re = "hlg.tokbox.com/prod/logging/vcp_webrtc", te = "https://", se = 1e4;
let S;
const oe = new Uint8Array(16);
var K = Object.defineProperty, X = (t, e, r) => e in t ? K(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r, Z = (t, e, r) => (X(t, typeof e != "symbol" ? e + "" : e, r), r), N = /* @__PURE__ */ ((t) => (t.automation = "automation", t.test = "test", t.vbc = "vbc", t.video = "video", t.voice = "voice", t))(N || {});
const ee = "hlg.tokbox.com/prod/logging/vcp_webrtc", re = "https://", te = 1e4;
let w;
const se = new Uint8Array(16);
function ie() {
if (!S && (S = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !S))
if (!w && (w = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !w))
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
return S(oe);
return w(se);
}
const f = [];
const c = [];
for (let t = 0; t < 256; ++t)
f.push((t + 256).toString(16).slice(1));
c.push((t + 256).toString(16).slice(1));
function ne(t, e = 0) {
return (f[t[e + 0]] + f[t[e + 1]] + f[t[e + 2]] + f[t[e + 3]] + "-" + f[t[e + 4]] + f[t[e + 5]] + "-" + f[t[e + 6]] + f[t[e + 7]] + "-" + f[t[e + 8]] + f[t[e + 9]] + "-" + f[t[e + 10]] + f[t[e + 11]] + f[t[e + 12]] + f[t[e + 13]] + f[t[e + 14]] + f[t[e + 15]]).toLowerCase();
return (c[t[e + 0]] + c[t[e + 1]] + c[t[e + 2]] + c[t[e + 3]] + "-" + c[t[e + 4]] + c[t[e + 5]] + "-" + c[t[e + 6]] + c[t[e + 7]] + "-" + c[t[e + 8]] + c[t[e + 9]] + "-" + c[t[e + 10]] + c[t[e + 11]] + c[t[e + 12]] + c[t[e + 13]] + c[t[e + 14]] + c[t[e + 15]]).toLowerCase();
}
const ae = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), z = {
randomUUID: ae
const oe = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), H = {
randomUUID: oe
};
function ce(t, e, r) {
if (z.randomUUID && !e && !t)
return z.randomUUID();
function ae(t, e, r) {
if (H.randomUUID && !e && !t)
return H.randomUUID();
t = t || {};

@@ -325,4 +329,4 @@ const s = t.random || (t.rng || ie)();

r = r || 0;
for (let o = 0; o < 16; ++o)
e[r + o] = s[o];
for (let i = 0; i < 16; ++i)
e[r + i] = s[i];
return e;

@@ -332,3 +336,3 @@ }

}
function W(t, e) {
function F(t, e) {
globalThis.vonage || (globalThis.vonage = {}), globalThis.vonage.workerizer || (globalThis.vonage.workerizer = {});

@@ -338,16 +342,16 @@ let r = globalThis.vonage.workerizer;

}
const p = W(
const h = F(
"globals",
{}
);
var d = /* @__PURE__ */ ((t) => (t.INIT = "INIT", t.FORWARD = "FORWARD", t.TERMINATE = "TERMINATE", t.GLOBALS_SYNC = "GLOBALS_SYNC", t))(d || {});
function j(t) {
return [ImageBitmap, ReadableStream, WritableStream].some((e) => t instanceof e);
var u = /* @__PURE__ */ ((t) => (t.INIT = "INIT", t.FORWARD = "FORWARD", t.TERMINATE = "TERMINATE", t.GLOBALS_SYNC = "GLOBALS_SYNC", t))(u || {});
function z(t) {
return [ImageBitmap, ReadableStream, WritableStream].some((r) => t instanceof r);
}
let fe = 0;
function le(t, e, r, s, o) {
const i = fe++;
let ce = 0;
function le(t, e, r, s, i) {
const n = ce++;
return t.postMessage(
{
id: i,
id: n,
type: e,

@@ -357,9 +361,9 @@ functionName: r,

},
s.filter((n) => j(n))
), new Promise((n) => {
o == null || o.set(i, n);
s.filter((a) => z(a))
), new Promise((a) => {
i == null || i.set(n, a);
});
}
function w(t, e) {
const { id: r, type: s } = t, o = Array.isArray(e) ? e : [e];
function y(t, e) {
const { id: r, type: s } = t, i = Array.isArray(e) ? e : [e];
postMessage(

@@ -371,22 +375,22 @@ {

},
o.filter((i) => j(i))
i.filter((n) => z(n))
);
}
const G = W("workerized", {});
function B() {
const Q = F("workerized", {});
function V() {
return typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope;
}
async function ue() {
if (B())
w({ type: d.GLOBALS_SYNC }, p);
async function fe() {
if (V())
y({ type: u.GLOBALS_SYNC }, h);
else {
const t = [];
for (const e in G) {
const { worker: r, resolvers: s } = G[e].workerContext;
for (const e in Q) {
const { worker: r, resolvers: s } = Q[e].workerContext;
r && t.push(
le(
r,
d.GLOBALS_SYNC,
u.GLOBALS_SYNC,
"",
[p],
[h],
s

@@ -416,16 +420,16 @@ )

throw `undefined function [${r}] in class ${e.instance.constructor.workerId}`;
w(t, await e.instance[r](...s != null ? s : []));
y(t, await e.instance[r](...s ?? []));
}
const pe = W("registeredWorkers", {});
const ue = F("registeredWorkers", {});
function de(t, e) {
if (!t.args)
throw "Missing className while initializing worker";
const [r, s] = t.args, o = pe[r];
if (o)
e.instance = new o(t.args.slice(1));
const [r, s] = t.args, i = ue[r];
if (i)
e.instance = new i(t.args.slice(1));
else
throw `unknown worker class ${r}`;
P(s, p), w(t, typeof e.instance !== void 0);
P(s, h), y(t, typeof e.instance !== void 0);
}
async function me(t, e) {
async function pe(t, e) {
const { args: r } = t;

@@ -435,10 +439,10 @@ if (!e.instance)

let s;
e.instance.terminate && (s = await e.instance.terminate(...r != null ? r : [])), w(t, s);
e.instance.terminate && (s = await e.instance.terminate(...r ?? [])), y(t, s);
}
function ge(t) {
function me(t) {
if (!t.args)
throw "Missing globals while syncing";
P(t.args[0], p), w(t, {});
P(t.args[0], h), y(t, {});
}
function _e() {
function ge() {
const t = {};

@@ -448,13 +452,13 @@ onmessage = async (e) => {

switch (r.type) {
case d.INIT:
case u.INIT:
de(r, t);
break;
case d.FORWARD:
case u.FORWARD:
he(r, t);
break;
case d.TERMINATE:
me(r, t);
case u.TERMINATE:
pe(r, t);
break;
case d.GLOBALS_SYNC:
ge(r);
case u.GLOBALS_SYNC:
me(r);
break;

@@ -464,42 +468,42 @@ }

}
B() && _e();
function ye(t, e) {
return p[t] || (p[t] = e), [
() => p[t],
V() && ge();
function _e(t, e) {
return h[t] || (h[t] = e), [
() => h[t],
async (r) => {
p[t] = r, await ue();
h[t] = r, await fe();
}
];
}
function be(t, e) {
return ye(t, e);
function ye(t, e) {
return _e(t, e);
}
const [we, Te] = be("metadata");
function Ce(t) {
Te(t);
const [be, we] = ye("metadata");
function xe(t) {
we(t);
}
function C() {
return we();
function x() {
return be();
}
class D {
constructor(e) {
N(this, "uuid", ce()), this.config = e;
class L {
constructor(e, r) {
Z(this, "uuid"), this.config = e, this.uuid = r ?? ae();
}
async send(e) {
var r, s, o;
const { appId: i, sourceType: n } = (r = C()) != null ? r : {};
if (!i || !n)
var r, s, i;
const { appId: n, sourceType: o } = (r = x()) != null ? r : {};
if (!n || !o)
return "metadata missing";
const c = new AbortController(), u = setTimeout(() => c.abort(), se);
return await ((o = (s = this.config) == null ? void 0 : s.fetch) != null ? o : fetch)(this.getUrl(), {
const a = new AbortController(), k = setTimeout(() => a.abort(), te);
return await ((i = (s = this.config) == null ? void 0 : s.fetch) != null ? i : fetch)(this.getUrl(), {
method: "POST",
headers: this.getHeaders(),
body: JSON.stringify(this.buildReport(e)),
signal: c.signal
}), clearTimeout(u), "success";
signal: a.signal
}), clearTimeout(k), "success";
}
getUrl() {
var e;
let r = (e = C().proxyUrl) != null ? e : te;
return r += (r.at(-1) === "/" ? "" : "/") + re, r;
let r = (e = x().proxyUrl) != null ? e : re;
return r += (r.at(-1) === "/" ? "" : "/") + ee, r;
}

@@ -512,3 +516,3 @@ getHeaders() {

buildReport(e) {
const r = C();
const r = x();
return {

@@ -524,10 +528,6 @@ guid: this.uuid,

}
const R = "2.0.3";
class Se {
constructor(e) {
a(this, "frameTransformedCount", 0);
a(this, "frameFromSourceCount", 0);
a(this, "startAt", 0);
a(this, "reporter");
this.config = e, this.reporter = new D(e);
const E = "2.0.4";
class Te {
constructor(e, r) {
this.config = e, this.frameTransformedCount = 0, this.frameFromSourceCount = 0, this.startAt = 0, this.reporter = new L(e, r);
}

@@ -538,14 +538,14 @@ async onFrameFromSource() {

get fps() {
const { startAt: e, frameFromSourceCount: r } = this, o = (Date.now() - e) / 1e3;
return r / o;
const { startAt: e, frameFromSourceCount: r } = this, i = (Date.now() - e) / 1e3;
return r / i;
}
async onFrameTransformed(e = {}, r = !1) {
this.startAt === 0 && (this.startAt = Date.now()), this.frameTransformedCount++;
const { startAt: s, frameTransformedCount: o, frameFromSourceCount: i } = this, n = Date.now(), c = (n - s) / 1e3, u = o / c, M = i / c;
return r || this.frameTransformedCount >= this.config.loggingIntervalFrameCount ? (this.frameFromSourceCount = 0, this.frameTransformedCount = 0, this.startAt = n, this.reporter.config = this.config, this.reporter.send({
const { startAt: s, frameTransformedCount: i, frameFromSourceCount: n } = this, o = Date.now(), a = (o - s) / 1e3, k = i / a, W = n / a;
return r || this.frameTransformedCount >= this.config.loggingIntervalFrameCount ? (this.frameFromSourceCount = 0, this.frameTransformedCount = 0, this.startAt = o, this.reporter.config = this.config, this.reporter.send({
...this.config.report,
variation: "QoS",
fps: M,
transformedFps: u,
framesTransformed: o,
fps: W,
transformedFps: k,
framesTransformed: i,
...e

@@ -555,64 +555,61 @@ })) : "success";

}
var Ee = /* @__PURE__ */ ((t) => (t.FPS_DROP = "fps_drop", t))(Ee || {}), Re = /* @__PURE__ */ ((t) => (t.start = "start", t.transform = "transform", t.flush = "flush", t))(Re || {}), F = /* @__PURE__ */ ((t) => (t.pipeline_ended = "pipeline_ended", t.pipeline_ended_with_error = "pipeline_ended_with_error", t.pipeline_started = "pipeline_started", t.pipeline_started_with_error = "pipeline_started_with_error", t.pipeline_restarted = "pipeline_restarted", t.pipeline_restarted_with_error = "pipeline_restarted_with_error", t))(F || {});
const ke = 500, Ae = 0.8;
class Pe extends L {
constructor(r, s) {
super();
a(this, "reporter_", new D());
a(this, "reporterQos_", new Se({
loggingIntervalFrameCount: ke,
var Ee = /* @__PURE__ */ ((t) => (t.FPS_DROP = "fps_drop", t))(Ee || {}), Se = /* @__PURE__ */ ((t) => (t.start = "start", t.transform = "transform", t.flush = "flush", t))(Se || {}), O = /* @__PURE__ */ ((t) => (t.pipeline_ended = "pipeline_ended", t.pipeline_ended_with_error = "pipeline_ended_with_error", t.pipeline_started = "pipeline_started", t.pipeline_started_with_error = "pipeline_started_with_error", t.pipeline_restarted = "pipeline_restarted", t.pipeline_restarted_with_error = "pipeline_restarted_with_error", t))(O || {});
const Re = 500, Pe = 0.8;
class ke extends v {
constructor(e, r) {
super(), this.reporter_ = new L(), this.reporterQos_ = new Te({
loggingIntervalFrameCount: Re,
report: {
version: R
version: E
}
}));
a(this, "transformerType_");
a(this, "transformer_");
a(this, "shouldStop_");
a(this, "isFlashed_");
a(this, "mediaTransformerQosReportStartTimestamp_");
a(this, "videoHeight_");
a(this, "videoWidth_");
a(this, "trackExpectedRate_");
a(this, "index_");
a(this, "controller_");
this.index_ = s, this.transformer_ = r, this.shouldStop_ = !1, this.isFlashed_ = !1, this.mediaTransformerQosReportStartTimestamp_ = 0, this.videoHeight_ = 0, this.videoWidth_ = 0, this.trackExpectedRate_ = -1, this.transformerType_ = "Custom", "getTransformerType" in r && (this.transformerType_ = r.getTransformerType()), this.report({
}), this.index_ = r, this.transformer_ = e, this.shouldStop_ = !1, this.isFlashed_ = !1, this.mediaTransformerQosReportStartTimestamp_ = 0, this.videoHeight_ = 0, this.videoWidth_ = 0, this.trackExpectedRate_ = -1, this.transformerType_ = "Custom", "getTransformerType" in e && (this.transformerType_ = e.getTransformerType()), this.report({
variation: "Create"
});
}
setTrackExpectedRate(r) {
this.trackExpectedRate_ = r;
setTrackExpectedRate(e) {
this.trackExpectedRate_ = e;
}
async start(r) {
if (this.controller_ = r, this.transformer_ && typeof this.transformer_.start == "function")
async start(e) {
if (this.controller_ = e, this.transformer_ && typeof this.transformer_.start == "function")
try {
await this.transformer_.start(r);
} catch (s) {
await this.transformer_.start(e);
} catch (r) {
this.report({
message: l.errors.transformer_start,
variation: "Error",
error: v(s)
error: I(r)
});
const o = { eventMetaData: { transformerIndex: this.index_ }, error: s, function: "start" };
this.emit("error", o);
const s = {
eventMetaData: { transformerIndex: this.index_ },
error: r,
function: "start"
/* start */
};
this.emit("error", s);
}
}
async transform(r, s) {
var o, i, n, c;
if (this.mediaTransformerQosReportStartTimestamp_ === 0 && (this.mediaTransformerQosReportStartTimestamp_ = Date.now()), r instanceof VideoFrame && (this.videoHeight_ = (o = r == null ? void 0 : r.displayHeight) != null ? o : 0, this.videoWidth_ = (i = r == null ? void 0 : r.displayWidth) != null ? i : 0), this.reporterQos_.onFrameFromSource(), this.transformer_)
async transform(e, r) {
var s, i;
if (this.mediaTransformerQosReportStartTimestamp_ === 0 && (this.mediaTransformerQosReportStartTimestamp_ = Date.now()), e instanceof VideoFrame && (this.videoHeight_ = (e == null ? void 0 : e.displayHeight) ?? 0, this.videoWidth_ = (e == null ? void 0 : e.displayWidth) ?? 0), this.reporterQos_.onFrameFromSource(), this.transformer_)
if (this.shouldStop_)
console.warn("[Pipeline] flush from transform"), r.close(), this.flush(s), s.terminate();
console.warn("[Pipeline] flush from transform"), e.close(), this.flush(r), r.terminate();
else {
try {
await ((c = (n = this.transformer_).transform) == null ? void 0 : c.call(n, r, s)), this.reportQos();
} catch (u) {
await ((i = (s = this.transformer_).transform) == null ? void 0 : i.call(s, e, r)), this.reportQos();
} catch (n) {
this.report({
message: l.errors.transformer_transform,
variation: "Error",
error: v(u)
error: I(n)
});
const M = { eventMetaData: { transformerIndex: this.index_ }, error: u, function: "transform" };
this.emit("error", M);
const o = {
eventMetaData: { transformerIndex: this.index_ },
error: n,
function: "transform"
/* transform */
};
this.emit("error", o);
}
if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Ae > this.reporterQos_.fps) {
const u = {
if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Pe > this.reporterQos_.fps) {
const n = {
eventMetaData: {

@@ -627,19 +624,24 @@ transformerIndex: this.index_

};
this.emit("warn", u);
this.emit("warn", n);
}
}
}
async flush(r) {
async flush(e) {
if (this.transformer_ && typeof this.transformer_.flush == "function" && !this.isFlashed_) {
this.isFlashed_ = !0;
try {
await this.transformer_.flush(r);
} catch (s) {
await this.transformer_.flush(e);
} catch (r) {
this.report({
message: l.errors.transformer_flush,
variation: "Error",
error: v(s)
error: I(r)
});
const o = { eventMetaData: { transformerIndex: this.index_ }, error: s, function: "flush" };
this.emit("error", o);
const s = {
eventMetaData: { transformerIndex: this.index_ },
error: r,
function: "flush"
/* flush */
};
this.emit("error", s);
}

@@ -654,43 +656,43 @@ }

}
report(r) {
report(e) {
this.reporter_.send({
version: R,
version: E,
action: "MediaTransformer",
transformerType: this.transformerType_,
...r
...e
});
}
reportQos(r = !1) {
reportQos(e = !1) {
this.reporterQos_.config = {
...this.reporterQos_.config
}, this.reporterQos_.onFrameTransformed({
version: R,
action: "MediaTransformer",
transformerType: this.transformerType_,
videoWidth: this.videoWidth_,
videoHeight: this.videoHeight_
}, r);
}, this.reporterQos_.onFrameTransformed(
{
version: E,
action: "MediaTransformer",
transformerType: this.transformerType_,
videoWidth: this.videoWidth_,
videoHeight: this.videoHeight_
},
e
);
}
}
class Me extends L {
constructor(r) {
super();
a(this, "transformers_");
a(this, "trackExpectedRate_");
this.transformers_ = [], this.trackExpectedRate_ = -1;
for (let s = 0; s < r.length; s++) {
let o = new Pe(r[s], s);
o.on("error", (i) => {
class Ae extends v {
constructor(e) {
super(), this.transformers_ = [], this.trackExpectedRate_ = -1;
for (let r = 0; r < e.length; r++) {
let s = new ke(e[r], r);
s.on("error", (i) => {
this.emit("error", i);
}), o.on("warn", (i) => {
}), s.on("warn", (i) => {
this.emit("warn", i);
}), this.transformers_.push(o);
}), this.transformers_.push(s);
}
}
setTrackExpectedRate(r) {
this.trackExpectedRate_ = r;
for (let s of this.transformers_)
s.setTrackExpectedRate(this.trackExpectedRate_);
setTrackExpectedRate(e) {
this.trackExpectedRate_ = e;
for (let r of this.transformers_)
r.setTrackExpectedRate(this.trackExpectedRate_);
}
async start(r, s) {
async start(e, r) {
if (!this.transformers_ || this.transformers_.length === 0) {

@@ -701,47 +703,88 @@ console.log("[Pipeline] No transformers.");

try {
let o = r;
let s = e;
for (let i of this.transformers_)
r = r.pipeThrough(new TransformStream(i));
r.pipeTo(s).then(async () => {
console.log("[Pipeline] Setup."), await s.abort(), await o.cancel(), this.emit("pipelineInfo", "pipeline_ended");
e = e.pipeThrough(
new TransformStream(i)
);
e.pipeTo(r).then(async () => {
console.log("[Pipeline] Setup."), await r.abort(), await s.cancel(), this.emit(
"pipelineInfo",
"pipeline_ended"
/* pipeline_ended */
);
}).catch(async (i) => {
r.cancel().then(() => {
console.log("[Pipeline] Shutting down streams after abort.");
e.cancel().then(() => {
console.log(
"[Pipeline] Shutting down streams after abort."
);
}).catch((n) => {
console.error("[Pipeline] Error from stream transform:", n);
}), await s.abort(i), await o.cancel(i), this.emit("pipelineInfo", "pipeline_ended_with_error");
console.error(
"[Pipeline] Error from stream transform:",
n
);
}), await r.abort(i), await s.cancel(i), this.emit(
"pipelineInfo",
"pipeline_ended_with_error"
/* pipeline_ended_with_error */
);
});
} catch {
this.emit("pipelineInfo", "pipeline_started_with_error"), this.destroy();
this.emit(
"pipelineInfo",
"pipeline_started_with_error"
/* pipeline_started_with_error */
), this.destroy();
return;
}
this.emit("pipelineInfo", "pipeline_started"), console.log("[Pipeline] Pipeline started.");
this.emit(
"pipelineInfo",
"pipeline_started"
/* pipeline_started */
), console.log("[Pipeline] Pipeline started.");
}
async destroy() {
console.log("[Pipeline] Destroying Pipeline.");
for (let r of this.transformers_)
r.stop();
for (let e of this.transformers_)
e.stop();
}
}
class Oe extends L {
class Ce extends v {
constructor() {
super();
a(this, "reporter_");
a(this, "pipeline_");
a(this, "transformers_");
a(this, "readable_");
a(this, "writable_");
a(this, "trackExpectedRate_");
this.reporter_ = new D(), this.trackExpectedRate_ = -1, this.report({
super(), this.reporter_ = new L(), this.trackExpectedRate_ = -1, this.report({
variation: "Create"
});
}
setTrackExpectedRate(r) {
this.trackExpectedRate_ = r, this.pipeline_ && this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_);
/**
* Sets the expected rate of the track per second.
* The media processor will use this number for calculating drops in the rate.
* This could happen when the transformation will take more time than expected.
* This will not cause an error, just warning to the client.
* Mostly:
* Video: 30 frames per second
* Audio: 50 audio data per second for OPUS
* In case of increased frame dropping rate a warning will be emitted according to info [here](/docs/intro#errors-and-warnings-listener).
* ***This is an optional method.***
* @param trackExpectedRate - number holds the predicted track rate.
*/
setTrackExpectedRate(e) {
this.trackExpectedRate_ = e, this.pipeline_ && this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_);
}
transform(r, s) {
return this.readable_ = r, this.writable_ = s, this.transformInternal();
/**
* Starts running the tranformation logic performed by the media processor instance.
* When running an instance of this class on a Web worker thread the call for this function should be made by the user. See example [here](/docs/intro#webworker-code).
* When running an instance of this class on the application main thread there is no need to call this method given it will be called by the `MediaProcessorConnector` instance.
*
* @param readable Readable stream associated to the media source being processed.
* @param writable Writable stream associated to the resulting media once processed.
*
* @returns
*/
transform(e, r) {
return this.readable_ = e, this.writable_ = r, this.transformInternal();
}
/**
* @private
*/
transformInternal() {
return new Promise(async (r, s) => {
return new Promise(async (e, r) => {
if (!this.transformers_ || this.transformers_.length === 0) {

@@ -751,3 +794,3 @@ this.report({

variation: "Error"
}), s("[MediaProcessor] Need to set transformers.");
}), r("[MediaProcessor] Need to set transformers.");
return;

@@ -759,3 +802,3 @@ }

message: l.errors.readable_null
}), s("[MediaProcessor] Readable is null.");
}), r("[MediaProcessor] Readable is null.");
return;

@@ -767,7 +810,7 @@ }

message: l.errors.writable_null
}), s("[MediaProcessor] Writable is null.");
}), r("[MediaProcessor] Writable is null.");
return;
}
let o = !1;
this.pipeline_ && (o = !0, this.pipeline_.clearListeners(), this.pipeline_.destroy()), this.pipeline_ = new Me(this.transformers_), this.pipeline_.on("warn", (i) => {
let s = !1;
this.pipeline_ && (s = !0, this.pipeline_.clearListeners(), this.pipeline_.destroy()), this.pipeline_ = new Ae(this.transformers_), this.pipeline_.on("warn", (i) => {
this.emit("warn", i);

@@ -777,33 +820,43 @@ }), this.pipeline_.on("error", (i) => {

}), this.pipeline_.on("pipelineInfo", (i) => {
o && (i === "pipeline_started" ? i = F.pipeline_restarted : i === "pipeline_started_with_error" && (i = F.pipeline_restarted_with_error)), this.emit("pipelineInfo", i);
s && (i === "pipeline_started" ? i = O.pipeline_restarted : i === "pipeline_started_with_error" && (i = O.pipeline_restarted_with_error)), this.emit("pipelineInfo", i);
}), this.trackExpectedRate_ != -1 && this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_), this.pipeline_.start(this.readable_, this.writable_).then(() => {
r();
e();
}).catch((i) => {
s(i);
r(i);
});
});
}
setTransformers(r) {
/**
* Sets an array of transfromer instances that will be hold and ran by the media processor instance.
* See example [here](/docs/intro#main-code)
*
* @param transformers An array of transformer instances.
*
* @returns
*/
setTransformers(e) {
return this.report({
variation: "Update",
message: l.updates.transformer_new
}), this.transformers_ = r, this.readable_ && this.writable_ ? this.transformInternal() : Promise.resolve();
}), this.transformers_ = e, this.readable_ && this.writable_ ? this.transformInternal() : Promise.resolve();
}
/**
* Stops running the tranformation logic performed by the media processor instance.
* @returns
*/
destroy() {
return new Promise(async (r) => {
this.pipeline_ && this.pipeline_.destroy(), this.report({ variation: "Delete" }), r();
return new Promise(async (e) => {
this.pipeline_ && this.pipeline_.destroy(), this.report({ variation: "Delete" }), e();
});
}
report(r) {
report(e) {
this.reporter_.send({
version: R,
version: E,
action: "MediaProcessor",
...r
...e
});
}
}
class xe {
class Me {
constructor() {
a(this, "processor_");
a(this, "generator_");
this.processor_ = null, this.generator_ = null;

@@ -815,9 +868,17 @@ }

this.processor_ = new MediaStreamTrackProcessor(e);
} catch (o) {
console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${o}`), s(o);
} catch (i) {
console.log(
`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${i}`
), s(i);
}
try {
e.kind === "audio" ? this.generator_ = new MediaStreamTrackGenerator({ kind: "audio" }) : e.kind === "video" ? this.generator_ = new MediaStreamTrackGenerator({ kind: "video" }) : s("kind not supported");
} catch (o) {
console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${o}`), s(o);
e.kind === "audio" ? this.generator_ = new MediaStreamTrackGenerator({
kind: "audio"
}) : e.kind === "video" ? this.generator_ = new MediaStreamTrackGenerator({
kind: "video"
}) : s("kind not supported");
} catch (i) {
console.log(
`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${i}`
), s(i);
}

@@ -837,21 +898,41 @@ r();

}
class Fe {
class Oe {
/**
* - When running insertable streams on the main `MediaProcessorInterface` should be instance of `MediaProcessor` class.
* - When running insertable streams on WebWorker `MediaProcessorInterface` should be instance of bridge calss created by the user. Example can be found [here](/docs/intro.md#using-the-transformer-on-webworker)
* @param vonageMediaProcessor - MediaProcessorInterface.
*/
constructor(e) {
a(this, "insertableStreamHelper_");
a(this, "mediaProcessor_");
this.insertableStreamHelper_ = new xe(), this.mediaProcessor_ = e;
this.insertableStreamHelper_ = new Me(), this.mediaProcessor_ = e;
}
/**
* @private
* Sets the media stream track instance to be processed.
*
* @param track MediaStreamTrack (audio or video) to be processed.
*
* @returns New track to be used.
*/
setTrack(e) {
return new Promise((r, s) => {
this.insertableStreamHelper_.init(e).then(() => {
this.mediaProcessor_.transform(this.insertableStreamHelper_.getReadable(), this.insertableStreamHelper_.getWriteable()).then(() => {
r(this.insertableStreamHelper_.getProccesorTrack());
}).catch((o) => {
s(o);
this.mediaProcessor_.transform(
this.insertableStreamHelper_.getReadable(),
this.insertableStreamHelper_.getWriteable()
).then(() => {
r(
this.insertableStreamHelper_.getProccesorTrack()
);
}).catch((i) => {
s(i);
});
}).catch((o) => {
s(o);
}).catch((i) => {
s(i);
});
});
}
/**
* @private
* Stops the media processing being performed.
*/
destroy() {

@@ -868,11 +949,11 @@ return new Promise((e, r) => {

export {
Re as ErrorFunction,
Oe as MediaProcessor,
Fe as MediaProcessorConnector,
F as PipelineInfoData,
ee as VonageSourceType,
Se as ErrorFunction,
Ce as MediaProcessor,
Oe as MediaProcessorConnector,
O as PipelineInfoData,
N as VonageSourceType,
Ee as WarningType,
C as getVonageMetadata,
ve as isSupported,
Ce as setVonageMetadata
x as getVonageMetadata,
Ie as isSupported,
xe as setVonageMetadata
};

@@ -1,1 +0,1 @@

var V=Object.defineProperty,Y=(e,t,r)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,a=(e,t,r)=>(Y(e,"symbol"!=typeof t?t+"":t,r),r);function ve(){return new Promise(((e,t)=>{typeof MediaStreamTrackProcessor>"u"||typeof MediaStreamTrackGenerator>"u"?t("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."):e()}))}class l{}a(l,"updates",{transformer_new:"New transformer",transformer_null:"Null transformer"}),a(l,"errors",{transformer_none:"No transformers provided",transformer_start:"Cannot start transformer",transformer_transform:"Cannot transform frame",transformer_flush:"Cannot flush transformer",readable_null:"Readable is null",writable_null:"Writable is null"});const h=new WeakMap,E=new WeakMap,y=new WeakMap,O=Symbol("anyProducer"),U=Promise.resolve(),k=Symbol("listenerAdded"),A=Symbol("listenerRemoved");let x=!1;function g(e){if("string"!=typeof e&&"symbol"!=typeof e)throw new TypeError("eventName must be a string or a symbol")}function T(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function _(e,t){const r=E.get(e);return r.has(t)||r.set(t,new Set),r.get(t)}function b(e,t){const r="string"==typeof t||"symbol"==typeof t?t:O,s=y.get(e);return s.has(r)||s.set(r,new Set),s.get(r)}function q(e,t,r){const s=y.get(e);if(s.has(t))for(const e of s.get(t))e.enqueue(r);if(s.has(O)){const e=Promise.all([t,r]);for(const t of s.get(O))t.enqueue(e)}}function $(e,t){t=Array.isArray(t)?t:[t];let r=!1,s=()=>{},o=[];const i={enqueue(e){o.push(e),s()},finish(){r=!0,s()}};for(const r of t)b(e,r).add(i);return{async next(){return o?0===o.length?r?(o=void 0,this.next()):(await new Promise((e=>{s=e})),this.next()):{done:!1,value:await o.shift()}:{done:!0}},async return(r){o=void 0;for(const r of t)b(e,r).delete(i);return s(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function H(e){if(void 0===e)return Q;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!Q.includes(t))throw"string"!=typeof t?new TypeError("`methodNames` element must be a string"):new Error(`${t} is not Emittery method`);return e}const I=e=>e===k||e===A;class m{static mixin(e,t){return t=H(t),r=>{if("function"!=typeof r)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==r.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(r.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new m}),this[e]}});const s=t=>function(...r){return this[e][t](...r)};for(const e of t)Object.defineProperty(r.prototype,e,{enumerable:!1,value:s(e)});return r}}static get isDebugEnabled(){if("object"!=typeof process)return x;const{env:e}=process||{env:{}};return"emittery"===e.DEBUG||"*"===e.DEBUG||x}static set isDebugEnabled(e){x=e}constructor(e={}){h.set(this,new Set),E.set(this,new Map),y.set(this,new Map),this.debug=e.debug||{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,r,s)=>{try{s=JSON.stringify(s)}catch{s=`Object with the following keys failed to stringify: ${Object.keys(s).join(",")}`}"symbol"==typeof r&&(r=r.toString());const o=new Date,i=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${i}][emittery:${e}][${t}] Event Name: ${r}\n\tdata: ${s}`)})}logIfDebugEnabled(e,t,r){(m.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,r)}on(e,t){T(t),e=Array.isArray(e)?e:[e];for(const r of e)g(r),_(this,r).add(t),this.logIfDebugEnabled("subscribe",r,void 0),I(r)||this.emit(k,{eventName:r,listener:t});return this.off.bind(this,e,t)}off(e,t){T(t),e=Array.isArray(e)?e:[e];for(const r of e)g(r),_(this,r).delete(t),this.logIfDebugEnabled("unsubscribe",r,void 0),I(r)||this.emit(A,{eventName:r,listener:t})}once(e){return new Promise((t=>{const r=this.on(e,(e=>{r(),t(e)}))}))}events(e){e=Array.isArray(e)?e:[e];for(const t of e)g(t);return $(this,e)}async emit(e,t){g(e),this.logIfDebugEnabled("emit",e,t),q(this,e,t);const r=_(this,e),s=h.get(this),o=[...r],i=I(e)?[]:[...s];await U,await Promise.all([...o.map((async e=>{if(r.has(e))return e(t)})),...i.map((async r=>{if(s.has(r))return r(e,t)}))])}async emitSerial(e,t){g(e),this.logIfDebugEnabled("emitSerial",e,t);const r=_(this,e),s=h.get(this),o=[...r],i=[...s];await U;for(const e of o)r.has(e)&&await e(t);for(const r of i)s.has(r)&&await r(e,t)}onAny(e){return T(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),h.get(this).add(e),this.emit(k,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return $(this)}offAny(e){T(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),this.emit(A,{listener:e}),h.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),"string"==typeof t||"symbol"==typeof t){_(this,t).clear();const e=b(this,t);for(const t of e)t.finish();e.clear()}else{h.get(this).clear();for(const e of E.get(this).values())e.clear();for(const e of y.get(this).values()){for(const t of e)t.finish();e.clear()}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const r of e)if("string"!=typeof r){typeof r<"u"&&g(r),t+=h.get(this).size;for(const e of E.get(this).values())t+=e.size;for(const e of y.get(this).values())t+=e.size}else t+=h.get(this).size+_(this,r).size+b(this,r).size+b(this).size;return t}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=H(t);for(const r of t){if(void 0!==e[r])throw new Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}}const Q=Object.getOwnPropertyNames(m.prototype).filter((e=>"constructor"!==e));Object.defineProperty(m,"listenerAdded",{value:k,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(m,"listenerRemoved",{value:A,writable:!1,enumerable:!0,configurable:!1});var L=m;function J(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}function X(e){if(J(e))return e;try{return new Error(JSON.stringify(e))}catch{return new Error(String(e))}}function v(e){return X(e).message}var Z=Object.defineProperty,K=(e,t,r)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,N=(e,t,r)=>(K(e,"symbol"!=typeof t?t+"":t,r),r),ee=(e=>(e.automation="automation",e.test="test",e.vbc="vbc",e.video="video",e.voice="voice",e))(ee||{});const re="hlg.tokbox.com/prod/logging/vcp_webrtc",te="https://",se=1e4;let S;const oe=new Uint8Array(16);function ie(){if(!S&&(S=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!S))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return S(oe)}const f=[];for(let e=0;e<256;++e)f.push((e+256).toString(16).slice(1));function ne(e,t=0){return(f[e[t+0]]+f[e[t+1]]+f[e[t+2]]+f[e[t+3]]+"-"+f[e[t+4]]+f[e[t+5]]+"-"+f[e[t+6]]+f[e[t+7]]+"-"+f[e[t+8]]+f[e[t+9]]+"-"+f[e[t+10]]+f[e[t+11]]+f[e[t+12]]+f[e[t+13]]+f[e[t+14]]+f[e[t+15]]).toLowerCase()}const ae=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),z={randomUUID:ae};function ce(e,t,r){if(z.randomUUID&&!t&&!e)return z.randomUUID();const s=(e=e||{}).random||(e.rng||ie)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=s[e];return t}return ne(s)}function W(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[e]||(r[e]=t),r[e]}const p=W("globals",{});var d=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e))(d||{});function j(e){return[ImageBitmap,ReadableStream,WritableStream].some((t=>e instanceof t))}let fe=0;function le(e,t,r,s,o){const i=fe++;return e.postMessage({id:i,type:t,functionName:r,args:s},s.filter((e=>j(e)))),new Promise((e=>{null==o||o.set(i,e)}))}function w(e,t){const{id:r,type:s}=e,o=Array.isArray(t)?t:[t];postMessage({id:r,type:s,result:t},o.filter((e=>j(e))))}const G=W("workerized",{});function B(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function ue(){if(B())w({type:d.GLOBALS_SYNC},p);else{const e=[];for(const t in G){const{worker:r,resolvers:s}=G[t].workerContext;r&&e.push(le(r,d.GLOBALS_SYNC,"",[p],s))}await Promise.all(e)}}function P(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const r in e)Array.isArray(e[r])?(t[r]=[],P(e[r],t[r])):"object"==typeof e[r]?(t[r]={},P(e[r],t[r])):t[r]=e[r]}async function he(e,t){const{functionName:r,args:s}=e;if(!t.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!t.instance[r])throw`undefined function [${r}] in class ${t.instance.constructor.workerId}`;w(e,await t.instance[r](...null!=s?s:[]))}const pe=W("registeredWorkers",{});function de(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,s]=e.args,o=pe[r];if(!o)throw`unknown worker class ${r}`;t.instance=new o(e.args.slice(1)),P(s,p),w(e,void 0!==typeof t.instance)}async function me(e,t){const{args:r}=e;if(!t.instance)throw"instance not initialized";let s;t.instance.terminate&&(s=await t.instance.terminate(...null!=r?r:[])),w(e,s)}function ge(e){if(!e.args)throw"Missing globals while syncing";P(e.args[0],p),w(e,{})}function _e(){const e={};onmessage=async t=>{const r=t.data;switch(r.type){case d.INIT:de(r,e);break;case d.FORWARD:he(r,e);break;case d.TERMINATE:me(r,e);break;case d.GLOBALS_SYNC:ge(r)}}}function ye(e,t){return p[e]||(p[e]=t),[()=>p[e],async t=>{p[e]=t,await ue()}]}function be(e,t){return ye(e,t)}B()&&_e();const[we,Te]=be("metadata");function Ce(e){Te(e)}function C(){return we()}class D{constructor(e){N(this,"uuid",ce()),this.config=e}async send(e){var t,r,s;const{appId:o,sourceType:i}=null!=(t=C())?t:{};if(!o||!i)return"metadata missing";const n=new AbortController,a=setTimeout((()=>n.abort()),se);return await(null!=(s=null==(r=this.config)?void 0:r.fetch)?s:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:n.signal}),clearTimeout(a),"success"}getUrl(){var e;let t=null!=(e=C().proxyUrl)?e:te;return t+=("/"===t.at(-1)?"":"/")+re,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=C();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}}const R="2.0.3";class Se{constructor(e){a(this,"frameTransformedCount",0),a(this,"frameFromSourceCount",0),a(this,"startAt",0),a(this,"reporter"),this.config=e,this.reporter=new D(e)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:t}=this;return t/((Date.now()-e)/1e3)}async onFrameTransformed(e={},t=!1){0===this.startAt&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:r,frameTransformedCount:s,frameFromSourceCount:o}=this,i=Date.now(),n=(i-r)/1e3,a=s/n,l=o/n;return t||this.frameTransformedCount>=this.config.loggingIntervalFrameCount?(this.frameFromSourceCount=0,this.frameTransformedCount=0,this.startAt=i,this.reporter.config=this.config,this.reporter.send({...this.config.report,variation:"QoS",fps:l,transformedFps:a,framesTransformed:s,...e})):"success"}}var Ee=(e=>(e.FPS_DROP="fps_drop",e))(Ee||{}),Re=(e=>(e.start="start",e.transform="transform",e.flush="flush",e))(Re||{}),F=(e=>(e.pipeline_ended="pipeline_ended",e.pipeline_ended_with_error="pipeline_ended_with_error",e.pipeline_started="pipeline_started",e.pipeline_started_with_error="pipeline_started_with_error",e.pipeline_restarted="pipeline_restarted",e.pipeline_restarted_with_error="pipeline_restarted_with_error",e))(F||{});const ke=500,Ae=.8;class Pe extends L{constructor(e,t){super(),a(this,"reporter_",new D),a(this,"reporterQos_",new Se({loggingIntervalFrameCount:ke,report:{version:R}})),a(this,"transformerType_"),a(this,"transformer_"),a(this,"shouldStop_"),a(this,"isFlashed_"),a(this,"mediaTransformerQosReportStartTimestamp_"),a(this,"videoHeight_"),a(this,"videoWidth_"),a(this,"trackExpectedRate_"),a(this,"index_"),a(this,"controller_"),this.index_=t,this.transformer_=e,this.shouldStop_=!1,this.isFlashed_=!1,this.mediaTransformerQosReportStartTimestamp_=0,this.videoHeight_=0,this.videoWidth_=0,this.trackExpectedRate_=-1,this.transformerType_="Custom","getTransformerType"in e&&(this.transformerType_=e.getTransformerType()),this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e}async start(e){if(this.controller_=e,this.transformer_&&"function"==typeof this.transformer_.start)try{await this.transformer_.start(e)}catch(e){this.report({message:l.errors.transformer_start,variation:"Error",error:v(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"start"};this.emit("error",t)}}async transform(e,t){var r,s,o,i;if(0===this.mediaTransformerQosReportStartTimestamp_&&(this.mediaTransformerQosReportStartTimestamp_=Date.now()),e instanceof VideoFrame&&(this.videoHeight_=null!=(r=null==e?void 0:e.displayHeight)?r:0,this.videoWidth_=null!=(s=null==e?void 0:e.displayWidth)?s:0),this.reporterQos_.onFrameFromSource(),this.transformer_)if(this.shouldStop_)console.warn("[Pipeline] flush from transform"),e.close(),this.flush(t),t.terminate();else{try{await(null==(i=(o=this.transformer_).transform)?void 0:i.call(o,e,t)),this.reportQos()}catch(e){this.report({message:l.errors.transformer_transform,variation:"Error",error:v(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"transform"};this.emit("error",t)}if(-1!=this.trackExpectedRate_&&this.trackExpectedRate_*Ae>this.reporterQos_.fps){const e={eventMetaData:{transformerIndex:this.index_},warningType:"fps_drop",dropInfo:{requested:this.trackExpectedRate_,current:this.reporterQos_.fps}};this.emit("warn",e)}}}async flush(e){if(this.transformer_&&"function"==typeof this.transformer_.flush&&!this.isFlashed_){this.isFlashed_=!0;try{await this.transformer_.flush(e)}catch(e){this.report({message:l.errors.transformer_flush,variation:"Error",error:v(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"flush"};this.emit("error",t)}}this.reportQos(!0),this.report({variation:"Delete"})}stop(){console.log("[Pipeline] Stop stream."),this.controller_&&(this.flush(this.controller_),this.controller_.terminate()),this.shouldStop_=!0}report(e){this.reporter_.send({version:R,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:R,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class Me extends L{constructor(e){super(),a(this,"transformers_"),a(this,"trackExpectedRate_"),this.transformers_=[],this.trackExpectedRate_=-1;for(let t=0;t<e.length;t++){let r=new Pe(e[t],t);r.on("error",(e=>{this.emit("error",e)})),r.on("warn",(e=>{this.emit("warn",e)})),this.transformers_.push(r)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let e of this.transformers_)e.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,t){if(this.transformers_&&0!==this.transformers_.length){try{let r=e;for(let t of this.transformers_)e=e.pipeThrough(new TransformStream(t));e.pipeTo(t).then((async()=>{console.log("[Pipeline] Setup."),await t.abort(),await r.cancel(),this.emit("pipelineInfo","pipeline_ended")})).catch((async s=>{e.cancel().then((()=>{console.log("[Pipeline] Shutting down streams after abort.")})).catch((e=>{console.error("[Pipeline] Error from stream transform:",e)})),await t.abort(s),await r.cancel(s),this.emit("pipelineInfo","pipeline_ended_with_error")}))}catch{return this.emit("pipelineInfo","pipeline_started_with_error"),void this.destroy()}this.emit("pipelineInfo","pipeline_started"),console.log("[Pipeline] Pipeline started.")}else console.log("[Pipeline] No transformers.")}async destroy(){console.log("[Pipeline] Destroying Pipeline.");for(let e of this.transformers_)e.stop()}}class Oe extends L{constructor(){super(),a(this,"reporter_"),a(this,"pipeline_"),a(this,"transformers_"),a(this,"readable_"),a(this,"writable_"),a(this,"trackExpectedRate_"),this.reporter_=new D,this.trackExpectedRate_=-1,this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e,this.pipeline_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_)}transform(e,t){return this.readable_=e,this.writable_=t,this.transformInternal()}transformInternal(){return new Promise((async(e,t)=>{if(!this.transformers_||0===this.transformers_.length)return this.report({message:l.errors.transformer_none,variation:"Error"}),void t("[MediaProcessor] Need to set transformers.");if(!this.readable_)return this.report({variation:"Error",message:l.errors.readable_null}),void t("[MediaProcessor] Readable is null.");if(!this.writable_)return this.report({variation:"Error",message:l.errors.writable_null}),void t("[MediaProcessor] Writable is null.");let r=!1;this.pipeline_&&(r=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new Me(this.transformers_),this.pipeline_.on("warn",(e=>{this.emit("warn",e)})),this.pipeline_.on("error",(e=>{this.emit("error",e)})),this.pipeline_.on("pipelineInfo",(e=>{r&&("pipeline_started"===e?e=F.pipeline_restarted:"pipeline_started_with_error"===e&&(e=F.pipeline_restarted_with_error)),this.emit("pipelineInfo",e)})),-1!=this.trackExpectedRate_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_),this.pipeline_.start(this.readable_,this.writable_).then((()=>{e()})).catch((e=>{t(e)}))}))}setTransformers(e){return this.report({variation:"Update",message:l.updates.transformer_new}),this.transformers_=e,this.readable_&&this.writable_?this.transformInternal():Promise.resolve()}destroy(){return new Promise((async e=>{this.pipeline_&&this.pipeline_.destroy(),this.report({variation:"Delete"}),e()}))}report(e){this.reporter_.send({version:R,action:"MediaProcessor",...e})}}class xe{constructor(){a(this,"processor_"),a(this,"generator_"),this.processor_=null,this.generator_=null}init(e){return new Promise(((t,r)=>{try{this.processor_=new MediaStreamTrackProcessor(e)}catch(e){console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${e}`),r(e)}try{"audio"===e.kind?this.generator_=new MediaStreamTrackGenerator({kind:"audio"}):"video"===e.kind?this.generator_=new MediaStreamTrackGenerator({kind:"video"}):r("kind not supported")}catch(e){console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${e}`),r(e)}t()}))}getReadable(){return this.processor_.readable}getWriteable(){return this.generator_.writable}getProccesorTrack(){return this.generator_}}class Fe{constructor(e){a(this,"insertableStreamHelper_"),a(this,"mediaProcessor_"),this.insertableStreamHelper_=new xe,this.mediaProcessor_=e}setTrack(e){return new Promise(((t,r)=>{this.insertableStreamHelper_.init(e).then((()=>{this.mediaProcessor_.transform(this.insertableStreamHelper_.getReadable(),this.insertableStreamHelper_.getWriteable()).then((()=>{t(this.insertableStreamHelper_.getProccesorTrack())})).catch((e=>{r(e)}))})).catch((e=>{r(e)}))}))}destroy(){return new Promise(((e,t)=>{this.mediaProcessor_?this.mediaProcessor_.destroy().then((()=>{e()})).catch((e=>{t(e)})):t("no processor")}))}}export{Re as ErrorFunction,Oe as MediaProcessor,Fe as MediaProcessorConnector,F as PipelineInfoData,ee as VonageSourceType,Ee as WarningType,C as getVonageMetadata,ve as isSupported,Ce as setVonageMetadata};
function Ie(){return new Promise(((e,t)=>{typeof MediaStreamTrackProcessor>"u"||typeof MediaStreamTrackGenerator>"u"?t("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."):e()}))}class l{}function j(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}l.updates={transformer_new:"New transformer",transformer_null:"Null transformer"},l.errors={transformer_none:"No transformers provided",transformer_start:"Cannot start transformer",transformer_transform:"Cannot transform frame",transformer_flush:"Cannot flush transformer",readable_null:"Readable is null",writable_null:"Writable is null"};const f=new WeakMap,T=new WeakMap,g=new WeakMap,C=Symbol("anyProducer"),U=Promise.resolve(),S=Symbol("listenerAdded"),R=Symbol("listenerRemoved");let A=!1;function p(e){if("string"!=typeof e&&"symbol"!=typeof e)throw new TypeError("eventName must be a string or a symbol")}function b(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function m(e,t){const r=T.get(e);return r.has(t)||r.set(t,new Set),r.get(t)}function _(e,t){const r="string"==typeof t||"symbol"==typeof t?t:C,s=g.get(e);return s.has(r)||s.set(r,new Set),s.get(r)}function B(e,t,r){const s=g.get(e);if(s.has(t))for(const e of s.get(t))e.enqueue(r);if(s.has(C)){const e=Promise.all([t,r]);for(const t of s.get(C))t.enqueue(e)}}function D(e,t){t=Array.isArray(t)?t:[t];let r=!1,s=()=>{},o=[];const n={enqueue(e){o.push(e),s()},finish(){r=!0,s()}};for(const r of t)_(e,r).add(n);return{async next(){return o?0===o.length?r?(o=void 0,this.next()):(await new Promise((e=>{s=e})),this.next()):{done:!1,value:await o.shift()}:{done:!0}},async return(r){o=void 0;for(const r of t)_(e,r).delete(n);return s(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function $(e){if(void 0===e)return G;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!G.includes(t))throw"string"!=typeof t?new TypeError("`methodNames` element must be a string"):new Error(`${t} is not Emittery method`);return e}const M=e=>e===S||e===R;class d{static mixin(e,t){return t=$(t),r=>{if("function"!=typeof r)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==r.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(r.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new d}),this[e]}});const s=t=>function(...r){return this[e][t](...r)};for(const e of t)Object.defineProperty(r.prototype,e,{enumerable:!1,value:s(e)});return r}}static get isDebugEnabled(){if("object"!=typeof process)return A;const{env:e}=process||{env:{}};return"emittery"===e.DEBUG||"*"===e.DEBUG||A}static set isDebugEnabled(e){A=e}constructor(e={}){f.set(this,new Set),T.set(this,new Map),g.set(this,new Map),this.debug=e.debug||{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,r,s)=>{try{s=JSON.stringify(s)}catch{s=`Object with the following keys failed to stringify: ${Object.keys(s).join(",")}`}"symbol"==typeof r&&(r=r.toString());const o=new Date,n=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${n}][emittery:${e}][${t}] Event Name: ${r}\n\tdata: ${s}`)})}logIfDebugEnabled(e,t,r){(d.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,r)}on(e,t){b(t),e=Array.isArray(e)?e:[e];for(const r of e)p(r),m(this,r).add(t),this.logIfDebugEnabled("subscribe",r,void 0),M(r)||this.emit(S,{eventName:r,listener:t});return this.off.bind(this,e,t)}off(e,t){b(t),e=Array.isArray(e)?e:[e];for(const r of e)p(r),m(this,r).delete(t),this.logIfDebugEnabled("unsubscribe",r,void 0),M(r)||this.emit(R,{eventName:r,listener:t})}once(e){return new Promise((t=>{const r=this.on(e,(e=>{r(),t(e)}))}))}events(e){e=Array.isArray(e)?e:[e];for(const t of e)p(t);return D(this,e)}async emit(e,t){p(e),this.logIfDebugEnabled("emit",e,t),B(this,e,t);const r=m(this,e),s=f.get(this),o=[...r],n=M(e)?[]:[...s];await U,await Promise.all([...o.map((async e=>{if(r.has(e))return e(t)})),...n.map((async r=>{if(s.has(r))return r(e,t)}))])}async emitSerial(e,t){p(e),this.logIfDebugEnabled("emitSerial",e,t);const r=m(this,e),s=f.get(this),o=[...r],n=[...s];await U;for(const e of o)r.has(e)&&await e(t);for(const r of n)s.has(r)&&await r(e,t)}onAny(e){return b(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),f.get(this).add(e),this.emit(S,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return D(this)}offAny(e){b(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),this.emit(R,{listener:e}),f.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),"string"==typeof t||"symbol"==typeof t){m(this,t).clear();const e=_(this,t);for(const t of e)t.finish();e.clear()}else{f.get(this).clear();for(const e of T.get(this).values())e.clear();for(const e of g.get(this).values()){for(const t of e)t.finish();e.clear()}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const r of e)if("string"!=typeof r){typeof r<"u"&&p(r),t+=f.get(this).size;for(const e of T.get(this).values())t+=e.size;for(const e of g.get(this).values())t+=e.size}else t+=f.get(this).size+m(this,r).size+_(this,r).size+_(this).size;return t}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=$(t);for(const r of t){if(void 0!==e[r])throw new Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}}const G=Object.getOwnPropertyNames(d.prototype).filter((e=>"constructor"!==e));Object.defineProperty(d,"listenerAdded",{value:S,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(d,"listenerRemoved",{value:R,writable:!1,enumerable:!0,configurable:!1});var Y=d;const v=j(Y);function q(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}function J(e){if(q(e))return e;try{return new Error(JSON.stringify(e))}catch{return new Error(String(e))}}function I(e){return J(e).message}var K=Object.defineProperty,X=(e,t,r)=>t in e?K(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Z=(e,t,r)=>(X(e,"symbol"!=typeof t?t+"":t,r),r),N=(e=>(e.automation="automation",e.test="test",e.vbc="vbc",e.video="video",e.voice="voice",e))(N||{});const ee="hlg.tokbox.com/prod/logging/vcp_webrtc",re="https://",te=1e4;let w;const se=new Uint8Array(16);function ie(){if(!w&&(w=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!w))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return w(se)}const c=[];for(let e=0;e<256;++e)c.push((e+256).toString(16).slice(1));function ne(e,t=0){return(c[e[t+0]]+c[e[t+1]]+c[e[t+2]]+c[e[t+3]]+"-"+c[e[t+4]]+c[e[t+5]]+"-"+c[e[t+6]]+c[e[t+7]]+"-"+c[e[t+8]]+c[e[t+9]]+"-"+c[e[t+10]]+c[e[t+11]]+c[e[t+12]]+c[e[t+13]]+c[e[t+14]]+c[e[t+15]]).toLowerCase()}const oe=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),H={randomUUID:oe};function ae(e,t,r){if(H.randomUUID&&!t&&!e)return H.randomUUID();const s=(e=e||{}).random||(e.rng||ie)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=s[e];return t}return ne(s)}function F(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[e]||(r[e]=t),r[e]}const h=F("globals",{});var u=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e))(u||{});function z(e){return[ImageBitmap,ReadableStream,WritableStream].some((t=>e instanceof t))}let ce=0;function le(e,t,r,s,o){const n=ce++;return e.postMessage({id:n,type:t,functionName:r,args:s},s.filter((e=>z(e)))),new Promise((e=>{null==o||o.set(n,e)}))}function y(e,t){const{id:r,type:s}=e,o=Array.isArray(t)?t:[t];postMessage({id:r,type:s,result:t},o.filter((e=>z(e))))}const Q=F("workerized",{});function V(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function fe(){if(V())y({type:u.GLOBALS_SYNC},h);else{const e=[];for(const t in Q){const{worker:r,resolvers:s}=Q[t].workerContext;r&&e.push(le(r,u.GLOBALS_SYNC,"",[h],s))}await Promise.all(e)}}function P(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const r in e)Array.isArray(e[r])?(t[r]=[],P(e[r],t[r])):"object"==typeof e[r]?(t[r]={},P(e[r],t[r])):t[r]=e[r]}async function he(e,t){const{functionName:r,args:s}=e;if(!t.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!t.instance[r])throw`undefined function [${r}] in class ${t.instance.constructor.workerId}`;y(e,await t.instance[r](...s??[]))}const ue=F("registeredWorkers",{});function de(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,s]=e.args,o=ue[r];if(!o)throw`unknown worker class ${r}`;t.instance=new o(e.args.slice(1)),P(s,h),y(e,void 0!==typeof t.instance)}async function pe(e,t){const{args:r}=e;if(!t.instance)throw"instance not initialized";let s;t.instance.terminate&&(s=await t.instance.terminate(...r??[])),y(e,s)}function me(e){if(!e.args)throw"Missing globals while syncing";P(e.args[0],h),y(e,{})}function ge(){const e={};onmessage=async t=>{const r=t.data;switch(r.type){case u.INIT:de(r,e);break;case u.FORWARD:he(r,e);break;case u.TERMINATE:pe(r,e);break;case u.GLOBALS_SYNC:me(r)}}}function _e(e,t){return h[e]||(h[e]=t),[()=>h[e],async t=>{h[e]=t,await fe()}]}function ye(e,t){return _e(e,t)}V()&&ge();const[be,we]=ye("metadata");function xe(e){we(e)}function x(){return be()}class L{constructor(e,t){Z(this,"uuid"),this.config=e,this.uuid=t??ae()}async send(e){var t,r,s;const{appId:o,sourceType:n}=null!=(t=x())?t:{};if(!o||!n)return"metadata missing";const i=new AbortController,a=setTimeout((()=>i.abort()),te);return await(null!=(s=null==(r=this.config)?void 0:r.fetch)?s:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:i.signal}),clearTimeout(a),"success"}getUrl(){var e;let t=null!=(e=x().proxyUrl)?e:re;return t+=("/"===t.at(-1)?"":"/")+ee,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=x();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}}const E="2.0.4";class Te{constructor(e,t){this.config=e,this.frameTransformedCount=0,this.frameFromSourceCount=0,this.startAt=0,this.reporter=new L(e,t)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:t}=this;return t/((Date.now()-e)/1e3)}async onFrameTransformed(e={},t=!1){0===this.startAt&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:r,frameTransformedCount:s,frameFromSourceCount:o}=this,n=Date.now(),i=(n-r)/1e3,a=s/i,c=o/i;return t||this.frameTransformedCount>=this.config.loggingIntervalFrameCount?(this.frameFromSourceCount=0,this.frameTransformedCount=0,this.startAt=n,this.reporter.config=this.config,this.reporter.send({...this.config.report,variation:"QoS",fps:c,transformedFps:a,framesTransformed:s,...e})):"success"}}var Ee=(e=>(e.FPS_DROP="fps_drop",e))(Ee||{}),Se=(e=>(e.start="start",e.transform="transform",e.flush="flush",e))(Se||{}),O=(e=>(e.pipeline_ended="pipeline_ended",e.pipeline_ended_with_error="pipeline_ended_with_error",e.pipeline_started="pipeline_started",e.pipeline_started_with_error="pipeline_started_with_error",e.pipeline_restarted="pipeline_restarted",e.pipeline_restarted_with_error="pipeline_restarted_with_error",e))(O||{});const Re=500,Pe=.8;class ke extends v{constructor(e,t){super(),this.reporter_=new L,this.reporterQos_=new Te({loggingIntervalFrameCount:Re,report:{version:E}}),this.index_=t,this.transformer_=e,this.shouldStop_=!1,this.isFlashed_=!1,this.mediaTransformerQosReportStartTimestamp_=0,this.videoHeight_=0,this.videoWidth_=0,this.trackExpectedRate_=-1,this.transformerType_="Custom","getTransformerType"in e&&(this.transformerType_=e.getTransformerType()),this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e}async start(e){if(this.controller_=e,this.transformer_&&"function"==typeof this.transformer_.start)try{await this.transformer_.start(e)}catch(e){this.report({message:l.errors.transformer_start,variation:"Error",error:I(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"start"};this.emit("error",t)}}async transform(e,t){var r,s;if(0===this.mediaTransformerQosReportStartTimestamp_&&(this.mediaTransformerQosReportStartTimestamp_=Date.now()),e instanceof VideoFrame&&(this.videoHeight_=(null==e?void 0:e.displayHeight)??0,this.videoWidth_=(null==e?void 0:e.displayWidth)??0),this.reporterQos_.onFrameFromSource(),this.transformer_)if(this.shouldStop_)console.warn("[Pipeline] flush from transform"),e.close(),this.flush(t),t.terminate();else{try{await(null==(s=(r=this.transformer_).transform)?void 0:s.call(r,e,t)),this.reportQos()}catch(e){this.report({message:l.errors.transformer_transform,variation:"Error",error:I(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"transform"};this.emit("error",t)}if(-1!=this.trackExpectedRate_&&this.trackExpectedRate_*Pe>this.reporterQos_.fps){const e={eventMetaData:{transformerIndex:this.index_},warningType:"fps_drop",dropInfo:{requested:this.trackExpectedRate_,current:this.reporterQos_.fps}};this.emit("warn",e)}}}async flush(e){if(this.transformer_&&"function"==typeof this.transformer_.flush&&!this.isFlashed_){this.isFlashed_=!0;try{await this.transformer_.flush(e)}catch(e){this.report({message:l.errors.transformer_flush,variation:"Error",error:I(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"flush"};this.emit("error",t)}}this.reportQos(!0),this.report({variation:"Delete"})}stop(){console.log("[Pipeline] Stop stream."),this.controller_&&(this.flush(this.controller_),this.controller_.terminate()),this.shouldStop_=!0}report(e){this.reporter_.send({version:E,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:E,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class Ae extends v{constructor(e){super(),this.transformers_=[],this.trackExpectedRate_=-1;for(let t=0;t<e.length;t++){let r=new ke(e[t],t);r.on("error",(e=>{this.emit("error",e)})),r.on("warn",(e=>{this.emit("warn",e)})),this.transformers_.push(r)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let e of this.transformers_)e.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,t){if(this.transformers_&&0!==this.transformers_.length){try{let r=e;for(let t of this.transformers_)e=e.pipeThrough(new TransformStream(t));e.pipeTo(t).then((async()=>{console.log("[Pipeline] Setup."),await t.abort(),await r.cancel(),this.emit("pipelineInfo","pipeline_ended")})).catch((async s=>{e.cancel().then((()=>{console.log("[Pipeline] Shutting down streams after abort.")})).catch((e=>{console.error("[Pipeline] Error from stream transform:",e)})),await t.abort(s),await r.cancel(s),this.emit("pipelineInfo","pipeline_ended_with_error")}))}catch{return this.emit("pipelineInfo","pipeline_started_with_error"),void this.destroy()}this.emit("pipelineInfo","pipeline_started"),console.log("[Pipeline] Pipeline started.")}else console.log("[Pipeline] No transformers.")}async destroy(){console.log("[Pipeline] Destroying Pipeline.");for(let e of this.transformers_)e.stop()}}class Ce extends v{constructor(){super(),this.reporter_=new L,this.trackExpectedRate_=-1,this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e,this.pipeline_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_)}transform(e,t){return this.readable_=e,this.writable_=t,this.transformInternal()}transformInternal(){return new Promise((async(e,t)=>{if(!this.transformers_||0===this.transformers_.length)return this.report({message:l.errors.transformer_none,variation:"Error"}),void t("[MediaProcessor] Need to set transformers.");if(!this.readable_)return this.report({variation:"Error",message:l.errors.readable_null}),void t("[MediaProcessor] Readable is null.");if(!this.writable_)return this.report({variation:"Error",message:l.errors.writable_null}),void t("[MediaProcessor] Writable is null.");let r=!1;this.pipeline_&&(r=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new Ae(this.transformers_),this.pipeline_.on("warn",(e=>{this.emit("warn",e)})),this.pipeline_.on("error",(e=>{this.emit("error",e)})),this.pipeline_.on("pipelineInfo",(e=>{r&&("pipeline_started"===e?e=O.pipeline_restarted:"pipeline_started_with_error"===e&&(e=O.pipeline_restarted_with_error)),this.emit("pipelineInfo",e)})),-1!=this.trackExpectedRate_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_),this.pipeline_.start(this.readable_,this.writable_).then((()=>{e()})).catch((e=>{t(e)}))}))}setTransformers(e){return this.report({variation:"Update",message:l.updates.transformer_new}),this.transformers_=e,this.readable_&&this.writable_?this.transformInternal():Promise.resolve()}destroy(){return new Promise((async e=>{this.pipeline_&&this.pipeline_.destroy(),this.report({variation:"Delete"}),e()}))}report(e){this.reporter_.send({version:E,action:"MediaProcessor",...e})}}class Me{constructor(){this.processor_=null,this.generator_=null}init(e){return new Promise(((t,r)=>{try{this.processor_=new MediaStreamTrackProcessor(e)}catch(e){console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${e}`),r(e)}try{"audio"===e.kind?this.generator_=new MediaStreamTrackGenerator({kind:"audio"}):"video"===e.kind?this.generator_=new MediaStreamTrackGenerator({kind:"video"}):r("kind not supported")}catch(e){console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${e}`),r(e)}t()}))}getReadable(){return this.processor_.readable}getWriteable(){return this.generator_.writable}getProccesorTrack(){return this.generator_}}class Oe{constructor(e){this.insertableStreamHelper_=new Me,this.mediaProcessor_=e}setTrack(e){return new Promise(((t,r)=>{this.insertableStreamHelper_.init(e).then((()=>{this.mediaProcessor_.transform(this.insertableStreamHelper_.getReadable(),this.insertableStreamHelper_.getWriteable()).then((()=>{t(this.insertableStreamHelper_.getProccesorTrack())})).catch((e=>{r(e)}))})).catch((e=>{r(e)}))}))}destroy(){return new Promise(((e,t)=>{this.mediaProcessor_?this.mediaProcessor_.destroy().then((()=>{e()})).catch((e=>{t(e)})):t("no processor")}))}}export{Se as ErrorFunction,Ce as MediaProcessor,Oe as MediaProcessorConnector,O as PipelineInfoData,N as VonageSourceType,Ee as WarningType,x as getVonageMetadata,Ie as isSupported,xe as setVonageMetadata};

@@ -1,7 +0,6 @@

var V = Object.defineProperty;
var Y = (t, e, r) => e in t ? V(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
var a = (t, e, r) => (Y(t, typeof e != "symbol" ? e + "" : e, r), r);
function ve() {
function Ie() {
return new Promise((t, e) => {
typeof MediaStreamTrackProcessor > "u" || typeof MediaStreamTrackGenerator > "u" ? e("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media.") : t();
typeof MediaStreamTrackProcessor > "u" || typeof MediaStreamTrackGenerator > "u" ? e(
"Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."
) : t();
});

@@ -11,6 +10,7 @@ }

}
a(l, "updates", {
l.updates = {
transformer_new: "New transformer",
transformer_null: "Null transformer"
}), a(l, "errors", {
};
l.errors = {
transformer_none: "No transformers provided",

@@ -22,39 +22,42 @@ transformer_start: "Cannot start transformer",

writable_null: "Writable is null"
});
const h = /* @__PURE__ */ new WeakMap(), E = /* @__PURE__ */ new WeakMap(), y = /* @__PURE__ */ new WeakMap(), O = Symbol("anyProducer"), U = Promise.resolve(), k = Symbol("listenerAdded"), A = Symbol("listenerRemoved");
let x = !1;
function g(t) {
};
function j(t) {
return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
}
const f = /* @__PURE__ */ new WeakMap(), T = /* @__PURE__ */ new WeakMap(), g = /* @__PURE__ */ new WeakMap(), C = Symbol("anyProducer"), U = Promise.resolve(), S = Symbol("listenerAdded"), R = Symbol("listenerRemoved");
let A = !1;
function p(t) {
if (typeof t != "string" && typeof t != "symbol")
throw new TypeError("eventName must be a string or a symbol");
}
function T(t) {
function b(t) {
if (typeof t != "function")
throw new TypeError("listener must be a function");
}
function _(t, e) {
const r = E.get(t);
function m(t, e) {
const r = T.get(t);
return r.has(e) || r.set(e, /* @__PURE__ */ new Set()), r.get(e);
}
function b(t, e) {
const r = typeof e == "string" || typeof e == "symbol" ? e : O, s = y.get(t);
function _(t, e) {
const r = typeof e == "string" || typeof e == "symbol" ? e : C, s = g.get(t);
return s.has(r) || s.set(r, /* @__PURE__ */ new Set()), s.get(r);
}
function q(t, e, r) {
const s = y.get(t);
function B(t, e, r) {
const s = g.get(t);
if (s.has(e))
for (const o of s.get(e))
o.enqueue(r);
if (s.has(O)) {
const o = Promise.all([e, r]);
for (const i of s.get(O))
i.enqueue(o);
for (const i of s.get(e))
i.enqueue(r);
if (s.has(C)) {
const i = Promise.all([e, r]);
for (const n of s.get(C))
n.enqueue(i);
}
}
function $(t, e) {
function D(t, e) {
e = Array.isArray(e) ? e : [e];
let r = !1, s = () => {
}, o = [];
const i = {
enqueue(n) {
o.push(n), s();
}, i = [];
const n = {
enqueue(o) {
i.push(o), s();
},

@@ -65,18 +68,18 @@ finish() {

};
for (const n of e)
b(t, n).add(i);
for (const o of e)
_(t, o).add(n);
return {
async next() {
return o ? o.length === 0 ? r ? (o = void 0, this.next()) : (await new Promise((n) => {
s = n;
return i ? i.length === 0 ? r ? (i = void 0, this.next()) : (await new Promise((o) => {
s = o;
}), this.next()) : {
done: !1,
value: await o.shift()
value: await i.shift()
} : { done: !0 };
},
async return(n) {
o = void 0;
for (const c of e)
b(t, c).delete(i);
return s(), arguments.length > 0 ? { done: !0, value: await n } : { done: !0 };
async return(o) {
i = void 0;
for (const a of e)
_(t, a).delete(n);
return s(), arguments.length > 0 ? { done: !0, value: await o } : { done: !0 };
},

@@ -88,25 +91,25 @@ [Symbol.asyncIterator]() {

}
function H(t) {
function $(t) {
if (t === void 0)
return Q;
return G;
if (!Array.isArray(t))
throw new TypeError("`methodNames` must be an array of strings");
for (const e of t)
if (!Q.includes(e))
if (!G.includes(e))
throw typeof e != "string" ? new TypeError("`methodNames` element must be a string") : new Error(`${e} is not Emittery method`);
return t;
}
const I = (t) => t === k || t === A;
class m {
const M = (t) => t === S || t === R;
class d {
static mixin(e, r) {
return r = H(r), (s) => {
return r = $(r), (s) => {
if (typeof s != "function")
throw new TypeError("`target` must be function");
for (const n of r)
if (s.prototype[n] !== void 0)
throw new Error(`The property \`${n}\` already exists on \`target\``);
function o() {
for (const o of r)
if (s.prototype[o] !== void 0)
throw new Error(`The property \`${o}\` already exists on \`target\``);
function i() {
return Object.defineProperty(this, e, {
enumerable: !1,
value: new m()
value: new d()
}), this[e];

@@ -116,11 +119,11 @@ }

enumerable: !1,
get: o
get: i
});
const i = (n) => function(...c) {
return this[e][n](...c);
const n = (o) => function(...a) {
return this[e][o](...a);
};
for (const n of r)
Object.defineProperty(s.prototype, n, {
for (const o of r)
Object.defineProperty(s.prototype, o, {
enumerable: !1,
value: i(n)
value: n(o)
});

@@ -132,40 +135,40 @@ return s;

if (typeof process != "object")
return x;
return A;
const { env: e } = process || { env: {} };
return e.DEBUG === "emittery" || e.DEBUG === "*" || x;
return e.DEBUG === "emittery" || e.DEBUG === "*" || A;
}
static set isDebugEnabled(e) {
x = e;
A = e;
}
constructor(e = {}) {
h.set(this, /* @__PURE__ */ new Set()), E.set(this, /* @__PURE__ */ new Map()), y.set(this, /* @__PURE__ */ new Map()), this.debug = e.debug || {}, this.debug.enabled === void 0 && (this.debug.enabled = !1), this.debug.logger || (this.debug.logger = (r, s, o, i) => {
f.set(this, /* @__PURE__ */ new Set()), T.set(this, /* @__PURE__ */ new Map()), g.set(this, /* @__PURE__ */ new Map()), this.debug = e.debug || {}, this.debug.enabled === void 0 && (this.debug.enabled = !1), this.debug.logger || (this.debug.logger = (r, s, i, n) => {
try {
i = JSON.stringify(i);
n = JSON.stringify(n);
} catch {
i = `Object with the following keys failed to stringify: ${Object.keys(i).join(",")}`;
n = `Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`;
}
typeof o == "symbol" && (o = o.toString());
const n = new Date(), c = `${n.getHours()}:${n.getMinutes()}:${n.getSeconds()}.${n.getMilliseconds()}`;
console.log(`[${c}][emittery:${r}][${s}] Event Name: ${o}
data: ${i}`);
typeof i == "symbol" && (i = i.toString());
const o = /* @__PURE__ */ new Date(), a = `${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;
console.log(`[${a}][emittery:${r}][${s}] Event Name: ${i}
data: ${n}`);
});
}
logIfDebugEnabled(e, r, s) {
(m.isDebugEnabled || this.debug.enabled) && this.debug.logger(e, this.debug.name, r, s);
(d.isDebugEnabled || this.debug.enabled) && this.debug.logger(e, this.debug.name, r, s);
}
on(e, r) {
T(r), e = Array.isArray(e) ? e : [e];
b(r), e = Array.isArray(e) ? e : [e];
for (const s of e)
g(s), _(this, s).add(r), this.logIfDebugEnabled("subscribe", s, void 0), I(s) || this.emit(k, { eventName: s, listener: r });
p(s), m(this, s).add(r), this.logIfDebugEnabled("subscribe", s, void 0), M(s) || this.emit(S, { eventName: s, listener: r });
return this.off.bind(this, e, r);
}
off(e, r) {
T(r), e = Array.isArray(e) ? e : [e];
b(r), e = Array.isArray(e) ? e : [e];
for (const s of e)
g(s), _(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(A, { eventName: s, listener: r });
p(s), m(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), M(s) || this.emit(R, { eventName: s, listener: r });
}
once(e) {
return new Promise((r) => {
const s = this.on(e, (o) => {
s(), r(o);
const s = this.on(e, (i) => {
s(), r(i);
});

@@ -177,16 +180,16 @@ });

for (const r of e)
g(r);
return $(this, e);
p(r);
return D(this, e);
}
async emit(e, r) {
g(e), this.logIfDebugEnabled("emit", e, r), q(this, e, r);
const s = _(this, e), o = h.get(this), i = [...s], n = I(e) ? [] : [...o];
p(e), this.logIfDebugEnabled("emit", e, r), B(this, e, r);
const s = m(this, e), i = f.get(this), n = [...s], o = M(e) ? [] : [...i];
await U, await Promise.all([
...i.map(async (c) => {
if (s.has(c))
return c(r);
...n.map(async (a) => {
if (s.has(a))
return a(r);
}),
...n.map(async (c) => {
if (o.has(c))
return c(e, r);
...o.map(async (a) => {
if (i.has(a))
return a(e, r);
})

@@ -196,18 +199,18 @@ ]);

async emitSerial(e, r) {
g(e), this.logIfDebugEnabled("emitSerial", e, r);
const s = _(this, e), o = h.get(this), i = [...s], n = [...o];
p(e), this.logIfDebugEnabled("emitSerial", e, r);
const s = m(this, e), i = f.get(this), n = [...s], o = [...i];
await U;
for (const c of i)
s.has(c) && await c(r);
for (const c of n)
o.has(c) && await c(e, r);
for (const a of n)
s.has(a) && await a(r);
for (const a of o)
i.has(a) && await a(e, r);
}
onAny(e) {
return T(e), this.logIfDebugEnabled("subscribeAny", void 0, void 0), h.get(this).add(e), this.emit(k, { listener: e }), this.offAny.bind(this, e);
return b(e), this.logIfDebugEnabled("subscribeAny", void 0, void 0), f.get(this).add(e), this.emit(S, { listener: e }), this.offAny.bind(this, e);
}
anyEvent() {
return $(this);
return D(this);
}
offAny(e) {
T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(A, { listener: e }), h.get(this).delete(e);
b(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(R, { listener: e }), f.get(this).delete(e);
}

@@ -218,14 +221,14 @@ clearListeners(e) {

if (this.logIfDebugEnabled("clear", r, void 0), typeof r == "string" || typeof r == "symbol") {
_(this, r).clear();
const s = b(this, r);
for (const o of s)
o.finish();
m(this, r).clear();
const s = _(this, r);
for (const i of s)
i.finish();
s.clear();
} else {
h.get(this).clear();
for (const s of E.get(this).values())
f.get(this).clear();
for (const s of T.get(this).values())
s.clear();
for (const s of y.get(this).values()) {
for (const o of s)
o.finish();
for (const s of g.get(this).values()) {
for (const i of s)
i.finish();
s.clear();

@@ -240,10 +243,10 @@ }

if (typeof s == "string") {
r += h.get(this).size + _(this, s).size + b(this, s).size + b(this).size;
r += f.get(this).size + m(this, s).size + _(this, s).size + _(this).size;
continue;
}
typeof s < "u" && g(s), r += h.get(this).size;
for (const o of E.get(this).values())
r += o.size;
for (const o of y.get(this).values())
r += o.size;
typeof s < "u" && p(s), r += f.get(this).size;
for (const i of T.get(this).values())
r += i.size;
for (const i of g.get(this).values())
r += i.size;
}

@@ -255,3 +258,3 @@ return r;

throw new TypeError("`target` must be an object");
r = H(r);
r = $(r);
for (const s of r) {

@@ -267,5 +270,5 @@ if (e[s] !== void 0)

}
const Q = Object.getOwnPropertyNames(m.prototype).filter((t) => t !== "constructor");
Object.defineProperty(m, "listenerAdded", {
value: k,
const G = Object.getOwnPropertyNames(d.prototype).filter((t) => t !== "constructor");
Object.defineProperty(d, "listenerAdded", {
value: S,
writable: !1,

@@ -275,4 +278,4 @@ enumerable: !0,

});
Object.defineProperty(m, "listenerRemoved", {
value: A,
Object.defineProperty(d, "listenerRemoved", {
value: R,
writable: !1,

@@ -282,8 +285,9 @@ enumerable: !0,

});
var L = m;
function J(t) {
var Y = d;
const v = /* @__PURE__ */ j(Y);
function q(t) {
return typeof t == "object" && t !== null && "message" in t && typeof t.message == "string";
}
function X(t) {
if (J(t))
function J(t) {
if (q(t))
return t;

@@ -296,26 +300,26 @@ try {

}
function v(t) {
return X(t).message;
function I(t) {
return J(t).message;
}
var Z = Object.defineProperty, K = (t, e, r) => e in t ? Z(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r, N = (t, e, r) => (K(t, typeof e != "symbol" ? e + "" : e, r), r), ee = /* @__PURE__ */ ((t) => (t.automation = "automation", t.test = "test", t.vbc = "vbc", t.video = "video", t.voice = "voice", t))(ee || {});
const re = "hlg.tokbox.com/prod/logging/vcp_webrtc", te = "https://", se = 1e4;
let S;
const oe = new Uint8Array(16);
var K = Object.defineProperty, X = (t, e, r) => e in t ? K(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r, Z = (t, e, r) => (X(t, typeof e != "symbol" ? e + "" : e, r), r), N = /* @__PURE__ */ ((t) => (t.automation = "automation", t.test = "test", t.vbc = "vbc", t.video = "video", t.voice = "voice", t))(N || {});
const ee = "hlg.tokbox.com/prod/logging/vcp_webrtc", re = "https://", te = 1e4;
let w;
const se = new Uint8Array(16);
function ie() {
if (!S && (S = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !S))
if (!w && (w = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !w))
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
return S(oe);
return w(se);
}
const f = [];
const c = [];
for (let t = 0; t < 256; ++t)
f.push((t + 256).toString(16).slice(1));
c.push((t + 256).toString(16).slice(1));
function ne(t, e = 0) {
return (f[t[e + 0]] + f[t[e + 1]] + f[t[e + 2]] + f[t[e + 3]] + "-" + f[t[e + 4]] + f[t[e + 5]] + "-" + f[t[e + 6]] + f[t[e + 7]] + "-" + f[t[e + 8]] + f[t[e + 9]] + "-" + f[t[e + 10]] + f[t[e + 11]] + f[t[e + 12]] + f[t[e + 13]] + f[t[e + 14]] + f[t[e + 15]]).toLowerCase();
return (c[t[e + 0]] + c[t[e + 1]] + c[t[e + 2]] + c[t[e + 3]] + "-" + c[t[e + 4]] + c[t[e + 5]] + "-" + c[t[e + 6]] + c[t[e + 7]] + "-" + c[t[e + 8]] + c[t[e + 9]] + "-" + c[t[e + 10]] + c[t[e + 11]] + c[t[e + 12]] + c[t[e + 13]] + c[t[e + 14]] + c[t[e + 15]]).toLowerCase();
}
const ae = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), z = {
randomUUID: ae
const oe = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), H = {
randomUUID: oe
};
function ce(t, e, r) {
if (z.randomUUID && !e && !t)
return z.randomUUID();
function ae(t, e, r) {
if (H.randomUUID && !e && !t)
return H.randomUUID();
t = t || {};

@@ -325,4 +329,4 @@ const s = t.random || (t.rng || ie)();

r = r || 0;
for (let o = 0; o < 16; ++o)
e[r + o] = s[o];
for (let i = 0; i < 16; ++i)
e[r + i] = s[i];
return e;

@@ -332,3 +336,3 @@ }

}
function W(t, e) {
function F(t, e) {
globalThis.vonage || (globalThis.vonage = {}), globalThis.vonage.workerizer || (globalThis.vonage.workerizer = {});

@@ -338,16 +342,16 @@ let r = globalThis.vonage.workerizer;

}
const p = W(
const h = F(
"globals",
{}
);
var d = /* @__PURE__ */ ((t) => (t.INIT = "INIT", t.FORWARD = "FORWARD", t.TERMINATE = "TERMINATE", t.GLOBALS_SYNC = "GLOBALS_SYNC", t))(d || {});
function j(t) {
return [ImageBitmap, ReadableStream, WritableStream].some((e) => t instanceof e);
var u = /* @__PURE__ */ ((t) => (t.INIT = "INIT", t.FORWARD = "FORWARD", t.TERMINATE = "TERMINATE", t.GLOBALS_SYNC = "GLOBALS_SYNC", t))(u || {});
function z(t) {
return [ImageBitmap, ReadableStream, WritableStream].some((r) => t instanceof r);
}
let fe = 0;
function le(t, e, r, s, o) {
const i = fe++;
let ce = 0;
function le(t, e, r, s, i) {
const n = ce++;
return t.postMessage(
{
id: i,
id: n,
type: e,

@@ -357,9 +361,9 @@ functionName: r,

},
s.filter((n) => j(n))
), new Promise((n) => {
o == null || o.set(i, n);
s.filter((a) => z(a))
), new Promise((a) => {
i == null || i.set(n, a);
});
}
function w(t, e) {
const { id: r, type: s } = t, o = Array.isArray(e) ? e : [e];
function y(t, e) {
const { id: r, type: s } = t, i = Array.isArray(e) ? e : [e];
postMessage(

@@ -371,22 +375,22 @@ {

},
o.filter((i) => j(i))
i.filter((n) => z(n))
);
}
const G = W("workerized", {});
function B() {
const Q = F("workerized", {});
function V() {
return typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope;
}
async function ue() {
if (B())
w({ type: d.GLOBALS_SYNC }, p);
async function fe() {
if (V())
y({ type: u.GLOBALS_SYNC }, h);
else {
const t = [];
for (const e in G) {
const { worker: r, resolvers: s } = G[e].workerContext;
for (const e in Q) {
const { worker: r, resolvers: s } = Q[e].workerContext;
r && t.push(
le(
r,
d.GLOBALS_SYNC,
u.GLOBALS_SYNC,
"",
[p],
[h],
s

@@ -416,16 +420,16 @@ )

throw `undefined function [${r}] in class ${e.instance.constructor.workerId}`;
w(t, await e.instance[r](...s != null ? s : []));
y(t, await e.instance[r](...s ?? []));
}
const pe = W("registeredWorkers", {});
const ue = F("registeredWorkers", {});
function de(t, e) {
if (!t.args)
throw "Missing className while initializing worker";
const [r, s] = t.args, o = pe[r];
if (o)
e.instance = new o(t.args.slice(1));
const [r, s] = t.args, i = ue[r];
if (i)
e.instance = new i(t.args.slice(1));
else
throw `unknown worker class ${r}`;
P(s, p), w(t, typeof e.instance !== void 0);
P(s, h), y(t, typeof e.instance !== void 0);
}
async function me(t, e) {
async function pe(t, e) {
const { args: r } = t;

@@ -435,10 +439,10 @@ if (!e.instance)

let s;
e.instance.terminate && (s = await e.instance.terminate(...r != null ? r : [])), w(t, s);
e.instance.terminate && (s = await e.instance.terminate(...r ?? [])), y(t, s);
}
function ge(t) {
function me(t) {
if (!t.args)
throw "Missing globals while syncing";
P(t.args[0], p), w(t, {});
P(t.args[0], h), y(t, {});
}
function _e() {
function ge() {
const t = {};

@@ -448,13 +452,13 @@ onmessage = async (e) => {

switch (r.type) {
case d.INIT:
case u.INIT:
de(r, t);
break;
case d.FORWARD:
case u.FORWARD:
he(r, t);
break;
case d.TERMINATE:
me(r, t);
case u.TERMINATE:
pe(r, t);
break;
case d.GLOBALS_SYNC:
ge(r);
case u.GLOBALS_SYNC:
me(r);
break;

@@ -464,42 +468,42 @@ }

}
B() && _e();
function ye(t, e) {
return p[t] || (p[t] = e), [
() => p[t],
V() && ge();
function _e(t, e) {
return h[t] || (h[t] = e), [
() => h[t],
async (r) => {
p[t] = r, await ue();
h[t] = r, await fe();
}
];
}
function be(t, e) {
return ye(t, e);
function ye(t, e) {
return _e(t, e);
}
const [we, Te] = be("metadata");
function Ce(t) {
Te(t);
const [be, we] = ye("metadata");
function xe(t) {
we(t);
}
function C() {
return we();
function x() {
return be();
}
class D {
constructor(e) {
N(this, "uuid", ce()), this.config = e;
class L {
constructor(e, r) {
Z(this, "uuid"), this.config = e, this.uuid = r ?? ae();
}
async send(e) {
var r, s, o;
const { appId: i, sourceType: n } = (r = C()) != null ? r : {};
if (!i || !n)
var r, s, i;
const { appId: n, sourceType: o } = (r = x()) != null ? r : {};
if (!n || !o)
return "metadata missing";
const c = new AbortController(), u = setTimeout(() => c.abort(), se);
return await ((o = (s = this.config) == null ? void 0 : s.fetch) != null ? o : fetch)(this.getUrl(), {
const a = new AbortController(), k = setTimeout(() => a.abort(), te);
return await ((i = (s = this.config) == null ? void 0 : s.fetch) != null ? i : fetch)(this.getUrl(), {
method: "POST",
headers: this.getHeaders(),
body: JSON.stringify(this.buildReport(e)),
signal: c.signal
}), clearTimeout(u), "success";
signal: a.signal
}), clearTimeout(k), "success";
}
getUrl() {
var e;
let r = (e = C().proxyUrl) != null ? e : te;
return r += (r.at(-1) === "/" ? "" : "/") + re, r;
let r = (e = x().proxyUrl) != null ? e : re;
return r += (r.at(-1) === "/" ? "" : "/") + ee, r;
}

@@ -512,3 +516,3 @@ getHeaders() {

buildReport(e) {
const r = C();
const r = x();
return {

@@ -524,10 +528,6 @@ guid: this.uuid,

}
const R = "2.0.3";
class Se {
constructor(e) {
a(this, "frameTransformedCount", 0);
a(this, "frameFromSourceCount", 0);
a(this, "startAt", 0);
a(this, "reporter");
this.config = e, this.reporter = new D(e);
const E = "2.0.4";
class Te {
constructor(e, r) {
this.config = e, this.frameTransformedCount = 0, this.frameFromSourceCount = 0, this.startAt = 0, this.reporter = new L(e, r);
}

@@ -538,14 +538,14 @@ async onFrameFromSource() {

get fps() {
const { startAt: e, frameFromSourceCount: r } = this, o = (Date.now() - e) / 1e3;
return r / o;
const { startAt: e, frameFromSourceCount: r } = this, i = (Date.now() - e) / 1e3;
return r / i;
}
async onFrameTransformed(e = {}, r = !1) {
this.startAt === 0 && (this.startAt = Date.now()), this.frameTransformedCount++;
const { startAt: s, frameTransformedCount: o, frameFromSourceCount: i } = this, n = Date.now(), c = (n - s) / 1e3, u = o / c, M = i / c;
return r || this.frameTransformedCount >= this.config.loggingIntervalFrameCount ? (this.frameFromSourceCount = 0, this.frameTransformedCount = 0, this.startAt = n, this.reporter.config = this.config, this.reporter.send({
const { startAt: s, frameTransformedCount: i, frameFromSourceCount: n } = this, o = Date.now(), a = (o - s) / 1e3, k = i / a, W = n / a;
return r || this.frameTransformedCount >= this.config.loggingIntervalFrameCount ? (this.frameFromSourceCount = 0, this.frameTransformedCount = 0, this.startAt = o, this.reporter.config = this.config, this.reporter.send({
...this.config.report,
variation: "QoS",
fps: M,
transformedFps: u,
framesTransformed: o,
fps: W,
transformedFps: k,
framesTransformed: i,
...e

@@ -555,64 +555,61 @@ })) : "success";

}
var Ee = /* @__PURE__ */ ((t) => (t.FPS_DROP = "fps_drop", t))(Ee || {}), Re = /* @__PURE__ */ ((t) => (t.start = "start", t.transform = "transform", t.flush = "flush", t))(Re || {}), F = /* @__PURE__ */ ((t) => (t.pipeline_ended = "pipeline_ended", t.pipeline_ended_with_error = "pipeline_ended_with_error", t.pipeline_started = "pipeline_started", t.pipeline_started_with_error = "pipeline_started_with_error", t.pipeline_restarted = "pipeline_restarted", t.pipeline_restarted_with_error = "pipeline_restarted_with_error", t))(F || {});
const ke = 500, Ae = 0.8;
class Pe extends L {
constructor(r, s) {
super();
a(this, "reporter_", new D());
a(this, "reporterQos_", new Se({
loggingIntervalFrameCount: ke,
var Ee = /* @__PURE__ */ ((t) => (t.FPS_DROP = "fps_drop", t))(Ee || {}), Se = /* @__PURE__ */ ((t) => (t.start = "start", t.transform = "transform", t.flush = "flush", t))(Se || {}), O = /* @__PURE__ */ ((t) => (t.pipeline_ended = "pipeline_ended", t.pipeline_ended_with_error = "pipeline_ended_with_error", t.pipeline_started = "pipeline_started", t.pipeline_started_with_error = "pipeline_started_with_error", t.pipeline_restarted = "pipeline_restarted", t.pipeline_restarted_with_error = "pipeline_restarted_with_error", t))(O || {});
const Re = 500, Pe = 0.8;
class ke extends v {
constructor(e, r) {
super(), this.reporter_ = new L(), this.reporterQos_ = new Te({
loggingIntervalFrameCount: Re,
report: {
version: R
version: E
}
}));
a(this, "transformerType_");
a(this, "transformer_");
a(this, "shouldStop_");
a(this, "isFlashed_");
a(this, "mediaTransformerQosReportStartTimestamp_");
a(this, "videoHeight_");
a(this, "videoWidth_");
a(this, "trackExpectedRate_");
a(this, "index_");
a(this, "controller_");
this.index_ = s, this.transformer_ = r, this.shouldStop_ = !1, this.isFlashed_ = !1, this.mediaTransformerQosReportStartTimestamp_ = 0, this.videoHeight_ = 0, this.videoWidth_ = 0, this.trackExpectedRate_ = -1, this.transformerType_ = "Custom", "getTransformerType" in r && (this.transformerType_ = r.getTransformerType()), this.report({
}), this.index_ = r, this.transformer_ = e, this.shouldStop_ = !1, this.isFlashed_ = !1, this.mediaTransformerQosReportStartTimestamp_ = 0, this.videoHeight_ = 0, this.videoWidth_ = 0, this.trackExpectedRate_ = -1, this.transformerType_ = "Custom", "getTransformerType" in e && (this.transformerType_ = e.getTransformerType()), this.report({
variation: "Create"
});
}
setTrackExpectedRate(r) {
this.trackExpectedRate_ = r;
setTrackExpectedRate(e) {
this.trackExpectedRate_ = e;
}
async start(r) {
if (this.controller_ = r, this.transformer_ && typeof this.transformer_.start == "function")
async start(e) {
if (this.controller_ = e, this.transformer_ && typeof this.transformer_.start == "function")
try {
await this.transformer_.start(r);
} catch (s) {
await this.transformer_.start(e);
} catch (r) {
this.report({
message: l.errors.transformer_start,
variation: "Error",
error: v(s)
error: I(r)
});
const o = { eventMetaData: { transformerIndex: this.index_ }, error: s, function: "start" };
this.emit("error", o);
const s = {
eventMetaData: { transformerIndex: this.index_ },
error: r,
function: "start"
/* start */
};
this.emit("error", s);
}
}
async transform(r, s) {
var o, i, n, c;
if (this.mediaTransformerQosReportStartTimestamp_ === 0 && (this.mediaTransformerQosReportStartTimestamp_ = Date.now()), r instanceof VideoFrame && (this.videoHeight_ = (o = r == null ? void 0 : r.displayHeight) != null ? o : 0, this.videoWidth_ = (i = r == null ? void 0 : r.displayWidth) != null ? i : 0), this.reporterQos_.onFrameFromSource(), this.transformer_)
async transform(e, r) {
var s, i;
if (this.mediaTransformerQosReportStartTimestamp_ === 0 && (this.mediaTransformerQosReportStartTimestamp_ = Date.now()), e instanceof VideoFrame && (this.videoHeight_ = (e == null ? void 0 : e.displayHeight) ?? 0, this.videoWidth_ = (e == null ? void 0 : e.displayWidth) ?? 0), this.reporterQos_.onFrameFromSource(), this.transformer_)
if (this.shouldStop_)
console.warn("[Pipeline] flush from transform"), r.close(), this.flush(s), s.terminate();
console.warn("[Pipeline] flush from transform"), e.close(), this.flush(r), r.terminate();
else {
try {
await ((c = (n = this.transformer_).transform) == null ? void 0 : c.call(n, r, s)), this.reportQos();
} catch (u) {
await ((i = (s = this.transformer_).transform) == null ? void 0 : i.call(s, e, r)), this.reportQos();
} catch (n) {
this.report({
message: l.errors.transformer_transform,
variation: "Error",
error: v(u)
error: I(n)
});
const M = { eventMetaData: { transformerIndex: this.index_ }, error: u, function: "transform" };
this.emit("error", M);
const o = {
eventMetaData: { transformerIndex: this.index_ },
error: n,
function: "transform"
/* transform */
};
this.emit("error", o);
}
if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Ae > this.reporterQos_.fps) {
const u = {
if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Pe > this.reporterQos_.fps) {
const n = {
eventMetaData: {

@@ -627,19 +624,24 @@ transformerIndex: this.index_

};
this.emit("warn", u);
this.emit("warn", n);
}
}
}
async flush(r) {
async flush(e) {
if (this.transformer_ && typeof this.transformer_.flush == "function" && !this.isFlashed_) {
this.isFlashed_ = !0;
try {
await this.transformer_.flush(r);
} catch (s) {
await this.transformer_.flush(e);
} catch (r) {
this.report({
message: l.errors.transformer_flush,
variation: "Error",
error: v(s)
error: I(r)
});
const o = { eventMetaData: { transformerIndex: this.index_ }, error: s, function: "flush" };
this.emit("error", o);
const s = {
eventMetaData: { transformerIndex: this.index_ },
error: r,
function: "flush"
/* flush */
};
this.emit("error", s);
}

@@ -654,43 +656,43 @@ }

}
report(r) {
report(e) {
this.reporter_.send({
version: R,
version: E,
action: "MediaTransformer",
transformerType: this.transformerType_,
...r
...e
});
}
reportQos(r = !1) {
reportQos(e = !1) {
this.reporterQos_.config = {
...this.reporterQos_.config
}, this.reporterQos_.onFrameTransformed({
version: R,
action: "MediaTransformer",
transformerType: this.transformerType_,
videoWidth: this.videoWidth_,
videoHeight: this.videoHeight_
}, r);
}, this.reporterQos_.onFrameTransformed(
{
version: E,
action: "MediaTransformer",
transformerType: this.transformerType_,
videoWidth: this.videoWidth_,
videoHeight: this.videoHeight_
},
e
);
}
}
class Me extends L {
constructor(r) {
super();
a(this, "transformers_");
a(this, "trackExpectedRate_");
this.transformers_ = [], this.trackExpectedRate_ = -1;
for (let s = 0; s < r.length; s++) {
let o = new Pe(r[s], s);
o.on("error", (i) => {
class Ae extends v {
constructor(e) {
super(), this.transformers_ = [], this.trackExpectedRate_ = -1;
for (let r = 0; r < e.length; r++) {
let s = new ke(e[r], r);
s.on("error", (i) => {
this.emit("error", i);
}), o.on("warn", (i) => {
}), s.on("warn", (i) => {
this.emit("warn", i);
}), this.transformers_.push(o);
}), this.transformers_.push(s);
}
}
setTrackExpectedRate(r) {
this.trackExpectedRate_ = r;
for (let s of this.transformers_)
s.setTrackExpectedRate(this.trackExpectedRate_);
setTrackExpectedRate(e) {
this.trackExpectedRate_ = e;
for (let r of this.transformers_)
r.setTrackExpectedRate(this.trackExpectedRate_);
}
async start(r, s) {
async start(e, r) {
if (!this.transformers_ || this.transformers_.length === 0) {

@@ -701,47 +703,88 @@ console.log("[Pipeline] No transformers.");

try {
let o = r;
let s = e;
for (let i of this.transformers_)
r = r.pipeThrough(new TransformStream(i));
r.pipeTo(s).then(async () => {
console.log("[Pipeline] Setup."), await s.abort(), await o.cancel(), this.emit("pipelineInfo", "pipeline_ended");
e = e.pipeThrough(
new TransformStream(i)
);
e.pipeTo(r).then(async () => {
console.log("[Pipeline] Setup."), await r.abort(), await s.cancel(), this.emit(
"pipelineInfo",
"pipeline_ended"
/* pipeline_ended */
);
}).catch(async (i) => {
r.cancel().then(() => {
console.log("[Pipeline] Shutting down streams after abort.");
e.cancel().then(() => {
console.log(
"[Pipeline] Shutting down streams after abort."
);
}).catch((n) => {
console.error("[Pipeline] Error from stream transform:", n);
}), await s.abort(i), await o.cancel(i), this.emit("pipelineInfo", "pipeline_ended_with_error");
console.error(
"[Pipeline] Error from stream transform:",
n
);
}), await r.abort(i), await s.cancel(i), this.emit(
"pipelineInfo",
"pipeline_ended_with_error"
/* pipeline_ended_with_error */
);
});
} catch {
this.emit("pipelineInfo", "pipeline_started_with_error"), this.destroy();
this.emit(
"pipelineInfo",
"pipeline_started_with_error"
/* pipeline_started_with_error */
), this.destroy();
return;
}
this.emit("pipelineInfo", "pipeline_started"), console.log("[Pipeline] Pipeline started.");
this.emit(
"pipelineInfo",
"pipeline_started"
/* pipeline_started */
), console.log("[Pipeline] Pipeline started.");
}
async destroy() {
console.log("[Pipeline] Destroying Pipeline.");
for (let r of this.transformers_)
r.stop();
for (let e of this.transformers_)
e.stop();
}
}
class Oe extends L {
class Ce extends v {
constructor() {
super();
a(this, "reporter_");
a(this, "pipeline_");
a(this, "transformers_");
a(this, "readable_");
a(this, "writable_");
a(this, "trackExpectedRate_");
this.reporter_ = new D(), this.trackExpectedRate_ = -1, this.report({
super(), this.reporter_ = new L(), this.trackExpectedRate_ = -1, this.report({
variation: "Create"
});
}
setTrackExpectedRate(r) {
this.trackExpectedRate_ = r, this.pipeline_ && this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_);
/**
* Sets the expected rate of the track per second.
* The media processor will use this number for calculating drops in the rate.
* This could happen when the transformation will take more time than expected.
* This will not cause an error, just warning to the client.
* Mostly:
* Video: 30 frames per second
* Audio: 50 audio data per second for OPUS
* In case of increased frame dropping rate a warning will be emitted according to info [here](/docs/intro#errors-and-warnings-listener).
* ***This is an optional method.***
* @param trackExpectedRate - number holds the predicted track rate.
*/
setTrackExpectedRate(e) {
this.trackExpectedRate_ = e, this.pipeline_ && this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_);
}
transform(r, s) {
return this.readable_ = r, this.writable_ = s, this.transformInternal();
/**
* Starts running the tranformation logic performed by the media processor instance.
* When running an instance of this class on a Web worker thread the call for this function should be made by the user. See example [here](/docs/intro#webworker-code).
* When running an instance of this class on the application main thread there is no need to call this method given it will be called by the `MediaProcessorConnector` instance.
*
* @param readable Readable stream associated to the media source being processed.
* @param writable Writable stream associated to the resulting media once processed.
*
* @returns
*/
transform(e, r) {
return this.readable_ = e, this.writable_ = r, this.transformInternal();
}
/**
* @private
*/
transformInternal() {
return new Promise(async (r, s) => {
return new Promise(async (e, r) => {
if (!this.transformers_ || this.transformers_.length === 0) {

@@ -751,3 +794,3 @@ this.report({

variation: "Error"
}), s("[MediaProcessor] Need to set transformers.");
}), r("[MediaProcessor] Need to set transformers.");
return;

@@ -759,3 +802,3 @@ }

message: l.errors.readable_null
}), s("[MediaProcessor] Readable is null.");
}), r("[MediaProcessor] Readable is null.");
return;

@@ -767,7 +810,7 @@ }

message: l.errors.writable_null
}), s("[MediaProcessor] Writable is null.");
}), r("[MediaProcessor] Writable is null.");
return;
}
let o = !1;
this.pipeline_ && (o = !0, this.pipeline_.clearListeners(), this.pipeline_.destroy()), this.pipeline_ = new Me(this.transformers_), this.pipeline_.on("warn", (i) => {
let s = !1;
this.pipeline_ && (s = !0, this.pipeline_.clearListeners(), this.pipeline_.destroy()), this.pipeline_ = new Ae(this.transformers_), this.pipeline_.on("warn", (i) => {
this.emit("warn", i);

@@ -777,33 +820,43 @@ }), this.pipeline_.on("error", (i) => {

}), this.pipeline_.on("pipelineInfo", (i) => {
o && (i === "pipeline_started" ? i = F.pipeline_restarted : i === "pipeline_started_with_error" && (i = F.pipeline_restarted_with_error)), this.emit("pipelineInfo", i);
s && (i === "pipeline_started" ? i = O.pipeline_restarted : i === "pipeline_started_with_error" && (i = O.pipeline_restarted_with_error)), this.emit("pipelineInfo", i);
}), this.trackExpectedRate_ != -1 && this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_), this.pipeline_.start(this.readable_, this.writable_).then(() => {
r();
e();
}).catch((i) => {
s(i);
r(i);
});
});
}
setTransformers(r) {
/**
* Sets an array of transfromer instances that will be hold and ran by the media processor instance.
* See example [here](/docs/intro#main-code)
*
* @param transformers An array of transformer instances.
*
* @returns
*/
setTransformers(e) {
return this.report({
variation: "Update",
message: l.updates.transformer_new
}), this.transformers_ = r, this.readable_ && this.writable_ ? this.transformInternal() : Promise.resolve();
}), this.transformers_ = e, this.readable_ && this.writable_ ? this.transformInternal() : Promise.resolve();
}
/**
* Stops running the tranformation logic performed by the media processor instance.
* @returns
*/
destroy() {
return new Promise(async (r) => {
this.pipeline_ && this.pipeline_.destroy(), this.report({ variation: "Delete" }), r();
return new Promise(async (e) => {
this.pipeline_ && this.pipeline_.destroy(), this.report({ variation: "Delete" }), e();
});
}
report(r) {
report(e) {
this.reporter_.send({
version: R,
version: E,
action: "MediaProcessor",
...r
...e
});
}
}
class xe {
class Me {
constructor() {
a(this, "processor_");
a(this, "generator_");
this.processor_ = null, this.generator_ = null;

@@ -815,9 +868,17 @@ }

this.processor_ = new MediaStreamTrackProcessor(e);
} catch (o) {
console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${o}`), s(o);
} catch (i) {
console.log(
`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${i}`
), s(i);
}
try {
e.kind === "audio" ? this.generator_ = new MediaStreamTrackGenerator({ kind: "audio" }) : e.kind === "video" ? this.generator_ = new MediaStreamTrackGenerator({ kind: "video" }) : s("kind not supported");
} catch (o) {
console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${o}`), s(o);
e.kind === "audio" ? this.generator_ = new MediaStreamTrackGenerator({
kind: "audio"
}) : e.kind === "video" ? this.generator_ = new MediaStreamTrackGenerator({
kind: "video"
}) : s("kind not supported");
} catch (i) {
console.log(
`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${i}`
), s(i);
}

@@ -837,21 +898,41 @@ r();

}
class Fe {
class Oe {
/**
* - When running insertable streams on the main `MediaProcessorInterface` should be instance of `MediaProcessor` class.
* - When running insertable streams on WebWorker `MediaProcessorInterface` should be instance of bridge calss created by the user. Example can be found [here](/docs/intro.md#using-the-transformer-on-webworker)
* @param vonageMediaProcessor - MediaProcessorInterface.
*/
constructor(e) {
a(this, "insertableStreamHelper_");
a(this, "mediaProcessor_");
this.insertableStreamHelper_ = new xe(), this.mediaProcessor_ = e;
this.insertableStreamHelper_ = new Me(), this.mediaProcessor_ = e;
}
/**
* @private
* Sets the media stream track instance to be processed.
*
* @param track MediaStreamTrack (audio or video) to be processed.
*
* @returns New track to be used.
*/
setTrack(e) {
return new Promise((r, s) => {
this.insertableStreamHelper_.init(e).then(() => {
this.mediaProcessor_.transform(this.insertableStreamHelper_.getReadable(), this.insertableStreamHelper_.getWriteable()).then(() => {
r(this.insertableStreamHelper_.getProccesorTrack());
}).catch((o) => {
s(o);
this.mediaProcessor_.transform(
this.insertableStreamHelper_.getReadable(),
this.insertableStreamHelper_.getWriteable()
).then(() => {
r(
this.insertableStreamHelper_.getProccesorTrack()
);
}).catch((i) => {
s(i);
});
}).catch((o) => {
s(o);
}).catch((i) => {
s(i);
});
});
}
/**
* @private
* Stops the media processing being performed.
*/
destroy() {

@@ -868,11 +949,11 @@ return new Promise((e, r) => {

export {
Re as ErrorFunction,
Oe as MediaProcessor,
Fe as MediaProcessorConnector,
F as PipelineInfoData,
ee as VonageSourceType,
Se as ErrorFunction,
Ce as MediaProcessor,
Oe as MediaProcessorConnector,
O as PipelineInfoData,
N as VonageSourceType,
Ee as WarningType,
C as getVonageMetadata,
ve as isSupported,
Ce as setVonageMetadata
x as getVonageMetadata,
Ie as isSupported,
xe as setVonageMetadata
};

@@ -1,2 +0,2 @@

(function(f,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(f=typeof globalThis<"u"?globalThis:f||self,h(f["media-processor"]={}))})(this,function(f){"use strict";var Oe=Object.defineProperty;var Fe=(f,h,u)=>h in f?Oe(f,h,{enumerable:!0,configurable:!0,writable:!0,value:u}):f[h]=u;var a=(f,h,u)=>(Fe(f,typeof h!="symbol"?h+"":h,u),u);function h(){return new Promise((t,e)=>{typeof MediaStreamTrackProcessor>"u"||typeof MediaStreamTrackGenerator>"u"?e("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."):t()})}class u{}a(u,"updates",{transformer_new:"New transformer",transformer_null:"Null transformer"}),a(u,"errors",{transformer_none:"No transformers provided",transformer_start:"Cannot start transformer",transformer_transform:"Cannot transform frame",transformer_flush:"Cannot flush transformer",readable_null:"Readable is null",writable_null:"Writable is null"});const d=new WeakMap,E=new WeakMap,w=new WeakMap,C=Symbol("anyProducer"),H=Promise.resolve(),R=Symbol("listenerAdded"),k=Symbol("listenerRemoved");let O=!1;function y(t){if(typeof t!="string"&&typeof t!="symbol")throw new TypeError("eventName must be a string or a symbol")}function P(t){if(typeof t!="function")throw new TypeError("listener must be a function")}function b(t,e){const r=E.get(t);return r.has(e)||r.set(e,new Set),r.get(e)}function T(t,e){const r=typeof e=="string"||typeof e=="symbol"?e:C,s=w.get(t);return s.has(r)||s.set(r,new Set),s.get(r)}function Z(t,e,r){const s=w.get(t);if(s.has(e))for(const o of s.get(e))o.enqueue(r);if(s.has(C)){const o=Promise.all([e,r]);for(const i of s.get(C))i.enqueue(o)}}function Q(t,e){e=Array.isArray(e)?e:[e];let r=!1,s=()=>{},o=[];const i={enqueue(n){o.push(n),s()},finish(){r=!0,s()}};for(const n of e)T(t,n).add(i);return{async next(){return o?o.length===0?r?(o=void 0,this.next()):(await new Promise(n=>{s=n}),this.next()):{done:!1,value:await o.shift()}:{done:!0}},async return(n){o=void 0;for(const c of e)T(t,c).delete(i);return s(),arguments.length>0?{done:!0,value:await n}:{done:!0}},[Symbol.asyncIterator](){return this}}}function j(t){if(t===void 0)return z;if(!Array.isArray(t))throw new TypeError("`methodNames` must be an array of strings");for(const e of t)if(!z.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return t}const F=t=>t===R||t===k;class g{static mixin(e,r){return r=j(r),s=>{if(typeof s!="function")throw new TypeError("`target` must be function");for(const n of r)if(s.prototype[n]!==void 0)throw new Error(`The property \`${n}\` already exists on \`target\``);function o(){return Object.defineProperty(this,e,{enumerable:!1,value:new g}),this[e]}Object.defineProperty(s.prototype,e,{enumerable:!1,get:o});const i=n=>function(...c){return this[e][n](...c)};for(const n of r)Object.defineProperty(s.prototype,n,{enumerable:!1,value:i(n)});return s}}static get isDebugEnabled(){if(typeof process!="object")return O;const{env:e}=process||{env:{}};return e.DEBUG==="emittery"||e.DEBUG==="*"||O}static set isDebugEnabled(e){O=e}constructor(e={}){d.set(this,new Set),E.set(this,new Map),w.set(this,new Map),this.debug=e.debug||{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(r,s,o,i)=>{try{i=JSON.stringify(i)}catch{i=`Object with the following keys failed to stringify: ${Object.keys(i).join(",")}`}typeof o=="symbol"&&(o=o.toString());const n=new Date,c=`${n.getHours()}:${n.getMinutes()}:${n.getSeconds()}.${n.getMilliseconds()}`;console.log(`[${c}][emittery:${r}][${s}] Event Name: ${o}
data: ${i}`)})}logIfDebugEnabled(e,r,s){(g.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,r,s)}on(e,r){P(r),e=Array.isArray(e)?e:[e];for(const s of e)y(s),b(this,s).add(r),this.logIfDebugEnabled("subscribe",s,void 0),F(s)||this.emit(R,{eventName:s,listener:r});return this.off.bind(this,e,r)}off(e,r){P(r),e=Array.isArray(e)?e:[e];for(const s of e)y(s),b(this,s).delete(r),this.logIfDebugEnabled("unsubscribe",s,void 0),F(s)||this.emit(k,{eventName:s,listener:r})}once(e){return new Promise(r=>{const s=this.on(e,o=>{s(),r(o)})})}events(e){e=Array.isArray(e)?e:[e];for(const r of e)y(r);return Q(this,e)}async emit(e,r){y(e),this.logIfDebugEnabled("emit",e,r),Z(this,e,r);const s=b(this,e),o=d.get(this),i=[...s],n=F(e)?[]:[...o];await H,await Promise.all([...i.map(async c=>{if(s.has(c))return c(r)}),...n.map(async c=>{if(o.has(c))return c(e,r)})])}async emitSerial(e,r){y(e),this.logIfDebugEnabled("emitSerial",e,r);const s=b(this,e),o=d.get(this),i=[...s],n=[...o];await H;for(const c of i)s.has(c)&&await c(r);for(const c of n)o.has(c)&&await c(e,r)}onAny(e){return P(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),d.get(this).add(e),this.emit(R,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return Q(this)}offAny(e){P(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),this.emit(k,{listener:e}),d.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const r of e)if(this.logIfDebugEnabled("clear",r,void 0),typeof r=="string"||typeof r=="symbol"){b(this,r).clear();const s=T(this,r);for(const o of s)o.finish();s.clear()}else{d.get(this).clear();for(const s of E.get(this).values())s.clear();for(const s of w.get(this).values()){for(const o of s)o.finish();s.clear()}}}listenerCount(e){e=Array.isArray(e)?e:[e];let r=0;for(const s of e){if(typeof s=="string"){r+=d.get(this).size+b(this,s).size+T(this,s).size+T(this).size;continue}typeof s<"u"&&y(s),r+=d.get(this).size;for(const o of E.get(this).values())r+=o.size;for(const o of w.get(this).values())r+=o.size}return r}bindMethods(e,r){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");r=j(r);for(const s of r){if(e[s]!==void 0)throw new Error(`The property \`${s}\` already exists on \`target\``);Object.defineProperty(e,s,{enumerable:!1,value:this[s].bind(this)})}}}const z=Object.getOwnPropertyNames(g.prototype).filter(t=>t!=="constructor");Object.defineProperty(g,"listenerAdded",{value:R,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(g,"listenerRemoved",{value:k,writable:!1,enumerable:!0,configurable:!1});var L=g;function K(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}function N(t){if(K(t))return t;try{return new Error(JSON.stringify(t))}catch{return new Error(String(t))}}function W(t){return N(t).message}var ee=Object.defineProperty,re=(t,e,r)=>e in t?ee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>(re(t,typeof e!="symbol"?e+"":e,r),r),G=(t=>(t.automation="automation",t.test="test",t.vbc="vbc",t.video="video",t.voice="voice",t))(G||{});const se="hlg.tokbox.com/prod/logging/vcp_webrtc",oe="https://",ie=1e4;let A;const ne=new Uint8Array(16);function ae(){if(!A&&(A=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!A))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return A(ne)}const l=[];for(let t=0;t<256;++t)l.push((t+256).toString(16).slice(1));function ce(t,e=0){return(l[t[e+0]]+l[t[e+1]]+l[t[e+2]]+l[t[e+3]]+"-"+l[t[e+4]]+l[t[e+5]]+"-"+l[t[e+6]]+l[t[e+7]]+"-"+l[t[e+8]]+l[t[e+9]]+"-"+l[t[e+10]]+l[t[e+11]]+l[t[e+12]]+l[t[e+13]]+l[t[e+14]]+l[t[e+15]]).toLowerCase()}const fe=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),B={randomUUID:fe};function le(t,e,r){if(B.randomUUID&&!e&&!t)return B.randomUUID();t=t||{};const s=t.random||(t.rng||ae)();if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=s[o];return e}return ce(s)}function D(t,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[t]||(r[t]=e),r[t]}const p=D("globals",{});var _=(t=>(t.INIT="INIT",t.FORWARD="FORWARD",t.TERMINATE="TERMINATE",t.GLOBALS_SYNC="GLOBALS_SYNC",t))(_||{});function V(t){return[ImageBitmap,ReadableStream,WritableStream].some(e=>t instanceof e)}let ue=0;function he(t,e,r,s,o){const i=ue++;return t.postMessage({id:i,type:e,functionName:r,args:s},s.filter(n=>V(n))),new Promise(n=>{o==null||o.set(i,n)})}function S(t,e){const{id:r,type:s}=t,o=Array.isArray(e)?e:[e];postMessage({id:r,type:s,result:e},o.filter(i=>V(i)))}const Y=D("workerized",{});function q(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function de(){if(q())S({type:_.GLOBALS_SYNC},p);else{const t=[];for(const e in Y){const{worker:r,resolvers:s}=Y[e].workerContext;r&&t.push(he(r,_.GLOBALS_SYNC,"",[p],s))}await Promise.all(t)}}function M(t,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const r in e)delete e[r];for(const r in t)Array.isArray(t[r])?(e[r]=[],M(t[r],e[r])):typeof t[r]=="object"?(e[r]={},M(t[r],e[r])):e[r]=t[r]}async function pe(t,e){const{functionName:r,args:s}=t;if(!e.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!e.instance[r])throw`undefined function [${r}] in class ${e.instance.constructor.workerId}`;S(t,await e.instance[r](...s!=null?s:[]))}const me=D("registeredWorkers",{});function ge(t,e){if(!t.args)throw"Missing className while initializing worker";const[r,s]=t.args,o=me[r];if(o)e.instance=new o(t.args.slice(1));else throw`unknown worker class ${r}`;M(s,p),S(t,typeof e.instance!==void 0)}async function _e(t,e){const{args:r}=t;if(!e.instance)throw"instance not initialized";let s;e.instance.terminate&&(s=await e.instance.terminate(...r!=null?r:[])),S(t,s)}function ye(t){if(!t.args)throw"Missing globals while syncing";M(t.args[0],p),S(t,{})}function be(){const t={};onmessage=async e=>{const r=e.data;switch(r.type){case _.INIT:ge(r,t);break;case _.FORWARD:pe(r,t);break;case _.TERMINATE:_e(r,t);break;case _.GLOBALS_SYNC:ye(r);break}}}q()&&be();function we(t,e){return p[t]||(p[t]=e),[()=>p[t],async r=>{p[t]=r,await de()}]}function Te(t,e){return we(t,e)}const[Se,Ee]=Te("metadata");function Re(t){Ee(t)}function I(){return Se()}class U{constructor(e){te(this,"uuid",le()),this.config=e}async send(e){var r,s,o;const{appId:i,sourceType:n}=(r=I())!=null?r:{};if(!i||!n)return"metadata missing";const c=new AbortController,m=setTimeout(()=>c.abort(),ie);return await((o=(s=this.config)==null?void 0:s.fetch)!=null?o:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:c.signal}),clearTimeout(m),"success"}getUrl(){var e;let r=(e=I().proxyUrl)!=null?e:oe;return r+=(r.at(-1)==="/"?"":"/")+se,r}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const r=I();return{guid:this.uuid,...e,applicationId:r.appId,timestamp:Date.now(),proxyUrl:r.proxyUrl,source:r.sourceType}}}const x="2.0.3";class ke{constructor(e){a(this,"frameTransformedCount",0);a(this,"frameFromSourceCount",0);a(this,"startAt",0);a(this,"reporter");this.config=e,this.reporter=new U(e)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:r}=this,o=(Date.now()-e)/1e3;return r/o}async onFrameTransformed(e={},r=!1){this.startAt===0&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:s,frameTransformedCount:o,frameFromSourceCount:i}=this,n=Date.now(),c=(n-s)/1e3,m=o/c,$=i/c;return r||this.frameTransformedCount>=this.config.loggingIntervalFrameCount?(this.frameFromSourceCount=0,this.frameTransformedCount=0,this.startAt=n,this.reporter.config=this.config,this.reporter.send({...this.config.report,variation:"QoS",fps:$,transformedFps:m,framesTransformed:o,...e})):"success"}}var J=(t=>(t.FPS_DROP="fps_drop",t))(J||{}),X=(t=>(t.start="start",t.transform="transform",t.flush="flush",t))(X||{}),v=(t=>(t.pipeline_ended="pipeline_ended",t.pipeline_ended_with_error="pipeline_ended_with_error",t.pipeline_started="pipeline_started",t.pipeline_started_with_error="pipeline_started_with_error",t.pipeline_restarted="pipeline_restarted",t.pipeline_restarted_with_error="pipeline_restarted_with_error",t))(v||{});const Pe=500,Ae=.8;class Me extends L{constructor(r,s){super();a(this,"reporter_",new U);a(this,"reporterQos_",new ke({loggingIntervalFrameCount:Pe,report:{version:x}}));a(this,"transformerType_");a(this,"transformer_");a(this,"shouldStop_");a(this,"isFlashed_");a(this,"mediaTransformerQosReportStartTimestamp_");a(this,"videoHeight_");a(this,"videoWidth_");a(this,"trackExpectedRate_");a(this,"index_");a(this,"controller_");this.index_=s,this.transformer_=r,this.shouldStop_=!1,this.isFlashed_=!1,this.mediaTransformerQosReportStartTimestamp_=0,this.videoHeight_=0,this.videoWidth_=0,this.trackExpectedRate_=-1,this.transformerType_="Custom","getTransformerType"in r&&(this.transformerType_=r.getTransformerType()),this.report({variation:"Create"})}setTrackExpectedRate(r){this.trackExpectedRate_=r}async start(r){if(this.controller_=r,this.transformer_&&typeof this.transformer_.start=="function")try{await this.transformer_.start(r)}catch(s){this.report({message:u.errors.transformer_start,variation:"Error",error:W(s)});const o={eventMetaData:{transformerIndex:this.index_},error:s,function:"start"};this.emit("error",o)}}async transform(r,s){var o,i,n,c;if(this.mediaTransformerQosReportStartTimestamp_===0&&(this.mediaTransformerQosReportStartTimestamp_=Date.now()),r instanceof VideoFrame&&(this.videoHeight_=(o=r==null?void 0:r.displayHeight)!=null?o:0,this.videoWidth_=(i=r==null?void 0:r.displayWidth)!=null?i:0),this.reporterQos_.onFrameFromSource(),this.transformer_)if(this.shouldStop_)console.warn("[Pipeline] flush from transform"),r.close(),this.flush(s),s.terminate();else{try{await((c=(n=this.transformer_).transform)==null?void 0:c.call(n,r,s)),this.reportQos()}catch(m){this.report({message:u.errors.transformer_transform,variation:"Error",error:W(m)});const $={eventMetaData:{transformerIndex:this.index_},error:m,function:"transform"};this.emit("error",$)}if(this.trackExpectedRate_!=-1&&this.trackExpectedRate_*Ae>this.reporterQos_.fps){const m={eventMetaData:{transformerIndex:this.index_},warningType:"fps_drop",dropInfo:{requested:this.trackExpectedRate_,current:this.reporterQos_.fps}};this.emit("warn",m)}}}async flush(r){if(this.transformer_&&typeof this.transformer_.flush=="function"&&!this.isFlashed_){this.isFlashed_=!0;try{await this.transformer_.flush(r)}catch(s){this.report({message:u.errors.transformer_flush,variation:"Error",error:W(s)});const o={eventMetaData:{transformerIndex:this.index_},error:s,function:"flush"};this.emit("error",o)}}this.reportQos(!0),this.report({variation:"Delete"})}stop(){console.log("[Pipeline] Stop stream."),this.controller_&&(this.flush(this.controller_),this.controller_.terminate()),this.shouldStop_=!0}report(r){this.reporter_.send({version:x,action:"MediaTransformer",transformerType:this.transformerType_,...r})}reportQos(r=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:x,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},r)}}class Ie extends L{constructor(r){super();a(this,"transformers_");a(this,"trackExpectedRate_");this.transformers_=[],this.trackExpectedRate_=-1;for(let s=0;s<r.length;s++){let o=new Me(r[s],s);o.on("error",i=>{this.emit("error",i)}),o.on("warn",i=>{this.emit("warn",i)}),this.transformers_.push(o)}}setTrackExpectedRate(r){this.trackExpectedRate_=r;for(let s of this.transformers_)s.setTrackExpectedRate(this.trackExpectedRate_)}async start(r,s){if(!this.transformers_||this.transformers_.length===0){console.log("[Pipeline] No transformers.");return}try{let o=r;for(let i of this.transformers_)r=r.pipeThrough(new TransformStream(i));r.pipeTo(s).then(async()=>{console.log("[Pipeline] Setup."),await s.abort(),await o.cancel(),this.emit("pipelineInfo","pipeline_ended")}).catch(async i=>{r.cancel().then(()=>{console.log("[Pipeline] Shutting down streams after abort.")}).catch(n=>{console.error("[Pipeline] Error from stream transform:",n)}),await s.abort(i),await o.cancel(i),this.emit("pipelineInfo","pipeline_ended_with_error")})}catch{this.emit("pipelineInfo","pipeline_started_with_error"),this.destroy();return}this.emit("pipelineInfo","pipeline_started"),console.log("[Pipeline] Pipeline started.")}async destroy(){console.log("[Pipeline] Destroying Pipeline.");for(let r of this.transformers_)r.stop()}}class xe extends L{constructor(){super();a(this,"reporter_");a(this,"pipeline_");a(this,"transformers_");a(this,"readable_");a(this,"writable_");a(this,"trackExpectedRate_");this.reporter_=new U,this.trackExpectedRate_=-1,this.report({variation:"Create"})}setTrackExpectedRate(r){this.trackExpectedRate_=r,this.pipeline_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_)}transform(r,s){return this.readable_=r,this.writable_=s,this.transformInternal()}transformInternal(){return new Promise(async(r,s)=>{if(!this.transformers_||this.transformers_.length===0){this.report({message:u.errors.transformer_none,variation:"Error"}),s("[MediaProcessor] Need to set transformers.");return}if(!this.readable_){this.report({variation:"Error",message:u.errors.readable_null}),s("[MediaProcessor] Readable is null.");return}if(!this.writable_){this.report({variation:"Error",message:u.errors.writable_null}),s("[MediaProcessor] Writable is null.");return}let o=!1;this.pipeline_&&(o=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new Ie(this.transformers_),this.pipeline_.on("warn",i=>{this.emit("warn",i)}),this.pipeline_.on("error",i=>{this.emit("error",i)}),this.pipeline_.on("pipelineInfo",i=>{o&&(i==="pipeline_started"?i=v.pipeline_restarted:i==="pipeline_started_with_error"&&(i=v.pipeline_restarted_with_error)),this.emit("pipelineInfo",i)}),this.trackExpectedRate_!=-1&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_),this.pipeline_.start(this.readable_,this.writable_).then(()=>{r()}).catch(i=>{s(i)})})}setTransformers(r){return this.report({variation:"Update",message:u.updates.transformer_new}),this.transformers_=r,this.readable_&&this.writable_?this.transformInternal():Promise.resolve()}destroy(){return new Promise(async r=>{this.pipeline_&&this.pipeline_.destroy(),this.report({variation:"Delete"}),r()})}report(r){this.reporter_.send({version:x,action:"MediaProcessor",...r})}}class ve{constructor(){a(this,"processor_");a(this,"generator_");this.processor_=null,this.generator_=null}init(e){return new Promise((r,s)=>{try{this.processor_=new MediaStreamTrackProcessor(e)}catch(o){console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${o}`),s(o)}try{e.kind==="audio"?this.generator_=new MediaStreamTrackGenerator({kind:"audio"}):e.kind==="video"?this.generator_=new MediaStreamTrackGenerator({kind:"video"}):s("kind not supported")}catch(o){console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${o}`),s(o)}r()})}getReadable(){return this.processor_.readable}getWriteable(){return this.generator_.writable}getProccesorTrack(){return this.generator_}}class Ce{constructor(e){a(this,"insertableStreamHelper_");a(this,"mediaProcessor_");this.insertableStreamHelper_=new ve,this.mediaProcessor_=e}setTrack(e){return new Promise((r,s)=>{this.insertableStreamHelper_.init(e).then(()=>{this.mediaProcessor_.transform(this.insertableStreamHelper_.getReadable(),this.insertableStreamHelper_.getWriteable()).then(()=>{r(this.insertableStreamHelper_.getProccesorTrack())}).catch(o=>{s(o)})}).catch(o=>{s(o)})})}destroy(){return new Promise((e,r)=>{this.mediaProcessor_?this.mediaProcessor_.destroy().then(()=>{e()}).catch(s=>{r(s)}):r("no processor")})}}f.ErrorFunction=X,f.MediaProcessor=xe,f.MediaProcessorConnector=Ce,f.PipelineInfoData=v,f.VonageSourceType=G,f.WarningType=J,f.getVonageMetadata=I,f.isSupported=h,f.setVonageMetadata=Re,Object.defineProperties(f,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
(function(l,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):(l=typeof globalThis<"u"?globalThis:l||self,_(l["media-processor"]={}))})(this,function(l){"use strict";function _(){return new Promise((t,e)=>{typeof MediaStreamTrackProcessor>"u"||typeof MediaStreamTrackGenerator>"u"?e("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."):t()})}class f{}f.updates={transformer_new:"New transformer",transformer_null:"Null transformer"},f.errors={transformer_none:"No transformers provided",transformer_start:"Cannot start transformer",transformer_transform:"Cannot transform frame",transformer_flush:"Cannot flush transformer",readable_null:"Readable is null",writable_null:"Writable is null"};function K(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}const u=new WeakMap,T=new WeakMap,y=new WeakMap,C=Symbol("anyProducer"),D=Promise.resolve(),S=Symbol("listenerAdded"),E=Symbol("listenerRemoved");let O=!1;function m(t){if(typeof t!="string"&&typeof t!="symbol")throw new TypeError("eventName must be a string or a symbol")}function R(t){if(typeof t!="function")throw new TypeError("listener must be a function")}function g(t,e){const r=T.get(t);return r.has(e)||r.set(e,new Set),r.get(e)}function b(t,e){const r=typeof e=="string"||typeof e=="symbol"?e:C,s=y.get(t);return s.has(r)||s.set(r,new Set),s.get(r)}function X(t,e,r){const s=y.get(t);if(s.has(e))for(const i of s.get(e))i.enqueue(r);if(s.has(C)){const i=Promise.all([e,r]);for(const n of s.get(C))n.enqueue(i)}}function $(t,e){e=Array.isArray(e)?e:[e];let r=!1,s=()=>{},i=[];const n={enqueue(o){i.push(o),s()},finish(){r=!0,s()}};for(const o of e)b(t,o).add(n);return{async next(){return i?i.length===0?r?(i=void 0,this.next()):(await new Promise(o=>{s=o}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(o){i=void 0;for(const a of e)b(t,a).delete(n);return s(),arguments.length>0?{done:!0,value:await o}:{done:!0}},[Symbol.asyncIterator](){return this}}}function G(t){if(t===void 0)return H;if(!Array.isArray(t))throw new TypeError("`methodNames` must be an array of strings");for(const e of t)if(!H.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return t}const v=t=>t===S||t===E;class d{static mixin(e,r){return r=G(r),s=>{if(typeof s!="function")throw new TypeError("`target` must be function");for(const o of r)if(s.prototype[o]!==void 0)throw new Error(`The property \`${o}\` already exists on \`target\``);function i(){return Object.defineProperty(this,e,{enumerable:!1,value:new d}),this[e]}Object.defineProperty(s.prototype,e,{enumerable:!1,get:i});const n=o=>function(...a){return this[e][o](...a)};for(const o of r)Object.defineProperty(s.prototype,o,{enumerable:!1,value:n(o)});return s}}static get isDebugEnabled(){if(typeof process!="object")return O;const{env:e}=process||{env:{}};return e.DEBUG==="emittery"||e.DEBUG==="*"||O}static set isDebugEnabled(e){O=e}constructor(e={}){u.set(this,new Set),T.set(this,new Map),y.set(this,new Map),this.debug=e.debug||{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(r,s,i,n)=>{try{n=JSON.stringify(n)}catch{n=`Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`}typeof i=="symbol"&&(i=i.toString());const o=new Date,a=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${a}][emittery:${r}][${s}] Event Name: ${i}
data: ${n}`)})}logIfDebugEnabled(e,r,s){(d.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,r,s)}on(e,r){R(r),e=Array.isArray(e)?e:[e];for(const s of e)m(s),g(this,s).add(r),this.logIfDebugEnabled("subscribe",s,void 0),v(s)||this.emit(S,{eventName:s,listener:r});return this.off.bind(this,e,r)}off(e,r){R(r),e=Array.isArray(e)?e:[e];for(const s of e)m(s),g(this,s).delete(r),this.logIfDebugEnabled("unsubscribe",s,void 0),v(s)||this.emit(E,{eventName:s,listener:r})}once(e){return new Promise(r=>{const s=this.on(e,i=>{s(),r(i)})})}events(e){e=Array.isArray(e)?e:[e];for(const r of e)m(r);return $(this,e)}async emit(e,r){m(e),this.logIfDebugEnabled("emit",e,r),X(this,e,r);const s=g(this,e),i=u.get(this),n=[...s],o=v(e)?[]:[...i];await D,await Promise.all([...n.map(async a=>{if(s.has(a))return a(r)}),...o.map(async a=>{if(i.has(a))return a(e,r)})])}async emitSerial(e,r){m(e),this.logIfDebugEnabled("emitSerial",e,r);const s=g(this,e),i=u.get(this),n=[...s],o=[...i];await D;for(const a of n)s.has(a)&&await a(r);for(const a of o)i.has(a)&&await a(e,r)}onAny(e){return R(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),u.get(this).add(e),this.emit(S,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return $(this)}offAny(e){R(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),this.emit(E,{listener:e}),u.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const r of e)if(this.logIfDebugEnabled("clear",r,void 0),typeof r=="string"||typeof r=="symbol"){g(this,r).clear();const s=b(this,r);for(const i of s)i.finish();s.clear()}else{u.get(this).clear();for(const s of T.get(this).values())s.clear();for(const s of y.get(this).values()){for(const i of s)i.finish();s.clear()}}}listenerCount(e){e=Array.isArray(e)?e:[e];let r=0;for(const s of e){if(typeof s=="string"){r+=u.get(this).size+g(this,s).size+b(this,s).size+b(this).size;continue}typeof s<"u"&&m(s),r+=u.get(this).size;for(const i of T.get(this).values())r+=i.size;for(const i of y.get(this).values())r+=i.size}return r}bindMethods(e,r){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");r=G(r);for(const s of r){if(e[s]!==void 0)throw new Error(`The property \`${s}\` already exists on \`target\``);Object.defineProperty(e,s,{enumerable:!1,value:this[s].bind(this)})}}}const H=Object.getOwnPropertyNames(d.prototype).filter(t=>t!=="constructor");Object.defineProperty(d,"listenerAdded",{value:S,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(d,"listenerRemoved",{value:E,writable:!1,enumerable:!0,configurable:!1});var Z=d;const x=K(Z);function N(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}function ee(t){if(N(t))return t;try{return new Error(JSON.stringify(t))}catch{return new Error(String(t))}}function F(t){return ee(t).message}var re=Object.defineProperty,te=(t,e,r)=>e in t?re(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,se=(t,e,r)=>(te(t,typeof e!="symbol"?e+"":e,r),r),Q=(t=>(t.automation="automation",t.test="test",t.vbc="vbc",t.video="video",t.voice="voice",t))(Q||{});const ie="hlg.tokbox.com/prod/logging/vcp_webrtc",ne="https://",oe=1e4;let P;const ae=new Uint8Array(16);function ce(){if(!P&&(P=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!P))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return P(ae)}const c=[];for(let t=0;t<256;++t)c.push((t+256).toString(16).slice(1));function le(t,e=0){return(c[t[e+0]]+c[t[e+1]]+c[t[e+2]]+c[t[e+3]]+"-"+c[t[e+4]]+c[t[e+5]]+"-"+c[t[e+6]]+c[t[e+7]]+"-"+c[t[e+8]]+c[t[e+9]]+"-"+c[t[e+10]]+c[t[e+11]]+c[t[e+12]]+c[t[e+13]]+c[t[e+14]]+c[t[e+15]]).toLowerCase()}const z={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function fe(t,e,r){if(z.randomUUID&&!e&&!t)return z.randomUUID();t=t||{};const s=t.random||(t.rng||ce)();if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){r=r||0;for(let i=0;i<16;++i)e[r+i]=s[i];return e}return le(s)}function L(t,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[t]||(r[t]=e),r[t]}const h=L("globals",{});var p=(t=>(t.INIT="INIT",t.FORWARD="FORWARD",t.TERMINATE="TERMINATE",t.GLOBALS_SYNC="GLOBALS_SYNC",t))(p||{});function V(t){return[ImageBitmap,ReadableStream,WritableStream].some(r=>t instanceof r)}let ue=0;function he(t,e,r,s,i){const n=ue++;return t.postMessage({id:n,type:e,functionName:r,args:s},s.filter(a=>V(a))),new Promise(a=>{i==null||i.set(n,a)})}function w(t,e){const{id:r,type:s}=t,i=Array.isArray(e)?e:[e];postMessage({id:r,type:s,result:e},i.filter(n=>V(n)))}const j=L("workerized",{});function B(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function de(){if(B())w({type:p.GLOBALS_SYNC},h);else{const t=[];for(const e in j){const{worker:r,resolvers:s}=j[e].workerContext;r&&t.push(he(r,p.GLOBALS_SYNC,"",[h],s))}await Promise.all(t)}}function M(t,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const r in e)delete e[r];for(const r in t)Array.isArray(t[r])?(e[r]=[],M(t[r],e[r])):typeof t[r]=="object"?(e[r]={},M(t[r],e[r])):e[r]=t[r]}async function pe(t,e){const{functionName:r,args:s}=t;if(!e.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!e.instance[r])throw`undefined function [${r}] in class ${e.instance.constructor.workerId}`;w(t,await e.instance[r](...s??[]))}const me=L("registeredWorkers",{});function ge(t,e){if(!t.args)throw"Missing className while initializing worker";const[r,s]=t.args,i=me[r];if(i)e.instance=new i(t.args.slice(1));else throw`unknown worker class ${r}`;M(s,h),w(t,typeof e.instance!==void 0)}async function _e(t,e){const{args:r}=t;if(!e.instance)throw"instance not initialized";let s;e.instance.terminate&&(s=await e.instance.terminate(...r??[])),w(t,s)}function ye(t){if(!t.args)throw"Missing globals while syncing";M(t.args[0],h),w(t,{})}function be(){const t={};onmessage=async e=>{const r=e.data;switch(r.type){case p.INIT:ge(r,t);break;case p.FORWARD:pe(r,t);break;case p.TERMINATE:_e(r,t);break;case p.GLOBALS_SYNC:ye(r);break}}}B()&&be();function we(t,e){return h[t]||(h[t]=e),[()=>h[t],async r=>{h[t]=r,await de()}]}function Te(t,e){return we(t,e)}const[Se,Ee]=Te("metadata");function Re(t){Ee(t)}function k(){return Se()}class W{constructor(e,r){se(this,"uuid"),this.config=e,this.uuid=r??fe()}async send(e){var r,s,i;const{appId:n,sourceType:o}=(r=k())!=null?r:{};if(!n||!o)return"metadata missing";const a=new AbortController,U=setTimeout(()=>a.abort(),oe);return await((i=(s=this.config)==null?void 0:s.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(U),"success"}getUrl(){var e;let r=(e=k().proxyUrl)!=null?e:ne;return r+=(r.at(-1)==="/"?"":"/")+ie,r}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const r=k();return{guid:this.uuid,...e,applicationId:r.appId,timestamp:Date.now(),proxyUrl:r.proxyUrl,source:r.sourceType}}}const A="2.0.4";class Pe{constructor(e,r){this.config=e,this.frameTransformedCount=0,this.frameFromSourceCount=0,this.startAt=0,this.reporter=new W(e,r)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:r}=this,i=(Date.now()-e)/1e3;return r/i}async onFrameTransformed(e={},r=!1){this.startAt===0&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:s,frameTransformedCount:i,frameFromSourceCount:n}=this,o=Date.now(),a=(o-s)/1e3,U=i/a,J=n/a;return r||this.frameTransformedCount>=this.config.loggingIntervalFrameCount?(this.frameFromSourceCount=0,this.frameTransformedCount=0,this.startAt=o,this.reporter.config=this.config,this.reporter.send({...this.config.report,variation:"QoS",fps:J,transformedFps:U,framesTransformed:i,...e})):"success"}}var Y=(t=>(t.FPS_DROP="fps_drop",t))(Y||{}),q=(t=>(t.start="start",t.transform="transform",t.flush="flush",t))(q||{}),I=(t=>(t.pipeline_ended="pipeline_ended",t.pipeline_ended_with_error="pipeline_ended_with_error",t.pipeline_started="pipeline_started",t.pipeline_started_with_error="pipeline_started_with_error",t.pipeline_restarted="pipeline_restarted",t.pipeline_restarted_with_error="pipeline_restarted_with_error",t))(I||{});const Me=500,ke=.8;class Ae extends x{constructor(e,r){super(),this.reporter_=new W,this.reporterQos_=new Pe({loggingIntervalFrameCount:Me,report:{version:A}}),this.index_=r,this.transformer_=e,this.shouldStop_=!1,this.isFlashed_=!1,this.mediaTransformerQosReportStartTimestamp_=0,this.videoHeight_=0,this.videoWidth_=0,this.trackExpectedRate_=-1,this.transformerType_="Custom","getTransformerType"in e&&(this.transformerType_=e.getTransformerType()),this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e}async start(e){if(this.controller_=e,this.transformer_&&typeof this.transformer_.start=="function")try{await this.transformer_.start(e)}catch(r){this.report({message:f.errors.transformer_start,variation:"Error",error:F(r)});const s={eventMetaData:{transformerIndex:this.index_},error:r,function:"start"};this.emit("error",s)}}async transform(e,r){var s,i;if(this.mediaTransformerQosReportStartTimestamp_===0&&(this.mediaTransformerQosReportStartTimestamp_=Date.now()),e instanceof VideoFrame&&(this.videoHeight_=(e==null?void 0:e.displayHeight)??0,this.videoWidth_=(e==null?void 0:e.displayWidth)??0),this.reporterQos_.onFrameFromSource(),this.transformer_)if(this.shouldStop_)console.warn("[Pipeline] flush from transform"),e.close(),this.flush(r),r.terminate();else{try{await((i=(s=this.transformer_).transform)==null?void 0:i.call(s,e,r)),this.reportQos()}catch(n){this.report({message:f.errors.transformer_transform,variation:"Error",error:F(n)});const o={eventMetaData:{transformerIndex:this.index_},error:n,function:"transform"};this.emit("error",o)}if(this.trackExpectedRate_!=-1&&this.trackExpectedRate_*ke>this.reporterQos_.fps){const n={eventMetaData:{transformerIndex:this.index_},warningType:"fps_drop",dropInfo:{requested:this.trackExpectedRate_,current:this.reporterQos_.fps}};this.emit("warn",n)}}}async flush(e){if(this.transformer_&&typeof this.transformer_.flush=="function"&&!this.isFlashed_){this.isFlashed_=!0;try{await this.transformer_.flush(e)}catch(r){this.report({message:f.errors.transformer_flush,variation:"Error",error:F(r)});const s={eventMetaData:{transformerIndex:this.index_},error:r,function:"flush"};this.emit("error",s)}}this.reportQos(!0),this.report({variation:"Delete"})}stop(){console.log("[Pipeline] Stop stream."),this.controller_&&(this.flush(this.controller_),this.controller_.terminate()),this.shouldStop_=!0}report(e){this.reporter_.send({version:A,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:A,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class Ie extends x{constructor(e){super(),this.transformers_=[],this.trackExpectedRate_=-1;for(let r=0;r<e.length;r++){let s=new Ae(e[r],r);s.on("error",i=>{this.emit("error",i)}),s.on("warn",i=>{this.emit("warn",i)}),this.transformers_.push(s)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let r of this.transformers_)r.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,r){if(!this.transformers_||this.transformers_.length===0){console.log("[Pipeline] No transformers.");return}try{let s=e;for(let i of this.transformers_)e=e.pipeThrough(new TransformStream(i));e.pipeTo(r).then(async()=>{console.log("[Pipeline] Setup."),await r.abort(),await s.cancel(),this.emit("pipelineInfo","pipeline_ended")}).catch(async i=>{e.cancel().then(()=>{console.log("[Pipeline] Shutting down streams after abort.")}).catch(n=>{console.error("[Pipeline] Error from stream transform:",n)}),await r.abort(i),await s.cancel(i),this.emit("pipelineInfo","pipeline_ended_with_error")})}catch{this.emit("pipelineInfo","pipeline_started_with_error"),this.destroy();return}this.emit("pipelineInfo","pipeline_started"),console.log("[Pipeline] Pipeline started.")}async destroy(){console.log("[Pipeline] Destroying Pipeline.");for(let e of this.transformers_)e.stop()}}class Ce extends x{constructor(){super(),this.reporter_=new W,this.trackExpectedRate_=-1,this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e,this.pipeline_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_)}transform(e,r){return this.readable_=e,this.writable_=r,this.transformInternal()}transformInternal(){return new Promise(async(e,r)=>{if(!this.transformers_||this.transformers_.length===0){this.report({message:f.errors.transformer_none,variation:"Error"}),r("[MediaProcessor] Need to set transformers.");return}if(!this.readable_){this.report({variation:"Error",message:f.errors.readable_null}),r("[MediaProcessor] Readable is null.");return}if(!this.writable_){this.report({variation:"Error",message:f.errors.writable_null}),r("[MediaProcessor] Writable is null.");return}let s=!1;this.pipeline_&&(s=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new Ie(this.transformers_),this.pipeline_.on("warn",i=>{this.emit("warn",i)}),this.pipeline_.on("error",i=>{this.emit("error",i)}),this.pipeline_.on("pipelineInfo",i=>{s&&(i==="pipeline_started"?i=I.pipeline_restarted:i==="pipeline_started_with_error"&&(i=I.pipeline_restarted_with_error)),this.emit("pipelineInfo",i)}),this.trackExpectedRate_!=-1&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_),this.pipeline_.start(this.readable_,this.writable_).then(()=>{e()}).catch(i=>{r(i)})})}setTransformers(e){return this.report({variation:"Update",message:f.updates.transformer_new}),this.transformers_=e,this.readable_&&this.writable_?this.transformInternal():Promise.resolve()}destroy(){return new Promise(async e=>{this.pipeline_&&this.pipeline_.destroy(),this.report({variation:"Delete"}),e()})}report(e){this.reporter_.send({version:A,action:"MediaProcessor",...e})}}class Oe{constructor(){this.processor_=null,this.generator_=null}init(e){return new Promise((r,s)=>{try{this.processor_=new MediaStreamTrackProcessor(e)}catch(i){console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${i}`),s(i)}try{e.kind==="audio"?this.generator_=new MediaStreamTrackGenerator({kind:"audio"}):e.kind==="video"?this.generator_=new MediaStreamTrackGenerator({kind:"video"}):s("kind not supported")}catch(i){console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${i}`),s(i)}r()})}getReadable(){return this.processor_.readable}getWriteable(){return this.generator_.writable}getProccesorTrack(){return this.generator_}}class ve{constructor(e){this.insertableStreamHelper_=new Oe,this.mediaProcessor_=e}setTrack(e){return new Promise((r,s)=>{this.insertableStreamHelper_.init(e).then(()=>{this.mediaProcessor_.transform(this.insertableStreamHelper_.getReadable(),this.insertableStreamHelper_.getWriteable()).then(()=>{r(this.insertableStreamHelper_.getProccesorTrack())}).catch(i=>{s(i)})}).catch(i=>{s(i)})})}destroy(){return new Promise((e,r)=>{this.mediaProcessor_?this.mediaProcessor_.destroy().then(()=>{e()}).catch(s=>{r(s)}):r("no processor")})}}l.ErrorFunction=q,l.MediaProcessor=Ce,l.MediaProcessorConnector=ve,l.PipelineInfoData=I,l.VonageSourceType=Q,l.WarningType=Y,l.getVonageMetadata=k,l.isSupported=_,l.setVonageMetadata=Re,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})});

@@ -1,4 +0,4 @@

import Pipeline, { EventDataMap } from './pipeline';
import Emittery from 'emittery';
import { MediaProcessorInterface } from './MediaProcessorInterface';
import Pipeline, { EventDataMap } from "./pipeline";
import Emittery from "emittery";
import { MediaProcessorInterface } from "./MediaProcessorInterface";
import { Reporter } from "@vonage/js-onewebrtc-telemetry";

@@ -39,13 +39,13 @@ /**

/**
* Sets the expected rate of the track per second.
* The media processor will use this number for calculating drops in the rate.
* This could happen when the transformation will take more time than expected.
* This will not cause an error, just warning to the client.
* Mostly:
* Video: 30 frames per second
* Audio: 50 audio data per second for OPUS
* In case of increased frame dropping rate a warning will be emitted according to info [here](/docs/intro#errors-and-warnings-listener).
* ***This is an optional method.***
* @param trackExpectedRate - number holds the predicted track rate.
*/
* Sets the expected rate of the track per second.
* The media processor will use this number for calculating drops in the rate.
* This could happen when the transformation will take more time than expected.
* This will not cause an error, just warning to the client.
* Mostly:
* Video: 30 frames per second
* Audio: 50 audio data per second for OPUS
* In case of increased frame dropping rate a warning will be emitted according to info [here](/docs/intro#errors-and-warnings-listener).
* ***This is an optional method.***
* @param trackExpectedRate - number holds the predicted track rate.
*/
setTrackExpectedRate(trackExpectedRate: number): void;

@@ -52,0 +52,0 @@ /**

@@ -1,4 +0,4 @@

import InsertableStreamHelper from './InsertableStreamHelper';
import { MediaProcessorConnectorInterface } from './MediaProcessorConnectorInterface';
import { MediaProcessorInterface } from './MediaProcessorInterface';
import InsertableStreamHelper from "./InsertableStreamHelper";
import { MediaProcessorConnectorInterface } from "./MediaProcessorConnectorInterface";
import { MediaProcessorInterface } from "./MediaProcessorInterface";
/**

@@ -5,0 +5,0 @@ * Helper class implementing the media Media Processor Connector Interface.

/// <reference types="dom-webcodecs" />
import Emittery from 'emittery';
import Emittery from "emittery";
/**

@@ -4,0 +4,0 @@ * EventMetaData. Some metadata of the event.

@@ -18,3 +18,3 @@ import { ReporterConfig, SendableReport } from "@vonage/js-onewebrtc-telemetry";

private reporter;
constructor(config: QosReporterConfig);
constructor(config: QosReporterConfig, reporterId?: string);
onFrameFromSource(): Promise<void>;

@@ -21,0 +21,0 @@ get fps(): number;

{
"name": "@vonage/media-processor",
"version": "2.0.3",
"version": "2.0.4",
"author": "Guy Mininberg <guy.mininberg@vonage.com>",

@@ -19,10 +19,14 @@ "contributors": [

"scripts": {
"build": "npm-run-all build:js build:static doc",
"build": "npm-run-all build:js build:static build:doc",
"build:js": "vite build && tsc --declaration --emitDeclarationOnly --outDir dist/types",
"build:dev": "vite build --mode development && tsc --declaration --emitDeclarationOnly --outDir dist/types",
"build:static": "node ./scripts/build-static.js && minify ./dist/media-processor.static.js > ./dist/media-processor.min.js ",
"doc": "typedoc --excludePrivate --excludeProtected --disableSources --out dist/docs lib/main.ts",
"build:doc": "typedoc --excludePrivate --excludeProtected --disableSources --out dist/docs lib/main.ts",
"dev": "vite",
"prettify": "prettier . --write",
"preview": "vite preview",
"test": "vitest --run"
"test": "vitest --threads=false --run",
"test:install": "",
"version:local": "node -pe 'require(\"./package.json\").version'",
"version:published": "npm show @vonage/media-processor version"
},

@@ -35,7 +39,6 @@ "dependencies": {

"@types/uuid": "^8.3.4",
"@vonage/js-onewebrtc-telemetry": "1.1.2",
"axios": "^0.25.0",
"@vonage/js-onewebrtc-telemetry": "1.1.4",
"emittery": "^0.10.1",
"typescript-optional": "3.0.0-alpha.3",
"uuid": "~8.3.2"
"uuid": "^9.0.0"
},

@@ -71,3 +74,3 @@ "files": [

"typescript": "^4.6.2",
"vite": "^3.1.8",
"vite": "^4.1.3",
"vitest": "^0.24.3"

@@ -74,0 +77,0 @@ },

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc