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