Socket
Socket
Sign inDemoInstall

@vonage/media-processor

Package Overview
Dependencies
Maintainers
39
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.2 to 2.0.3

80

dist/media-processor.es.js

@@ -22,5 +22,5 @@ var V = Object.defineProperty;

});
const h = /* @__PURE__ */ new WeakMap(), E = /* @__PURE__ */ new WeakMap(), y = /* @__PURE__ */ new WeakMap(), O = Symbol("anyProducer"), U = Promise.resolve(), k = Symbol("listenerAdded"), P = Symbol("listenerRemoved");
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 _(t) {
function g(t) {
if (typeof t != "string" && typeof t != "symbol")

@@ -33,3 +33,3 @@ throw new TypeError("eventName must be a string or a symbol");

}
function g(t, e) {
function _(t, e) {
const r = E.get(t);

@@ -97,3 +97,3 @@ return r.has(e) || r.set(e, /* @__PURE__ */ new Set()), r.get(e);

}
const I = (t) => t === k || t === P;
const I = (t) => t === k || t === A;
class m {

@@ -156,3 +156,3 @@ static mixin(e, r) {

for (const s of e)
_(s), g(this, s).add(r), this.logIfDebugEnabled("subscribe", s, void 0), I(s) || this.emit(k, { eventName: s, listener: r });
g(s), _(this, s).add(r), this.logIfDebugEnabled("subscribe", s, void 0), I(s) || this.emit(k, { eventName: s, listener: r });
return this.off.bind(this, e, r);

@@ -163,3 +163,3 @@ }

for (const s of e)
_(s), g(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(P, { eventName: s, listener: r });
g(s), _(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(A, { eventName: s, listener: r });
}

@@ -176,8 +176,8 @@ once(e) {

for (const r of e)
_(r);
g(r);
return $(this, e);
}
async emit(e, r) {
_(e), this.logIfDebugEnabled("emit", e, r), q(this, e, r);
const s = g(this, e), o = h.get(this), i = [...s], n = I(e) ? [] : [...o];
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];
await U, await Promise.all([

@@ -195,4 +195,4 @@ ...i.map(async (c) => {

async emitSerial(e, r) {
_(e), this.logIfDebugEnabled("emitSerial", e, r);
const s = g(this, e), o = h.get(this), i = [...s], n = [...o];
g(e), this.logIfDebugEnabled("emitSerial", e, r);
const s = _(this, e), o = h.get(this), i = [...s], n = [...o];
await U;

@@ -211,3 +211,3 @@ for (const c of i)

offAny(e) {
T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(P, { listener: e }), h.get(this).delete(e);
T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(A, { listener: e }), h.get(this).delete(e);
}

@@ -218,3 +218,3 @@ clearListeners(e) {

if (this.logIfDebugEnabled("clear", r, void 0), typeof r == "string" || typeof r == "symbol") {
g(this, r).clear();
_(this, r).clear();
const s = b(this, r);

@@ -240,6 +240,6 @@ for (const o of s)

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

@@ -274,3 +274,3 @@ r += o.size;

Object.defineProperty(m, "listenerRemoved", {
value: P,
value: A,
writable: !1,

@@ -311,8 +311,8 @@ enumerable: !0,

}
const ae = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), G = {
const ae = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), z = {
randomUUID: ae
};
function ce(t, e, r) {
if (G.randomUUID && !e && !t)
return G.randomUUID();
if (z.randomUUID && !e && !t)
return z.randomUUID();
t = t || {};

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

function W(t, e) {
return globalThis[t] || (globalThis[t] = e), globalThis[t];
globalThis.vonage || (globalThis.vonage = {}), globalThis.vonage.workerizer || (globalThis.vonage.workerizer = {});
let r = globalThis.vonage.workerizer;
return r[t] || (r[t] = e), r[t];
}

@@ -337,3 +339,3 @@ const p = W(

var d = /* @__PURE__ */ ((t) => (t.INIT = "INIT", t.FORWARD = "FORWARD", t.TERMINATE = "TERMINATE", t.GLOBALS_SYNC = "GLOBALS_SYNC", t))(d || {});
function z(t) {
function j(t) {
return [ImageBitmap, ReadableStream, WritableStream].some((e) => t instanceof e);

@@ -351,3 +353,3 @@ }

},
s.filter((n) => z(n))
s.filter((n) => j(n))
), new Promise((n) => {

@@ -365,6 +367,6 @@ o == null || o.set(i, n);

},
o.filter((i) => z(i))
o.filter((i) => j(i))
);
}
const j = W("workerized", {});
const G = W("workerized", {});
function B() {

@@ -378,4 +380,4 @@ return typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope;

const t = [];
for (const e in j) {
const { worker: r, resolvers: s } = j[e].workerContext;
for (const e in G) {
const { worker: r, resolvers: s } = G[e].workerContext;
r && t.push(

@@ -394,3 +396,3 @@ le(

}
function A(t, e) {
function P(t, e) {
if (Array.isArray(e))

@@ -402,3 +404,3 @@ e.splice(0, e.length);

for (const r in t)
Array.isArray(t[r]) ? (e[r] = [], A(t[r], e[r])) : typeof t[r] == "object" ? (e[r] = {}, A(t[r], e[r])) : e[r] = t[r];
Array.isArray(t[r]) ? (e[r] = [], P(t[r], e[r])) : typeof t[r] == "object" ? (e[r] = {}, P(t[r], e[r])) : e[r] = t[r];
}

@@ -424,3 +426,3 @@ async function he(t, e) {

throw `unknown worker class ${r}`;
A(s, p), w(t, typeof e.instance !== void 0);
P(s, p), w(t, typeof e.instance !== void 0);
}

@@ -434,8 +436,8 @@ async function me(t, e) {

}
function _e(t) {
function ge(t) {
if (!t.args)
throw "Missing globals while syncing";
A(t.args[0], p), w(t, {});
P(t.args[0], p), w(t, {});
}
function ge() {
function _e() {
const t = {};

@@ -455,3 +457,3 @@ onmessage = async (e) => {

case d.GLOBALS_SYNC:
_e(r);
ge(r);
break;

@@ -461,3 +463,3 @@ }

}
B() && ge();
B() && _e();
function ye(t, e) {

@@ -520,3 +522,3 @@ return p[t] || (p[t] = e), [

}
const R = "2.0.2";
const R = "2.0.3";
class Se {

@@ -551,4 +553,4 @@ constructor(e) {

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, Pe = 0.8;
class Ae extends L {
const ke = 500, Ae = 0.8;
class Pe extends L {
constructor(r, s) {

@@ -611,3 +613,3 @@ super();

}
if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Pe > this.reporterQos_.fps) {
if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Ae > this.reporterQos_.fps) {
const u = {

@@ -676,3 +678,3 @@ eventMetaData: {

for (let s = 0; s < r.length; s++) {
let o = new Ae(r[s], s);
let o = new Pe(r[s], s);
o.on("error", (i) => {

@@ -679,0 +681,0 @@ this.emit("error", i);

@@ -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"),P=Symbol("listenerRemoved");let x=!1;function _(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 g(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===P;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)_(r),g(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)_(r),g(this,r).delete(t),this.logIfDebugEnabled("unsubscribe",r,void 0),I(r)||this.emit(P,{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)_(t);return $(this,e)}async emit(e,t){_(e),this.logIfDebugEnabled("emit",e,t),q(this,e,t);const r=g(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){_(e),this.logIfDebugEnabled("emitSerial",e,t);const r=g(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(P,{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){g(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"&&_(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+g(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:P,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),G={randomUUID:ae};function ce(e,t,r){if(G.randomUUID&&!t&&!e)return G.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){return globalThis[e]||(globalThis[e]=t),globalThis[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 z(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=>z(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=>z(e))))}const j=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 j){const{worker:r,resolvers:s}=j[t].workerContext;r&&e.push(le(r,d.GLOBALS_SYNC,"",[p],s))}await Promise.all(e)}}function A(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]=[],A(e[r],t[r])):"object"==typeof e[r]?(t[r]={},A(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)),A(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 _e(e){if(!e.args)throw"Missing globals while syncing";A(e.args[0],p),w(e,{})}function ge(){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:_e(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()&&ge();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.2";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,Pe=.8;class Ae 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_*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: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 Ae(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};
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};

@@ -22,5 +22,5 @@ var V = Object.defineProperty;

});
const h = /* @__PURE__ */ new WeakMap(), E = /* @__PURE__ */ new WeakMap(), y = /* @__PURE__ */ new WeakMap(), O = Symbol("anyProducer"), U = Promise.resolve(), k = Symbol("listenerAdded"), P = Symbol("listenerRemoved");
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 _(t) {
function g(t) {
if (typeof t != "string" && typeof t != "symbol")

@@ -33,3 +33,3 @@ throw new TypeError("eventName must be a string or a symbol");

}
function g(t, e) {
function _(t, e) {
const r = E.get(t);

@@ -97,3 +97,3 @@ return r.has(e) || r.set(e, /* @__PURE__ */ new Set()), r.get(e);

}
const I = (t) => t === k || t === P;
const I = (t) => t === k || t === A;
class m {

@@ -156,3 +156,3 @@ static mixin(e, r) {

for (const s of e)
_(s), g(this, s).add(r), this.logIfDebugEnabled("subscribe", s, void 0), I(s) || this.emit(k, { eventName: s, listener: r });
g(s), _(this, s).add(r), this.logIfDebugEnabled("subscribe", s, void 0), I(s) || this.emit(k, { eventName: s, listener: r });
return this.off.bind(this, e, r);

@@ -163,3 +163,3 @@ }

for (const s of e)
_(s), g(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(P, { eventName: s, listener: r });
g(s), _(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(A, { eventName: s, listener: r });
}

@@ -176,8 +176,8 @@ once(e) {

for (const r of e)
_(r);
g(r);
return $(this, e);
}
async emit(e, r) {
_(e), this.logIfDebugEnabled("emit", e, r), q(this, e, r);
const s = g(this, e), o = h.get(this), i = [...s], n = I(e) ? [] : [...o];
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];
await U, await Promise.all([

@@ -195,4 +195,4 @@ ...i.map(async (c) => {

async emitSerial(e, r) {
_(e), this.logIfDebugEnabled("emitSerial", e, r);
const s = g(this, e), o = h.get(this), i = [...s], n = [...o];
g(e), this.logIfDebugEnabled("emitSerial", e, r);
const s = _(this, e), o = h.get(this), i = [...s], n = [...o];
await U;

@@ -211,3 +211,3 @@ for (const c of i)

offAny(e) {
T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(P, { listener: e }), h.get(this).delete(e);
T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(A, { listener: e }), h.get(this).delete(e);
}

@@ -218,3 +218,3 @@ clearListeners(e) {

if (this.logIfDebugEnabled("clear", r, void 0), typeof r == "string" || typeof r == "symbol") {
g(this, r).clear();
_(this, r).clear();
const s = b(this, r);

@@ -240,6 +240,6 @@ for (const o of s)

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

@@ -274,3 +274,3 @@ r += o.size;

Object.defineProperty(m, "listenerRemoved", {
value: P,
value: A,
writable: !1,

@@ -311,8 +311,8 @@ enumerable: !0,

}
const ae = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), G = {
const ae = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), z = {
randomUUID: ae
};
function ce(t, e, r) {
if (G.randomUUID && !e && !t)
return G.randomUUID();
if (z.randomUUID && !e && !t)
return z.randomUUID();
t = t || {};

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

function W(t, e) {
return globalThis[t] || (globalThis[t] = e), globalThis[t];
globalThis.vonage || (globalThis.vonage = {}), globalThis.vonage.workerizer || (globalThis.vonage.workerizer = {});
let r = globalThis.vonage.workerizer;
return r[t] || (r[t] = e), r[t];
}

@@ -337,3 +339,3 @@ const p = W(

var d = /* @__PURE__ */ ((t) => (t.INIT = "INIT", t.FORWARD = "FORWARD", t.TERMINATE = "TERMINATE", t.GLOBALS_SYNC = "GLOBALS_SYNC", t))(d || {});
function z(t) {
function j(t) {
return [ImageBitmap, ReadableStream, WritableStream].some((e) => t instanceof e);

@@ -351,3 +353,3 @@ }

},
s.filter((n) => z(n))
s.filter((n) => j(n))
), new Promise((n) => {

@@ -365,6 +367,6 @@ o == null || o.set(i, n);

},
o.filter((i) => z(i))
o.filter((i) => j(i))
);
}
const j = W("workerized", {});
const G = W("workerized", {});
function B() {

@@ -378,4 +380,4 @@ return typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope;

const t = [];
for (const e in j) {
const { worker: r, resolvers: s } = j[e].workerContext;
for (const e in G) {
const { worker: r, resolvers: s } = G[e].workerContext;
r && t.push(

@@ -394,3 +396,3 @@ le(

}
function A(t, e) {
function P(t, e) {
if (Array.isArray(e))

@@ -402,3 +404,3 @@ e.splice(0, e.length);

for (const r in t)
Array.isArray(t[r]) ? (e[r] = [], A(t[r], e[r])) : typeof t[r] == "object" ? (e[r] = {}, A(t[r], e[r])) : e[r] = t[r];
Array.isArray(t[r]) ? (e[r] = [], P(t[r], e[r])) : typeof t[r] == "object" ? (e[r] = {}, P(t[r], e[r])) : e[r] = t[r];
}

@@ -424,3 +426,3 @@ async function he(t, e) {

throw `unknown worker class ${r}`;
A(s, p), w(t, typeof e.instance !== void 0);
P(s, p), w(t, typeof e.instance !== void 0);
}

@@ -434,8 +436,8 @@ async function me(t, e) {

}
function _e(t) {
function ge(t) {
if (!t.args)
throw "Missing globals while syncing";
A(t.args[0], p), w(t, {});
P(t.args[0], p), w(t, {});
}
function ge() {
function _e() {
const t = {};

@@ -455,3 +457,3 @@ onmessage = async (e) => {

case d.GLOBALS_SYNC:
_e(r);
ge(r);
break;

@@ -461,3 +463,3 @@ }

}
B() && ge();
B() && _e();
function ye(t, e) {

@@ -520,3 +522,3 @@ return p[t] || (p[t] = e), [

}
const R = "2.0.2";
const R = "2.0.3";
class Se {

@@ -551,4 +553,4 @@ constructor(e) {

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, Pe = 0.8;
class Ae extends L {
const ke = 500, Ae = 0.8;
class Pe extends L {
constructor(r, s) {

@@ -611,3 +613,3 @@ super();

}
if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Pe > this.reporterQos_.fps) {
if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Ae > this.reporterQos_.fps) {
const u = {

@@ -676,3 +678,3 @@ eventMetaData: {

for (let s = 0; s < r.length; s++) {
let o = new Ae(r[s], s);
let o = new Pe(r[s], s);
o.on("error", (i) => {

@@ -679,0 +681,0 @@ this.emit("error", i);

@@ -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"),P=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 k(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 G;if(!Array.isArray(t))throw new TypeError("`methodNames` must be an array of strings");for(const e of t)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 F=t=>t===R||t===P;class _{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 _}),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){(_.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,r,s)}on(e,r){k(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){k(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(P,{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 k(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){k(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),this.emit(P,{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 G=Object.getOwnPropertyNames(_.prototype).filter(t=>t!=="constructor");Object.defineProperty(_,"listenerAdded",{value:R,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(_,"listenerRemoved",{value:P,writable:!1,enumerable:!0,configurable:!1});var L=_;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),z=(t=>(t.automation="automation",t.test="test",t.vbc="vbc",t.video="video",t.voice="voice",t))(z||{});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){return globalThis[t]||(globalThis[t]=e),globalThis[t]}const p=D("globals",{});var g=(t=>(t.INIT="INIT",t.FORWARD="FORWARD",t.TERMINATE="TERMINATE",t.GLOBALS_SYNC="GLOBALS_SYNC",t))(g||{});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:g.GLOBALS_SYNC},p);else{const t=[];for(const e in Y){const{worker:r,resolvers:s}=Y[e].workerContext;r&&t.push(he(r,g.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 _e(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 ge(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 g.INIT:_e(r,t);break;case g.FORWARD:pe(r,t);break;case g.TERMINATE:ge(r,t);break;case g.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.2";class Pe{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 ke=500,Ae=.8;class Me extends L{constructor(r,s){super();a(this,"reporter_",new U);a(this,"reporterQos_",new Pe({loggingIntervalFrameCount:ke,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=z,f.WarningType=J,f.getVonageMetadata=I,f.isSupported=h,f.setVonageMetadata=Re,Object.defineProperties(f,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
(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"}})});
{
"name": "@vonage/media-processor",
"version": "2.0.2",
"version": "2.0.3",
"author": "Guy Mininberg <guy.mininberg@vonage.com>",

@@ -26,3 +26,3 @@ "contributors": [

"preview": "vite preview",
"test": "vitest --run --threads false"
"test": "vitest --run"
},

@@ -35,3 +35,3 @@ "dependencies": {

"@types/uuid": "^8.3.4",
"@vonage/js-onewebrtc-telemetry": "1.1.1",
"@vonage/js-onewebrtc-telemetry": "1.1.2",
"axios": "^0.25.0",

@@ -65,2 +65,3 @@ "emittery": "^0.10.1",

"mocha": "^10.1.0",
"node-fetch": "^3.3.0",
"npm-run-all": "^4.1.5",

@@ -67,0 +68,0 @@ "puppeteer": "^19.0.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