@vonage/media-processor 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- var B = Object.defineProperty;
2
- var V = (t, e, r) => e in t ? B(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
- var a = (t, e, r) => (V(t, typeof e != "symbol" ? e + "" : e, r), r);
4
- function Ie() {
1
+ var V = Object.defineProperty;
2
+ var Y = (t, e, r) => e in t ? V(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
+ var a = (t, e, r) => (Y(t, typeof e != "symbol" ? e + "" : e, r), r);
4
+ function ve() {
5
5
  return new Promise((t, e) => {
6
6
  typeof MediaStreamTrackProcessor > "u" || typeof MediaStreamTrackGenerator > "u" ? e("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media.") : t();
7
7
  });
@@ -19,7 +19,7 @@ a(l, "updates", {
19
19
  readable_null: "Readable is null",
20
20
  writable_null: "Writable is null"
21
21
  });
22
- const h = /* @__PURE__ */ new WeakMap(), E = /* @__PURE__ */ new WeakMap(), y = /* @__PURE__ */ new WeakMap(), O = Symbol("anyProducer"), D = Promise.resolve(), k = Symbol("listenerAdded"), A = Symbol("listenerRemoved");
22
+ 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");
23
23
  let x = !1;
24
24
  function _(t) {
25
25
  if (typeof t != "string" && typeof t != "symbol")
@@ -37,7 +37,7 @@ function b(t, e) {
37
37
  const r = typeof e == "string" || typeof e == "symbol" ? e : O, s = y.get(t);
38
38
  return s.has(r) || s.set(r, /* @__PURE__ */ new Set()), s.get(r);
39
39
  }
40
- function Y(t, e, r) {
40
+ function q(t, e, r) {
41
41
  const s = y.get(t);
42
42
  if (s.has(e))
43
43
  for (const o of s.get(e))
@@ -48,7 +48,7 @@ function Y(t, e, r) {
48
48
  i.enqueue(o);
49
49
  }
50
50
  }
51
- function U(t, e) {
51
+ function $(t, e) {
52
52
  e = Array.isArray(e) ? e : [e];
53
53
  let r = !1, s = () => {
54
54
  }, o = [];
@@ -84,15 +84,15 @@ function U(t, e) {
84
84
  }
85
85
  function H(t) {
86
86
  if (t === void 0)
87
- return $;
87
+ return Q;
88
88
  if (!Array.isArray(t))
89
89
  throw new TypeError("`methodNames` must be an array of strings");
90
90
  for (const e of t)
91
- if (!$.includes(e))
91
+ if (!Q.includes(e))
92
92
  throw typeof e != "string" ? new TypeError("`methodNames` element must be a string") : new Error(`${e} is not Emittery method`);
93
93
  return t;
94
94
  }
95
- const I = (t) => t === k || t === A;
95
+ const I = (t) => t === k || t === P;
96
96
  class m {
97
97
  static mixin(e, r) {
98
98
  return r = H(r), (s) => {
@@ -156,7 +156,7 @@ class m {
156
156
  off(e, r) {
157
157
  T(r), e = Array.isArray(e) ? e : [e];
158
158
  for (const s of e)
159
- _(s), g(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(A, { eventName: s, listener: r });
159
+ _(s), g(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(P, { eventName: s, listener: r });
160
160
  }
161
161
  once(e) {
162
162
  return new Promise((r) => {
@@ -169,12 +169,12 @@ class m {
169
169
  e = Array.isArray(e) ? e : [e];
170
170
  for (const r of e)
171
171
  _(r);
172
- return U(this, e);
172
+ return $(this, e);
173
173
  }
174
174
  async emit(e, r) {
175
- _(e), this.logIfDebugEnabled("emit", e, r), Y(this, e, r);
175
+ _(e), this.logIfDebugEnabled("emit", e, r), q(this, e, r);
176
176
  const s = g(this, e), o = h.get(this), i = [...s], n = I(e) ? [] : [...o];
177
- await D, await Promise.all([
177
+ await U, await Promise.all([
178
178
  ...i.map(async (c) => {
179
179
  if (s.has(c))
180
180
  return c(r);
@@ -188,7 +188,7 @@ class m {
188
188
  async emitSerial(e, r) {
189
189
  _(e), this.logIfDebugEnabled("emitSerial", e, r);
190
190
  const s = g(this, e), o = h.get(this), i = [...s], n = [...o];
191
- await D;
191
+ await U;
192
192
  for (const c of i)
193
193
  s.has(c) && await c(r);
194
194
  for (const c of n)
@@ -198,10 +198,10 @@ class m {
198
198
  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);
199
199
  }
200
200
  anyEvent() {
201
- return U(this);
201
+ return $(this);
202
202
  }
203
203
  offAny(e) {
204
- T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(A, { listener: e }), h.get(this).delete(e);
204
+ T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(P, { listener: e }), h.get(this).delete(e);
205
205
  }
206
206
  clearListeners(e) {
207
207
  e = Array.isArray(e) ? e : [e];
@@ -253,7 +253,7 @@ class m {
253
253
  }
254
254
  }
255
255
  }
256
- const $ = Object.getOwnPropertyNames(m.prototype).filter((t) => t !== "constructor");
256
+ const Q = Object.getOwnPropertyNames(m.prototype).filter((t) => t !== "constructor");
257
257
  Object.defineProperty(m, "listenerAdded", {
258
258
  value: k,
259
259
  writable: !1,
@@ -261,17 +261,17 @@ Object.defineProperty(m, "listenerAdded", {
261
261
  configurable: !1
262
262
  });
263
263
  Object.defineProperty(m, "listenerRemoved", {
264
- value: A,
264
+ value: P,
265
265
  writable: !1,
266
266
  enumerable: !0,
267
267
  configurable: !1
268
268
  });
269
269
  var L = m;
270
- function q(t) {
270
+ function J(t) {
271
271
  return typeof t == "object" && t !== null && "message" in t && typeof t.message == "string";
272
272
  }
273
- function J(t) {
274
- if (q(t))
273
+ function X(t) {
274
+ if (J(t))
275
275
  return t;
276
276
  try {
277
277
  return new Error(JSON.stringify(t));
@@ -280,47 +280,53 @@ function J(t) {
280
280
  }
281
281
  }
282
282
  function v(t) {
283
- return J(t).message;
283
+ return X(t).message;
284
284
  }
285
- var X = Object.defineProperty, Z = (t, e, r) => e in t ? X(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r, K = (t, e, r) => (Z(t, typeof e != "symbol" ? e + "" : e, r), r), N = /* @__PURE__ */ ((t) => (t.automation = "automation", t.test = "test", t.vbc = "vbc", t.video = "video", t.voice = "voice", t))(N || {});
286
- const ee = "hlg.tokbox.com/prod/logging/vcp_webrtc", re = "https://", te = 1e4;
285
+ var Z = Object.defineProperty, K = (t, e, r) => e in t ? Z(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r, N = (t, e, r) => (K(t, typeof e != "symbol" ? e + "" : e, r), r), ee = /* @__PURE__ */ ((t) => (t.automation = "automation", t.test = "test", t.vbc = "vbc", t.video = "video", t.voice = "voice", t))(ee || {});
286
+ const re = "hlg.tokbox.com/prod/logging/vcp_webrtc", te = "https://", se = 1e4;
287
287
  let S;
288
- const se = new Uint8Array(16);
289
- function oe() {
288
+ const oe = new Uint8Array(16);
289
+ function ie() {
290
290
  if (!S && (S = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !S))
291
291
  throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
292
- return S(se);
292
+ return S(oe);
293
293
  }
294
294
  const f = [];
295
295
  for (let t = 0; t < 256; ++t)
296
296
  f.push((t + 256).toString(16).slice(1));
297
- function ie(t, e = 0) {
297
+ function ne(t, e = 0) {
298
298
  return (f[t[e + 0]] + f[t[e + 1]] + f[t[e + 2]] + f[t[e + 3]] + "-" + f[t[e + 4]] + f[t[e + 5]] + "-" + f[t[e + 6]] + f[t[e + 7]] + "-" + f[t[e + 8]] + f[t[e + 9]] + "-" + f[t[e + 10]] + f[t[e + 11]] + f[t[e + 12]] + f[t[e + 13]] + f[t[e + 14]] + f[t[e + 15]]).toLowerCase();
299
299
  }
300
- const ne = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), Q = {
301
- randomUUID: ne
300
+ const ae = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), G = {
301
+ randomUUID: ae
302
302
  };
303
- function ae(t, e, r) {
304
- if (Q.randomUUID && !e && !t)
305
- return Q.randomUUID();
303
+ function ce(t, e, r) {
304
+ if (G.randomUUID && !e && !t)
305
+ return G.randomUUID();
306
306
  t = t || {};
307
- const s = t.random || (t.rng || oe)();
307
+ const s = t.random || (t.rng || ie)();
308
308
  if (s[6] = s[6] & 15 | 64, s[8] = s[8] & 63 | 128, e) {
309
309
  r = r || 0;
310
310
  for (let o = 0; o < 16; ++o)
311
311
  e[r + o] = s[o];
312
312
  return e;
313
313
  }
314
- return ie(s);
314
+ return ne(s);
315
315
  }
316
- const p = {};
316
+ function W(t, e) {
317
+ return globalThis[t] || (globalThis[t] = e), globalThis[t];
318
+ }
319
+ const p = W(
320
+ "globals",
321
+ {}
322
+ );
317
323
  var d = /* @__PURE__ */ ((t) => (t.INIT = "INIT", t.FORWARD = "FORWARD", t.TERMINATE = "TERMINATE", t.GLOBALS_SYNC = "GLOBALS_SYNC", t))(d || {});
318
- function j(t) {
324
+ function z(t) {
319
325
  return [ImageBitmap, ReadableStream, WritableStream].some((e) => t instanceof e);
320
326
  }
321
- let ce = 0;
322
- function fe(t, e, r, s, o) {
323
- const i = ce++;
327
+ let fe = 0;
328
+ function le(t, e, r, s, o) {
329
+ const i = fe++;
324
330
  return t.postMessage(
325
331
  {
326
332
  id: i,
@@ -328,7 +334,7 @@ function fe(t, e, r, s, o) {
328
334
  functionName: r,
329
335
  args: s
330
336
  },
331
- s.filter((n) => j(n))
337
+ s.filter((n) => z(n))
332
338
  ), new Promise((n) => {
333
339
  o == null || o.set(i, n);
334
340
  });
@@ -341,22 +347,22 @@ function w(t, e) {
341
347
  type: s,
342
348
  result: e
343
349
  },
344
- o.filter((i) => j(i))
350
+ o.filter((i) => z(i))
345
351
  );
346
352
  }
347
- const G = {};
348
- function z() {
353
+ const j = W("workerized", {});
354
+ function B() {
349
355
  return typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope;
350
356
  }
351
- async function le() {
352
- if (z())
357
+ async function ue() {
358
+ if (B())
353
359
  w({ type: d.GLOBALS_SYNC }, p);
354
360
  else {
355
361
  const t = [];
356
- for (const e in G) {
357
- const { worker: r, resolvers: s } = G[e].workerContext;
362
+ for (const e in j) {
363
+ const { worker: r, resolvers: s } = j[e].workerContext;
358
364
  r && t.push(
359
- fe(
365
+ le(
360
366
  r,
361
367
  d.GLOBALS_SYNC,
362
368
  "",
@@ -368,16 +374,16 @@ async function le() {
368
374
  await Promise.all(t);
369
375
  }
370
376
  }
371
- function P(t, e) {
377
+ function A(t, e) {
372
378
  if (Array.isArray(e))
373
379
  e.splice(0, e.length);
374
380
  else if (typeof e == "object")
375
381
  for (const r in e)
376
382
  delete e[r];
377
383
  for (const r in t)
378
- 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];
384
+ 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];
379
385
  }
380
- async function ue(t, e) {
386
+ async function he(t, e) {
381
387
  const { functionName: r, args: s } = t;
382
388
  if (!e.instance)
383
389
  throw "instance not initialized";
@@ -387,78 +393,78 @@ async function ue(t, e) {
387
393
  throw `undefined function [${r}] in class ${e.instance.constructor.workerId}`;
388
394
  w(t, await e.instance[r](...s != null ? s : []));
389
395
  }
390
- const he = {};
391
- function pe(t, e) {
396
+ const pe = W("registeredWorkers", {});
397
+ function de(t, e) {
392
398
  if (!t.args)
393
399
  throw "Missing className while initializing worker";
394
- const [r, s] = t.args, o = he[r];
400
+ const [r, s] = t.args, o = pe[r];
395
401
  if (o)
396
402
  e.instance = new o(t.args.slice(1));
397
403
  else
398
404
  throw `unknown worker class ${r}`;
399
- P(s, p), w(t, typeof e.instance !== void 0);
405
+ A(s, p), w(t, typeof e.instance !== void 0);
400
406
  }
401
- async function de(t, e) {
407
+ async function me(t, e) {
402
408
  const { args: r } = t;
403
409
  if (!e.instance)
404
410
  throw "instance not initialized";
405
411
  let s;
406
412
  e.instance.terminate && (s = await e.instance.terminate(...r != null ? r : [])), w(t, s);
407
413
  }
408
- function me(t) {
414
+ function _e(t) {
409
415
  if (!t.args)
410
416
  throw "Missing globals while syncing";
411
- P(t.args[0], p), w(t, {});
417
+ A(t.args[0], p), w(t, {});
412
418
  }
413
- function _e() {
419
+ function ge() {
414
420
  const t = {};
415
421
  onmessage = async (e) => {
416
422
  const r = e.data;
417
423
  switch (r.type) {
418
424
  case d.INIT:
419
- pe(r, t);
425
+ de(r, t);
420
426
  break;
421
427
  case d.FORWARD:
422
- ue(r, t);
428
+ he(r, t);
423
429
  break;
424
430
  case d.TERMINATE:
425
- de(r, t);
431
+ me(r, t);
426
432
  break;
427
433
  case d.GLOBALS_SYNC:
428
- me(r);
434
+ _e(r);
429
435
  break;
430
436
  }
431
437
  };
432
438
  }
433
- z() && _e();
434
- function ge(t, e) {
439
+ B() && ge();
440
+ function ye(t, e) {
435
441
  return p[t] || (p[t] = e), [
436
442
  () => p[t],
437
443
  async (r) => {
438
- p[t] = r, await le();
444
+ p[t] = r, await ue();
439
445
  }
440
446
  ];
441
447
  }
442
- function ye(t, e) {
443
- return ge(t, e);
448
+ function be(t, e) {
449
+ return ye(t, e);
444
450
  }
445
- const [be, we] = ye("metadata");
446
- function ve(t) {
447
- we(t);
451
+ const [we, Te] = be("metadata");
452
+ function Ce(t) {
453
+ Te(t);
448
454
  }
449
455
  function C() {
450
- return be();
456
+ return we();
451
457
  }
452
- class W {
458
+ class D {
453
459
  constructor(e) {
454
- K(this, "uuid", ae()), this.config = e;
460
+ N(this, "uuid", ce()), this.config = e;
455
461
  }
456
462
  async send(e) {
457
463
  var r, s, o;
458
464
  const { appId: i, sourceType: n } = (r = C()) != null ? r : {};
459
465
  if (!i || !n)
460
466
  return "metadata missing";
461
- const c = new AbortController(), u = setTimeout(() => c.abort(), te);
467
+ const c = new AbortController(), u = setTimeout(() => c.abort(), se);
462
468
  return await ((o = (s = this.config) == null ? void 0 : s.fetch) != null ? o : fetch)(this.getUrl(), {
463
469
  method: "POST",
464
470
  headers: this.getHeaders(),
@@ -468,8 +474,8 @@ class W {
468
474
  }
469
475
  getUrl() {
470
476
  var e;
471
- let r = (e = C().proxyUrl) != null ? e : re;
472
- return r += (r.at(-1) === "/" ? "" : "/") + ee, r;
477
+ let r = (e = C().proxyUrl) != null ? e : te;
478
+ return r += (r.at(-1) === "/" ? "" : "/") + re, r;
473
479
  }
474
480
  getHeaders() {
475
481
  return {
@@ -488,14 +494,14 @@ class W {
488
494
  };
489
495
  }
490
496
  }
491
- const R = "2.0.1";
492
- class Te {
497
+ const R = "2.0.2";
498
+ class Se {
493
499
  constructor(e) {
494
500
  a(this, "frameTransformedCount", 0);
495
501
  a(this, "frameFromSourceCount", 0);
496
502
  a(this, "startAt", 0);
497
503
  a(this, "reporter");
498
- this.config = e, this.reporter = new W(e);
504
+ this.config = e, this.reporter = new D(e);
499
505
  }
500
506
  async onFrameFromSource() {
501
507
  this.frameFromSourceCount++;
@@ -517,14 +523,14 @@ class Te {
517
523
  })) : "success";
518
524
  }
519
525
  }
520
- var Se = /* @__PURE__ */ ((t) => (t.FPS_DROP = "fps_drop", t))(Se || {}), Ee = /* @__PURE__ */ ((t) => (t.start = "start", t.transform = "transform", t.flush = "flush", t))(Ee || {}), 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 || {});
521
- const Re = 500, ke = 0.8;
526
+ 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 || {});
527
+ const ke = 500, Pe = 0.8;
522
528
  class Ae extends L {
523
529
  constructor(r, s) {
524
530
  super();
525
- a(this, "reporter_", new W());
526
- a(this, "reporterQos_", new Te({
527
- loggingIntervalFrameCount: Re,
531
+ a(this, "reporter_", new D());
532
+ a(this, "reporterQos_", new Se({
533
+ loggingIntervalFrameCount: ke,
528
534
  report: {
529
535
  version: R
530
536
  }
@@ -577,7 +583,7 @@ class Ae extends L {
577
583
  const M = { eventMetaData: { transformerIndex: this.index_ }, error: u, function: "transform" };
578
584
  this.emit("error", M);
579
585
  }
580
- if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * ke > this.reporterQos_.fps) {
586
+ if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Pe > this.reporterQos_.fps) {
581
587
  const u = {
582
588
  eventMetaData: {
583
589
  transformerIndex: this.index_
@@ -634,7 +640,7 @@ class Ae extends L {
634
640
  }, r);
635
641
  }
636
642
  }
637
- class Pe extends L {
643
+ class Me extends L {
638
644
  constructor(r) {
639
645
  super();
640
646
  a(this, "transformers_");
@@ -684,7 +690,7 @@ class Pe extends L {
684
690
  r.stop();
685
691
  }
686
692
  }
687
- class Ce extends L {
693
+ class Oe extends L {
688
694
  constructor() {
689
695
  super();
690
696
  a(this, "reporter_");
@@ -693,7 +699,7 @@ class Ce extends L {
693
699
  a(this, "readable_");
694
700
  a(this, "writable_");
695
701
  a(this, "trackExpectedRate_");
696
- this.reporter_ = new W(), this.trackExpectedRate_ = -1, this.report({
702
+ this.reporter_ = new D(), this.trackExpectedRate_ = -1, this.report({
697
703
  variation: "Create"
698
704
  });
699
705
  }
@@ -727,7 +733,7 @@ class Ce extends L {
727
733
  return;
728
734
  }
729
735
  let o = !1;
730
- this.pipeline_ && (o = !0, this.pipeline_.clearListeners(), this.pipeline_.destroy()), this.pipeline_ = new Pe(this.transformers_), this.pipeline_.on("warn", (i) => {
736
+ this.pipeline_ && (o = !0, this.pipeline_.clearListeners(), this.pipeline_.destroy()), this.pipeline_ = new Me(this.transformers_), this.pipeline_.on("warn", (i) => {
731
737
  this.emit("warn", i);
732
738
  }), this.pipeline_.on("error", (i) => {
733
739
  this.emit("error", i);
@@ -759,7 +765,7 @@ class Ce extends L {
759
765
  });
760
766
  }
761
767
  }
762
- class Me {
768
+ class xe {
763
769
  constructor() {
764
770
  a(this, "processor_");
765
771
  a(this, "generator_");
@@ -790,11 +796,11 @@ class Me {
790
796
  return this.generator_;
791
797
  }
792
798
  }
793
- class Oe {
799
+ class Fe {
794
800
  constructor(e) {
795
801
  a(this, "insertableStreamHelper_");
796
802
  a(this, "mediaProcessor_");
797
- this.insertableStreamHelper_ = new Me(), this.mediaProcessor_ = e;
803
+ this.insertableStreamHelper_ = new xe(), this.mediaProcessor_ = e;
798
804
  }
799
805
  setTrack(e) {
800
806
  return new Promise((r, s) => {
@@ -820,13 +826,13 @@ class Oe {
820
826
  }
821
827
  }
822
828
  export {
823
- Ee as ErrorFunction,
824
- Ce as MediaProcessor,
825
- Oe as MediaProcessorConnector,
829
+ Re as ErrorFunction,
830
+ Oe as MediaProcessor,
831
+ Fe as MediaProcessorConnector,
826
832
  F as PipelineInfoData,
827
- N as VonageSourceType,
828
- Se as WarningType,
833
+ ee as VonageSourceType,
834
+ Ee as WarningType,
829
835
  C as getVonageMetadata,
830
- Ie as isSupported,
831
- ve as setVonageMetadata
836
+ ve as isSupported,
837
+ Ce as setVonageMetadata
832
838
  };
@@ -1 +1 @@
1
- var B=Object.defineProperty,V=(e,t,r)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,a=(e,t,r)=>(V(e,"symbol"!=typeof t?t+"":t,r),r);function Ie(){return new Promise(((e,t)=>{typeof MediaStreamTrackProcessor>"u"||typeof MediaStreamTrackGenerator>"u"?t("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."):e()}))}class l{}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"),D=Promise.resolve(),k=Symbol("listenerAdded"),A=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 Y(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 U(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 $;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!$.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)_(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(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)_(t);return U(this,e)}async emit(e,t){_(e),this.logIfDebugEnabled("emit",e,t),Y(this,e,t);const r=g(this,e),s=h.get(this),o=[...r],i=I(e)?[]:[...s];await D,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 D;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 U(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){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 $=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 q(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}function J(e){if(q(e))return e;try{return new Error(JSON.stringify(e))}catch{return new Error(String(e))}}function v(e){return J(e).message}var X=Object.defineProperty,Z=(e,t,r)=>t in e?X(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,K=(e,t,r)=>(Z(e,"symbol"!=typeof t?t+"":t,r),r),N=(e=>(e.automation="automation",e.test="test",e.vbc="vbc",e.video="video",e.voice="voice",e))(N||{});const ee="hlg.tokbox.com/prod/logging/vcp_webrtc",re="https://",te=1e4;let S;const se=new Uint8Array(16);function oe(){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(se)}const f=[];for(let e=0;e<256;++e)f.push((e+256).toString(16).slice(1));function ie(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 ne=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Q={randomUUID:ne};function ae(e,t,r){if(Q.randomUUID&&!t&&!e)return Q.randomUUID();const s=(e=e||{}).random||(e.rng||oe)();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 ie(s)}const p={};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 ce=0;function fe(e,t,r,s,o){const i=ce++;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={};function z(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function le(){if(z())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(fe(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 ue(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 he={};function pe(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,s]=e.args,o=he[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 de(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 me(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:pe(r,e);break;case d.FORWARD:ue(r,e);break;case d.TERMINATE:de(r,e);break;case d.GLOBALS_SYNC:me(r)}}}function ge(e,t){return p[e]||(p[e]=t),[()=>p[e],async t=>{p[e]=t,await le()}]}function ye(e,t){return ge(e,t)}z()&&_e();const[be,we]=ye("metadata");function ve(e){we(e)}function C(){return be()}class W{constructor(e){K(this,"uuid",ae()),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()),te);return await(null!=(s=null==(r=this.config)?void 0:r.fetch)?s:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:n.signal}),clearTimeout(a),"success"}getUrl(){var e;let t=null!=(e=C().proxyUrl)?e:re;return t+=("/"===t.at(-1)?"":"/")+ee,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.1";class Te{constructor(e){a(this,"frameTransformedCount",0),a(this,"frameFromSourceCount",0),a(this,"startAt",0),a(this,"reporter"),this.config=e,this.reporter=new W(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,c=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:c,transformedFps:a,framesTransformed:s,...e})):"success"}}var Se=(e=>(e.FPS_DROP="fps_drop",e))(Se||{}),Ee=(e=>(e.start="start",e.transform="transform",e.flush="flush",e))(Ee||{}),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 Re=500,ke=.8;class Ae extends L{constructor(e,t){super(),a(this,"reporter_",new W),a(this,"reporterQos_",new Te({loggingIntervalFrameCount:Re,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_*ke>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 Pe 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 Ce 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 W,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 Pe(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 Me{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 Oe{constructor(e){a(this,"insertableStreamHelper_"),a(this,"mediaProcessor_"),this.insertableStreamHelper_=new Me,this.mediaProcessor_=e}setTrack(e){return new Promise(((t,r)=>{this.insertableStreamHelper_.init(e).then((()=>{this.mediaProcessor_.transform(this.insertableStreamHelper_.getReadable(),this.insertableStreamHelper_.getWriteable()).then((()=>{t(this.insertableStreamHelper_.getProccesorTrack())})).catch((e=>{r(e)}))})).catch((e=>{r(e)}))}))}destroy(){return new Promise(((e,t)=>{this.mediaProcessor_?this.mediaProcessor_.destroy().then((()=>{e()})).catch((e=>{t(e)})):t("no processor")}))}}export{Ee as ErrorFunction,Ce as MediaProcessor,Oe as MediaProcessorConnector,F as PipelineInfoData,N as VonageSourceType,Se as WarningType,C as getVonageMetadata,Ie as isSupported,ve as setVonageMetadata};
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};
@@ -1,7 +1,7 @@
1
- var B = Object.defineProperty;
2
- var V = (t, e, r) => e in t ? B(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
- var a = (t, e, r) => (V(t, typeof e != "symbol" ? e + "" : e, r), r);
4
- function Ie() {
1
+ var V = Object.defineProperty;
2
+ var Y = (t, e, r) => e in t ? V(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
+ var a = (t, e, r) => (Y(t, typeof e != "symbol" ? e + "" : e, r), r);
4
+ function ve() {
5
5
  return new Promise((t, e) => {
6
6
  typeof MediaStreamTrackProcessor > "u" || typeof MediaStreamTrackGenerator > "u" ? e("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media.") : t();
7
7
  });
@@ -19,7 +19,7 @@ a(l, "updates", {
19
19
  readable_null: "Readable is null",
20
20
  writable_null: "Writable is null"
21
21
  });
22
- const h = /* @__PURE__ */ new WeakMap(), E = /* @__PURE__ */ new WeakMap(), y = /* @__PURE__ */ new WeakMap(), O = Symbol("anyProducer"), D = Promise.resolve(), k = Symbol("listenerAdded"), A = Symbol("listenerRemoved");
22
+ 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");
23
23
  let x = !1;
24
24
  function _(t) {
25
25
  if (typeof t != "string" && typeof t != "symbol")
@@ -37,7 +37,7 @@ function b(t, e) {
37
37
  const r = typeof e == "string" || typeof e == "symbol" ? e : O, s = y.get(t);
38
38
  return s.has(r) || s.set(r, /* @__PURE__ */ new Set()), s.get(r);
39
39
  }
40
- function Y(t, e, r) {
40
+ function q(t, e, r) {
41
41
  const s = y.get(t);
42
42
  if (s.has(e))
43
43
  for (const o of s.get(e))
@@ -48,7 +48,7 @@ function Y(t, e, r) {
48
48
  i.enqueue(o);
49
49
  }
50
50
  }
51
- function U(t, e) {
51
+ function $(t, e) {
52
52
  e = Array.isArray(e) ? e : [e];
53
53
  let r = !1, s = () => {
54
54
  }, o = [];
@@ -84,15 +84,15 @@ function U(t, e) {
84
84
  }
85
85
  function H(t) {
86
86
  if (t === void 0)
87
- return $;
87
+ return Q;
88
88
  if (!Array.isArray(t))
89
89
  throw new TypeError("`methodNames` must be an array of strings");
90
90
  for (const e of t)
91
- if (!$.includes(e))
91
+ if (!Q.includes(e))
92
92
  throw typeof e != "string" ? new TypeError("`methodNames` element must be a string") : new Error(`${e} is not Emittery method`);
93
93
  return t;
94
94
  }
95
- const I = (t) => t === k || t === A;
95
+ const I = (t) => t === k || t === P;
96
96
  class m {
97
97
  static mixin(e, r) {
98
98
  return r = H(r), (s) => {
@@ -156,7 +156,7 @@ class m {
156
156
  off(e, r) {
157
157
  T(r), e = Array.isArray(e) ? e : [e];
158
158
  for (const s of e)
159
- _(s), g(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(A, { eventName: s, listener: r });
159
+ _(s), g(this, s).delete(r), this.logIfDebugEnabled("unsubscribe", s, void 0), I(s) || this.emit(P, { eventName: s, listener: r });
160
160
  }
161
161
  once(e) {
162
162
  return new Promise((r) => {
@@ -169,12 +169,12 @@ class m {
169
169
  e = Array.isArray(e) ? e : [e];
170
170
  for (const r of e)
171
171
  _(r);
172
- return U(this, e);
172
+ return $(this, e);
173
173
  }
174
174
  async emit(e, r) {
175
- _(e), this.logIfDebugEnabled("emit", e, r), Y(this, e, r);
175
+ _(e), this.logIfDebugEnabled("emit", e, r), q(this, e, r);
176
176
  const s = g(this, e), o = h.get(this), i = [...s], n = I(e) ? [] : [...o];
177
- await D, await Promise.all([
177
+ await U, await Promise.all([
178
178
  ...i.map(async (c) => {
179
179
  if (s.has(c))
180
180
  return c(r);
@@ -188,7 +188,7 @@ class m {
188
188
  async emitSerial(e, r) {
189
189
  _(e), this.logIfDebugEnabled("emitSerial", e, r);
190
190
  const s = g(this, e), o = h.get(this), i = [...s], n = [...o];
191
- await D;
191
+ await U;
192
192
  for (const c of i)
193
193
  s.has(c) && await c(r);
194
194
  for (const c of n)
@@ -198,10 +198,10 @@ class m {
198
198
  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);
199
199
  }
200
200
  anyEvent() {
201
- return U(this);
201
+ return $(this);
202
202
  }
203
203
  offAny(e) {
204
- T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(A, { listener: e }), h.get(this).delete(e);
204
+ T(e), this.logIfDebugEnabled("unsubscribeAny", void 0, void 0), this.emit(P, { listener: e }), h.get(this).delete(e);
205
205
  }
206
206
  clearListeners(e) {
207
207
  e = Array.isArray(e) ? e : [e];
@@ -253,7 +253,7 @@ class m {
253
253
  }
254
254
  }
255
255
  }
256
- const $ = Object.getOwnPropertyNames(m.prototype).filter((t) => t !== "constructor");
256
+ const Q = Object.getOwnPropertyNames(m.prototype).filter((t) => t !== "constructor");
257
257
  Object.defineProperty(m, "listenerAdded", {
258
258
  value: k,
259
259
  writable: !1,
@@ -261,17 +261,17 @@ Object.defineProperty(m, "listenerAdded", {
261
261
  configurable: !1
262
262
  });
263
263
  Object.defineProperty(m, "listenerRemoved", {
264
- value: A,
264
+ value: P,
265
265
  writable: !1,
266
266
  enumerable: !0,
267
267
  configurable: !1
268
268
  });
269
269
  var L = m;
270
- function q(t) {
270
+ function J(t) {
271
271
  return typeof t == "object" && t !== null && "message" in t && typeof t.message == "string";
272
272
  }
273
- function J(t) {
274
- if (q(t))
273
+ function X(t) {
274
+ if (J(t))
275
275
  return t;
276
276
  try {
277
277
  return new Error(JSON.stringify(t));
@@ -280,47 +280,53 @@ function J(t) {
280
280
  }
281
281
  }
282
282
  function v(t) {
283
- return J(t).message;
283
+ return X(t).message;
284
284
  }
285
- var X = Object.defineProperty, Z = (t, e, r) => e in t ? X(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r, K = (t, e, r) => (Z(t, typeof e != "symbol" ? e + "" : e, r), r), N = /* @__PURE__ */ ((t) => (t.automation = "automation", t.test = "test", t.vbc = "vbc", t.video = "video", t.voice = "voice", t))(N || {});
286
- const ee = "hlg.tokbox.com/prod/logging/vcp_webrtc", re = "https://", te = 1e4;
285
+ var Z = Object.defineProperty, K = (t, e, r) => e in t ? Z(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r, N = (t, e, r) => (K(t, typeof e != "symbol" ? e + "" : e, r), r), ee = /* @__PURE__ */ ((t) => (t.automation = "automation", t.test = "test", t.vbc = "vbc", t.video = "video", t.voice = "voice", t))(ee || {});
286
+ const re = "hlg.tokbox.com/prod/logging/vcp_webrtc", te = "https://", se = 1e4;
287
287
  let S;
288
- const se = new Uint8Array(16);
289
- function oe() {
288
+ const oe = new Uint8Array(16);
289
+ function ie() {
290
290
  if (!S && (S = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !S))
291
291
  throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
292
- return S(se);
292
+ return S(oe);
293
293
  }
294
294
  const f = [];
295
295
  for (let t = 0; t < 256; ++t)
296
296
  f.push((t + 256).toString(16).slice(1));
297
- function ie(t, e = 0) {
297
+ function ne(t, e = 0) {
298
298
  return (f[t[e + 0]] + f[t[e + 1]] + f[t[e + 2]] + f[t[e + 3]] + "-" + f[t[e + 4]] + f[t[e + 5]] + "-" + f[t[e + 6]] + f[t[e + 7]] + "-" + f[t[e + 8]] + f[t[e + 9]] + "-" + f[t[e + 10]] + f[t[e + 11]] + f[t[e + 12]] + f[t[e + 13]] + f[t[e + 14]] + f[t[e + 15]]).toLowerCase();
299
299
  }
300
- const ne = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), Q = {
301
- randomUUID: ne
300
+ const ae = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), G = {
301
+ randomUUID: ae
302
302
  };
303
- function ae(t, e, r) {
304
- if (Q.randomUUID && !e && !t)
305
- return Q.randomUUID();
303
+ function ce(t, e, r) {
304
+ if (G.randomUUID && !e && !t)
305
+ return G.randomUUID();
306
306
  t = t || {};
307
- const s = t.random || (t.rng || oe)();
307
+ const s = t.random || (t.rng || ie)();
308
308
  if (s[6] = s[6] & 15 | 64, s[8] = s[8] & 63 | 128, e) {
309
309
  r = r || 0;
310
310
  for (let o = 0; o < 16; ++o)
311
311
  e[r + o] = s[o];
312
312
  return e;
313
313
  }
314
- return ie(s);
314
+ return ne(s);
315
315
  }
316
- const p = {};
316
+ function W(t, e) {
317
+ return globalThis[t] || (globalThis[t] = e), globalThis[t];
318
+ }
319
+ const p = W(
320
+ "globals",
321
+ {}
322
+ );
317
323
  var d = /* @__PURE__ */ ((t) => (t.INIT = "INIT", t.FORWARD = "FORWARD", t.TERMINATE = "TERMINATE", t.GLOBALS_SYNC = "GLOBALS_SYNC", t))(d || {});
318
- function j(t) {
324
+ function z(t) {
319
325
  return [ImageBitmap, ReadableStream, WritableStream].some((e) => t instanceof e);
320
326
  }
321
- let ce = 0;
322
- function fe(t, e, r, s, o) {
323
- const i = ce++;
327
+ let fe = 0;
328
+ function le(t, e, r, s, o) {
329
+ const i = fe++;
324
330
  return t.postMessage(
325
331
  {
326
332
  id: i,
@@ -328,7 +334,7 @@ function fe(t, e, r, s, o) {
328
334
  functionName: r,
329
335
  args: s
330
336
  },
331
- s.filter((n) => j(n))
337
+ s.filter((n) => z(n))
332
338
  ), new Promise((n) => {
333
339
  o == null || o.set(i, n);
334
340
  });
@@ -341,22 +347,22 @@ function w(t, e) {
341
347
  type: s,
342
348
  result: e
343
349
  },
344
- o.filter((i) => j(i))
350
+ o.filter((i) => z(i))
345
351
  );
346
352
  }
347
- const G = {};
348
- function z() {
353
+ const j = W("workerized", {});
354
+ function B() {
349
355
  return typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope;
350
356
  }
351
- async function le() {
352
- if (z())
357
+ async function ue() {
358
+ if (B())
353
359
  w({ type: d.GLOBALS_SYNC }, p);
354
360
  else {
355
361
  const t = [];
356
- for (const e in G) {
357
- const { worker: r, resolvers: s } = G[e].workerContext;
362
+ for (const e in j) {
363
+ const { worker: r, resolvers: s } = j[e].workerContext;
358
364
  r && t.push(
359
- fe(
365
+ le(
360
366
  r,
361
367
  d.GLOBALS_SYNC,
362
368
  "",
@@ -368,16 +374,16 @@ async function le() {
368
374
  await Promise.all(t);
369
375
  }
370
376
  }
371
- function P(t, e) {
377
+ function A(t, e) {
372
378
  if (Array.isArray(e))
373
379
  e.splice(0, e.length);
374
380
  else if (typeof e == "object")
375
381
  for (const r in e)
376
382
  delete e[r];
377
383
  for (const r in t)
378
- 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];
384
+ 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];
379
385
  }
380
- async function ue(t, e) {
386
+ async function he(t, e) {
381
387
  const { functionName: r, args: s } = t;
382
388
  if (!e.instance)
383
389
  throw "instance not initialized";
@@ -387,78 +393,78 @@ async function ue(t, e) {
387
393
  throw `undefined function [${r}] in class ${e.instance.constructor.workerId}`;
388
394
  w(t, await e.instance[r](...s != null ? s : []));
389
395
  }
390
- const he = {};
391
- function pe(t, e) {
396
+ const pe = W("registeredWorkers", {});
397
+ function de(t, e) {
392
398
  if (!t.args)
393
399
  throw "Missing className while initializing worker";
394
- const [r, s] = t.args, o = he[r];
400
+ const [r, s] = t.args, o = pe[r];
395
401
  if (o)
396
402
  e.instance = new o(t.args.slice(1));
397
403
  else
398
404
  throw `unknown worker class ${r}`;
399
- P(s, p), w(t, typeof e.instance !== void 0);
405
+ A(s, p), w(t, typeof e.instance !== void 0);
400
406
  }
401
- async function de(t, e) {
407
+ async function me(t, e) {
402
408
  const { args: r } = t;
403
409
  if (!e.instance)
404
410
  throw "instance not initialized";
405
411
  let s;
406
412
  e.instance.terminate && (s = await e.instance.terminate(...r != null ? r : [])), w(t, s);
407
413
  }
408
- function me(t) {
414
+ function _e(t) {
409
415
  if (!t.args)
410
416
  throw "Missing globals while syncing";
411
- P(t.args[0], p), w(t, {});
417
+ A(t.args[0], p), w(t, {});
412
418
  }
413
- function _e() {
419
+ function ge() {
414
420
  const t = {};
415
421
  onmessage = async (e) => {
416
422
  const r = e.data;
417
423
  switch (r.type) {
418
424
  case d.INIT:
419
- pe(r, t);
425
+ de(r, t);
420
426
  break;
421
427
  case d.FORWARD:
422
- ue(r, t);
428
+ he(r, t);
423
429
  break;
424
430
  case d.TERMINATE:
425
- de(r, t);
431
+ me(r, t);
426
432
  break;
427
433
  case d.GLOBALS_SYNC:
428
- me(r);
434
+ _e(r);
429
435
  break;
430
436
  }
431
437
  };
432
438
  }
433
- z() && _e();
434
- function ge(t, e) {
439
+ B() && ge();
440
+ function ye(t, e) {
435
441
  return p[t] || (p[t] = e), [
436
442
  () => p[t],
437
443
  async (r) => {
438
- p[t] = r, await le();
444
+ p[t] = r, await ue();
439
445
  }
440
446
  ];
441
447
  }
442
- function ye(t, e) {
443
- return ge(t, e);
448
+ function be(t, e) {
449
+ return ye(t, e);
444
450
  }
445
- const [be, we] = ye("metadata");
446
- function ve(t) {
447
- we(t);
451
+ const [we, Te] = be("metadata");
452
+ function Ce(t) {
453
+ Te(t);
448
454
  }
449
455
  function C() {
450
- return be();
456
+ return we();
451
457
  }
452
- class W {
458
+ class D {
453
459
  constructor(e) {
454
- K(this, "uuid", ae()), this.config = e;
460
+ N(this, "uuid", ce()), this.config = e;
455
461
  }
456
462
  async send(e) {
457
463
  var r, s, o;
458
464
  const { appId: i, sourceType: n } = (r = C()) != null ? r : {};
459
465
  if (!i || !n)
460
466
  return "metadata missing";
461
- const c = new AbortController(), u = setTimeout(() => c.abort(), te);
467
+ const c = new AbortController(), u = setTimeout(() => c.abort(), se);
462
468
  return await ((o = (s = this.config) == null ? void 0 : s.fetch) != null ? o : fetch)(this.getUrl(), {
463
469
  method: "POST",
464
470
  headers: this.getHeaders(),
@@ -468,8 +474,8 @@ class W {
468
474
  }
469
475
  getUrl() {
470
476
  var e;
471
- let r = (e = C().proxyUrl) != null ? e : re;
472
- return r += (r.at(-1) === "/" ? "" : "/") + ee, r;
477
+ let r = (e = C().proxyUrl) != null ? e : te;
478
+ return r += (r.at(-1) === "/" ? "" : "/") + re, r;
473
479
  }
474
480
  getHeaders() {
475
481
  return {
@@ -488,14 +494,14 @@ class W {
488
494
  };
489
495
  }
490
496
  }
491
- const R = "2.0.1";
492
- class Te {
497
+ const R = "2.0.2";
498
+ class Se {
493
499
  constructor(e) {
494
500
  a(this, "frameTransformedCount", 0);
495
501
  a(this, "frameFromSourceCount", 0);
496
502
  a(this, "startAt", 0);
497
503
  a(this, "reporter");
498
- this.config = e, this.reporter = new W(e);
504
+ this.config = e, this.reporter = new D(e);
499
505
  }
500
506
  async onFrameFromSource() {
501
507
  this.frameFromSourceCount++;
@@ -517,14 +523,14 @@ class Te {
517
523
  })) : "success";
518
524
  }
519
525
  }
520
- var Se = /* @__PURE__ */ ((t) => (t.FPS_DROP = "fps_drop", t))(Se || {}), Ee = /* @__PURE__ */ ((t) => (t.start = "start", t.transform = "transform", t.flush = "flush", t))(Ee || {}), 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 || {});
521
- const Re = 500, ke = 0.8;
526
+ 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 || {});
527
+ const ke = 500, Pe = 0.8;
522
528
  class Ae extends L {
523
529
  constructor(r, s) {
524
530
  super();
525
- a(this, "reporter_", new W());
526
- a(this, "reporterQos_", new Te({
527
- loggingIntervalFrameCount: Re,
531
+ a(this, "reporter_", new D());
532
+ a(this, "reporterQos_", new Se({
533
+ loggingIntervalFrameCount: ke,
528
534
  report: {
529
535
  version: R
530
536
  }
@@ -577,7 +583,7 @@ class Ae extends L {
577
583
  const M = { eventMetaData: { transformerIndex: this.index_ }, error: u, function: "transform" };
578
584
  this.emit("error", M);
579
585
  }
580
- if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * ke > this.reporterQos_.fps) {
586
+ if (this.trackExpectedRate_ != -1 && this.trackExpectedRate_ * Pe > this.reporterQos_.fps) {
581
587
  const u = {
582
588
  eventMetaData: {
583
589
  transformerIndex: this.index_
@@ -634,7 +640,7 @@ class Ae extends L {
634
640
  }, r);
635
641
  }
636
642
  }
637
- class Pe extends L {
643
+ class Me extends L {
638
644
  constructor(r) {
639
645
  super();
640
646
  a(this, "transformers_");
@@ -684,7 +690,7 @@ class Pe extends L {
684
690
  r.stop();
685
691
  }
686
692
  }
687
- class Ce extends L {
693
+ class Oe extends L {
688
694
  constructor() {
689
695
  super();
690
696
  a(this, "reporter_");
@@ -693,7 +699,7 @@ class Ce extends L {
693
699
  a(this, "readable_");
694
700
  a(this, "writable_");
695
701
  a(this, "trackExpectedRate_");
696
- this.reporter_ = new W(), this.trackExpectedRate_ = -1, this.report({
702
+ this.reporter_ = new D(), this.trackExpectedRate_ = -1, this.report({
697
703
  variation: "Create"
698
704
  });
699
705
  }
@@ -727,7 +733,7 @@ class Ce extends L {
727
733
  return;
728
734
  }
729
735
  let o = !1;
730
- this.pipeline_ && (o = !0, this.pipeline_.clearListeners(), this.pipeline_.destroy()), this.pipeline_ = new Pe(this.transformers_), this.pipeline_.on("warn", (i) => {
736
+ this.pipeline_ && (o = !0, this.pipeline_.clearListeners(), this.pipeline_.destroy()), this.pipeline_ = new Me(this.transformers_), this.pipeline_.on("warn", (i) => {
731
737
  this.emit("warn", i);
732
738
  }), this.pipeline_.on("error", (i) => {
733
739
  this.emit("error", i);
@@ -759,7 +765,7 @@ class Ce extends L {
759
765
  });
760
766
  }
761
767
  }
762
- class Me {
768
+ class xe {
763
769
  constructor() {
764
770
  a(this, "processor_");
765
771
  a(this, "generator_");
@@ -790,11 +796,11 @@ class Me {
790
796
  return this.generator_;
791
797
  }
792
798
  }
793
- class Oe {
799
+ class Fe {
794
800
  constructor(e) {
795
801
  a(this, "insertableStreamHelper_");
796
802
  a(this, "mediaProcessor_");
797
- this.insertableStreamHelper_ = new Me(), this.mediaProcessor_ = e;
803
+ this.insertableStreamHelper_ = new xe(), this.mediaProcessor_ = e;
798
804
  }
799
805
  setTrack(e) {
800
806
  return new Promise((r, s) => {
@@ -820,13 +826,13 @@ class Oe {
820
826
  }
821
827
  }
822
828
  export {
823
- Ee as ErrorFunction,
824
- Ce as MediaProcessor,
825
- Oe as MediaProcessorConnector,
829
+ Re as ErrorFunction,
830
+ Oe as MediaProcessor,
831
+ Fe as MediaProcessorConnector,
826
832
  F as PipelineInfoData,
827
- N as VonageSourceType,
828
- Se as WarningType,
833
+ ee as VonageSourceType,
834
+ Ee as WarningType,
829
835
  C as getVonageMetadata,
830
- Ie as isSupported,
831
- ve as setVonageMetadata
836
+ ve as isSupported,
837
+ Ce as setVonageMetadata
832
838
  };
@@ -1,2 +1,2 @@
1
- (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 Ce=Object.defineProperty;var Oe=(f,h,u)=>h in f?Ce(f,h,{enumerable:!0,configurable:!0,writable:!0,value:u}):f[h]=u;var a=(f,h,u)=>(Oe(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 X(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 $(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 Q(t){if(t===void 0)return j;if(!Array.isArray(t))throw new TypeError("`methodNames` must be an array of strings");for(const e of t)if(!j.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=Q(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}
2
- 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 $(this,e)}async emit(e,r){y(e),this.logIfDebugEnabled("emit",e,r),X(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 $(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=Q(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 j=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 Z(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}function K(t){if(Z(t))return t;try{return new Error(JSON.stringify(t))}catch{return new Error(String(t))}}function W(t){return K(t).message}var N=Object.defineProperty,ee=(t,e,r)=>e in t?N(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,re=(t,e,r)=>(ee(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 te="hlg.tokbox.com/prod/logging/vcp_webrtc",se="https://",oe=1e4;let A;const ie=new Uint8Array(16);function ne(){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(ie)}const l=[];for(let t=0;t<256;++t)l.push((t+256).toString(16).slice(1));function ae(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 ce=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),z={randomUUID:ce};function fe(t,e,r){if(z.randomUUID&&!e&&!t)return z.randomUUID();t=t||{};const s=t.random||(t.rng||ne)();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 ae(s)}const p={};var g=(t=>(t.INIT="INIT",t.FORWARD="FORWARD",t.TERMINATE="TERMINATE",t.GLOBALS_SYNC="GLOBALS_SYNC",t))(g||{});function B(t){return[ImageBitmap,ReadableStream,WritableStream].some(e=>t instanceof e)}let le=0;function ue(t,e,r,s,o){const i=le++;return t.postMessage({id:i,type:e,functionName:r,args:s},s.filter(n=>B(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=>B(i)))}const V={};function Y(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function he(){if(Y())S({type:g.GLOBALS_SYNC},p);else{const t=[];for(const e in V){const{worker:r,resolvers:s}=V[e].workerContext;r&&t.push(ue(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 de(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 pe={};function me(t,e){if(!t.args)throw"Missing className while initializing worker";const[r,s]=t.args,o=pe[r];if(o)e.instance=new o(t.args.slice(1));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 ge(t){if(!t.args)throw"Missing globals while syncing";M(t.args[0],p),S(t,{})}function ye(){const t={};onmessage=async e=>{const r=e.data;switch(r.type){case g.INIT:me(r,t);break;case g.FORWARD:de(r,t);break;case g.TERMINATE:_e(r,t);break;case g.GLOBALS_SYNC:ge(r);break}}}Y()&&ye();function be(t,e){return p[t]||(p[t]=e),[()=>p[t],async r=>{p[t]=r,await he()}]}function we(t,e){return be(t,e)}const[Te,Se]=we("metadata");function Ee(t){Se(t)}function I(){return Te()}class D{constructor(e){re(this,"uuid",fe()),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(),oe);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:se;return r+=(r.at(-1)==="/"?"":"/")+te,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.1";class Re{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: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,U=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:U,transformedFps:m,framesTransformed:o,...e})):"success"}}var q=(t=>(t.FPS_DROP="fps_drop",t))(q||{}),J=(t=>(t.start="start",t.transform="transform",t.flush="flush",t))(J||{}),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,ke=.8;class Ae extends L{constructor(r,s){super();a(this,"reporter_",new D);a(this,"reporterQos_",new Re({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 U={eventMetaData:{transformerIndex:this.index_},error:m,function:"transform"};this.emit("error",U)}if(this.trackExpectedRate_!=-1&&this.trackExpectedRate_*ke>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 Me extends L{constructor(r){super();a(this,"transformers_");a(this,"trackExpectedRate_");this.transformers_=[],this.trackExpectedRate_=-1;for(let s=0;s<r.length;s++){let o=new Ae(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 Ie 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(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 Me(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 xe{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 ve{constructor(e){a(this,"insertableStreamHelper_");a(this,"mediaProcessor_");this.insertableStreamHelper_=new xe,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=J,f.MediaProcessor=Ie,f.MediaProcessorConnector=ve,f.PipelineInfoData=v,f.VonageSourceType=G,f.WarningType=q,f.getVonageMetadata=I,f.isSupported=h,f.setVonageMetadata=Ee,Object.defineProperties(f,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
1
+ (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}
2
+ 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"}})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vonage/media-processor",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "author": "Guy Mininberg <guy.mininberg@vonage.com>",
5
5
  "contributors": [
6
6
  "Guy Mininberg <guy.mininberg@vonage.com>",
@@ -31,7 +31,7 @@
31
31
  "@types/node": "^17.0.10",
32
32
  "@types/offscreencanvas": "^2019.6.4",
33
33
  "@types/uuid": "^8.3.4",
34
- "@vonage/js-onewebrtc-telemetry": "1.1.0",
34
+ "@vonage/js-onewebrtc-telemetry": "1.1.1",
35
35
  "axios": "^0.25.0",
36
36
  "emittery": "^0.10.1",
37
37
  "typescript-optional": "3.0.0-alpha.3",
@@ -40,7 +40,7 @@
40
40
  "files": [
41
41
  "dist"
42
42
  ],
43
- "types": "./dist/types/main.d.ts",
43
+ "types": "./dist/types/lib/main.d.ts",
44
44
  "main": "./dist/media-processor.umd.js",
45
45
  "module": "./dist/media-processor.es.js",
46
46
  "exports": {