@vonage/ml-transformers 7.0.0-alpha.2 → 7.0.0

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,17 +1,17 @@
1
- (function(R,de){typeof exports=="object"&&typeof module<"u"?de(exports):typeof define=="function"&&define.amd?define(["exports"],de):(R=typeof globalThis<"u"?globalThis:R||self,de(R["ml-transformers"]={}))})(this,(function(R){"use strict";var de;self.MediaStreamTrackProcessor||(self.MediaStreamTrackProcessor=(de=class{constructor(r){const e=r.track??r;e.kind=="video"?this.readable=new ReadableStream({async start(t){e.addEventListener("ended",()=>t.close(),{once:!0}),this.video=document.createElement("video"),this.video.srcObject=new MediaStream([e]),await Promise.all([this.video.play(),new Promise(n=>this.video.onloadedmetadata=n)]),this.track=e,this.canvas=new OffscreenCanvas(this.video.videoWidth,this.video.videoHeight),this.ctx=this.canvas.getContext("2d",{desynchronized:!0}),this.t1=performance.now()},async pull(t){if(e.readyState=="ended")return t.close();const n=e.getSettings().frameRate||30;for(;performance.now()-this.t1<1e3/n;)if(await new Promise(i=>requestAnimationFrame(i)),e.readyState=="ended")return t.close();this.canvas.width=this.video.videoWidth,this.canvas.height=this.video.videoHeight,this.t1=performance.now(),this.ctx.drawImage(this.video,0,0),t.enqueue(new VideoFrame(this.canvas,{timestamp:this.t1}))}}):e.kind=="audio"&&(this.readable=new ReadableStream({async start(t){e.addEventListener("ended",()=>t.close(),{once:!0}),this.ac=new AudioContext,this.arrays=[];function n(){registerProcessor("mstp-shim",class extends AudioWorkletProcessor{process(i){return this.port.postMessage(i),!0}})}await this.ac.audioWorklet.addModule(`data:text/javascript,(${n.toString()})()`),this.node=new AudioWorkletNode(this.ac,"mstp-shim"),this.ac.createMediaStreamSource(new MediaStream([e])).connect(this.node),this.node.port.addEventListener("message",({data:i})=>i[0][0]&&this.arrays.push(i))},async pull(t){if(e.readyState=="ended")return t.close();for(;!this.arrays.length;)if(await new Promise(o=>this.node.port.onmessage=o),e.readyState=="ended")return t.close();const[n]=this.arrays.shift(),i=new Float32Array(n.reduce((o,s)=>o+s.length,0));n.reduce((o,s)=>(i.set(s,o),o+s.length),0),t.enqueue(new AudioData({format:"f32-planar",sampleRate:this.ac.sampleRate,numberOfFrames:n[0].length,numberOfChannels:n.length,timestamp:this.ac.currentTime*1e6|0,data:i,transfer:[i.buffer]}))}}))}},de.__POLYFILLED=!0,de));var pr;self.MediaStreamTrackGenerator||(self.MediaStreamTrackGenerator=(pr=class{constructor({kind:r}){if(r=="video"){const e=document.createElement("canvas"),t=e.getContext("2d",{desynchronized:!0}),n=e.captureStream().getVideoTracks()[0];return n.writable=new WritableStream({write(i){e.width=i.displayWidth,e.height=i.displayHeight,t.drawImage(i,0,0,e.width,e.height),i.close()}}),n}else if(r=="audio"){const e=new AudioContext,t=e.createMediaStreamDestination(),[n]=t.stream.getAudioTracks();return n.writable=new WritableStream({async start(i){this.arrays=[];function o(){registerProcessor("mstg-shim",class extends AudioWorkletProcessor{constructor(){super(),this.arrays=[],this.arrayOffset=0,this.port.onmessage=({data:s})=>this.arrays.push(s),this.emptyArray=new Float32Array(0)}process(s,[[a]]){for(let c=0;c<a.length;c++)(!this.array||this.arrayOffset>=this.array.length)&&(this.array=this.arrays.shift()||this.emptyArray,this.arrayOffset=0),a[c]=this.array[this.arrayOffset++]||0;return!0}})}return await e.audioWorklet.addModule(`data:text/javascript,(${o.toString()})()`),this.node=new AudioWorkletNode(e,"mstg-shim"),this.node.connect(t),n},write(i){const o=new Float32Array(i.numberOfFrames*i.numberOfChannels);i.copyTo(o,{planeIndex:0}),this.node.port.postMessage(o,[o.buffer]),i.close()}}),n}}},pr.__POLYFILLED=!0,pr));async function Fo(){return new Promise(async(r,e)=>{await vn()||xn()?r():e("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media.")})}function xn(){return self.MediaStreamTrackProcessor!==void 0&&self.MediaStreamTrackGenerator!==void 0&&(!(self.MediaStreamTrackProcessor.hasOwnProperty("__POLYFILLED")||self.MediaStreamTrackGenerator.hasOwnProperty("__POLYFILLED"))||Oo())}function Oo(){return[self.ReadableStream,self.WritableStream,self.MediaStream,self.OffscreenCanvas,self.VideoFrame,self.AudioContext,self.AudioWorkletNode].filter(r=>r===void 0).length===0}function vn(){return new Promise(r=>{function e(){self.postMessage(typeof MediaStreamTrackProcessor<"u"&&typeof VideoTrackGenerator<"u")}const t=new Worker(`data:text/javascript,(${e.toString()})()`);t.onmessage=({data:n})=>r(n)})}const ee=new WeakMap,he=new WeakMap,Q=new WeakMap,lt=Symbol("anyProducer"),_n=Promise.resolve(),ft=Symbol("listenerAdded"),dt=Symbol("listenerRemoved");let ht=!1,gr=!1;const mt=r=>typeof r=="string"||typeof r=="symbol"||typeof r=="number";function Se(r){if(!mt(r))throw new TypeError("`eventName` must be a string, symbol, or number")}function pt(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Ie(r,e){const t=he.get(r);if(t.has(e))return t.get(e)}function Ge(r,e){const t=mt(e)?e:lt,n=Q.get(r);if(n.has(t))return n.get(t)}function Co(r,e,t){const n=Q.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(lt)){const i=Promise.all([e,t]);for(const o of n.get(lt))o.enqueue(i)}}function En(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const o={enqueue(s){i.push(s),n()},finish(){t=!0,n()}};for(const s of e){let a=Ge(r,s);a||(a=new Set,Q.get(r).set(s,a)),a.add(o)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(s=>{n=s}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(s){i=void 0;for(const a of e){const c=Ge(r,a);c&&(c.delete(o),c.size===0&&Q.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await s}:{done:!0}},[Symbol.asyncIterator](){return this}}}function An(r){if(r===void 0)return Tn;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!Tn.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const ke=r=>r===ft||r===dt;function gt(r,e,t){if(ke(e))try{ht=!0,r.emit(e,t)}finally{ht=!1}}class q{static mixin(e,t){return t=An(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const s of t)if(n.prototype[s]!==void 0)throw new Error(`The property \`${s}\` already exists on \`target\``);function i(){return Object.defineProperty(this,e,{enumerable:!1,value:new q}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const o=s=>function(...a){return this[e][s](...a)};for(const s of t)Object.defineProperty(n.prototype,s,{enumerable:!1,value:o(s)});return n}}static get isDebugEnabled(){if(typeof globalThis.process?.env!="object")return gr;const{env:e}=globalThis.process??{env:{}};return e.DEBUG==="emittery"||e.DEBUG==="*"||gr}static set isDebugEnabled(e){gr=e}constructor(e={}){ee.set(this,new Set),he.set(this,new Map),Q.set(this,new Map),Q.get(this).set(lt,new Set),this.debug=e.debug??{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(t,n,i,o)=>{try{o=JSON.stringify(o)}catch{o=`Object with the following keys failed to stringify: ${Object.keys(o).join(",")}`}(typeof i=="symbol"||typeof i=="number")&&(i=i.toString());const s=new Date,a=`${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}.${s.getMilliseconds()}`;console.log(`[${a}][emittery:${t}][${n}] Event Name: ${i}
2
- data: ${o}`)})}logIfDebugEnabled(e,t,n){(q.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t,{signal:n}={}){pt(t),e=Array.isArray(e)?e:[e];for(const o of e){Se(o);let s=Ie(this,o);s||(s=new Set,he.get(this).set(o,s)),s.add(t),this.logIfDebugEnabled("subscribe",o,void 0),ke(o)||gt(this,ft,{eventName:o,listener:t})}const i=()=>{this.off(e,t),n?.removeEventListener("abort",i)};return n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i(),i}off(e,t){pt(t),e=Array.isArray(e)?e:[e];for(const n of e){Se(n);const i=Ie(this,n);i&&(i.delete(t),i.size===0&&he.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),ke(n)||gt(this,dt,{eventName:n,listener:t})}}once(e,t){if(t!==void 0&&typeof t!="function")throw new TypeError("predicate must be a function");let n;const i=new Promise(o=>{n=this.on(e,s=>{t&&!t(s)||(n(),o(s))})});return i.off=n,i}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Se(t);return En(this,e)}async emit(e,t){if(Se(e),ke(e)&&!ht)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),Co(this,e,t);const n=Ie(this,e)??new Set,i=ee.get(this),o=[...n],s=ke(e)?[]:[...i];await _n,await Promise.all([...o.map(async a=>{if(n.has(a))return a(t)}),...s.map(async a=>{if(i.has(a))return a(e,t)})])}async emitSerial(e,t){if(Se(e),ke(e)&&!ht)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const n=Ie(this,e)??new Set,i=ee.get(this),o=[...n],s=[...i];await _n;for(const a of o)n.has(a)&&await a(t);for(const a of s)i.has(a)&&await a(e,t)}onAny(e,{signal:t}={}){pt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),ee.get(this).add(e),gt(this,ft,{listener:e});const n=()=>{this.offAny(e),t?.removeEventListener("abort",n)};return t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n(),n}anyEvent(){return En(this)}offAny(e){pt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),gt(this,dt,{listener:e}),ee.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),mt(t)){const n=Ie(this,t);n&&n.clear();const i=Ge(this,t);if(i){for(const o of i)o.finish();i.clear()}}else{ee.get(this).clear();for(const[n,i]of he.get(this).entries())i.clear(),he.get(this).delete(n);for(const[n,i]of Q.get(this).entries()){for(const o of i)o.finish();i.clear(),Q.get(this).delete(n)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const n of e){if(mt(n)){t+=ee.get(this).size+(Ie(this,n)?.size??0)+(Ge(this,n)?.size??0)+(Ge(this)?.size??0);continue}n!==void 0&&Se(n),t+=ee.get(this).size;for(const i of he.get(this).values())t+=i.size;for(const i of Q.get(this).values())t+=i.size}return t}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=An(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const Tn=Object.getOwnPropertyNames(q.prototype).filter(r=>r!=="constructor");Object.defineProperty(q,"listenerAdded",{value:ft,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(q,"listenerRemoved",{value:dt,writable:!1,enumerable:!0,configurable:!1});var Mo=Object.defineProperty,Bo=(r,e,t)=>e in r?Mo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Do=(r,e,t)=>(Bo(r,e+"",t),t);const Uo="hlg.tokbox.com/prod/logging/vcp_webrtc",Lo="https://",zo=1e4;let yt;const No=new Uint8Array(16);function $o(){if(!yt&&(yt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!yt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return yt(No)}const P=[];for(let r=0;r<256;++r)P.push((r+256).toString(16).slice(1));function Wo(r,e=0){return(P[r[e+0]]+P[r[e+1]]+P[r[e+2]]+P[r[e+3]]+"-"+P[r[e+4]]+P[r[e+5]]+"-"+P[r[e+6]]+P[r[e+7]]+"-"+P[r[e+8]]+P[r[e+9]]+"-"+P[r[e+10]]+P[r[e+11]]+P[r[e+12]]+P[r[e+13]]+P[r[e+14]]+P[r[e+15]]).toLowerCase()}const Go=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Sn={randomUUID:Go};function Vo(r,e,t){if(Sn.randomUUID&&!r)return Sn.randomUUID();r=r||{};const n=r.random||(r.rng||$o)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Wo(n)}function yr(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const te=yr("globals",{});var me=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r))(me||{});function In(r){return[ImageBitmap,ReadableStream,WritableStream].some(e=>r instanceof e)}let Ho=0;function jo(r,e,t,n,i){const o=Ho++;return r.postMessage({id:o,type:e,functionName:t,args:n},n.filter(s=>In(s))),new Promise(s=>{i?.set(o,s)})}function Ve(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(o=>In(o)))}const kn=yr("workerized",{});function Rn(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function Yo(){if(Rn())Ve({type:me.GLOBALS_SYNC},te);else{const r=[];for(const e in kn){const{worker:t,resolvers:n}=kn[e].workerContext;t&&r.push(jo(t,me.GLOBALS_SYNC,"",[te],n))}await Promise.all(r)}}function bt(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],bt(r[t],e[t])):typeof r[t]=="object"?(e[t]={},bt(r[t],e[t])):e[t]=r[t]}async function Qo(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Ve(r,await e.instance[t](...n??[]))}const qo=yr("registeredWorkers",{});function Xo(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=qo[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;bt(n,te),Ve(r,typeof e.instance!==void 0)}async function Ko(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Ve(r,n)}function Jo(r){if(!r.args)throw"Missing globals while syncing";bt(r.args[0],te),Ve(r,{})}function Zo(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case me.INIT:Xo(t,r);break;case me.FORWARD:Qo(t,r);break;case me.TERMINATE:Ko(t,r);break;case me.GLOBALS_SYNC:Jo(t);break}}}Rn()&&Zo();function es(r,e){return te[r]||(te[r]=e),[()=>te[r],async t=>{te[r]=t,await Yo()}]}function ts(r,e){return es(r,e)}const[rs,ns]=ts("metadata");function is(r){ns(r)}function wt(){return rs()}let br=class{constructor(e,t){Do(this,"uuid"),this.config=e,this.uuid=t??Vo()}async send(e){var t,n,i;const{appId:o,sourceType:s}=(t=wt())!=null?t:{};if(!o||!s)return"metadata missing";const a=new AbortController,c=setTimeout(()=>a.abort(),zo);return await((i=(n=this.config)==null?void 0:n.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(c),"success"}getUrl(){var e;let t=(e=wt().proxyUrl)!=null?e:Lo;return t+=(t.at(-1)==="/"?"":"/")+Uo,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=wt();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}};const xt="3.0.0",wr=class{};wr.updates={transformer_new:"New transformer",transformer_null:"Null transformer"},wr.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"};let pe=wr;function os(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function ss(r){if(os(r))return r;try{return new Error(JSON.stringify(r))}catch{return new Error(String(r))}}function xr(r){return ss(r).message}class as{constructor(e,t){this.config=e,this.frameTransformedCount=0,this.frameFromSourceCount=0,this.startAt=0,this.reporter=new br(e,t)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:t}=this,n=(Date.now()-e)/1e3;return t/n}async onFrameTransformed(e={},t=!1){this.startAt===0&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:n,frameTransformedCount:i,frameFromSourceCount:o}=this,s=Date.now(),a=(s-n)/1e3,c=i/a,u=o/a;return t||this.frameTransformedCount>=this.config.loggingIntervalFrameCount?(this.frameFromSourceCount=0,this.frameTransformedCount=0,this.startAt=s,this.reporter.config=this.config,this.reporter.send({...this.config.report,variation:"QoS",fps:u,transformedFps:c,framesTransformed:i,...e})):"success"}}var Pn=(r=>(r.FPS_DROP="fps_drop",r))(Pn||{}),Fn=(r=>(r.start="start",r.transform="transform",r.flush="flush",r))(Fn||{}),vt=(r=>(r.pipeline_ended="pipeline_ended",r.pipeline_ended_with_error="pipeline_ended_with_error",r.pipeline_started="pipeline_started",r.pipeline_started_with_error="pipeline_started_with_error",r.pipeline_restarted="pipeline_restarted",r.pipeline_restarted_with_error="pipeline_restarted_with_error",r))(vt||{});const cs=500,us=.8;class ls extends q{constructor(e,t){super(),this.reporter_=new br,this.reporterQos_=new as({loggingIntervalFrameCount:cs,report:{version:xt}}),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_&&typeof this.transformer_.start=="function")try{await this.transformer_.start(e)}catch(t){this.report({message:pe.errors.transformer_start,variation:"Error",error:xr(t)});const n={eventMetaData:{transformerIndex:this.index_},error:t,function:"start"};this.emit("error",n)}}async transform(e,t){if(this.mediaTransformerQosReportStartTimestamp_===0&&(this.mediaTransformerQosReportStartTimestamp_=Date.now()),e instanceof VideoFrame&&(this.videoHeight_=e?.displayHeight??0,this.videoWidth_=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 this.transformer_.transform?.(e,t),this.reportQos()}catch(n){this.report({message:pe.errors.transformer_transform,variation:"Error",error:xr(n)});const i={eventMetaData:{transformerIndex:this.index_},error:n,function:"transform"};this.emit("error",i)}if(this.trackExpectedRate_!=-1&&this.trackExpectedRate_*us>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(t){this.report({message:pe.errors.transformer_flush,variation:"Error",error:xr(t)});const n={eventMetaData:{transformerIndex:this.index_},error:t,function:"flush"};this.emit("error",n)}}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:xt,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:xt,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class fs extends q{constructor(e){super(),this.transformers_=[],this.trackExpectedRate_=-1;for(let t=0;t<e.length;t++){let n=new ls(e[t],t);n.on("error",i=>{this.emit("error",i)}),n.on("warn",i=>{this.emit("warn",i)}),this.transformers_.push(n)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let t of this.transformers_)t.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,t){if(!this.transformers_||this.transformers_.length===0){console.log("[Pipeline] No transformers.");return}try{let n=e;for(let i of this.transformers_)e=e.pipeThrough(new TransformStream(i));e.pipeTo(t).then(async()=>{console.log("[Pipeline] Setup."),await t.abort(),await n.cancel(),this.emit("pipelineInfo","pipeline_ended")}).catch(async i=>{e.cancel().then(()=>{console.log("[Pipeline] Shutting down streams after abort.")}).catch(o=>{console.error("[Pipeline] Error from stream transform:",o)}),await t.abort(i),await n.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 On extends q{constructor(){super(),this.reporter_=new br,this.trackExpectedRate_=-1,this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e,this.pipeline_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_)}async transform(e,t){if(this.isTrack(e)){if(e.kind==="video"){const n=new MediaStreamTrackProcessor({track:e}),i=new VideoTrackGenerator;return this.readable_=n.readable,this.writable_=i.writable,await this.transformInternal(),i.track}throw Error("Cannot process audio tracks inside a web worker when passing a track to transform")}else return this.readable_=e,this.writable_=t,this.transformInternal()}transformInternal(){return new Promise(async(e,t)=>{if(!this.transformers_||this.transformers_.length===0){this.report({message:pe.errors.transformer_none,variation:"Error"}),t("[MediaProcessor] Need to set transformers.");return}if(!this.readable_){this.report({variation:"Error",message:pe.errors.readable_null}),t("[MediaProcessor] Readable is null.");return}if(!this.writable_){this.report({variation:"Error",message:pe.errors.writable_null}),t("[MediaProcessor] Writable is null.");return}let n=!1;this.pipeline_&&(n=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new fs(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=>{n&&(i==="pipeline_started"?i=vt.pipeline_restarted:i==="pipeline_started_with_error"&&(i=vt.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=>{t(i)})})}setTransformers(e){return this.report({variation:"Update",message:pe.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:xt,action:"MediaProcessor",...e})}isTrack(e){return"kind"in e}}class ds{constructor(){this.processor_=null,this.generator_=null}init(e){return new Promise((t,n)=>{try{this.processor_=new MediaStreamTrackProcessor(e)}catch(i){console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${i}`),n(i)}try{e.kind==="audio"?this.generator_=new MediaStreamTrackGenerator({kind:"audio"}):e.kind==="video"?this.generator_=new MediaStreamTrackGenerator({kind:"video"}):n("kind not supported")}catch(i){console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${i}`),n(i)}t()})}getReadable(){return this.processor_.readable}getWriteable(){return this.generator_.writable}getProccesorTrack(){return this.generator_}}class hs{constructor(e){this.mediaProcessor_=e}async setTrack(e){if(!(this.mediaProcessor_ instanceof On)&&await vn()){if(e.kind==="audio")throw Error("Cannot process audio tracks inside a web worker when passing a track to transform");return await this.mediaProcessor_.transform(e)}if(xn()){const t=new ds;return await t.init(e),await this.mediaProcessor_.transform(t.getReadable(),t.getWriteable()),t.getProccesorTrack()}throw Error("MediaStreamTrack API for Insertable Streams of Media is not supported")}destroy(){return new Promise((e,t)=>{this.mediaProcessor_?this.mediaProcessor_.destroy().then(()=>{e()}).catch(n=>{t(n)}):t("no processor")})}}var He=(r=>(r.Low="Low",r.High="High",r))(He||{}),Cn=(r=>(r.BackgroundBlur="BackgroundBlur",r.VirtualBackground="VirtualBackground",r.VideoBackground="VideoBackground",r.SilhouetteBlur="SilhouetteBlur",r))(Cn||{}),_t=(r=>(r.FAST="FAST",r.PRECISE="PRECISE",r))(_t||{}),je=(r=>(r.CANVAS="CANVAS",r.WEBGL="WEBGL",r))(je||{});const ms=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]));async function ps(){const{wasm:r,insertableStreams:e,simd:t,webgl:n}=await Mn();if(!r.supported)throw r.message;if(!e.supported)throw e.message;if(!t.supported)throw t.message;if(!n.supported)throw n.message}async function Mn(){const r={wasm:{supported:typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function",message:"Your browser does not support WebAssembly features."},simd:{supported:await ms(),message:"Your browser does not support simd features."},insertableStreams:{supported:!0},gpu:{message:"Your browser does not support gpu features.",supported:!0},webgl:gs(),performance:Bn()};try{await Fo()}catch(e){r.insertableStreams.supported=!1,r.insertableStreams.message=e}return r}function gs(){if(!OffscreenCanvas)return{supported:!1,message:"Your browser does not support offscreen canvas"};const e=new OffscreenCanvas(0,0).getContext("webgl2");if(e){const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}else return{supported:!1,message:"Your browser does not support webgl 2"};return{supported:!0}}function Bn(){const e=new OffscreenCanvas(0,0).getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(e){const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}else return{supported:!1,message:"Your hardware does not perform good enough to run the library efficiently"};return{supported:!0}}const re=new WeakMap,ge=new WeakMap,X=new WeakMap,Et=Symbol("anyProducer"),Dn=Promise.resolve(),At=Symbol("listenerAdded"),Tt=Symbol("listenerRemoved");let St=!1,vr=!1;const It=r=>typeof r=="string"||typeof r=="symbol"||typeof r=="number";function Re(r){if(!It(r))throw new TypeError("`eventName` must be a string, symbol, or number")}function kt(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Pe(r,e){const t=ge.get(r);if(t.has(e))return t.get(e)}function Ye(r,e){const t=It(e)?e:Et,n=X.get(r);if(n.has(t))return n.get(t)}function ys(r,e,t){const n=X.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(Et)){const i=Promise.all([e,t]);for(const o of n.get(Et))o.enqueue(i)}}function Un(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const o={enqueue(s){i.push(s),n()},finish(){t=!0,n()}};for(const s of e){let a=Ye(r,s);a||(a=new Set,X.get(r).set(s,a)),a.add(o)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(s=>{n=s}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(s){i=void 0;for(const a of e){const c=Ye(r,a);c&&(c.delete(o),c.size===0&&X.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await s}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Ln(r){if(r===void 0)return zn;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!zn.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const Fe=r=>r===At||r===Tt;function Rt(r,e,t){if(Fe(e))try{St=!0,r.emit(e,t)}finally{St=!1}}let Qe=class wn{static mixin(e,t){return t=Ln(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const s of t)if(n.prototype[s]!==void 0)throw new Error(`The property \`${s}\` already exists on \`target\``);function i(){return Object.defineProperty(this,e,{enumerable:!1,value:new wn}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const o=s=>function(...a){return this[e][s](...a)};for(const s of t)Object.defineProperty(n.prototype,s,{enumerable:!1,value:o(s)});return n}}static get isDebugEnabled(){if(typeof globalThis.process?.env!="object")return vr;const{env:e}=globalThis.process??{env:{}};return e.DEBUG==="emittery"||e.DEBUG==="*"||vr}static set isDebugEnabled(e){vr=e}constructor(e={}){re.set(this,new Set),ge.set(this,new Map),X.set(this,new Map),X.get(this).set(Et,new Set),this.debug=e.debug??{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(t,n,i,o)=>{try{o=JSON.stringify(o)}catch{o=`Object with the following keys failed to stringify: ${Object.keys(o).join(",")}`}(typeof i=="symbol"||typeof i=="number")&&(i=i.toString());const s=new Date,a=`${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}.${s.getMilliseconds()}`;console.log(`[${a}][emittery:${t}][${n}] Event Name: ${i}
3
- data: ${o}`)})}logIfDebugEnabled(e,t,n){(wn.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t,{signal:n}={}){kt(t),e=Array.isArray(e)?e:[e];for(const o of e){Re(o);let s=Pe(this,o);s||(s=new Set,ge.get(this).set(o,s)),s.add(t),this.logIfDebugEnabled("subscribe",o,void 0),Fe(o)||Rt(this,At,{eventName:o,listener:t})}const i=()=>{this.off(e,t),n?.removeEventListener("abort",i)};return n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i(),i}off(e,t){kt(t),e=Array.isArray(e)?e:[e];for(const n of e){Re(n);const i=Pe(this,n);i&&(i.delete(t),i.size===0&&ge.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),Fe(n)||Rt(this,Tt,{eventName:n,listener:t})}}once(e,t){if(t!==void 0&&typeof t!="function")throw new TypeError("predicate must be a function");let n;const i=new Promise(o=>{n=this.on(e,s=>{t&&!t(s)||(n(),o(s))})});return i.off=n,i}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Re(t);return Un(this,e)}async emit(e,t){if(Re(e),Fe(e)&&!St)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),ys(this,e,t);const n=Pe(this,e)??new Set,i=re.get(this),o=[...n],s=Fe(e)?[]:[...i];await Dn,await Promise.all([...o.map(async a=>{if(n.has(a))return a(t)}),...s.map(async a=>{if(i.has(a))return a(e,t)})])}async emitSerial(e,t){if(Re(e),Fe(e)&&!St)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const n=Pe(this,e)??new Set,i=re.get(this),o=[...n],s=[...i];await Dn;for(const a of o)n.has(a)&&await a(t);for(const a of s)i.has(a)&&await a(e,t)}onAny(e,{signal:t}={}){kt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),re.get(this).add(e),Rt(this,At,{listener:e});const n=()=>{this.offAny(e),t?.removeEventListener("abort",n)};return t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n(),n}anyEvent(){return Un(this)}offAny(e){kt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),Rt(this,Tt,{listener:e}),re.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),It(t)){const n=Pe(this,t);n&&n.clear();const i=Ye(this,t);if(i){for(const o of i)o.finish();i.clear()}}else{re.get(this).clear();for(const[n,i]of ge.get(this).entries())i.clear(),ge.get(this).delete(n);for(const[n,i]of X.get(this).entries()){for(const o of i)o.finish();i.clear(),X.get(this).delete(n)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const n of e){if(It(n)){t+=re.get(this).size+(Pe(this,n)?.size??0)+(Ye(this,n)?.size??0)+(Ye(this)?.size??0);continue}n!==void 0&&Re(n),t+=re.get(this).size;for(const i of ge.get(this).values())t+=i.size;for(const i of X.get(this).values())t+=i.size}return t}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=Ln(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}};const zn=Object.getOwnPropertyNames(Qe.prototype).filter(r=>r!=="constructor");Object.defineProperty(Qe,"listenerAdded",{value:At,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Qe,"listenerRemoved",{value:Tt,writable:!1,enumerable:!0,configurable:!1});function _r(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const Oe=_r("globals",{});var z=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r.EVENT="EVENT",r))(z||{});function Nn(r){return[ImageBitmap,ReadableStream,WritableStream].some(t=>r instanceof t)}let bs=0;function Pt(r,e,t,n,i){const o=bs++;return r.postMessage({id:o,type:e,functionName:t,args:n},n.filter(a=>Nn(a))),new Promise(a=>{i?.set(o,a)})}function Ce(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(o=>Nn(o)))}const Ft=_r("workerized",{});function Er(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function ws(){if(Er())Ce({type:z.GLOBALS_SYNC},Oe);else{const r=[];for(const e in Ft){const{worker:t,resolvers:n}=Ft[e].workerContext;t&&r.push(Pt(t,z.GLOBALS_SYNC,"",[Oe],n))}await Promise.all(r)}}function qe(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],qe(r[t],e[t])):typeof r[t]=="object"?(e[t]={},qe(r[t],e[t])):e[t]=r[t]}async function xs(r,e,t,n){const i=new e;if(i.addEventListener("message",async({data:s})=>{var a,c,u,f,m,p,b;switch(s.type){case z.GLOBALS_SYNC:s.id?((c=t.get((a=s.id)!=null?a:-1))==null||c(s.result),t.delete((u=s.id)!=null?u:-1)):(qe((f=s.result)!=null?f:{},Oe),await ws());break;case z.EVENT:const{result:d}=s,g=d;if(g?.name==null)throw"Missing event name";n(g.name,g.data);break;default:(p=t.get((m=s.id)!=null?m:-1))==null||p(s.result),t.delete((b=s.id)!=null?b:-1)}}),!await Pt(i,z.INIT,"",[r.workerId,Oe],t))throw"Failed to instantiate workerized class";return i}const ne=new WeakMap,ye=new WeakMap,K=new WeakMap,Ot=Symbol("anyProducer"),$n=Promise.resolve(),Ct=Symbol("listenerAdded"),Mt=Symbol("listenerRemoved");let Bt=!1,Ar=!1;function Me(r){if(typeof r!="string"&&typeof r!="symbol"&&typeof r!="number")throw new TypeError("`eventName` must be a string, symbol, or number")}function Dt(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Be(r,e){const t=ye.get(r);if(t.has(e))return t.get(e)}function Xe(r,e){const t=typeof e=="string"||typeof e=="symbol"||typeof e=="number"?e:Ot,n=K.get(r);if(n.has(t))return n.get(t)}function vs(r,e,t){const n=K.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(Ot)){const i=Promise.all([e,t]);for(const o of n.get(Ot))o.enqueue(i)}}function Wn(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const o={enqueue(s){i.push(s),n()},finish(){t=!0,n()}};for(const s of e){let a=Xe(r,s);a||(a=new Set,K.get(r).set(s,a)),a.add(o)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(s=>{n=s}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(s){i=void 0;for(const a of e){const c=Xe(r,a);c&&(c.delete(o),c.size===0&&K.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await s}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Gn(r){if(r===void 0)return Vn;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!Vn.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const De=r=>r===Ct||r===Mt;function Ut(r,e,t){if(De(e))try{Bt=!0,r.emit(e,t)}finally{Bt=!1}}class be{static mixin(e,t){return t=Gn(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const s of t)if(n.prototype[s]!==void 0)throw new Error(`The property \`${s}\` already exists on \`target\``);function i(){return Object.defineProperty(this,e,{enumerable:!1,value:new be}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const o=s=>function(...a){return this[e][s](...a)};for(const s of t)Object.defineProperty(n.prototype,s,{enumerable:!1,value:o(s)});return n}}static get isDebugEnabled(){var e,t;if(typeof((e=globalThis.process)==null?void 0:e.env)!="object")return Ar;const{env:n}=(t=globalThis.process)!=null?t:{env:{}};return n.DEBUG==="emittery"||n.DEBUG==="*"||Ar}static set isDebugEnabled(e){Ar=e}constructor(e={}){var t;ne.set(this,new Set),ye.set(this,new Map),K.set(this,new Map),K.get(this).set(Ot,new Set),this.debug=(t=e.debug)!=null?t:{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(n,i,o,s)=>{try{s=JSON.stringify(s)}catch{s=`Object with the following keys failed to stringify: ${Object.keys(s).join(",")}`}(typeof o=="symbol"||typeof o=="number")&&(o=o.toString());const a=new Date,c=`${a.getHours()}:${a.getMinutes()}:${a.getSeconds()}.${a.getMilliseconds()}`;console.log(`[${c}][emittery:${n}][${i}] Event Name: ${o}
4
- data: ${s}`)})}logIfDebugEnabled(e,t,n){(be.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t){Dt(t),e=Array.isArray(e)?e:[e];for(const n of e){Me(n);let i=Be(this,n);i||(i=new Set,ye.get(this).set(n,i)),i.add(t),this.logIfDebugEnabled("subscribe",n,void 0),De(n)||Ut(this,Ct,{eventName:n,listener:t})}return this.off.bind(this,e,t)}off(e,t){Dt(t),e=Array.isArray(e)?e:[e];for(const n of e){Me(n);const i=Be(this,n);i&&(i.delete(t),i.size===0&&ye.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),De(n)||Ut(this,Mt,{eventName:n,listener:t})}}once(e){let t;const n=new Promise(i=>{t=this.on(e,o=>{t(),i(o)})});return n.off=t,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Me(t);return Wn(this,e)}async emit(e,t){var n;if(Me(e),De(e)&&!Bt)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),vs(this,e,t);const i=(n=Be(this,e))!=null?n:new Set,o=ne.get(this),s=[...i],a=De(e)?[]:[...o];await $n,await Promise.all([...s.map(async c=>{if(i.has(c))return c(t)}),...a.map(async c=>{if(o.has(c))return c(e,t)})])}async emitSerial(e,t){var n;if(Me(e),De(e)&&!Bt)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const i=(n=Be(this,e))!=null?n:new Set,o=ne.get(this),s=[...i],a=[...o];await $n;for(const c of s)i.has(c)&&await c(t);for(const c of a)o.has(c)&&await c(e,t)}onAny(e){return Dt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),ne.get(this).add(e),Ut(this,Ct,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return Wn(this)}offAny(e){Dt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),Ut(this,Mt,{listener:e}),ne.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),typeof t=="string"||typeof t=="symbol"||typeof t=="number"){const n=Be(this,t);n&&n.clear();const i=Xe(this,t);if(i){for(const o of i)o.finish();i.clear()}}else{ne.get(this).clear();for(const[n,i]of ye.get(this).entries())i.clear(),ye.get(this).delete(n);for(const[n,i]of K.get(this).entries()){for(const o of i)o.finish();i.clear(),K.get(this).delete(n)}}}listenerCount(e){var t,n,i,o,s,a;e=Array.isArray(e)?e:[e];let c=0;for(const u of e){if(typeof u=="string"){c+=ne.get(this).size+((n=(t=Be(this,u))==null?void 0:t.size)!=null?n:0)+((o=(i=Xe(this,u))==null?void 0:i.size)!=null?o:0)+((a=(s=Xe(this))==null?void 0:s.size)!=null?a:0);continue}typeof u<"u"&&Me(u),c+=ne.get(this).size;for(const f of ye.get(this).values())c+=f.size;for(const f of K.get(this).values())c+=f.size}return c}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=Gn(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const Vn=Object.getOwnPropertyNames(be.prototype).filter(r=>r!=="constructor");Object.defineProperty(be,"listenerAdded",{value:Ct,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(be,"listenerRemoved",{value:Mt,writable:!1,enumerable:!0,configurable:!1});function _s(r){return r.onAny&&r.emit}function Es(r){return r.prototype.onAny&&r.prototype.emit}let As=0;async function Ts(r,e,t){const i=Es(r)?new be:{},o=As++;return Object.getOwnPropertyNames(r.prototype).forEach(s=>{i[s]=(...a)=>Pt(e,z.FORWARD,s,a,t)}),i.terminate=async(...s)=>{const a=await Pt(e,z.TERMINATE,"",s,t);return delete Ft[o],e.terminate(),i.workerContext.worker=void 0,a},i.workerContext={id:o,worker:e,resolvers:t},Ft[o]=i,i}async function Ss(r,e){const t=new Map;let n;const i=await xs(r,e,t,(o,s)=>{n?.emit&&n?.emit(o,s)});return n=await Ts(r,i,t),n}async function Is(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Ce(r,await e.instance[t](...n??[]))}const Hn=_r("registeredWorkers",{});function ks(r,e){e.workerId=r,Er()&&(Hn[e.workerId]=e)}function Rs(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=Hn[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;qe(n,Oe),_s(e.instance)&&e.instance.onAny((o,s)=>{Ce({type:z.EVENT},{name:o,data:s})}),Ce(r,typeof e.instance!==void 0)}async function Ps(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Ce(r,n)}function Fs(r){if(!r.args)throw"Missing globals while syncing";qe(r.args[0],Oe),Ce(r,{})}function Os(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case z.INIT:Rs(t,r);break;case z.FORWARD:Is(t,r);break;case z.TERMINATE:Ps(t,r);break;case z.GLOBALS_SYNC:Fs(t);break}}}Er()&&Os();class jn{static async createVideoReadable(e){return new Promise((t,n)=>{const i=document.createElement("video");let o=new AbortController,s=new AbortController;i.addEventListener("canplay",()=>{o.abort(),i.muted=!0,i.loop=!0,i.play().then(()=>{try{const a=i.captureStream(),c=new MediaStreamTrackProcessor(a.getVideoTracks()[0]);t(c.readable)}catch(a){n(a)}})},{once:!0,signal:s.signal}),i.addEventListener("error",a=>{s.abort(),n("loading error:"+a)},{once:!0,signal:o.signal}),i.crossOrigin="anonymous",i.src=e})}static async createImageCanvas(e){const n=await(await fetch(e)).blob();return await createImageBitmap(n)}}var Cs=Object.defineProperty,Ms=(r,e,t)=>e in r?Cs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Bs=(r,e,t)=>(Ms(r,e+"",t),t);const Ds="hlg.tokbox.com/prod/logging/vcp_webrtc",Us="https://",Ls=1e4;let Lt;const zs=new Uint8Array(16);function Ns(){if(!Lt&&(Lt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Lt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lt(zs)}const F=[];for(let r=0;r<256;++r)F.push((r+256).toString(16).slice(1));function $s(r,e=0){return(F[r[e+0]]+F[r[e+1]]+F[r[e+2]]+F[r[e+3]]+"-"+F[r[e+4]]+F[r[e+5]]+"-"+F[r[e+6]]+F[r[e+7]]+"-"+F[r[e+8]]+F[r[e+9]]+"-"+F[r[e+10]]+F[r[e+11]]+F[r[e+12]]+F[r[e+13]]+F[r[e+14]]+F[r[e+15]]).toLowerCase()}const Ws=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Yn={randomUUID:Ws};function Gs(r,e,t){if(Yn.randomUUID&&!e&&!r)return Yn.randomUUID();r=r||{};const n=r.random||(r.rng||Ns)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,$s(n)}function Tr(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const ie=Tr("globals",{});var we=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r))(we||{});function Qn(r){return[ImageBitmap,ReadableStream,WritableStream].some(e=>r instanceof e)}let Vs=0;function Hs(r,e,t,n,i){const o=Vs++;return r.postMessage({id:o,type:e,functionName:t,args:n},n.filter(s=>Qn(s))),new Promise(s=>{i?.set(o,s)})}function Ke(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(o=>Qn(o)))}const qn=Tr("workerized",{});function Xn(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function js(){if(Xn())Ke({type:we.GLOBALS_SYNC},ie);else{const r=[];for(const e in qn){const{worker:t,resolvers:n}=qn[e].workerContext;t&&r.push(Hs(t,we.GLOBALS_SYNC,"",[ie],n))}await Promise.all(r)}}function zt(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],zt(r[t],e[t])):typeof r[t]=="object"?(e[t]={},zt(r[t],e[t])):e[t]=r[t]}async function Ys(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Ke(r,await e.instance[t](...n??[]))}const Qs=Tr("registeredWorkers",{});function qs(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=Qs[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;zt(n,ie),Ke(r,typeof e.instance!==void 0)}async function Xs(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Ke(r,n)}function Ks(r){if(!r.args)throw"Missing globals while syncing";zt(r.args[0],ie),Ke(r,{})}function Js(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case we.INIT:qs(t,r);break;case we.FORWARD:Ys(t,r);break;case we.TERMINATE:Xs(t,r);break;case we.GLOBALS_SYNC:Ks(t);break}}}Xn()&&Js();function Zs(r,e){return ie[r]||(ie[r]=e),[()=>ie[r],async t=>{ie[r]=t,await js()}]}function ea(r,e){return Zs(r,e)}const[ta]=ea("metadata");function Sr(){return ta()}class ra{constructor(e){Bs(this,"uuid",Gs()),this.config=e}async send(e){var t,n,i;const{appId:o,sourceType:s}=(t=Sr())!=null?t:{};if(!o||!s)return"metadata missing";const a=new AbortController,c=setTimeout(()=>a.abort(),Ls);return await((i=(n=this.config)==null?void 0:n.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(c),"success"}getUrl(){var e;let t=(e=Sr().proxyUrl)!=null?e:Us;return t+=(t.at(-1)==="/"?"":"/")+Ds,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=Sr();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}}const na="7.0.0-alpha.2";class Ir{constructor(){const e=new OffscreenCanvas(0,0),t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw"Fail to retrieve 2d context";this.canvas=e,this.context=t}enablePostProcessing(){}disablePostProcessing(){}async profileWebgl(e){return[]}async render(e,t){return this.canvas}resizeCanvas(e){const{width:t,height:n}=e;this.canvas.width=t,this.canvas.height=n}renderSilhouette(e,t,n="none"){const{width:i,height:o}=e;this.context.save(),this.context.drawImage(t,0,0,t.width,t.height,0,0,i,o),this.context.filter="blur(5px)",this.context.globalCompositeOperation="source-in",this.context.drawImage(t,0,0,t.width,t.height,0,0,i,o),this.context.globalCompositeOperation="source-in",this.context.filter=n,this.context.drawImage(e,0,0,i,o,0,0,this.canvas.width,this.canvas.height),this.context.restore()}destroy(){}}class ia extends Ir{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n),this.context.save(),this.context.filter=`blur(${this.radius}px)`,this.context.globalCompositeOperation="destination-over",this.context.drawImage(e,0,0,e.width,e.height),this.context.restore(),super.render(e,t)}}class oa extends Ir{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n,`blur(${this.radius}px)`),this.context.save(),this.context.filter="none",this.context.globalCompositeOperation="destination-over",this.context.drawImage(e,0,0,e.width,e.height),this.context.restore(),super.render(e,t)}}class sa extends Ir{setBackgroundImage(e){this.backgroundImage=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n),this.backgroundImage&&(this.context.save(),this.context.filter="none",this.context.globalCompositeOperation="destination-over",this.context.drawImage(this.backgroundImage,0,0,this.backgroundImage.width,this.backgroundImage.height,0,0,e.width,e.height),this.context.restore()),super.render(e,t)}}const kr=5120,Je=5121,Rr=5122,Pr=5123,Fr=5124,Or=5125,Cr=5126,aa=32819,ca=32820,ua=33635,la=5131,fa=33640,da=35899,ha=35902,ma=36269,pa=34042,Kn={};{const r=Kn;r[kr]=Int8Array,r[Je]=Uint8Array,r[Rr]=Int16Array,r[Pr]=Uint16Array,r[Fr]=Int32Array,r[Or]=Uint32Array,r[Cr]=Float32Array,r[aa]=Uint16Array,r[ca]=Uint16Array,r[ua]=Uint16Array,r[la]=Uint16Array,r[fa]=Uint32Array,r[da]=Uint32Array,r[ha]=Uint32Array,r[ma]=Uint32Array,r[pa]=Uint32Array}function Mr(r){if(r instanceof Int8Array)return kr;if(r instanceof Uint8Array||r instanceof Uint8ClampedArray)return Je;if(r instanceof Int16Array)return Rr;if(r instanceof Uint16Array)return Pr;if(r instanceof Int32Array)return Fr;if(r instanceof Uint32Array)return Or;if(r instanceof Float32Array)return Cr;throw new Error("unsupported typed array type")}function Jn(r){if(r===Int8Array)return kr;if(r===Uint8Array||r===Uint8ClampedArray)return Je;if(r===Int16Array)return Rr;if(r===Uint16Array)return Pr;if(r===Int32Array)return Fr;if(r===Uint32Array)return Or;if(r===Float32Array)return Cr;throw new Error("unsupported typed array type")}function Zn(r){const e=Kn[r];if(!e)throw new Error("unknown gl type");return e}const Nt=typeof SharedArrayBuffer<"u"?function(e){return e&&e.buffer&&(e.buffer instanceof ArrayBuffer||e.buffer instanceof SharedArrayBuffer)}:function(e){return e&&e.buffer&&e.buffer instanceof ArrayBuffer};function ei(...r){console.error(...r)}const ti=new Map;function $t(r,e){if(!r||typeof r!="object")return!1;let t=ti.get(e);t||(t=new WeakMap,ti.set(e,t));let n=t.get(r);if(n===void 0){const i=Object.prototype.toString.call(r);n=i.substring(8,i.length-1)===e,t.set(r,n)}return n}function ga(r,e){return typeof WebGLBuffer<"u"&&$t(e,"WebGLBuffer")}function ya(r,e){return typeof WebGLRenderbuffer<"u"&&$t(e,"WebGLRenderbuffer")}function Br(r,e){return typeof WebGLTexture<"u"&&$t(e,"WebGLTexture")}function ba(r,e){return typeof WebGLSampler<"u"&&$t(e,"WebGLSampler")}const ri=35044,xe=34962,wa=34963,xa=34660,va=5120,_a=5121,Ea=5122,Aa=5123,Ta=5124,Sa=5125,ni=5126,ii={attribPrefix:""};function Ia(r,e,t,n,i){r.bindBuffer(e,t),r.bufferData(e,n,i||ri)}function oi(r,e,t,n){if(ga(r,e))return e;t=t||xe;const i=r.createBuffer();return Ia(r,t,i,e,n),i}function si(r){return r==="indices"}function ka(r){return r===Int8Array||r===Uint8Array}function Ra(r){return r.length?r:r.data}const Pa=/coord|texture/i,Fa=/color|colour/i;function Oa(r,e){let t;if(Pa.test(r)?t=2:Fa.test(r)?t=4:t=3,e%t>0)throw new Error(`Can not guess numComponents for attribute '${r}'. Tried ${t} but ${e} values is not evenly divisible by ${t}. You should specify it.`);return t}function Ca(r,e,t){return r.numComponents||r.size||Oa(e,t||Ra(r).length)}function ai(r,e){if(Nt(r))return r;if(Nt(r.data))return r.data;Array.isArray(r)&&(r={data:r});let t=r.type?Dr(r.type):void 0;return t||(si(e)?t=Uint16Array:t=Float32Array),new t(r.data)}function Ma(r){return typeof r=="number"?r:r?Jn(r):ni}function Dr(r){return typeof r=="number"?Zn(r):r||Float32Array}function Ba(r,e){return{buffer:e.buffer,numValues:24,type:Ma(e.type),arrayType:Dr(e.type)}}function Da(r,e){const t=e.data||e,n=Dr(e.type),i=t*n.BYTES_PER_ELEMENT,o=r.createBuffer();return r.bindBuffer(xe,o),r.bufferData(xe,i,e.drawType||ri),{buffer:o,numValues:t,type:Jn(n),arrayType:n}}function Ua(r,e,t){const n=ai(e,t);return{arrayType:n.constructor,buffer:oi(r,n,void 0,e.drawType),type:Mr(n),numValues:0}}function La(r,e){const t={};return Object.keys(e).forEach(function(n){if(!si(n)){const i=e[n],o=i.attrib||i.name||i.attribName||ii.attribPrefix+n;if(i.value){if(!Array.isArray(i.value)&&!Nt(i.value))throw new Error("array.value is not array or typedarray");t[o]={value:i.value}}else{let s;i.buffer&&i.buffer instanceof WebGLBuffer?s=Ba:typeof i=="number"||typeof i.data=="number"?s=Da:s=Ua;const{buffer:a,type:c,numValues:u,arrayType:f}=s(r,i,n),m=i.normalize!==void 0?i.normalize:ka(f),p=Ca(i,n,u);t[o]={buffer:a,numComponents:p,type:c,normalize:m,stride:i.stride||0,offset:i.offset||0,divisor:i.divisor===void 0?void 0:i.divisor,drawType:i.drawType}}}}),r.bindBuffer(xe,null),t}function za(r,e){return e===va||e===_a?1:e===Ea||e===Aa?2:e===Ta||e===Sa||e===ni?4:0}const Ur=["position","positions","a_position"];function Na(r,e){let t,n;for(n=0;n<Ur.length&&(t=Ur[n],!(t in e||(t=ii.attribPrefix+t,t in e)));++n);n===Ur.length&&(t=Object.keys(e)[0]);const i=e[t];if(!i.buffer)return 1;r.bindBuffer(xe,i.buffer);const o=r.getBufferParameter(xe,xa);r.bindBuffer(xe,null);const s=za(r,i.type),a=o/s,c=i.numComponents||i.size,u=a/c;if(u%1!==0)throw new Error(`numComponents ${c} not correct for length ${length}`);return u}function $a(r,e,t){const n=La(r,e),i=Object.assign({},t||{});i.attribs=Object.assign({},t?t.attribs:{},n);const o=e.indices;if(o){const s=ai(o,"indices");i.indices=oi(r,s,wa),i.numElements=s.length,i.elementType=Mr(s)}else i.numElements||(i.numElements=Na(r,i.attribs));return i}function Ze(r){return!!r.texStorage2D}const ci=(function(){const r={},e={};function t(n){const i=n.constructor.name;if(!r[i]){for(const o in n)if(typeof n[o]=="number"){const s=e[n[o]];e[n[o]]=s?`${s} | ${o}`:o}r[i]=!0}}return function(i,o){return t(i),e[o]||(typeof o=="number"?`0x${o.toString(16)}`:o)}})(),oe={textureColor:new Uint8Array([128,192,255,255]),textureOptions:{},crossOrigin:void 0},et=Nt,ui=(function(){let r;return function(){return r=r||(typeof document<"u"&&document.createElement?document.createElement("canvas").getContext("2d"):null),r}})(),li=6406,j=6407,T=6408,fi=6409,di=6410,tt=6402,hi=34041,Wt=33071,Wa=9728,Ga=9729,se=3553,ae=34067,ve=32879,_e=35866,Lr=34069,Va=34070,Ha=34071,ja=34072,Ya=34073,Qa=34074,zr=10241,Nr=10240,Gt=10242,Vt=10243,mi=32882,qa=33082,Xa=33083,Ka=33084,Ja=33085,Za=34892,ec=34893,$r=3317,pi=3314,gi=32878,yi=3316,bi=3315,wi=32877,tc=37443,rc=37441,nc=37440,ic=33321,oc=36756,sc=33325,ac=33326,cc=33330,uc=33329,lc=33338,fc=33337,dc=33340,hc=33339,mc=33323,pc=36757,gc=33327,yc=33328,bc=33336,wc=33335,xc=33332,vc=33331,_c=33334,Ec=33333,Ac=32849,Tc=35905,Sc=36194,Ic=36758,kc=35898,Rc=35901,Pc=34843,Fc=34837,Oc=36221,Cc=36239,Mc=36215,Bc=36233,Dc=36209,Uc=36227,Lc=32856,zc=35907,Nc=36759,$c=32855,Wc=32854,Gc=32857,Vc=34842,Hc=34836,jc=36220,Yc=36238,Qc=36975,qc=36214,Xc=36232,Kc=36226,Jc=36208,Zc=33189,eu=33190,tu=36012,ru=36013,nu=35056,ce=5120,A=5121,Ht=5122,Ue=5123,jt=5124,Ee=5125,M=5126,xi=32819,vi=32820,_i=33635,W=5131,rt=36193,Wr=33640,iu=35899,ou=35902,su=36269,au=34042,Yt=33319,Le=33320,Qt=6403,ze=36244,Ne=36248,Ae=36249;let Gr;function qt(r){if(!Gr){const e={};e[li]={textureFormat:li,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[A,W,rt,M]},e[fi]={textureFormat:fi,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[A,W,rt,M]},e[di]={textureFormat:di,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2,4,4,8],type:[A,W,rt,M]},e[j]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,6,6,12,2],type:[A,W,rt,M,_i]},e[T]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,8,8,16,2,2],type:[A,W,rt,M,xi,vi]},e[tt]={textureFormat:tt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[Ee,Ue]},e[ic]={textureFormat:Qt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1],type:[A]},e[oc]={textureFormat:Qt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[1],type:[ce]},e[sc]={textureFormat:Qt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4,2],type:[M,W]},e[ac]={textureFormat:Qt,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[cc]={textureFormat:ze,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[A]},e[uc]={textureFormat:ze,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[ce]},e[xc]={textureFormat:ze,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Ue]},e[vc]={textureFormat:ze,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Ht]},e[_c]={textureFormat:ze,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Ee]},e[Ec]={textureFormat:ze,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[jt]},e[mc]={textureFormat:Yt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2],type:[A]},e[pc]={textureFormat:Yt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[2],type:[ce]},e[gc]={textureFormat:Yt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[8,4],type:[M,W]},e[yc]={textureFormat:Yt,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[8],type:[M]},e[bc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[A]},e[wc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[ce]},e[lc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Ue]},e[fc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Ht]},e[dc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Ee]},e[hc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[jt]},e[Ac]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3],type:[A]},e[Tc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[A]},e[Sc]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,2],type:[A,_i]},e[Ic]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[ce]},e[kc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,W,iu]},e[Rc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,W,ou]},e[Pc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6],type:[M,W]},e[Fc]={textureFormat:j,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[M]},e[Oc]={textureFormat:Ne,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[A]},e[Cc]={textureFormat:Ne,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[ce]},e[Mc]={textureFormat:Ne,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Ue]},e[Bc]={textureFormat:Ne,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Ht]},e[Dc]={textureFormat:Ne,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[Ee]},e[Uc]={textureFormat:Ne,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[jt]},e[Lc]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[A]},e[zc]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[A]},e[Nc]={textureFormat:T,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4],type:[ce]},e[$c]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2,4],type:[A,vi,Wr]},e[Wc]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2],type:[A,xi]},e[Gc]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[Wr]},e[Vc]={textureFormat:T,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[16,8],type:[M,W]},e[Hc]={textureFormat:T,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[16],type:[M]},e[jc]={textureFormat:Ae,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[A]},e[Yc]={textureFormat:Ae,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ce]},e[Qc]={textureFormat:Ae,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Wr]},e[qc]={textureFormat:Ae,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Ue]},e[Xc]={textureFormat:Ae,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Ht]},e[Kc]={textureFormat:Ae,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[jt]},e[Jc]={textureFormat:Ae,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[Ee]},e[Zc]={textureFormat:tt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[Ue,Ee]},e[eu]={textureFormat:tt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Ee]},e[tu]={textureFormat:tt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[nu]={textureFormat:hi,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[au]},e[ru]={textureFormat:hi,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[su]},Object.keys(e).forEach(function(t){const n=e[t];n.bytesPerElementMap={},n.bytesPerElement.forEach(function(i,o){const s=n.type[o];n.bytesPerElementMap[s]=i})}),Gr=e}return Gr[r]}function cu(r,e){const t=qt(r);if(!t)throw"unknown internal format";const n=t.bytesPerElementMap[e];if(n===void 0)throw"unknown internal format";return n}function nt(r){const e=qt(r);if(!e)throw"unknown internal format";return{format:e.textureFormat,type:e.type[0]}}function Ei(r){return(r&r-1)===0}function uu(r,e,t,n){if(!Ze(r))return Ei(e)&&Ei(t);const i=qt(n);if(!i)throw"unknown internal format";return i.colorRenderable&&i.textureFilterable}function lu(r){const e=qt(r);if(!e)throw"unknown internal format";return e.textureFilterable}function fu(r,e,t){return et(e)?Mr(e):t||A}function Xt(r,e,t,n,i){if(i%1!==0)throw"can't guess dimensions";if(!t&&!n){const o=Math.sqrt(i/(e===ae?6:1));o%1===0?(t=o,n=o):(t=i,n=1)}else if(n){if(!t&&(t=i/n,t%1))throw"can't guess dimensions"}else if(n=i/t,n%1)throw"can't guess dimensions";return{width:t,height:n}}function $e(r,e){e.colorspaceConversion!==void 0&&r.pixelStorei(tc,e.colorspaceConversion),e.premultiplyAlpha!==void 0&&r.pixelStorei(rc,e.premultiplyAlpha),e.flipY!==void 0&&r.pixelStorei(nc,e.flipY)}function Ai(r){r.pixelStorei($r,4),Ze(r)&&(r.pixelStorei(pi,0),r.pixelStorei(gi,0),r.pixelStorei(yi,0),r.pixelStorei(bi,0),r.pixelStorei(wi,0))}function du(r,e,t,n){n.minMag&&(t.call(r,e,zr,n.minMag),t.call(r,e,Nr,n.minMag)),n.min&&t.call(r,e,zr,n.min),n.mag&&t.call(r,e,Nr,n.mag),n.wrap&&(t.call(r,e,Gt,n.wrap),t.call(r,e,Vt,n.wrap),(e===ve||ba(r,e))&&t.call(r,e,mi,n.wrap)),n.wrapR&&t.call(r,e,mi,n.wrapR),n.wrapS&&t.call(r,e,Gt,n.wrapS),n.wrapT&&t.call(r,e,Vt,n.wrapT),n.minLod!==void 0&&t.call(r,e,qa,n.minLod),n.maxLod!==void 0&&t.call(r,e,Xa,n.maxLod),n.baseLevel!==void 0&&t.call(r,e,Ka,n.baseLevel),n.maxLevel!==void 0&&t.call(r,e,Ja,n.maxLevel),n.compareFunc!==void 0&&t.call(r,e,ec,n.compareFunc),n.compareMode!==void 0&&t.call(r,e,Za,n.compareMode)}function Ti(r,e,t){const n=t.target||se;r.bindTexture(n,e),du(r,n,r.texParameteri,t)}function hu(r){return r=r||oe.textureColor,et(r)?r:new Uint8Array([r[0]*255,r[1]*255,r[2]*255,r[3]*255])}function Vr(r,e,t,n,i,o){t=t||oe.textureOptions,o=o||T;const s=t.target||se;if(n=n||t.width,i=i||t.height,r.bindTexture(s,e),uu(r,n,i,o))r.generateMipmap(s);else{const a=lu(o)?Ga:Wa;r.texParameteri(s,zr,a),r.texParameteri(s,Nr,a),r.texParameteri(s,Gt,Wt),r.texParameteri(s,Vt,Wt)}}function it(r){return r.auto===!0||r.auto===void 0&&r.level===void 0}function Hr(r,e){return e=e||{},e.cubeFaceOrder||[Lr,Va,Ha,ja,Ya,Qa]}function jr(r,e){const n=Hr(r,e).map(function(i,o){return{face:i,ndx:o}});return n.sort(function(i,o){return i.face-o.face}),n}function Si(r,e,t,n){n=n||oe.textureOptions;const i=n.target||se,o=n.level||0;let s=t.width,a=t.height;const c=n.internalFormat||n.format||T,u=nt(c),f=n.format||u.format,m=n.type||u.type;if($e(r,n),r.bindTexture(i,e),i===ae){const p=t.width,b=t.height;let d,g;if(p/6===b)d=b,g=[0,0,1,0,2,0,3,0,4,0,5,0];else if(b/6===p)d=p,g=[0,0,0,1,0,2,0,3,0,4,0,5];else if(p/3===b/2)d=p/3,g=[0,0,1,0,2,0,0,1,1,1,2,1];else if(p/2===b/3)d=p/2,g=[0,0,1,0,0,1,1,1,0,2,1,2];else throw"can't figure out cube map from element: "+(t.src?t.src:t.nodeName);const x=ui();x?(x.canvas.width=d,x.canvas.height=d,s=d,a=d,jr(r,n).forEach(function(v){const k=g[v.ndx*2+0]*d,O=g[v.ndx*2+1]*d;x.drawImage(t,k,O,d,d,0,0,d,d),r.texImage2D(v.face,o,c,f,m,x.canvas)}),x.canvas.width=1,x.canvas.height=1):typeof createImageBitmap<"u"&&(s=d,a=d,jr(r,n).forEach(function(v){const k=g[v.ndx*2+0]*d,O=g[v.ndx*2+1]*d;r.texImage2D(v.face,o,c,d,d,0,f,m,null),createImageBitmap(t,k,O,d,d,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(function(N){$e(r,n),r.bindTexture(i,e),r.texImage2D(v.face,o,c,f,m,N),it(n)&&Vr(r,e,n,s,a,c)})}))}else if(i===ve||i===_e){const p=Math.min(t.width,t.height),b=Math.max(t.width,t.height),d=b/p;if(d%1!==0)throw"can not compute 3D dimensions of element";const g=t.width===b?1:0,x=t.height===b?1:0;r.pixelStorei($r,1),r.pixelStorei(pi,t.width),r.pixelStorei(gi,0),r.pixelStorei(wi,0),r.texImage3D(i,o,c,p,p,p,0,f,m,null);for(let v=0;v<d;++v){const k=v*p*g,O=v*p*x;r.pixelStorei(yi,k),r.pixelStorei(bi,O),r.texSubImage3D(i,o,0,0,v,p,p,1,f,m,t)}Ai(r)}else r.texImage2D(i,o,c,f,m,t);it(n)&&Vr(r,e,n,s,a,c),Ti(r,e,n)}function ot(){}function mu(r){if(typeof document<"u"){const e=document.createElement("a");return e.href=r,e.hostname===location.hostname&&e.port===location.port&&e.protocol===location.protocol}else{const e=new URL(location.href).origin;return new URL(r,location.href).origin===e}}function pu(r,e){return e===void 0&&!mu(r)?"anonymous":e}function gu(r,e,t){t=t||ot;let n;if(e=e!==void 0?e:oe.crossOrigin,e=pu(r,e),typeof Image<"u"){n=new Image,e!==void 0&&(n.crossOrigin=e);const i=function(){n.removeEventListener("error",o),n.removeEventListener("load",s),n=null},o=function(){const c="couldn't load image: "+r;ei(c),t(c,n),i()},s=function(){t(null,n),i()};return n.addEventListener("error",o),n.addEventListener("load",s),n.src=r,n}else if(typeof ImageBitmap<"u"){let i,o;const s=function(){t(i,o)},a={};e&&(a.mode="cors"),fetch(r,a).then(function(c){if(!c.ok)throw c;return c.blob()}).then(function(c){return createImageBitmap(c,{premultiplyAlpha:"none",colorSpaceConversion:"none"})}).then(function(c){o=c,setTimeout(s)}).catch(function(c){i=c,setTimeout(s)}),n=null}return n}function Ii(r){return typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof ImageData<"u"&&r instanceof ImageData||typeof HTMLElement<"u"&&r instanceof HTMLElement}function Yr(r,e,t){return Ii(r)?(setTimeout(function(){t(null,r)}),r):gu(r,e,t)}function Qr(r,e,t){t=t||oe.textureOptions;const n=t.target||se;if(r.bindTexture(n,e),t.color===!1)return;const i=hu(t.color);if(n===ae)for(let o=0;o<6;++o)r.texImage2D(Lr+o,0,T,1,1,0,T,A,i);else n===ve||n===_e?r.texImage3D(n,0,T,1,1,1,0,T,A,i):r.texImage2D(n,0,T,1,1,0,T,A,i)}function yu(r,e,t,n){return n=n||ot,t=t||oe.textureOptions,Qr(r,e,t),t=Object.assign({},t),Yr(t.src,t.crossOrigin,function(o,s){o?n(o,e,s):(Si(r,e,s,t),n(null,e,s))})}function bu(r,e,t,n){n=n||ot;const i=t.src;if(i.length!==6)throw"there must be 6 urls for a cubemap";const o=t.level||0,s=t.internalFormat||t.format||T,a=nt(s),c=t.format||a.format,u=t.type||A,f=t.target||se;if(f!==ae)throw"target must be TEXTURE_CUBE_MAP";Qr(r,e,t),t=Object.assign({},t);let m=6;const p=[],b=Hr(r,t);let d;function g(x){return function(v,k){--m,v?p.push(v):k.width!==k.height?p.push("cubemap face img is not a square: "+k.src):($e(r,t),r.bindTexture(f,e),m===5?Hr().forEach(function(O){r.texImage2D(O,o,s,c,u,k)}):r.texImage2D(x,o,s,c,u,k),it(t)&&r.generateMipmap(f)),m===0&&n(p.length?p:void 0,e,d)}}d=i.map(function(x,v){return Yr(x,t.crossOrigin,g(b[v]))})}function wu(r,e,t,n){n=n||ot;const i=t.src,o=t.internalFormat||t.format||T,s=nt(o),a=t.format||s.format,c=t.type||A,u=t.target||_e;if(u!==ve&&u!==_e)throw"target must be TEXTURE_3D or TEXTURE_2D_ARRAY";Qr(r,e,t),t=Object.assign({},t);let f=i.length;const m=[];let p;const b=t.level||0;let d=t.width,g=t.height;const x=i.length;let v=!0;function k(O){return function(N,J){if(--f,N)m.push(N);else{if($e(r,t),r.bindTexture(u,e),v){v=!1,d=t.width||J.width,g=t.height||J.height,r.texImage3D(u,b,o,d,g,x,0,a,c,null);for(let Z=0;Z<x;++Z)r.texSubImage3D(u,b,0,0,Z,d,g,1,a,c,J)}else{let Z=J,$;(J.width!==d||J.height!==g)&&($=ui(),Z=$.canvas,$.canvas.width=d,$.canvas.height=g,$.drawImage(J,0,0,d,g)),r.texSubImage3D(u,b,0,0,O,d,g,1,a,c,Z),$&&Z===$.canvas&&($.canvas.width=0,$.canvas.height=0)}it(t)&&r.generateMipmap(u)}f===0&&n(m.length?m:void 0,e,p)}}p=i.map(function(O,N){return Yr(O,t.crossOrigin,k(N))})}function xu(r,e,t,n){n=n||oe.textureOptions;const i=n.target||se;r.bindTexture(i,e);let o=n.width,s=n.height,a=n.depth;const c=n.level||0,u=n.internalFormat||n.format||T,f=nt(u),m=n.format||f.format,p=n.type||fu(r,t,f.type);if(et(t))t instanceof Uint8ClampedArray&&(t=new Uint8Array(t.buffer));else{const x=Zn(p);t=new x(t)}const b=cu(u,p),d=t.byteLength/b;if(d%1)throw"length wrong size for format: "+ci(r,m);let g;if(i===ve||i===_e)if(!o&&!s&&!a){const x=Math.cbrt(d);if(x%1!==0)throw"can't guess cube size of array of numElements: "+d;o=x,s=x,a=x}else o&&(!s||!a)?(g=Xt(r,i,s,a,d/o),s=g.width,a=g.height):s&&(!o||!a)?(g=Xt(r,i,o,a,d/s),o=g.width,a=g.height):(g=Xt(r,i,o,s,d/a),o=g.width,s=g.height);else g=Xt(r,i,o,s,d),o=g.width,s=g.height;if(Ai(r),r.pixelStorei($r,n.unpackAlignment||1),$e(r,n),i===ae){const x=b/t.BYTES_PER_ELEMENT,v=d/6*x;jr(r,n).forEach(k=>{const O=v*k.ndx,N=t.subarray(O,O+v);r.texImage2D(k.face,c,u,o,s,0,m,p,N)})}else i===ve||i===_e?r.texImage3D(i,c,u,o,s,a,0,m,p,t):r.texImage2D(i,c,u,o,s,0,m,p,t);return{width:o,height:s,depth:a,type:p}}function vu(r,e,t){const n=t.target||se;r.bindTexture(n,e);const i=t.level||0,o=t.internalFormat||t.format||T,s=nt(o),a=t.format||s.format,c=t.type||s.type;if($e(r,t),n===ae)for(let u=0;u<6;++u)r.texImage2D(Lr+u,i,o,t.width,t.height,0,a,c,null);else n===ve||n===_e?r.texImage3D(n,i,o,t.width,t.height,t.depth,0,a,c,null):r.texImage2D(n,i,o,t.width,t.height,0,a,c,null)}function ki(r,e,t){t=t||ot,e=e||oe.textureOptions;const n=r.createTexture(),i=e.target||se;let o=e.width||1,s=e.height||1;const a=e.internalFormat||T;r.bindTexture(i,n),i===ae&&(r.texParameteri(i,Gt,Wt),r.texParameteri(i,Vt,Wt));let c=e.src;if(c)if(typeof c=="function"&&(c=c(r,e)),typeof c=="string")yu(r,n,e,t);else if(et(c)||Array.isArray(c)&&(typeof c[0]=="number"||Array.isArray(c[0])||et(c[0]))){const u=xu(r,n,c,e);o=u.width,s=u.height}else Array.isArray(c)&&(typeof c[0]=="string"||Ii(c[0]))?i===ae?bu(r,n,e,t):wu(r,n,e,t):(Si(r,n,c,e),o=c.width,s=c.height);else vu(r,n,e);return it(e)&&Vr(r,n,e,o,s,a),Ti(r,n,e),n}const qr=ei;function Ri(r){return typeof document<"u"&&document.getElementById?document.getElementById(r):null}const Kt=33984,Jt=34962,_u=34963,Eu=35713,Au=35714,Tu=35632,Su=35633,Iu=35981,Pi=35718,ku=35721,Ru=35971,Pu=35382,Fu=35396,Ou=35398,Cu=35392,Mu=35395,Zt=5126,Fi=35664,Oi=35665,Ci=35666,Xr=5124,Mi=35667,Bi=35668,Di=35669,Ui=35670,Li=35671,zi=35672,Ni=35673,$i=35674,Wi=35675,Gi=35676,Bu=35678,Du=35680,Uu=35679,Lu=35682,zu=35685,Nu=35686,$u=35687,Wu=35688,Gu=35689,Vu=35690,Hu=36289,ju=36292,Yu=36293,Kr=5125,Vi=36294,Hi=36295,ji=36296,Qu=36298,qu=36299,Xu=36300,Ku=36303,Ju=36306,Zu=36307,el=36308,tl=36311,er=3553,tr=34067,Jr=32879,rr=35866,w={};function Yi(r,e){return w[e].bindPoint}function rl(r,e){return function(t){r.uniform1f(e,t)}}function nl(r,e){return function(t){r.uniform1fv(e,t)}}function il(r,e){return function(t){r.uniform2fv(e,t)}}function ol(r,e){return function(t){r.uniform3fv(e,t)}}function sl(r,e){return function(t){r.uniform4fv(e,t)}}function Qi(r,e){return function(t){r.uniform1i(e,t)}}function qi(r,e){return function(t){r.uniform1iv(e,t)}}function Xi(r,e){return function(t){r.uniform2iv(e,t)}}function Ki(r,e){return function(t){r.uniform3iv(e,t)}}function Ji(r,e){return function(t){r.uniform4iv(e,t)}}function al(r,e){return function(t){r.uniform1ui(e,t)}}function cl(r,e){return function(t){r.uniform1uiv(e,t)}}function ul(r,e){return function(t){r.uniform2uiv(e,t)}}function ll(r,e){return function(t){r.uniform3uiv(e,t)}}function fl(r,e){return function(t){r.uniform4uiv(e,t)}}function dl(r,e){return function(t){r.uniformMatrix2fv(e,!1,t)}}function hl(r,e){return function(t){r.uniformMatrix3fv(e,!1,t)}}function ml(r,e){return function(t){r.uniformMatrix4fv(e,!1,t)}}function pl(r,e){return function(t){r.uniformMatrix2x3fv(e,!1,t)}}function gl(r,e){return function(t){r.uniformMatrix3x2fv(e,!1,t)}}function yl(r,e){return function(t){r.uniformMatrix2x4fv(e,!1,t)}}function bl(r,e){return function(t){r.uniformMatrix4x2fv(e,!1,t)}}function wl(r,e){return function(t){r.uniformMatrix3x4fv(e,!1,t)}}function xl(r,e){return function(t){r.uniformMatrix4x3fv(e,!1,t)}}function U(r,e,t,n){const i=Yi(r,e);return Ze(r)?function(o){let s,a;!o||Br(r,o)?(s=o,a=null):(s=o.texture,a=o.sampler),r.uniform1i(n,t),r.activeTexture(Kt+t),r.bindTexture(i,s),r.bindSampler(t,a)}:function(o){r.uniform1i(n,t),r.activeTexture(Kt+t),r.bindTexture(i,o)}}function L(r,e,t,n,i){const o=Yi(r,e),s=new Int32Array(i);for(let a=0;a<i;++a)s[a]=t+a;return Ze(r)?function(a){r.uniform1iv(n,s),a.forEach(function(c,u){r.activeTexture(Kt+s[u]);let f,m;!c||Br(r,c)?(f=c,m=null):(f=c.texture,m=c.sampler),r.bindSampler(t,m),r.bindTexture(o,f)})}:function(a){r.uniform1iv(n,s),a.forEach(function(c,u){r.activeTexture(Kt+s[u]),r.bindTexture(o,c)})}}w[Zt]={Type:Float32Array,size:4,setter:rl,arraySetter:nl},w[Fi]={Type:Float32Array,size:8,setter:il,cols:2},w[Oi]={Type:Float32Array,size:12,setter:ol,cols:3},w[Ci]={Type:Float32Array,size:16,setter:sl,cols:4},w[Xr]={Type:Int32Array,size:4,setter:Qi,arraySetter:qi},w[Mi]={Type:Int32Array,size:8,setter:Xi,cols:2},w[Bi]={Type:Int32Array,size:12,setter:Ki,cols:3},w[Di]={Type:Int32Array,size:16,setter:Ji,cols:4},w[Kr]={Type:Uint32Array,size:4,setter:al,arraySetter:cl},w[Vi]={Type:Uint32Array,size:8,setter:ul,cols:2},w[Hi]={Type:Uint32Array,size:12,setter:ll,cols:3},w[ji]={Type:Uint32Array,size:16,setter:fl,cols:4},w[Ui]={Type:Uint32Array,size:4,setter:Qi,arraySetter:qi},w[Li]={Type:Uint32Array,size:8,setter:Xi,cols:2},w[zi]={Type:Uint32Array,size:12,setter:Ki,cols:3},w[Ni]={Type:Uint32Array,size:16,setter:Ji,cols:4},w[$i]={Type:Float32Array,size:32,setter:dl,rows:2,cols:2},w[Wi]={Type:Float32Array,size:48,setter:hl,rows:3,cols:3},w[Gi]={Type:Float32Array,size:64,setter:ml,rows:4,cols:4},w[zu]={Type:Float32Array,size:32,setter:pl,rows:2,cols:3},w[Nu]={Type:Float32Array,size:32,setter:yl,rows:2,cols:4},w[$u]={Type:Float32Array,size:48,setter:gl,rows:3,cols:2},w[Wu]={Type:Float32Array,size:48,setter:wl,rows:3,cols:4},w[Gu]={Type:Float32Array,size:64,setter:bl,rows:4,cols:2},w[Vu]={Type:Float32Array,size:64,setter:xl,rows:4,cols:3},w[Bu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:er},w[Du]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:tr},w[Uu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:Jr},w[Lu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:er},w[Hu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:rr},w[ju]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:rr},w[Yu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:tr},w[Qu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:er},w[qu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:Jr},w[Xu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:tr},w[Ku]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:rr},w[Ju]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:er},w[Zu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:Jr},w[el]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:tr},w[tl]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:rr};function nr(r,e){return function(t){if(t.value)switch(r.disableVertexAttribArray(e),t.value.length){case 4:r.vertexAttrib4fv(e,t.value);break;case 3:r.vertexAttrib3fv(e,t.value);break;case 2:r.vertexAttrib2fv(e,t.value);break;case 1:r.vertexAttrib1fv(e,t.value);break;default:throw new Error("the length of a float constant value must be between 1 and 4!")}else r.bindBuffer(Jt,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribPointer(e,t.numComponents||t.size,t.type||Zt,t.normalize||!1,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function ue(r,e){return function(t){if(t.value)if(r.disableVertexAttribArray(e),t.value.length===4)r.vertexAttrib4iv(e,t.value);else throw new Error("The length of an integer constant value must be 4!");else r.bindBuffer(Jt,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribIPointer(e,t.numComponents||t.size,t.type||Xr,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function ir(r,e){return function(t){if(t.value)if(r.disableVertexAttribArray(e),t.value.length===4)r.vertexAttrib4uiv(e,t.value);else throw new Error("The length of an unsigned integer constant value must be 4!");else r.bindBuffer(Jt,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribIPointer(e,t.numComponents||t.size,t.type||Kr,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function Zr(r,e,t){const n=t.size,i=t.count;return function(o){r.bindBuffer(Jt,o.buffer);const s=o.size||o.numComponents||n,a=s/i,c=o.type||Zt,f=w[c].size*s,m=o.normalize||!1,p=o.offset||0,b=f/i;for(let d=0;d<i;++d)r.enableVertexAttribArray(e+d),r.vertexAttribPointer(e+d,a,c,m,f,p+b*d),r.vertexAttribDivisor&&r.vertexAttribDivisor(e+d,o.divisor||0)}}const S={};S[Zt]={size:4,setter:nr},S[Fi]={size:8,setter:nr},S[Oi]={size:12,setter:nr},S[Ci]={size:16,setter:nr},S[Xr]={size:4,setter:ue},S[Mi]={size:8,setter:ue},S[Bi]={size:12,setter:ue},S[Di]={size:16,setter:ue},S[Kr]={size:4,setter:ir},S[Vi]={size:8,setter:ir},S[Hi]={size:12,setter:ir},S[ji]={size:16,setter:ir},S[Ui]={size:4,setter:ue},S[Li]={size:8,setter:ue},S[zi]={size:12,setter:ue},S[Ni]={size:16,setter:ue},S[$i]={size:4,setter:Zr,count:2},S[Wi]={size:9,setter:Zr,count:3},S[Gi]={size:16,setter:Zr,count:4};const vl=/ERROR:\s*\d+:(\d+)/gi;function _l(r,e="",t=0){const n=[...e.matchAll(vl)],i=new Map(n.map((o,s)=>{const a=parseInt(o[1]),c=n[s+1],u=c?c.index:e.length,f=e.substring(o.index,u);return[a-1,f]}));return r.split(`
1
+ (function(k,We){typeof exports=="object"&&typeof module<"u"?We(exports):typeof define=="function"&&define.amd?define(["exports"],We):(k=typeof globalThis<"u"?globalThis:k||self,We(k["ml-transformers"]={}))})(this,(function(k){"use strict";async function We(){return new Promise(async(r,e)=>{!Fo()&&(await xn()||wn())?r():e("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media.")})}function wn(){return self.MediaStreamTrackProcessor!==void 0&&self.MediaStreamTrackGenerator!==void 0||Po()}function Po(){return[self.ReadableStream,self.WritableStream,self.MediaStream,self.OffscreenCanvas,self.VideoFrame,self.AudioContext,self.AudioWorkletNode].filter(r=>r===void 0).length===0}function Fo(){const r=navigator.userAgent.toLowerCase();return navigator.vendor&&navigator.vendor.toLowerCase().indexOf("apple")>-1&&!(r.indexOf("applewebkit")>-1&&r.indexOf("version")===-1)?parseInt((r.split(" ").find(e=>e.includes("version/"))??"/0").split("/")[1])<26:!1}function xn(){return new Promise(r=>{function e(){self.postMessage(typeof MediaStreamTrackProcessor<"u"&&typeof VideoTrackGenerator<"u")}const t=new Worker(`data:text/javascript,(${e.toString()})()`);t.onmessage=({data:n})=>r(n)})}const ee=new WeakMap,de=new WeakMap,Q=new WeakMap,lt=Symbol("anyProducer"),vn=Promise.resolve(),ft=Symbol("listenerAdded"),dt=Symbol("listenerRemoved");let ht=!1,pr=!1;const mt=r=>typeof r=="string"||typeof r=="symbol"||typeof r=="number";function Te(r){if(!mt(r))throw new TypeError("`eventName` must be a string, symbol, or number")}function pt(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Se(r,e){const t=de.get(r);if(t.has(e))return t.get(e)}function Ge(r,e){const t=mt(e)?e:lt,n=Q.get(r);if(n.has(t))return n.get(t)}function Co(r,e,t){const n=Q.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(lt)){const i=Promise.all([e,t]);for(const o of n.get(lt))o.enqueue(i)}}function _n(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const o={enqueue(s){i.push(s),n()},finish(){t=!0,n()}};for(const s of e){let a=Ge(r,s);a||(a=new Set,Q.get(r).set(s,a)),a.add(o)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(s=>{n=s}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(s){i=void 0;for(const a of e){const c=Ge(r,a);c&&(c.delete(o),c.size===0&&Q.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await s}:{done:!0}},[Symbol.asyncIterator](){return this}}}function En(r){if(r===void 0)return An;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!An.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const Ie=r=>r===ft||r===dt;function gt(r,e,t){if(Ie(e))try{ht=!0,r.emit(e,t)}finally{ht=!1}}class q{static mixin(e,t){return t=En(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const s of t)if(n.prototype[s]!==void 0)throw new Error(`The property \`${s}\` already exists on \`target\``);function i(){return Object.defineProperty(this,e,{enumerable:!1,value:new q}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const o=s=>function(...a){return this[e][s](...a)};for(const s of t)Object.defineProperty(n.prototype,s,{enumerable:!1,value:o(s)});return n}}static get isDebugEnabled(){if(typeof globalThis.process?.env!="object")return pr;const{env:e}=globalThis.process??{env:{}};return e.DEBUG==="emittery"||e.DEBUG==="*"||pr}static set isDebugEnabled(e){pr=e}constructor(e={}){ee.set(this,new Set),de.set(this,new Map),Q.set(this,new Map),Q.get(this).set(lt,new Set),this.debug=e.debug??{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(t,n,i,o)=>{try{o=JSON.stringify(o)}catch{o=`Object with the following keys failed to stringify: ${Object.keys(o).join(",")}`}(typeof i=="symbol"||typeof i=="number")&&(i=i.toString());const s=new Date,a=`${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}.${s.getMilliseconds()}`;console.log(`[${a}][emittery:${t}][${n}] Event Name: ${i}
2
+ data: ${o}`)})}logIfDebugEnabled(e,t,n){(q.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t,{signal:n}={}){pt(t),e=Array.isArray(e)?e:[e];for(const o of e){Te(o);let s=Se(this,o);s||(s=new Set,de.get(this).set(o,s)),s.add(t),this.logIfDebugEnabled("subscribe",o,void 0),Ie(o)||gt(this,ft,{eventName:o,listener:t})}const i=()=>{this.off(e,t),n?.removeEventListener("abort",i)};return n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i(),i}off(e,t){pt(t),e=Array.isArray(e)?e:[e];for(const n of e){Te(n);const i=Se(this,n);i&&(i.delete(t),i.size===0&&de.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),Ie(n)||gt(this,dt,{eventName:n,listener:t})}}once(e,t){if(t!==void 0&&typeof t!="function")throw new TypeError("predicate must be a function");let n;const i=new Promise(o=>{n=this.on(e,s=>{t&&!t(s)||(n(),o(s))})});return i.off=n,i}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Te(t);return _n(this,e)}async emit(e,t){if(Te(e),Ie(e)&&!ht)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),Co(this,e,t);const n=Se(this,e)??new Set,i=ee.get(this),o=[...n],s=Ie(e)?[]:[...i];await vn,await Promise.all([...o.map(async a=>{if(n.has(a))return a(t)}),...s.map(async a=>{if(i.has(a))return a(e,t)})])}async emitSerial(e,t){if(Te(e),Ie(e)&&!ht)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const n=Se(this,e)??new Set,i=ee.get(this),o=[...n],s=[...i];await vn;for(const a of o)n.has(a)&&await a(t);for(const a of s)i.has(a)&&await a(e,t)}onAny(e,{signal:t}={}){pt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),ee.get(this).add(e),gt(this,ft,{listener:e});const n=()=>{this.offAny(e),t?.removeEventListener("abort",n)};return t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n(),n}anyEvent(){return _n(this)}offAny(e){pt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),gt(this,dt,{listener:e}),ee.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),mt(t)){const n=Se(this,t);n&&n.clear();const i=Ge(this,t);if(i){for(const o of i)o.finish();i.clear()}}else{ee.get(this).clear();for(const[n,i]of de.get(this).entries())i.clear(),de.get(this).delete(n);for(const[n,i]of Q.get(this).entries()){for(const o of i)o.finish();i.clear(),Q.get(this).delete(n)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const n of e){if(mt(n)){t+=ee.get(this).size+(Se(this,n)?.size??0)+(Ge(this,n)?.size??0)+(Ge(this)?.size??0);continue}n!==void 0&&Te(n),t+=ee.get(this).size;for(const i of de.get(this).values())t+=i.size;for(const i of Q.get(this).values())t+=i.size}return t}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=En(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const An=Object.getOwnPropertyNames(q.prototype).filter(r=>r!=="constructor");Object.defineProperty(q,"listenerAdded",{value:ft,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(q,"listenerRemoved",{value:dt,writable:!1,enumerable:!0,configurable:!1});var Oo=Object.defineProperty,Mo=(r,e,t)=>e in r?Oo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Bo=(r,e,t)=>(Mo(r,e+"",t),t);const Do="hlg.tokbox.com/prod/logging/vcp_webrtc",Uo="https://",Lo=1e4;let yt;const zo=new Uint8Array(16);function No(){if(!yt&&(yt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!yt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return yt(zo)}const P=[];for(let r=0;r<256;++r)P.push((r+256).toString(16).slice(1));function $o(r,e=0){return(P[r[e+0]]+P[r[e+1]]+P[r[e+2]]+P[r[e+3]]+"-"+P[r[e+4]]+P[r[e+5]]+"-"+P[r[e+6]]+P[r[e+7]]+"-"+P[r[e+8]]+P[r[e+9]]+"-"+P[r[e+10]]+P[r[e+11]]+P[r[e+12]]+P[r[e+13]]+P[r[e+14]]+P[r[e+15]]).toLowerCase()}const Wo=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Tn={randomUUID:Wo};function Go(r,e,t){if(Tn.randomUUID&&!r)return Tn.randomUUID();r=r||{};const n=r.random||(r.rng||No)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,$o(n)}function gr(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const te=gr("globals",{});var he=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r))(he||{});function Sn(r){return[ImageBitmap,ReadableStream,WritableStream].some(e=>r instanceof e)}let Vo=0;function Ho(r,e,t,n,i){const o=Vo++;return r.postMessage({id:o,type:e,functionName:t,args:n},n.filter(s=>Sn(s))),new Promise(s=>{i?.set(o,s)})}function Ve(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(o=>Sn(o)))}const In=gr("workerized",{});function Rn(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function jo(){if(Rn())Ve({type:he.GLOBALS_SYNC},te);else{const r=[];for(const e in In){const{worker:t,resolvers:n}=In[e].workerContext;t&&r.push(Ho(t,he.GLOBALS_SYNC,"",[te],n))}await Promise.all(r)}}function bt(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],bt(r[t],e[t])):typeof r[t]=="object"?(e[t]={},bt(r[t],e[t])):e[t]=r[t]}async function Yo(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Ve(r,await e.instance[t](...n??[]))}const Qo=gr("registeredWorkers",{});function qo(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=Qo[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;bt(n,te),Ve(r,typeof e.instance!==void 0)}async function Xo(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Ve(r,n)}function Ko(r){if(!r.args)throw"Missing globals while syncing";bt(r.args[0],te),Ve(r,{})}function Jo(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case he.INIT:qo(t,r);break;case he.FORWARD:Yo(t,r);break;case he.TERMINATE:Xo(t,r);break;case he.GLOBALS_SYNC:Ko(t);break}}}Rn()&&Jo();function Zo(r,e){return te[r]||(te[r]=e),[()=>te[r],async t=>{te[r]=t,await jo()}]}function es(r,e){return Zo(r,e)}const[ts,rs]=es("metadata");function ns(r){rs(r)}function wt(){return ts()}let yr=class{constructor(e,t){Bo(this,"uuid"),this.config=e,this.uuid=t??Go()}async send(e){var t,n,i;const{appId:o,sourceType:s}=(t=wt())!=null?t:{};if(!o||!s)return"metadata missing";const a=new AbortController,c=setTimeout(()=>a.abort(),Lo);return await((i=(n=this.config)==null?void 0:n.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(c),"success"}getUrl(){var e;let t=(e=wt().proxyUrl)!=null?e:Uo;return t+=(t.at(-1)==="/"?"":"/")+Do,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=wt();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}};const xt="3.0.1",br=class{};br.updates={transformer_new:"New transformer",transformer_null:"Null transformer"},br.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"};let me=br;function is(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function os(r){if(is(r))return r;try{return new Error(JSON.stringify(r))}catch{return new Error(String(r))}}function wr(r){return os(r).message}class ss{constructor(e,t){this.config=e,this.frameTransformedCount=0,this.frameFromSourceCount=0,this.startAt=0,this.reporter=new yr(e,t)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:t}=this,n=(Date.now()-e)/1e3;return t/n}async onFrameTransformed(e={},t=!1){this.startAt===0&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:n,frameTransformedCount:i,frameFromSourceCount:o}=this,s=Date.now(),a=(s-n)/1e3,c=i/a,u=o/a;return t||this.frameTransformedCount>=this.config.loggingIntervalFrameCount?(this.frameFromSourceCount=0,this.frameTransformedCount=0,this.startAt=s,this.reporter.config=this.config,this.reporter.send({...this.config.report,variation:"QoS",fps:u,transformedFps:c,framesTransformed:i,...e})):"success"}}var kn=(r=>(r.FPS_DROP="fps_drop",r))(kn||{}),Pn=(r=>(r.start="start",r.transform="transform",r.flush="flush",r))(Pn||{}),vt=(r=>(r.pipeline_ended="pipeline_ended",r.pipeline_ended_with_error="pipeline_ended_with_error",r.pipeline_started="pipeline_started",r.pipeline_started_with_error="pipeline_started_with_error",r.pipeline_restarted="pipeline_restarted",r.pipeline_restarted_with_error="pipeline_restarted_with_error",r))(vt||{});const as=500,cs=.8;class us extends q{constructor(e,t){super(),this.reporter_=new yr,this.reporterQos_=new ss({loggingIntervalFrameCount:as,report:{version:xt}}),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_&&typeof this.transformer_.start=="function")try{await this.transformer_.start(e)}catch(t){this.report({message:me.errors.transformer_start,variation:"Error",error:wr(t)});const n={eventMetaData:{transformerIndex:this.index_},error:t,function:"start"};this.emit("error",n)}}async transform(e,t){if(this.mediaTransformerQosReportStartTimestamp_===0&&(this.mediaTransformerQosReportStartTimestamp_=Date.now()),e instanceof VideoFrame&&(this.videoHeight_=e?.displayHeight??0,this.videoWidth_=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 this.transformer_.transform?.(e,t),this.reportQos()}catch(n){this.report({message:me.errors.transformer_transform,variation:"Error",error:wr(n)});const i={eventMetaData:{transformerIndex:this.index_},error:n,function:"transform"};this.emit("error",i)}if(this.trackExpectedRate_!=-1&&this.trackExpectedRate_*cs>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(t){this.report({message:me.errors.transformer_flush,variation:"Error",error:wr(t)});const n={eventMetaData:{transformerIndex:this.index_},error:t,function:"flush"};this.emit("error",n)}}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:xt,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:xt,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class ls extends q{constructor(e){super(),this.transformers_=[],this.trackExpectedRate_=-1;for(let t=0;t<e.length;t++){let n=new us(e[t],t);n.on("error",i=>{this.emit("error",i)}),n.on("warn",i=>{this.emit("warn",i)}),this.transformers_.push(n)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let t of this.transformers_)t.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,t){if(!this.transformers_||this.transformers_.length===0){console.log("[Pipeline] No transformers.");return}try{let n=e;for(let i of this.transformers_)e=e.pipeThrough(new TransformStream(i));e.pipeTo(t).then(async()=>{console.log("[Pipeline] Setup."),await t.abort(),await n.cancel(),this.emit("pipelineInfo","pipeline_ended")}).catch(async i=>{e.cancel().then(()=>{console.log("[Pipeline] Shutting down streams after abort.")}).catch(o=>{console.error("[Pipeline] Error from stream transform:",o)}),await t.abort(i),await n.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 Fn extends q{constructor(){super(),this.reporter_=new yr,this.trackExpectedRate_=-1,this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e,this.pipeline_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_)}async transform(e,t){if(this.isTrack(e)){if(e.kind==="video"){const n=new MediaStreamTrackProcessor({track:e}),i=new VideoTrackGenerator;return this.readable_=n.readable,this.writable_=i.writable,await this.transformInternal(),i.track}throw Error("Cannot process audio tracks inside a web worker when passing a track to transform")}else return this.readable_=e,this.writable_=t,this.transformInternal()}transformInternal(){return new Promise(async(e,t)=>{if(!this.transformers_||this.transformers_.length===0){this.report({message:me.errors.transformer_none,variation:"Error"}),t("[MediaProcessor] Need to set transformers.");return}if(!this.readable_){this.report({variation:"Error",message:me.errors.readable_null}),t("[MediaProcessor] Readable is null.");return}if(!this.writable_){this.report({variation:"Error",message:me.errors.writable_null}),t("[MediaProcessor] Writable is null.");return}let n=!1;this.pipeline_&&(n=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new ls(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=>{n&&(i==="pipeline_started"?i=vt.pipeline_restarted:i==="pipeline_started_with_error"&&(i=vt.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=>{t(i)})})}setTransformers(e){return this.report({variation:"Update",message:me.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:xt,action:"MediaProcessor",...e})}isTrack(e){return"kind"in e}}class fs{constructor({kind:e}){if(e=="video"){const t=document.createElement("canvas"),n=t.getContext("2d",{desynchronized:!0}),i=t.captureStream().getVideoTracks()[0];return i.writable=new WritableStream({write(o){t.width=o.displayWidth,t.height=o.displayHeight,n.drawImage(o,0,0,t.width,t.height),o.close()}}),i}else if(e=="audio"){const t=new AudioContext,n=t.createMediaStreamDestination(),[i]=n.stream.getAudioTracks();return i.writable=new WritableStream({async start(o){this.arrays=[];function s(){registerProcessor("mstg-shim",class extends AudioWorkletProcessor{constructor(){super(),this.arrays=[],this.arrayOffset=0,this.port.onmessage=({data:a})=>this.arrays.push(a),this.emptyArray=new Float32Array(0)}process(a,[[c]]){for(let u=0;u<c.length;u++)(!this.array||this.arrayOffset>=this.array.length)&&(this.array=this.arrays.shift()||this.emptyArray,this.arrayOffset=0),c[u]=this.array[this.arrayOffset++]||0;return!0}})}return await t.audioWorklet.addModule(`data:text/javascript,(${s.toString()})()`),this.node=new AudioWorkletNode(t,"mstg-shim"),this.node.connect(n),i},write(o){const s=new Float32Array(o.numberOfFrames*o.numberOfChannels);o.copyTo(s,{planeIndex:0}),this.node.port.postMessage(s,[s.buffer]),o.close()}}),i}}}function ds(){return self.MediaStreamTrackGenerator?self.MediaStreamTrackGenerator:fs}class hs{constructor(e){const t=e.track??e;t.kind=="video"?this.readable=new ReadableStream({async start(n){t.addEventListener("ended",()=>n.close(),{once:!0}),this.video=document.createElement("video"),this.video.srcObject=new MediaStream([t]),await Promise.all([this.video.play(),new Promise(i=>this.video.onloadedmetadata=i)]),this.track=t,this.canvas=new OffscreenCanvas(this.video.videoWidth,this.video.videoHeight),this.ctx=this.canvas.getContext("2d",{desynchronized:!0}),this.t1=performance.now()},async pull(n){if(t.readyState=="ended")return n.close();const i=t.getSettings().frameRate||30;for(;performance.now()-this.t1<1e3/i;)if(await new Promise(o=>requestAnimationFrame(o)),t.readyState=="ended")return n.close();this.canvas.width=this.video.videoWidth,this.canvas.height=this.video.videoHeight,this.t1=performance.now(),this.ctx.drawImage(this.video,0,0),n.enqueue(new VideoFrame(this.canvas,{timestamp:this.t1}))}}):t.kind=="audio"&&(this.readable=new ReadableStream({async start(n){t.addEventListener("ended",()=>n.close(),{once:!0}),this.ac=new AudioContext,this.arrays=[];function i(){registerProcessor("mstp-shim",class extends AudioWorkletProcessor{process(o){return this.port.postMessage(o),!0}})}await this.ac.audioWorklet.addModule(`data:text/javascript,(${i.toString()})()`),this.node=new AudioWorkletNode(this.ac,"mstp-shim"),this.ac.createMediaStreamSource(new MediaStream([t])).connect(this.node),this.node.port.addEventListener("message",({data:o})=>o[0][0]&&this.arrays.push(o))},async pull(n){if(t.readyState=="ended")return n.close();for(;!this.arrays.length;)if(await new Promise(s=>this.node.port.onmessage=s),t.readyState=="ended")return n.close();const[i]=this.arrays.shift(),o=new Float32Array(i.reduce((s,a)=>s+a.length,0));i.reduce((s,a)=>(o.set(a,s),s+a.length),0),n.enqueue(new AudioData({format:"f32-planar",sampleRate:this.ac.sampleRate,numberOfFrames:i[0].length,numberOfChannels:i.length,timestamp:this.ac.currentTime*1e6|0,data:o,transfer:[o.buffer]}))}}))}}function ms(){return self.MediaStreamTrackProcessor?self.MediaStreamTrackProcessor:hs}class ps{constructor(){this.processor_=null,this.generator_=null}init(e){return new Promise((t,n)=>{try{const i=ms();this.processor_=new i(e)}catch(i){console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${i}`),n(i)}try{const i=ds();e.kind==="audio"?this.generator_=new i({kind:"audio"}):e.kind==="video"?this.generator_=new i({kind:"video"}):n("kind not supported")}catch(i){console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${i}`),n(i)}t()})}getReadable(){return this.processor_.readable}getWriteable(){return this.generator_.writable}getProccesorTrack(){return this.generator_}}class gs{constructor(e){this.mediaProcessor_=e}async setTrack(e){if(!(this.mediaProcessor_ instanceof Fn)&&await xn()){if(e.kind==="audio")throw Error("Cannot process audio tracks inside a web worker when passing a track to transform");return await this.mediaProcessor_.transform(e)}if(wn()){const t=new ps;return await t.init(e),await this.mediaProcessor_.transform(t.getReadable(),t.getWriteable()),t.getProccesorTrack()}throw Error("MediaStreamTrack API for Insertable Streams of Media is not supported")}destroy(){return new Promise((e,t)=>{this.mediaProcessor_?this.mediaProcessor_.destroy().then(()=>{e()}).catch(n=>{t(n)}):t("no processor")})}}var He=(r=>(r.Low="Low",r.High="High",r))(He||{}),Cn=(r=>(r.BackgroundBlur="BackgroundBlur",r.VirtualBackground="VirtualBackground",r.VideoBackground="VideoBackground",r.SilhouetteBlur="SilhouetteBlur",r))(Cn||{}),_t=(r=>(r.FAST="FAST",r.PRECISE="PRECISE",r))(_t||{}),je=(r=>(r.CANVAS="CANVAS",r.WEBGL="WEBGL",r))(je||{});const ys=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]));async function bs(){const{wasm:r,insertableStreams:e,simd:t,webgl:n}=await On();if(!r.supported)throw r.message;if(!e.supported)throw e.message;if(!t.supported)throw t.message;if(!n.supported)throw n.message}async function On(){const r={wasm:{supported:typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function",message:"Your browser does not support WebAssembly features."},simd:{supported:await ys(),message:"Your browser does not support simd features."},insertableStreams:{supported:!0},gpu:{message:"Your browser does not support gpu features.",supported:!0},webgl:ws(),performance:Mn()};try{await We()}catch(e){r.insertableStreams.supported=!1,r.insertableStreams.message=e}return r}function ws(){if(!OffscreenCanvas)return{supported:!1,message:"Your browser does not support offscreen canvas"};const e=new OffscreenCanvas(0,0).getContext("webgl2");if(e){const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}else return{supported:!1,message:"Your browser does not support webgl 2"};return{supported:!0}}function Mn(){const e=new OffscreenCanvas(0,0).getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(e){const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}else return{supported:!1,message:"Your hardware does not perform good enough to run the library efficiently"};return{supported:!0}}const re=new WeakMap,pe=new WeakMap,X=new WeakMap,Et=Symbol("anyProducer"),Bn=Promise.resolve(),At=Symbol("listenerAdded"),Tt=Symbol("listenerRemoved");let St=!1,xr=!1;const It=r=>typeof r=="string"||typeof r=="symbol"||typeof r=="number";function Re(r){if(!It(r))throw new TypeError("`eventName` must be a string, symbol, or number")}function Rt(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function ke(r,e){const t=pe.get(r);if(t.has(e))return t.get(e)}function Ye(r,e){const t=It(e)?e:Et,n=X.get(r);if(n.has(t))return n.get(t)}function xs(r,e,t){const n=X.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(Et)){const i=Promise.all([e,t]);for(const o of n.get(Et))o.enqueue(i)}}function Dn(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const o={enqueue(s){i.push(s),n()},finish(){t=!0,n()}};for(const s of e){let a=Ye(r,s);a||(a=new Set,X.get(r).set(s,a)),a.add(o)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(s=>{n=s}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(s){i=void 0;for(const a of e){const c=Ye(r,a);c&&(c.delete(o),c.size===0&&X.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await s}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Un(r){if(r===void 0)return Ln;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!Ln.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const Pe=r=>r===At||r===Tt;function kt(r,e,t){if(Pe(e))try{St=!0,r.emit(e,t)}finally{St=!1}}let Qe=class bn{static mixin(e,t){return t=Un(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const s of t)if(n.prototype[s]!==void 0)throw new Error(`The property \`${s}\` already exists on \`target\``);function i(){return Object.defineProperty(this,e,{enumerable:!1,value:new bn}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const o=s=>function(...a){return this[e][s](...a)};for(const s of t)Object.defineProperty(n.prototype,s,{enumerable:!1,value:o(s)});return n}}static get isDebugEnabled(){if(typeof globalThis.process?.env!="object")return xr;const{env:e}=globalThis.process??{env:{}};return e.DEBUG==="emittery"||e.DEBUG==="*"||xr}static set isDebugEnabled(e){xr=e}constructor(e={}){re.set(this,new Set),pe.set(this,new Map),X.set(this,new Map),X.get(this).set(Et,new Set),this.debug=e.debug??{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(t,n,i,o)=>{try{o=JSON.stringify(o)}catch{o=`Object with the following keys failed to stringify: ${Object.keys(o).join(",")}`}(typeof i=="symbol"||typeof i=="number")&&(i=i.toString());const s=new Date,a=`${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}.${s.getMilliseconds()}`;console.log(`[${a}][emittery:${t}][${n}] Event Name: ${i}
3
+ data: ${o}`)})}logIfDebugEnabled(e,t,n){(bn.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t,{signal:n}={}){Rt(t),e=Array.isArray(e)?e:[e];for(const o of e){Re(o);let s=ke(this,o);s||(s=new Set,pe.get(this).set(o,s)),s.add(t),this.logIfDebugEnabled("subscribe",o,void 0),Pe(o)||kt(this,At,{eventName:o,listener:t})}const i=()=>{this.off(e,t),n?.removeEventListener("abort",i)};return n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i(),i}off(e,t){Rt(t),e=Array.isArray(e)?e:[e];for(const n of e){Re(n);const i=ke(this,n);i&&(i.delete(t),i.size===0&&pe.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),Pe(n)||kt(this,Tt,{eventName:n,listener:t})}}once(e,t){if(t!==void 0&&typeof t!="function")throw new TypeError("predicate must be a function");let n;const i=new Promise(o=>{n=this.on(e,s=>{t&&!t(s)||(n(),o(s))})});return i.off=n,i}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Re(t);return Dn(this,e)}async emit(e,t){if(Re(e),Pe(e)&&!St)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),xs(this,e,t);const n=ke(this,e)??new Set,i=re.get(this),o=[...n],s=Pe(e)?[]:[...i];await Bn,await Promise.all([...o.map(async a=>{if(n.has(a))return a(t)}),...s.map(async a=>{if(i.has(a))return a(e,t)})])}async emitSerial(e,t){if(Re(e),Pe(e)&&!St)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const n=ke(this,e)??new Set,i=re.get(this),o=[...n],s=[...i];await Bn;for(const a of o)n.has(a)&&await a(t);for(const a of s)i.has(a)&&await a(e,t)}onAny(e,{signal:t}={}){Rt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),re.get(this).add(e),kt(this,At,{listener:e});const n=()=>{this.offAny(e),t?.removeEventListener("abort",n)};return t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n(),n}anyEvent(){return Dn(this)}offAny(e){Rt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),kt(this,Tt,{listener:e}),re.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),It(t)){const n=ke(this,t);n&&n.clear();const i=Ye(this,t);if(i){for(const o of i)o.finish();i.clear()}}else{re.get(this).clear();for(const[n,i]of pe.get(this).entries())i.clear(),pe.get(this).delete(n);for(const[n,i]of X.get(this).entries()){for(const o of i)o.finish();i.clear(),X.get(this).delete(n)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const n of e){if(It(n)){t+=re.get(this).size+(ke(this,n)?.size??0)+(Ye(this,n)?.size??0)+(Ye(this)?.size??0);continue}n!==void 0&&Re(n),t+=re.get(this).size;for(const i of pe.get(this).values())t+=i.size;for(const i of X.get(this).values())t+=i.size}return t}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=Un(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}};const Ln=Object.getOwnPropertyNames(Qe.prototype).filter(r=>r!=="constructor");Object.defineProperty(Qe,"listenerAdded",{value:At,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Qe,"listenerRemoved",{value:Tt,writable:!1,enumerable:!0,configurable:!1});function vr(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const Fe=vr("globals",{});var z=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r.EVENT="EVENT",r))(z||{});function zn(r){return[ImageBitmap,ReadableStream,WritableStream].some(t=>r instanceof t)}let vs=0;function Pt(r,e,t,n,i){const o=vs++;return r.postMessage({id:o,type:e,functionName:t,args:n},n.filter(a=>zn(a))),new Promise(a=>{i?.set(o,a)})}function Ce(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(o=>zn(o)))}const Ft=vr("workerized",{});function _r(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function _s(){if(_r())Ce({type:z.GLOBALS_SYNC},Fe);else{const r=[];for(const e in Ft){const{worker:t,resolvers:n}=Ft[e].workerContext;t&&r.push(Pt(t,z.GLOBALS_SYNC,"",[Fe],n))}await Promise.all(r)}}function qe(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],qe(r[t],e[t])):typeof r[t]=="object"?(e[t]={},qe(r[t],e[t])):e[t]=r[t]}async function Es(r,e,t,n){const i=new e;if(i.addEventListener("message",async({data:s})=>{var a,c,u,f,m,p,b;switch(s.type){case z.GLOBALS_SYNC:s.id?((c=t.get((a=s.id)!=null?a:-1))==null||c(s.result),t.delete((u=s.id)!=null?u:-1)):(qe((f=s.result)!=null?f:{},Fe),await _s());break;case z.EVENT:const{result:d}=s,g=d;if(g?.name==null)throw"Missing event name";n(g.name,g.data);break;default:(p=t.get((m=s.id)!=null?m:-1))==null||p(s.result),t.delete((b=s.id)!=null?b:-1)}}),!await Pt(i,z.INIT,"",[r.workerId,Fe],t))throw"Failed to instantiate workerized class";return i}const ne=new WeakMap,ge=new WeakMap,K=new WeakMap,Ct=Symbol("anyProducer"),Nn=Promise.resolve(),Ot=Symbol("listenerAdded"),Mt=Symbol("listenerRemoved");let Bt=!1,Er=!1;function Oe(r){if(typeof r!="string"&&typeof r!="symbol"&&typeof r!="number")throw new TypeError("`eventName` must be a string, symbol, or number")}function Dt(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Me(r,e){const t=ge.get(r);if(t.has(e))return t.get(e)}function Xe(r,e){const t=typeof e=="string"||typeof e=="symbol"||typeof e=="number"?e:Ct,n=K.get(r);if(n.has(t))return n.get(t)}function As(r,e,t){const n=K.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(Ct)){const i=Promise.all([e,t]);for(const o of n.get(Ct))o.enqueue(i)}}function $n(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const o={enqueue(s){i.push(s),n()},finish(){t=!0,n()}};for(const s of e){let a=Xe(r,s);a||(a=new Set,K.get(r).set(s,a)),a.add(o)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(s=>{n=s}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(s){i=void 0;for(const a of e){const c=Xe(r,a);c&&(c.delete(o),c.size===0&&K.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await s}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Wn(r){if(r===void 0)return Gn;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!Gn.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const Be=r=>r===Ot||r===Mt;function Ut(r,e,t){if(Be(e))try{Bt=!0,r.emit(e,t)}finally{Bt=!1}}class ye{static mixin(e,t){return t=Wn(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const s of t)if(n.prototype[s]!==void 0)throw new Error(`The property \`${s}\` already exists on \`target\``);function i(){return Object.defineProperty(this,e,{enumerable:!1,value:new ye}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const o=s=>function(...a){return this[e][s](...a)};for(const s of t)Object.defineProperty(n.prototype,s,{enumerable:!1,value:o(s)});return n}}static get isDebugEnabled(){var e,t;if(typeof((e=globalThis.process)==null?void 0:e.env)!="object")return Er;const{env:n}=(t=globalThis.process)!=null?t:{env:{}};return n.DEBUG==="emittery"||n.DEBUG==="*"||Er}static set isDebugEnabled(e){Er=e}constructor(e={}){var t;ne.set(this,new Set),ge.set(this,new Map),K.set(this,new Map),K.get(this).set(Ct,new Set),this.debug=(t=e.debug)!=null?t:{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(n,i,o,s)=>{try{s=JSON.stringify(s)}catch{s=`Object with the following keys failed to stringify: ${Object.keys(s).join(",")}`}(typeof o=="symbol"||typeof o=="number")&&(o=o.toString());const a=new Date,c=`${a.getHours()}:${a.getMinutes()}:${a.getSeconds()}.${a.getMilliseconds()}`;console.log(`[${c}][emittery:${n}][${i}] Event Name: ${o}
4
+ data: ${s}`)})}logIfDebugEnabled(e,t,n){(ye.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t){Dt(t),e=Array.isArray(e)?e:[e];for(const n of e){Oe(n);let i=Me(this,n);i||(i=new Set,ge.get(this).set(n,i)),i.add(t),this.logIfDebugEnabled("subscribe",n,void 0),Be(n)||Ut(this,Ot,{eventName:n,listener:t})}return this.off.bind(this,e,t)}off(e,t){Dt(t),e=Array.isArray(e)?e:[e];for(const n of e){Oe(n);const i=Me(this,n);i&&(i.delete(t),i.size===0&&ge.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),Be(n)||Ut(this,Mt,{eventName:n,listener:t})}}once(e){let t;const n=new Promise(i=>{t=this.on(e,o=>{t(),i(o)})});return n.off=t,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Oe(t);return $n(this,e)}async emit(e,t){var n;if(Oe(e),Be(e)&&!Bt)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),As(this,e,t);const i=(n=Me(this,e))!=null?n:new Set,o=ne.get(this),s=[...i],a=Be(e)?[]:[...o];await Nn,await Promise.all([...s.map(async c=>{if(i.has(c))return c(t)}),...a.map(async c=>{if(o.has(c))return c(e,t)})])}async emitSerial(e,t){var n;if(Oe(e),Be(e)&&!Bt)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const i=(n=Me(this,e))!=null?n:new Set,o=ne.get(this),s=[...i],a=[...o];await Nn;for(const c of s)i.has(c)&&await c(t);for(const c of a)o.has(c)&&await c(e,t)}onAny(e){return Dt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),ne.get(this).add(e),Ut(this,Ot,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return $n(this)}offAny(e){Dt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),Ut(this,Mt,{listener:e}),ne.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),typeof t=="string"||typeof t=="symbol"||typeof t=="number"){const n=Me(this,t);n&&n.clear();const i=Xe(this,t);if(i){for(const o of i)o.finish();i.clear()}}else{ne.get(this).clear();for(const[n,i]of ge.get(this).entries())i.clear(),ge.get(this).delete(n);for(const[n,i]of K.get(this).entries()){for(const o of i)o.finish();i.clear(),K.get(this).delete(n)}}}listenerCount(e){var t,n,i,o,s,a;e=Array.isArray(e)?e:[e];let c=0;for(const u of e){if(typeof u=="string"){c+=ne.get(this).size+((n=(t=Me(this,u))==null?void 0:t.size)!=null?n:0)+((o=(i=Xe(this,u))==null?void 0:i.size)!=null?o:0)+((a=(s=Xe(this))==null?void 0:s.size)!=null?a:0);continue}typeof u<"u"&&Oe(u),c+=ne.get(this).size;for(const f of ge.get(this).values())c+=f.size;for(const f of K.get(this).values())c+=f.size}return c}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=Wn(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const Gn=Object.getOwnPropertyNames(ye.prototype).filter(r=>r!=="constructor");Object.defineProperty(ye,"listenerAdded",{value:Ot,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(ye,"listenerRemoved",{value:Mt,writable:!1,enumerable:!0,configurable:!1});function Ts(r){return r.onAny&&r.emit}function Ss(r){return r.prototype.onAny&&r.prototype.emit}let Is=0;async function Rs(r,e,t){const i=Ss(r)?new ye:{},o=Is++;return Object.getOwnPropertyNames(r.prototype).forEach(s=>{i[s]=(...a)=>Pt(e,z.FORWARD,s,a,t)}),i.terminate=async(...s)=>{const a=await Pt(e,z.TERMINATE,"",s,t);return delete Ft[o],e.terminate(),i.workerContext.worker=void 0,a},i.workerContext={id:o,worker:e,resolvers:t},Ft[o]=i,i}async function ks(r,e){const t=new Map;let n;const i=await Es(r,e,t,(o,s)=>{n?.emit&&n?.emit(o,s)});return n=await Rs(r,i,t),n}async function Ps(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Ce(r,await e.instance[t](...n??[]))}const Vn=vr("registeredWorkers",{});function Fs(r,e){e.workerId=r,_r()&&(Vn[e.workerId]=e)}function Cs(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=Vn[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;qe(n,Fe),Ts(e.instance)&&e.instance.onAny((o,s)=>{Ce({type:z.EVENT},{name:o,data:s})}),Ce(r,typeof e.instance!==void 0)}async function Os(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Ce(r,n)}function Ms(r){if(!r.args)throw"Missing globals while syncing";qe(r.args[0],Fe),Ce(r,{})}function Bs(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case z.INIT:Cs(t,r);break;case z.FORWARD:Ps(t,r);break;case z.TERMINATE:Os(t,r);break;case z.GLOBALS_SYNC:Ms(t);break}}}_r()&&Bs();class Hn{static async createVideoReadable(e){return new Promise((t,n)=>{const i=document.createElement("video");let o=new AbortController,s=new AbortController;i.addEventListener("canplay",()=>{o.abort(),i.muted=!0,i.loop=!0,i.play().then(()=>{try{const a=i.captureStream(),c=new MediaStreamTrackProcessor(a.getVideoTracks()[0]);t(c.readable)}catch(a){n(a)}})},{once:!0,signal:s.signal}),i.addEventListener("error",a=>{s.abort(),n("loading error:"+a)},{once:!0,signal:o.signal}),i.crossOrigin="anonymous",i.src=e})}static async createImageCanvas(e){const n=await(await fetch(e)).blob();return await createImageBitmap(n)}}var Ds=Object.defineProperty,Us=(r,e,t)=>e in r?Ds(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ls=(r,e,t)=>(Us(r,e+"",t),t);const zs="hlg.tokbox.com/prod/logging/vcp_webrtc",Ns="https://",$s=1e4;let Lt;const Ws=new Uint8Array(16);function Gs(){if(!Lt&&(Lt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Lt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lt(Ws)}const F=[];for(let r=0;r<256;++r)F.push((r+256).toString(16).slice(1));function Vs(r,e=0){return(F[r[e+0]]+F[r[e+1]]+F[r[e+2]]+F[r[e+3]]+"-"+F[r[e+4]]+F[r[e+5]]+"-"+F[r[e+6]]+F[r[e+7]]+"-"+F[r[e+8]]+F[r[e+9]]+"-"+F[r[e+10]]+F[r[e+11]]+F[r[e+12]]+F[r[e+13]]+F[r[e+14]]+F[r[e+15]]).toLowerCase()}const Hs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),jn={randomUUID:Hs};function js(r,e,t){if(jn.randomUUID&&!e&&!r)return jn.randomUUID();r=r||{};const n=r.random||(r.rng||Gs)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Vs(n)}function Ar(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const ie=Ar("globals",{});var be=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r))(be||{});function Yn(r){return[ImageBitmap,ReadableStream,WritableStream].some(e=>r instanceof e)}let Ys=0;function Qs(r,e,t,n,i){const o=Ys++;return r.postMessage({id:o,type:e,functionName:t,args:n},n.filter(s=>Yn(s))),new Promise(s=>{i?.set(o,s)})}function Ke(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(o=>Yn(o)))}const Qn=Ar("workerized",{});function qn(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function qs(){if(qn())Ke({type:be.GLOBALS_SYNC},ie);else{const r=[];for(const e in Qn){const{worker:t,resolvers:n}=Qn[e].workerContext;t&&r.push(Qs(t,be.GLOBALS_SYNC,"",[ie],n))}await Promise.all(r)}}function zt(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],zt(r[t],e[t])):typeof r[t]=="object"?(e[t]={},zt(r[t],e[t])):e[t]=r[t]}async function Xs(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Ke(r,await e.instance[t](...n??[]))}const Ks=Ar("registeredWorkers",{});function Js(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=Ks[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;zt(n,ie),Ke(r,typeof e.instance!==void 0)}async function Zs(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Ke(r,n)}function ea(r){if(!r.args)throw"Missing globals while syncing";zt(r.args[0],ie),Ke(r,{})}function ta(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case be.INIT:Js(t,r);break;case be.FORWARD:Xs(t,r);break;case be.TERMINATE:Zs(t,r);break;case be.GLOBALS_SYNC:ea(t);break}}}qn()&&ta();function ra(r,e){return ie[r]||(ie[r]=e),[()=>ie[r],async t=>{ie[r]=t,await qs()}]}function na(r,e){return ra(r,e)}const[ia]=na("metadata");function Tr(){return ia()}class oa{constructor(e){Ls(this,"uuid",js()),this.config=e}async send(e){var t,n,i;const{appId:o,sourceType:s}=(t=Tr())!=null?t:{};if(!o||!s)return"metadata missing";const a=new AbortController,c=setTimeout(()=>a.abort(),$s);return await((i=(n=this.config)==null?void 0:n.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(c),"success"}getUrl(){var e;let t=(e=Tr().proxyUrl)!=null?e:Ns;return t+=(t.at(-1)==="/"?"":"/")+zs,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=Tr();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}}const sa="7.0.0";class Sr{constructor(){const e=new OffscreenCanvas(0,0),t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw"Fail to retrieve 2d context";this.canvas=e,this.context=t}enablePostProcessing(){}disablePostProcessing(){}async profileWebgl(e){return[]}async render(e,t){return this.canvas}resizeCanvas(e){const{width:t,height:n}=e;this.canvas.width=t,this.canvas.height=n}renderSilhouette(e,t,n="none"){const{width:i,height:o}=e;this.context.save(),this.context.drawImage(t,0,0,t.width,t.height,0,0,i,o),this.context.filter="blur(5px)",this.context.globalCompositeOperation="source-in",this.context.drawImage(t,0,0,t.width,t.height,0,0,i,o),this.context.globalCompositeOperation="source-in",this.context.filter=n,this.context.drawImage(e,0,0,i,o,0,0,this.canvas.width,this.canvas.height),this.context.restore()}destroy(){}}class aa extends Sr{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n),this.context.save(),this.context.filter=`blur(${this.radius}px)`,this.context.globalCompositeOperation="destination-over",this.context.drawImage(e,0,0,e.width,e.height),this.context.restore(),super.render(e,t)}}class ca extends Sr{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n,`blur(${this.radius}px)`),this.context.save(),this.context.filter="none",this.context.globalCompositeOperation="destination-over",this.context.drawImage(e,0,0,e.width,e.height),this.context.restore(),super.render(e,t)}}class ua extends Sr{setBackgroundImage(e){this.backgroundImage=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n),this.backgroundImage&&(this.context.save(),this.context.filter="none",this.context.globalCompositeOperation="destination-over",this.context.drawImage(this.backgroundImage,0,0,this.backgroundImage.width,this.backgroundImage.height,0,0,e.width,e.height),this.context.restore()),super.render(e,t)}}const Ir=5120,Je=5121,Rr=5122,kr=5123,Pr=5124,Fr=5125,Cr=5126,la=32819,fa=32820,da=33635,ha=5131,ma=33640,pa=35899,ga=35902,ya=36269,ba=34042,Xn={};{const r=Xn;r[Ir]=Int8Array,r[Je]=Uint8Array,r[Rr]=Int16Array,r[kr]=Uint16Array,r[Pr]=Int32Array,r[Fr]=Uint32Array,r[Cr]=Float32Array,r[la]=Uint16Array,r[fa]=Uint16Array,r[da]=Uint16Array,r[ha]=Uint16Array,r[ma]=Uint32Array,r[pa]=Uint32Array,r[ga]=Uint32Array,r[ya]=Uint32Array,r[ba]=Uint32Array}function Or(r){if(r instanceof Int8Array)return Ir;if(r instanceof Uint8Array||r instanceof Uint8ClampedArray)return Je;if(r instanceof Int16Array)return Rr;if(r instanceof Uint16Array)return kr;if(r instanceof Int32Array)return Pr;if(r instanceof Uint32Array)return Fr;if(r instanceof Float32Array)return Cr;throw new Error("unsupported typed array type")}function Kn(r){if(r===Int8Array)return Ir;if(r===Uint8Array||r===Uint8ClampedArray)return Je;if(r===Int16Array)return Rr;if(r===Uint16Array)return kr;if(r===Int32Array)return Pr;if(r===Uint32Array)return Fr;if(r===Float32Array)return Cr;throw new Error("unsupported typed array type")}function Jn(r){const e=Xn[r];if(!e)throw new Error("unknown gl type");return e}const Nt=typeof SharedArrayBuffer<"u"?function(e){return e&&e.buffer&&(e.buffer instanceof ArrayBuffer||e.buffer instanceof SharedArrayBuffer)}:function(e){return e&&e.buffer&&e.buffer instanceof ArrayBuffer};function Zn(...r){console.error(...r)}const ei=new Map;function $t(r,e){if(!r||typeof r!="object")return!1;let t=ei.get(e);t||(t=new WeakMap,ei.set(e,t));let n=t.get(r);if(n===void 0){const i=Object.prototype.toString.call(r);n=i.substring(8,i.length-1)===e,t.set(r,n)}return n}function wa(r,e){return typeof WebGLBuffer<"u"&&$t(e,"WebGLBuffer")}function xa(r,e){return typeof WebGLRenderbuffer<"u"&&$t(e,"WebGLRenderbuffer")}function Mr(r,e){return typeof WebGLTexture<"u"&&$t(e,"WebGLTexture")}function va(r,e){return typeof WebGLSampler<"u"&&$t(e,"WebGLSampler")}const ti=35044,we=34962,_a=34963,Ea=34660,Aa=5120,Ta=5121,Sa=5122,Ia=5123,Ra=5124,ka=5125,ri=5126,ni={attribPrefix:""};function Pa(r,e,t,n,i){r.bindBuffer(e,t),r.bufferData(e,n,i||ti)}function ii(r,e,t,n){if(wa(r,e))return e;t=t||we;const i=r.createBuffer();return Pa(r,t,i,e,n),i}function oi(r){return r==="indices"}function Fa(r){return r===Int8Array||r===Uint8Array}function Ca(r){return r.length?r:r.data}const Oa=/coord|texture/i,Ma=/color|colour/i;function Ba(r,e){let t;if(Oa.test(r)?t=2:Ma.test(r)?t=4:t=3,e%t>0)throw new Error(`Can not guess numComponents for attribute '${r}'. Tried ${t} but ${e} values is not evenly divisible by ${t}. You should specify it.`);return t}function Da(r,e,t){return r.numComponents||r.size||Ba(e,t||Ca(r).length)}function si(r,e){if(Nt(r))return r;if(Nt(r.data))return r.data;Array.isArray(r)&&(r={data:r});let t=r.type?Br(r.type):void 0;return t||(oi(e)?t=Uint16Array:t=Float32Array),new t(r.data)}function Ua(r){return typeof r=="number"?r:r?Kn(r):ri}function Br(r){return typeof r=="number"?Jn(r):r||Float32Array}function La(r,e){return{buffer:e.buffer,numValues:24,type:Ua(e.type),arrayType:Br(e.type)}}function za(r,e){const t=e.data||e,n=Br(e.type),i=t*n.BYTES_PER_ELEMENT,o=r.createBuffer();return r.bindBuffer(we,o),r.bufferData(we,i,e.drawType||ti),{buffer:o,numValues:t,type:Kn(n),arrayType:n}}function Na(r,e,t){const n=si(e,t);return{arrayType:n.constructor,buffer:ii(r,n,void 0,e.drawType),type:Or(n),numValues:0}}function $a(r,e){const t={};return Object.keys(e).forEach(function(n){if(!oi(n)){const i=e[n],o=i.attrib||i.name||i.attribName||ni.attribPrefix+n;if(i.value){if(!Array.isArray(i.value)&&!Nt(i.value))throw new Error("array.value is not array or typedarray");t[o]={value:i.value}}else{let s;i.buffer&&i.buffer instanceof WebGLBuffer?s=La:typeof i=="number"||typeof i.data=="number"?s=za:s=Na;const{buffer:a,type:c,numValues:u,arrayType:f}=s(r,i,n),m=i.normalize!==void 0?i.normalize:Fa(f),p=Da(i,n,u);t[o]={buffer:a,numComponents:p,type:c,normalize:m,stride:i.stride||0,offset:i.offset||0,divisor:i.divisor===void 0?void 0:i.divisor,drawType:i.drawType}}}}),r.bindBuffer(we,null),t}function Wa(r,e){return e===Aa||e===Ta?1:e===Sa||e===Ia?2:e===Ra||e===ka||e===ri?4:0}const Dr=["position","positions","a_position"];function Ga(r,e){let t,n;for(n=0;n<Dr.length&&(t=Dr[n],!(t in e||(t=ni.attribPrefix+t,t in e)));++n);n===Dr.length&&(t=Object.keys(e)[0]);const i=e[t];if(!i.buffer)return 1;r.bindBuffer(we,i.buffer);const o=r.getBufferParameter(we,Ea);r.bindBuffer(we,null);const s=Wa(r,i.type),a=o/s,c=i.numComponents||i.size,u=a/c;if(u%1!==0)throw new Error(`numComponents ${c} not correct for length ${length}`);return u}function Va(r,e,t){const n=$a(r,e),i=Object.assign({},t||{});i.attribs=Object.assign({},t?t.attribs:{},n);const o=e.indices;if(o){const s=si(o,"indices");i.indices=ii(r,s,_a),i.numElements=s.length,i.elementType=Or(s)}else i.numElements||(i.numElements=Ga(r,i.attribs));return i}function Ze(r){return!!r.texStorage2D}const ai=(function(){const r={},e={};function t(n){const i=n.constructor.name;if(!r[i]){for(const o in n)if(typeof n[o]=="number"){const s=e[n[o]];e[n[o]]=s?`${s} | ${o}`:o}r[i]=!0}}return function(i,o){return t(i),e[o]||(typeof o=="number"?`0x${o.toString(16)}`:o)}})(),oe={textureColor:new Uint8Array([128,192,255,255]),textureOptions:{},crossOrigin:void 0},et=Nt,ci=(function(){let r;return function(){return r=r||(typeof document<"u"&&document.createElement?document.createElement("canvas").getContext("2d"):null),r}})(),ui=6406,j=6407,T=6408,li=6409,fi=6410,tt=6402,di=34041,Wt=33071,Ha=9728,ja=9729,se=3553,ae=34067,xe=32879,ve=35866,Ur=34069,Ya=34070,Qa=34071,qa=34072,Xa=34073,Ka=34074,Lr=10241,zr=10240,Gt=10242,Vt=10243,hi=32882,Ja=33082,Za=33083,ec=33084,tc=33085,rc=34892,nc=34893,Nr=3317,mi=3314,pi=32878,gi=3316,yi=3315,bi=32877,ic=37443,oc=37441,sc=37440,ac=33321,cc=36756,uc=33325,lc=33326,fc=33330,dc=33329,hc=33338,mc=33337,pc=33340,gc=33339,yc=33323,bc=36757,wc=33327,xc=33328,vc=33336,_c=33335,Ec=33332,Ac=33331,Tc=33334,Sc=33333,Ic=32849,Rc=35905,kc=36194,Pc=36758,Fc=35898,Cc=35901,Oc=34843,Mc=34837,Bc=36221,Dc=36239,Uc=36215,Lc=36233,zc=36209,Nc=36227,$c=32856,Wc=35907,Gc=36759,Vc=32855,Hc=32854,jc=32857,Yc=34842,Qc=34836,qc=36220,Xc=36238,Kc=36975,Jc=36214,Zc=36232,eu=36226,tu=36208,ru=33189,nu=33190,iu=36012,ou=36013,su=35056,ce=5120,A=5121,Ht=5122,De=5123,jt=5124,_e=5125,M=5126,wi=32819,xi=32820,vi=33635,W=5131,rt=36193,$r=33640,au=35899,cu=35902,uu=36269,lu=34042,Yt=33319,Ue=33320,Qt=6403,Le=36244,ze=36248,Ee=36249;let Wr;function qt(r){if(!Wr){const e={};e[ui]={textureFormat:ui,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[A,W,rt,M]},e[li]={textureFormat:li,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[A,W,rt,M]},e[fi]={textureFormat:fi,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2,4,4,8],type:[A,W,rt,M]},e[j]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,6,6,12,2],type:[A,W,rt,M,vi]},e[T]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,8,8,16,2,2],type:[A,W,rt,M,wi,xi]},e[tt]={textureFormat:tt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[_e,De]},e[ac]={textureFormat:Qt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1],type:[A]},e[cc]={textureFormat:Qt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[1],type:[ce]},e[uc]={textureFormat:Qt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4,2],type:[M,W]},e[lc]={textureFormat:Qt,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[fc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[A]},e[dc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[ce]},e[Ec]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[De]},e[Ac]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Ht]},e[Tc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[_e]},e[Sc]={textureFormat:Le,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[jt]},e[yc]={textureFormat:Yt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2],type:[A]},e[bc]={textureFormat:Yt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[2],type:[ce]},e[wc]={textureFormat:Yt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[8,4],type:[M,W]},e[xc]={textureFormat:Yt,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[8],type:[M]},e[vc]={textureFormat:Ue,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[A]},e[_c]={textureFormat:Ue,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[ce]},e[hc]={textureFormat:Ue,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[De]},e[mc]={textureFormat:Ue,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Ht]},e[pc]={textureFormat:Ue,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[_e]},e[gc]={textureFormat:Ue,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[jt]},e[Ic]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3],type:[A]},e[Rc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[A]},e[kc]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,2],type:[A,vi]},e[Pc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[ce]},e[Fc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,W,au]},e[Cc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,W,cu]},e[Oc]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6],type:[M,W]},e[Mc]={textureFormat:j,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[M]},e[Bc]={textureFormat:ze,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[A]},e[Dc]={textureFormat:ze,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[ce]},e[Uc]={textureFormat:ze,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[De]},e[Lc]={textureFormat:ze,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Ht]},e[zc]={textureFormat:ze,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[_e]},e[Nc]={textureFormat:ze,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[jt]},e[$c]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[A]},e[Wc]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[A]},e[Gc]={textureFormat:T,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4],type:[ce]},e[Vc]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2,4],type:[A,xi,$r]},e[Hc]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2],type:[A,wi]},e[jc]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[$r]},e[Yc]={textureFormat:T,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[16,8],type:[M,W]},e[Qc]={textureFormat:T,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[16],type:[M]},e[qc]={textureFormat:Ee,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[A]},e[Xc]={textureFormat:Ee,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ce]},e[Kc]={textureFormat:Ee,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[$r]},e[Jc]={textureFormat:Ee,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[De]},e[Zc]={textureFormat:Ee,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Ht]},e[eu]={textureFormat:Ee,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[jt]},e[tu]={textureFormat:Ee,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[_e]},e[ru]={textureFormat:tt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[De,_e]},e[nu]={textureFormat:tt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[_e]},e[iu]={textureFormat:tt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[su]={textureFormat:di,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[lu]},e[ou]={textureFormat:di,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[uu]},Object.keys(e).forEach(function(t){const n=e[t];n.bytesPerElementMap={},n.bytesPerElement.forEach(function(i,o){const s=n.type[o];n.bytesPerElementMap[s]=i})}),Wr=e}return Wr[r]}function fu(r,e){const t=qt(r);if(!t)throw"unknown internal format";const n=t.bytesPerElementMap[e];if(n===void 0)throw"unknown internal format";return n}function nt(r){const e=qt(r);if(!e)throw"unknown internal format";return{format:e.textureFormat,type:e.type[0]}}function _i(r){return(r&r-1)===0}function du(r,e,t,n){if(!Ze(r))return _i(e)&&_i(t);const i=qt(n);if(!i)throw"unknown internal format";return i.colorRenderable&&i.textureFilterable}function hu(r){const e=qt(r);if(!e)throw"unknown internal format";return e.textureFilterable}function mu(r,e,t){return et(e)?Or(e):t||A}function Xt(r,e,t,n,i){if(i%1!==0)throw"can't guess dimensions";if(!t&&!n){const o=Math.sqrt(i/(e===ae?6:1));o%1===0?(t=o,n=o):(t=i,n=1)}else if(n){if(!t&&(t=i/n,t%1))throw"can't guess dimensions"}else if(n=i/t,n%1)throw"can't guess dimensions";return{width:t,height:n}}function Ne(r,e){e.colorspaceConversion!==void 0&&r.pixelStorei(ic,e.colorspaceConversion),e.premultiplyAlpha!==void 0&&r.pixelStorei(oc,e.premultiplyAlpha),e.flipY!==void 0&&r.pixelStorei(sc,e.flipY)}function Ei(r){r.pixelStorei(Nr,4),Ze(r)&&(r.pixelStorei(mi,0),r.pixelStorei(pi,0),r.pixelStorei(gi,0),r.pixelStorei(yi,0),r.pixelStorei(bi,0))}function pu(r,e,t,n){n.minMag&&(t.call(r,e,Lr,n.minMag),t.call(r,e,zr,n.minMag)),n.min&&t.call(r,e,Lr,n.min),n.mag&&t.call(r,e,zr,n.mag),n.wrap&&(t.call(r,e,Gt,n.wrap),t.call(r,e,Vt,n.wrap),(e===xe||va(r,e))&&t.call(r,e,hi,n.wrap)),n.wrapR&&t.call(r,e,hi,n.wrapR),n.wrapS&&t.call(r,e,Gt,n.wrapS),n.wrapT&&t.call(r,e,Vt,n.wrapT),n.minLod!==void 0&&t.call(r,e,Ja,n.minLod),n.maxLod!==void 0&&t.call(r,e,Za,n.maxLod),n.baseLevel!==void 0&&t.call(r,e,ec,n.baseLevel),n.maxLevel!==void 0&&t.call(r,e,tc,n.maxLevel),n.compareFunc!==void 0&&t.call(r,e,nc,n.compareFunc),n.compareMode!==void 0&&t.call(r,e,rc,n.compareMode)}function Ai(r,e,t){const n=t.target||se;r.bindTexture(n,e),pu(r,n,r.texParameteri,t)}function gu(r){return r=r||oe.textureColor,et(r)?r:new Uint8Array([r[0]*255,r[1]*255,r[2]*255,r[3]*255])}function Gr(r,e,t,n,i,o){t=t||oe.textureOptions,o=o||T;const s=t.target||se;if(n=n||t.width,i=i||t.height,r.bindTexture(s,e),du(r,n,i,o))r.generateMipmap(s);else{const a=hu(o)?ja:Ha;r.texParameteri(s,Lr,a),r.texParameteri(s,zr,a),r.texParameteri(s,Gt,Wt),r.texParameteri(s,Vt,Wt)}}function it(r){return r.auto===!0||r.auto===void 0&&r.level===void 0}function Vr(r,e){return e=e||{},e.cubeFaceOrder||[Ur,Ya,Qa,qa,Xa,Ka]}function Hr(r,e){const n=Vr(r,e).map(function(i,o){return{face:i,ndx:o}});return n.sort(function(i,o){return i.face-o.face}),n}function Ti(r,e,t,n){n=n||oe.textureOptions;const i=n.target||se,o=n.level||0;let s=t.width,a=t.height;const c=n.internalFormat||n.format||T,u=nt(c),f=n.format||u.format,m=n.type||u.type;if(Ne(r,n),r.bindTexture(i,e),i===ae){const p=t.width,b=t.height;let d,g;if(p/6===b)d=b,g=[0,0,1,0,2,0,3,0,4,0,5,0];else if(b/6===p)d=p,g=[0,0,0,1,0,2,0,3,0,4,0,5];else if(p/3===b/2)d=p/3,g=[0,0,1,0,2,0,0,1,1,1,2,1];else if(p/2===b/3)d=p/2,g=[0,0,1,0,0,1,1,1,0,2,1,2];else throw"can't figure out cube map from element: "+(t.src?t.src:t.nodeName);const x=ci();x?(x.canvas.width=d,x.canvas.height=d,s=d,a=d,Hr(r,n).forEach(function(v){const R=g[v.ndx*2+0]*d,C=g[v.ndx*2+1]*d;x.drawImage(t,R,C,d,d,0,0,d,d),r.texImage2D(v.face,o,c,f,m,x.canvas)}),x.canvas.width=1,x.canvas.height=1):typeof createImageBitmap<"u"&&(s=d,a=d,Hr(r,n).forEach(function(v){const R=g[v.ndx*2+0]*d,C=g[v.ndx*2+1]*d;r.texImage2D(v.face,o,c,d,d,0,f,m,null),createImageBitmap(t,R,C,d,d,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(function(N){Ne(r,n),r.bindTexture(i,e),r.texImage2D(v.face,o,c,f,m,N),it(n)&&Gr(r,e,n,s,a,c)})}))}else if(i===xe||i===ve){const p=Math.min(t.width,t.height),b=Math.max(t.width,t.height),d=b/p;if(d%1!==0)throw"can not compute 3D dimensions of element";const g=t.width===b?1:0,x=t.height===b?1:0;r.pixelStorei(Nr,1),r.pixelStorei(mi,t.width),r.pixelStorei(pi,0),r.pixelStorei(bi,0),r.texImage3D(i,o,c,p,p,p,0,f,m,null);for(let v=0;v<d;++v){const R=v*p*g,C=v*p*x;r.pixelStorei(gi,R),r.pixelStorei(yi,C),r.texSubImage3D(i,o,0,0,v,p,p,1,f,m,t)}Ei(r)}else r.texImage2D(i,o,c,f,m,t);it(n)&&Gr(r,e,n,s,a,c),Ai(r,e,n)}function ot(){}function yu(r){if(typeof document<"u"){const e=document.createElement("a");return e.href=r,e.hostname===location.hostname&&e.port===location.port&&e.protocol===location.protocol}else{const e=new URL(location.href).origin;return new URL(r,location.href).origin===e}}function bu(r,e){return e===void 0&&!yu(r)?"anonymous":e}function wu(r,e,t){t=t||ot;let n;if(e=e!==void 0?e:oe.crossOrigin,e=bu(r,e),typeof Image<"u"){n=new Image,e!==void 0&&(n.crossOrigin=e);const i=function(){n.removeEventListener("error",o),n.removeEventListener("load",s),n=null},o=function(){const c="couldn't load image: "+r;Zn(c),t(c,n),i()},s=function(){t(null,n),i()};return n.addEventListener("error",o),n.addEventListener("load",s),n.src=r,n}else if(typeof ImageBitmap<"u"){let i,o;const s=function(){t(i,o)},a={};e&&(a.mode="cors"),fetch(r,a).then(function(c){if(!c.ok)throw c;return c.blob()}).then(function(c){return createImageBitmap(c,{premultiplyAlpha:"none",colorSpaceConversion:"none"})}).then(function(c){o=c,setTimeout(s)}).catch(function(c){i=c,setTimeout(s)}),n=null}return n}function Si(r){return typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof ImageData<"u"&&r instanceof ImageData||typeof HTMLElement<"u"&&r instanceof HTMLElement}function jr(r,e,t){return Si(r)?(setTimeout(function(){t(null,r)}),r):wu(r,e,t)}function Yr(r,e,t){t=t||oe.textureOptions;const n=t.target||se;if(r.bindTexture(n,e),t.color===!1)return;const i=gu(t.color);if(n===ae)for(let o=0;o<6;++o)r.texImage2D(Ur+o,0,T,1,1,0,T,A,i);else n===xe||n===ve?r.texImage3D(n,0,T,1,1,1,0,T,A,i):r.texImage2D(n,0,T,1,1,0,T,A,i)}function xu(r,e,t,n){return n=n||ot,t=t||oe.textureOptions,Yr(r,e,t),t=Object.assign({},t),jr(t.src,t.crossOrigin,function(o,s){o?n(o,e,s):(Ti(r,e,s,t),n(null,e,s))})}function vu(r,e,t,n){n=n||ot;const i=t.src;if(i.length!==6)throw"there must be 6 urls for a cubemap";const o=t.level||0,s=t.internalFormat||t.format||T,a=nt(s),c=t.format||a.format,u=t.type||A,f=t.target||se;if(f!==ae)throw"target must be TEXTURE_CUBE_MAP";Yr(r,e,t),t=Object.assign({},t);let m=6;const p=[],b=Vr(r,t);let d;function g(x){return function(v,R){--m,v?p.push(v):R.width!==R.height?p.push("cubemap face img is not a square: "+R.src):(Ne(r,t),r.bindTexture(f,e),m===5?Vr().forEach(function(C){r.texImage2D(C,o,s,c,u,R)}):r.texImage2D(x,o,s,c,u,R),it(t)&&r.generateMipmap(f)),m===0&&n(p.length?p:void 0,e,d)}}d=i.map(function(x,v){return jr(x,t.crossOrigin,g(b[v]))})}function _u(r,e,t,n){n=n||ot;const i=t.src,o=t.internalFormat||t.format||T,s=nt(o),a=t.format||s.format,c=t.type||A,u=t.target||ve;if(u!==xe&&u!==ve)throw"target must be TEXTURE_3D or TEXTURE_2D_ARRAY";Yr(r,e,t),t=Object.assign({},t);let f=i.length;const m=[];let p;const b=t.level||0;let d=t.width,g=t.height;const x=i.length;let v=!0;function R(C){return function(N,J){if(--f,N)m.push(N);else{if(Ne(r,t),r.bindTexture(u,e),v){v=!1,d=t.width||J.width,g=t.height||J.height,r.texImage3D(u,b,o,d,g,x,0,a,c,null);for(let Z=0;Z<x;++Z)r.texSubImage3D(u,b,0,0,Z,d,g,1,a,c,J)}else{let Z=J,$;(J.width!==d||J.height!==g)&&($=ci(),Z=$.canvas,$.canvas.width=d,$.canvas.height=g,$.drawImage(J,0,0,d,g)),r.texSubImage3D(u,b,0,0,C,d,g,1,a,c,Z),$&&Z===$.canvas&&($.canvas.width=0,$.canvas.height=0)}it(t)&&r.generateMipmap(u)}f===0&&n(m.length?m:void 0,e,p)}}p=i.map(function(C,N){return jr(C,t.crossOrigin,R(N))})}function Eu(r,e,t,n){n=n||oe.textureOptions;const i=n.target||se;r.bindTexture(i,e);let o=n.width,s=n.height,a=n.depth;const c=n.level||0,u=n.internalFormat||n.format||T,f=nt(u),m=n.format||f.format,p=n.type||mu(r,t,f.type);if(et(t))t instanceof Uint8ClampedArray&&(t=new Uint8Array(t.buffer));else{const x=Jn(p);t=new x(t)}const b=fu(u,p),d=t.byteLength/b;if(d%1)throw"length wrong size for format: "+ai(r,m);let g;if(i===xe||i===ve)if(!o&&!s&&!a){const x=Math.cbrt(d);if(x%1!==0)throw"can't guess cube size of array of numElements: "+d;o=x,s=x,a=x}else o&&(!s||!a)?(g=Xt(r,i,s,a,d/o),s=g.width,a=g.height):s&&(!o||!a)?(g=Xt(r,i,o,a,d/s),o=g.width,a=g.height):(g=Xt(r,i,o,s,d/a),o=g.width,s=g.height);else g=Xt(r,i,o,s,d),o=g.width,s=g.height;if(Ei(r),r.pixelStorei(Nr,n.unpackAlignment||1),Ne(r,n),i===ae){const x=b/t.BYTES_PER_ELEMENT,v=d/6*x;Hr(r,n).forEach(R=>{const C=v*R.ndx,N=t.subarray(C,C+v);r.texImage2D(R.face,c,u,o,s,0,m,p,N)})}else i===xe||i===ve?r.texImage3D(i,c,u,o,s,a,0,m,p,t):r.texImage2D(i,c,u,o,s,0,m,p,t);return{width:o,height:s,depth:a,type:p}}function Au(r,e,t){const n=t.target||se;r.bindTexture(n,e);const i=t.level||0,o=t.internalFormat||t.format||T,s=nt(o),a=t.format||s.format,c=t.type||s.type;if(Ne(r,t),n===ae)for(let u=0;u<6;++u)r.texImage2D(Ur+u,i,o,t.width,t.height,0,a,c,null);else n===xe||n===ve?r.texImage3D(n,i,o,t.width,t.height,t.depth,0,a,c,null):r.texImage2D(n,i,o,t.width,t.height,0,a,c,null)}function Ii(r,e,t){t=t||ot,e=e||oe.textureOptions;const n=r.createTexture(),i=e.target||se;let o=e.width||1,s=e.height||1;const a=e.internalFormat||T;r.bindTexture(i,n),i===ae&&(r.texParameteri(i,Gt,Wt),r.texParameteri(i,Vt,Wt));let c=e.src;if(c)if(typeof c=="function"&&(c=c(r,e)),typeof c=="string")xu(r,n,e,t);else if(et(c)||Array.isArray(c)&&(typeof c[0]=="number"||Array.isArray(c[0])||et(c[0]))){const u=Eu(r,n,c,e);o=u.width,s=u.height}else Array.isArray(c)&&(typeof c[0]=="string"||Si(c[0]))?i===ae?vu(r,n,e,t):_u(r,n,e,t):(Ti(r,n,c,e),o=c.width,s=c.height);else Au(r,n,e);return it(e)&&Gr(r,n,e,o,s,a),Ai(r,n,e),n}const Qr=Zn;function Ri(r){return typeof document<"u"&&document.getElementById?document.getElementById(r):null}const Kt=33984,Jt=34962,Tu=34963,Su=35713,Iu=35714,Ru=35632,ku=35633,Pu=35981,ki=35718,Fu=35721,Cu=35971,Ou=35382,Mu=35396,Bu=35398,Du=35392,Uu=35395,Zt=5126,Pi=35664,Fi=35665,Ci=35666,qr=5124,Oi=35667,Mi=35668,Bi=35669,Di=35670,Ui=35671,Li=35672,zi=35673,Ni=35674,$i=35675,Wi=35676,Lu=35678,zu=35680,Nu=35679,$u=35682,Wu=35685,Gu=35686,Vu=35687,Hu=35688,ju=35689,Yu=35690,Qu=36289,qu=36292,Xu=36293,Xr=5125,Gi=36294,Vi=36295,Hi=36296,Ku=36298,Ju=36299,Zu=36300,el=36303,tl=36306,rl=36307,nl=36308,il=36311,er=3553,tr=34067,Kr=32879,rr=35866,w={};function ji(r,e){return w[e].bindPoint}function ol(r,e){return function(t){r.uniform1f(e,t)}}function sl(r,e){return function(t){r.uniform1fv(e,t)}}function al(r,e){return function(t){r.uniform2fv(e,t)}}function cl(r,e){return function(t){r.uniform3fv(e,t)}}function ul(r,e){return function(t){r.uniform4fv(e,t)}}function Yi(r,e){return function(t){r.uniform1i(e,t)}}function Qi(r,e){return function(t){r.uniform1iv(e,t)}}function qi(r,e){return function(t){r.uniform2iv(e,t)}}function Xi(r,e){return function(t){r.uniform3iv(e,t)}}function Ki(r,e){return function(t){r.uniform4iv(e,t)}}function ll(r,e){return function(t){r.uniform1ui(e,t)}}function fl(r,e){return function(t){r.uniform1uiv(e,t)}}function dl(r,e){return function(t){r.uniform2uiv(e,t)}}function hl(r,e){return function(t){r.uniform3uiv(e,t)}}function ml(r,e){return function(t){r.uniform4uiv(e,t)}}function pl(r,e){return function(t){r.uniformMatrix2fv(e,!1,t)}}function gl(r,e){return function(t){r.uniformMatrix3fv(e,!1,t)}}function yl(r,e){return function(t){r.uniformMatrix4fv(e,!1,t)}}function bl(r,e){return function(t){r.uniformMatrix2x3fv(e,!1,t)}}function wl(r,e){return function(t){r.uniformMatrix3x2fv(e,!1,t)}}function xl(r,e){return function(t){r.uniformMatrix2x4fv(e,!1,t)}}function vl(r,e){return function(t){r.uniformMatrix4x2fv(e,!1,t)}}function _l(r,e){return function(t){r.uniformMatrix3x4fv(e,!1,t)}}function El(r,e){return function(t){r.uniformMatrix4x3fv(e,!1,t)}}function U(r,e,t,n){const i=ji(r,e);return Ze(r)?function(o){let s,a;!o||Mr(r,o)?(s=o,a=null):(s=o.texture,a=o.sampler),r.uniform1i(n,t),r.activeTexture(Kt+t),r.bindTexture(i,s),r.bindSampler(t,a)}:function(o){r.uniform1i(n,t),r.activeTexture(Kt+t),r.bindTexture(i,o)}}function L(r,e,t,n,i){const o=ji(r,e),s=new Int32Array(i);for(let a=0;a<i;++a)s[a]=t+a;return Ze(r)?function(a){r.uniform1iv(n,s),a.forEach(function(c,u){r.activeTexture(Kt+s[u]);let f,m;!c||Mr(r,c)?(f=c,m=null):(f=c.texture,m=c.sampler),r.bindSampler(t,m),r.bindTexture(o,f)})}:function(a){r.uniform1iv(n,s),a.forEach(function(c,u){r.activeTexture(Kt+s[u]),r.bindTexture(o,c)})}}w[Zt]={Type:Float32Array,size:4,setter:ol,arraySetter:sl},w[Pi]={Type:Float32Array,size:8,setter:al,cols:2},w[Fi]={Type:Float32Array,size:12,setter:cl,cols:3},w[Ci]={Type:Float32Array,size:16,setter:ul,cols:4},w[qr]={Type:Int32Array,size:4,setter:Yi,arraySetter:Qi},w[Oi]={Type:Int32Array,size:8,setter:qi,cols:2},w[Mi]={Type:Int32Array,size:12,setter:Xi,cols:3},w[Bi]={Type:Int32Array,size:16,setter:Ki,cols:4},w[Xr]={Type:Uint32Array,size:4,setter:ll,arraySetter:fl},w[Gi]={Type:Uint32Array,size:8,setter:dl,cols:2},w[Vi]={Type:Uint32Array,size:12,setter:hl,cols:3},w[Hi]={Type:Uint32Array,size:16,setter:ml,cols:4},w[Di]={Type:Uint32Array,size:4,setter:Yi,arraySetter:Qi},w[Ui]={Type:Uint32Array,size:8,setter:qi,cols:2},w[Li]={Type:Uint32Array,size:12,setter:Xi,cols:3},w[zi]={Type:Uint32Array,size:16,setter:Ki,cols:4},w[Ni]={Type:Float32Array,size:32,setter:pl,rows:2,cols:2},w[$i]={Type:Float32Array,size:48,setter:gl,rows:3,cols:3},w[Wi]={Type:Float32Array,size:64,setter:yl,rows:4,cols:4},w[Wu]={Type:Float32Array,size:32,setter:bl,rows:2,cols:3},w[Gu]={Type:Float32Array,size:32,setter:xl,rows:2,cols:4},w[Vu]={Type:Float32Array,size:48,setter:wl,rows:3,cols:2},w[Hu]={Type:Float32Array,size:48,setter:_l,rows:3,cols:4},w[ju]={Type:Float32Array,size:64,setter:vl,rows:4,cols:2},w[Yu]={Type:Float32Array,size:64,setter:El,rows:4,cols:3},w[Lu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:er},w[zu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:tr},w[Nu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:Kr},w[$u]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:er},w[Qu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:rr},w[qu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:rr},w[Xu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:tr},w[Ku]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:er},w[Ju]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:Kr},w[Zu]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:tr},w[el]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:rr},w[tl]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:er},w[rl]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:Kr},w[nl]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:tr},w[il]={Type:null,size:0,setter:U,arraySetter:L,bindPoint:rr};function nr(r,e){return function(t){if(t.value)switch(r.disableVertexAttribArray(e),t.value.length){case 4:r.vertexAttrib4fv(e,t.value);break;case 3:r.vertexAttrib3fv(e,t.value);break;case 2:r.vertexAttrib2fv(e,t.value);break;case 1:r.vertexAttrib1fv(e,t.value);break;default:throw new Error("the length of a float constant value must be between 1 and 4!")}else r.bindBuffer(Jt,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribPointer(e,t.numComponents||t.size,t.type||Zt,t.normalize||!1,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function ue(r,e){return function(t){if(t.value)if(r.disableVertexAttribArray(e),t.value.length===4)r.vertexAttrib4iv(e,t.value);else throw new Error("The length of an integer constant value must be 4!");else r.bindBuffer(Jt,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribIPointer(e,t.numComponents||t.size,t.type||qr,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function ir(r,e){return function(t){if(t.value)if(r.disableVertexAttribArray(e),t.value.length===4)r.vertexAttrib4uiv(e,t.value);else throw new Error("The length of an unsigned integer constant value must be 4!");else r.bindBuffer(Jt,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribIPointer(e,t.numComponents||t.size,t.type||Xr,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function Jr(r,e,t){const n=t.size,i=t.count;return function(o){r.bindBuffer(Jt,o.buffer);const s=o.size||o.numComponents||n,a=s/i,c=o.type||Zt,f=w[c].size*s,m=o.normalize||!1,p=o.offset||0,b=f/i;for(let d=0;d<i;++d)r.enableVertexAttribArray(e+d),r.vertexAttribPointer(e+d,a,c,m,f,p+b*d),r.vertexAttribDivisor&&r.vertexAttribDivisor(e+d,o.divisor||0)}}const S={};S[Zt]={size:4,setter:nr},S[Pi]={size:8,setter:nr},S[Fi]={size:12,setter:nr},S[Ci]={size:16,setter:nr},S[qr]={size:4,setter:ue},S[Oi]={size:8,setter:ue},S[Mi]={size:12,setter:ue},S[Bi]={size:16,setter:ue},S[Xr]={size:4,setter:ir},S[Gi]={size:8,setter:ir},S[Vi]={size:12,setter:ir},S[Hi]={size:16,setter:ir},S[Di]={size:4,setter:ue},S[Ui]={size:8,setter:ue},S[Li]={size:12,setter:ue},S[zi]={size:16,setter:ue},S[Ni]={size:4,setter:Jr,count:2},S[$i]={size:9,setter:Jr,count:3},S[Wi]={size:16,setter:Jr,count:4};const Al=/ERROR:\s*\d+:(\d+)/gi;function Tl(r,e="",t=0){const n=[...e.matchAll(Al)],i=new Map(n.map((o,s)=>{const a=parseInt(o[1]),c=n[s+1],u=c?c.index:e.length,f=e.substring(o.index,u);return[a-1,f]}));return r.split(`
5
5
  `).map((o,s)=>{const a=i.get(s);return`${s+1+t}: ${o}${a?`
6
6
 
7
7
  ^^^ ${a}`:""}`}).join(`
8
- `)}const Zi=/^[ \t]*\n/;function eo(r){let e=0;return Zi.test(r)&&(e=1,r=r.replace(Zi,"")),{lineOffset:e,shaderSource:r}}function El(r,e){return r.errorCallback(e),r.callback&&setTimeout(()=>{r.callback(`${e}
8
+ `)}const Ji=/^[ \t]*\n/;function Zi(r){let e=0;return Ji.test(r)&&(e=1,r=r.replace(Ji,"")),{lineOffset:e,shaderSource:r}}function Sl(r,e){return r.errorCallback(e),r.callback&&setTimeout(()=>{r.callback(`${e}
9
9
  ${r.errors.join(`
10
- `)}`)}),null}function Al(r,e,t,n){if(n=n||qr,!r.getShaderParameter(t,Eu)){const o=r.getShaderInfoLog(t),{lineOffset:s,shaderSource:a}=eo(r.getShaderSource(t)),c=`${_l(a,o,s)}
11
- Error compiling ${ci(r,e)}: ${o}`;return n(c),c}return""}function en(r,e,t){let n,i,o;if(typeof e=="function"&&(t=e,e=void 0),typeof r=="function")t=r,r=void 0;else if(r&&!Array.isArray(r)){const u=r;t=u.errorCallback,r=u.attribLocations,n=u.transformFeedbackVaryings,i=u.transformFeedbackMode,o=u.callback}const s=t||qr,a=[],c={errorCallback(u,...f){a.push(u),s(u,...f)},transformFeedbackVaryings:n,transformFeedbackMode:i,callback:o,errors:a};{let u={};Array.isArray(r)?r.forEach(function(f,m){u[f]=e?e[m]:m}):u=r||{},c.attribLocations=u}return c}const Tl=["VERTEX_SHADER","FRAGMENT_SHADER"];function Sl(r,e){if(e.indexOf("frag")>=0)return Tu;if(e.indexOf("vert")>=0)return Su}function Il(r,e,t){const n=r.getAttachedShaders(e);for(const i of n)t.has(i)&&r.deleteShader(i);r.deleteProgram(e)}const kl=(r=0)=>new Promise(e=>setTimeout(e,r));function Rl(r,e,t){const n=r.createProgram(),{attribLocations:i,transformFeedbackVaryings:o,transformFeedbackMode:s}=en(t);for(let a=0;a<e.length;++a){let c=e[a];if(typeof c=="string"){const u=Ri(c),f=u?u.text:c;let m=r[Tl[a]];u&&u.type&&(m=Sl(r,u.type)||m),c=r.createShader(m),r.shaderSource(c,eo(f).shaderSource),r.compileShader(c),r.attachShader(n,c)}}Object.entries(i).forEach(([a,c])=>r.bindAttribLocation(n,c,a));{let a=o;a&&(a.attribs&&(a=a.attribs),Array.isArray(a)||(a=Object.keys(a)),r.transformFeedbackVaryings(n,a,s||Iu))}return r.linkProgram(n),n}function Pl(r,e,t,n,i){const o=en(t,n,i),s=new Set(e),a=Rl(r,e,o);function c(u,f){const m=Ol(u,f,o.errorCallback);return m&&Il(u,f,s),m}if(o.callback){Fl(r,a).then(()=>{const u=c(r,a);o.callback(u,u?void 0:a)});return}return c(r,a)?void 0:a}async function Fl(r,e){const t=r.getExtension("KHR_parallel_shader_compile"),n=t?(o,s)=>o.getProgramParameter(s,t.COMPLETION_STATUS_KHR):()=>!0;let i=0;do await kl(i),i=1e3/60;while(!n(r,e))}function Ol(r,e,t){if(t=t||qr,!r.getProgramParameter(e,Au)){const i=r.getProgramInfoLog(e);t(`Error in program linking: ${i}`);const s=r.getAttachedShaders(e).map(a=>Al(r,r.getShaderParameter(a,r.SHADER_TYPE),a,t));return`${i}
10
+ `)}`)}),null}function Il(r,e,t,n){if(n=n||Qr,!r.getShaderParameter(t,Su)){const o=r.getShaderInfoLog(t),{lineOffset:s,shaderSource:a}=Zi(r.getShaderSource(t)),c=`${Tl(a,o,s)}
11
+ Error compiling ${ai(r,e)}: ${o}`;return n(c),c}return""}function Zr(r,e,t){let n,i,o;if(typeof e=="function"&&(t=e,e=void 0),typeof r=="function")t=r,r=void 0;else if(r&&!Array.isArray(r)){const u=r;t=u.errorCallback,r=u.attribLocations,n=u.transformFeedbackVaryings,i=u.transformFeedbackMode,o=u.callback}const s=t||Qr,a=[],c={errorCallback(u,...f){a.push(u),s(u,...f)},transformFeedbackVaryings:n,transformFeedbackMode:i,callback:o,errors:a};{let u={};Array.isArray(r)?r.forEach(function(f,m){u[f]=e?e[m]:m}):u=r||{},c.attribLocations=u}return c}const Rl=["VERTEX_SHADER","FRAGMENT_SHADER"];function kl(r,e){if(e.indexOf("frag")>=0)return Ru;if(e.indexOf("vert")>=0)return ku}function Pl(r,e,t){const n=r.getAttachedShaders(e);for(const i of n)t.has(i)&&r.deleteShader(i);r.deleteProgram(e)}const Fl=(r=0)=>new Promise(e=>setTimeout(e,r));function Cl(r,e,t){const n=r.createProgram(),{attribLocations:i,transformFeedbackVaryings:o,transformFeedbackMode:s}=Zr(t);for(let a=0;a<e.length;++a){let c=e[a];if(typeof c=="string"){const u=Ri(c),f=u?u.text:c;let m=r[Rl[a]];u&&u.type&&(m=kl(r,u.type)||m),c=r.createShader(m),r.shaderSource(c,Zi(f).shaderSource),r.compileShader(c),r.attachShader(n,c)}}Object.entries(i).forEach(([a,c])=>r.bindAttribLocation(n,c,a));{let a=o;a&&(a.attribs&&(a=a.attribs),Array.isArray(a)||(a=Object.keys(a)),r.transformFeedbackVaryings(n,a,s||Pu))}return r.linkProgram(n),n}function Ol(r,e,t,n,i){const o=Zr(t,n,i),s=new Set(e),a=Cl(r,e,o);function c(u,f){const m=Bl(u,f,o.errorCallback);return m&&Pl(u,f,s),m}if(o.callback){Ml(r,a).then(()=>{const u=c(r,a);o.callback(u,u?void 0:a)});return}return c(r,a)?void 0:a}async function Ml(r,e){const t=r.getExtension("KHR_parallel_shader_compile"),n=t?(o,s)=>o.getProgramParameter(s,t.COMPLETION_STATUS_KHR):()=>!0;let i=0;do await Fl(i),i=1e3/60;while(!n(r,e))}function Bl(r,e,t){if(t=t||Qr,!r.getProgramParameter(e,Iu)){const i=r.getProgramInfoLog(e);t(`Error in program linking: ${i}`);const s=r.getAttachedShaders(e).map(a=>Il(r,r.getShaderParameter(a,r.SHADER_TYPE),a,t));return`${i}
12
12
  ${s.filter(a=>a).join(`
13
- `)}`}}function Cl(r,e,t,n,i){return Pl(r,e,t,n,i)}function to(r){const e=r.name;return e.startsWith("gl_")||e.startsWith("webgl_")}const Ml=/(\.|\[|]|\w+)/g,Bl=r=>r>="0"&&r<="9";function Dl(r,e,t,n){const i=r.split(Ml).filter(a=>a!=="");let o=0,s="";for(;;){const a=i[o++];s+=a;const c=Bl(a[0]),u=c?parseInt(a):a;if(c&&(s+=i[o++]),o===i.length){t[u]=e;break}else{const m=i[o++],p=m==="[",b=t[u]||(p?[]:{});t[u]=b,t=b,n[s]=n[s]||(function(d){return function(g){ro(d,g)}})(b),s+=m}}}function Ul(r,e){let t=0;function n(a,c,u){const f=c.name.endsWith("[0]"),m=c.type,p=w[m];if(!p)throw new Error(`unknown type: 0x${m.toString(16)}`);let b;if(p.bindPoint){const d=t;t+=c.size,f?b=p.arraySetter(r,m,d,u,c.size):b=p.setter(r,m,d,u,c.size)}else p.arraySetter&&f?b=p.arraySetter(r,u):b=p.setter(r,u);return b.location=u,b}const i={},o={},s=r.getProgramParameter(e,Pi);for(let a=0;a<s;++a){const c=r.getActiveUniform(e,a);if(to(c))continue;let u=c.name;u.endsWith("[0]")&&(u=u.substr(0,u.length-3));const f=r.getUniformLocation(e,c.name);if(f){const m=n(e,c,f);i[u]=m,Dl(u,m,o,i)}}return i}function Ll(r,e){const t={},n=r.getProgramParameter(e,Ru);for(let i=0;i<n;++i){const o=r.getTransformFeedbackVarying(e,i);t[o.name]={index:i,type:o.type,size:o.size}}return t}function zl(r,e){const t=r.getProgramParameter(e,Pi),n=[],i=[];for(let a=0;a<t;++a){i.push(a),n.push({});const c=r.getActiveUniform(e,a);n[a].name=c.name}[["UNIFORM_TYPE","type"],["UNIFORM_SIZE","size"],["UNIFORM_BLOCK_INDEX","blockNdx"],["UNIFORM_OFFSET","offset"]].forEach(function(a){const c=a[0],u=a[1];r.getActiveUniforms(e,i,r[c]).forEach(function(f,m){n[m][u]=f})});const o={},s=r.getProgramParameter(e,Pu);for(let a=0;a<s;++a){const c=r.getActiveUniformBlockName(e,a),u={index:r.getUniformBlockIndex(e,c),usedByVertexShader:r.getActiveUniformBlockParameter(e,a,Fu),usedByFragmentShader:r.getActiveUniformBlockParameter(e,a,Ou),size:r.getActiveUniformBlockParameter(e,a,Cu),uniformIndices:r.getActiveUniformBlockParameter(e,a,Mu)};u.used=u.usedByVertexShader||u.usedByFragmentShader,o[c]=u}return{blockSpecs:o,uniformData:n}}function ro(r,e){for(const t in e){const n=r[t];typeof n=="function"?n(e[t]):ro(r[t],e[t])}}function no(r,...e){const t=r.uniformSetters||r,n=e.length;for(let i=0;i<n;++i){const o=e[i];if(Array.isArray(o)){const s=o.length;for(let a=0;a<s;++a)no(t,o[a])}else for(const s in o){const a=t[s];a&&a(o[s])}}}function Nl(r,e){const t={},n=r.getProgramParameter(e,ku);for(let i=0;i<n;++i){const o=r.getActiveAttrib(e,i);if(to(o))continue;const s=r.getAttribLocation(e,o.name),a=S[o.type],c=a.setter(r,s,a);c.location=s,t[o.name]=c}return t}function $l(r,e){for(const t in e){const n=r[t];n&&n(e[t])}}function Wl(r,e,t){t.vertexArrayObject?r.bindVertexArray(t.vertexArrayObject):($l(e.attribSetters||e,t.attribs),t.indices&&r.bindBuffer(_u,t.indices))}function io(r,e){const t=Ul(r,e),n=Nl(r,e),i={program:e,uniformSetters:t,attribSetters:n};return Ze(r)&&(i.uniformBlockSpec=zl(r,e),i.transformFeedbackInfo=Ll(r,e)),i}const Gl=/\s|{|}|;/;function Vl(r,e,t,n,i){const o=en(t,n,i),s=[];if(e=e.map(function(u){if(!Gl.test(u)){const f=Ri(u);if(f)u=f.text;else{const m=`no element with id: ${u}`;o.errorCallback(m),s.push(m)}}return u}),s.length)return El(o,"");const a=o.callback;a&&(o.callback=(u,f)=>{a(u,u?void 0:io(r,f))});const c=Cl(r,e,o);return c?io(r,c):null}const Hl=4,oo=5123;function jl(r,e,t,n,i,o){t=t===void 0?Hl:t;const s=e.indices,a=e.elementType,c=n===void 0?e.numElements:n;i=i===void 0?0:i,a||s?o!==void 0?r.drawElementsInstanced(t,c,a===void 0?oo:e.elementType,i,o):r.drawElements(t,c,a===void 0?oo:e.elementType,i):o!==void 0?r.drawArraysInstanced(t,i,c,o):r.drawArrays(t,i,c)}const so=36160,or=36161,Yl=3553,Ql=5121,ql=6402,Xl=6408,Kl=33190,Jl=36012,Zl=35056,ef=36013,tf=32854,rf=32855,nf=36194,ao=33189,co=6401,uo=36168,tn=34041,rn=36064,sr=36096,lo=36128,nn=33306,on=33071,sn=9729,of=[{format:Xl,type:Ql,min:sn,wrap:on},{format:tn}],G={};G[tn]=nn,G[co]=lo,G[uo]=lo,G[ql]=sr,G[ao]=sr,G[Kl]=sr,G[Jl]=sr,G[Zl]=nn,G[ef]=nn;function sf(r,e){return G[r]||G[e]}const le={};le[tf]=!0,le[rf]=!0,le[nf]=!0,le[tn]=!0,le[ao]=!0,le[co]=!0,le[uo]=!0;function af(r){return le[r]}const cf=32;function uf(r){return r>=rn&&r<rn+cf}function fo(r,e,t,n){const i=so,o=r.createFramebuffer();r.bindFramebuffer(i,o),t=t||r.drawingBufferWidth,n=n||r.drawingBufferHeight,e=e||of;const s=[],a={framebuffer:o,attachments:[],width:t,height:n};return e.forEach(function(c,u){let f=c.attachment;const m=c.samples,p=c.format;let b=c.attachmentPoint||sf(p,c.internalFormat);if(b||(b=rn+u),uf(b)&&s.push(b),!f)if(m!==void 0||af(p))f=r.createRenderbuffer(),r.bindRenderbuffer(or,f),m>1?r.renderbufferStorageMultisample(or,m,p,t,n):r.renderbufferStorage(or,p,t,n);else{const d=Object.assign({},c);d.width=t,d.height=n,d.auto===void 0&&(d.auto=!1,d.min=d.min||d.minMag||sn,d.mag=d.mag||d.minMag||sn,d.wrapS=d.wrapS||d.wrap||on,d.wrapT=d.wrapT||d.wrap||on),f=ki(r,d)}if(ya(r,f))r.framebufferRenderbuffer(i,b,or,f);else if(Br(r,f))c.layer!==void 0?r.framebufferTextureLayer(i,b,f,c.level||0,c.layer):r.framebufferTexture2D(i,b,c.target||Yl,f,c.level||0);else throw new Error("unknown attachment type");a.attachments.push(f)}),r.drawBuffers&&r.drawBuffers(s),a}function lf(r,e,t){t=t||so,e?(r.bindFramebuffer(t,e.framebuffer),r.viewport(0,0,e.width,e.height)):(r.bindFramebuffer(t,null),r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight))}function B(r,e){return()=>e instanceof WebGLTexture?e:ki(r,{src:e,wrap:r.CLAMP_TO_EDGE})}const We=2;class st{constructor(e){this.id="_";const{context:t,width:n,height:i}=e;this.context=t,this.options=e;const o=this.buildDefines();this.programInfo=Vl(this.context,[o+this.getVertexShader(),o+this.getFragmentShader()]),this.bufferInfo=$a(this.context,this.getBuffers()),this.fbi=fo(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],n,i),this.output=this.fbi.attachments[0]}resizeOutput(e,t){this.fbi=fo(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],e,t),this.options.width=e,this.options.height=t,this.output=this.fbi.attachments[0]}getDefines(){return{}}getBuffers(){return{position:{numComponents:2,data:[-1,-1,-1,1,1,-1,1,1,-1,1,1,-1]},texture_coord:{numComponents:2,data:[0,0,0,1,1,0,1,1,0,1,1,0]}}}buildDefines(){let e="";const t=this.getDefines();for(let n in t)e+=`#define ${n} ${t[n].toFixed(1)}
14
- `;return e}run(e){this.profiler?.pushContext(`[${this.id}] PROG : ${this.constructor.name}`),this.profiler?.pushContext(`[${this.id}] UNIFORMS`);for(const i in e)typeof e[i]=="function"&&(this.profiler?.pushContext(`[${this.id}] UNI : ${i}`),e[i]=e[i](),this.profiler?.popContext(`[${this.id}] UNI : ${i}`));this.profiler?.popContext(`[${this.id}] UNIFORMS`);const t=Date.now();let n=0;this.lastRun&&(n=(t-this.lastRun)/1e3),this.lastRun=t,this.context.viewport(0,0,this.context.canvas.width,this.context.canvas.height),this.context.useProgram(this.programInfo.program),Wl(this.context,this.programInfo,this.bufferInfo),no(this.programInfo,{delta:n,canvas:[this.context.canvas.width,this.context.canvas.height],...e}),lf(this.context,this.options.disableFramebuffer?null:this.fbi),jl(this.context,this.bufferInfo),this.profiler?.popContext(`[${this.id}] PROG : ${this.constructor.name}`)}setProfiler(e){this.profiler=e}}const ff=`precision mediump float;
13
+ `)}`}}function Dl(r,e,t,n,i){return Ol(r,e,t,n,i)}function eo(r){const e=r.name;return e.startsWith("gl_")||e.startsWith("webgl_")}const Ul=/(\.|\[|]|\w+)/g,Ll=r=>r>="0"&&r<="9";function zl(r,e,t,n){const i=r.split(Ul).filter(a=>a!=="");let o=0,s="";for(;;){const a=i[o++];s+=a;const c=Ll(a[0]),u=c?parseInt(a):a;if(c&&(s+=i[o++]),o===i.length){t[u]=e;break}else{const m=i[o++],p=m==="[",b=t[u]||(p?[]:{});t[u]=b,t=b,n[s]=n[s]||(function(d){return function(g){to(d,g)}})(b),s+=m}}}function Nl(r,e){let t=0;function n(a,c,u){const f=c.name.endsWith("[0]"),m=c.type,p=w[m];if(!p)throw new Error(`unknown type: 0x${m.toString(16)}`);let b;if(p.bindPoint){const d=t;t+=c.size,f?b=p.arraySetter(r,m,d,u,c.size):b=p.setter(r,m,d,u,c.size)}else p.arraySetter&&f?b=p.arraySetter(r,u):b=p.setter(r,u);return b.location=u,b}const i={},o={},s=r.getProgramParameter(e,ki);for(let a=0;a<s;++a){const c=r.getActiveUniform(e,a);if(eo(c))continue;let u=c.name;u.endsWith("[0]")&&(u=u.substr(0,u.length-3));const f=r.getUniformLocation(e,c.name);if(f){const m=n(e,c,f);i[u]=m,zl(u,m,o,i)}}return i}function $l(r,e){const t={},n=r.getProgramParameter(e,Cu);for(let i=0;i<n;++i){const o=r.getTransformFeedbackVarying(e,i);t[o.name]={index:i,type:o.type,size:o.size}}return t}function Wl(r,e){const t=r.getProgramParameter(e,ki),n=[],i=[];for(let a=0;a<t;++a){i.push(a),n.push({});const c=r.getActiveUniform(e,a);n[a].name=c.name}[["UNIFORM_TYPE","type"],["UNIFORM_SIZE","size"],["UNIFORM_BLOCK_INDEX","blockNdx"],["UNIFORM_OFFSET","offset"]].forEach(function(a){const c=a[0],u=a[1];r.getActiveUniforms(e,i,r[c]).forEach(function(f,m){n[m][u]=f})});const o={},s=r.getProgramParameter(e,Ou);for(let a=0;a<s;++a){const c=r.getActiveUniformBlockName(e,a),u={index:r.getUniformBlockIndex(e,c),usedByVertexShader:r.getActiveUniformBlockParameter(e,a,Mu),usedByFragmentShader:r.getActiveUniformBlockParameter(e,a,Bu),size:r.getActiveUniformBlockParameter(e,a,Du),uniformIndices:r.getActiveUniformBlockParameter(e,a,Uu)};u.used=u.usedByVertexShader||u.usedByFragmentShader,o[c]=u}return{blockSpecs:o,uniformData:n}}function to(r,e){for(const t in e){const n=r[t];typeof n=="function"?n(e[t]):to(r[t],e[t])}}function ro(r,...e){const t=r.uniformSetters||r,n=e.length;for(let i=0;i<n;++i){const o=e[i];if(Array.isArray(o)){const s=o.length;for(let a=0;a<s;++a)ro(t,o[a])}else for(const s in o){const a=t[s];a&&a(o[s])}}}function Gl(r,e){const t={},n=r.getProgramParameter(e,Fu);for(let i=0;i<n;++i){const o=r.getActiveAttrib(e,i);if(eo(o))continue;const s=r.getAttribLocation(e,o.name),a=S[o.type],c=a.setter(r,s,a);c.location=s,t[o.name]=c}return t}function Vl(r,e){for(const t in e){const n=r[t];n&&n(e[t])}}function Hl(r,e,t){t.vertexArrayObject?r.bindVertexArray(t.vertexArrayObject):(Vl(e.attribSetters||e,t.attribs),t.indices&&r.bindBuffer(Tu,t.indices))}function no(r,e){const t=Nl(r,e),n=Gl(r,e),i={program:e,uniformSetters:t,attribSetters:n};return Ze(r)&&(i.uniformBlockSpec=Wl(r,e),i.transformFeedbackInfo=$l(r,e)),i}const jl=/\s|{|}|;/;function Yl(r,e,t,n,i){const o=Zr(t,n,i),s=[];if(e=e.map(function(u){if(!jl.test(u)){const f=Ri(u);if(f)u=f.text;else{const m=`no element with id: ${u}`;o.errorCallback(m),s.push(m)}}return u}),s.length)return Sl(o,"");const a=o.callback;a&&(o.callback=(u,f)=>{a(u,u?void 0:no(r,f))});const c=Dl(r,e,o);return c?no(r,c):null}const Ql=4,io=5123;function ql(r,e,t,n,i,o){t=t===void 0?Ql:t;const s=e.indices,a=e.elementType,c=n===void 0?e.numElements:n;i=i===void 0?0:i,a||s?o!==void 0?r.drawElementsInstanced(t,c,a===void 0?io:e.elementType,i,o):r.drawElements(t,c,a===void 0?io:e.elementType,i):o!==void 0?r.drawArraysInstanced(t,i,c,o):r.drawArrays(t,i,c)}const oo=36160,or=36161,Xl=3553,Kl=5121,Jl=6402,Zl=6408,ef=33190,tf=36012,rf=35056,nf=36013,of=32854,sf=32855,af=36194,so=33189,ao=6401,co=36168,en=34041,tn=36064,sr=36096,uo=36128,rn=33306,nn=33071,on=9729,cf=[{format:Zl,type:Kl,min:on,wrap:nn},{format:en}],G={};G[en]=rn,G[ao]=uo,G[co]=uo,G[Jl]=sr,G[so]=sr,G[ef]=sr,G[tf]=sr,G[rf]=rn,G[nf]=rn;function uf(r,e){return G[r]||G[e]}const le={};le[of]=!0,le[sf]=!0,le[af]=!0,le[en]=!0,le[so]=!0,le[ao]=!0,le[co]=!0;function lf(r){return le[r]}const ff=32;function df(r){return r>=tn&&r<tn+ff}function lo(r,e,t,n){const i=oo,o=r.createFramebuffer();r.bindFramebuffer(i,o),t=t||r.drawingBufferWidth,n=n||r.drawingBufferHeight,e=e||cf;const s=[],a={framebuffer:o,attachments:[],width:t,height:n};return e.forEach(function(c,u){let f=c.attachment;const m=c.samples,p=c.format;let b=c.attachmentPoint||uf(p,c.internalFormat);if(b||(b=tn+u),df(b)&&s.push(b),!f)if(m!==void 0||lf(p))f=r.createRenderbuffer(),r.bindRenderbuffer(or,f),m>1?r.renderbufferStorageMultisample(or,m,p,t,n):r.renderbufferStorage(or,p,t,n);else{const d=Object.assign({},c);d.width=t,d.height=n,d.auto===void 0&&(d.auto=!1,d.min=d.min||d.minMag||on,d.mag=d.mag||d.minMag||on,d.wrapS=d.wrapS||d.wrap||nn,d.wrapT=d.wrapT||d.wrap||nn),f=Ii(r,d)}if(xa(r,f))r.framebufferRenderbuffer(i,b,or,f);else if(Mr(r,f))c.layer!==void 0?r.framebufferTextureLayer(i,b,f,c.level||0,c.layer):r.framebufferTexture2D(i,b,c.target||Xl,f,c.level||0);else throw new Error("unknown attachment type");a.attachments.push(f)}),r.drawBuffers&&r.drawBuffers(s),a}function hf(r,e,t){t=t||oo,e?(r.bindFramebuffer(t,e.framebuffer),r.viewport(0,0,e.width,e.height)):(r.bindFramebuffer(t,null),r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight))}function B(r,e){return()=>e instanceof WebGLTexture?e:Ii(r,{src:e,wrap:r.CLAMP_TO_EDGE})}const $e=2;class st{constructor(e){this.id="_";const{context:t,width:n,height:i}=e;this.context=t,this.options=e;const o=this.buildDefines();this.programInfo=Yl(this.context,[o+this.getVertexShader(),o+this.getFragmentShader()]),this.bufferInfo=Va(this.context,this.getBuffers()),this.fbi=lo(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],n,i),this.output=this.fbi.attachments[0]}resizeOutput(e,t){this.fbi=lo(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],e,t),this.options.width=e,this.options.height=t,this.output=this.fbi.attachments[0]}getDefines(){return{}}getBuffers(){return{position:{numComponents:2,data:[-1,-1,-1,1,1,-1,1,1,-1,1,1,-1]},texture_coord:{numComponents:2,data:[0,0,0,1,1,0,1,1,0,1,1,0]}}}buildDefines(){let e="";const t=this.getDefines();for(let n in t)e+=`#define ${n} ${t[n].toFixed(1)}
14
+ `;return e}run(e){this.profiler?.pushContext(`[${this.id}] PROG : ${this.constructor.name}`),this.profiler?.pushContext(`[${this.id}] UNIFORMS`);for(const i in e)typeof e[i]=="function"&&(this.profiler?.pushContext(`[${this.id}] UNI : ${i}`),e[i]=e[i](),this.profiler?.popContext(`[${this.id}] UNI : ${i}`));this.profiler?.popContext(`[${this.id}] UNIFORMS`);const t=Date.now();let n=0;this.lastRun&&(n=(t-this.lastRun)/1e3),this.lastRun=t,this.context.viewport(0,0,this.context.canvas.width,this.context.canvas.height),this.context.useProgram(this.programInfo.program),Hl(this.context,this.programInfo,this.bufferInfo),ro(this.programInfo,{delta:n,canvas:[this.context.canvas.width,this.context.canvas.height],...e}),hf(this.context,this.options.disableFramebuffer?null:this.fbi),ql(this.context,this.bufferInfo),this.profiler?.popContext(`[${this.id}] PROG : ${this.constructor.name}`)}setProfiler(e){this.profiler=e}}const mf=`precision mediump float;
15
15
 
16
16
  varying vec2 _texture_coord;
17
17
 
@@ -26,7 +26,7 @@ void main() {
26
26
  gl_FragColor = foregroundColor * tresholdColor.a +
27
27
  backgroundColor * (1. - tresholdColor.a);
28
28
  }
29
- `,df=`varying vec2 _texture_coord;
29
+ `,pf=`varying vec2 _texture_coord;
30
30
 
31
31
  attribute vec2 position;
32
32
  attribute vec2 texture_coord;
@@ -36,13 +36,13 @@ void main() {
36
36
  _texture_coord = texture_coord;
37
37
  _texture_coord.y = 1. - texture_coord.y;
38
38
  }
39
- `;class an extends st{getFragmentShader(){return ff}getVertexShader(){return df}}class cn{constructor(){this.steps=[]}addStep(e){this.steps.push(e)}async run(){for(const e of this.steps)e.program.run(e.getUniforms())}resizeOutput(e,t){this.profiler?.pushContext(`PIP [${this.constructor.name}]`);for(const n of this.steps)n.preventResize||n.program.resizeOutput(e,t);this.profiler?.popContext(`PIP [${this.constructor.name}]`)}setProfiler(e){this.profiler=e;for(const t of this.steps)t.program.setProfiler(e)}setId(e){for(const t of this.steps)t.program.id=e}}class un extends cn{constructor(){super(...arguments),this.preciseMaskEnabled=!1}}class ho extends un{constructor(e){super(),this.context=e,this.preciseMaskEnabled=!0;const t={context:e,height:e.canvas.height,width:e.canvas.width},n=new an({...t,disableFramebuffer:!0});this.addStep({program:n,getUniforms:()=>({background:B(e,this.inputBackgroundImage),foreground:B(e,this.inputImage),threshold:B(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}const hf=`precision mediump float;
39
+ `;class sn extends st{getFragmentShader(){return mf}getVertexShader(){return pf}}class an{constructor(){this.steps=[]}addStep(e){this.steps.push(e)}async run(){for(const e of this.steps)e.program.run(e.getUniforms())}resizeOutput(e,t){this.profiler?.pushContext(`PIP [${this.constructor.name}]`);for(const n of this.steps)n.preventResize||n.program.resizeOutput(e,t);this.profiler?.popContext(`PIP [${this.constructor.name}]`)}setProfiler(e){this.profiler=e;for(const t of this.steps)t.program.setProfiler(e)}setId(e){for(const t of this.steps)t.program.id=e}}class cn extends an{constructor(){super(...arguments),this.preciseMaskEnabled=!1}}class fo extends cn{constructor(e){super(),this.context=e,this.preciseMaskEnabled=!0;const t={context:e,height:e.canvas.height,width:e.canvas.width},n=new sn({...t,disableFramebuffer:!0});this.addStep({program:n,getUniforms:()=>({background:B(e,this.inputBackgroundImage),foreground:B(e,this.inputImage),threshold:B(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}const gf=`precision mediump float;
40
40
 
41
41
  varying vec2 _texture_coord;
42
42
  uniform sampler2D texture;
43
43
 
44
44
  void main() { gl_FragColor = texture2D(texture, _texture_coord); }
45
- `,mf=`varying vec2 _texture_coord;
45
+ `,yf=`varying vec2 _texture_coord;
46
46
 
47
47
  attribute vec2 position;
48
48
  attribute vec2 texture_coord;
@@ -55,7 +55,7 @@ void main() {
55
55
  _texture_coord.y = 1. - texture_coord.y;
56
56
  }
57
57
  }
58
- `;class pf extends st{getFragmentShader(){return hf}getVertexShader(){return mf}}class gf extends cn{constructor(e,t,n){super(),this.context=e;const i={context:e,height:n,width:t};this.addStep({program:new pf({...i,disableFramebuffer:!0}),getUniforms:()=>({texture:B(e,this.inputImage),invert_y:!0})})}setData(e){this.inputImage=e}}async function mo(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}const yf=`precision mediump float;
58
+ `;class bf extends st{getFragmentShader(){return gf}getVertexShader(){return yf}}class wf extends an{constructor(e,t,n){super(),this.context=e;const i={context:e,height:n,width:t};this.addStep({program:new bf({...i,disableFramebuffer:!0}),getUniforms:()=>({texture:B(e,this.inputImage),invert_y:!0})})}setData(e){this.inputImage=e}}async function ho(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}const xf=`precision mediump float;
59
59
 
60
60
  varying vec2 _texture_coord;
61
61
 
@@ -65,7 +65,7 @@ uniform sampler2D texture;
65
65
  vec4 loop();
66
66
 
67
67
  void main() { gl_FragColor = loop(); }
68
- `,bf=`varying vec2 _texture_coord;
68
+ `,vf=`varying vec2 _texture_coord;
69
69
 
70
70
  attribute vec2 position;
71
71
  attribute vec2 texture_coord;
@@ -74,7 +74,7 @@ void main() {
74
74
  gl_Position = vec4(position, 0., 1.);
75
75
  _texture_coord = texture_coord;
76
76
  }
77
- `;var ln=(r=>(r[r.LINEAR=0]="LINEAR",r[r.GAUSSIAN=1]="GAUSSIAN",r))(ln||{});class po extends st{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return yf+this.createLoopFunction()}getVertexShader(){return bf}createLoopFunction(){let e=this.options.radius??1;return`
77
+ `;var un=(r=>(r[r.LINEAR=0]="LINEAR",r[r.GAUSSIAN=1]="GAUSSIAN",r))(un||{});class mo extends st{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return xf+this.createLoopFunction()}getVertexShader(){return vf}createLoopFunction(){let e=this.options.radius??1;return`
78
78
 
79
79
  vec4 loop() {
80
80
  vec4 result = vec4(0,0,0,0);
@@ -95,7 +95,7 @@ void main() {
95
95
  diff.x = normalizedRadius.x;
96
96
  }
97
97
  return result / factorSum;
98
- }`}}const wf=`#version 300 es
98
+ }`}}const _f=`#version 300 es
99
99
  // https://github.com/Volcomix/virtual-background/blob/main/src/pipelines/webgl2/jointBilateralFilterStage.ts
100
100
 
101
101
  precision highp float;
@@ -141,14 +141,14 @@ void main() {
141
141
  }
142
142
  newVal /= totalWeight;
143
143
  outColor = vec4(vec3(0.), newVal);
144
- }`,xf=`#version 300 es
144
+ }`,Ef=`#version 300 es
145
145
  in vec2 position;
146
146
  in vec2 texture_coord;
147
147
  out vec2 _texture_coord;
148
148
  void main() {
149
149
  gl_Position = vec4(position, 0.0, 1.0);
150
150
  _texture_coord = texture_coord;
151
- }`;class vf extends st{getFragmentShader(){return wf}getVertexShader(){return xf}}class _f extends cn{constructor(e,t,n){super(),this.context=e;const i={context:e,height:n,width:t},o=new po({...i,radius:1,type:ln.GAUSSIAN});this.jointBilateral=new vf(i),this.addStep({program:o,getUniforms:()=>({inputs:B(e,this.inputMask)})}),this.addStep({program:this.jointBilateral,getUniforms:()=>{const a=this.inputImage?.width??1,c=this.inputImage?.height??1;this.inputMask?.width,this.inputMask?.height;const u=3,f=Math.max(1,Math.sqrt(u)*.66),m=1/a,p=1/c;return{input_frame:B(e,this.inputImage),segmentation_mask:B(e,this.inputMask),texel_size:[m,p],step:f,radius:u,offset:f>1?f*.5:0,sigma_texel:Math.max(m,p)*u,sigma_color:u}}}),this.output=this.jointBilateral.output}setData(e,t){this.previousInputImage=this.inputImage?this.inputImage:e,this.previousInputMask=this.inputMask?this.inputMask:t,this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t),this.output=this.jointBilateral.output}}var go=(r=>(r.PUSH="PUSH",r.POP="POP",r))(go||{});class Ef{constructor(e){this.queries=[],this.context=e,this.extension=e.getExtension("EXT_disjoint_timer_query_webgl2")}start(){}stop(){this.activeQuery&&this.context.endQuery(this.extension.TIME_ELAPSED_EXT)}pushContext(e){this.createQuery("PUSH",e)}popContext(e){this.createQuery("POP",e)}createQuery(e,t){this.activeQuery&&this.context.endQuery(this.extension.TIME_ELAPSED_EXT),this.activeQuery=this.context.createQuery(),this.context.beginQuery(this.extension.TIME_ELAPSED_EXT,this.activeQuery),this.queries.push({name:t,action:e,query:this.activeQuery})}async getResolvedQueries(){const e=(await Promise.all([...this.queries].map(t=>this.resolveQuery(t)))).filter(t=>t);for(let t=1;t<e.length;++t)e[t].timestamp+=e[t-1].duration+e[t-1].timestamp;return e}async resolveQuery(e){if(!await this.awaitQueryAvailable(e)){console.log("Unawaitable query",e);return}if(this.context.getParameter(this.extension.GPU_DISJOINT_EXT)){console.log("Disjointed query",e);return}return{...e,duration:this.context.getQueryParameter(e.query,this.context.QUERY_RESULT),timestamp:0}}async awaitQueryAvailable(e){for(let t=0;t<10;++t){if(this.context.getQueryParameter(e.query,this.context.QUERY_RESULT_AVAILABLE))return e;await mo(200)}}}class ar{constructor(){this.previousImageWidth=0,this.previousImageHeight=0,this.previousMaskWidth=We,this.previousMaskHeight=We,this.postProcessingEnabled=!0;const e=new OffscreenCanvas(0,0),t=e.getContext("webgl2");if(!t)throw"Fail to retrieve webgl2 context";this.canvas=e,this.context=t,this.improveMask=new _f(this.context,We,We)}enablePostProcessing(){this.postProcessingEnabled=!0}disablePostProcessing(){this.postProcessingEnabled=!1}async profileWebgl(e){const t=new Ef(this.context);return this.profiler=t,t.start(),await mo(e),this.profiler=void 0,t.stop(),t.getResolvedQueries()}async render(e,t){if(!this.pipeline)throw"missing pipeline";(this.previousImageHeight!==e.height||this.previousImageWidth!==e.width)&&this.resizeOutput(e.width,e.height),(this.previousMaskHeight!==t.height||this.previousMaskWidth!==t.width)&&(this.improveMask.resizeOutput(t.width,t.height),this.previousMaskWidth=t.width,this.previousMaskHeight=t.height);const n="renderer";this.profiler?.pushContext(n),this.improveMask.setProfiler(this.profiler),this.pipeline.setProfiler(this.profiler);const i=await createImageBitmap(t);let o=i;return this.postProcessingEnabled&&(this.improveMask.setData(e,i),this.improveMask.run(),o=this.improveMask.output),this.pipeline.setData(e,o),await this.pipeline.run(),this.profiler?.popContext(n),this.canvas}resizeOutput(e,t){this.canvas.width=e,this.canvas.height=t,this.pipeline?.resizeOutput(e,t),this.previousImageWidth=e,this.previousImageHeight=t}destroy(){const e=this.context?.getExtension("WEBGL_lose_context");e&&e.loseContext()}}class yo extends ar{constructor(){super(),this.pipeline=new ho(this.context);const e=new OffscreenCanvas(0,0),t=e.getContext("webgl2");if(!t)throw"Fail to retrieve webgl context";this.backgroundImageResizerCanvas=e,this.backgroundImageResizerContext=t,this.backgroundImageResizer=new gf(this.backgroundImageResizerContext,0,0)}setBackgroundImage(e){this.backgroundImage=e,this.updateBackgroundImage()}updateBackgroundImage(){const{width:e,height:t}=this.canvas;this.backgroundImageResizer.resizeOutput(e,t),this.backgroundImageResizer.setData(this.backgroundImage),this.backgroundImageResizer.run(),this.pipeline.inputBackgroundImage=this.backgroundImageResizerCanvas}resizeOutput(e,t){super.resizeOutput(e,t),this.backgroundImageResizerCanvas.width=e,this.backgroundImageResizerCanvas.height=t,this.backgroundImageResizer.resizeOutput(e,t),this.updateBackgroundImage()}destroy(){const e=this.backgroundImageResizerContext?.getExtension("WEBGL_lose_context");e&&e.loseContext(),super.destroy()}}class Af extends yo{setBackgroundVideo(e){this.frameReader=e}async render(e,t){return await this.readNextVideoFrame(),super.render(e,t)}async readNextVideoFrame(){const e=await this.frameReader?.read();if(e?.value){const t=await createImageBitmap(e.value);this.setBackgroundImage(t),e.value.close()}}}class bo{blurBackground(e){return new ia(e)}blurSilhouette(e){return new oa(e)}imageBackground(){return new sa}videoBackground(){return new Af}}const Tf=`precision mediump float;
151
+ }`;class Af extends st{getFragmentShader(){return _f}getVertexShader(){return Ef}}class Tf extends an{constructor(e,t,n){super(),this.context=e;const i={context:e,height:n,width:t},o=new mo({...i,radius:1,type:un.GAUSSIAN});this.jointBilateral=new Af(i),this.addStep({program:o,getUniforms:()=>({inputs:B(e,this.inputMask)})}),this.addStep({program:this.jointBilateral,getUniforms:()=>{const a=this.inputImage?.width??1,c=this.inputImage?.height??1;this.inputMask?.width,this.inputMask?.height;const u=3,f=Math.max(1,Math.sqrt(u)*.66),m=1/a,p=1/c;return{input_frame:B(e,this.inputImage),segmentation_mask:B(e,this.inputMask),texel_size:[m,p],step:f,radius:u,offset:f>1?f*.5:0,sigma_texel:Math.max(m,p)*u,sigma_color:u}}}),this.output=this.jointBilateral.output}setData(e,t){this.previousInputImage=this.inputImage?this.inputImage:e,this.previousInputMask=this.inputMask?this.inputMask:t,this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t),this.output=this.jointBilateral.output}}var po=(r=>(r.PUSH="PUSH",r.POP="POP",r))(po||{});class Sf{constructor(e){this.queries=[],this.context=e,this.extension=e.getExtension("EXT_disjoint_timer_query_webgl2")}start(){}stop(){this.activeQuery&&this.context.endQuery(this.extension.TIME_ELAPSED_EXT)}pushContext(e){this.createQuery("PUSH",e)}popContext(e){this.createQuery("POP",e)}createQuery(e,t){this.activeQuery&&this.context.endQuery(this.extension.TIME_ELAPSED_EXT),this.activeQuery=this.context.createQuery(),this.context.beginQuery(this.extension.TIME_ELAPSED_EXT,this.activeQuery),this.queries.push({name:t,action:e,query:this.activeQuery})}async getResolvedQueries(){const e=(await Promise.all([...this.queries].map(t=>this.resolveQuery(t)))).filter(t=>t);for(let t=1;t<e.length;++t)e[t].timestamp+=e[t-1].duration+e[t-1].timestamp;return e}async resolveQuery(e){if(!await this.awaitQueryAvailable(e)){console.log("Unawaitable query",e);return}if(this.context.getParameter(this.extension.GPU_DISJOINT_EXT)){console.log("Disjointed query",e);return}return{...e,duration:this.context.getQueryParameter(e.query,this.context.QUERY_RESULT),timestamp:0}}async awaitQueryAvailable(e){for(let t=0;t<10;++t){if(this.context.getQueryParameter(e.query,this.context.QUERY_RESULT_AVAILABLE))return e;await ho(200)}}}class ar{constructor(){this.previousImageWidth=0,this.previousImageHeight=0,this.previousMaskWidth=$e,this.previousMaskHeight=$e,this.postProcessingEnabled=!0;const e=new OffscreenCanvas(0,0),t=e.getContext("webgl2");if(!t)throw"Fail to retrieve webgl2 context";this.canvas=e,this.context=t,this.improveMask=new Tf(this.context,$e,$e)}enablePostProcessing(){this.postProcessingEnabled=!0}disablePostProcessing(){this.postProcessingEnabled=!1}async profileWebgl(e){const t=new Sf(this.context);return this.profiler=t,t.start(),await ho(e),this.profiler=void 0,t.stop(),t.getResolvedQueries()}async render(e,t){if(!this.pipeline)throw"missing pipeline";(this.previousImageHeight!==e.height||this.previousImageWidth!==e.width)&&this.resizeOutput(e.width,e.height),(this.previousMaskHeight!==t.height||this.previousMaskWidth!==t.width)&&(this.improveMask.resizeOutput(t.width,t.height),this.previousMaskWidth=t.width,this.previousMaskHeight=t.height);const n="renderer";this.profiler?.pushContext(n),this.improveMask.setProfiler(this.profiler),this.pipeline.setProfiler(this.profiler);const i=await createImageBitmap(t);let o=i;return this.postProcessingEnabled&&(this.improveMask.setData(e,i),this.improveMask.run(),o=this.improveMask.output),this.pipeline.setData(e,o),await this.pipeline.run(),this.profiler?.popContext(n),this.canvas}resizeOutput(e,t){this.canvas.width=e,this.canvas.height=t,this.pipeline?.resizeOutput(e,t),this.previousImageWidth=e,this.previousImageHeight=t}destroy(){const e=this.context?.getExtension("WEBGL_lose_context");e&&e.loseContext()}}class go extends ar{constructor(){super(),this.pipeline=new fo(this.context);const e=new OffscreenCanvas(0,0),t=e.getContext("webgl2");if(!t)throw"Fail to retrieve webgl context";this.backgroundImageResizerCanvas=e,this.backgroundImageResizerContext=t,this.backgroundImageResizer=new wf(this.backgroundImageResizerContext,0,0)}setBackgroundImage(e){this.backgroundImage=e,this.updateBackgroundImage()}updateBackgroundImage(){const{width:e,height:t}=this.canvas;this.backgroundImageResizer.resizeOutput(e,t),this.backgroundImageResizer.setData(this.backgroundImage),this.backgroundImageResizer.run(),this.pipeline.inputBackgroundImage=this.backgroundImageResizerCanvas}resizeOutput(e,t){super.resizeOutput(e,t),this.backgroundImageResizerCanvas.width=e,this.backgroundImageResizerCanvas.height=t,this.backgroundImageResizer.resizeOutput(e,t),this.updateBackgroundImage()}destroy(){const e=this.backgroundImageResizerContext?.getExtension("WEBGL_lose_context");e&&e.loseContext(),super.destroy()}}class If extends go{setBackgroundVideo(e){this.frameReader=e}async render(e,t){return await this.readNextVideoFrame(),super.render(e,t)}async readNextVideoFrame(){const e=await this.frameReader?.read();if(e?.value){const t=await createImageBitmap(e.value);this.setBackgroundImage(t),e.value.close()}}}class yo{blurBackground(e){return new aa(e)}blurSilhouette(e){return new ca(e)}imageBackground(){return new ua}videoBackground(){return new If}}const Rf=`precision mediump float;
152
152
 
153
153
  varying vec2 _texture_coord;
154
154
 
@@ -159,7 +159,7 @@ uniform sampler2D mask;
159
159
  vec4 loop();
160
160
 
161
161
  void main() { gl_FragColor = loop(); }
162
- `,Sf=`varying vec2 _texture_coord;
162
+ `,kf=`varying vec2 _texture_coord;
163
163
 
164
164
  attribute vec2 position;
165
165
  attribute vec2 texture_coord;
@@ -168,7 +168,7 @@ void main() {
168
168
  gl_Position = vec4(position, 0., 1.);
169
169
  _texture_coord = texture_coord;
170
170
  }
171
- `;class If extends st{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return Tf+this.createLoopFunction()}getVertexShader(){return Sf}createLoopFunction(){let e=this.options.radius??1;return`
171
+ `;class Pf extends st{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return Rf+this.createLoopFunction()}getVertexShader(){return kf}createLoopFunction(){let e=this.options.radius??1;return`
172
172
 
173
173
  vec4 loop() {
174
174
  vec4 result = vec4(0,0,0,0);
@@ -190,5 +190,5 @@ void main() {
190
190
  diff.x = normalizedRadius.x;
191
191
  }
192
192
  return result / factorSum;
193
- }`}}const kf=10,Rf=2,Pf=8;class Ff extends un{constructor(e,t){super(),this.context=e,this.radius=t;const n={context:e,height:e.canvas.height,width:e.canvas.width};this.blur=new If({...n,radius:t,...this.getBlurTextureSize(e.canvas.width,e.canvas.height)});const i=new an({...n,disableFramebuffer:!0});this.addStep({program:this.blur,preventResize:!0,getUniforms:()=>({texture:B(e,this.inputImage),mask:B(e,this.inputMask)})}),this.addStep({program:i,getUniforms:()=>({background:B(e,this.blur.output),foreground:B(e,this.inputImage),threshold:B(e,this.inputMask)})})}getBlurTextureSize(e,t){const n=this.radius>kf?Pf:Rf;return{width:Math.max(We,e/n),height:Math.max(We,t/n)}}setData(e,t){this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t);const n=this.getBlurTextureSize(e,t);this.blur.resizeOutput(n.width,n.height)}}class Of extends ar{constructor(e){super(),this.pipeline=new Ff(this.context,e),this.disablePostProcessing()}}class Cf extends un{constructor(e,t){super(),this.context=e;const n={context:e,height:e.canvas.height,width:e.canvas.width},i=new po({...n,radius:t,type:ln.GAUSSIAN}),o=new an({...n,disableFramebuffer:!0});this.addStep({program:i,getUniforms:()=>({texture:B(e,this.inputImage)})}),this.addStep({program:o,getUniforms:()=>({background:B(e,this.inputImage),foreground:B(e,i.output),threshold:B(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}class Mf extends ar{constructor(e){super(),this.pipeline=new Cf(this.context,e),this.disablePostProcessing()}}class Bf extends ho{constructor(){super(...arguments),this.preciseMaskEnabled=!0}set reader(e){this.frameReader=e}async run(){this.frameReader&&(await this.readNextVideoFrame(),await super.run())}async readNextVideoFrame(){const e=await this.frameReader?.read();e?.value&&(this.inputBackgroundImage=await createImageBitmap(e.value),e.value.close())}}class Df extends ar{constructor(){super(),this.pipeline=new Bf(this.context)}setBackgroundVideo(e){this.pipeline.reader=e}}class wo{blurBackground(e){return new Of(e)}blurSilhouette(e){return new Mf(e)}imageBackground(){return new yo}videoBackground(){return new Df}}class Uf{constructor(e){switch(e){case je.CANVAS:this.factory=new bo;break;case je.WEBGL:this.factory=new wo;break;default:const t=Bn();this.factory=t.supported?new wo:new bo}}blurBackground(e){return this.getFactory().blurBackground(e)}blurSilhouette(e){return this.getFactory().blurSilhouette(e)}imageBackground(){return this.getFactory().imageBackground()}videoBackground(){return this.getFactory().videoBackground()}getFactory(){if(!this.factory)throw"Factory is not initialized";return this.factory}}class Lf{setBackgroundOptions(e){this.renderer&&this.renderer.destroy();const t=new Uf(e.renderingOptions?.type);switch(e.transformerType){case"BackgroundBlur":this.renderer=t.blurBackground(this.getBlurSize(e.radius));break;case"SilhouetteBlur":this.renderer=t.blurSilhouette(this.getBlurSize(e.radius));break;case"VideoBackground":const n=t.videoBackground();this.backgroundVideo&&n.setBackgroundVideo(this.backgroundVideo),this.renderer=n;break;case"VirtualBackground":const i=t.imageBackground();this.backgroundImage&&i.setBackgroundImage(this.backgroundImage),this.renderer=i;break;default:throw`Unknown rendering type [${e.transformerType}]`}e.renderingOptions?.type===je.WEBGL&&(e.renderingOptions.selfieSegmentationType===_t.PRECISE?this.renderer.enablePostProcessing():e.renderingOptions.selfieSegmentationType===_t.FAST&&this.renderer.disablePostProcessing())}setVideoBGReadable(e){this.backgroundVideo=e.getReader();const t=this.renderer;t?.setBackgroundVideo&&t.setBackgroundVideo(this.backgroundVideo)}async setVirtualBGImage(e){const t=this.renderer;t?.setBackgroundImage&&t.setBackgroundImage(e),this.backgroundImage=e}async process(e,t){if(this.renderer)return this.renderer.render(e,t)}async resizeForeground(e,t){}getBlurSize(e=He.Low){switch(e){case He.Low:return 5;case He.High:return 12}return e}async profile(e){return this.renderer?.profileWebgl(e)??[]}}var zf=(function(){var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return(function(e){e=e||{};var t=typeof e<"u"?e:{},n,i;t.ready=new Promise(function(l,h){n=l,i=h});var o={},s;for(s in t)t.hasOwnProperty(s)&&(o[s]=t[s]);var a="./this.program",c=function(l,h){throw h},u=!0,f="";function m(l){return t.locateFile?t.locateFile(l,f):f+l}var p;typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),r&&(f=r),f.indexOf("blob:")!==0?f=f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):f="";var b=t.print||console.log.bind(console),d=t.printErr||console.warn.bind(console);for(s in o)o.hasOwnProperty(s)&&(t[s]=o[s]);o=null,t.arguments&&t.arguments,t.thisProgram&&(a=t.thisProgram),t.quit&&(c=t.quit);var g;t.wasmBinary&&(g=t.wasmBinary),t.noExitRuntime,typeof WebAssembly!="object"&&fe("no native wasm support detected");var x,v=!1,k=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function O(l,h,y){for(var _=h+y,I=h;l[I]&&!(I>=_);)++I;if(I-h>16&&l.subarray&&k)return k.decode(l.subarray(h,I));for(var C="";h<I;){var E=l[h++];if(!(E&128)){C+=String.fromCharCode(E);continue}var D=l[h++]&63;if((E&224)==192){C+=String.fromCharCode((E&31)<<6|D);continue}var Y=l[h++]&63;if((E&240)==224?E=(E&15)<<12|D<<6|Y:E=(E&7)<<18|D<<12|Y<<6|l[h++]&63,E<65536)C+=String.fromCharCode(E);else{var Po=E-65536;C+=String.fromCharCode(55296|Po>>10,56320|Po&1023)}}return C}function N(l,h){return l?O(at,l,h):""}function J(l,h,y){for(var _=0;_<l.length;++_)lr[h++>>0]=l.charCodeAt(_);lr[h>>0]=0}function Z(l,h){return l%h>0&&(l+=h-l%h),l}var $,lr,at,V;function Eo(l){$=l,t.HEAP8=lr=new Int8Array(l),t.HEAP16=new Int16Array(l),t.HEAP32=V=new Int32Array(l),t.HEAPU8=at=new Uint8Array(l),t.HEAPU16=new Uint16Array(l),t.HEAPU32=new Uint32Array(l),t.HEAPF32=new Float32Array(l),t.HEAPF64=new Float64Array(l)}t.INITIAL_MEMORY;var pn,Ao=[],To=[],So=[];function Jf(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)td(t.preRun.shift());gn(Ao)}function Zf(){gn(To)}function ed(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)nd(t.postRun.shift());gn(So)}function td(l){Ao.unshift(l)}function rd(l){To.unshift(l)}function nd(l){So.unshift(l)}var Te=0,ct=null;function id(l){Te++,t.monitorRunDependencies&&t.monitorRunDependencies(Te)}function od(l){if(Te--,t.monitorRunDependencies&&t.monitorRunDependencies(Te),Te==0&&ct){var h=ct;ct=null,h()}}t.preloadedImages={},t.preloadedAudios={};function fe(l){t.onAbort&&t.onAbort(l),l="Aborted("+l+")",d(l),v=!0,l+=". Build with -s ASSERTIONS=1 for more info.";var h=new WebAssembly.RuntimeError(l);throw i(h),h}var sd="data:application/octet-stream;base64,";function Io(l){return l.startsWith(sd)}var H;H="tflite-simd.wasm",Io(H)||(H=m(H));function ko(l){try{if(l==H&&g)return new Uint8Array(g);if(!p)throw"both async and sync fetching of the wasm failed"}catch(h){fe(h)}}function ad(){return!g&&u&&typeof fetch=="function"?fetch(H,{credentials:"same-origin"}).then(function(l){if(!l.ok)throw"failed to load wasm binary file at '"+H+"'";return l.arrayBuffer()}).catch(function(){return ko(H)}):Promise.resolve().then(function(){return ko(H)})}function cd(){var l={a:Rd};function h(E,D){var Y=E.exports;t.asm=Y,x=t.asm.q,Eo(x.buffer),pn=t.asm.E,rd(t.asm.r),od()}id();function y(E){h(E.instance)}function _(E){return ad().then(function(D){return WebAssembly.instantiate(D,l)}).then(function(D){return D}).then(E,function(D){d("failed to asynchronously prepare wasm: "+D),fe(D)})}function I(){return!g&&typeof WebAssembly.instantiateStreaming=="function"&&!Io(H)&&typeof fetch=="function"?fetch(H,{credentials:"same-origin"}).then(function(E){var D=WebAssembly.instantiateStreaming(E,l);return D.then(y,function(Y){return d("wasm streaming compile failed: "+Y),d("falling back to ArrayBuffer instantiation"),_(y)})}):_(y)}if(t.instantiateWasm)try{var C=t.instantiateWasm(l,h);return C}catch(E){return d("Module.instantiateWasm callback failed with error: "+E),!1}return I().catch(i),{}}function gn(l){for(;l.length>0;){var h=l.shift();if(typeof h=="function"){h(t);continue}var y=h.func;typeof y=="number"?h.arg===void 0?pn.get(y)():pn.get(y)(h.arg):y(h.arg===void 0?null:h.arg)}}function ud(l,h,y,_){fe("Assertion failed: "+N(l)+", at: "+[h?N(h):"unknown filename",y,_?N(_):"unknown function"])}function ld(l,h){fe("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")}function fd(l,h){fe("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")}function dd(){fe("")}var fr;fr=function(){return performance.now()};var hd=!0;function md(l){return V[Ro()>>2]=l,l}function pd(l,h){var y;if(l===0)y=Date.now();else if((l===1||l===4)&&hd)y=fr();else return md(28),-1;return V[h>>2]=y/1e3|0,V[h+4>>2]=y%1e3*1e3*1e3|0,0}function gd(){return 2147483648}function yd(l,h,y){at.copyWithin(l,h,h+y)}function bd(l){try{return x.grow(l-$.byteLength+65535>>>16),Eo(x.buffer),1}catch{}}function wd(l){var h=at.length;l=l>>>0;var y=2147483648;if(l>y)return!1;for(var _=1;_<=4;_*=2){var I=h*(1+.2/_);I=Math.min(I,l+100663296);var C=Math.min(y,Z(Math.max(l,I),65536)),E=bd(C);if(E)return!0}return!1}function xd(l){for(var h=fr();fr()-h<l;);}var yn={};function vd(){return a||"./this.program"}function ut(){if(!ut.strings){var l=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",h={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:l,_:vd()};for(var y in yn)yn[y]===void 0?delete h[y]:h[y]=yn[y];var _=[];for(var y in h)_.push(y+"="+h[y]);ut.strings=_}return ut.strings}var dr={mappings:{},buffers:[null,[],[]],printChar:function(l,h){var y=dr.buffers[l];h===0||h===10?((l===1?b:d)(O(y,0)),y.length=0):y.push(h)},varargs:void 0,get:function(){dr.varargs+=4;var l=V[dr.varargs-4>>2];return l},getStr:function(l){var h=N(l);return h},get64:function(l,h){return l}};function _d(l,h){var y=0;return ut().forEach(function(_,I){var C=h+y;V[l+I*4>>2]=C,J(_,C),y+=_.length+1}),0}function Ed(l,h){var y=ut();V[l>>2]=y.length;var _=0;return y.forEach(function(I){_+=I.length+1}),V[h>>2]=_,0}function Ad(l){Fd(l)}function Td(l){return 0}function Sd(l,h,y,_,I){}function Id(l,h,y,_){for(var I=0,C=0;C<y;C++){for(var E=V[h+C*8>>2],D=V[h+(C*8+4)>>2],Y=0;Y<D;Y++)dr.printChar(l,at[E+Y]);I+=D}return V[_>>2]=I,0}function kd(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var l=new Uint8Array(1);return function(){return crypto.getRandomValues(l),l[0]}}else return function(){fe("randomDevice")}}function hr(l,h){hr.randomDevice||(hr.randomDevice=kd());for(var y=0;y<h;y++)lr[l+y>>0]=hr.randomDevice();return 0}var Rd={a:ud,e:ld,d:fd,b:dd,n:pd,h:gd,l:yd,m:wd,p:xd,f:_d,g:Ed,j:Ad,i:Td,k:Sd,c:Id,o:hr};cd(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.r).apply(null,arguments)},t._getModelBufferMemoryOffset=function(){return(t._getModelBufferMemoryOffset=t.asm.s).apply(null,arguments)},t._getInputMemoryOffset=function(){return(t._getInputMemoryOffset=t.asm.t).apply(null,arguments)},t._getInputHeight=function(){return(t._getInputHeight=t.asm.u).apply(null,arguments)},t._getInputWidth=function(){return(t._getInputWidth=t.asm.v).apply(null,arguments)},t._getInputChannelCount=function(){return(t._getInputChannelCount=t.asm.w).apply(null,arguments)},t._getOutputMemoryOffset=function(){return(t._getOutputMemoryOffset=t.asm.x).apply(null,arguments)},t._getOutputHeight=function(){return(t._getOutputHeight=t.asm.y).apply(null,arguments)},t._getOutputWidth=function(){return(t._getOutputWidth=t.asm.z).apply(null,arguments)},t._getOutputChannelCount=function(){return(t._getOutputChannelCount=t.asm.A).apply(null,arguments)},t._loadModel=function(){return(t._loadModel=t.asm.B).apply(null,arguments)},t._runInference=function(){return(t._runInference=t.asm.C).apply(null,arguments)},t._isGPUEnabled=function(){return(t._isGPUEnabled=t.asm.D).apply(null,arguments)};var Ro=t.___errno_location=function(){return(Ro=t.___errno_location=t.asm.F).apply(null,arguments)},mr;function Pd(l){this.name="ExitStatus",this.message="Program terminated with exit("+l+")",this.status=l}ct=function l(){mr||bn(),mr||(ct=l)};function bn(l){if(Te>0||(Jf(),Te>0))return;function h(){mr||(mr=!0,t.calledRun=!0,!v&&(Zf(),n(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),ed()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),h()},1)):h()}t.run=bn;function Fd(l,h){Od(l)}function Od(l){c(l,new Pd(l))}if(t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();return bn(),e.ready})})();class Nf{constructor(){this.isSIMDSupported=!1,this.isThreadsSupported=!1,this.inputWidth=0,this.inputHeight=0,this.inputChannelCount=0,this.inputMemoryOffset=0,this.outputWidth=0,this.outputHeight=0,this.outputChannelCount=0,this.outputMemoryOffset=0}}const $f="https://d3opqjmqzxf057.cloudfront.net/vonage-tensorflow-wasm/tflite-simd-wasm/1.1.3/",Wf="https://d3opqjmqzxf057.cloudfront.net/ml/selfie_segmentation/4.0.0/selfie_segmentation_landscape.tflite";async function Gf(r=$f,e=Wf){let t=new Nf;var n=new Promise(function(i,o){async function s(){return zf({locateFile:function(u){return r+u}})}async function a(c){return new Promise(async(u,f)=>{const m=c;if(typeof m>"u")return f("TFLite backend unavailable: wasmSimd");let p=e;console.log("TFLite modelUrl: "+p);try{const d=await(await fetch(p)).arrayBuffer();console.log("Model buffer size:",d.byteLength);const g=m._getModelBufferMemoryOffset();console.log("Model buffer memory offset:",g),console.log("Loading model buffer..."),m.HEAPU8.set(new Uint8Array(d),g);const x=m._loadModel(d.byteLength);if(console.log("Load model result:",x),x!==0){f("Cannot load model");return}t.inputWidth=m._getInputWidth(),t.inputHeight=m._getInputHeight(),t.inputChannelCount=m._getInputChannelCount(),t.inputMemoryOffset=m._getInputMemoryOffset(),console.log("Input memory offset:",t.inputMemoryOffset),console.log("Input height:",t.inputHeight),console.log("Input width:",t.inputWidth),console.log("Input channels:",t.inputChannelCount),t.outputMemoryOffset=m._getOutputMemoryOffset(),t.outputWidth=m._getOutputWidth(),t.outputHeight=m._getOutputHeight(),t.outputChannelCount=m._getOutputChannelCount(),console.log("Output memory offset:",t.outputMemoryOffset),console.log("Output height:",t.outputHeight),console.log("Output width:",t.outputWidth),console.log("Output channels:",t.outputChannelCount),t.selectedTFLite=m}catch(b){f(b);return}u()})}s().then(c=>{if(c===null)throw console.error("loadTFLite null"),"loadTFLite null";a(c).then(u=>{i(t)}).catch(u=>{console.error("loadTFLiteModel error"),o("loadTFLiteModel error")})}).catch(c=>{console.error("loadTFLite error:",c),o("loadTFLite error:"+c)})});return n}const Vf=.1,Hf=.7,jf="https://d3opqjmqzxf057.cloudfront.net/ml/vonage_selfie_segmenter/float16/v1/vonage_selfie_segmenter.tflite";class Yf{constructor(){this.canvas=new OffscreenCanvas(0,0),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.width=0,this.height=0,this.gpuDelegate=!0}async createImageSegmenter(){if(!this.ImageSegmenter||!this.wasmFileset){console.warn("Mediapipe objects not loaded");return}this.imageSegmenter=await this.ImageSegmenter.createFromOptions(this.wasmFileset,{baseOptions:{modelAssetPath:this.modelAssetUriPath,delegate:this.gpuDelegate?"GPU":"CPU"},runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!0})}async loadMediapipeAssets(e,t){this.modelAssetUriPath=e||jf;const n=t?`${t}/task-vision.js`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/+esm",i=t?`${t}/wasm`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/wasm",{FilesetResolver:o,ImageSegmenter:s}=await import(n);this.ImageSegmenter=s,this.wasmFileset=await o.forVisionTasks(i)}async init(e,t,n){n===!1&&(this.gpuDelegate=!1),await this.loadMediapipeAssets(e,t),globalThis.document={},await this.createImageSegmenter()}async process(e){if(!this.imageSegmenter){console.warn("ImageSegmenter instance not available");return}(this.width!==e.width||this.height!==e.height)&&(this.canvas.width=this.width=e.width,this.canvas.height=this.height=e.height,this.mask&&(this.mask=new ImageData(this.width,this.height))),this.mask||(this.mask=new ImageData(this.width,this.height)),this.context.drawImage(e,0,0,e.width,e.height);const t=Date.now();let n;try{this.imageSegmenter?.segmentForVideo(this.context.getImageData(0,0,e.width,e.height),t,s=>{n=s.confidenceMasks?.[0]?.getAsFloat32Array()})}catch{await this.createImageSegmenter();return}if(!n)return;if(!this.previousConfidenceMask){this.previousConfidenceMask=n.slice();return}const i=n.map((s,a)=>{const c=this.previousConfidenceMask?.[a];return c!==void 0?this.blend(c,s):s}),o=[255,0,0];for(let s=0;s<i?.length;s++){const a=1-i[s];a>Vf?(a<Hf?(this.mask.data[s*4]=o[0]*a,this.mask.data[s*4+3]=255*a):(this.mask.data[s*4]=o[0],this.mask.data[s*4+3]=255),this.mask.data[s*4+1]=o[1],this.mask.data[s*4+2]=o[2]):this.mask.data[s*4]=this.mask.data[s*4+1]=this.mask.data[s*4+2]=this.mask.data[s*4+3]=0}return this.previousConfidenceMask=i.slice(),this.mask}isGpuSupported(){return!0}blend(e,t){const i=-.748699,o=-57.8051,s=291.309,a=-624.717,c=t-.5,u=c*c,f=1-Math.min(1,u*(5.68842+u*(i+u*(o+u*(s+u*a)))));return t+(e-t)*(f*.9)}}class Qf{constructor(){this.canvas=new OffscreenCanvas(0,0),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.pixelCount=0,this.inputOffset=0,this.outputOffset=0}async init(e,t,n){await this.initWasm(t,e),this.infos&&(this.canvas.width=this.infos.inputWidth,this.canvas.height=this.infos.inputHeight,this.pixelCount=this.infos.inputWidth*this.infos.inputHeight,this.mask=new ImageData(this.infos.inputWidth,this.infos.inputHeight),this.inputOffset=this.infos.inputMemoryOffset/4,this.outputOffset=this.infos.outputMemoryOffset/4)}async initWasm(e,t){this.infos=await Gf(e,t)}async process(e){if(!this.mask||!this.infos)return;const t=this.infos.inputWidth,n=this.infos.inputHeight;this.context.drawImage(e,0,0,e.width,e.height,0,0,t,n);const i=this.context.getImageData(0,0,t,n),o=this.infos.selectedTFLite.HEAPF32;for(let s=0;s<this.pixelCount;s++){const a=this.inputOffset+s*3;o[a]=i.data[s*4]/255,o[a+1]=i.data[s*4+1]/255,o[a+2]=i.data[s*4+2]/255}this.infos.selectedTFLite._runInference();for(let s=0;s<this.pixelCount;s++){const a=this.infos.selectedTFLite.HEAPF32[this.outputOffset+s];this.mask.data[s*4]=this.mask.data[s*4+3]=255*a}return this.mask}isGpuSupported(){return this.infos?.selectedTFLite?._isGPUEnabled()??!1}}class xo{constructor(){this.reporter=new ra,this.isEnabled=!0}async init(e,t){t.segmentationOptions?.lightWeightEngine===!0?this.selfieSegmentation=new Qf:this.selfieSegmentation=new Yf,this.selfieSegmentation?.init(t.modelAssetUriPath,t.mediapipeBaseAssetsUri,t.segmentationOptions?.gpuSupport),this.backgroundFilter=new Lf,this.report({variation:"Create"})}async transform(e,t){if(!this.isEnabled)return t.enqueue(e);let n;const i=e.timestamp??0,o=await createImageBitmap(e),s=await this.selfieSegmentation?.process(o);s&&(n=await this.backgroundFilter?.process(o,s)),n?(e.close(),t.enqueue(new VideoFrame(n,{timestamp:i,alpha:"discard"}))):t.enqueue(e)}async setBackgroundOptions(e){this.backgroundOptions=e,this.backgroundFilter?.setBackgroundOptions(e),this.report({variation:"Update"})}setVideoBGReadable(e){this.backgroundFilter?.setVideoBGReadable(e)}async setVirtualBGImage(e){await this.backgroundFilter?.setVirtualBGImage(e)}async profile(e){return this.backgroundFilter?.profile(e)??[]}getTransformerType(){return this.backgroundOptions?.transformerType??"Undefined"}enable(){this.isEnabled=!0}disable(){this.isEnabled=!1}report(e){this.reporter.send({version:na,action:"MlTransformers",transformerType:this.backgroundOptions?.transformerType,config:JSON.stringify(this.backgroundOptions),...e})}}const hn=class hn{constructor(){this.backgroundTransformer=new xo,this.mediaProcessor=new On,this.rate=30,this.eventsQueue=[],this.frameTransformLatencyMs=[]}async init(e,t){this.frameTransformLatencyMs=[],await this.backgroundTransformer.init(e,t),await this.mediaProcessor.setTransformers([this.backgroundTransformer]),this.mediaProcessor.setTrackExpectedRate(this.rate),this.mediaProcessor.onAny((n,i)=>{this.resolveOnMediaProcessor?(this.resolveOnMediaProcessor({name:n,data:i}),this.resolveOnMediaProcessor=void 0):this.eventsQueue.push({name:n,data:i})})}enable(){this.backgroundTransformer.enable()}disable(){this.backgroundTransformer.disable()}async onMediaProcessorEvent(){return await new Promise(e=>{this.eventsQueue.length>0?e(this.eventsQueue.shift()):this.resolveOnMediaProcessor=e})}async setTrackExpectedRate(e){this.rate=e,this.mediaProcessor.setTrackExpectedRate(e)}async transform(e,t){let n=this.mediaProcessor.transform(e,t),i=performance.now();return this.frameTransformLatencyMs.push(performance.now()-i),n}async setBackgroundOptions(e){await this.backgroundTransformer?.setBackgroundOptions(e)}setVideoBGReadable(e){this.backgroundTransformer.setVideoBGReadable(e)}async setVirtualBGImage(e){await this.backgroundTransformer.setVirtualBGImage(e)}async terminate(){await this.mediaProcessor.destroy();const t=this.frameTransformLatencyMs.reduce((n,i)=>n+i,0)/this.frameTransformLatencyMs.length||0;console.log(`Transform latency average is: ${t} ms`)}setVonageMetadata(e){is(e)}async profile(e){return JSON.stringify(await this.backgroundTransformer.profile(e))}};ks("ProcessorWorker",hn);let fn=hn;const vo='(function(){"use strict";function Vt(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const jr=Vt("globals",{});var xe=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r.EVENT="EVENT",r))(xe||{});function $i(r){return[ImageBitmap,ReadableStream,WritableStream].some(t=>r instanceof t)}function Me(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(s=>$i(s)))}Vt("workerized",{});function Yr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function qe(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],qe(r[t],e[t])):typeof r[t]=="object"?(e[t]={},qe(r[t],e[t])):e[t]=r[t]}const K=new WeakMap,ce=new WeakMap,j=new WeakMap,Ke=Symbol("anyProducer"),Xr=Promise.resolve(),Je=Symbol("listenerAdded"),Ze=Symbol("listenerRemoved");let et=!1,Ht=!1;function _e(r){if(typeof r!="string"&&typeof r!="symbol"&&typeof r!="number")throw new TypeError("`eventName` must be a string, symbol, or number")}function tt(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Ee(r,e){const t=ce.get(r);if(t.has(e))return t.get(e)}function Be(r,e){const t=typeof e=="string"||typeof e=="symbol"||typeof e=="number"?e:Ke,n=j.get(r);if(n.has(t))return n.get(t)}function Wi(r,e,t){const n=j.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(Ke)){const i=Promise.all([e,t]);for(const s of n.get(Ke))s.enqueue(i)}}function Qr(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const s={enqueue(o){i.push(o),n()},finish(){t=!0,n()}};for(const o of e){let a=Be(r,o);a||(a=new Set,j.get(r).set(o,a)),a.add(s)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(o=>{n=o}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(o){i=void 0;for(const a of e){const c=Be(r,a);c&&(c.delete(s),c.size===0&&j.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await o}:{done:!0}},[Symbol.asyncIterator](){return this}}}function qr(r){if(r===void 0)return Kr;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!Kr.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const we=r=>r===Je||r===Ze;function rt(r,e,t){if(we(e))try{et=!0,r.emit(e,t)}finally{et=!1}}class ve{static mixin(e,t){return t=qr(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const o of t)if(n.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 ve}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const s=o=>function(...a){return this[e][o](...a)};for(const o of t)Object.defineProperty(n.prototype,o,{enumerable:!1,value:s(o)});return n}}static get isDebugEnabled(){var e,t;if(typeof((e=globalThis.process)==null?void 0:e.env)!="object")return Ht;const{env:n}=(t=globalThis.process)!=null?t:{env:{}};return n.DEBUG==="emittery"||n.DEBUG==="*"||Ht}static set isDebugEnabled(e){Ht=e}constructor(e={}){var t;K.set(this,new Set),ce.set(this,new Map),j.set(this,new Map),j.get(this).set(Ke,new Set),this.debug=(t=e.debug)!=null?t:{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(n,i,s,o)=>{try{o=JSON.stringify(o)}catch{o=`Object with the following keys failed to stringify: ${Object.keys(o).join(",")}`}(typeof s=="symbol"||typeof s=="number")&&(s=s.toString());const a=new Date,c=`${a.getHours()}:${a.getMinutes()}:${a.getSeconds()}.${a.getMilliseconds()}`;console.log(`[${c}][emittery:${n}][${i}] Event Name: ${s}\n data: ${o}`)})}logIfDebugEnabled(e,t,n){(ve.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t){tt(t),e=Array.isArray(e)?e:[e];for(const n of e){_e(n);let i=Ee(this,n);i||(i=new Set,ce.get(this).set(n,i)),i.add(t),this.logIfDebugEnabled("subscribe",n,void 0),we(n)||rt(this,Je,{eventName:n,listener:t})}return this.off.bind(this,e,t)}off(e,t){tt(t),e=Array.isArray(e)?e:[e];for(const n of e){_e(n);const i=Ee(this,n);i&&(i.delete(t),i.size===0&&ce.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),we(n)||rt(this,Ze,{eventName:n,listener:t})}}once(e){let t;const n=new Promise(i=>{t=this.on(e,s=>{t(),i(s)})});return n.off=t,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)_e(t);return Qr(this,e)}async emit(e,t){var n;if(_e(e),we(e)&&!et)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),Wi(this,e,t);const i=(n=Ee(this,e))!=null?n:new Set,s=K.get(this),o=[...i],a=we(e)?[]:[...s];await Xr,await Promise.all([...o.map(async c=>{if(i.has(c))return c(t)}),...a.map(async c=>{if(s.has(c))return c(e,t)})])}async emitSerial(e,t){var n;if(_e(e),we(e)&&!et)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const i=(n=Ee(this,e))!=null?n:new Set,s=K.get(this),o=[...i],a=[...s];await Xr;for(const c of o)i.has(c)&&await c(t);for(const c of a)s.has(c)&&await c(e,t)}onAny(e){return tt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),K.get(this).add(e),rt(this,Je,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return Qr(this)}offAny(e){tt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),rt(this,Ze,{listener:e}),K.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),typeof t=="string"||typeof t=="symbol"||typeof t=="number"){const n=Ee(this,t);n&&n.clear();const i=Be(this,t);if(i){for(const s of i)s.finish();i.clear()}}else{K.get(this).clear();for(const[n,i]of ce.get(this).entries())i.clear(),ce.get(this).delete(n);for(const[n,i]of j.get(this).entries()){for(const s of i)s.finish();i.clear(),j.get(this).delete(n)}}}listenerCount(e){var t,n,i,s,o,a;e=Array.isArray(e)?e:[e];let c=0;for(const u of e){if(typeof u=="string"){c+=K.get(this).size+((n=(t=Ee(this,u))==null?void 0:t.size)!=null?n:0)+((s=(i=Be(this,u))==null?void 0:i.size)!=null?s:0)+((a=(o=Be(this))==null?void 0:o.size)!=null?a:0);continue}typeof u<"u"&&_e(u),c+=K.get(this).size;for(const d of ce.get(this).values())c+=d.size;for(const d of j.get(this).values())c+=d.size}return c}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=qr(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \\`${n}\\` already exists on \\`target\\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const Kr=Object.getOwnPropertyNames(ve.prototype).filter(r=>r!=="constructor");Object.defineProperty(ve,"listenerAdded",{value:Je,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(ve,"listenerRemoved",{value:Ze,writable:!1,enumerable:!0,configurable:!1});function Vi(r){return r.onAny&&r.emit}async function Hi(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Me(r,await e.instance[t](...n??[]))}const Jr=Vt("registeredWorkers",{});function ji(r,e){e.workerId=r,Yr()&&(Jr[e.workerId]=e)}function Yi(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=Jr[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;qe(n,jr),Vi(e.instance)&&e.instance.onAny((s,o)=>{Me({type:xe.EVENT},{name:s,data:o})}),Me(r,typeof e.instance!==void 0)}async function Xi(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Me(r,n)}function Qi(r){if(!r.args)throw"Missing globals while syncing";qe(r.args[0],jr),Me(r,{})}function qi(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case xe.INIT:Yi(t,r);break;case xe.FORWARD:Hi(t,r);break;case xe.TERMINATE:Xi(t,r);break;case xe.GLOBALS_SYNC:Qi(t);break}}}Yr()&&qi();var jt;self.MediaStreamTrackProcessor||(self.MediaStreamTrackProcessor=(jt=class{constructor(r){const e=r.track??r;e.kind=="video"?this.readable=new ReadableStream({async start(t){e.addEventListener("ended",()=>t.close(),{once:!0}),this.video=document.createElement("video"),this.video.srcObject=new MediaStream([e]),await Promise.all([this.video.play(),new Promise(n=>this.video.onloadedmetadata=n)]),this.track=e,this.canvas=new OffscreenCanvas(this.video.videoWidth,this.video.videoHeight),this.ctx=this.canvas.getContext("2d",{desynchronized:!0}),this.t1=performance.now()},async pull(t){if(e.readyState=="ended")return t.close();const n=e.getSettings().frameRate||30;for(;performance.now()-this.t1<1e3/n;)if(await new Promise(i=>requestAnimationFrame(i)),e.readyState=="ended")return t.close();this.canvas.width=this.video.videoWidth,this.canvas.height=this.video.videoHeight,this.t1=performance.now(),this.ctx.drawImage(this.video,0,0),t.enqueue(new VideoFrame(this.canvas,{timestamp:this.t1}))}}):e.kind=="audio"&&(this.readable=new ReadableStream({async start(t){e.addEventListener("ended",()=>t.close(),{once:!0}),this.ac=new AudioContext,this.arrays=[];function n(){registerProcessor("mstp-shim",class extends AudioWorkletProcessor{process(i){return this.port.postMessage(i),!0}})}await this.ac.audioWorklet.addModule(`data:text/javascript,(${n.toString()})()`),this.node=new AudioWorkletNode(this.ac,"mstp-shim"),this.ac.createMediaStreamSource(new MediaStream([e])).connect(this.node),this.node.port.addEventListener("message",({data:i})=>i[0][0]&&this.arrays.push(i))},async pull(t){if(e.readyState=="ended")return t.close();for(;!this.arrays.length;)if(await new Promise(s=>this.node.port.onmessage=s),e.readyState=="ended")return t.close();const[n]=this.arrays.shift(),i=new Float32Array(n.reduce((s,o)=>s+o.length,0));n.reduce((s,o)=>(i.set(o,s),s+o.length),0),t.enqueue(new AudioData({format:"f32-planar",sampleRate:this.ac.sampleRate,numberOfFrames:n[0].length,numberOfChannels:n.length,timestamp:this.ac.currentTime*1e6|0,data:i,transfer:[i.buffer]}))}}))}},jt.__POLYFILLED=!0,jt));var Yt;self.MediaStreamTrackGenerator||(self.MediaStreamTrackGenerator=(Yt=class{constructor({kind:r}){if(r=="video"){const e=document.createElement("canvas"),t=e.getContext("2d",{desynchronized:!0}),n=e.captureStream().getVideoTracks()[0];return n.writable=new WritableStream({write(i){e.width=i.displayWidth,e.height=i.displayHeight,t.drawImage(i,0,0,e.width,e.height),i.close()}}),n}else if(r=="audio"){const e=new AudioContext,t=e.createMediaStreamDestination(),[n]=t.stream.getAudioTracks();return n.writable=new WritableStream({async start(i){this.arrays=[];function s(){registerProcessor("mstg-shim",class extends AudioWorkletProcessor{constructor(){super(),this.arrays=[],this.arrayOffset=0,this.port.onmessage=({data:o})=>this.arrays.push(o),this.emptyArray=new Float32Array(0)}process(o,[[a]]){for(let c=0;c<a.length;c++)(!this.array||this.arrayOffset>=this.array.length)&&(this.array=this.arrays.shift()||this.emptyArray,this.arrayOffset=0),a[c]=this.array[this.arrayOffset++]||0;return!0}})}return await e.audioWorklet.addModule(`data:text/javascript,(${s.toString()})()`),this.node=new AudioWorkletNode(e,"mstg-shim"),this.node.connect(t),n},write(i){const s=new Float32Array(i.numberOfFrames*i.numberOfChannels);i.copyTo(s,{planeIndex:0}),this.node.port.postMessage(s,[s.buffer]),i.close()}}),n}}},Yt.__POLYFILLED=!0,Yt));const J=new WeakMap,ue=new WeakMap,Y=new WeakMap,nt=Symbol("anyProducer"),Zr=Promise.resolve(),it=Symbol("listenerAdded"),st=Symbol("listenerRemoved");let ot=!1,Xt=!1;const at=r=>typeof r=="string"||typeof r=="symbol"||typeof r=="number";function Te(r){if(!at(r))throw new TypeError("`eventName` must be a string, symbol, or number")}function ct(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Ae(r,e){const t=ue.get(r);if(t.has(e))return t.get(e)}function De(r,e){const t=at(e)?e:nt,n=Y.get(r);if(n.has(t))return n.get(t)}function Ki(r,e,t){const n=Y.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(nt)){const i=Promise.all([e,t]);for(const s of n.get(nt))s.enqueue(i)}}function en(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const s={enqueue(o){i.push(o),n()},finish(){t=!0,n()}};for(const o of e){let a=De(r,o);a||(a=new Set,Y.get(r).set(o,a)),a.add(s)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(o=>{n=o}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(o){i=void 0;for(const a of e){const c=De(r,a);c&&(c.delete(s),c.size===0&&Y.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await o}:{done:!0}},[Symbol.asyncIterator](){return this}}}function tn(r){if(r===void 0)return rn;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!rn.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const Se=r=>r===it||r===st;function ut(r,e,t){if(Se(e))try{ot=!0,r.emit(e,t)}finally{ot=!1}}class X{static mixin(e,t){return t=tn(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const o of t)if(n.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 X}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const s=o=>function(...a){return this[e][o](...a)};for(const o of t)Object.defineProperty(n.prototype,o,{enumerable:!1,value:s(o)});return n}}static get isDebugEnabled(){if(typeof globalThis.process?.env!="object")return Xt;const{env:e}=globalThis.process??{env:{}};return e.DEBUG==="emittery"||e.DEBUG==="*"||Xt}static set isDebugEnabled(e){Xt=e}constructor(e={}){J.set(this,new Set),ue.set(this,new Map),Y.set(this,new Map),Y.get(this).set(nt,new Set),this.debug=e.debug??{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(t,n,i,s)=>{try{s=JSON.stringify(s)}catch{s=`Object with the following keys failed to stringify: ${Object.keys(s).join(",")}`}(typeof i=="symbol"||typeof i=="number")&&(i=i.toString());const o=new Date,a=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${a}][emittery:${t}][${n}] Event Name: ${i}\n data: ${s}`)})}logIfDebugEnabled(e,t,n){(X.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t,{signal:n}={}){ct(t),e=Array.isArray(e)?e:[e];for(const s of e){Te(s);let o=Ae(this,s);o||(o=new Set,ue.get(this).set(s,o)),o.add(t),this.logIfDebugEnabled("subscribe",s,void 0),Se(s)||ut(this,it,{eventName:s,listener:t})}const i=()=>{this.off(e,t),n?.removeEventListener("abort",i)};return n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i(),i}off(e,t){ct(t),e=Array.isArray(e)?e:[e];for(const n of e){Te(n);const i=Ae(this,n);i&&(i.delete(t),i.size===0&&ue.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),Se(n)||ut(this,st,{eventName:n,listener:t})}}once(e,t){if(t!==void 0&&typeof t!="function")throw new TypeError("predicate must be a function");let n;const i=new Promise(s=>{n=this.on(e,o=>{t&&!t(o)||(n(),s(o))})});return i.off=n,i}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Te(t);return en(this,e)}async emit(e,t){if(Te(e),Se(e)&&!ot)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),Ki(this,e,t);const n=Ae(this,e)??new Set,i=J.get(this),s=[...n],o=Se(e)?[]:[...i];await Zr,await Promise.all([...s.map(async a=>{if(n.has(a))return a(t)}),...o.map(async a=>{if(i.has(a))return a(e,t)})])}async emitSerial(e,t){if(Te(e),Se(e)&&!ot)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const n=Ae(this,e)??new Set,i=J.get(this),s=[...n],o=[...i];await Zr;for(const a of s)n.has(a)&&await a(t);for(const a of o)i.has(a)&&await a(e,t)}onAny(e,{signal:t}={}){ct(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),J.get(this).add(e),ut(this,it,{listener:e});const n=()=>{this.offAny(e),t?.removeEventListener("abort",n)};return t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n(),n}anyEvent(){return en(this)}offAny(e){ct(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),ut(this,st,{listener:e}),J.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),at(t)){const n=Ae(this,t);n&&n.clear();const i=De(this,t);if(i){for(const s of i)s.finish();i.clear()}}else{J.get(this).clear();for(const[n,i]of ue.get(this).entries())i.clear(),ue.get(this).delete(n);for(const[n,i]of Y.get(this).entries()){for(const s of i)s.finish();i.clear(),Y.get(this).delete(n)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const n of e){if(at(n)){t+=J.get(this).size+(Ae(this,n)?.size??0)+(De(this,n)?.size??0)+(De(this)?.size??0);continue}n!==void 0&&Te(n),t+=J.get(this).size;for(const i of ue.get(this).values())t+=i.size;for(const i of Y.get(this).values())t+=i.size}return t}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=tn(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \\`${n}\\` already exists on \\`target\\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const rn=Object.getOwnPropertyNames(X.prototype).filter(r=>r!=="constructor");Object.defineProperty(X,"listenerAdded",{value:it,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(X,"listenerRemoved",{value:st,writable:!1,enumerable:!0,configurable:!1});var Ji=Object.defineProperty,Zi=(r,e,t)=>e in r?Ji(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,es=(r,e,t)=>(Zi(r,e+"",t),t);const ts="hlg.tokbox.com/prod/logging/vcp_webrtc",rs="https://",ns=1e4;let ft;const is=new Uint8Array(16);function ss(){if(!ft&&(ft=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ft))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ft(is)}const F=[];for(let r=0;r<256;++r)F.push((r+256).toString(16).slice(1));function os(r,e=0){return(F[r[e+0]]+F[r[e+1]]+F[r[e+2]]+F[r[e+3]]+"-"+F[r[e+4]]+F[r[e+5]]+"-"+F[r[e+6]]+F[r[e+7]]+"-"+F[r[e+8]]+F[r[e+9]]+"-"+F[r[e+10]]+F[r[e+11]]+F[r[e+12]]+F[r[e+13]]+F[r[e+14]]+F[r[e+15]]).toLowerCase()}const as=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),nn={randomUUID:as};function cs(r,e,t){if(nn.randomUUID&&!r)return nn.randomUUID();r=r||{};const n=r.random||(r.rng||ss)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,os(n)}function Qt(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const Z=Qt("globals",{});var fe=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r))(fe||{});function sn(r){return[ImageBitmap,ReadableStream,WritableStream].some(e=>r instanceof e)}let us=0;function fs(r,e,t,n,i){const s=us++;return r.postMessage({id:s,type:e,functionName:t,args:n},n.filter(o=>sn(o))),new Promise(o=>{i?.set(s,o)})}function Oe(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(s=>sn(s)))}const on=Qt("workerized",{});function an(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function ls(){if(an())Oe({type:fe.GLOBALS_SYNC},Z);else{const r=[];for(const e in on){const{worker:t,resolvers:n}=on[e].workerContext;t&&r.push(fs(t,fe.GLOBALS_SYNC,"",[Z],n))}await Promise.all(r)}}function lt(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],lt(r[t],e[t])):typeof r[t]=="object"?(e[t]={},lt(r[t],e[t])):e[t]=r[t]}async function ds(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Oe(r,await e.instance[t](...n??[]))}const hs=Qt("registeredWorkers",{});function ms(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=hs[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;lt(n,Z),Oe(r,typeof e.instance!==void 0)}async function ps(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Oe(r,n)}function gs(r){if(!r.args)throw"Missing globals while syncing";lt(r.args[0],Z),Oe(r,{})}function ys(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case fe.INIT:ms(t,r);break;case fe.FORWARD:ds(t,r);break;case fe.TERMINATE:ps(t,r);break;case fe.GLOBALS_SYNC:gs(t);break}}}an()&&ys();function bs(r,e){return Z[r]||(Z[r]=e),[()=>Z[r],async t=>{Z[r]=t,await ls()}]}function xs(r,e){return bs(r,e)}const[_s,Es]=xs("metadata");function ws(r){Es(r)}function qt(){return _s()}let Kt=class{constructor(e,t){es(this,"uuid"),this.config=e,this.uuid=t??cs()}async send(e){var t,n,i;const{appId:s,sourceType:o}=(t=qt())!=null?t:{};if(!s||!o)return"metadata missing";const a=new AbortController,c=setTimeout(()=>a.abort(),ns);return await((i=(n=this.config)==null?void 0:n.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(c),"success"}getUrl(){var e;let t=(e=qt().proxyUrl)!=null?e:rs;return t+=(t.at(-1)==="/"?"":"/")+ts,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=qt();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}};const dt="3.0.0",Jt=class{};Jt.updates={transformer_new:"New transformer",transformer_null:"Null transformer"},Jt.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"};let le=Jt;function vs(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function Ts(r){if(vs(r))return r;try{return new Error(JSON.stringify(r))}catch{return new Error(String(r))}}function Zt(r){return Ts(r).message}class As{constructor(e,t){this.config=e,this.frameTransformedCount=0,this.frameFromSourceCount=0,this.startAt=0,this.reporter=new Kt(e,t)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:t}=this,n=(Date.now()-e)/1e3;return t/n}async onFrameTransformed(e={},t=!1){this.startAt===0&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:n,frameTransformedCount:i,frameFromSourceCount:s}=this,o=Date.now(),a=(o-n)/1e3,c=i/a,u=s/a;return t||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:u,transformedFps:c,framesTransformed:i,...e})):"success"}}var er=(r=>(r.pipeline_ended="pipeline_ended",r.pipeline_ended_with_error="pipeline_ended_with_error",r.pipeline_started="pipeline_started",r.pipeline_started_with_error="pipeline_started_with_error",r.pipeline_restarted="pipeline_restarted",r.pipeline_restarted_with_error="pipeline_restarted_with_error",r))(er||{});const Ss=500,Is=.8;class Rs extends X{constructor(e,t){super(),this.reporter_=new Kt,this.reporterQos_=new As({loggingIntervalFrameCount:Ss,report:{version:dt}}),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_&&typeof this.transformer_.start=="function")try{await this.transformer_.start(e)}catch(t){this.report({message:le.errors.transformer_start,variation:"Error",error:Zt(t)});const n={eventMetaData:{transformerIndex:this.index_},error:t,function:"start"};this.emit("error",n)}}async transform(e,t){if(this.mediaTransformerQosReportStartTimestamp_===0&&(this.mediaTransformerQosReportStartTimestamp_=Date.now()),e instanceof VideoFrame&&(this.videoHeight_=e?.displayHeight??0,this.videoWidth_=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 this.transformer_.transform?.(e,t),this.reportQos()}catch(n){this.report({message:le.errors.transformer_transform,variation:"Error",error:Zt(n)});const i={eventMetaData:{transformerIndex:this.index_},error:n,function:"transform"};this.emit("error",i)}if(this.trackExpectedRate_!=-1&&this.trackExpectedRate_*Is>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(t){this.report({message:le.errors.transformer_flush,variation:"Error",error:Zt(t)});const n={eventMetaData:{transformerIndex:this.index_},error:t,function:"flush"};this.emit("error",n)}}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:dt,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:dt,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class Fs extends X{constructor(e){super(),this.transformers_=[],this.trackExpectedRate_=-1;for(let t=0;t<e.length;t++){let n=new Rs(e[t],t);n.on("error",i=>{this.emit("error",i)}),n.on("warn",i=>{this.emit("warn",i)}),this.transformers_.push(n)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let t of this.transformers_)t.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,t){if(!this.transformers_||this.transformers_.length===0){console.log("[Pipeline] No transformers.");return}try{let n=e;for(let i of this.transformers_)e=e.pipeThrough(new TransformStream(i));e.pipeTo(t).then(async()=>{console.log("[Pipeline] Setup."),await t.abort(),await n.cancel(),this.emit("pipelineInfo","pipeline_ended")}).catch(async i=>{e.cancel().then(()=>{console.log("[Pipeline] Shutting down streams after abort.")}).catch(s=>{console.error("[Pipeline] Error from stream transform:",s)}),await t.abort(i),await n.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 Ps extends X{constructor(){super(),this.reporter_=new Kt,this.trackExpectedRate_=-1,this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e,this.pipeline_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_)}async transform(e,t){if(this.isTrack(e)){if(e.kind==="video"){const n=new MediaStreamTrackProcessor({track:e}),i=new VideoTrackGenerator;return this.readable_=n.readable,this.writable_=i.writable,await this.transformInternal(),i.track}throw Error("Cannot process audio tracks inside a web worker when passing a track to transform")}else return this.readable_=e,this.writable_=t,this.transformInternal()}transformInternal(){return new Promise(async(e,t)=>{if(!this.transformers_||this.transformers_.length===0){this.report({message:le.errors.transformer_none,variation:"Error"}),t("[MediaProcessor] Need to set transformers.");return}if(!this.readable_){this.report({variation:"Error",message:le.errors.readable_null}),t("[MediaProcessor] Readable is null.");return}if(!this.writable_){this.report({variation:"Error",message:le.errors.writable_null}),t("[MediaProcessor] Writable is null.");return}let n=!1;this.pipeline_&&(n=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new Fs(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=>{n&&(i==="pipeline_started"?i=er.pipeline_restarted:i==="pipeline_started_with_error"&&(i=er.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=>{t(i)})})}setTransformers(e){return this.report({variation:"Update",message:le.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:dt,action:"MediaProcessor",...e})}isTrack(e){return"kind"in e}}var ks=Object.defineProperty,Cs=(r,e,t)=>e in r?ks(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ms=(r,e,t)=>(Cs(r,e+"",t),t);const Bs="hlg.tokbox.com/prod/logging/vcp_webrtc",Ds="https://",Os=1e4;let ht;const Us=new Uint8Array(16);function Ns(){if(!ht&&(ht=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ht))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ht(Us)}const P=[];for(let r=0;r<256;++r)P.push((r+256).toString(16).slice(1));function Ls(r,e=0){return(P[r[e+0]]+P[r[e+1]]+P[r[e+2]]+P[r[e+3]]+"-"+P[r[e+4]]+P[r[e+5]]+"-"+P[r[e+6]]+P[r[e+7]]+"-"+P[r[e+8]]+P[r[e+9]]+"-"+P[r[e+10]]+P[r[e+11]]+P[r[e+12]]+P[r[e+13]]+P[r[e+14]]+P[r[e+15]]).toLowerCase()}const zs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),cn={randomUUID:zs};function Gs(r,e,t){if(cn.randomUUID&&!e&&!r)return cn.randomUUID();r=r||{};const n=r.random||(r.rng||Ns)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Ls(n)}function tr(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const ee=tr("globals",{});var de=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r))(de||{});function un(r){return[ImageBitmap,ReadableStream,WritableStream].some(e=>r instanceof e)}let $s=0;function Ws(r,e,t,n,i){const s=$s++;return r.postMessage({id:s,type:e,functionName:t,args:n},n.filter(o=>un(o))),new Promise(o=>{i?.set(s,o)})}function Ue(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(s=>un(s)))}const fn=tr("workerized",{});function ln(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function Vs(){if(ln())Ue({type:de.GLOBALS_SYNC},ee);else{const r=[];for(const e in fn){const{worker:t,resolvers:n}=fn[e].workerContext;t&&r.push(Ws(t,de.GLOBALS_SYNC,"",[ee],n))}await Promise.all(r)}}function mt(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],mt(r[t],e[t])):typeof r[t]=="object"?(e[t]={},mt(r[t],e[t])):e[t]=r[t]}async function Hs(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Ue(r,await e.instance[t](...n??[]))}const js=tr("registeredWorkers",{});function Ys(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=js[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;mt(n,ee),Ue(r,typeof e.instance!==void 0)}async function Xs(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Ue(r,n)}function Qs(r){if(!r.args)throw"Missing globals while syncing";mt(r.args[0],ee),Ue(r,{})}function qs(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case de.INIT:Ys(t,r);break;case de.FORWARD:Hs(t,r);break;case de.TERMINATE:Xs(t,r);break;case de.GLOBALS_SYNC:Qs(t);break}}}ln()&&qs();function Ks(r,e){return ee[r]||(ee[r]=e),[()=>ee[r],async t=>{ee[r]=t,await Vs()}]}function Js(r,e){return Ks(r,e)}const[Zs]=Js("metadata");function rr(){return Zs()}class eo{constructor(e){Ms(this,"uuid",Gs()),this.config=e}async send(e){var t,n,i;const{appId:s,sourceType:o}=(t=rr())!=null?t:{};if(!s||!o)return"metadata missing";const a=new AbortController,c=setTimeout(()=>a.abort(),Os);return await((i=(n=this.config)==null?void 0:n.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(c),"success"}getUrl(){var e;let t=(e=rr().proxyUrl)!=null?e:Ds;return t+=(t.at(-1)==="/"?"":"/")+Bs,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=rr();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}}const to="7.0.0-alpha.2";var pt=(r=>(r.Low="Low",r.High="High",r))(pt||{}),nr=(r=>(r.FAST="FAST",r.PRECISE="PRECISE",r))(nr||{}),gt=(r=>(r.CANVAS="CANVAS",r.WEBGL="WEBGL",r))(gt||{});function ro(){const e=new OffscreenCanvas(0,0).getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(e){const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}else return{supported:!1,message:"Your hardware does not perform good enough to run the library efficiently"};return{supported:!0}}class ir{constructor(){const e=new OffscreenCanvas(0,0),t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw"Fail to retrieve 2d context";this.canvas=e,this.context=t}enablePostProcessing(){}disablePostProcessing(){}async profileWebgl(e){return[]}async render(e,t){return this.canvas}resizeCanvas(e){const{width:t,height:n}=e;this.canvas.width=t,this.canvas.height=n}renderSilhouette(e,t,n="none"){const{width:i,height:s}=e;this.context.save(),this.context.drawImage(t,0,0,t.width,t.height,0,0,i,s),this.context.filter="blur(5px)",this.context.globalCompositeOperation="source-in",this.context.drawImage(t,0,0,t.width,t.height,0,0,i,s),this.context.globalCompositeOperation="source-in",this.context.filter=n,this.context.drawImage(e,0,0,i,s,0,0,this.canvas.width,this.canvas.height),this.context.restore()}destroy(){}}class no extends ir{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n),this.context.save(),this.context.filter=`blur(${this.radius}px)`,this.context.globalCompositeOperation="destination-over",this.context.drawImage(e,0,0,e.width,e.height),this.context.restore(),super.render(e,t)}}class io extends ir{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n,`blur(${this.radius}px)`),this.context.save(),this.context.filter="none",this.context.globalCompositeOperation="destination-over",this.context.drawImage(e,0,0,e.width,e.height),this.context.restore(),super.render(e,t)}}class so extends ir{setBackgroundImage(e){this.backgroundImage=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n),this.backgroundImage&&(this.context.save(),this.context.filter="none",this.context.globalCompositeOperation="destination-over",this.context.drawImage(this.backgroundImage,0,0,this.backgroundImage.width,this.backgroundImage.height,0,0,e.width,e.height),this.context.restore()),super.render(e,t)}}const sr=5120,Ne=5121,or=5122,ar=5123,cr=5124,ur=5125,fr=5126,oo=32819,ao=32820,co=33635,uo=5131,fo=33640,lo=35899,ho=35902,mo=36269,po=34042,dn={};{const r=dn;r[sr]=Int8Array,r[Ne]=Uint8Array,r[or]=Int16Array,r[ar]=Uint16Array,r[cr]=Int32Array,r[ur]=Uint32Array,r[fr]=Float32Array,r[oo]=Uint16Array,r[ao]=Uint16Array,r[co]=Uint16Array,r[uo]=Uint16Array,r[fo]=Uint32Array,r[lo]=Uint32Array,r[ho]=Uint32Array,r[mo]=Uint32Array,r[po]=Uint32Array}function lr(r){if(r instanceof Int8Array)return sr;if(r instanceof Uint8Array||r instanceof Uint8ClampedArray)return Ne;if(r instanceof Int16Array)return or;if(r instanceof Uint16Array)return ar;if(r instanceof Int32Array)return cr;if(r instanceof Uint32Array)return ur;if(r instanceof Float32Array)return fr;throw new Error("unsupported typed array type")}function hn(r){if(r===Int8Array)return sr;if(r===Uint8Array||r===Uint8ClampedArray)return Ne;if(r===Int16Array)return or;if(r===Uint16Array)return ar;if(r===Int32Array)return cr;if(r===Uint32Array)return ur;if(r===Float32Array)return fr;throw new Error("unsupported typed array type")}function mn(r){const e=dn[r];if(!e)throw new Error("unknown gl type");return e}const yt=typeof SharedArrayBuffer<"u"?function(e){return e&&e.buffer&&(e.buffer instanceof ArrayBuffer||e.buffer instanceof SharedArrayBuffer)}:function(e){return e&&e.buffer&&e.buffer instanceof ArrayBuffer};function pn(...r){console.error(...r)}const gn=new Map;function bt(r,e){if(!r||typeof r!="object")return!1;let t=gn.get(e);t||(t=new WeakMap,gn.set(e,t));let n=t.get(r);if(n===void 0){const i=Object.prototype.toString.call(r);n=i.substring(8,i.length-1)===e,t.set(r,n)}return n}function go(r,e){return typeof WebGLBuffer<"u"&&bt(e,"WebGLBuffer")}function yo(r,e){return typeof WebGLRenderbuffer<"u"&&bt(e,"WebGLRenderbuffer")}function dr(r,e){return typeof WebGLTexture<"u"&&bt(e,"WebGLTexture")}function bo(r,e){return typeof WebGLSampler<"u"&&bt(e,"WebGLSampler")}const yn=35044,he=34962,xo=34963,_o=34660,Eo=5120,wo=5121,vo=5122,To=5123,Ao=5124,So=5125,bn=5126,xn={attribPrefix:""};function Io(r,e,t,n,i){r.bindBuffer(e,t),r.bufferData(e,n,i||yn)}function _n(r,e,t,n){if(go(r,e))return e;t=t||he;const i=r.createBuffer();return Io(r,t,i,e,n),i}function En(r){return r==="indices"}function Ro(r){return r===Int8Array||r===Uint8Array}function Fo(r){return r.length?r:r.data}const Po=/coord|texture/i,ko=/color|colour/i;function Co(r,e){let t;if(Po.test(r)?t=2:ko.test(r)?t=4:t=3,e%t>0)throw new Error(`Can not guess numComponents for attribute \'${r}\'. Tried ${t} but ${e} values is not evenly divisible by ${t}. You should specify it.`);return t}function Mo(r,e,t){return r.numComponents||r.size||Co(e,t||Fo(r).length)}function wn(r,e){if(yt(r))return r;if(yt(r.data))return r.data;Array.isArray(r)&&(r={data:r});let t=r.type?hr(r.type):void 0;return t||(En(e)?t=Uint16Array:t=Float32Array),new t(r.data)}function Bo(r){return typeof r=="number"?r:r?hn(r):bn}function hr(r){return typeof r=="number"?mn(r):r||Float32Array}function Do(r,e){return{buffer:e.buffer,numValues:24,type:Bo(e.type),arrayType:hr(e.type)}}function Oo(r,e){const t=e.data||e,n=hr(e.type),i=t*n.BYTES_PER_ELEMENT,s=r.createBuffer();return r.bindBuffer(he,s),r.bufferData(he,i,e.drawType||yn),{buffer:s,numValues:t,type:hn(n),arrayType:n}}function Uo(r,e,t){const n=wn(e,t);return{arrayType:n.constructor,buffer:_n(r,n,void 0,e.drawType),type:lr(n),numValues:0}}function No(r,e){const t={};return Object.keys(e).forEach(function(n){if(!En(n)){const i=e[n],s=i.attrib||i.name||i.attribName||xn.attribPrefix+n;if(i.value){if(!Array.isArray(i.value)&&!yt(i.value))throw new Error("array.value is not array or typedarray");t[s]={value:i.value}}else{let o;i.buffer&&i.buffer instanceof WebGLBuffer?o=Do:typeof i=="number"||typeof i.data=="number"?o=Oo:o=Uo;const{buffer:a,type:c,numValues:u,arrayType:d}=o(r,i,n),m=i.normalize!==void 0?i.normalize:Ro(d),p=Mo(i,n,u);t[s]={buffer:a,numComponents:p,type:c,normalize:m,stride:i.stride||0,offset:i.offset||0,divisor:i.divisor===void 0?void 0:i.divisor,drawType:i.drawType}}}}),r.bindBuffer(he,null),t}function Lo(r,e){return e===Eo||e===wo?1:e===vo||e===To?2:e===Ao||e===So||e===bn?4:0}const mr=["position","positions","a_position"];function zo(r,e){let t,n;for(n=0;n<mr.length&&(t=mr[n],!(t in e||(t=xn.attribPrefix+t,t in e)));++n);n===mr.length&&(t=Object.keys(e)[0]);const i=e[t];if(!i.buffer)return 1;r.bindBuffer(he,i.buffer);const s=r.getBufferParameter(he,_o);r.bindBuffer(he,null);const o=Lo(r,i.type),a=s/o,c=i.numComponents||i.size,u=a/c;if(u%1!==0)throw new Error(`numComponents ${c} not correct for length ${length}`);return u}function Go(r,e,t){const n=No(r,e),i=Object.assign({},t||{});i.attribs=Object.assign({},t?t.attribs:{},n);const s=e.indices;if(s){const o=wn(s,"indices");i.indices=_n(r,o,xo),i.numElements=o.length,i.elementType=lr(o)}else i.numElements||(i.numElements=zo(r,i.attribs));return i}function Le(r){return!!r.texStorage2D}const vn=(function(){const r={},e={};function t(n){const i=n.constructor.name;if(!r[i]){for(const s in n)if(typeof n[s]=="number"){const o=e[n[s]];e[n[s]]=o?`${o} | ${s}`:s}r[i]=!0}}return function(i,s){return t(i),e[s]||(typeof s=="number"?`0x${s.toString(16)}`:s)}})(),te={textureColor:new Uint8Array([128,192,255,255]),textureOptions:{},crossOrigin:void 0},ze=yt,Tn=(function(){let r;return function(){return r=r||(typeof document<"u"&&document.createElement?document.createElement("canvas").getContext("2d"):null),r}})(),An=6406,V=6407,A=6408,Sn=6409,In=6410,Ge=6402,Rn=34041,xt=33071,$o=9728,Wo=9729,re=3553,ne=34067,me=32879,pe=35866,pr=34069,Vo=34070,Ho=34071,jo=34072,Yo=34073,Xo=34074,gr=10241,yr=10240,_t=10242,Et=10243,Fn=32882,Qo=33082,qo=33083,Ko=33084,Jo=33085,Zo=34892,ea=34893,br=3317,Pn=3314,kn=32878,Cn=3316,Mn=3315,Bn=32877,ta=37443,ra=37441,na=37440,ia=33321,sa=36756,oa=33325,aa=33326,ca=33330,ua=33329,fa=33338,la=33337,da=33340,ha=33339,ma=33323,pa=36757,ga=33327,ya=33328,ba=33336,xa=33335,_a=33332,Ea=33331,wa=33334,va=33333,Ta=32849,Aa=35905,Sa=36194,Ia=36758,Ra=35898,Fa=35901,Pa=34843,ka=34837,Ca=36221,Ma=36239,Ba=36215,Da=36233,Oa=36209,Ua=36227,Na=32856,La=35907,za=36759,Ga=32855,$a=32854,Wa=32857,Va=34842,Ha=34836,ja=36220,Ya=36238,Xa=36975,Qa=36214,qa=36232,Ka=36226,Ja=36208,Za=33189,ec=33190,tc=36012,rc=36013,nc=35056,ie=5120,T=5121,wt=5122,Ie=5123,vt=5124,ge=5125,M=5126,Dn=32819,On=32820,Un=33635,z=5131,$e=36193,xr=33640,ic=35899,sc=35902,oc=36269,ac=34042,Tt=33319,Re=33320,At=6403,Fe=36244,Pe=36248,ye=36249;let _r;function St(r){if(!_r){const e={};e[An]={textureFormat:An,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[T,z,$e,M]},e[Sn]={textureFormat:Sn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[T,z,$e,M]},e[In]={textureFormat:In,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2,4,4,8],type:[T,z,$e,M]},e[V]={textureFormat:V,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,6,6,12,2],type:[T,z,$e,M,Un]},e[A]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,8,8,16,2,2],type:[T,z,$e,M,Dn,On]},e[Ge]={textureFormat:Ge,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[ge,Ie]},e[ia]={textureFormat:At,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1],type:[T]},e[sa]={textureFormat:At,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[1],type:[ie]},e[oa]={textureFormat:At,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4,2],type:[M,z]},e[aa]={textureFormat:At,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[ca]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[T]},e[ua]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[ie]},e[_a]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Ie]},e[Ea]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[wt]},e[wa]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ge]},e[va]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[vt]},e[ma]={textureFormat:Tt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2],type:[T]},e[pa]={textureFormat:Tt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[2],type:[ie]},e[ga]={textureFormat:Tt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[8,4],type:[M,z]},e[ya]={textureFormat:Tt,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[8],type:[M]},e[ba]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[T]},e[xa]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[ie]},e[fa]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Ie]},e[la]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[wt]},e[da]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[ge]},e[ha]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[vt]},e[Ta]={textureFormat:V,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3],type:[T]},e[Aa]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[T]},e[Sa]={textureFormat:V,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,2],type:[T,Un]},e[Ia]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[ie]},e[Ra]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,z,ic]},e[Fa]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,z,sc]},e[Pa]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6],type:[M,z]},e[ka]={textureFormat:V,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[M]},e[Ca]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[T]},e[Ma]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[ie]},e[Ba]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Ie]},e[Da]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[wt]},e[Oa]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[ge]},e[Ua]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[vt]},e[Na]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[T]},e[La]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[T]},e[za]={textureFormat:A,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4],type:[ie]},e[Ga]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2,4],type:[T,On,xr]},e[$a]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2],type:[T,Dn]},e[Wa]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[xr]},e[Va]={textureFormat:A,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[16,8],type:[M,z]},e[Ha]={textureFormat:A,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[16],type:[M]},e[ja]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[T]},e[Ya]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ie]},e[Xa]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[xr]},e[Qa]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Ie]},e[qa]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[wt]},e[Ka]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[vt]},e[Ja]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[ge]},e[Za]={textureFormat:Ge,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[Ie,ge]},e[ec]={textureFormat:Ge,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ge]},e[tc]={textureFormat:Ge,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[nc]={textureFormat:Rn,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ac]},e[rc]={textureFormat:Rn,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[oc]},Object.keys(e).forEach(function(t){const n=e[t];n.bytesPerElementMap={},n.bytesPerElement.forEach(function(i,s){const o=n.type[s];n.bytesPerElementMap[o]=i})}),_r=e}return _r[r]}function cc(r,e){const t=St(r);if(!t)throw"unknown internal format";const n=t.bytesPerElementMap[e];if(n===void 0)throw"unknown internal format";return n}function We(r){const e=St(r);if(!e)throw"unknown internal format";return{format:e.textureFormat,type:e.type[0]}}function Nn(r){return(r&r-1)===0}function uc(r,e,t,n){if(!Le(r))return Nn(e)&&Nn(t);const i=St(n);if(!i)throw"unknown internal format";return i.colorRenderable&&i.textureFilterable}function fc(r){const e=St(r);if(!e)throw"unknown internal format";return e.textureFilterable}function lc(r,e,t){return ze(e)?lr(e):t||T}function It(r,e,t,n,i){if(i%1!==0)throw"can\'t guess dimensions";if(!t&&!n){const s=Math.sqrt(i/(e===ne?6:1));s%1===0?(t=s,n=s):(t=i,n=1)}else if(n){if(!t&&(t=i/n,t%1))throw"can\'t guess dimensions"}else if(n=i/t,n%1)throw"can\'t guess dimensions";return{width:t,height:n}}function ke(r,e){e.colorspaceConversion!==void 0&&r.pixelStorei(ta,e.colorspaceConversion),e.premultiplyAlpha!==void 0&&r.pixelStorei(ra,e.premultiplyAlpha),e.flipY!==void 0&&r.pixelStorei(na,e.flipY)}function Ln(r){r.pixelStorei(br,4),Le(r)&&(r.pixelStorei(Pn,0),r.pixelStorei(kn,0),r.pixelStorei(Cn,0),r.pixelStorei(Mn,0),r.pixelStorei(Bn,0))}function dc(r,e,t,n){n.minMag&&(t.call(r,e,gr,n.minMag),t.call(r,e,yr,n.minMag)),n.min&&t.call(r,e,gr,n.min),n.mag&&t.call(r,e,yr,n.mag),n.wrap&&(t.call(r,e,_t,n.wrap),t.call(r,e,Et,n.wrap),(e===me||bo(r,e))&&t.call(r,e,Fn,n.wrap)),n.wrapR&&t.call(r,e,Fn,n.wrapR),n.wrapS&&t.call(r,e,_t,n.wrapS),n.wrapT&&t.call(r,e,Et,n.wrapT),n.minLod!==void 0&&t.call(r,e,Qo,n.minLod),n.maxLod!==void 0&&t.call(r,e,qo,n.maxLod),n.baseLevel!==void 0&&t.call(r,e,Ko,n.baseLevel),n.maxLevel!==void 0&&t.call(r,e,Jo,n.maxLevel),n.compareFunc!==void 0&&t.call(r,e,ea,n.compareFunc),n.compareMode!==void 0&&t.call(r,e,Zo,n.compareMode)}function zn(r,e,t){const n=t.target||re;r.bindTexture(n,e),dc(r,n,r.texParameteri,t)}function hc(r){return r=r||te.textureColor,ze(r)?r:new Uint8Array([r[0]*255,r[1]*255,r[2]*255,r[3]*255])}function Er(r,e,t,n,i,s){t=t||te.textureOptions,s=s||A;const o=t.target||re;if(n=n||t.width,i=i||t.height,r.bindTexture(o,e),uc(r,n,i,s))r.generateMipmap(o);else{const a=fc(s)?Wo:$o;r.texParameteri(o,gr,a),r.texParameteri(o,yr,a),r.texParameteri(o,_t,xt),r.texParameteri(o,Et,xt)}}function Ve(r){return r.auto===!0||r.auto===void 0&&r.level===void 0}function wr(r,e){return e=e||{},e.cubeFaceOrder||[pr,Vo,Ho,jo,Yo,Xo]}function vr(r,e){const n=wr(r,e).map(function(i,s){return{face:i,ndx:s}});return n.sort(function(i,s){return i.face-s.face}),n}function Gn(r,e,t,n){n=n||te.textureOptions;const i=n.target||re,s=n.level||0;let o=t.width,a=t.height;const c=n.internalFormat||n.format||A,u=We(c),d=n.format||u.format,m=n.type||u.type;if(ke(r,n),r.bindTexture(i,e),i===ne){const p=t.width,y=t.height;let l,b;if(p/6===y)l=y,b=[0,0,1,0,2,0,3,0,4,0,5,0];else if(y/6===p)l=p,b=[0,0,0,1,0,2,0,3,0,4,0,5];else if(p/3===y/2)l=p/3,b=[0,0,1,0,2,0,0,1,1,1,2,1];else if(p/2===y/3)l=p/2,b=[0,0,1,0,0,1,1,1,0,2,1,2];else throw"can\'t figure out cube map from element: "+(t.src?t.src:t.nodeName);const _=Tn();_?(_.canvas.width=l,_.canvas.height=l,o=l,a=l,vr(r,n).forEach(function(E){const R=b[E.ndx*2+0]*l,k=b[E.ndx*2+1]*l;_.drawImage(t,R,k,l,l,0,0,l,l),r.texImage2D(E.face,s,c,d,m,_.canvas)}),_.canvas.width=1,_.canvas.height=1):typeof createImageBitmap<"u"&&(o=l,a=l,vr(r,n).forEach(function(E){const R=b[E.ndx*2+0]*l,k=b[E.ndx*2+1]*l;r.texImage2D(E.face,s,c,l,l,0,d,m,null),createImageBitmap(t,R,k,l,l,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(function(N){ke(r,n),r.bindTexture(i,e),r.texImage2D(E.face,s,c,d,m,N),Ve(n)&&Er(r,e,n,o,a,c)})}))}else if(i===me||i===pe){const p=Math.min(t.width,t.height),y=Math.max(t.width,t.height),l=y/p;if(l%1!==0)throw"can not compute 3D dimensions of element";const b=t.width===y?1:0,_=t.height===y?1:0;r.pixelStorei(br,1),r.pixelStorei(Pn,t.width),r.pixelStorei(kn,0),r.pixelStorei(Bn,0),r.texImage3D(i,s,c,p,p,p,0,d,m,null);for(let E=0;E<l;++E){const R=E*p*b,k=E*p*_;r.pixelStorei(Cn,R),r.pixelStorei(Mn,k),r.texSubImage3D(i,s,0,0,E,p,p,1,d,m,t)}Ln(r)}else r.texImage2D(i,s,c,d,m,t);Ve(n)&&Er(r,e,n,o,a,c),zn(r,e,n)}function He(){}function mc(r){if(typeof document<"u"){const e=document.createElement("a");return e.href=r,e.hostname===location.hostname&&e.port===location.port&&e.protocol===location.protocol}else{const e=new URL(location.href).origin;return new URL(r,location.href).origin===e}}function pc(r,e){return e===void 0&&!mc(r)?"anonymous":e}function gc(r,e,t){t=t||He;let n;if(e=e!==void 0?e:te.crossOrigin,e=pc(r,e),typeof Image<"u"){n=new Image,e!==void 0&&(n.crossOrigin=e);const i=function(){n.removeEventListener("error",s),n.removeEventListener("load",o),n=null},s=function(){const c="couldn\'t load image: "+r;pn(c),t(c,n),i()},o=function(){t(null,n),i()};return n.addEventListener("error",s),n.addEventListener("load",o),n.src=r,n}else if(typeof ImageBitmap<"u"){let i,s;const o=function(){t(i,s)},a={};e&&(a.mode="cors"),fetch(r,a).then(function(c){if(!c.ok)throw c;return c.blob()}).then(function(c){return createImageBitmap(c,{premultiplyAlpha:"none",colorSpaceConversion:"none"})}).then(function(c){s=c,setTimeout(o)}).catch(function(c){i=c,setTimeout(o)}),n=null}return n}function $n(r){return typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof ImageData<"u"&&r instanceof ImageData||typeof HTMLElement<"u"&&r instanceof HTMLElement}function Tr(r,e,t){return $n(r)?(setTimeout(function(){t(null,r)}),r):gc(r,e,t)}function Ar(r,e,t){t=t||te.textureOptions;const n=t.target||re;if(r.bindTexture(n,e),t.color===!1)return;const i=hc(t.color);if(n===ne)for(let s=0;s<6;++s)r.texImage2D(pr+s,0,A,1,1,0,A,T,i);else n===me||n===pe?r.texImage3D(n,0,A,1,1,1,0,A,T,i):r.texImage2D(n,0,A,1,1,0,A,T,i)}function yc(r,e,t,n){return n=n||He,t=t||te.textureOptions,Ar(r,e,t),t=Object.assign({},t),Tr(t.src,t.crossOrigin,function(s,o){s?n(s,e,o):(Gn(r,e,o,t),n(null,e,o))})}function bc(r,e,t,n){n=n||He;const i=t.src;if(i.length!==6)throw"there must be 6 urls for a cubemap";const s=t.level||0,o=t.internalFormat||t.format||A,a=We(o),c=t.format||a.format,u=t.type||T,d=t.target||re;if(d!==ne)throw"target must be TEXTURE_CUBE_MAP";Ar(r,e,t),t=Object.assign({},t);let m=6;const p=[],y=wr(r,t);let l;function b(_){return function(E,R){--m,E?p.push(E):R.width!==R.height?p.push("cubemap face img is not a square: "+R.src):(ke(r,t),r.bindTexture(d,e),m===5?wr().forEach(function(k){r.texImage2D(k,s,o,c,u,R)}):r.texImage2D(_,s,o,c,u,R),Ve(t)&&r.generateMipmap(d)),m===0&&n(p.length?p:void 0,e,l)}}l=i.map(function(_,E){return Tr(_,t.crossOrigin,b(y[E]))})}function xc(r,e,t,n){n=n||He;const i=t.src,s=t.internalFormat||t.format||A,o=We(s),a=t.format||o.format,c=t.type||T,u=t.target||pe;if(u!==me&&u!==pe)throw"target must be TEXTURE_3D or TEXTURE_2D_ARRAY";Ar(r,e,t),t=Object.assign({},t);let d=i.length;const m=[];let p;const y=t.level||0;let l=t.width,b=t.height;const _=i.length;let E=!0;function R(k){return function(N,Q){if(--d,N)m.push(N);else{if(ke(r,t),r.bindTexture(u,e),E){E=!1,l=t.width||Q.width,b=t.height||Q.height,r.texImage3D(u,y,s,l,b,_,0,a,c,null);for(let q=0;q<_;++q)r.texSubImage3D(u,y,0,0,q,l,b,1,a,c,Q)}else{let q=Q,L;(Q.width!==l||Q.height!==b)&&(L=Tn(),q=L.canvas,L.canvas.width=l,L.canvas.height=b,L.drawImage(Q,0,0,l,b)),r.texSubImage3D(u,y,0,0,k,l,b,1,a,c,q),L&&q===L.canvas&&(L.canvas.width=0,L.canvas.height=0)}Ve(t)&&r.generateMipmap(u)}d===0&&n(m.length?m:void 0,e,p)}}p=i.map(function(k,N){return Tr(k,t.crossOrigin,R(N))})}function _c(r,e,t,n){n=n||te.textureOptions;const i=n.target||re;r.bindTexture(i,e);let s=n.width,o=n.height,a=n.depth;const c=n.level||0,u=n.internalFormat||n.format||A,d=We(u),m=n.format||d.format,p=n.type||lc(r,t,d.type);if(ze(t))t instanceof Uint8ClampedArray&&(t=new Uint8Array(t.buffer));else{const _=mn(p);t=new _(t)}const y=cc(u,p),l=t.byteLength/y;if(l%1)throw"length wrong size for format: "+vn(r,m);let b;if(i===me||i===pe)if(!s&&!o&&!a){const _=Math.cbrt(l);if(_%1!==0)throw"can\'t guess cube size of array of numElements: "+l;s=_,o=_,a=_}else s&&(!o||!a)?(b=It(r,i,o,a,l/s),o=b.width,a=b.height):o&&(!s||!a)?(b=It(r,i,s,a,l/o),s=b.width,a=b.height):(b=It(r,i,s,o,l/a),s=b.width,o=b.height);else b=It(r,i,s,o,l),s=b.width,o=b.height;if(Ln(r),r.pixelStorei(br,n.unpackAlignment||1),ke(r,n),i===ne){const _=y/t.BYTES_PER_ELEMENT,E=l/6*_;vr(r,n).forEach(R=>{const k=E*R.ndx,N=t.subarray(k,k+E);r.texImage2D(R.face,c,u,s,o,0,m,p,N)})}else i===me||i===pe?r.texImage3D(i,c,u,s,o,a,0,m,p,t):r.texImage2D(i,c,u,s,o,0,m,p,t);return{width:s,height:o,depth:a,type:p}}function Ec(r,e,t){const n=t.target||re;r.bindTexture(n,e);const i=t.level||0,s=t.internalFormat||t.format||A,o=We(s),a=t.format||o.format,c=t.type||o.type;if(ke(r,t),n===ne)for(let u=0;u<6;++u)r.texImage2D(pr+u,i,s,t.width,t.height,0,a,c,null);else n===me||n===pe?r.texImage3D(n,i,s,t.width,t.height,t.depth,0,a,c,null):r.texImage2D(n,i,s,t.width,t.height,0,a,c,null)}function Wn(r,e,t){t=t||He,e=e||te.textureOptions;const n=r.createTexture(),i=e.target||re;let s=e.width||1,o=e.height||1;const a=e.internalFormat||A;r.bindTexture(i,n),i===ne&&(r.texParameteri(i,_t,xt),r.texParameteri(i,Et,xt));let c=e.src;if(c)if(typeof c=="function"&&(c=c(r,e)),typeof c=="string")yc(r,n,e,t);else if(ze(c)||Array.isArray(c)&&(typeof c[0]=="number"||Array.isArray(c[0])||ze(c[0]))){const u=_c(r,n,c,e);s=u.width,o=u.height}else Array.isArray(c)&&(typeof c[0]=="string"||$n(c[0]))?i===ne?bc(r,n,e,t):xc(r,n,e,t):(Gn(r,n,c,e),s=c.width,o=c.height);else Ec(r,n,e);return Ve(e)&&Er(r,n,e,s,o,a),zn(r,n,e),n}const Sr=pn;function Vn(r){return typeof document<"u"&&document.getElementById?document.getElementById(r):null}const Rt=33984,Ft=34962,wc=34963,vc=35713,Tc=35714,Ac=35632,Sc=35633,Ic=35981,Hn=35718,Rc=35721,Fc=35971,Pc=35382,kc=35396,Cc=35398,Mc=35392,Bc=35395,Pt=5126,jn=35664,Yn=35665,Xn=35666,Ir=5124,Qn=35667,qn=35668,Kn=35669,Jn=35670,Zn=35671,ei=35672,ti=35673,ri=35674,ni=35675,ii=35676,Dc=35678,Oc=35680,Uc=35679,Nc=35682,Lc=35685,zc=35686,Gc=35687,$c=35688,Wc=35689,Vc=35690,Hc=36289,jc=36292,Yc=36293,Rr=5125,si=36294,oi=36295,ai=36296,Xc=36298,Qc=36299,qc=36300,Kc=36303,Jc=36306,Zc=36307,eu=36308,tu=36311,kt=3553,Ct=34067,Fr=32879,Mt=35866,x={};function ci(r,e){return x[e].bindPoint}function ru(r,e){return function(t){r.uniform1f(e,t)}}function nu(r,e){return function(t){r.uniform1fv(e,t)}}function iu(r,e){return function(t){r.uniform2fv(e,t)}}function su(r,e){return function(t){r.uniform3fv(e,t)}}function ou(r,e){return function(t){r.uniform4fv(e,t)}}function ui(r,e){return function(t){r.uniform1i(e,t)}}function fi(r,e){return function(t){r.uniform1iv(e,t)}}function li(r,e){return function(t){r.uniform2iv(e,t)}}function di(r,e){return function(t){r.uniform3iv(e,t)}}function hi(r,e){return function(t){r.uniform4iv(e,t)}}function au(r,e){return function(t){r.uniform1ui(e,t)}}function cu(r,e){return function(t){r.uniform1uiv(e,t)}}function uu(r,e){return function(t){r.uniform2uiv(e,t)}}function fu(r,e){return function(t){r.uniform3uiv(e,t)}}function lu(r,e){return function(t){r.uniform4uiv(e,t)}}function du(r,e){return function(t){r.uniformMatrix2fv(e,!1,t)}}function hu(r,e){return function(t){r.uniformMatrix3fv(e,!1,t)}}function mu(r,e){return function(t){r.uniformMatrix4fv(e,!1,t)}}function pu(r,e){return function(t){r.uniformMatrix2x3fv(e,!1,t)}}function gu(r,e){return function(t){r.uniformMatrix3x2fv(e,!1,t)}}function yu(r,e){return function(t){r.uniformMatrix2x4fv(e,!1,t)}}function bu(r,e){return function(t){r.uniformMatrix4x2fv(e,!1,t)}}function xu(r,e){return function(t){r.uniformMatrix3x4fv(e,!1,t)}}function _u(r,e){return function(t){r.uniformMatrix4x3fv(e,!1,t)}}function O(r,e,t,n){const i=ci(r,e);return Le(r)?function(s){let o,a;!s||dr(r,s)?(o=s,a=null):(o=s.texture,a=s.sampler),r.uniform1i(n,t),r.activeTexture(Rt+t),r.bindTexture(i,o),r.bindSampler(t,a)}:function(s){r.uniform1i(n,t),r.activeTexture(Rt+t),r.bindTexture(i,s)}}function U(r,e,t,n,i){const s=ci(r,e),o=new Int32Array(i);for(let a=0;a<i;++a)o[a]=t+a;return Le(r)?function(a){r.uniform1iv(n,o),a.forEach(function(c,u){r.activeTexture(Rt+o[u]);let d,m;!c||dr(r,c)?(d=c,m=null):(d=c.texture,m=c.sampler),r.bindSampler(t,m),r.bindTexture(s,d)})}:function(a){r.uniform1iv(n,o),a.forEach(function(c,u){r.activeTexture(Rt+o[u]),r.bindTexture(s,c)})}}x[Pt]={Type:Float32Array,size:4,setter:ru,arraySetter:nu},x[jn]={Type:Float32Array,size:8,setter:iu,cols:2},x[Yn]={Type:Float32Array,size:12,setter:su,cols:3},x[Xn]={Type:Float32Array,size:16,setter:ou,cols:4},x[Ir]={Type:Int32Array,size:4,setter:ui,arraySetter:fi},x[Qn]={Type:Int32Array,size:8,setter:li,cols:2},x[qn]={Type:Int32Array,size:12,setter:di,cols:3},x[Kn]={Type:Int32Array,size:16,setter:hi,cols:4},x[Rr]={Type:Uint32Array,size:4,setter:au,arraySetter:cu},x[si]={Type:Uint32Array,size:8,setter:uu,cols:2},x[oi]={Type:Uint32Array,size:12,setter:fu,cols:3},x[ai]={Type:Uint32Array,size:16,setter:lu,cols:4},x[Jn]={Type:Uint32Array,size:4,setter:ui,arraySetter:fi},x[Zn]={Type:Uint32Array,size:8,setter:li,cols:2},x[ei]={Type:Uint32Array,size:12,setter:di,cols:3},x[ti]={Type:Uint32Array,size:16,setter:hi,cols:4},x[ri]={Type:Float32Array,size:32,setter:du,rows:2,cols:2},x[ni]={Type:Float32Array,size:48,setter:hu,rows:3,cols:3},x[ii]={Type:Float32Array,size:64,setter:mu,rows:4,cols:4},x[Lc]={Type:Float32Array,size:32,setter:pu,rows:2,cols:3},x[zc]={Type:Float32Array,size:32,setter:yu,rows:2,cols:4},x[Gc]={Type:Float32Array,size:48,setter:gu,rows:3,cols:2},x[$c]={Type:Float32Array,size:48,setter:xu,rows:3,cols:4},x[Wc]={Type:Float32Array,size:64,setter:bu,rows:4,cols:2},x[Vc]={Type:Float32Array,size:64,setter:_u,rows:4,cols:3},x[Dc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:kt},x[Oc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Ct},x[Uc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Fr},x[Nc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:kt},x[Hc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Mt},x[jc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Mt},x[Yc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Ct},x[Xc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:kt},x[Qc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Fr},x[qc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Ct},x[Kc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Mt},x[Jc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:kt},x[Zc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Fr},x[eu]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Ct},x[tu]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Mt};function Bt(r,e){return function(t){if(t.value)switch(r.disableVertexAttribArray(e),t.value.length){case 4:r.vertexAttrib4fv(e,t.value);break;case 3:r.vertexAttrib3fv(e,t.value);break;case 2:r.vertexAttrib2fv(e,t.value);break;case 1:r.vertexAttrib1fv(e,t.value);break;default:throw new Error("the length of a float constant value must be between 1 and 4!")}else r.bindBuffer(Ft,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribPointer(e,t.numComponents||t.size,t.type||Pt,t.normalize||!1,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function se(r,e){return function(t){if(t.value)if(r.disableVertexAttribArray(e),t.value.length===4)r.vertexAttrib4iv(e,t.value);else throw new Error("The length of an integer constant value must be 4!");else r.bindBuffer(Ft,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribIPointer(e,t.numComponents||t.size,t.type||Ir,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function Dt(r,e){return function(t){if(t.value)if(r.disableVertexAttribArray(e),t.value.length===4)r.vertexAttrib4uiv(e,t.value);else throw new Error("The length of an unsigned integer constant value must be 4!");else r.bindBuffer(Ft,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribIPointer(e,t.numComponents||t.size,t.type||Rr,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function Pr(r,e,t){const n=t.size,i=t.count;return function(s){r.bindBuffer(Ft,s.buffer);const o=s.size||s.numComponents||n,a=o/i,c=s.type||Pt,d=x[c].size*o,m=s.normalize||!1,p=s.offset||0,y=d/i;for(let l=0;l<i;++l)r.enableVertexAttribArray(e+l),r.vertexAttribPointer(e+l,a,c,m,d,p+y*l),r.vertexAttribDivisor&&r.vertexAttribDivisor(e+l,s.divisor||0)}}const S={};S[Pt]={size:4,setter:Bt},S[jn]={size:8,setter:Bt},S[Yn]={size:12,setter:Bt},S[Xn]={size:16,setter:Bt},S[Ir]={size:4,setter:se},S[Qn]={size:8,setter:se},S[qn]={size:12,setter:se},S[Kn]={size:16,setter:se},S[Rr]={size:4,setter:Dt},S[si]={size:8,setter:Dt},S[oi]={size:12,setter:Dt},S[ai]={size:16,setter:Dt},S[Jn]={size:4,setter:se},S[Zn]={size:8,setter:se},S[ei]={size:12,setter:se},S[ti]={size:16,setter:se},S[ri]={size:4,setter:Pr,count:2},S[ni]={size:9,setter:Pr,count:3},S[ii]={size:16,setter:Pr,count:4};const Eu=/ERROR:\\s*\\d+:(\\d+)/gi;function wu(r,e="",t=0){const n=[...e.matchAll(Eu)],i=new Map(n.map((s,o)=>{const a=parseInt(s[1]),c=n[o+1],u=c?c.index:e.length,d=e.substring(s.index,u);return[a-1,d]}));return r.split(`\n`).map((s,o)=>{const a=i.get(o);return`${o+1+t}: ${s}${a?`\n\n^^^ ${a}`:""}`}).join(`\n`)}const mi=/^[ \\t]*\\n/;function pi(r){let e=0;return mi.test(r)&&(e=1,r=r.replace(mi,"")),{lineOffset:e,shaderSource:r}}function vu(r,e){return r.errorCallback(e),r.callback&&setTimeout(()=>{r.callback(`${e}\n${r.errors.join(`\n`)}`)}),null}function Tu(r,e,t,n){if(n=n||Sr,!r.getShaderParameter(t,vc)){const s=r.getShaderInfoLog(t),{lineOffset:o,shaderSource:a}=pi(r.getShaderSource(t)),c=`${wu(a,s,o)}\nError compiling ${vn(r,e)}: ${s}`;return n(c),c}return""}function kr(r,e,t){let n,i,s;if(typeof e=="function"&&(t=e,e=void 0),typeof r=="function")t=r,r=void 0;else if(r&&!Array.isArray(r)){const u=r;t=u.errorCallback,r=u.attribLocations,n=u.transformFeedbackVaryings,i=u.transformFeedbackMode,s=u.callback}const o=t||Sr,a=[],c={errorCallback(u,...d){a.push(u),o(u,...d)},transformFeedbackVaryings:n,transformFeedbackMode:i,callback:s,errors:a};{let u={};Array.isArray(r)?r.forEach(function(d,m){u[d]=e?e[m]:m}):u=r||{},c.attribLocations=u}return c}const Au=["VERTEX_SHADER","FRAGMENT_SHADER"];function Su(r,e){if(e.indexOf("frag")>=0)return Ac;if(e.indexOf("vert")>=0)return Sc}function Iu(r,e,t){const n=r.getAttachedShaders(e);for(const i of n)t.has(i)&&r.deleteShader(i);r.deleteProgram(e)}const Ru=(r=0)=>new Promise(e=>setTimeout(e,r));function Fu(r,e,t){const n=r.createProgram(),{attribLocations:i,transformFeedbackVaryings:s,transformFeedbackMode:o}=kr(t);for(let a=0;a<e.length;++a){let c=e[a];if(typeof c=="string"){const u=Vn(c),d=u?u.text:c;let m=r[Au[a]];u&&u.type&&(m=Su(r,u.type)||m),c=r.createShader(m),r.shaderSource(c,pi(d).shaderSource),r.compileShader(c),r.attachShader(n,c)}}Object.entries(i).forEach(([a,c])=>r.bindAttribLocation(n,c,a));{let a=s;a&&(a.attribs&&(a=a.attribs),Array.isArray(a)||(a=Object.keys(a)),r.transformFeedbackVaryings(n,a,o||Ic))}return r.linkProgram(n),n}function Pu(r,e,t,n,i){const s=kr(t,n,i),o=new Set(e),a=Fu(r,e,s);function c(u,d){const m=Cu(u,d,s.errorCallback);return m&&Iu(u,d,o),m}if(s.callback){ku(r,a).then(()=>{const u=c(r,a);s.callback(u,u?void 0:a)});return}return c(r,a)?void 0:a}async function ku(r,e){const t=r.getExtension("KHR_parallel_shader_compile"),n=t?(s,o)=>s.getProgramParameter(o,t.COMPLETION_STATUS_KHR):()=>!0;let i=0;do await Ru(i),i=1e3/60;while(!n(r,e))}function Cu(r,e,t){if(t=t||Sr,!r.getProgramParameter(e,Tc)){const i=r.getProgramInfoLog(e);t(`Error in program linking: ${i}`);const o=r.getAttachedShaders(e).map(a=>Tu(r,r.getShaderParameter(a,r.SHADER_TYPE),a,t));return`${i}\n${o.filter(a=>a).join(`\n`)}`}}function Mu(r,e,t,n,i){return Pu(r,e,t,n,i)}function gi(r){const e=r.name;return e.startsWith("gl_")||e.startsWith("webgl_")}const Bu=/(\\.|\\[|]|\\w+)/g,Du=r=>r>="0"&&r<="9";function Ou(r,e,t,n){const i=r.split(Bu).filter(a=>a!=="");let s=0,o="";for(;;){const a=i[s++];o+=a;const c=Du(a[0]),u=c?parseInt(a):a;if(c&&(o+=i[s++]),s===i.length){t[u]=e;break}else{const m=i[s++],p=m==="[",y=t[u]||(p?[]:{});t[u]=y,t=y,n[o]=n[o]||(function(l){return function(b){yi(l,b)}})(y),o+=m}}}function Uu(r,e){let t=0;function n(a,c,u){const d=c.name.endsWith("[0]"),m=c.type,p=x[m];if(!p)throw new Error(`unknown type: 0x${m.toString(16)}`);let y;if(p.bindPoint){const l=t;t+=c.size,d?y=p.arraySetter(r,m,l,u,c.size):y=p.setter(r,m,l,u,c.size)}else p.arraySetter&&d?y=p.arraySetter(r,u):y=p.setter(r,u);return y.location=u,y}const i={},s={},o=r.getProgramParameter(e,Hn);for(let a=0;a<o;++a){const c=r.getActiveUniform(e,a);if(gi(c))continue;let u=c.name;u.endsWith("[0]")&&(u=u.substr(0,u.length-3));const d=r.getUniformLocation(e,c.name);if(d){const m=n(e,c,d);i[u]=m,Ou(u,m,s,i)}}return i}function Nu(r,e){const t={},n=r.getProgramParameter(e,Fc);for(let i=0;i<n;++i){const s=r.getTransformFeedbackVarying(e,i);t[s.name]={index:i,type:s.type,size:s.size}}return t}function Lu(r,e){const t=r.getProgramParameter(e,Hn),n=[],i=[];for(let a=0;a<t;++a){i.push(a),n.push({});const c=r.getActiveUniform(e,a);n[a].name=c.name}[["UNIFORM_TYPE","type"],["UNIFORM_SIZE","size"],["UNIFORM_BLOCK_INDEX","blockNdx"],["UNIFORM_OFFSET","offset"]].forEach(function(a){const c=a[0],u=a[1];r.getActiveUniforms(e,i,r[c]).forEach(function(d,m){n[m][u]=d})});const s={},o=r.getProgramParameter(e,Pc);for(let a=0;a<o;++a){const c=r.getActiveUniformBlockName(e,a),u={index:r.getUniformBlockIndex(e,c),usedByVertexShader:r.getActiveUniformBlockParameter(e,a,kc),usedByFragmentShader:r.getActiveUniformBlockParameter(e,a,Cc),size:r.getActiveUniformBlockParameter(e,a,Mc),uniformIndices:r.getActiveUniformBlockParameter(e,a,Bc)};u.used=u.usedByVertexShader||u.usedByFragmentShader,s[c]=u}return{blockSpecs:s,uniformData:n}}function yi(r,e){for(const t in e){const n=r[t];typeof n=="function"?n(e[t]):yi(r[t],e[t])}}function bi(r,...e){const t=r.uniformSetters||r,n=e.length;for(let i=0;i<n;++i){const s=e[i];if(Array.isArray(s)){const o=s.length;for(let a=0;a<o;++a)bi(t,s[a])}else for(const o in s){const a=t[o];a&&a(s[o])}}}function zu(r,e){const t={},n=r.getProgramParameter(e,Rc);for(let i=0;i<n;++i){const s=r.getActiveAttrib(e,i);if(gi(s))continue;const o=r.getAttribLocation(e,s.name),a=S[s.type],c=a.setter(r,o,a);c.location=o,t[s.name]=c}return t}function Gu(r,e){for(const t in e){const n=r[t];n&&n(e[t])}}function $u(r,e,t){t.vertexArrayObject?r.bindVertexArray(t.vertexArrayObject):(Gu(e.attribSetters||e,t.attribs),t.indices&&r.bindBuffer(wc,t.indices))}function xi(r,e){const t=Uu(r,e),n=zu(r,e),i={program:e,uniformSetters:t,attribSetters:n};return Le(r)&&(i.uniformBlockSpec=Lu(r,e),i.transformFeedbackInfo=Nu(r,e)),i}const Wu=/\\s|{|}|;/;function Vu(r,e,t,n,i){const s=kr(t,n,i),o=[];if(e=e.map(function(u){if(!Wu.test(u)){const d=Vn(u);if(d)u=d.text;else{const m=`no element with id: ${u}`;s.errorCallback(m),o.push(m)}}return u}),o.length)return vu(s,"");const a=s.callback;a&&(s.callback=(u,d)=>{a(u,u?void 0:xi(r,d))});const c=Mu(r,e,s);return c?xi(r,c):null}const Hu=4,_i=5123;function ju(r,e,t,n,i,s){t=t===void 0?Hu:t;const o=e.indices,a=e.elementType,c=n===void 0?e.numElements:n;i=i===void 0?0:i,a||o?s!==void 0?r.drawElementsInstanced(t,c,a===void 0?_i:e.elementType,i,s):r.drawElements(t,c,a===void 0?_i:e.elementType,i):s!==void 0?r.drawArraysInstanced(t,i,c,s):r.drawArrays(t,i,c)}const Ei=36160,Ot=36161,Yu=3553,Xu=5121,Qu=6402,qu=6408,Ku=33190,Ju=36012,Zu=35056,ef=36013,tf=32854,rf=32855,nf=36194,wi=33189,vi=6401,Ti=36168,Cr=34041,Mr=36064,Ut=36096,Ai=36128,Br=33306,Dr=33071,Or=9729,sf=[{format:qu,type:Xu,min:Or,wrap:Dr},{format:Cr}],G={};G[Cr]=Br,G[vi]=Ai,G[Ti]=Ai,G[Qu]=Ut,G[wi]=Ut,G[Ku]=Ut,G[Ju]=Ut,G[Zu]=Br,G[ef]=Br;function of(r,e){return G[r]||G[e]}const oe={};oe[tf]=!0,oe[rf]=!0,oe[nf]=!0,oe[Cr]=!0,oe[wi]=!0,oe[vi]=!0,oe[Ti]=!0;function af(r){return oe[r]}const cf=32;function uf(r){return r>=Mr&&r<Mr+cf}function Si(r,e,t,n){const i=Ei,s=r.createFramebuffer();r.bindFramebuffer(i,s),t=t||r.drawingBufferWidth,n=n||r.drawingBufferHeight,e=e||sf;const o=[],a={framebuffer:s,attachments:[],width:t,height:n};return e.forEach(function(c,u){let d=c.attachment;const m=c.samples,p=c.format;let y=c.attachmentPoint||of(p,c.internalFormat);if(y||(y=Mr+u),uf(y)&&o.push(y),!d)if(m!==void 0||af(p))d=r.createRenderbuffer(),r.bindRenderbuffer(Ot,d),m>1?r.renderbufferStorageMultisample(Ot,m,p,t,n):r.renderbufferStorage(Ot,p,t,n);else{const l=Object.assign({},c);l.width=t,l.height=n,l.auto===void 0&&(l.auto=!1,l.min=l.min||l.minMag||Or,l.mag=l.mag||l.minMag||Or,l.wrapS=l.wrapS||l.wrap||Dr,l.wrapT=l.wrapT||l.wrap||Dr),d=Wn(r,l)}if(yo(r,d))r.framebufferRenderbuffer(i,y,Ot,d);else if(dr(r,d))c.layer!==void 0?r.framebufferTextureLayer(i,y,d,c.level||0,c.layer):r.framebufferTexture2D(i,y,c.target||Yu,d,c.level||0);else throw new Error("unknown attachment type");a.attachments.push(d)}),r.drawBuffers&&r.drawBuffers(o),a}function ff(r,e,t){t=t||Ei,e?(r.bindFramebuffer(t,e.framebuffer),r.viewport(0,0,e.width,e.height)):(r.bindFramebuffer(t,null),r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight))}function B(r,e){return()=>e instanceof WebGLTexture?e:Wn(r,{src:e,wrap:r.CLAMP_TO_EDGE})}const Ce=2;class je{constructor(e){this.id="_";const{context:t,width:n,height:i}=e;this.context=t,this.options=e;const s=this.buildDefines();this.programInfo=Vu(this.context,[s+this.getVertexShader(),s+this.getFragmentShader()]),this.bufferInfo=Go(this.context,this.getBuffers()),this.fbi=Si(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],n,i),this.output=this.fbi.attachments[0]}resizeOutput(e,t){this.fbi=Si(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],e,t),this.options.width=e,this.options.height=t,this.output=this.fbi.attachments[0]}getDefines(){return{}}getBuffers(){return{position:{numComponents:2,data:[-1,-1,-1,1,1,-1,1,1,-1,1,1,-1]},texture_coord:{numComponents:2,data:[0,0,0,1,1,0,1,1,0,1,1,0]}}}buildDefines(){let e="";const t=this.getDefines();for(let n in t)e+=`#define ${n} ${t[n].toFixed(1)}\n`;return e}run(e){this.profiler?.pushContext(`[${this.id}] PROG : ${this.constructor.name}`),this.profiler?.pushContext(`[${this.id}] UNIFORMS`);for(const i in e)typeof e[i]=="function"&&(this.profiler?.pushContext(`[${this.id}] UNI : ${i}`),e[i]=e[i](),this.profiler?.popContext(`[${this.id}] UNI : ${i}`));this.profiler?.popContext(`[${this.id}] UNIFORMS`);const t=Date.now();let n=0;this.lastRun&&(n=(t-this.lastRun)/1e3),this.lastRun=t,this.context.viewport(0,0,this.context.canvas.width,this.context.canvas.height),this.context.useProgram(this.programInfo.program),$u(this.context,this.programInfo,this.bufferInfo),bi(this.programInfo,{delta:n,canvas:[this.context.canvas.width,this.context.canvas.height],...e}),ff(this.context,this.options.disableFramebuffer?null:this.fbi),ju(this.context,this.bufferInfo),this.profiler?.popContext(`[${this.id}] PROG : ${this.constructor.name}`)}setProfiler(e){this.profiler=e}}var lf=`precision mediump float;\n\nvarying vec2 _texture_coord;\n\nuniform sampler2D background;\nuniform sampler2D foreground;\nuniform sampler2D threshold;\n\nvoid main() {\n vec4 backgroundColor = texture2D(background, _texture_coord);\n vec4 foregroundColor = texture2D(foreground, _texture_coord);\n vec4 tresholdColor = texture2D(threshold, _texture_coord);\n gl_FragColor = foregroundColor * tresholdColor.a +\n backgroundColor * (1. - tresholdColor.a);\n}\n`,df=`varying vec2 _texture_coord;\n\nattribute vec2 position;\nattribute vec2 texture_coord;\n\nvoid main() {\n gl_Position = vec4(position, 0., 1.);\n _texture_coord = texture_coord;\n _texture_coord.y = 1. - texture_coord.y;\n}\n`;class Ur extends je{getFragmentShader(){return lf}getVertexShader(){return df}}class Nr{constructor(){this.steps=[]}addStep(e){this.steps.push(e)}async run(){for(const e of this.steps)e.program.run(e.getUniforms())}resizeOutput(e,t){this.profiler?.pushContext(`PIP [${this.constructor.name}]`);for(const n of this.steps)n.preventResize||n.program.resizeOutput(e,t);this.profiler?.popContext(`PIP [${this.constructor.name}]`)}setProfiler(e){this.profiler=e;for(const t of this.steps)t.program.setProfiler(e)}setId(e){for(const t of this.steps)t.program.id=e}}class Lr extends Nr{constructor(){super(...arguments),this.preciseMaskEnabled=!1}}class Ii extends Lr{constructor(e){super(),this.context=e,this.preciseMaskEnabled=!0;const t={context:e,height:e.canvas.height,width:e.canvas.width},n=new Ur({...t,disableFramebuffer:!0});this.addStep({program:n,getUniforms:()=>({background:B(e,this.inputBackgroundImage),foreground:B(e,this.inputImage),threshold:B(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}var hf=`precision mediump float;\n\nvarying vec2 _texture_coord;\nuniform sampler2D texture;\n\nvoid main() { gl_FragColor = texture2D(texture, _texture_coord); }\n`,mf=`varying vec2 _texture_coord;\n\nattribute vec2 position;\nattribute vec2 texture_coord;\nuniform bool invert_y;\n\nvoid main() {\n gl_Position = vec4(position, 0., 1.);\n _texture_coord = texture_coord;\n if (invert_y) {\n _texture_coord.y = 1. - texture_coord.y;\n }\n}\n`;class pf extends je{getFragmentShader(){return hf}getVertexShader(){return mf}}class gf extends Nr{constructor(e,t,n){super(),this.context=e;const i={context:e,height:n,width:t};this.addStep({program:new pf({...i,disableFramebuffer:!0}),getUniforms:()=>({texture:B(e,this.inputImage),invert_y:!0})})}setData(e){this.inputImage=e}}async function Ri(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}var yf=`precision mediump float;\n\nvarying vec2 _texture_coord;\n\nuniform vec2 canvas;\nuniform sampler2D texture;\n\nvec4 loop();\n\nvoid main() { gl_FragColor = loop(); }\n`,bf=`varying vec2 _texture_coord;\n\nattribute vec2 position;\nattribute vec2 texture_coord;\n\nvoid main() {\n gl_Position = vec4(position, 0., 1.);\n _texture_coord = texture_coord;\n}\n`,zr=(r=>(r[r.LINEAR=0]="LINEAR",r[r.GAUSSIAN=1]="GAUSSIAN",r))(zr||{});class Fi extends je{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return yf+this.createLoopFunction()}getVertexShader(){return bf}createLoopFunction(){let e=this.options.radius??1;return`\n\n vec4 loop() { \n vec4 result = vec4(0,0,0,0);\n float factorSum = 0.;\n\n vec2 normalizedRadius = vec2(-${e}.) / canvas;\n vec2 normalizedIncrement = vec2(1.) / canvas;\n vec2 diff = normalizedRadius;\n\n for(int y=-${e}; y<${e+1}; ++y) {\n for(int x=-${e}; x<${e+1}; ++x) {\n float factor = 1.;\n result += factor * texture2D(texture, _texture_coord + diff);\n factorSum += factor;\n diff.x += normalizedIncrement.x;\n }\n diff.y += normalizedIncrement.y;\n diff.x = normalizedRadius.x;\n }\n return result / factorSum;\n }`}}var xf=`#version 300 es\n// https://github.com/Volcomix/virtual-background/blob/main/src/pipelines/webgl2/jointBilateralFilterStage.ts\n\nprecision highp float;\nuniform sampler2D input_frame;\nuniform sampler2D segmentation_mask;\nuniform sampler2D threshold;\nuniform vec2 texel_size;\nuniform float step;\nuniform float radius;\nuniform float offset;\nuniform float sigma_texel;\nuniform float sigma_color;\n\nin vec2 _texture_coord;\nout vec4 outColor;\n\nfloat gaussian(float x, float sigma) {\n float coeff = -0.5 / (sigma * sigma * 4.0 + 1.0e-6);\n return exp((x * x) * coeff);\n}\n\nvoid main() {\n vec2 centerCoord = _texture_coord;\n vec3 centerColor = texture(input_frame, centerCoord).rgb;\n float newVal = 0.0;\n float spaceWeight = 0.0;\n float colorWeight = 0.0;\n float totalWeight = 0.0;\n // Subsample kernel space.\n for (float i = -radius + offset; i <= radius; i += step) {\n for (float j = -radius + offset; j <= radius; j += step) {\n vec2 shift = vec2(j, i) * texel_size;\n vec2 coord = vec2(centerCoord + shift);\n vec3 frameColor = texture(input_frame, coord).rgb;\n float threshold = texture(threshold, coord).a;\n float outVal = texture(segmentation_mask, coord).a;\n\n spaceWeight = gaussian(distance(centerCoord, coord), sigma_texel);\n colorWeight = gaussian(distance(centerColor, frameColor), sigma_color);\n totalWeight += spaceWeight * colorWeight;\n newVal += spaceWeight * colorWeight * outVal * threshold;\n }\n }\n newVal /= totalWeight;\n outColor = vec4(vec3(0.), newVal);\n}`,_f=`#version 300 es\nin vec2 position;\nin vec2 texture_coord;\nout vec2 _texture_coord;\nvoid main() {\n gl_Position = vec4(position, 0.0, 1.0);\n _texture_coord = texture_coord;\n}`;class Ef extends je{getFragmentShader(){return xf}getVertexShader(){return _f}}class wf extends Nr{constructor(e,t,n){super(),this.context=e;const i={context:e,height:n,width:t},s=new Fi({...i,radius:1,type:zr.GAUSSIAN});this.jointBilateral=new Ef(i),this.addStep({program:s,getUniforms:()=>({inputs:B(e,this.inputMask)})}),this.addStep({program:this.jointBilateral,getUniforms:()=>{const a=this.inputImage?.width??1,c=this.inputImage?.height??1;this.inputMask?.width,this.inputMask?.height;const u=3,d=Math.max(1,Math.sqrt(u)*.66),m=1/a,p=1/c;return{input_frame:B(e,this.inputImage),segmentation_mask:B(e,this.inputMask),texel_size:[m,p],step:d,radius:u,offset:d>1?d*.5:0,sigma_texel:Math.max(m,p)*u,sigma_color:u}}}),this.output=this.jointBilateral.output}setData(e,t){this.previousInputImage=this.inputImage?this.inputImage:e,this.previousInputMask=this.inputMask?this.inputMask:t,this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t),this.output=this.jointBilateral.output}}class vf{constructor(e){this.queries=[],this.context=e,this.extension=e.getExtension("EXT_disjoint_timer_query_webgl2")}start(){}stop(){this.activeQuery&&this.context.endQuery(this.extension.TIME_ELAPSED_EXT)}pushContext(e){this.createQuery("PUSH",e)}popContext(e){this.createQuery("POP",e)}createQuery(e,t){this.activeQuery&&this.context.endQuery(this.extension.TIME_ELAPSED_EXT),this.activeQuery=this.context.createQuery(),this.context.beginQuery(this.extension.TIME_ELAPSED_EXT,this.activeQuery),this.queries.push({name:t,action:e,query:this.activeQuery})}async getResolvedQueries(){const e=(await Promise.all([...this.queries].map(t=>this.resolveQuery(t)))).filter(t=>t);for(let t=1;t<e.length;++t)e[t].timestamp+=e[t-1].duration+e[t-1].timestamp;return e}async resolveQuery(e){if(!await this.awaitQueryAvailable(e)){console.log("Unawaitable query",e);return}if(this.context.getParameter(this.extension.GPU_DISJOINT_EXT)){console.log("Disjointed query",e);return}return{...e,duration:this.context.getQueryParameter(e.query,this.context.QUERY_RESULT),timestamp:0}}async awaitQueryAvailable(e){for(let t=0;t<10;++t){if(this.context.getQueryParameter(e.query,this.context.QUERY_RESULT_AVAILABLE))return e;await Ri(200)}}}class Nt{constructor(){this.previousImageWidth=0,this.previousImageHeight=0,this.previousMaskWidth=Ce,this.previousMaskHeight=Ce,this.postProcessingEnabled=!0;const e=new OffscreenCanvas(0,0),t=e.getContext("webgl2");if(!t)throw"Fail to retrieve webgl2 context";this.canvas=e,this.context=t,this.improveMask=new wf(this.context,Ce,Ce)}enablePostProcessing(){this.postProcessingEnabled=!0}disablePostProcessing(){this.postProcessingEnabled=!1}async profileWebgl(e){const t=new vf(this.context);return this.profiler=t,t.start(),await Ri(e),this.profiler=void 0,t.stop(),t.getResolvedQueries()}async render(e,t){if(!this.pipeline)throw"missing pipeline";(this.previousImageHeight!==e.height||this.previousImageWidth!==e.width)&&this.resizeOutput(e.width,e.height),(this.previousMaskHeight!==t.height||this.previousMaskWidth!==t.width)&&(this.improveMask.resizeOutput(t.width,t.height),this.previousMaskWidth=t.width,this.previousMaskHeight=t.height);const n="renderer";this.profiler?.pushContext(n),this.improveMask.setProfiler(this.profiler),this.pipeline.setProfiler(this.profiler);const i=await createImageBitmap(t);let s=i;return this.postProcessingEnabled&&(this.improveMask.setData(e,i),this.improveMask.run(),s=this.improveMask.output),this.pipeline.setData(e,s),await this.pipeline.run(),this.profiler?.popContext(n),this.canvas}resizeOutput(e,t){this.canvas.width=e,this.canvas.height=t,this.pipeline?.resizeOutput(e,t),this.previousImageWidth=e,this.previousImageHeight=t}destroy(){const e=this.context?.getExtension("WEBGL_lose_context");e&&e.loseContext()}}class Pi extends Nt{constructor(){super(),this.pipeline=new Ii(this.context);const e=new OffscreenCanvas(0,0),t=e.getContext("webgl2");if(!t)throw"Fail to retrieve webgl context";this.backgroundImageResizerCanvas=e,this.backgroundImageResizerContext=t,this.backgroundImageResizer=new gf(this.backgroundImageResizerContext,0,0)}setBackgroundImage(e){this.backgroundImage=e,this.updateBackgroundImage()}updateBackgroundImage(){const{width:e,height:t}=this.canvas;this.backgroundImageResizer.resizeOutput(e,t),this.backgroundImageResizer.setData(this.backgroundImage),this.backgroundImageResizer.run(),this.pipeline.inputBackgroundImage=this.backgroundImageResizerCanvas}resizeOutput(e,t){super.resizeOutput(e,t),this.backgroundImageResizerCanvas.width=e,this.backgroundImageResizerCanvas.height=t,this.backgroundImageResizer.resizeOutput(e,t),this.updateBackgroundImage()}destroy(){const e=this.backgroundImageResizerContext?.getExtension("WEBGL_lose_context");e&&e.loseContext(),super.destroy()}}class Tf extends Pi{setBackgroundVideo(e){this.frameReader=e}async render(e,t){return await this.readNextVideoFrame(),super.render(e,t)}async readNextVideoFrame(){const e=await this.frameReader?.read();if(e?.value){const t=await createImageBitmap(e.value);this.setBackgroundImage(t),e.value.close()}}}class ki{blurBackground(e){return new no(e)}blurSilhouette(e){return new io(e)}imageBackground(){return new so}videoBackground(){return new Tf}}var Af=`precision mediump float;\n\nvarying vec2 _texture_coord;\n\nuniform vec2 canvas;\nuniform sampler2D texture;\nuniform sampler2D mask;\n\nvec4 loop();\n\nvoid main() { gl_FragColor = loop(); }\n`,Sf=`varying vec2 _texture_coord;\n\nattribute vec2 position;\nattribute vec2 texture_coord;\n\nvoid main() {\n gl_Position = vec4(position, 0., 1.);\n _texture_coord = texture_coord;\n}\n`;class If extends je{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return Af+this.createLoopFunction()}getVertexShader(){return Sf}createLoopFunction(){let e=this.options.radius??1;return`\n\n vec4 loop() { \n vec4 result = vec4(0,0,0,0);\n float factorSum = 0.;\n\n vec2 normalizedRadius = vec2(-${e}.) / canvas;\n vec2 normalizedIncrement = vec2(1.) / canvas;\n vec2 diff = normalizedRadius;\n float maxLength = length(normalizedRadius);\n\n for(int y=-${e}; y<${e+1}; ++y) {\n for(int x=-${e}; x<${e+1}; ++x) {\n float factor = (1.- texture2D(mask, _texture_coord + diff).a) * (maxLength - length(diff)) / maxLength;\n result += factor * texture2D(texture, _texture_coord + diff);\n factorSum += factor;\n diff.x += normalizedIncrement.x;\n }\n diff.y += normalizedIncrement.y;\n diff.x = normalizedRadius.x;\n }\n return result / factorSum;\n }`}}const Rf=10,Ff=2,Pf=8;class kf extends Lr{constructor(e,t){super(),this.context=e,this.radius=t;const n={context:e,height:e.canvas.height,width:e.canvas.width};this.blur=new If({...n,radius:t,...this.getBlurTextureSize(e.canvas.width,e.canvas.height)});const i=new Ur({...n,disableFramebuffer:!0});this.addStep({program:this.blur,preventResize:!0,getUniforms:()=>({texture:B(e,this.inputImage),mask:B(e,this.inputMask)})}),this.addStep({program:i,getUniforms:()=>({background:B(e,this.blur.output),foreground:B(e,this.inputImage),threshold:B(e,this.inputMask)})})}getBlurTextureSize(e,t){const n=this.radius>Rf?Pf:Ff;return{width:Math.max(Ce,e/n),height:Math.max(Ce,t/n)}}setData(e,t){this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t);const n=this.getBlurTextureSize(e,t);this.blur.resizeOutput(n.width,n.height)}}class Cf extends Nt{constructor(e){super(),this.pipeline=new kf(this.context,e),this.disablePostProcessing()}}class Mf extends Lr{constructor(e,t){super(),this.context=e;const n={context:e,height:e.canvas.height,width:e.canvas.width},i=new Fi({...n,radius:t,type:zr.GAUSSIAN}),s=new Ur({...n,disableFramebuffer:!0});this.addStep({program:i,getUniforms:()=>({texture:B(e,this.inputImage)})}),this.addStep({program:s,getUniforms:()=>({background:B(e,this.inputImage),foreground:B(e,i.output),threshold:B(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}class Bf extends Nt{constructor(e){super(),this.pipeline=new Mf(this.context,e),this.disablePostProcessing()}}class Df extends Ii{constructor(){super(...arguments),this.preciseMaskEnabled=!0}set reader(e){this.frameReader=e}async run(){this.frameReader&&(await this.readNextVideoFrame(),await super.run())}async readNextVideoFrame(){const e=await this.frameReader?.read();e?.value&&(this.inputBackgroundImage=await createImageBitmap(e.value),e.value.close())}}class Of extends Nt{constructor(){super(),this.pipeline=new Df(this.context)}setBackgroundVideo(e){this.pipeline.reader=e}}class Ci{blurBackground(e){return new Cf(e)}blurSilhouette(e){return new Bf(e)}imageBackground(){return new Pi}videoBackground(){return new Of}}class Uf{constructor(e){switch(e){case gt.CANVAS:this.factory=new ki;break;case gt.WEBGL:this.factory=new Ci;break;default:const t=ro();this.factory=t.supported?new Ci:new ki}}blurBackground(e){return this.getFactory().blurBackground(e)}blurSilhouette(e){return this.getFactory().blurSilhouette(e)}imageBackground(){return this.getFactory().imageBackground()}videoBackground(){return this.getFactory().videoBackground()}getFactory(){if(!this.factory)throw"Factory is not initialized";return this.factory}}class Nf{setBackgroundOptions(e){this.renderer&&this.renderer.destroy();const t=new Uf(e.renderingOptions?.type);switch(e.transformerType){case"BackgroundBlur":this.renderer=t.blurBackground(this.getBlurSize(e.radius));break;case"SilhouetteBlur":this.renderer=t.blurSilhouette(this.getBlurSize(e.radius));break;case"VideoBackground":const n=t.videoBackground();this.backgroundVideo&&n.setBackgroundVideo(this.backgroundVideo),this.renderer=n;break;case"VirtualBackground":const i=t.imageBackground();this.backgroundImage&&i.setBackgroundImage(this.backgroundImage),this.renderer=i;break;default:throw`Unknown rendering type [${e.transformerType}]`}e.renderingOptions?.type===gt.WEBGL&&(e.renderingOptions.selfieSegmentationType===nr.PRECISE?this.renderer.enablePostProcessing():e.renderingOptions.selfieSegmentationType===nr.FAST&&this.renderer.disablePostProcessing())}setVideoBGReadable(e){this.backgroundVideo=e.getReader();const t=this.renderer;t?.setBackgroundVideo&&t.setBackgroundVideo(this.backgroundVideo)}async setVirtualBGImage(e){const t=this.renderer;t?.setBackgroundImage&&t.setBackgroundImage(e),this.backgroundImage=e}async process(e,t){if(this.renderer)return this.renderer.render(e,t)}async resizeForeground(e,t){}getBlurSize(e=pt.Low){switch(e){case pt.Low:return 5;case pt.High:return 12}return e}async profile(e){return this.renderer?.profileWebgl(e)??[]}}var Lf=(function(){var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return(function(e){e=e||{};var t=typeof e<"u"?e:{},n,i;t.ready=new Promise(function(f,h){n=f,i=h});var s={},o;for(o in t)t.hasOwnProperty(o)&&(s[o]=t[o]);var a="./this.program",c=function(f,h){throw h},u=!0,d="";function m(f){return t.locateFile?t.locateFile(f,d):d+f}var p;typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),r&&(d=r),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="";var y=t.print||console.log.bind(console),l=t.printErr||console.warn.bind(console);for(o in s)s.hasOwnProperty(o)&&(t[o]=s[o]);s=null,t.arguments&&t.arguments,t.thisProgram&&(a=t.thisProgram),t.quit&&(c=t.quit);var b;t.wasmBinary&&(b=t.wasmBinary),t.noExitRuntime,typeof WebAssembly!="object"&&ae("no native wasm support detected");var _,E=!1,R=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function k(f,h,g){for(var w=h+g,I=h;f[I]&&!(I>=w);)++I;if(I-h>16&&f.subarray&&R)return R.decode(f.subarray(h,I));for(var C="";h<I;){var v=f[h++];if(!(v&128)){C+=String.fromCharCode(v);continue}var D=f[h++]&63;if((v&224)==192){C+=String.fromCharCode((v&31)<<6|D);continue}var H=f[h++]&63;if((v&240)==224?v=(v&15)<<12|D<<6|H:v=(v&7)<<18|D<<12|H<<6|f[h++]&63,v<65536)C+=String.fromCharCode(v);else{var Gi=v-65536;C+=String.fromCharCode(55296|Gi>>10,56320|Gi&1023)}}return C}function N(f,h){return f?k(Ye,f,h):""}function Q(f,h,g){for(var w=0;w<f.length;++w)Lt[h++>>0]=f.charCodeAt(w);Lt[h>>0]=0}function q(f,h){return f%h>0&&(f+=h-f%h),f}var L,Lt,Ye,$;function Bi(f){L=f,t.HEAP8=Lt=new Int8Array(f),t.HEAP16=new Int16Array(f),t.HEAP32=$=new Int32Array(f),t.HEAPU8=Ye=new Uint8Array(f),t.HEAPU16=new Uint16Array(f),t.HEAPU32=new Uint32Array(f),t.HEAPF32=new Float32Array(f),t.HEAPF64=new Float64Array(f)}t.INITIAL_MEMORY;var $r,Di=[],Oi=[],Ui=[];function qf(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)Zf(t.preRun.shift());Wr(Di)}function Kf(){Wr(Oi)}function Jf(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)tl(t.postRun.shift());Wr(Ui)}function Zf(f){Di.unshift(f)}function el(f){Oi.unshift(f)}function tl(f){Ui.unshift(f)}var be=0,Xe=null;function rl(f){be++,t.monitorRunDependencies&&t.monitorRunDependencies(be)}function nl(f){if(be--,t.monitorRunDependencies&&t.monitorRunDependencies(be),be==0&&Xe){var h=Xe;Xe=null,h()}}t.preloadedImages={},t.preloadedAudios={};function ae(f){t.onAbort&&t.onAbort(f),f="Aborted("+f+")",l(f),E=!0,f+=". Build with -s ASSERTIONS=1 for more info.";var h=new WebAssembly.RuntimeError(f);throw i(h),h}var il="data:application/octet-stream;base64,";function Ni(f){return f.startsWith(il)}var W;W="tflite-simd.wasm",Ni(W)||(W=m(W));function Li(f){try{if(f==W&&b)return new Uint8Array(b);if(!p)throw"both async and sync fetching of the wasm failed"}catch(h){ae(h)}}function sl(){return!b&&u&&typeof fetch=="function"?fetch(W,{credentials:"same-origin"}).then(function(f){if(!f.ok)throw"failed to load wasm binary file at \'"+W+"\'";return f.arrayBuffer()}).catch(function(){return Li(W)}):Promise.resolve().then(function(){return Li(W)})}function ol(){var f={a:Il};function h(v,D){var H=v.exports;t.asm=H,_=t.asm.q,Bi(_.buffer),$r=t.asm.E,el(t.asm.r),nl()}rl();function g(v){h(v.instance)}function w(v){return sl().then(function(D){return WebAssembly.instantiate(D,f)}).then(function(D){return D}).then(v,function(D){l("failed to asynchronously prepare wasm: "+D),ae(D)})}function I(){return!b&&typeof WebAssembly.instantiateStreaming=="function"&&!Ni(W)&&typeof fetch=="function"?fetch(W,{credentials:"same-origin"}).then(function(v){var D=WebAssembly.instantiateStreaming(v,f);return D.then(g,function(H){return l("wasm streaming compile failed: "+H),l("falling back to ArrayBuffer instantiation"),w(g)})}):w(g)}if(t.instantiateWasm)try{var C=t.instantiateWasm(f,h);return C}catch(v){return l("Module.instantiateWasm callback failed with error: "+v),!1}return I().catch(i),{}}function Wr(f){for(;f.length>0;){var h=f.shift();if(typeof h=="function"){h(t);continue}var g=h.func;typeof g=="number"?h.arg===void 0?$r.get(g)():$r.get(g)(h.arg):g(h.arg===void 0?null:h.arg)}}function al(f,h,g,w){ae("Assertion failed: "+N(f)+", at: "+[h?N(h):"unknown filename",g,w?N(w):"unknown function"])}function cl(f,h){ae("To use dlopen, you need to use Emscripten\'s linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")}function ul(f,h){ae("To use dlopen, you need to use Emscripten\'s linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")}function fl(){ae("")}var zt;zt=function(){return performance.now()};var ll=!0;function dl(f){return $[zi()>>2]=f,f}function hl(f,h){var g;if(f===0)g=Date.now();else if((f===1||f===4)&&ll)g=zt();else return dl(28),-1;return $[h>>2]=g/1e3|0,$[h+4>>2]=g%1e3*1e3*1e3|0,0}function ml(){return 2147483648}function pl(f,h,g){Ye.copyWithin(f,h,h+g)}function gl(f){try{return _.grow(f-L.byteLength+65535>>>16),Bi(_.buffer),1}catch{}}function yl(f){var h=Ye.length;f=f>>>0;var g=2147483648;if(f>g)return!1;for(var w=1;w<=4;w*=2){var I=h*(1+.2/w);I=Math.min(I,f+100663296);var C=Math.min(g,q(Math.max(f,I),65536)),v=gl(C);if(v)return!0}return!1}function bl(f){for(var h=zt();zt()-h<f;);}var Vr={};function xl(){return a||"./this.program"}function Qe(){if(!Qe.strings){var f=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",h={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:f,_:xl()};for(var g in Vr)Vr[g]===void 0?delete h[g]:h[g]=Vr[g];var w=[];for(var g in h)w.push(g+"="+h[g]);Qe.strings=w}return Qe.strings}var Gt={mappings:{},buffers:[null,[],[]],printChar:function(f,h){var g=Gt.buffers[f];h===0||h===10?((f===1?y:l)(k(g,0)),g.length=0):g.push(h)},varargs:void 0,get:function(){Gt.varargs+=4;var f=$[Gt.varargs-4>>2];return f},getStr:function(f){var h=N(f);return h},get64:function(f,h){return f}};function _l(f,h){var g=0;return Qe().forEach(function(w,I){var C=h+g;$[f+I*4>>2]=C,Q(w,C),g+=w.length+1}),0}function El(f,h){var g=Qe();$[f>>2]=g.length;var w=0;return g.forEach(function(I){w+=I.length+1}),$[h>>2]=w,0}function wl(f){Fl(f)}function vl(f){return 0}function Tl(f,h,g,w,I){}function Al(f,h,g,w){for(var I=0,C=0;C<g;C++){for(var v=$[h+C*8>>2],D=$[h+(C*8+4)>>2],H=0;H<D;H++)Gt.printChar(f,Ye[v+H]);I+=D}return $[w>>2]=I,0}function Sl(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var f=new Uint8Array(1);return function(){return crypto.getRandomValues(f),f[0]}}else return function(){ae("randomDevice")}}function $t(f,h){$t.randomDevice||($t.randomDevice=Sl());for(var g=0;g<h;g++)Lt[f+g>>0]=$t.randomDevice();return 0}var Il={a:al,e:cl,d:ul,b:fl,n:hl,h:ml,l:pl,m:yl,p:bl,f:_l,g:El,j:wl,i:vl,k:Tl,c:Al,o:$t};ol(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.r).apply(null,arguments)},t._getModelBufferMemoryOffset=function(){return(t._getModelBufferMemoryOffset=t.asm.s).apply(null,arguments)},t._getInputMemoryOffset=function(){return(t._getInputMemoryOffset=t.asm.t).apply(null,arguments)},t._getInputHeight=function(){return(t._getInputHeight=t.asm.u).apply(null,arguments)},t._getInputWidth=function(){return(t._getInputWidth=t.asm.v).apply(null,arguments)},t._getInputChannelCount=function(){return(t._getInputChannelCount=t.asm.w).apply(null,arguments)},t._getOutputMemoryOffset=function(){return(t._getOutputMemoryOffset=t.asm.x).apply(null,arguments)},t._getOutputHeight=function(){return(t._getOutputHeight=t.asm.y).apply(null,arguments)},t._getOutputWidth=function(){return(t._getOutputWidth=t.asm.z).apply(null,arguments)},t._getOutputChannelCount=function(){return(t._getOutputChannelCount=t.asm.A).apply(null,arguments)},t._loadModel=function(){return(t._loadModel=t.asm.B).apply(null,arguments)},t._runInference=function(){return(t._runInference=t.asm.C).apply(null,arguments)},t._isGPUEnabled=function(){return(t._isGPUEnabled=t.asm.D).apply(null,arguments)};var zi=t.___errno_location=function(){return(zi=t.___errno_location=t.asm.F).apply(null,arguments)},Wt;function Rl(f){this.name="ExitStatus",this.message="Program terminated with exit("+f+")",this.status=f}Xe=function f(){Wt||Hr(),Wt||(Xe=f)};function Hr(f){if(be>0||(qf(),be>0))return;function h(){Wt||(Wt=!0,t.calledRun=!0,!E&&(Kf(),n(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),Jf()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),h()},1)):h()}t.run=Hr;function Fl(f,h){Pl(f)}function Pl(f){c(f,new Rl(f))}if(t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();return Hr(),e.ready})})();class zf{constructor(){this.isSIMDSupported=!1,this.isThreadsSupported=!1,this.inputWidth=0,this.inputHeight=0,this.inputChannelCount=0,this.inputMemoryOffset=0,this.outputWidth=0,this.outputHeight=0,this.outputChannelCount=0,this.outputMemoryOffset=0}}const Gf="https://d3opqjmqzxf057.cloudfront.net/vonage-tensorflow-wasm/tflite-simd-wasm/1.1.3/",$f="https://d3opqjmqzxf057.cloudfront.net/ml/selfie_segmentation/4.0.0/selfie_segmentation_landscape.tflite";async function Wf(r=Gf,e=$f){let t=new zf;var n=new Promise(function(i,s){async function o(){return Lf({locateFile:function(u){return r+u}})}async function a(c){return new Promise(async(u,d)=>{const m=c;if(typeof m>"u")return d("TFLite backend unavailable: wasmSimd");let p=e;console.log("TFLite modelUrl: "+p);try{const l=await(await fetch(p)).arrayBuffer();console.log("Model buffer size:",l.byteLength);const b=m._getModelBufferMemoryOffset();console.log("Model buffer memory offset:",b),console.log("Loading model buffer..."),m.HEAPU8.set(new Uint8Array(l),b);const _=m._loadModel(l.byteLength);if(console.log("Load model result:",_),_!==0){d("Cannot load model");return}t.inputWidth=m._getInputWidth(),t.inputHeight=m._getInputHeight(),t.inputChannelCount=m._getInputChannelCount(),t.inputMemoryOffset=m._getInputMemoryOffset(),console.log("Input memory offset:",t.inputMemoryOffset),console.log("Input height:",t.inputHeight),console.log("Input width:",t.inputWidth),console.log("Input channels:",t.inputChannelCount),t.outputMemoryOffset=m._getOutputMemoryOffset(),t.outputWidth=m._getOutputWidth(),t.outputHeight=m._getOutputHeight(),t.outputChannelCount=m._getOutputChannelCount(),console.log("Output memory offset:",t.outputMemoryOffset),console.log("Output height:",t.outputHeight),console.log("Output width:",t.outputWidth),console.log("Output channels:",t.outputChannelCount),t.selectedTFLite=m}catch(y){d(y);return}u()})}o().then(c=>{if(c===null)throw console.error("loadTFLite null"),"loadTFLite null";a(c).then(u=>{i(t)}).catch(u=>{console.error("loadTFLiteModel error"),s("loadTFLiteModel error")})}).catch(c=>{console.error("loadTFLite error:",c),s("loadTFLite error:"+c)})});return n}const Vf=.1,Hf=.7,jf="https://d3opqjmqzxf057.cloudfront.net/ml/vonage_selfie_segmenter/float16/v1/vonage_selfie_segmenter.tflite";class Yf{constructor(){this.canvas=new OffscreenCanvas(0,0),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.width=0,this.height=0,this.gpuDelegate=!0}async createImageSegmenter(){if(!this.ImageSegmenter||!this.wasmFileset){console.warn("Mediapipe objects not loaded");return}this.imageSegmenter=await this.ImageSegmenter.createFromOptions(this.wasmFileset,{baseOptions:{modelAssetPath:this.modelAssetUriPath,delegate:this.gpuDelegate?"GPU":"CPU"},runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!0})}async loadMediapipeAssets(e,t){this.modelAssetUriPath=e||jf;const n=t?`${t}/task-vision.js`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/+esm",i=t?`${t}/wasm`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/wasm",{FilesetResolver:s,ImageSegmenter:o}=await import(n);this.ImageSegmenter=o,this.wasmFileset=await s.forVisionTasks(i)}async init(e,t,n){n===!1&&(this.gpuDelegate=!1),await this.loadMediapipeAssets(e,t),globalThis.document={},await this.createImageSegmenter()}async process(e){if(!this.imageSegmenter){console.warn("ImageSegmenter instance not available");return}(this.width!==e.width||this.height!==e.height)&&(this.canvas.width=this.width=e.width,this.canvas.height=this.height=e.height,this.mask&&(this.mask=new ImageData(this.width,this.height))),this.mask||(this.mask=new ImageData(this.width,this.height)),this.context.drawImage(e,0,0,e.width,e.height);const t=Date.now();let n;try{this.imageSegmenter?.segmentForVideo(this.context.getImageData(0,0,e.width,e.height),t,o=>{n=o.confidenceMasks?.[0]?.getAsFloat32Array()})}catch{await this.createImageSegmenter();return}if(!n)return;if(!this.previousConfidenceMask){this.previousConfidenceMask=n.slice();return}const i=n.map((o,a)=>{const c=this.previousConfidenceMask?.[a];return c!==void 0?this.blend(c,o):o}),s=[255,0,0];for(let o=0;o<i?.length;o++){const a=1-i[o];a>Vf?(a<Hf?(this.mask.data[o*4]=s[0]*a,this.mask.data[o*4+3]=255*a):(this.mask.data[o*4]=s[0],this.mask.data[o*4+3]=255),this.mask.data[o*4+1]=s[1],this.mask.data[o*4+2]=s[2]):this.mask.data[o*4]=this.mask.data[o*4+1]=this.mask.data[o*4+2]=this.mask.data[o*4+3]=0}return this.previousConfidenceMask=i.slice(),this.mask}isGpuSupported(){return!0}blend(e,t){const i=-.748699,s=-57.8051,o=291.309,a=-624.717,c=t-.5,u=c*c,d=1-Math.min(1,u*(5.68842+u*(i+u*(s+u*(o+u*a)))));return t+(e-t)*(d*.9)}}class Xf{constructor(){this.canvas=new OffscreenCanvas(0,0),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.pixelCount=0,this.inputOffset=0,this.outputOffset=0}async init(e,t,n){await this.initWasm(t,e),this.infos&&(this.canvas.width=this.infos.inputWidth,this.canvas.height=this.infos.inputHeight,this.pixelCount=this.infos.inputWidth*this.infos.inputHeight,this.mask=new ImageData(this.infos.inputWidth,this.infos.inputHeight),this.inputOffset=this.infos.inputMemoryOffset/4,this.outputOffset=this.infos.outputMemoryOffset/4)}async initWasm(e,t){this.infos=await Wf(e,t)}async process(e){if(!this.mask||!this.infos)return;const t=this.infos.inputWidth,n=this.infos.inputHeight;this.context.drawImage(e,0,0,e.width,e.height,0,0,t,n);const i=this.context.getImageData(0,0,t,n),s=this.infos.selectedTFLite.HEAPF32;for(let o=0;o<this.pixelCount;o++){const a=this.inputOffset+o*3;s[a]=i.data[o*4]/255,s[a+1]=i.data[o*4+1]/255,s[a+2]=i.data[o*4+2]/255}this.infos.selectedTFLite._runInference();for(let o=0;o<this.pixelCount;o++){const a=this.infos.selectedTFLite.HEAPF32[this.outputOffset+o];this.mask.data[o*4]=this.mask.data[o*4+3]=255*a}return this.mask}isGpuSupported(){return this.infos?.selectedTFLite?._isGPUEnabled()??!1}}class Qf{constructor(){this.reporter=new eo,this.isEnabled=!0}async init(e,t){t.segmentationOptions?.lightWeightEngine===!0?this.selfieSegmentation=new Xf:this.selfieSegmentation=new Yf,this.selfieSegmentation?.init(t.modelAssetUriPath,t.mediapipeBaseAssetsUri,t.segmentationOptions?.gpuSupport),this.backgroundFilter=new Nf,this.report({variation:"Create"})}async transform(e,t){if(!this.isEnabled)return t.enqueue(e);let n;const i=e.timestamp??0,s=await createImageBitmap(e),o=await this.selfieSegmentation?.process(s);o&&(n=await this.backgroundFilter?.process(s,o)),n?(e.close(),t.enqueue(new VideoFrame(n,{timestamp:i,alpha:"discard"}))):t.enqueue(e)}async setBackgroundOptions(e){this.backgroundOptions=e,this.backgroundFilter?.setBackgroundOptions(e),this.report({variation:"Update"})}setVideoBGReadable(e){this.backgroundFilter?.setVideoBGReadable(e)}async setVirtualBGImage(e){await this.backgroundFilter?.setVirtualBGImage(e)}async profile(e){return this.backgroundFilter?.profile(e)??[]}getTransformerType(){return this.backgroundOptions?.transformerType??"Undefined"}enable(){this.isEnabled=!0}disable(){this.isEnabled=!1}report(e){this.reporter.send({version:to,action:"MlTransformers",transformerType:this.backgroundOptions?.transformerType,config:JSON.stringify(this.backgroundOptions),...e})}}const Gr=class Gr{constructor(){this.backgroundTransformer=new Qf,this.mediaProcessor=new Ps,this.rate=30,this.eventsQueue=[],this.frameTransformLatencyMs=[]}async init(e,t){this.frameTransformLatencyMs=[],await this.backgroundTransformer.init(e,t),await this.mediaProcessor.setTransformers([this.backgroundTransformer]),this.mediaProcessor.setTrackExpectedRate(this.rate),this.mediaProcessor.onAny((n,i)=>{this.resolveOnMediaProcessor?(this.resolveOnMediaProcessor({name:n,data:i}),this.resolveOnMediaProcessor=void 0):this.eventsQueue.push({name:n,data:i})})}enable(){this.backgroundTransformer.enable()}disable(){this.backgroundTransformer.disable()}async onMediaProcessorEvent(){return await new Promise(e=>{this.eventsQueue.length>0?e(this.eventsQueue.shift()):this.resolveOnMediaProcessor=e})}async setTrackExpectedRate(e){this.rate=e,this.mediaProcessor.setTrackExpectedRate(e)}async transform(e,t){let n=this.mediaProcessor.transform(e,t),i=performance.now();return this.frameTransformLatencyMs.push(performance.now()-i),n}async setBackgroundOptions(e){await this.backgroundTransformer?.setBackgroundOptions(e)}setVideoBGReadable(e){this.backgroundTransformer.setVideoBGReadable(e)}async setVirtualBGImage(e){await this.backgroundTransformer.setVirtualBGImage(e)}async terminate(){await this.mediaProcessor.destroy();const t=this.frameTransformLatencyMs.reduce((n,i)=>n+i,0)/this.frameTransformLatencyMs.length||0;console.log(`Transform latency average is: ${t} ms`)}setVonageMetadata(e){ws(e)}async profile(e){return JSON.stringify(await this.backgroundTransformer.profile(e))}};ji("ProcessorWorker",Gr);let Mi=Gr})();\n//# sourceMappingURL=processor-worker-BKH_E7wA.js.map\n',_o=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",vo],{type:"text/javascript;charset=utf-8"});function qf(r){let e;try{if(e=_o&&(self.URL||self.webkitURL).createObjectURL(_o),!e)throw"";const t=new Worker(e,{name:r?.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(vo),{name:r?.name})}}const ur=class ur extends Qe{constructor(e){super(),this.rate=30,this.isEnabled=!0,this.config=e}async setTrackExpectedRate(e){await this.startWorker(),await this.worker?.setTrackExpectedRate(e)}async setBackgroundOptions(e){this.backgroundOptions=e,await this.updateBackgroundOptions(e)}async transform(e,t){return await this.startWorker(),await this.worker?.transform(e,t)}async destroy(){await this.worker?.terminate(),this.worker=void 0}async profile(e){const t=await this.worker?.profile(e);return JSON.parse(t??"[]")}async enable(){this.isEnabled=!0,await this.worker?.enable()}async disable(){this.isEnabled=!1,await this.worker?.disable()}async listenWorker(){for(;this.worker?.workerContext.worker;){const{name:e,data:t}=await this.worker?.onMediaProcessorEvent();switch(e){case"error":case"warn":this.emit(e,t);break;case"pipelineInfo":switch(this.emit(e,t),t){case"pipeline_ended":case"pipeline_ended_with_error":await this.destroy();return}break}}}async startWorker(){!this.config||this.worker||(this.worker=await Ss(fn,qf),this.isEnabled||await this.worker.disable(),await this.worker.init(`worker_${ur.initCount++}`,this.config),await this.worker.setVonageMetadata(wt()),this.backgroundOptions?await this.setBackgroundOptions(this.backgroundOptions):await this.setBackgroundOptions(this.config),this.listenWorker())}async updateBackgroundOptions(e){await this.startWorker();const{transformerType:t}=e;switch(t){case"VideoBackground":await this.worker?.setVideoBGReadable(await jn.createVideoReadable(e.backgroundAssetUri));break;case"VirtualBackground":await this.worker?.setVirtualBGImage(await jn.createImageCanvas(e.backgroundAssetUri));break}await this.worker?.setBackgroundOptions(e)}};ur.initCount=0;let dn=ur;class Xf{constructor(e){this.queries=e}async downloadSpeedscope(){this.download(await this.convertToSpeedscope())}download(e){const t=document.createElement("a");t.href=URL.createObjectURL(new Blob([e],{type:"application/json"})),t.download=`profile-${+new Date}.speedscope.json`,document.body.appendChild(t),t.click(),document.body.removeChild(t)}convertToSpeedscope(){const e=[],t={},n=[];let i=0;for(const s of this.queries){const a=[];for(const c of s)t[c.name]===void 0&&(t[c.name]=e.length,e.push({name:c.name})),a.push({type:c.action==go.PUSH?"O":"C",frame:t[c.name],at:c.timestamp}),i=Math.max(i,c.timestamp+c.duration);n.push({events:a,type:"evented",name:"GPU Profile",unit:"nanoseconds",startValue:0,endValue:i})}return JSON.stringify({$schema:"https://www.speedscope.app/file-format-schema.json",shared:{frames:e},profiles:n},null,2)}}const mn=class mn extends Qe{constructor(e){super(),this.worker=new dn(e),this.connector=new hs(this.worker),this.worker.onAny((t,n)=>this.emit(t,n))}async setBackgroundOptions(e){await this.worker.setBackgroundOptions(e)}async enable(){await this.worker.enable()}async disable(){await this.worker.disable()}setTrackExpectedRate(e){this.worker.setTrackExpectedRate(e)}getConnector(){return this.connector}async profile(e){return this.worker.profile(e)}static async profile(e){const t=await Promise.all(this.instances.map(n=>n.profile(e)));return new Xf(t)}static async create(e){const t=new this(e);return this.instances.push(t),t}};mn.instances=[];let cr=mn;async function Kf(r){return await cr.create(r)}R.BackgroundTransformer=xo,R.BackgroundTransformerType=Cn,R.BlurRadius=He,R.ErrorFunction=Fn,R.PipelineInfoData=vt,R.RenderingType=je,R.VonageMediaProcessor=cr,R.WarningType=Pn,R.WebglSelfieSegmentationType=_t,R.createVonageMediaProcessor=Kf,R.getSupportedBrowserFeatures=Mn,R.isSupported=ps,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})}));
193
+ }`}}const Ff=10,Cf=2,Of=8;class Mf extends cn{constructor(e,t){super(),this.context=e,this.radius=t;const n={context:e,height:e.canvas.height,width:e.canvas.width};this.blur=new Pf({...n,radius:t,...this.getBlurTextureSize(e.canvas.width,e.canvas.height)});const i=new sn({...n,disableFramebuffer:!0});this.addStep({program:this.blur,preventResize:!0,getUniforms:()=>({texture:B(e,this.inputImage),mask:B(e,this.inputMask)})}),this.addStep({program:i,getUniforms:()=>({background:B(e,this.blur.output),foreground:B(e,this.inputImage),threshold:B(e,this.inputMask)})})}getBlurTextureSize(e,t){const n=this.radius>Ff?Of:Cf;return{width:Math.max($e,e/n),height:Math.max($e,t/n)}}setData(e,t){this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t);const n=this.getBlurTextureSize(e,t);this.blur.resizeOutput(n.width,n.height)}}class Bf extends ar{constructor(e){super(),this.pipeline=new Mf(this.context,e),this.disablePostProcessing()}}class Df extends cn{constructor(e,t){super(),this.context=e;const n={context:e,height:e.canvas.height,width:e.canvas.width},i=new mo({...n,radius:t,type:un.GAUSSIAN}),o=new sn({...n,disableFramebuffer:!0});this.addStep({program:i,getUniforms:()=>({texture:B(e,this.inputImage)})}),this.addStep({program:o,getUniforms:()=>({background:B(e,this.inputImage),foreground:B(e,i.output),threshold:B(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}class Uf extends ar{constructor(e){super(),this.pipeline=new Df(this.context,e),this.disablePostProcessing()}}class Lf extends fo{constructor(){super(...arguments),this.preciseMaskEnabled=!0}set reader(e){this.frameReader=e}async run(){this.frameReader&&(await this.readNextVideoFrame(),await super.run())}async readNextVideoFrame(){const e=await this.frameReader?.read();e?.value&&(this.inputBackgroundImage=await createImageBitmap(e.value),e.value.close())}}class zf extends ar{constructor(){super(),this.pipeline=new Lf(this.context)}setBackgroundVideo(e){this.pipeline.reader=e}}class bo{blurBackground(e){return new Bf(e)}blurSilhouette(e){return new Uf(e)}imageBackground(){return new go}videoBackground(){return new zf}}class Nf{constructor(e){switch(e){case je.CANVAS:this.factory=new yo;break;case je.WEBGL:this.factory=new bo;break;default:const t=Mn();this.factory=t.supported?new bo:new yo}}blurBackground(e){return this.getFactory().blurBackground(e)}blurSilhouette(e){return this.getFactory().blurSilhouette(e)}imageBackground(){return this.getFactory().imageBackground()}videoBackground(){return this.getFactory().videoBackground()}getFactory(){if(!this.factory)throw"Factory is not initialized";return this.factory}}class $f{setBackgroundOptions(e){this.renderer&&this.renderer.destroy();const t=new Nf(e.renderingOptions?.type);switch(e.transformerType){case"BackgroundBlur":this.renderer=t.blurBackground(this.getBlurSize(e.radius));break;case"SilhouetteBlur":this.renderer=t.blurSilhouette(this.getBlurSize(e.radius));break;case"VideoBackground":const n=t.videoBackground();this.backgroundVideo&&n.setBackgroundVideo(this.backgroundVideo),this.renderer=n;break;case"VirtualBackground":const i=t.imageBackground();this.backgroundImage&&i.setBackgroundImage(this.backgroundImage),this.renderer=i;break;default:throw`Unknown rendering type [${e.transformerType}]`}e.renderingOptions?.type===je.WEBGL&&(e.renderingOptions.selfieSegmentationType===_t.PRECISE?this.renderer.enablePostProcessing():e.renderingOptions.selfieSegmentationType===_t.FAST&&this.renderer.disablePostProcessing())}setVideoBGReadable(e){this.backgroundVideo=e.getReader();const t=this.renderer;t?.setBackgroundVideo&&t.setBackgroundVideo(this.backgroundVideo)}async setVirtualBGImage(e){const t=this.renderer;t?.setBackgroundImage&&t.setBackgroundImage(e),this.backgroundImage=e}async process(e,t){if(this.renderer)return this.renderer.render(e,t)}async resizeForeground(e,t){}getBlurSize(e=He.Low){switch(e){case He.Low:return 5;case He.High:return 12}return e}async profile(e){return this.renderer?.profileWebgl(e)??[]}}var Wf=(function(){var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return(function(e){e=e||{};var t=typeof e<"u"?e:{},n,i;t.ready=new Promise(function(l,h){n=l,i=h});var o={},s;for(s in t)t.hasOwnProperty(s)&&(o[s]=t[s]);var a="./this.program",c=function(l,h){throw h},u=!0,f="";function m(l){return t.locateFile?t.locateFile(l,f):f+l}var p;typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),r&&(f=r),f.indexOf("blob:")!==0?f=f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):f="";var b=t.print||console.log.bind(console),d=t.printErr||console.warn.bind(console);for(s in o)o.hasOwnProperty(s)&&(t[s]=o[s]);o=null,t.arguments&&t.arguments,t.thisProgram&&(a=t.thisProgram),t.quit&&(c=t.quit);var g;t.wasmBinary&&(g=t.wasmBinary),t.noExitRuntime,typeof WebAssembly!="object"&&fe("no native wasm support detected");var x,v=!1,R=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function C(l,h,y){for(var _=h+y,I=h;l[I]&&!(I>=_);)++I;if(I-h>16&&l.subarray&&R)return R.decode(l.subarray(h,I));for(var O="";h<I;){var E=l[h++];if(!(E&128)){O+=String.fromCharCode(E);continue}var D=l[h++]&63;if((E&224)==192){O+=String.fromCharCode((E&31)<<6|D);continue}var Y=l[h++]&63;if((E&240)==224?E=(E&15)<<12|D<<6|Y:E=(E&7)<<18|D<<12|Y<<6|l[h++]&63,E<65536)O+=String.fromCharCode(E);else{var ko=E-65536;O+=String.fromCharCode(55296|ko>>10,56320|ko&1023)}}return O}function N(l,h){return l?C(at,l,h):""}function J(l,h,y){for(var _=0;_<l.length;++_)lr[h++>>0]=l.charCodeAt(_);lr[h>>0]=0}function Z(l,h){return l%h>0&&(l+=h-l%h),l}var $,lr,at,V;function _o(l){$=l,t.HEAP8=lr=new Int8Array(l),t.HEAP16=new Int16Array(l),t.HEAP32=V=new Int32Array(l),t.HEAPU8=at=new Uint8Array(l),t.HEAPU16=new Uint16Array(l),t.HEAPU32=new Uint32Array(l),t.HEAPF32=new Float32Array(l),t.HEAPF64=new Float64Array(l)}t.INITIAL_MEMORY;var mn,Eo=[],Ao=[],To=[];function td(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)id(t.preRun.shift());pn(Eo)}function rd(){pn(Ao)}function nd(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)sd(t.postRun.shift());pn(To)}function id(l){Eo.unshift(l)}function od(l){Ao.unshift(l)}function sd(l){To.unshift(l)}var Ae=0,ct=null;function ad(l){Ae++,t.monitorRunDependencies&&t.monitorRunDependencies(Ae)}function cd(l){if(Ae--,t.monitorRunDependencies&&t.monitorRunDependencies(Ae),Ae==0&&ct){var h=ct;ct=null,h()}}t.preloadedImages={},t.preloadedAudios={};function fe(l){t.onAbort&&t.onAbort(l),l="Aborted("+l+")",d(l),v=!0,l+=". Build with -s ASSERTIONS=1 for more info.";var h=new WebAssembly.RuntimeError(l);throw i(h),h}var ud="data:application/octet-stream;base64,";function So(l){return l.startsWith(ud)}var H;H="tflite-simd.wasm",So(H)||(H=m(H));function Io(l){try{if(l==H&&g)return new Uint8Array(g);if(!p)throw"both async and sync fetching of the wasm failed"}catch(h){fe(h)}}function ld(){return!g&&u&&typeof fetch=="function"?fetch(H,{credentials:"same-origin"}).then(function(l){if(!l.ok)throw"failed to load wasm binary file at '"+H+"'";return l.arrayBuffer()}).catch(function(){return Io(H)}):Promise.resolve().then(function(){return Io(H)})}function fd(){var l={a:Cd};function h(E,D){var Y=E.exports;t.asm=Y,x=t.asm.q,_o(x.buffer),mn=t.asm.E,od(t.asm.r),cd()}ad();function y(E){h(E.instance)}function _(E){return ld().then(function(D){return WebAssembly.instantiate(D,l)}).then(function(D){return D}).then(E,function(D){d("failed to asynchronously prepare wasm: "+D),fe(D)})}function I(){return!g&&typeof WebAssembly.instantiateStreaming=="function"&&!So(H)&&typeof fetch=="function"?fetch(H,{credentials:"same-origin"}).then(function(E){var D=WebAssembly.instantiateStreaming(E,l);return D.then(y,function(Y){return d("wasm streaming compile failed: "+Y),d("falling back to ArrayBuffer instantiation"),_(y)})}):_(y)}if(t.instantiateWasm)try{var O=t.instantiateWasm(l,h);return O}catch(E){return d("Module.instantiateWasm callback failed with error: "+E),!1}return I().catch(i),{}}function pn(l){for(;l.length>0;){var h=l.shift();if(typeof h=="function"){h(t);continue}var y=h.func;typeof y=="number"?h.arg===void 0?mn.get(y)():mn.get(y)(h.arg):y(h.arg===void 0?null:h.arg)}}function dd(l,h,y,_){fe("Assertion failed: "+N(l)+", at: "+[h?N(h):"unknown filename",y,_?N(_):"unknown function"])}function hd(l,h){fe("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")}function md(l,h){fe("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")}function pd(){fe("")}var fr;fr=function(){return performance.now()};var gd=!0;function yd(l){return V[Ro()>>2]=l,l}function bd(l,h){var y;if(l===0)y=Date.now();else if((l===1||l===4)&&gd)y=fr();else return yd(28),-1;return V[h>>2]=y/1e3|0,V[h+4>>2]=y%1e3*1e3*1e3|0,0}function wd(){return 2147483648}function xd(l,h,y){at.copyWithin(l,h,h+y)}function vd(l){try{return x.grow(l-$.byteLength+65535>>>16),_o(x.buffer),1}catch{}}function _d(l){var h=at.length;l=l>>>0;var y=2147483648;if(l>y)return!1;for(var _=1;_<=4;_*=2){var I=h*(1+.2/_);I=Math.min(I,l+100663296);var O=Math.min(y,Z(Math.max(l,I),65536)),E=vd(O);if(E)return!0}return!1}function Ed(l){for(var h=fr();fr()-h<l;);}var gn={};function Ad(){return a||"./this.program"}function ut(){if(!ut.strings){var l=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",h={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:l,_:Ad()};for(var y in gn)gn[y]===void 0?delete h[y]:h[y]=gn[y];var _=[];for(var y in h)_.push(y+"="+h[y]);ut.strings=_}return ut.strings}var dr={mappings:{},buffers:[null,[],[]],printChar:function(l,h){var y=dr.buffers[l];h===0||h===10?((l===1?b:d)(C(y,0)),y.length=0):y.push(h)},varargs:void 0,get:function(){dr.varargs+=4;var l=V[dr.varargs-4>>2];return l},getStr:function(l){var h=N(l);return h},get64:function(l,h){return l}};function Td(l,h){var y=0;return ut().forEach(function(_,I){var O=h+y;V[l+I*4>>2]=O,J(_,O),y+=_.length+1}),0}function Sd(l,h){var y=ut();V[l>>2]=y.length;var _=0;return y.forEach(function(I){_+=I.length+1}),V[h>>2]=_,0}function Id(l){Md(l)}function Rd(l){return 0}function kd(l,h,y,_,I){}function Pd(l,h,y,_){for(var I=0,O=0;O<y;O++){for(var E=V[h+O*8>>2],D=V[h+(O*8+4)>>2],Y=0;Y<D;Y++)dr.printChar(l,at[E+Y]);I+=D}return V[_>>2]=I,0}function Fd(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var l=new Uint8Array(1);return function(){return crypto.getRandomValues(l),l[0]}}else return function(){fe("randomDevice")}}function hr(l,h){hr.randomDevice||(hr.randomDevice=Fd());for(var y=0;y<h;y++)lr[l+y>>0]=hr.randomDevice();return 0}var Cd={a:dd,e:hd,d:md,b:pd,n:bd,h:wd,l:xd,m:_d,p:Ed,f:Td,g:Sd,j:Id,i:Rd,k:kd,c:Pd,o:hr};fd(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.r).apply(null,arguments)},t._getModelBufferMemoryOffset=function(){return(t._getModelBufferMemoryOffset=t.asm.s).apply(null,arguments)},t._getInputMemoryOffset=function(){return(t._getInputMemoryOffset=t.asm.t).apply(null,arguments)},t._getInputHeight=function(){return(t._getInputHeight=t.asm.u).apply(null,arguments)},t._getInputWidth=function(){return(t._getInputWidth=t.asm.v).apply(null,arguments)},t._getInputChannelCount=function(){return(t._getInputChannelCount=t.asm.w).apply(null,arguments)},t._getOutputMemoryOffset=function(){return(t._getOutputMemoryOffset=t.asm.x).apply(null,arguments)},t._getOutputHeight=function(){return(t._getOutputHeight=t.asm.y).apply(null,arguments)},t._getOutputWidth=function(){return(t._getOutputWidth=t.asm.z).apply(null,arguments)},t._getOutputChannelCount=function(){return(t._getOutputChannelCount=t.asm.A).apply(null,arguments)},t._loadModel=function(){return(t._loadModel=t.asm.B).apply(null,arguments)},t._runInference=function(){return(t._runInference=t.asm.C).apply(null,arguments)},t._isGPUEnabled=function(){return(t._isGPUEnabled=t.asm.D).apply(null,arguments)};var Ro=t.___errno_location=function(){return(Ro=t.___errno_location=t.asm.F).apply(null,arguments)},mr;function Od(l){this.name="ExitStatus",this.message="Program terminated with exit("+l+")",this.status=l}ct=function l(){mr||yn(),mr||(ct=l)};function yn(l){if(Ae>0||(td(),Ae>0))return;function h(){mr||(mr=!0,t.calledRun=!0,!v&&(rd(),n(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),nd()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),h()},1)):h()}t.run=yn;function Md(l,h){Bd(l)}function Bd(l){c(l,new Od(l))}if(t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();return yn(),e.ready})})();class Gf{constructor(){this.isSIMDSupported=!1,this.isThreadsSupported=!1,this.inputWidth=0,this.inputHeight=0,this.inputChannelCount=0,this.inputMemoryOffset=0,this.outputWidth=0,this.outputHeight=0,this.outputChannelCount=0,this.outputMemoryOffset=0}}const Vf="https://d3opqjmqzxf057.cloudfront.net/vonage-tensorflow-wasm/tflite-simd-wasm/1.1.3/",Hf="https://d3opqjmqzxf057.cloudfront.net/ml/selfie_segmentation/4.0.0/selfie_segmentation_landscape.tflite";async function jf(r=Vf,e=Hf){let t=new Gf;var n=new Promise(function(i,o){async function s(){return Wf({locateFile:function(u){return r+u}})}async function a(c){return new Promise(async(u,f)=>{const m=c;if(typeof m>"u")return f("TFLite backend unavailable: wasmSimd");let p=e;console.log("TFLite modelUrl: "+p);try{const d=await(await fetch(p)).arrayBuffer();console.log("Model buffer size:",d.byteLength);const g=m._getModelBufferMemoryOffset();console.log("Model buffer memory offset:",g),console.log("Loading model buffer..."),m.HEAPU8.set(new Uint8Array(d),g);const x=m._loadModel(d.byteLength);if(console.log("Load model result:",x),x!==0){f("Cannot load model");return}t.inputWidth=m._getInputWidth(),t.inputHeight=m._getInputHeight(),t.inputChannelCount=m._getInputChannelCount(),t.inputMemoryOffset=m._getInputMemoryOffset(),console.log("Input memory offset:",t.inputMemoryOffset),console.log("Input height:",t.inputHeight),console.log("Input width:",t.inputWidth),console.log("Input channels:",t.inputChannelCount),t.outputMemoryOffset=m._getOutputMemoryOffset(),t.outputWidth=m._getOutputWidth(),t.outputHeight=m._getOutputHeight(),t.outputChannelCount=m._getOutputChannelCount(),console.log("Output memory offset:",t.outputMemoryOffset),console.log("Output height:",t.outputHeight),console.log("Output width:",t.outputWidth),console.log("Output channels:",t.outputChannelCount),t.selectedTFLite=m}catch(b){f(b);return}u()})}s().then(c=>{if(c===null)throw console.error("loadTFLite null"),"loadTFLite null";a(c).then(u=>{i(t)}).catch(u=>{console.error("loadTFLiteModel error"),o("loadTFLiteModel error")})}).catch(c=>{console.error("loadTFLite error:",c),o("loadTFLite error:"+c)})});return n}const Yf=.1,Qf=.7,qf="https://d3opqjmqzxf057.cloudfront.net/ml/vonage_selfie_segmenter/float16/v1/vonage_selfie_segmenter.tflite";class Xf{constructor(){this.canvas=new OffscreenCanvas(0,0),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.width=0,this.height=0,this.gpuDelegate=!0}async createImageSegmenter(){if(!this.ImageSegmenter||!this.wasmFileset){console.warn("Mediapipe objects not loaded");return}this.imageSegmenter=await this.ImageSegmenter.createFromOptions(this.wasmFileset,{baseOptions:{modelAssetPath:this.modelAssetUriPath,delegate:this.gpuDelegate?"GPU":"CPU"},runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!0})}async loadMediapipeAssets(e,t){this.modelAssetUriPath=e||qf;const n=t?`${t}/task-vision.js`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/+esm",i=t?`${t}/wasm`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/wasm",{FilesetResolver:o,ImageSegmenter:s}=await import(n);this.ImageSegmenter=s,this.wasmFileset=await o.forVisionTasks(i)}async init(e,t,n){n===!1&&(this.gpuDelegate=!1),await this.loadMediapipeAssets(e,t),globalThis.document={},await this.createImageSegmenter()}async process(e){if(!this.imageSegmenter){console.warn("ImageSegmenter instance not available");return}(this.width!==e.width||this.height!==e.height)&&(this.canvas.width=this.width=e.width,this.canvas.height=this.height=e.height,this.mask&&(this.mask=new ImageData(this.width,this.height))),this.mask||(this.mask=new ImageData(this.width,this.height)),this.context.drawImage(e,0,0,e.width,e.height);const t=Date.now();let n;try{this.imageSegmenter?.segmentForVideo(this.context.getImageData(0,0,e.width,e.height),t,s=>{n=s.confidenceMasks?.[0]?.getAsFloat32Array()})}catch{await this.createImageSegmenter();return}if(!n)return;if(!this.previousConfidenceMask){this.previousConfidenceMask=n.slice();return}const i=n.map((s,a)=>{const c=this.previousConfidenceMask?.[a];return c!==void 0?this.blend(c,s):s}),o=[255,0,0];for(let s=0;s<i?.length;s++){const a=1-i[s];a>Yf?(a<Qf?(this.mask.data[s*4]=o[0]*a,this.mask.data[s*4+3]=255*a):(this.mask.data[s*4]=o[0],this.mask.data[s*4+3]=255),this.mask.data[s*4+1]=o[1],this.mask.data[s*4+2]=o[2]):this.mask.data[s*4]=this.mask.data[s*4+1]=this.mask.data[s*4+2]=this.mask.data[s*4+3]=0}return this.previousConfidenceMask=i.slice(),this.mask}isGpuSupported(){return!0}blend(e,t){const i=-.748699,o=-57.8051,s=291.309,a=-624.717,c=t-.5,u=c*c,f=1-Math.min(1,u*(5.68842+u*(i+u*(o+u*(s+u*a)))));return t+(e-t)*(f*.9)}}class Kf{constructor(){this.canvas=new OffscreenCanvas(0,0),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.pixelCount=0,this.inputOffset=0,this.outputOffset=0}async init(e,t,n){await this.initWasm(t,e),this.infos&&(this.canvas.width=this.infos.inputWidth,this.canvas.height=this.infos.inputHeight,this.pixelCount=this.infos.inputWidth*this.infos.inputHeight,this.mask=new ImageData(this.infos.inputWidth,this.infos.inputHeight),this.inputOffset=this.infos.inputMemoryOffset/4,this.outputOffset=this.infos.outputMemoryOffset/4)}async initWasm(e,t){this.infos=await jf(e,t)}async process(e){if(!this.mask||!this.infos)return;const t=this.infos.inputWidth,n=this.infos.inputHeight;this.context.drawImage(e,0,0,e.width,e.height,0,0,t,n);const i=this.context.getImageData(0,0,t,n),o=this.infos.selectedTFLite.HEAPF32;for(let s=0;s<this.pixelCount;s++){const a=this.inputOffset+s*3;o[a]=i.data[s*4]/255,o[a+1]=i.data[s*4+1]/255,o[a+2]=i.data[s*4+2]/255}this.infos.selectedTFLite._runInference();for(let s=0;s<this.pixelCount;s++){const a=this.infos.selectedTFLite.HEAPF32[this.outputOffset+s];this.mask.data[s*4]=this.mask.data[s*4+3]=255*a}return this.mask}isGpuSupported(){return this.infos?.selectedTFLite?._isGPUEnabled()??!1}}class wo{constructor(){this.reporter=new oa,this.isEnabled=!0}async init(e,t){t.segmentationOptions?.lightWeightEngine===!0?this.selfieSegmentation=new Kf:this.selfieSegmentation=new Xf,this.selfieSegmentation?.init(t.modelAssetUriPath,t.mediapipeBaseAssetsUri,t.segmentationOptions?.gpuSupport),this.backgroundFilter=new $f,this.report({variation:"Create"})}async transform(e,t){if(!this.isEnabled)return t.enqueue(e);let n;const i=e.timestamp??0,o=await createImageBitmap(e),s=await this.selfieSegmentation?.process(o);s&&(n=await this.backgroundFilter?.process(o,s)),n?(e.close(),t.enqueue(new VideoFrame(n,{timestamp:i,alpha:"discard"}))):t.enqueue(e)}async setBackgroundOptions(e){this.backgroundOptions=e,this.backgroundFilter?.setBackgroundOptions(e),this.report({variation:"Update"})}setVideoBGReadable(e){this.backgroundFilter?.setVideoBGReadable(e)}async setVirtualBGImage(e){await this.backgroundFilter?.setVirtualBGImage(e)}async profile(e){return this.backgroundFilter?.profile(e)??[]}getTransformerType(){return this.backgroundOptions?.transformerType??"Undefined"}enable(){this.isEnabled=!0}disable(){this.isEnabled=!1}report(e){this.reporter.send({version:sa,action:"MlTransformers",transformerType:this.backgroundOptions?.transformerType,config:JSON.stringify(this.backgroundOptions),...e})}}const dn=class dn{constructor(){this.backgroundTransformer=new wo,this.mediaProcessor=new Fn,this.rate=30,this.eventsQueue=[],this.frameTransformLatencyMs=[]}async init(e,t){this.frameTransformLatencyMs=[],await this.backgroundTransformer.init(e,t),await this.mediaProcessor.setTransformers([this.backgroundTransformer]),this.mediaProcessor.setTrackExpectedRate(this.rate),this.mediaProcessor.onAny((n,i)=>{this.resolveOnMediaProcessor?(this.resolveOnMediaProcessor({name:n,data:i}),this.resolveOnMediaProcessor=void 0):this.eventsQueue.push({name:n,data:i})})}enable(){this.backgroundTransformer.enable()}disable(){this.backgroundTransformer.disable()}async onMediaProcessorEvent(){return await new Promise(e=>{this.eventsQueue.length>0?e(this.eventsQueue.shift()):this.resolveOnMediaProcessor=e})}async setTrackExpectedRate(e){this.rate=e,this.mediaProcessor.setTrackExpectedRate(e)}async transform(e,t){let n=this.mediaProcessor.transform(e,t),i=performance.now();return this.frameTransformLatencyMs.push(performance.now()-i),n}async setBackgroundOptions(e){await this.backgroundTransformer?.setBackgroundOptions(e)}setVideoBGReadable(e){this.backgroundTransformer.setVideoBGReadable(e)}async setVirtualBGImage(e){await this.backgroundTransformer.setVirtualBGImage(e)}async terminate(){await this.mediaProcessor.destroy();const t=this.frameTransformLatencyMs.reduce((n,i)=>n+i,0)/this.frameTransformLatencyMs.length||0;console.log(`Transform latency average is: ${t} ms`)}setVonageMetadata(e){ns(e)}async profile(e){return JSON.stringify(await this.backgroundTransformer.profile(e))}};Fs("ProcessorWorker",dn);let ln=dn;const xo='(function(){"use strict";function Vt(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const Vr=Vt("globals",{});var xe=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r.EVENT="EVENT",r))(xe||{});function zi(r){return[ImageBitmap,ReadableStream,WritableStream].some(t=>r instanceof t)}function Be(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(s=>zi(s)))}Vt("workerized",{});function Hr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function qe(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],qe(r[t],e[t])):typeof r[t]=="object"?(e[t]={},qe(r[t],e[t])):e[t]=r[t]}const K=new WeakMap,ce=new WeakMap,j=new WeakMap,Ke=Symbol("anyProducer"),jr=Promise.resolve(),Je=Symbol("listenerAdded"),Ze=Symbol("listenerRemoved");let et=!1,Ht=!1;function _e(r){if(typeof r!="string"&&typeof r!="symbol"&&typeof r!="number")throw new TypeError("`eventName` must be a string, symbol, or number")}function tt(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Ee(r,e){const t=ce.get(r);if(t.has(e))return t.get(e)}function De(r,e){const t=typeof e=="string"||typeof e=="symbol"||typeof e=="number"?e:Ke,n=j.get(r);if(n.has(t))return n.get(t)}function Gi(r,e,t){const n=j.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(Ke)){const i=Promise.all([e,t]);for(const s of n.get(Ke))s.enqueue(i)}}function Xr(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const s={enqueue(o){i.push(o),n()},finish(){t=!0,n()}};for(const o of e){let a=De(r,o);a||(a=new Set,j.get(r).set(o,a)),a.add(s)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(o=>{n=o}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(o){i=void 0;for(const a of e){const c=De(r,a);c&&(c.delete(s),c.size===0&&j.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await o}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Yr(r){if(r===void 0)return Qr;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!Qr.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const we=r=>r===Je||r===Ze;function rt(r,e,t){if(we(e))try{et=!0,r.emit(e,t)}finally{et=!1}}class ve{static mixin(e,t){return t=Yr(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const o of t)if(n.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 ve}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const s=o=>function(...a){return this[e][o](...a)};for(const o of t)Object.defineProperty(n.prototype,o,{enumerable:!1,value:s(o)});return n}}static get isDebugEnabled(){var e,t;if(typeof((e=globalThis.process)==null?void 0:e.env)!="object")return Ht;const{env:n}=(t=globalThis.process)!=null?t:{env:{}};return n.DEBUG==="emittery"||n.DEBUG==="*"||Ht}static set isDebugEnabled(e){Ht=e}constructor(e={}){var t;K.set(this,new Set),ce.set(this,new Map),j.set(this,new Map),j.get(this).set(Ke,new Set),this.debug=(t=e.debug)!=null?t:{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(n,i,s,o)=>{try{o=JSON.stringify(o)}catch{o=`Object with the following keys failed to stringify: ${Object.keys(o).join(",")}`}(typeof s=="symbol"||typeof s=="number")&&(s=s.toString());const a=new Date,c=`${a.getHours()}:${a.getMinutes()}:${a.getSeconds()}.${a.getMilliseconds()}`;console.log(`[${c}][emittery:${n}][${i}] Event Name: ${s}\n data: ${o}`)})}logIfDebugEnabled(e,t,n){(ve.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t){tt(t),e=Array.isArray(e)?e:[e];for(const n of e){_e(n);let i=Ee(this,n);i||(i=new Set,ce.get(this).set(n,i)),i.add(t),this.logIfDebugEnabled("subscribe",n,void 0),we(n)||rt(this,Je,{eventName:n,listener:t})}return this.off.bind(this,e,t)}off(e,t){tt(t),e=Array.isArray(e)?e:[e];for(const n of e){_e(n);const i=Ee(this,n);i&&(i.delete(t),i.size===0&&ce.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),we(n)||rt(this,Ze,{eventName:n,listener:t})}}once(e){let t;const n=new Promise(i=>{t=this.on(e,s=>{t(),i(s)})});return n.off=t,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)_e(t);return Xr(this,e)}async emit(e,t){var n;if(_e(e),we(e)&&!et)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),Gi(this,e,t);const i=(n=Ee(this,e))!=null?n:new Set,s=K.get(this),o=[...i],a=we(e)?[]:[...s];await jr,await Promise.all([...o.map(async c=>{if(i.has(c))return c(t)}),...a.map(async c=>{if(s.has(c))return c(e,t)})])}async emitSerial(e,t){var n;if(_e(e),we(e)&&!et)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const i=(n=Ee(this,e))!=null?n:new Set,s=K.get(this),o=[...i],a=[...s];await jr;for(const c of o)i.has(c)&&await c(t);for(const c of a)s.has(c)&&await c(e,t)}onAny(e){return tt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),K.get(this).add(e),rt(this,Je,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return Xr(this)}offAny(e){tt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),rt(this,Ze,{listener:e}),K.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),typeof t=="string"||typeof t=="symbol"||typeof t=="number"){const n=Ee(this,t);n&&n.clear();const i=De(this,t);if(i){for(const s of i)s.finish();i.clear()}}else{K.get(this).clear();for(const[n,i]of ce.get(this).entries())i.clear(),ce.get(this).delete(n);for(const[n,i]of j.get(this).entries()){for(const s of i)s.finish();i.clear(),j.get(this).delete(n)}}}listenerCount(e){var t,n,i,s,o,a;e=Array.isArray(e)?e:[e];let c=0;for(const u of e){if(typeof u=="string"){c+=K.get(this).size+((n=(t=Ee(this,u))==null?void 0:t.size)!=null?n:0)+((s=(i=De(this,u))==null?void 0:i.size)!=null?s:0)+((a=(o=De(this))==null?void 0:o.size)!=null?a:0);continue}typeof u<"u"&&_e(u),c+=K.get(this).size;for(const d of ce.get(this).values())c+=d.size;for(const d of j.get(this).values())c+=d.size}return c}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=Yr(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \\`${n}\\` already exists on \\`target\\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const Qr=Object.getOwnPropertyNames(ve.prototype).filter(r=>r!=="constructor");Object.defineProperty(ve,"listenerAdded",{value:Je,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(ve,"listenerRemoved",{value:Ze,writable:!1,enumerable:!0,configurable:!1});function $i(r){return r.onAny&&r.emit}async function Wi(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Be(r,await e.instance[t](...n??[]))}const qr=Vt("registeredWorkers",{});function Vi(r,e){e.workerId=r,Hr()&&(qr[e.workerId]=e)}function Hi(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=qr[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;qe(n,Vr),$i(e.instance)&&e.instance.onAny((s,o)=>{Be({type:xe.EVENT},{name:s,data:o})}),Be(r,typeof e.instance!==void 0)}async function ji(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Be(r,n)}function Xi(r){if(!r.args)throw"Missing globals while syncing";qe(r.args[0],Vr),Be(r,{})}function Yi(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case xe.INIT:Hi(t,r);break;case xe.FORWARD:Wi(t,r);break;case xe.TERMINATE:ji(t,r);break;case xe.GLOBALS_SYNC:Xi(t);break}}}Hr()&&Yi();const J=new WeakMap,ue=new WeakMap,X=new WeakMap,nt=Symbol("anyProducer"),Kr=Promise.resolve(),it=Symbol("listenerAdded"),st=Symbol("listenerRemoved");let ot=!1,jt=!1;const at=r=>typeof r=="string"||typeof r=="symbol"||typeof r=="number";function Te(r){if(!at(r))throw new TypeError("`eventName` must be a string, symbol, or number")}function ct(r){if(typeof r!="function")throw new TypeError("listener must be a function")}function Ae(r,e){const t=ue.get(r);if(t.has(e))return t.get(e)}function Me(r,e){const t=at(e)?e:nt,n=X.get(r);if(n.has(t))return n.get(t)}function Qi(r,e,t){const n=X.get(r);if(n.has(e))for(const i of n.get(e))i.enqueue(t);if(n.has(nt)){const i=Promise.all([e,t]);for(const s of n.get(nt))s.enqueue(i)}}function Jr(r,e){e=Array.isArray(e)?e:[e];let t=!1,n=()=>{},i=[];const s={enqueue(o){i.push(o),n()},finish(){t=!0,n()}};for(const o of e){let a=Me(r,o);a||(a=new Set,X.get(r).set(o,a)),a.add(s)}return{async next(){return i?i.length===0?t?(i=void 0,this.next()):(await new Promise(o=>{n=o}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(o){i=void 0;for(const a of e){const c=Me(r,a);c&&(c.delete(s),c.size===0&&X.get(r).delete(a))}return n(),arguments.length>0?{done:!0,value:await o}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Zr(r){if(r===void 0)return en;if(!Array.isArray(r))throw new TypeError("`methodNames` must be an array of strings");for(const e of r)if(!en.includes(e))throw typeof e!="string"?new TypeError("`methodNames` element must be a string"):new Error(`${e} is not Emittery method`);return r}const Ie=r=>r===it||r===st;function ut(r,e,t){if(Ie(e))try{ot=!0,r.emit(e,t)}finally{ot=!1}}class Y{static mixin(e,t){return t=Zr(t),n=>{if(typeof n!="function")throw new TypeError("`target` must be function");for(const o of t)if(n.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 Y}),this[e]}Object.defineProperty(n.prototype,e,{enumerable:!1,get:i});const s=o=>function(...a){return this[e][o](...a)};for(const o of t)Object.defineProperty(n.prototype,o,{enumerable:!1,value:s(o)});return n}}static get isDebugEnabled(){if(typeof globalThis.process?.env!="object")return jt;const{env:e}=globalThis.process??{env:{}};return e.DEBUG==="emittery"||e.DEBUG==="*"||jt}static set isDebugEnabled(e){jt=e}constructor(e={}){J.set(this,new Set),ue.set(this,new Map),X.set(this,new Map),X.get(this).set(nt,new Set),this.debug=e.debug??{},this.debug.enabled===void 0&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(t,n,i,s)=>{try{s=JSON.stringify(s)}catch{s=`Object with the following keys failed to stringify: ${Object.keys(s).join(",")}`}(typeof i=="symbol"||typeof i=="number")&&(i=i.toString());const o=new Date,a=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${a}][emittery:${t}][${n}] Event Name: ${i}\n data: ${s}`)})}logIfDebugEnabled(e,t,n){(Y.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t,{signal:n}={}){ct(t),e=Array.isArray(e)?e:[e];for(const s of e){Te(s);let o=Ae(this,s);o||(o=new Set,ue.get(this).set(s,o)),o.add(t),this.logIfDebugEnabled("subscribe",s,void 0),Ie(s)||ut(this,it,{eventName:s,listener:t})}const i=()=>{this.off(e,t),n?.removeEventListener("abort",i)};return n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i(),i}off(e,t){ct(t),e=Array.isArray(e)?e:[e];for(const n of e){Te(n);const i=Ae(this,n);i&&(i.delete(t),i.size===0&&ue.get(this).delete(n)),this.logIfDebugEnabled("unsubscribe",n,void 0),Ie(n)||ut(this,st,{eventName:n,listener:t})}}once(e,t){if(t!==void 0&&typeof t!="function")throw new TypeError("predicate must be a function");let n;const i=new Promise(s=>{n=this.on(e,o=>{t&&!t(o)||(n(),s(o))})});return i.off=n,i}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Te(t);return Jr(this,e)}async emit(e,t){if(Te(e),Ie(e)&&!ot)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),Qi(this,e,t);const n=Ae(this,e)??new Set,i=J.get(this),s=[...n],o=Ie(e)?[]:[...i];await Kr,await Promise.all([...s.map(async a=>{if(n.has(a))return a(t)}),...o.map(async a=>{if(i.has(a))return a(e,t)})])}async emitSerial(e,t){if(Te(e),Ie(e)&&!ot)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const n=Ae(this,e)??new Set,i=J.get(this),s=[...n],o=[...i];await Kr;for(const a of s)n.has(a)&&await a(t);for(const a of o)i.has(a)&&await a(e,t)}onAny(e,{signal:t}={}){ct(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),J.get(this).add(e),ut(this,it,{listener:e});const n=()=>{this.offAny(e),t?.removeEventListener("abort",n)};return t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n(),n}anyEvent(){return Jr(this)}offAny(e){ct(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),ut(this,st,{listener:e}),J.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),at(t)){const n=Ae(this,t);n&&n.clear();const i=Me(this,t);if(i){for(const s of i)s.finish();i.clear()}}else{J.get(this).clear();for(const[n,i]of ue.get(this).entries())i.clear(),ue.get(this).delete(n);for(const[n,i]of X.get(this).entries()){for(const s of i)s.finish();i.clear(),X.get(this).delete(n)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const n of e){if(at(n)){t+=J.get(this).size+(Ae(this,n)?.size??0)+(Me(this,n)?.size??0)+(Me(this)?.size??0);continue}n!==void 0&&Te(n),t+=J.get(this).size;for(const i of ue.get(this).values())t+=i.size;for(const i of X.get(this).values())t+=i.size}return t}bindMethods(e,t){if(typeof e!="object"||e===null)throw new TypeError("`target` must be an object");t=Zr(t);for(const n of t){if(e[n]!==void 0)throw new Error(`The property \\`${n}\\` already exists on \\`target\\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const en=Object.getOwnPropertyNames(Y.prototype).filter(r=>r!=="constructor");Object.defineProperty(Y,"listenerAdded",{value:it,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Y,"listenerRemoved",{value:st,writable:!1,enumerable:!0,configurable:!1});var qi=Object.defineProperty,Ki=(r,e,t)=>e in r?qi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ji=(r,e,t)=>(Ki(r,e+"",t),t);const Zi="hlg.tokbox.com/prod/logging/vcp_webrtc",es="https://",ts=1e4;let ft;const rs=new Uint8Array(16);function ns(){if(!ft&&(ft=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ft))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ft(rs)}const F=[];for(let r=0;r<256;++r)F.push((r+256).toString(16).slice(1));function is(r,e=0){return(F[r[e+0]]+F[r[e+1]]+F[r[e+2]]+F[r[e+3]]+"-"+F[r[e+4]]+F[r[e+5]]+"-"+F[r[e+6]]+F[r[e+7]]+"-"+F[r[e+8]]+F[r[e+9]]+"-"+F[r[e+10]]+F[r[e+11]]+F[r[e+12]]+F[r[e+13]]+F[r[e+14]]+F[r[e+15]]).toLowerCase()}const ss=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),tn={randomUUID:ss};function os(r,e,t){if(tn.randomUUID&&!r)return tn.randomUUID();r=r||{};const n=r.random||(r.rng||ns)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,is(n)}function Xt(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const Z=Xt("globals",{});var fe=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r))(fe||{});function rn(r){return[ImageBitmap,ReadableStream,WritableStream].some(e=>r instanceof e)}let as=0;function cs(r,e,t,n,i){const s=as++;return r.postMessage({id:s,type:e,functionName:t,args:n},n.filter(o=>rn(o))),new Promise(o=>{i?.set(s,o)})}function Oe(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(s=>rn(s)))}const nn=Xt("workerized",{});function sn(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function us(){if(sn())Oe({type:fe.GLOBALS_SYNC},Z);else{const r=[];for(const e in nn){const{worker:t,resolvers:n}=nn[e].workerContext;t&&r.push(cs(t,fe.GLOBALS_SYNC,"",[Z],n))}await Promise.all(r)}}function lt(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],lt(r[t],e[t])):typeof r[t]=="object"?(e[t]={},lt(r[t],e[t])):e[t]=r[t]}async function fs(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Oe(r,await e.instance[t](...n??[]))}const ls=Xt("registeredWorkers",{});function ds(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=ls[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;lt(n,Z),Oe(r,typeof e.instance!==void 0)}async function hs(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Oe(r,n)}function ms(r){if(!r.args)throw"Missing globals while syncing";lt(r.args[0],Z),Oe(r,{})}function ps(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case fe.INIT:ds(t,r);break;case fe.FORWARD:fs(t,r);break;case fe.TERMINATE:hs(t,r);break;case fe.GLOBALS_SYNC:ms(t);break}}}sn()&&ps();function gs(r,e){return Z[r]||(Z[r]=e),[()=>Z[r],async t=>{Z[r]=t,await us()}]}function ys(r,e){return gs(r,e)}const[bs,xs]=ys("metadata");function _s(r){xs(r)}function Yt(){return bs()}let Qt=class{constructor(e,t){Ji(this,"uuid"),this.config=e,this.uuid=t??os()}async send(e){var t,n,i;const{appId:s,sourceType:o}=(t=Yt())!=null?t:{};if(!s||!o)return"metadata missing";const a=new AbortController,c=setTimeout(()=>a.abort(),ts);return await((i=(n=this.config)==null?void 0:n.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(c),"success"}getUrl(){var e;let t=(e=Yt().proxyUrl)!=null?e:es;return t+=(t.at(-1)==="/"?"":"/")+Zi,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=Yt();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}};const dt="3.0.1",qt=class{};qt.updates={transformer_new:"New transformer",transformer_null:"Null transformer"},qt.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"};let le=qt;function Es(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function ws(r){if(Es(r))return r;try{return new Error(JSON.stringify(r))}catch{return new Error(String(r))}}function Kt(r){return ws(r).message}class vs{constructor(e,t){this.config=e,this.frameTransformedCount=0,this.frameFromSourceCount=0,this.startAt=0,this.reporter=new Qt(e,t)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:t}=this,n=(Date.now()-e)/1e3;return t/n}async onFrameTransformed(e={},t=!1){this.startAt===0&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:n,frameTransformedCount:i,frameFromSourceCount:s}=this,o=Date.now(),a=(o-n)/1e3,c=i/a,u=s/a;return t||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:u,transformedFps:c,framesTransformed:i,...e})):"success"}}var Jt=(r=>(r.pipeline_ended="pipeline_ended",r.pipeline_ended_with_error="pipeline_ended_with_error",r.pipeline_started="pipeline_started",r.pipeline_started_with_error="pipeline_started_with_error",r.pipeline_restarted="pipeline_restarted",r.pipeline_restarted_with_error="pipeline_restarted_with_error",r))(Jt||{});const Ts=500,As=.8;class Is extends Y{constructor(e,t){super(),this.reporter_=new Qt,this.reporterQos_=new vs({loggingIntervalFrameCount:Ts,report:{version:dt}}),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_&&typeof this.transformer_.start=="function")try{await this.transformer_.start(e)}catch(t){this.report({message:le.errors.transformer_start,variation:"Error",error:Kt(t)});const n={eventMetaData:{transformerIndex:this.index_},error:t,function:"start"};this.emit("error",n)}}async transform(e,t){if(this.mediaTransformerQosReportStartTimestamp_===0&&(this.mediaTransformerQosReportStartTimestamp_=Date.now()),e instanceof VideoFrame&&(this.videoHeight_=e?.displayHeight??0,this.videoWidth_=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 this.transformer_.transform?.(e,t),this.reportQos()}catch(n){this.report({message:le.errors.transformer_transform,variation:"Error",error:Kt(n)});const i={eventMetaData:{transformerIndex:this.index_},error:n,function:"transform"};this.emit("error",i)}if(this.trackExpectedRate_!=-1&&this.trackExpectedRate_*As>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(t){this.report({message:le.errors.transformer_flush,variation:"Error",error:Kt(t)});const n={eventMetaData:{transformerIndex:this.index_},error:t,function:"flush"};this.emit("error",n)}}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:dt,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:dt,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class Ss extends Y{constructor(e){super(),this.transformers_=[],this.trackExpectedRate_=-1;for(let t=0;t<e.length;t++){let n=new Is(e[t],t);n.on("error",i=>{this.emit("error",i)}),n.on("warn",i=>{this.emit("warn",i)}),this.transformers_.push(n)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let t of this.transformers_)t.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,t){if(!this.transformers_||this.transformers_.length===0){console.log("[Pipeline] No transformers.");return}try{let n=e;for(let i of this.transformers_)e=e.pipeThrough(new TransformStream(i));e.pipeTo(t).then(async()=>{console.log("[Pipeline] Setup."),await t.abort(),await n.cancel(),this.emit("pipelineInfo","pipeline_ended")}).catch(async i=>{e.cancel().then(()=>{console.log("[Pipeline] Shutting down streams after abort.")}).catch(s=>{console.error("[Pipeline] Error from stream transform:",s)}),await t.abort(i),await n.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 Rs extends Y{constructor(){super(),this.reporter_=new Qt,this.trackExpectedRate_=-1,this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e,this.pipeline_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_)}async transform(e,t){if(this.isTrack(e)){if(e.kind==="video"){const n=new MediaStreamTrackProcessor({track:e}),i=new VideoTrackGenerator;return this.readable_=n.readable,this.writable_=i.writable,await this.transformInternal(),i.track}throw Error("Cannot process audio tracks inside a web worker when passing a track to transform")}else return this.readable_=e,this.writable_=t,this.transformInternal()}transformInternal(){return new Promise(async(e,t)=>{if(!this.transformers_||this.transformers_.length===0){this.report({message:le.errors.transformer_none,variation:"Error"}),t("[MediaProcessor] Need to set transformers.");return}if(!this.readable_){this.report({variation:"Error",message:le.errors.readable_null}),t("[MediaProcessor] Readable is null.");return}if(!this.writable_){this.report({variation:"Error",message:le.errors.writable_null}),t("[MediaProcessor] Writable is null.");return}let n=!1;this.pipeline_&&(n=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new Ss(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=>{n&&(i==="pipeline_started"?i=Jt.pipeline_restarted:i==="pipeline_started_with_error"&&(i=Jt.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=>{t(i)})})}setTransformers(e){return this.report({variation:"Update",message:le.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:dt,action:"MediaProcessor",...e})}isTrack(e){return"kind"in e}}var Fs=Object.defineProperty,Ps=(r,e,t)=>e in r?Fs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ks=(r,e,t)=>(Ps(r,e+"",t),t);const Cs="hlg.tokbox.com/prod/logging/vcp_webrtc",Bs="https://",Ds=1e4;let ht;const Ms=new Uint8Array(16);function Os(){if(!ht&&(ht=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ht))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ht(Ms)}const P=[];for(let r=0;r<256;++r)P.push((r+256).toString(16).slice(1));function Us(r,e=0){return(P[r[e+0]]+P[r[e+1]]+P[r[e+2]]+P[r[e+3]]+"-"+P[r[e+4]]+P[r[e+5]]+"-"+P[r[e+6]]+P[r[e+7]]+"-"+P[r[e+8]]+P[r[e+9]]+"-"+P[r[e+10]]+P[r[e+11]]+P[r[e+12]]+P[r[e+13]]+P[r[e+14]]+P[r[e+15]]).toLowerCase()}const Ns=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),on={randomUUID:Ns};function Ls(r,e,t){if(on.randomUUID&&!e&&!r)return on.randomUUID();r=r||{};const n=r.random||(r.rng||Os)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Us(n)}function Zt(r,e){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let t=globalThis.vonage.workerizer;return t[r]||(t[r]=e),t[r]}const ee=Zt("globals",{});var de=(r=>(r.INIT="INIT",r.FORWARD="FORWARD",r.TERMINATE="TERMINATE",r.GLOBALS_SYNC="GLOBALS_SYNC",r))(de||{});function an(r){return[ImageBitmap,ReadableStream,WritableStream].some(e=>r instanceof e)}let zs=0;function Gs(r,e,t,n,i){const s=zs++;return r.postMessage({id:s,type:e,functionName:t,args:n},n.filter(o=>an(o))),new Promise(o=>{i?.set(s,o)})}function Ue(r,e){const{id:t,type:n}=r,i=Array.isArray(e)?e:[e];postMessage({id:t,type:n,result:e},i.filter(s=>an(s)))}const cn=Zt("workerized",{});function un(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function $s(){if(un())Ue({type:de.GLOBALS_SYNC},ee);else{const r=[];for(const e in cn){const{worker:t,resolvers:n}=cn[e].workerContext;t&&r.push(Gs(t,de.GLOBALS_SYNC,"",[ee],n))}await Promise.all(r)}}function mt(r,e){if(Array.isArray(e))e.splice(0,e.length);else if(typeof e=="object")for(const t in e)delete e[t];for(const t in r)Array.isArray(r[t])?(e[t]=[],mt(r[t],e[t])):typeof r[t]=="object"?(e[t]={},mt(r[t],e[t])):e[t]=r[t]}async function Ws(r,e){const{functionName:t,args:n}=r;if(!e.instance)throw"instance not initialized";if(!t)throw"missing function name to call";if(!e.instance[t])throw`undefined function [${t}] in class ${e.instance.constructor.workerId}`;Ue(r,await e.instance[t](...n??[]))}const Vs=Zt("registeredWorkers",{});function Hs(r,e){if(!r.args)throw"Missing className while initializing worker";const[t,n]=r.args,i=Vs[t];if(i)e.instance=new i(r.args.slice(1));else throw`unknown worker class ${t}`;mt(n,ee),Ue(r,typeof e.instance!==void 0)}async function js(r,e){const{args:t}=r;if(!e.instance)throw"instance not initialized";let n;e.instance.terminate&&(n=await e.instance.terminate(...t??[])),Ue(r,n)}function Xs(r){if(!r.args)throw"Missing globals while syncing";mt(r.args[0],ee),Ue(r,{})}function Ys(){const r={};onmessage=async e=>{const t=e.data;switch(t.type){case de.INIT:Hs(t,r);break;case de.FORWARD:Ws(t,r);break;case de.TERMINATE:js(t,r);break;case de.GLOBALS_SYNC:Xs(t);break}}}un()&&Ys();function Qs(r,e){return ee[r]||(ee[r]=e),[()=>ee[r],async t=>{ee[r]=t,await $s()}]}function qs(r,e){return Qs(r,e)}const[Ks]=qs("metadata");function er(){return Ks()}class Js{constructor(e){ks(this,"uuid",Ls()),this.config=e}async send(e){var t,n,i;const{appId:s,sourceType:o}=(t=er())!=null?t:{};if(!s||!o)return"metadata missing";const a=new AbortController,c=setTimeout(()=>a.abort(),Ds);return await((i=(n=this.config)==null?void 0:n.fetch)!=null?i:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:a.signal}),clearTimeout(c),"success"}getUrl(){var e;let t=(e=er().proxyUrl)!=null?e:Bs;return t+=(t.at(-1)==="/"?"":"/")+Cs,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=er();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}}const Zs="7.0.0";var pt=(r=>(r.Low="Low",r.High="High",r))(pt||{}),tr=(r=>(r.FAST="FAST",r.PRECISE="PRECISE",r))(tr||{}),gt=(r=>(r.CANVAS="CANVAS",r.WEBGL="WEBGL",r))(gt||{});function eo(){const e=new OffscreenCanvas(0,0).getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(e){const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}else return{supported:!1,message:"Your hardware does not perform good enough to run the library efficiently"};return{supported:!0}}class rr{constructor(){const e=new OffscreenCanvas(0,0),t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw"Fail to retrieve 2d context";this.canvas=e,this.context=t}enablePostProcessing(){}disablePostProcessing(){}async profileWebgl(e){return[]}async render(e,t){return this.canvas}resizeCanvas(e){const{width:t,height:n}=e;this.canvas.width=t,this.canvas.height=n}renderSilhouette(e,t,n="none"){const{width:i,height:s}=e;this.context.save(),this.context.drawImage(t,0,0,t.width,t.height,0,0,i,s),this.context.filter="blur(5px)",this.context.globalCompositeOperation="source-in",this.context.drawImage(t,0,0,t.width,t.height,0,0,i,s),this.context.globalCompositeOperation="source-in",this.context.filter=n,this.context.drawImage(e,0,0,i,s,0,0,this.canvas.width,this.canvas.height),this.context.restore()}destroy(){}}class to extends rr{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n),this.context.save(),this.context.filter=`blur(${this.radius}px)`,this.context.globalCompositeOperation="destination-over",this.context.drawImage(e,0,0,e.width,e.height),this.context.restore(),super.render(e,t)}}class ro extends rr{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n,`blur(${this.radius}px)`),this.context.save(),this.context.filter="none",this.context.globalCompositeOperation="destination-over",this.context.drawImage(e,0,0,e.width,e.height),this.context.restore(),super.render(e,t)}}class no extends rr{setBackgroundImage(e){this.backgroundImage=e}async render(e,t){super.resizeCanvas(e);const n=await createImageBitmap(t);return this.renderSilhouette(e,n),this.backgroundImage&&(this.context.save(),this.context.filter="none",this.context.globalCompositeOperation="destination-over",this.context.drawImage(this.backgroundImage,0,0,this.backgroundImage.width,this.backgroundImage.height,0,0,e.width,e.height),this.context.restore()),super.render(e,t)}}const nr=5120,Ne=5121,ir=5122,sr=5123,or=5124,ar=5125,cr=5126,io=32819,so=32820,oo=33635,ao=5131,co=33640,uo=35899,fo=35902,lo=36269,ho=34042,fn={};{const r=fn;r[nr]=Int8Array,r[Ne]=Uint8Array,r[ir]=Int16Array,r[sr]=Uint16Array,r[or]=Int32Array,r[ar]=Uint32Array,r[cr]=Float32Array,r[io]=Uint16Array,r[so]=Uint16Array,r[oo]=Uint16Array,r[ao]=Uint16Array,r[co]=Uint32Array,r[uo]=Uint32Array,r[fo]=Uint32Array,r[lo]=Uint32Array,r[ho]=Uint32Array}function ur(r){if(r instanceof Int8Array)return nr;if(r instanceof Uint8Array||r instanceof Uint8ClampedArray)return Ne;if(r instanceof Int16Array)return ir;if(r instanceof Uint16Array)return sr;if(r instanceof Int32Array)return or;if(r instanceof Uint32Array)return ar;if(r instanceof Float32Array)return cr;throw new Error("unsupported typed array type")}function ln(r){if(r===Int8Array)return nr;if(r===Uint8Array||r===Uint8ClampedArray)return Ne;if(r===Int16Array)return ir;if(r===Uint16Array)return sr;if(r===Int32Array)return or;if(r===Uint32Array)return ar;if(r===Float32Array)return cr;throw new Error("unsupported typed array type")}function dn(r){const e=fn[r];if(!e)throw new Error("unknown gl type");return e}const yt=typeof SharedArrayBuffer<"u"?function(e){return e&&e.buffer&&(e.buffer instanceof ArrayBuffer||e.buffer instanceof SharedArrayBuffer)}:function(e){return e&&e.buffer&&e.buffer instanceof ArrayBuffer};function hn(...r){console.error(...r)}const mn=new Map;function bt(r,e){if(!r||typeof r!="object")return!1;let t=mn.get(e);t||(t=new WeakMap,mn.set(e,t));let n=t.get(r);if(n===void 0){const i=Object.prototype.toString.call(r);n=i.substring(8,i.length-1)===e,t.set(r,n)}return n}function mo(r,e){return typeof WebGLBuffer<"u"&&bt(e,"WebGLBuffer")}function po(r,e){return typeof WebGLRenderbuffer<"u"&&bt(e,"WebGLRenderbuffer")}function fr(r,e){return typeof WebGLTexture<"u"&&bt(e,"WebGLTexture")}function go(r,e){return typeof WebGLSampler<"u"&&bt(e,"WebGLSampler")}const pn=35044,he=34962,yo=34963,bo=34660,xo=5120,_o=5121,Eo=5122,wo=5123,vo=5124,To=5125,gn=5126,yn={attribPrefix:""};function Ao(r,e,t,n,i){r.bindBuffer(e,t),r.bufferData(e,n,i||pn)}function bn(r,e,t,n){if(mo(r,e))return e;t=t||he;const i=r.createBuffer();return Ao(r,t,i,e,n),i}function xn(r){return r==="indices"}function Io(r){return r===Int8Array||r===Uint8Array}function So(r){return r.length?r:r.data}const Ro=/coord|texture/i,Fo=/color|colour/i;function Po(r,e){let t;if(Ro.test(r)?t=2:Fo.test(r)?t=4:t=3,e%t>0)throw new Error(`Can not guess numComponents for attribute \'${r}\'. Tried ${t} but ${e} values is not evenly divisible by ${t}. You should specify it.`);return t}function ko(r,e,t){return r.numComponents||r.size||Po(e,t||So(r).length)}function _n(r,e){if(yt(r))return r;if(yt(r.data))return r.data;Array.isArray(r)&&(r={data:r});let t=r.type?lr(r.type):void 0;return t||(xn(e)?t=Uint16Array:t=Float32Array),new t(r.data)}function Co(r){return typeof r=="number"?r:r?ln(r):gn}function lr(r){return typeof r=="number"?dn(r):r||Float32Array}function Bo(r,e){return{buffer:e.buffer,numValues:24,type:Co(e.type),arrayType:lr(e.type)}}function Do(r,e){const t=e.data||e,n=lr(e.type),i=t*n.BYTES_PER_ELEMENT,s=r.createBuffer();return r.bindBuffer(he,s),r.bufferData(he,i,e.drawType||pn),{buffer:s,numValues:t,type:ln(n),arrayType:n}}function Mo(r,e,t){const n=_n(e,t);return{arrayType:n.constructor,buffer:bn(r,n,void 0,e.drawType),type:ur(n),numValues:0}}function Oo(r,e){const t={};return Object.keys(e).forEach(function(n){if(!xn(n)){const i=e[n],s=i.attrib||i.name||i.attribName||yn.attribPrefix+n;if(i.value){if(!Array.isArray(i.value)&&!yt(i.value))throw new Error("array.value is not array or typedarray");t[s]={value:i.value}}else{let o;i.buffer&&i.buffer instanceof WebGLBuffer?o=Bo:typeof i=="number"||typeof i.data=="number"?o=Do:o=Mo;const{buffer:a,type:c,numValues:u,arrayType:d}=o(r,i,n),m=i.normalize!==void 0?i.normalize:Io(d),p=ko(i,n,u);t[s]={buffer:a,numComponents:p,type:c,normalize:m,stride:i.stride||0,offset:i.offset||0,divisor:i.divisor===void 0?void 0:i.divisor,drawType:i.drawType}}}}),r.bindBuffer(he,null),t}function Uo(r,e){return e===xo||e===_o?1:e===Eo||e===wo?2:e===vo||e===To||e===gn?4:0}const dr=["position","positions","a_position"];function No(r,e){let t,n;for(n=0;n<dr.length&&(t=dr[n],!(t in e||(t=yn.attribPrefix+t,t in e)));++n);n===dr.length&&(t=Object.keys(e)[0]);const i=e[t];if(!i.buffer)return 1;r.bindBuffer(he,i.buffer);const s=r.getBufferParameter(he,bo);r.bindBuffer(he,null);const o=Uo(r,i.type),a=s/o,c=i.numComponents||i.size,u=a/c;if(u%1!==0)throw new Error(`numComponents ${c} not correct for length ${length}`);return u}function Lo(r,e,t){const n=Oo(r,e),i=Object.assign({},t||{});i.attribs=Object.assign({},t?t.attribs:{},n);const s=e.indices;if(s){const o=_n(s,"indices");i.indices=bn(r,o,yo),i.numElements=o.length,i.elementType=ur(o)}else i.numElements||(i.numElements=No(r,i.attribs));return i}function Le(r){return!!r.texStorage2D}const En=(function(){const r={},e={};function t(n){const i=n.constructor.name;if(!r[i]){for(const s in n)if(typeof n[s]=="number"){const o=e[n[s]];e[n[s]]=o?`${o} | ${s}`:s}r[i]=!0}}return function(i,s){return t(i),e[s]||(typeof s=="number"?`0x${s.toString(16)}`:s)}})(),te={textureColor:new Uint8Array([128,192,255,255]),textureOptions:{},crossOrigin:void 0},ze=yt,wn=(function(){let r;return function(){return r=r||(typeof document<"u"&&document.createElement?document.createElement("canvas").getContext("2d"):null),r}})(),vn=6406,V=6407,A=6408,Tn=6409,An=6410,Ge=6402,In=34041,xt=33071,zo=9728,Go=9729,re=3553,ne=34067,me=32879,pe=35866,hr=34069,$o=34070,Wo=34071,Vo=34072,Ho=34073,jo=34074,mr=10241,pr=10240,_t=10242,Et=10243,Sn=32882,Xo=33082,Yo=33083,Qo=33084,qo=33085,Ko=34892,Jo=34893,gr=3317,Rn=3314,Fn=32878,Pn=3316,kn=3315,Cn=32877,Zo=37443,ea=37441,ta=37440,ra=33321,na=36756,ia=33325,sa=33326,oa=33330,aa=33329,ca=33338,ua=33337,fa=33340,la=33339,da=33323,ha=36757,ma=33327,pa=33328,ga=33336,ya=33335,ba=33332,xa=33331,_a=33334,Ea=33333,wa=32849,va=35905,Ta=36194,Aa=36758,Ia=35898,Sa=35901,Ra=34843,Fa=34837,Pa=36221,ka=36239,Ca=36215,Ba=36233,Da=36209,Ma=36227,Oa=32856,Ua=35907,Na=36759,La=32855,za=32854,Ga=32857,$a=34842,Wa=34836,Va=36220,Ha=36238,ja=36975,Xa=36214,Ya=36232,Qa=36226,qa=36208,Ka=33189,Ja=33190,Za=36012,ec=36013,tc=35056,ie=5120,T=5121,wt=5122,Se=5123,vt=5124,ge=5125,B=5126,Bn=32819,Dn=32820,Mn=33635,z=5131,$e=36193,yr=33640,rc=35899,nc=35902,ic=36269,sc=34042,Tt=33319,Re=33320,At=6403,Fe=36244,Pe=36248,ye=36249;let br;function It(r){if(!br){const e={};e[vn]={textureFormat:vn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[T,z,$e,B]},e[Tn]={textureFormat:Tn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[T,z,$e,B]},e[An]={textureFormat:An,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2,4,4,8],type:[T,z,$e,B]},e[V]={textureFormat:V,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,6,6,12,2],type:[T,z,$e,B,Mn]},e[A]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,8,8,16,2,2],type:[T,z,$e,B,Bn,Dn]},e[Ge]={textureFormat:Ge,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[ge,Se]},e[ra]={textureFormat:At,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1],type:[T]},e[na]={textureFormat:At,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[1],type:[ie]},e[ia]={textureFormat:At,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4,2],type:[B,z]},e[sa]={textureFormat:At,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[4],type:[B]},e[oa]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[T]},e[aa]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[ie]},e[ba]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Se]},e[xa]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[wt]},e[_a]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ge]},e[Ea]={textureFormat:Fe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[vt]},e[da]={textureFormat:Tt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2],type:[T]},e[ha]={textureFormat:Tt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[2],type:[ie]},e[ma]={textureFormat:Tt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[8,4],type:[B,z]},e[pa]={textureFormat:Tt,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[8],type:[B]},e[ga]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[T]},e[ya]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[ie]},e[ca]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Se]},e[ua]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[wt]},e[fa]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[ge]},e[la]={textureFormat:Re,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[vt]},e[wa]={textureFormat:V,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3],type:[T]},e[va]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[T]},e[Ta]={textureFormat:V,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,2],type:[T,Mn]},e[Aa]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[ie]},e[Ia]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[B,z,rc]},e[Sa]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[B,z,nc]},e[Ra]={textureFormat:V,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6],type:[B,z]},e[Fa]={textureFormat:V,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[B]},e[Pa]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[T]},e[ka]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[ie]},e[Ca]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Se]},e[Ba]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[wt]},e[Da]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[ge]},e[Ma]={textureFormat:Pe,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[vt]},e[Oa]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[T]},e[Ua]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[T]},e[Na]={textureFormat:A,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4],type:[ie]},e[La]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2,4],type:[T,Dn,yr]},e[za]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2],type:[T,Bn]},e[Ga]={textureFormat:A,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[yr]},e[$a]={textureFormat:A,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[16,8],type:[B,z]},e[Wa]={textureFormat:A,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[16],type:[B]},e[Va]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[T]},e[Ha]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ie]},e[ja]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[yr]},e[Xa]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Se]},e[Ya]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[wt]},e[Qa]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[vt]},e[qa]={textureFormat:ye,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[ge]},e[Ka]={textureFormat:Ge,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[Se,ge]},e[Ja]={textureFormat:Ge,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ge]},e[Za]={textureFormat:Ge,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[B]},e[tc]={textureFormat:In,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[sc]},e[ec]={textureFormat:In,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ic]},Object.keys(e).forEach(function(t){const n=e[t];n.bytesPerElementMap={},n.bytesPerElement.forEach(function(i,s){const o=n.type[s];n.bytesPerElementMap[o]=i})}),br=e}return br[r]}function oc(r,e){const t=It(r);if(!t)throw"unknown internal format";const n=t.bytesPerElementMap[e];if(n===void 0)throw"unknown internal format";return n}function We(r){const e=It(r);if(!e)throw"unknown internal format";return{format:e.textureFormat,type:e.type[0]}}function On(r){return(r&r-1)===0}function ac(r,e,t,n){if(!Le(r))return On(e)&&On(t);const i=It(n);if(!i)throw"unknown internal format";return i.colorRenderable&&i.textureFilterable}function cc(r){const e=It(r);if(!e)throw"unknown internal format";return e.textureFilterable}function uc(r,e,t){return ze(e)?ur(e):t||T}function St(r,e,t,n,i){if(i%1!==0)throw"can\'t guess dimensions";if(!t&&!n){const s=Math.sqrt(i/(e===ne?6:1));s%1===0?(t=s,n=s):(t=i,n=1)}else if(n){if(!t&&(t=i/n,t%1))throw"can\'t guess dimensions"}else if(n=i/t,n%1)throw"can\'t guess dimensions";return{width:t,height:n}}function ke(r,e){e.colorspaceConversion!==void 0&&r.pixelStorei(Zo,e.colorspaceConversion),e.premultiplyAlpha!==void 0&&r.pixelStorei(ea,e.premultiplyAlpha),e.flipY!==void 0&&r.pixelStorei(ta,e.flipY)}function Un(r){r.pixelStorei(gr,4),Le(r)&&(r.pixelStorei(Rn,0),r.pixelStorei(Fn,0),r.pixelStorei(Pn,0),r.pixelStorei(kn,0),r.pixelStorei(Cn,0))}function fc(r,e,t,n){n.minMag&&(t.call(r,e,mr,n.minMag),t.call(r,e,pr,n.minMag)),n.min&&t.call(r,e,mr,n.min),n.mag&&t.call(r,e,pr,n.mag),n.wrap&&(t.call(r,e,_t,n.wrap),t.call(r,e,Et,n.wrap),(e===me||go(r,e))&&t.call(r,e,Sn,n.wrap)),n.wrapR&&t.call(r,e,Sn,n.wrapR),n.wrapS&&t.call(r,e,_t,n.wrapS),n.wrapT&&t.call(r,e,Et,n.wrapT),n.minLod!==void 0&&t.call(r,e,Xo,n.minLod),n.maxLod!==void 0&&t.call(r,e,Yo,n.maxLod),n.baseLevel!==void 0&&t.call(r,e,Qo,n.baseLevel),n.maxLevel!==void 0&&t.call(r,e,qo,n.maxLevel),n.compareFunc!==void 0&&t.call(r,e,Jo,n.compareFunc),n.compareMode!==void 0&&t.call(r,e,Ko,n.compareMode)}function Nn(r,e,t){const n=t.target||re;r.bindTexture(n,e),fc(r,n,r.texParameteri,t)}function lc(r){return r=r||te.textureColor,ze(r)?r:new Uint8Array([r[0]*255,r[1]*255,r[2]*255,r[3]*255])}function xr(r,e,t,n,i,s){t=t||te.textureOptions,s=s||A;const o=t.target||re;if(n=n||t.width,i=i||t.height,r.bindTexture(o,e),ac(r,n,i,s))r.generateMipmap(o);else{const a=cc(s)?Go:zo;r.texParameteri(o,mr,a),r.texParameteri(o,pr,a),r.texParameteri(o,_t,xt),r.texParameteri(o,Et,xt)}}function Ve(r){return r.auto===!0||r.auto===void 0&&r.level===void 0}function _r(r,e){return e=e||{},e.cubeFaceOrder||[hr,$o,Wo,Vo,Ho,jo]}function Er(r,e){const n=_r(r,e).map(function(i,s){return{face:i,ndx:s}});return n.sort(function(i,s){return i.face-s.face}),n}function Ln(r,e,t,n){n=n||te.textureOptions;const i=n.target||re,s=n.level||0;let o=t.width,a=t.height;const c=n.internalFormat||n.format||A,u=We(c),d=n.format||u.format,m=n.type||u.type;if(ke(r,n),r.bindTexture(i,e),i===ne){const p=t.width,y=t.height;let l,b;if(p/6===y)l=y,b=[0,0,1,0,2,0,3,0,4,0,5,0];else if(y/6===p)l=p,b=[0,0,0,1,0,2,0,3,0,4,0,5];else if(p/3===y/2)l=p/3,b=[0,0,1,0,2,0,0,1,1,1,2,1];else if(p/2===y/3)l=p/2,b=[0,0,1,0,0,1,1,1,0,2,1,2];else throw"can\'t figure out cube map from element: "+(t.src?t.src:t.nodeName);const _=wn();_?(_.canvas.width=l,_.canvas.height=l,o=l,a=l,Er(r,n).forEach(function(E){const R=b[E.ndx*2+0]*l,k=b[E.ndx*2+1]*l;_.drawImage(t,R,k,l,l,0,0,l,l),r.texImage2D(E.face,s,c,d,m,_.canvas)}),_.canvas.width=1,_.canvas.height=1):typeof createImageBitmap<"u"&&(o=l,a=l,Er(r,n).forEach(function(E){const R=b[E.ndx*2+0]*l,k=b[E.ndx*2+1]*l;r.texImage2D(E.face,s,c,l,l,0,d,m,null),createImageBitmap(t,R,k,l,l,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(function(N){ke(r,n),r.bindTexture(i,e),r.texImage2D(E.face,s,c,d,m,N),Ve(n)&&xr(r,e,n,o,a,c)})}))}else if(i===me||i===pe){const p=Math.min(t.width,t.height),y=Math.max(t.width,t.height),l=y/p;if(l%1!==0)throw"can not compute 3D dimensions of element";const b=t.width===y?1:0,_=t.height===y?1:0;r.pixelStorei(gr,1),r.pixelStorei(Rn,t.width),r.pixelStorei(Fn,0),r.pixelStorei(Cn,0),r.texImage3D(i,s,c,p,p,p,0,d,m,null);for(let E=0;E<l;++E){const R=E*p*b,k=E*p*_;r.pixelStorei(Pn,R),r.pixelStorei(kn,k),r.texSubImage3D(i,s,0,0,E,p,p,1,d,m,t)}Un(r)}else r.texImage2D(i,s,c,d,m,t);Ve(n)&&xr(r,e,n,o,a,c),Nn(r,e,n)}function He(){}function dc(r){if(typeof document<"u"){const e=document.createElement("a");return e.href=r,e.hostname===location.hostname&&e.port===location.port&&e.protocol===location.protocol}else{const e=new URL(location.href).origin;return new URL(r,location.href).origin===e}}function hc(r,e){return e===void 0&&!dc(r)?"anonymous":e}function mc(r,e,t){t=t||He;let n;if(e=e!==void 0?e:te.crossOrigin,e=hc(r,e),typeof Image<"u"){n=new Image,e!==void 0&&(n.crossOrigin=e);const i=function(){n.removeEventListener("error",s),n.removeEventListener("load",o),n=null},s=function(){const c="couldn\'t load image: "+r;hn(c),t(c,n),i()},o=function(){t(null,n),i()};return n.addEventListener("error",s),n.addEventListener("load",o),n.src=r,n}else if(typeof ImageBitmap<"u"){let i,s;const o=function(){t(i,s)},a={};e&&(a.mode="cors"),fetch(r,a).then(function(c){if(!c.ok)throw c;return c.blob()}).then(function(c){return createImageBitmap(c,{premultiplyAlpha:"none",colorSpaceConversion:"none"})}).then(function(c){s=c,setTimeout(o)}).catch(function(c){i=c,setTimeout(o)}),n=null}return n}function zn(r){return typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof ImageData<"u"&&r instanceof ImageData||typeof HTMLElement<"u"&&r instanceof HTMLElement}function wr(r,e,t){return zn(r)?(setTimeout(function(){t(null,r)}),r):mc(r,e,t)}function vr(r,e,t){t=t||te.textureOptions;const n=t.target||re;if(r.bindTexture(n,e),t.color===!1)return;const i=lc(t.color);if(n===ne)for(let s=0;s<6;++s)r.texImage2D(hr+s,0,A,1,1,0,A,T,i);else n===me||n===pe?r.texImage3D(n,0,A,1,1,1,0,A,T,i):r.texImage2D(n,0,A,1,1,0,A,T,i)}function pc(r,e,t,n){return n=n||He,t=t||te.textureOptions,vr(r,e,t),t=Object.assign({},t),wr(t.src,t.crossOrigin,function(s,o){s?n(s,e,o):(Ln(r,e,o,t),n(null,e,o))})}function gc(r,e,t,n){n=n||He;const i=t.src;if(i.length!==6)throw"there must be 6 urls for a cubemap";const s=t.level||0,o=t.internalFormat||t.format||A,a=We(o),c=t.format||a.format,u=t.type||T,d=t.target||re;if(d!==ne)throw"target must be TEXTURE_CUBE_MAP";vr(r,e,t),t=Object.assign({},t);let m=6;const p=[],y=_r(r,t);let l;function b(_){return function(E,R){--m,E?p.push(E):R.width!==R.height?p.push("cubemap face img is not a square: "+R.src):(ke(r,t),r.bindTexture(d,e),m===5?_r().forEach(function(k){r.texImage2D(k,s,o,c,u,R)}):r.texImage2D(_,s,o,c,u,R),Ve(t)&&r.generateMipmap(d)),m===0&&n(p.length?p:void 0,e,l)}}l=i.map(function(_,E){return wr(_,t.crossOrigin,b(y[E]))})}function yc(r,e,t,n){n=n||He;const i=t.src,s=t.internalFormat||t.format||A,o=We(s),a=t.format||o.format,c=t.type||T,u=t.target||pe;if(u!==me&&u!==pe)throw"target must be TEXTURE_3D or TEXTURE_2D_ARRAY";vr(r,e,t),t=Object.assign({},t);let d=i.length;const m=[];let p;const y=t.level||0;let l=t.width,b=t.height;const _=i.length;let E=!0;function R(k){return function(N,Q){if(--d,N)m.push(N);else{if(ke(r,t),r.bindTexture(u,e),E){E=!1,l=t.width||Q.width,b=t.height||Q.height,r.texImage3D(u,y,s,l,b,_,0,a,c,null);for(let q=0;q<_;++q)r.texSubImage3D(u,y,0,0,q,l,b,1,a,c,Q)}else{let q=Q,L;(Q.width!==l||Q.height!==b)&&(L=wn(),q=L.canvas,L.canvas.width=l,L.canvas.height=b,L.drawImage(Q,0,0,l,b)),r.texSubImage3D(u,y,0,0,k,l,b,1,a,c,q),L&&q===L.canvas&&(L.canvas.width=0,L.canvas.height=0)}Ve(t)&&r.generateMipmap(u)}d===0&&n(m.length?m:void 0,e,p)}}p=i.map(function(k,N){return wr(k,t.crossOrigin,R(N))})}function bc(r,e,t,n){n=n||te.textureOptions;const i=n.target||re;r.bindTexture(i,e);let s=n.width,o=n.height,a=n.depth;const c=n.level||0,u=n.internalFormat||n.format||A,d=We(u),m=n.format||d.format,p=n.type||uc(r,t,d.type);if(ze(t))t instanceof Uint8ClampedArray&&(t=new Uint8Array(t.buffer));else{const _=dn(p);t=new _(t)}const y=oc(u,p),l=t.byteLength/y;if(l%1)throw"length wrong size for format: "+En(r,m);let b;if(i===me||i===pe)if(!s&&!o&&!a){const _=Math.cbrt(l);if(_%1!==0)throw"can\'t guess cube size of array of numElements: "+l;s=_,o=_,a=_}else s&&(!o||!a)?(b=St(r,i,o,a,l/s),o=b.width,a=b.height):o&&(!s||!a)?(b=St(r,i,s,a,l/o),s=b.width,a=b.height):(b=St(r,i,s,o,l/a),s=b.width,o=b.height);else b=St(r,i,s,o,l),s=b.width,o=b.height;if(Un(r),r.pixelStorei(gr,n.unpackAlignment||1),ke(r,n),i===ne){const _=y/t.BYTES_PER_ELEMENT,E=l/6*_;Er(r,n).forEach(R=>{const k=E*R.ndx,N=t.subarray(k,k+E);r.texImage2D(R.face,c,u,s,o,0,m,p,N)})}else i===me||i===pe?r.texImage3D(i,c,u,s,o,a,0,m,p,t):r.texImage2D(i,c,u,s,o,0,m,p,t);return{width:s,height:o,depth:a,type:p}}function xc(r,e,t){const n=t.target||re;r.bindTexture(n,e);const i=t.level||0,s=t.internalFormat||t.format||A,o=We(s),a=t.format||o.format,c=t.type||o.type;if(ke(r,t),n===ne)for(let u=0;u<6;++u)r.texImage2D(hr+u,i,s,t.width,t.height,0,a,c,null);else n===me||n===pe?r.texImage3D(n,i,s,t.width,t.height,t.depth,0,a,c,null):r.texImage2D(n,i,s,t.width,t.height,0,a,c,null)}function Gn(r,e,t){t=t||He,e=e||te.textureOptions;const n=r.createTexture(),i=e.target||re;let s=e.width||1,o=e.height||1;const a=e.internalFormat||A;r.bindTexture(i,n),i===ne&&(r.texParameteri(i,_t,xt),r.texParameteri(i,Et,xt));let c=e.src;if(c)if(typeof c=="function"&&(c=c(r,e)),typeof c=="string")pc(r,n,e,t);else if(ze(c)||Array.isArray(c)&&(typeof c[0]=="number"||Array.isArray(c[0])||ze(c[0]))){const u=bc(r,n,c,e);s=u.width,o=u.height}else Array.isArray(c)&&(typeof c[0]=="string"||zn(c[0]))?i===ne?gc(r,n,e,t):yc(r,n,e,t):(Ln(r,n,c,e),s=c.width,o=c.height);else xc(r,n,e);return Ve(e)&&xr(r,n,e,s,o,a),Nn(r,n,e),n}const Tr=hn;function $n(r){return typeof document<"u"&&document.getElementById?document.getElementById(r):null}const Rt=33984,Ft=34962,_c=34963,Ec=35713,wc=35714,vc=35632,Tc=35633,Ac=35981,Wn=35718,Ic=35721,Sc=35971,Rc=35382,Fc=35396,Pc=35398,kc=35392,Cc=35395,Pt=5126,Vn=35664,Hn=35665,jn=35666,Ar=5124,Xn=35667,Yn=35668,Qn=35669,qn=35670,Kn=35671,Jn=35672,Zn=35673,ei=35674,ti=35675,ri=35676,Bc=35678,Dc=35680,Mc=35679,Oc=35682,Uc=35685,Nc=35686,Lc=35687,zc=35688,Gc=35689,$c=35690,Wc=36289,Vc=36292,Hc=36293,Ir=5125,ni=36294,ii=36295,si=36296,jc=36298,Xc=36299,Yc=36300,Qc=36303,qc=36306,Kc=36307,Jc=36308,Zc=36311,kt=3553,Ct=34067,Sr=32879,Bt=35866,x={};function oi(r,e){return x[e].bindPoint}function eu(r,e){return function(t){r.uniform1f(e,t)}}function tu(r,e){return function(t){r.uniform1fv(e,t)}}function ru(r,e){return function(t){r.uniform2fv(e,t)}}function nu(r,e){return function(t){r.uniform3fv(e,t)}}function iu(r,e){return function(t){r.uniform4fv(e,t)}}function ai(r,e){return function(t){r.uniform1i(e,t)}}function ci(r,e){return function(t){r.uniform1iv(e,t)}}function ui(r,e){return function(t){r.uniform2iv(e,t)}}function fi(r,e){return function(t){r.uniform3iv(e,t)}}function li(r,e){return function(t){r.uniform4iv(e,t)}}function su(r,e){return function(t){r.uniform1ui(e,t)}}function ou(r,e){return function(t){r.uniform1uiv(e,t)}}function au(r,e){return function(t){r.uniform2uiv(e,t)}}function cu(r,e){return function(t){r.uniform3uiv(e,t)}}function uu(r,e){return function(t){r.uniform4uiv(e,t)}}function fu(r,e){return function(t){r.uniformMatrix2fv(e,!1,t)}}function lu(r,e){return function(t){r.uniformMatrix3fv(e,!1,t)}}function du(r,e){return function(t){r.uniformMatrix4fv(e,!1,t)}}function hu(r,e){return function(t){r.uniformMatrix2x3fv(e,!1,t)}}function mu(r,e){return function(t){r.uniformMatrix3x2fv(e,!1,t)}}function pu(r,e){return function(t){r.uniformMatrix2x4fv(e,!1,t)}}function gu(r,e){return function(t){r.uniformMatrix4x2fv(e,!1,t)}}function yu(r,e){return function(t){r.uniformMatrix3x4fv(e,!1,t)}}function bu(r,e){return function(t){r.uniformMatrix4x3fv(e,!1,t)}}function O(r,e,t,n){const i=oi(r,e);return Le(r)?function(s){let o,a;!s||fr(r,s)?(o=s,a=null):(o=s.texture,a=s.sampler),r.uniform1i(n,t),r.activeTexture(Rt+t),r.bindTexture(i,o),r.bindSampler(t,a)}:function(s){r.uniform1i(n,t),r.activeTexture(Rt+t),r.bindTexture(i,s)}}function U(r,e,t,n,i){const s=oi(r,e),o=new Int32Array(i);for(let a=0;a<i;++a)o[a]=t+a;return Le(r)?function(a){r.uniform1iv(n,o),a.forEach(function(c,u){r.activeTexture(Rt+o[u]);let d,m;!c||fr(r,c)?(d=c,m=null):(d=c.texture,m=c.sampler),r.bindSampler(t,m),r.bindTexture(s,d)})}:function(a){r.uniform1iv(n,o),a.forEach(function(c,u){r.activeTexture(Rt+o[u]),r.bindTexture(s,c)})}}x[Pt]={Type:Float32Array,size:4,setter:eu,arraySetter:tu},x[Vn]={Type:Float32Array,size:8,setter:ru,cols:2},x[Hn]={Type:Float32Array,size:12,setter:nu,cols:3},x[jn]={Type:Float32Array,size:16,setter:iu,cols:4},x[Ar]={Type:Int32Array,size:4,setter:ai,arraySetter:ci},x[Xn]={Type:Int32Array,size:8,setter:ui,cols:2},x[Yn]={Type:Int32Array,size:12,setter:fi,cols:3},x[Qn]={Type:Int32Array,size:16,setter:li,cols:4},x[Ir]={Type:Uint32Array,size:4,setter:su,arraySetter:ou},x[ni]={Type:Uint32Array,size:8,setter:au,cols:2},x[ii]={Type:Uint32Array,size:12,setter:cu,cols:3},x[si]={Type:Uint32Array,size:16,setter:uu,cols:4},x[qn]={Type:Uint32Array,size:4,setter:ai,arraySetter:ci},x[Kn]={Type:Uint32Array,size:8,setter:ui,cols:2},x[Jn]={Type:Uint32Array,size:12,setter:fi,cols:3},x[Zn]={Type:Uint32Array,size:16,setter:li,cols:4},x[ei]={Type:Float32Array,size:32,setter:fu,rows:2,cols:2},x[ti]={Type:Float32Array,size:48,setter:lu,rows:3,cols:3},x[ri]={Type:Float32Array,size:64,setter:du,rows:4,cols:4},x[Uc]={Type:Float32Array,size:32,setter:hu,rows:2,cols:3},x[Nc]={Type:Float32Array,size:32,setter:pu,rows:2,cols:4},x[Lc]={Type:Float32Array,size:48,setter:mu,rows:3,cols:2},x[zc]={Type:Float32Array,size:48,setter:yu,rows:3,cols:4},x[Gc]={Type:Float32Array,size:64,setter:gu,rows:4,cols:2},x[$c]={Type:Float32Array,size:64,setter:bu,rows:4,cols:3},x[Bc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:kt},x[Dc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Ct},x[Mc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Sr},x[Oc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:kt},x[Wc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Bt},x[Vc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Bt},x[Hc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Ct},x[jc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:kt},x[Xc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Sr},x[Yc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Ct},x[Qc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Bt},x[qc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:kt},x[Kc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Sr},x[Jc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Ct},x[Zc]={Type:null,size:0,setter:O,arraySetter:U,bindPoint:Bt};function Dt(r,e){return function(t){if(t.value)switch(r.disableVertexAttribArray(e),t.value.length){case 4:r.vertexAttrib4fv(e,t.value);break;case 3:r.vertexAttrib3fv(e,t.value);break;case 2:r.vertexAttrib2fv(e,t.value);break;case 1:r.vertexAttrib1fv(e,t.value);break;default:throw new Error("the length of a float constant value must be between 1 and 4!")}else r.bindBuffer(Ft,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribPointer(e,t.numComponents||t.size,t.type||Pt,t.normalize||!1,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function se(r,e){return function(t){if(t.value)if(r.disableVertexAttribArray(e),t.value.length===4)r.vertexAttrib4iv(e,t.value);else throw new Error("The length of an integer constant value must be 4!");else r.bindBuffer(Ft,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribIPointer(e,t.numComponents||t.size,t.type||Ar,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function Mt(r,e){return function(t){if(t.value)if(r.disableVertexAttribArray(e),t.value.length===4)r.vertexAttrib4uiv(e,t.value);else throw new Error("The length of an unsigned integer constant value must be 4!");else r.bindBuffer(Ft,t.buffer),r.enableVertexAttribArray(e),r.vertexAttribIPointer(e,t.numComponents||t.size,t.type||Ir,t.stride||0,t.offset||0),r.vertexAttribDivisor&&r.vertexAttribDivisor(e,t.divisor||0)}}function Rr(r,e,t){const n=t.size,i=t.count;return function(s){r.bindBuffer(Ft,s.buffer);const o=s.size||s.numComponents||n,a=o/i,c=s.type||Pt,d=x[c].size*o,m=s.normalize||!1,p=s.offset||0,y=d/i;for(let l=0;l<i;++l)r.enableVertexAttribArray(e+l),r.vertexAttribPointer(e+l,a,c,m,d,p+y*l),r.vertexAttribDivisor&&r.vertexAttribDivisor(e+l,s.divisor||0)}}const I={};I[Pt]={size:4,setter:Dt},I[Vn]={size:8,setter:Dt},I[Hn]={size:12,setter:Dt},I[jn]={size:16,setter:Dt},I[Ar]={size:4,setter:se},I[Xn]={size:8,setter:se},I[Yn]={size:12,setter:se},I[Qn]={size:16,setter:se},I[Ir]={size:4,setter:Mt},I[ni]={size:8,setter:Mt},I[ii]={size:12,setter:Mt},I[si]={size:16,setter:Mt},I[qn]={size:4,setter:se},I[Kn]={size:8,setter:se},I[Jn]={size:12,setter:se},I[Zn]={size:16,setter:se},I[ei]={size:4,setter:Rr,count:2},I[ti]={size:9,setter:Rr,count:3},I[ri]={size:16,setter:Rr,count:4};const xu=/ERROR:\\s*\\d+:(\\d+)/gi;function _u(r,e="",t=0){const n=[...e.matchAll(xu)],i=new Map(n.map((s,o)=>{const a=parseInt(s[1]),c=n[o+1],u=c?c.index:e.length,d=e.substring(s.index,u);return[a-1,d]}));return r.split(`\n`).map((s,o)=>{const a=i.get(o);return`${o+1+t}: ${s}${a?`\n\n^^^ ${a}`:""}`}).join(`\n`)}const di=/^[ \\t]*\\n/;function hi(r){let e=0;return di.test(r)&&(e=1,r=r.replace(di,"")),{lineOffset:e,shaderSource:r}}function Eu(r,e){return r.errorCallback(e),r.callback&&setTimeout(()=>{r.callback(`${e}\n${r.errors.join(`\n`)}`)}),null}function wu(r,e,t,n){if(n=n||Tr,!r.getShaderParameter(t,Ec)){const s=r.getShaderInfoLog(t),{lineOffset:o,shaderSource:a}=hi(r.getShaderSource(t)),c=`${_u(a,s,o)}\nError compiling ${En(r,e)}: ${s}`;return n(c),c}return""}function Fr(r,e,t){let n,i,s;if(typeof e=="function"&&(t=e,e=void 0),typeof r=="function")t=r,r=void 0;else if(r&&!Array.isArray(r)){const u=r;t=u.errorCallback,r=u.attribLocations,n=u.transformFeedbackVaryings,i=u.transformFeedbackMode,s=u.callback}const o=t||Tr,a=[],c={errorCallback(u,...d){a.push(u),o(u,...d)},transformFeedbackVaryings:n,transformFeedbackMode:i,callback:s,errors:a};{let u={};Array.isArray(r)?r.forEach(function(d,m){u[d]=e?e[m]:m}):u=r||{},c.attribLocations=u}return c}const vu=["VERTEX_SHADER","FRAGMENT_SHADER"];function Tu(r,e){if(e.indexOf("frag")>=0)return vc;if(e.indexOf("vert")>=0)return Tc}function Au(r,e,t){const n=r.getAttachedShaders(e);for(const i of n)t.has(i)&&r.deleteShader(i);r.deleteProgram(e)}const Iu=(r=0)=>new Promise(e=>setTimeout(e,r));function Su(r,e,t){const n=r.createProgram(),{attribLocations:i,transformFeedbackVaryings:s,transformFeedbackMode:o}=Fr(t);for(let a=0;a<e.length;++a){let c=e[a];if(typeof c=="string"){const u=$n(c),d=u?u.text:c;let m=r[vu[a]];u&&u.type&&(m=Tu(r,u.type)||m),c=r.createShader(m),r.shaderSource(c,hi(d).shaderSource),r.compileShader(c),r.attachShader(n,c)}}Object.entries(i).forEach(([a,c])=>r.bindAttribLocation(n,c,a));{let a=s;a&&(a.attribs&&(a=a.attribs),Array.isArray(a)||(a=Object.keys(a)),r.transformFeedbackVaryings(n,a,o||Ac))}return r.linkProgram(n),n}function Ru(r,e,t,n,i){const s=Fr(t,n,i),o=new Set(e),a=Su(r,e,s);function c(u,d){const m=Pu(u,d,s.errorCallback);return m&&Au(u,d,o),m}if(s.callback){Fu(r,a).then(()=>{const u=c(r,a);s.callback(u,u?void 0:a)});return}return c(r,a)?void 0:a}async function Fu(r,e){const t=r.getExtension("KHR_parallel_shader_compile"),n=t?(s,o)=>s.getProgramParameter(o,t.COMPLETION_STATUS_KHR):()=>!0;let i=0;do await Iu(i),i=1e3/60;while(!n(r,e))}function Pu(r,e,t){if(t=t||Tr,!r.getProgramParameter(e,wc)){const i=r.getProgramInfoLog(e);t(`Error in program linking: ${i}`);const o=r.getAttachedShaders(e).map(a=>wu(r,r.getShaderParameter(a,r.SHADER_TYPE),a,t));return`${i}\n${o.filter(a=>a).join(`\n`)}`}}function ku(r,e,t,n,i){return Ru(r,e,t,n,i)}function mi(r){const e=r.name;return e.startsWith("gl_")||e.startsWith("webgl_")}const Cu=/(\\.|\\[|]|\\w+)/g,Bu=r=>r>="0"&&r<="9";function Du(r,e,t,n){const i=r.split(Cu).filter(a=>a!=="");let s=0,o="";for(;;){const a=i[s++];o+=a;const c=Bu(a[0]),u=c?parseInt(a):a;if(c&&(o+=i[s++]),s===i.length){t[u]=e;break}else{const m=i[s++],p=m==="[",y=t[u]||(p?[]:{});t[u]=y,t=y,n[o]=n[o]||(function(l){return function(b){pi(l,b)}})(y),o+=m}}}function Mu(r,e){let t=0;function n(a,c,u){const d=c.name.endsWith("[0]"),m=c.type,p=x[m];if(!p)throw new Error(`unknown type: 0x${m.toString(16)}`);let y;if(p.bindPoint){const l=t;t+=c.size,d?y=p.arraySetter(r,m,l,u,c.size):y=p.setter(r,m,l,u,c.size)}else p.arraySetter&&d?y=p.arraySetter(r,u):y=p.setter(r,u);return y.location=u,y}const i={},s={},o=r.getProgramParameter(e,Wn);for(let a=0;a<o;++a){const c=r.getActiveUniform(e,a);if(mi(c))continue;let u=c.name;u.endsWith("[0]")&&(u=u.substr(0,u.length-3));const d=r.getUniformLocation(e,c.name);if(d){const m=n(e,c,d);i[u]=m,Du(u,m,s,i)}}return i}function Ou(r,e){const t={},n=r.getProgramParameter(e,Sc);for(let i=0;i<n;++i){const s=r.getTransformFeedbackVarying(e,i);t[s.name]={index:i,type:s.type,size:s.size}}return t}function Uu(r,e){const t=r.getProgramParameter(e,Wn),n=[],i=[];for(let a=0;a<t;++a){i.push(a),n.push({});const c=r.getActiveUniform(e,a);n[a].name=c.name}[["UNIFORM_TYPE","type"],["UNIFORM_SIZE","size"],["UNIFORM_BLOCK_INDEX","blockNdx"],["UNIFORM_OFFSET","offset"]].forEach(function(a){const c=a[0],u=a[1];r.getActiveUniforms(e,i,r[c]).forEach(function(d,m){n[m][u]=d})});const s={},o=r.getProgramParameter(e,Rc);for(let a=0;a<o;++a){const c=r.getActiveUniformBlockName(e,a),u={index:r.getUniformBlockIndex(e,c),usedByVertexShader:r.getActiveUniformBlockParameter(e,a,Fc),usedByFragmentShader:r.getActiveUniformBlockParameter(e,a,Pc),size:r.getActiveUniformBlockParameter(e,a,kc),uniformIndices:r.getActiveUniformBlockParameter(e,a,Cc)};u.used=u.usedByVertexShader||u.usedByFragmentShader,s[c]=u}return{blockSpecs:s,uniformData:n}}function pi(r,e){for(const t in e){const n=r[t];typeof n=="function"?n(e[t]):pi(r[t],e[t])}}function gi(r,...e){const t=r.uniformSetters||r,n=e.length;for(let i=0;i<n;++i){const s=e[i];if(Array.isArray(s)){const o=s.length;for(let a=0;a<o;++a)gi(t,s[a])}else for(const o in s){const a=t[o];a&&a(s[o])}}}function Nu(r,e){const t={},n=r.getProgramParameter(e,Ic);for(let i=0;i<n;++i){const s=r.getActiveAttrib(e,i);if(mi(s))continue;const o=r.getAttribLocation(e,s.name),a=I[s.type],c=a.setter(r,o,a);c.location=o,t[s.name]=c}return t}function Lu(r,e){for(const t in e){const n=r[t];n&&n(e[t])}}function zu(r,e,t){t.vertexArrayObject?r.bindVertexArray(t.vertexArrayObject):(Lu(e.attribSetters||e,t.attribs),t.indices&&r.bindBuffer(_c,t.indices))}function yi(r,e){const t=Mu(r,e),n=Nu(r,e),i={program:e,uniformSetters:t,attribSetters:n};return Le(r)&&(i.uniformBlockSpec=Uu(r,e),i.transformFeedbackInfo=Ou(r,e)),i}const Gu=/\\s|{|}|;/;function $u(r,e,t,n,i){const s=Fr(t,n,i),o=[];if(e=e.map(function(u){if(!Gu.test(u)){const d=$n(u);if(d)u=d.text;else{const m=`no element with id: ${u}`;s.errorCallback(m),o.push(m)}}return u}),o.length)return Eu(s,"");const a=s.callback;a&&(s.callback=(u,d)=>{a(u,u?void 0:yi(r,d))});const c=ku(r,e,s);return c?yi(r,c):null}const Wu=4,bi=5123;function Vu(r,e,t,n,i,s){t=t===void 0?Wu:t;const o=e.indices,a=e.elementType,c=n===void 0?e.numElements:n;i=i===void 0?0:i,a||o?s!==void 0?r.drawElementsInstanced(t,c,a===void 0?bi:e.elementType,i,s):r.drawElements(t,c,a===void 0?bi:e.elementType,i):s!==void 0?r.drawArraysInstanced(t,i,c,s):r.drawArrays(t,i,c)}const xi=36160,Ot=36161,Hu=3553,ju=5121,Xu=6402,Yu=6408,Qu=33190,qu=36012,Ku=35056,Ju=36013,Zu=32854,ef=32855,tf=36194,_i=33189,Ei=6401,wi=36168,Pr=34041,kr=36064,Ut=36096,vi=36128,Cr=33306,Br=33071,Dr=9729,rf=[{format:Yu,type:ju,min:Dr,wrap:Br},{format:Pr}],G={};G[Pr]=Cr,G[Ei]=vi,G[wi]=vi,G[Xu]=Ut,G[_i]=Ut,G[Qu]=Ut,G[qu]=Ut,G[Ku]=Cr,G[Ju]=Cr;function nf(r,e){return G[r]||G[e]}const oe={};oe[Zu]=!0,oe[ef]=!0,oe[tf]=!0,oe[Pr]=!0,oe[_i]=!0,oe[Ei]=!0,oe[wi]=!0;function sf(r){return oe[r]}const of=32;function af(r){return r>=kr&&r<kr+of}function Ti(r,e,t,n){const i=xi,s=r.createFramebuffer();r.bindFramebuffer(i,s),t=t||r.drawingBufferWidth,n=n||r.drawingBufferHeight,e=e||rf;const o=[],a={framebuffer:s,attachments:[],width:t,height:n};return e.forEach(function(c,u){let d=c.attachment;const m=c.samples,p=c.format;let y=c.attachmentPoint||nf(p,c.internalFormat);if(y||(y=kr+u),af(y)&&o.push(y),!d)if(m!==void 0||sf(p))d=r.createRenderbuffer(),r.bindRenderbuffer(Ot,d),m>1?r.renderbufferStorageMultisample(Ot,m,p,t,n):r.renderbufferStorage(Ot,p,t,n);else{const l=Object.assign({},c);l.width=t,l.height=n,l.auto===void 0&&(l.auto=!1,l.min=l.min||l.minMag||Dr,l.mag=l.mag||l.minMag||Dr,l.wrapS=l.wrapS||l.wrap||Br,l.wrapT=l.wrapT||l.wrap||Br),d=Gn(r,l)}if(po(r,d))r.framebufferRenderbuffer(i,y,Ot,d);else if(fr(r,d))c.layer!==void 0?r.framebufferTextureLayer(i,y,d,c.level||0,c.layer):r.framebufferTexture2D(i,y,c.target||Hu,d,c.level||0);else throw new Error("unknown attachment type");a.attachments.push(d)}),r.drawBuffers&&r.drawBuffers(o),a}function cf(r,e,t){t=t||xi,e?(r.bindFramebuffer(t,e.framebuffer),r.viewport(0,0,e.width,e.height)):(r.bindFramebuffer(t,null),r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight))}function D(r,e){return()=>e instanceof WebGLTexture?e:Gn(r,{src:e,wrap:r.CLAMP_TO_EDGE})}const Ce=2;class je{constructor(e){this.id="_";const{context:t,width:n,height:i}=e;this.context=t,this.options=e;const s=this.buildDefines();this.programInfo=$u(this.context,[s+this.getVertexShader(),s+this.getFragmentShader()]),this.bufferInfo=Lo(this.context,this.getBuffers()),this.fbi=Ti(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],n,i),this.output=this.fbi.attachments[0]}resizeOutput(e,t){this.fbi=Ti(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],e,t),this.options.width=e,this.options.height=t,this.output=this.fbi.attachments[0]}getDefines(){return{}}getBuffers(){return{position:{numComponents:2,data:[-1,-1,-1,1,1,-1,1,1,-1,1,1,-1]},texture_coord:{numComponents:2,data:[0,0,0,1,1,0,1,1,0,1,1,0]}}}buildDefines(){let e="";const t=this.getDefines();for(let n in t)e+=`#define ${n} ${t[n].toFixed(1)}\n`;return e}run(e){this.profiler?.pushContext(`[${this.id}] PROG : ${this.constructor.name}`),this.profiler?.pushContext(`[${this.id}] UNIFORMS`);for(const i in e)typeof e[i]=="function"&&(this.profiler?.pushContext(`[${this.id}] UNI : ${i}`),e[i]=e[i](),this.profiler?.popContext(`[${this.id}] UNI : ${i}`));this.profiler?.popContext(`[${this.id}] UNIFORMS`);const t=Date.now();let n=0;this.lastRun&&(n=(t-this.lastRun)/1e3),this.lastRun=t,this.context.viewport(0,0,this.context.canvas.width,this.context.canvas.height),this.context.useProgram(this.programInfo.program),zu(this.context,this.programInfo,this.bufferInfo),gi(this.programInfo,{delta:n,canvas:[this.context.canvas.width,this.context.canvas.height],...e}),cf(this.context,this.options.disableFramebuffer?null:this.fbi),Vu(this.context,this.bufferInfo),this.profiler?.popContext(`[${this.id}] PROG : ${this.constructor.name}`)}setProfiler(e){this.profiler=e}}var uf=`precision mediump float;\n\nvarying vec2 _texture_coord;\n\nuniform sampler2D background;\nuniform sampler2D foreground;\nuniform sampler2D threshold;\n\nvoid main() {\n vec4 backgroundColor = texture2D(background, _texture_coord);\n vec4 foregroundColor = texture2D(foreground, _texture_coord);\n vec4 tresholdColor = texture2D(threshold, _texture_coord);\n gl_FragColor = foregroundColor * tresholdColor.a +\n backgroundColor * (1. - tresholdColor.a);\n}\n`,ff=`varying vec2 _texture_coord;\n\nattribute vec2 position;\nattribute vec2 texture_coord;\n\nvoid main() {\n gl_Position = vec4(position, 0., 1.);\n _texture_coord = texture_coord;\n _texture_coord.y = 1. - texture_coord.y;\n}\n`;class Mr extends je{getFragmentShader(){return uf}getVertexShader(){return ff}}class Or{constructor(){this.steps=[]}addStep(e){this.steps.push(e)}async run(){for(const e of this.steps)e.program.run(e.getUniforms())}resizeOutput(e,t){this.profiler?.pushContext(`PIP [${this.constructor.name}]`);for(const n of this.steps)n.preventResize||n.program.resizeOutput(e,t);this.profiler?.popContext(`PIP [${this.constructor.name}]`)}setProfiler(e){this.profiler=e;for(const t of this.steps)t.program.setProfiler(e)}setId(e){for(const t of this.steps)t.program.id=e}}class Ur extends Or{constructor(){super(...arguments),this.preciseMaskEnabled=!1}}class Ai extends Ur{constructor(e){super(),this.context=e,this.preciseMaskEnabled=!0;const t={context:e,height:e.canvas.height,width:e.canvas.width},n=new Mr({...t,disableFramebuffer:!0});this.addStep({program:n,getUniforms:()=>({background:D(e,this.inputBackgroundImage),foreground:D(e,this.inputImage),threshold:D(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}var lf=`precision mediump float;\n\nvarying vec2 _texture_coord;\nuniform sampler2D texture;\n\nvoid main() { gl_FragColor = texture2D(texture, _texture_coord); }\n`,df=`varying vec2 _texture_coord;\n\nattribute vec2 position;\nattribute vec2 texture_coord;\nuniform bool invert_y;\n\nvoid main() {\n gl_Position = vec4(position, 0., 1.);\n _texture_coord = texture_coord;\n if (invert_y) {\n _texture_coord.y = 1. - texture_coord.y;\n }\n}\n`;class hf extends je{getFragmentShader(){return lf}getVertexShader(){return df}}class mf extends Or{constructor(e,t,n){super(),this.context=e;const i={context:e,height:n,width:t};this.addStep({program:new hf({...i,disableFramebuffer:!0}),getUniforms:()=>({texture:D(e,this.inputImage),invert_y:!0})})}setData(e){this.inputImage=e}}async function Ii(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}var pf=`precision mediump float;\n\nvarying vec2 _texture_coord;\n\nuniform vec2 canvas;\nuniform sampler2D texture;\n\nvec4 loop();\n\nvoid main() { gl_FragColor = loop(); }\n`,gf=`varying vec2 _texture_coord;\n\nattribute vec2 position;\nattribute vec2 texture_coord;\n\nvoid main() {\n gl_Position = vec4(position, 0., 1.);\n _texture_coord = texture_coord;\n}\n`,Nr=(r=>(r[r.LINEAR=0]="LINEAR",r[r.GAUSSIAN=1]="GAUSSIAN",r))(Nr||{});class Si extends je{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return pf+this.createLoopFunction()}getVertexShader(){return gf}createLoopFunction(){let e=this.options.radius??1;return`\n\n vec4 loop() { \n vec4 result = vec4(0,0,0,0);\n float factorSum = 0.;\n\n vec2 normalizedRadius = vec2(-${e}.) / canvas;\n vec2 normalizedIncrement = vec2(1.) / canvas;\n vec2 diff = normalizedRadius;\n\n for(int y=-${e}; y<${e+1}; ++y) {\n for(int x=-${e}; x<${e+1}; ++x) {\n float factor = 1.;\n result += factor * texture2D(texture, _texture_coord + diff);\n factorSum += factor;\n diff.x += normalizedIncrement.x;\n }\n diff.y += normalizedIncrement.y;\n diff.x = normalizedRadius.x;\n }\n return result / factorSum;\n }`}}var yf=`#version 300 es\n// https://github.com/Volcomix/virtual-background/blob/main/src/pipelines/webgl2/jointBilateralFilterStage.ts\n\nprecision highp float;\nuniform sampler2D input_frame;\nuniform sampler2D segmentation_mask;\nuniform sampler2D threshold;\nuniform vec2 texel_size;\nuniform float step;\nuniform float radius;\nuniform float offset;\nuniform float sigma_texel;\nuniform float sigma_color;\n\nin vec2 _texture_coord;\nout vec4 outColor;\n\nfloat gaussian(float x, float sigma) {\n float coeff = -0.5 / (sigma * sigma * 4.0 + 1.0e-6);\n return exp((x * x) * coeff);\n}\n\nvoid main() {\n vec2 centerCoord = _texture_coord;\n vec3 centerColor = texture(input_frame, centerCoord).rgb;\n float newVal = 0.0;\n float spaceWeight = 0.0;\n float colorWeight = 0.0;\n float totalWeight = 0.0;\n // Subsample kernel space.\n for (float i = -radius + offset; i <= radius; i += step) {\n for (float j = -radius + offset; j <= radius; j += step) {\n vec2 shift = vec2(j, i) * texel_size;\n vec2 coord = vec2(centerCoord + shift);\n vec3 frameColor = texture(input_frame, coord).rgb;\n float threshold = texture(threshold, coord).a;\n float outVal = texture(segmentation_mask, coord).a;\n\n spaceWeight = gaussian(distance(centerCoord, coord), sigma_texel);\n colorWeight = gaussian(distance(centerColor, frameColor), sigma_color);\n totalWeight += spaceWeight * colorWeight;\n newVal += spaceWeight * colorWeight * outVal * threshold;\n }\n }\n newVal /= totalWeight;\n outColor = vec4(vec3(0.), newVal);\n}`,bf=`#version 300 es\nin vec2 position;\nin vec2 texture_coord;\nout vec2 _texture_coord;\nvoid main() {\n gl_Position = vec4(position, 0.0, 1.0);\n _texture_coord = texture_coord;\n}`;class xf extends je{getFragmentShader(){return yf}getVertexShader(){return bf}}class _f extends Or{constructor(e,t,n){super(),this.context=e;const i={context:e,height:n,width:t},s=new Si({...i,radius:1,type:Nr.GAUSSIAN});this.jointBilateral=new xf(i),this.addStep({program:s,getUniforms:()=>({inputs:D(e,this.inputMask)})}),this.addStep({program:this.jointBilateral,getUniforms:()=>{const a=this.inputImage?.width??1,c=this.inputImage?.height??1;this.inputMask?.width,this.inputMask?.height;const u=3,d=Math.max(1,Math.sqrt(u)*.66),m=1/a,p=1/c;return{input_frame:D(e,this.inputImage),segmentation_mask:D(e,this.inputMask),texel_size:[m,p],step:d,radius:u,offset:d>1?d*.5:0,sigma_texel:Math.max(m,p)*u,sigma_color:u}}}),this.output=this.jointBilateral.output}setData(e,t){this.previousInputImage=this.inputImage?this.inputImage:e,this.previousInputMask=this.inputMask?this.inputMask:t,this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t),this.output=this.jointBilateral.output}}class Ef{constructor(e){this.queries=[],this.context=e,this.extension=e.getExtension("EXT_disjoint_timer_query_webgl2")}start(){}stop(){this.activeQuery&&this.context.endQuery(this.extension.TIME_ELAPSED_EXT)}pushContext(e){this.createQuery("PUSH",e)}popContext(e){this.createQuery("POP",e)}createQuery(e,t){this.activeQuery&&this.context.endQuery(this.extension.TIME_ELAPSED_EXT),this.activeQuery=this.context.createQuery(),this.context.beginQuery(this.extension.TIME_ELAPSED_EXT,this.activeQuery),this.queries.push({name:t,action:e,query:this.activeQuery})}async getResolvedQueries(){const e=(await Promise.all([...this.queries].map(t=>this.resolveQuery(t)))).filter(t=>t);for(let t=1;t<e.length;++t)e[t].timestamp+=e[t-1].duration+e[t-1].timestamp;return e}async resolveQuery(e){if(!await this.awaitQueryAvailable(e)){console.log("Unawaitable query",e);return}if(this.context.getParameter(this.extension.GPU_DISJOINT_EXT)){console.log("Disjointed query",e);return}return{...e,duration:this.context.getQueryParameter(e.query,this.context.QUERY_RESULT),timestamp:0}}async awaitQueryAvailable(e){for(let t=0;t<10;++t){if(this.context.getQueryParameter(e.query,this.context.QUERY_RESULT_AVAILABLE))return e;await Ii(200)}}}class Nt{constructor(){this.previousImageWidth=0,this.previousImageHeight=0,this.previousMaskWidth=Ce,this.previousMaskHeight=Ce,this.postProcessingEnabled=!0;const e=new OffscreenCanvas(0,0),t=e.getContext("webgl2");if(!t)throw"Fail to retrieve webgl2 context";this.canvas=e,this.context=t,this.improveMask=new _f(this.context,Ce,Ce)}enablePostProcessing(){this.postProcessingEnabled=!0}disablePostProcessing(){this.postProcessingEnabled=!1}async profileWebgl(e){const t=new Ef(this.context);return this.profiler=t,t.start(),await Ii(e),this.profiler=void 0,t.stop(),t.getResolvedQueries()}async render(e,t){if(!this.pipeline)throw"missing pipeline";(this.previousImageHeight!==e.height||this.previousImageWidth!==e.width)&&this.resizeOutput(e.width,e.height),(this.previousMaskHeight!==t.height||this.previousMaskWidth!==t.width)&&(this.improveMask.resizeOutput(t.width,t.height),this.previousMaskWidth=t.width,this.previousMaskHeight=t.height);const n="renderer";this.profiler?.pushContext(n),this.improveMask.setProfiler(this.profiler),this.pipeline.setProfiler(this.profiler);const i=await createImageBitmap(t);let s=i;return this.postProcessingEnabled&&(this.improveMask.setData(e,i),this.improveMask.run(),s=this.improveMask.output),this.pipeline.setData(e,s),await this.pipeline.run(),this.profiler?.popContext(n),this.canvas}resizeOutput(e,t){this.canvas.width=e,this.canvas.height=t,this.pipeline?.resizeOutput(e,t),this.previousImageWidth=e,this.previousImageHeight=t}destroy(){const e=this.context?.getExtension("WEBGL_lose_context");e&&e.loseContext()}}class Ri extends Nt{constructor(){super(),this.pipeline=new Ai(this.context);const e=new OffscreenCanvas(0,0),t=e.getContext("webgl2");if(!t)throw"Fail to retrieve webgl context";this.backgroundImageResizerCanvas=e,this.backgroundImageResizerContext=t,this.backgroundImageResizer=new mf(this.backgroundImageResizerContext,0,0)}setBackgroundImage(e){this.backgroundImage=e,this.updateBackgroundImage()}updateBackgroundImage(){const{width:e,height:t}=this.canvas;this.backgroundImageResizer.resizeOutput(e,t),this.backgroundImageResizer.setData(this.backgroundImage),this.backgroundImageResizer.run(),this.pipeline.inputBackgroundImage=this.backgroundImageResizerCanvas}resizeOutput(e,t){super.resizeOutput(e,t),this.backgroundImageResizerCanvas.width=e,this.backgroundImageResizerCanvas.height=t,this.backgroundImageResizer.resizeOutput(e,t),this.updateBackgroundImage()}destroy(){const e=this.backgroundImageResizerContext?.getExtension("WEBGL_lose_context");e&&e.loseContext(),super.destroy()}}class wf extends Ri{setBackgroundVideo(e){this.frameReader=e}async render(e,t){return await this.readNextVideoFrame(),super.render(e,t)}async readNextVideoFrame(){const e=await this.frameReader?.read();if(e?.value){const t=await createImageBitmap(e.value);this.setBackgroundImage(t),e.value.close()}}}class Fi{blurBackground(e){return new to(e)}blurSilhouette(e){return new ro(e)}imageBackground(){return new no}videoBackground(){return new wf}}var vf=`precision mediump float;\n\nvarying vec2 _texture_coord;\n\nuniform vec2 canvas;\nuniform sampler2D texture;\nuniform sampler2D mask;\n\nvec4 loop();\n\nvoid main() { gl_FragColor = loop(); }\n`,Tf=`varying vec2 _texture_coord;\n\nattribute vec2 position;\nattribute vec2 texture_coord;\n\nvoid main() {\n gl_Position = vec4(position, 0., 1.);\n _texture_coord = texture_coord;\n}\n`;class Af extends je{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return vf+this.createLoopFunction()}getVertexShader(){return Tf}createLoopFunction(){let e=this.options.radius??1;return`\n\n vec4 loop() { \n vec4 result = vec4(0,0,0,0);\n float factorSum = 0.;\n\n vec2 normalizedRadius = vec2(-${e}.) / canvas;\n vec2 normalizedIncrement = vec2(1.) / canvas;\n vec2 diff = normalizedRadius;\n float maxLength = length(normalizedRadius);\n\n for(int y=-${e}; y<${e+1}; ++y) {\n for(int x=-${e}; x<${e+1}; ++x) {\n float factor = (1.- texture2D(mask, _texture_coord + diff).a) * (maxLength - length(diff)) / maxLength;\n result += factor * texture2D(texture, _texture_coord + diff);\n factorSum += factor;\n diff.x += normalizedIncrement.x;\n }\n diff.y += normalizedIncrement.y;\n diff.x = normalizedRadius.x;\n }\n return result / factorSum;\n }`}}const If=10,Sf=2,Rf=8;class Ff extends Ur{constructor(e,t){super(),this.context=e,this.radius=t;const n={context:e,height:e.canvas.height,width:e.canvas.width};this.blur=new Af({...n,radius:t,...this.getBlurTextureSize(e.canvas.width,e.canvas.height)});const i=new Mr({...n,disableFramebuffer:!0});this.addStep({program:this.blur,preventResize:!0,getUniforms:()=>({texture:D(e,this.inputImage),mask:D(e,this.inputMask)})}),this.addStep({program:i,getUniforms:()=>({background:D(e,this.blur.output),foreground:D(e,this.inputImage),threshold:D(e,this.inputMask)})})}getBlurTextureSize(e,t){const n=this.radius>If?Rf:Sf;return{width:Math.max(Ce,e/n),height:Math.max(Ce,t/n)}}setData(e,t){this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t);const n=this.getBlurTextureSize(e,t);this.blur.resizeOutput(n.width,n.height)}}class Pf extends Nt{constructor(e){super(),this.pipeline=new Ff(this.context,e),this.disablePostProcessing()}}class kf extends Ur{constructor(e,t){super(),this.context=e;const n={context:e,height:e.canvas.height,width:e.canvas.width},i=new Si({...n,radius:t,type:Nr.GAUSSIAN}),s=new Mr({...n,disableFramebuffer:!0});this.addStep({program:i,getUniforms:()=>({texture:D(e,this.inputImage)})}),this.addStep({program:s,getUniforms:()=>({background:D(e,this.inputImage),foreground:D(e,i.output),threshold:D(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}class Cf extends Nt{constructor(e){super(),this.pipeline=new kf(this.context,e),this.disablePostProcessing()}}class Bf extends Ai{constructor(){super(...arguments),this.preciseMaskEnabled=!0}set reader(e){this.frameReader=e}async run(){this.frameReader&&(await this.readNextVideoFrame(),await super.run())}async readNextVideoFrame(){const e=await this.frameReader?.read();e?.value&&(this.inputBackgroundImage=await createImageBitmap(e.value),e.value.close())}}class Df extends Nt{constructor(){super(),this.pipeline=new Bf(this.context)}setBackgroundVideo(e){this.pipeline.reader=e}}class Pi{blurBackground(e){return new Pf(e)}blurSilhouette(e){return new Cf(e)}imageBackground(){return new Ri}videoBackground(){return new Df}}class Mf{constructor(e){switch(e){case gt.CANVAS:this.factory=new Fi;break;case gt.WEBGL:this.factory=new Pi;break;default:const t=eo();this.factory=t.supported?new Pi:new Fi}}blurBackground(e){return this.getFactory().blurBackground(e)}blurSilhouette(e){return this.getFactory().blurSilhouette(e)}imageBackground(){return this.getFactory().imageBackground()}videoBackground(){return this.getFactory().videoBackground()}getFactory(){if(!this.factory)throw"Factory is not initialized";return this.factory}}class Of{setBackgroundOptions(e){this.renderer&&this.renderer.destroy();const t=new Mf(e.renderingOptions?.type);switch(e.transformerType){case"BackgroundBlur":this.renderer=t.blurBackground(this.getBlurSize(e.radius));break;case"SilhouetteBlur":this.renderer=t.blurSilhouette(this.getBlurSize(e.radius));break;case"VideoBackground":const n=t.videoBackground();this.backgroundVideo&&n.setBackgroundVideo(this.backgroundVideo),this.renderer=n;break;case"VirtualBackground":const i=t.imageBackground();this.backgroundImage&&i.setBackgroundImage(this.backgroundImage),this.renderer=i;break;default:throw`Unknown rendering type [${e.transformerType}]`}e.renderingOptions?.type===gt.WEBGL&&(e.renderingOptions.selfieSegmentationType===tr.PRECISE?this.renderer.enablePostProcessing():e.renderingOptions.selfieSegmentationType===tr.FAST&&this.renderer.disablePostProcessing())}setVideoBGReadable(e){this.backgroundVideo=e.getReader();const t=this.renderer;t?.setBackgroundVideo&&t.setBackgroundVideo(this.backgroundVideo)}async setVirtualBGImage(e){const t=this.renderer;t?.setBackgroundImage&&t.setBackgroundImage(e),this.backgroundImage=e}async process(e,t){if(this.renderer)return this.renderer.render(e,t)}async resizeForeground(e,t){}getBlurSize(e=pt.Low){switch(e){case pt.Low:return 5;case pt.High:return 12}return e}async profile(e){return this.renderer?.profileWebgl(e)??[]}}var Uf=(function(){var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return(function(e){e=e||{};var t=typeof e<"u"?e:{},n,i;t.ready=new Promise(function(f,h){n=f,i=h});var s={},o;for(o in t)t.hasOwnProperty(o)&&(s[o]=t[o]);var a="./this.program",c=function(f,h){throw h},u=!0,d="";function m(f){return t.locateFile?t.locateFile(f,d):d+f}var p;typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),r&&(d=r),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="";var y=t.print||console.log.bind(console),l=t.printErr||console.warn.bind(console);for(o in s)s.hasOwnProperty(o)&&(t[o]=s[o]);s=null,t.arguments&&t.arguments,t.thisProgram&&(a=t.thisProgram),t.quit&&(c=t.quit);var b;t.wasmBinary&&(b=t.wasmBinary),t.noExitRuntime,typeof WebAssembly!="object"&&ae("no native wasm support detected");var _,E=!1,R=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function k(f,h,g){for(var w=h+g,S=h;f[S]&&!(S>=w);)++S;if(S-h>16&&f.subarray&&R)return R.decode(f.subarray(h,S));for(var C="";h<S;){var v=f[h++];if(!(v&128)){C+=String.fromCharCode(v);continue}var M=f[h++]&63;if((v&224)==192){C+=String.fromCharCode((v&31)<<6|M);continue}var H=f[h++]&63;if((v&240)==224?v=(v&15)<<12|M<<6|H:v=(v&7)<<18|M<<12|H<<6|f[h++]&63,v<65536)C+=String.fromCharCode(v);else{var Li=v-65536;C+=String.fromCharCode(55296|Li>>10,56320|Li&1023)}}return C}function N(f,h){return f?k(Xe,f,h):""}function Q(f,h,g){for(var w=0;w<f.length;++w)Lt[h++>>0]=f.charCodeAt(w);Lt[h>>0]=0}function q(f,h){return f%h>0&&(f+=h-f%h),f}var L,Lt,Xe,$;function Ci(f){L=f,t.HEAP8=Lt=new Int8Array(f),t.HEAP16=new Int16Array(f),t.HEAP32=$=new Int32Array(f),t.HEAPU8=Xe=new Uint8Array(f),t.HEAPU16=new Uint16Array(f),t.HEAPU32=new Uint32Array(f),t.HEAPF32=new Float32Array(f),t.HEAPF64=new Float64Array(f)}t.INITIAL_MEMORY;var zr,Bi=[],Di=[],Mi=[];function Yf(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)Kf(t.preRun.shift());Gr(Bi)}function Qf(){Gr(Di)}function qf(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)Zf(t.postRun.shift());Gr(Mi)}function Kf(f){Bi.unshift(f)}function Jf(f){Di.unshift(f)}function Zf(f){Mi.unshift(f)}var be=0,Ye=null;function el(f){be++,t.monitorRunDependencies&&t.monitorRunDependencies(be)}function tl(f){if(be--,t.monitorRunDependencies&&t.monitorRunDependencies(be),be==0&&Ye){var h=Ye;Ye=null,h()}}t.preloadedImages={},t.preloadedAudios={};function ae(f){t.onAbort&&t.onAbort(f),f="Aborted("+f+")",l(f),E=!0,f+=". Build with -s ASSERTIONS=1 for more info.";var h=new WebAssembly.RuntimeError(f);throw i(h),h}var rl="data:application/octet-stream;base64,";function Oi(f){return f.startsWith(rl)}var W;W="tflite-simd.wasm",Oi(W)||(W=m(W));function Ui(f){try{if(f==W&&b)return new Uint8Array(b);if(!p)throw"both async and sync fetching of the wasm failed"}catch(h){ae(h)}}function nl(){return!b&&u&&typeof fetch=="function"?fetch(W,{credentials:"same-origin"}).then(function(f){if(!f.ok)throw"failed to load wasm binary file at \'"+W+"\'";return f.arrayBuffer()}).catch(function(){return Ui(W)}):Promise.resolve().then(function(){return Ui(W)})}function il(){var f={a:Al};function h(v,M){var H=v.exports;t.asm=H,_=t.asm.q,Ci(_.buffer),zr=t.asm.E,Jf(t.asm.r),tl()}el();function g(v){h(v.instance)}function w(v){return nl().then(function(M){return WebAssembly.instantiate(M,f)}).then(function(M){return M}).then(v,function(M){l("failed to asynchronously prepare wasm: "+M),ae(M)})}function S(){return!b&&typeof WebAssembly.instantiateStreaming=="function"&&!Oi(W)&&typeof fetch=="function"?fetch(W,{credentials:"same-origin"}).then(function(v){var M=WebAssembly.instantiateStreaming(v,f);return M.then(g,function(H){return l("wasm streaming compile failed: "+H),l("falling back to ArrayBuffer instantiation"),w(g)})}):w(g)}if(t.instantiateWasm)try{var C=t.instantiateWasm(f,h);return C}catch(v){return l("Module.instantiateWasm callback failed with error: "+v),!1}return S().catch(i),{}}function Gr(f){for(;f.length>0;){var h=f.shift();if(typeof h=="function"){h(t);continue}var g=h.func;typeof g=="number"?h.arg===void 0?zr.get(g)():zr.get(g)(h.arg):g(h.arg===void 0?null:h.arg)}}function sl(f,h,g,w){ae("Assertion failed: "+N(f)+", at: "+[h?N(h):"unknown filename",g,w?N(w):"unknown function"])}function ol(f,h){ae("To use dlopen, you need to use Emscripten\'s linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")}function al(f,h){ae("To use dlopen, you need to use Emscripten\'s linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")}function cl(){ae("")}var zt;zt=function(){return performance.now()};var ul=!0;function fl(f){return $[Ni()>>2]=f,f}function ll(f,h){var g;if(f===0)g=Date.now();else if((f===1||f===4)&&ul)g=zt();else return fl(28),-1;return $[h>>2]=g/1e3|0,$[h+4>>2]=g%1e3*1e3*1e3|0,0}function dl(){return 2147483648}function hl(f,h,g){Xe.copyWithin(f,h,h+g)}function ml(f){try{return _.grow(f-L.byteLength+65535>>>16),Ci(_.buffer),1}catch{}}function pl(f){var h=Xe.length;f=f>>>0;var g=2147483648;if(f>g)return!1;for(var w=1;w<=4;w*=2){var S=h*(1+.2/w);S=Math.min(S,f+100663296);var C=Math.min(g,q(Math.max(f,S),65536)),v=ml(C);if(v)return!0}return!1}function gl(f){for(var h=zt();zt()-h<f;);}var $r={};function yl(){return a||"./this.program"}function Qe(){if(!Qe.strings){var f=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",h={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:f,_:yl()};for(var g in $r)$r[g]===void 0?delete h[g]:h[g]=$r[g];var w=[];for(var g in h)w.push(g+"="+h[g]);Qe.strings=w}return Qe.strings}var Gt={mappings:{},buffers:[null,[],[]],printChar:function(f,h){var g=Gt.buffers[f];h===0||h===10?((f===1?y:l)(k(g,0)),g.length=0):g.push(h)},varargs:void 0,get:function(){Gt.varargs+=4;var f=$[Gt.varargs-4>>2];return f},getStr:function(f){var h=N(f);return h},get64:function(f,h){return f}};function bl(f,h){var g=0;return Qe().forEach(function(w,S){var C=h+g;$[f+S*4>>2]=C,Q(w,C),g+=w.length+1}),0}function xl(f,h){var g=Qe();$[f>>2]=g.length;var w=0;return g.forEach(function(S){w+=S.length+1}),$[h>>2]=w,0}function _l(f){Sl(f)}function El(f){return 0}function wl(f,h,g,w,S){}function vl(f,h,g,w){for(var S=0,C=0;C<g;C++){for(var v=$[h+C*8>>2],M=$[h+(C*8+4)>>2],H=0;H<M;H++)Gt.printChar(f,Xe[v+H]);S+=M}return $[w>>2]=S,0}function Tl(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var f=new Uint8Array(1);return function(){return crypto.getRandomValues(f),f[0]}}else return function(){ae("randomDevice")}}function $t(f,h){$t.randomDevice||($t.randomDevice=Tl());for(var g=0;g<h;g++)Lt[f+g>>0]=$t.randomDevice();return 0}var Al={a:sl,e:ol,d:al,b:cl,n:ll,h:dl,l:hl,m:pl,p:gl,f:bl,g:xl,j:_l,i:El,k:wl,c:vl,o:$t};il(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.r).apply(null,arguments)},t._getModelBufferMemoryOffset=function(){return(t._getModelBufferMemoryOffset=t.asm.s).apply(null,arguments)},t._getInputMemoryOffset=function(){return(t._getInputMemoryOffset=t.asm.t).apply(null,arguments)},t._getInputHeight=function(){return(t._getInputHeight=t.asm.u).apply(null,arguments)},t._getInputWidth=function(){return(t._getInputWidth=t.asm.v).apply(null,arguments)},t._getInputChannelCount=function(){return(t._getInputChannelCount=t.asm.w).apply(null,arguments)},t._getOutputMemoryOffset=function(){return(t._getOutputMemoryOffset=t.asm.x).apply(null,arguments)},t._getOutputHeight=function(){return(t._getOutputHeight=t.asm.y).apply(null,arguments)},t._getOutputWidth=function(){return(t._getOutputWidth=t.asm.z).apply(null,arguments)},t._getOutputChannelCount=function(){return(t._getOutputChannelCount=t.asm.A).apply(null,arguments)},t._loadModel=function(){return(t._loadModel=t.asm.B).apply(null,arguments)},t._runInference=function(){return(t._runInference=t.asm.C).apply(null,arguments)},t._isGPUEnabled=function(){return(t._isGPUEnabled=t.asm.D).apply(null,arguments)};var Ni=t.___errno_location=function(){return(Ni=t.___errno_location=t.asm.F).apply(null,arguments)},Wt;function Il(f){this.name="ExitStatus",this.message="Program terminated with exit("+f+")",this.status=f}Ye=function f(){Wt||Wr(),Wt||(Ye=f)};function Wr(f){if(be>0||(Yf(),be>0))return;function h(){Wt||(Wt=!0,t.calledRun=!0,!E&&(Qf(),n(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),qf()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),h()},1)):h()}t.run=Wr;function Sl(f,h){Rl(f)}function Rl(f){c(f,new Il(f))}if(t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();return Wr(),e.ready})})();class Nf{constructor(){this.isSIMDSupported=!1,this.isThreadsSupported=!1,this.inputWidth=0,this.inputHeight=0,this.inputChannelCount=0,this.inputMemoryOffset=0,this.outputWidth=0,this.outputHeight=0,this.outputChannelCount=0,this.outputMemoryOffset=0}}const Lf="https://d3opqjmqzxf057.cloudfront.net/vonage-tensorflow-wasm/tflite-simd-wasm/1.1.3/",zf="https://d3opqjmqzxf057.cloudfront.net/ml/selfie_segmentation/4.0.0/selfie_segmentation_landscape.tflite";async function Gf(r=Lf,e=zf){let t=new Nf;var n=new Promise(function(i,s){async function o(){return Uf({locateFile:function(u){return r+u}})}async function a(c){return new Promise(async(u,d)=>{const m=c;if(typeof m>"u")return d("TFLite backend unavailable: wasmSimd");let p=e;console.log("TFLite modelUrl: "+p);try{const l=await(await fetch(p)).arrayBuffer();console.log("Model buffer size:",l.byteLength);const b=m._getModelBufferMemoryOffset();console.log("Model buffer memory offset:",b),console.log("Loading model buffer..."),m.HEAPU8.set(new Uint8Array(l),b);const _=m._loadModel(l.byteLength);if(console.log("Load model result:",_),_!==0){d("Cannot load model");return}t.inputWidth=m._getInputWidth(),t.inputHeight=m._getInputHeight(),t.inputChannelCount=m._getInputChannelCount(),t.inputMemoryOffset=m._getInputMemoryOffset(),console.log("Input memory offset:",t.inputMemoryOffset),console.log("Input height:",t.inputHeight),console.log("Input width:",t.inputWidth),console.log("Input channels:",t.inputChannelCount),t.outputMemoryOffset=m._getOutputMemoryOffset(),t.outputWidth=m._getOutputWidth(),t.outputHeight=m._getOutputHeight(),t.outputChannelCount=m._getOutputChannelCount(),console.log("Output memory offset:",t.outputMemoryOffset),console.log("Output height:",t.outputHeight),console.log("Output width:",t.outputWidth),console.log("Output channels:",t.outputChannelCount),t.selectedTFLite=m}catch(y){d(y);return}u()})}o().then(c=>{if(c===null)throw console.error("loadTFLite null"),"loadTFLite null";a(c).then(u=>{i(t)}).catch(u=>{console.error("loadTFLiteModel error"),s("loadTFLiteModel error")})}).catch(c=>{console.error("loadTFLite error:",c),s("loadTFLite error:"+c)})});return n}const $f=.1,Wf=.7,Vf="https://d3opqjmqzxf057.cloudfront.net/ml/vonage_selfie_segmenter/float16/v1/vonage_selfie_segmenter.tflite";class Hf{constructor(){this.canvas=new OffscreenCanvas(0,0),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.width=0,this.height=0,this.gpuDelegate=!0}async createImageSegmenter(){if(!this.ImageSegmenter||!this.wasmFileset){console.warn("Mediapipe objects not loaded");return}this.imageSegmenter=await this.ImageSegmenter.createFromOptions(this.wasmFileset,{baseOptions:{modelAssetPath:this.modelAssetUriPath,delegate:this.gpuDelegate?"GPU":"CPU"},runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!0})}async loadMediapipeAssets(e,t){this.modelAssetUriPath=e||Vf;const n=t?`${t}/task-vision.js`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/+esm",i=t?`${t}/wasm`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/wasm",{FilesetResolver:s,ImageSegmenter:o}=await import(n);this.ImageSegmenter=o,this.wasmFileset=await s.forVisionTasks(i)}async init(e,t,n){n===!1&&(this.gpuDelegate=!1),await this.loadMediapipeAssets(e,t),globalThis.document={},await this.createImageSegmenter()}async process(e){if(!this.imageSegmenter){console.warn("ImageSegmenter instance not available");return}(this.width!==e.width||this.height!==e.height)&&(this.canvas.width=this.width=e.width,this.canvas.height=this.height=e.height,this.mask&&(this.mask=new ImageData(this.width,this.height))),this.mask||(this.mask=new ImageData(this.width,this.height)),this.context.drawImage(e,0,0,e.width,e.height);const t=Date.now();let n;try{this.imageSegmenter?.segmentForVideo(this.context.getImageData(0,0,e.width,e.height),t,o=>{n=o.confidenceMasks?.[0]?.getAsFloat32Array()})}catch{await this.createImageSegmenter();return}if(!n)return;if(!this.previousConfidenceMask){this.previousConfidenceMask=n.slice();return}const i=n.map((o,a)=>{const c=this.previousConfidenceMask?.[a];return c!==void 0?this.blend(c,o):o}),s=[255,0,0];for(let o=0;o<i?.length;o++){const a=1-i[o];a>$f?(a<Wf?(this.mask.data[o*4]=s[0]*a,this.mask.data[o*4+3]=255*a):(this.mask.data[o*4]=s[0],this.mask.data[o*4+3]=255),this.mask.data[o*4+1]=s[1],this.mask.data[o*4+2]=s[2]):this.mask.data[o*4]=this.mask.data[o*4+1]=this.mask.data[o*4+2]=this.mask.data[o*4+3]=0}return this.previousConfidenceMask=i.slice(),this.mask}isGpuSupported(){return!0}blend(e,t){const i=-.748699,s=-57.8051,o=291.309,a=-624.717,c=t-.5,u=c*c,d=1-Math.min(1,u*(5.68842+u*(i+u*(s+u*(o+u*a)))));return t+(e-t)*(d*.9)}}class jf{constructor(){this.canvas=new OffscreenCanvas(0,0),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.pixelCount=0,this.inputOffset=0,this.outputOffset=0}async init(e,t,n){await this.initWasm(t,e),this.infos&&(this.canvas.width=this.infos.inputWidth,this.canvas.height=this.infos.inputHeight,this.pixelCount=this.infos.inputWidth*this.infos.inputHeight,this.mask=new ImageData(this.infos.inputWidth,this.infos.inputHeight),this.inputOffset=this.infos.inputMemoryOffset/4,this.outputOffset=this.infos.outputMemoryOffset/4)}async initWasm(e,t){this.infos=await Gf(e,t)}async process(e){if(!this.mask||!this.infos)return;const t=this.infos.inputWidth,n=this.infos.inputHeight;this.context.drawImage(e,0,0,e.width,e.height,0,0,t,n);const i=this.context.getImageData(0,0,t,n),s=this.infos.selectedTFLite.HEAPF32;for(let o=0;o<this.pixelCount;o++){const a=this.inputOffset+o*3;s[a]=i.data[o*4]/255,s[a+1]=i.data[o*4+1]/255,s[a+2]=i.data[o*4+2]/255}this.infos.selectedTFLite._runInference();for(let o=0;o<this.pixelCount;o++){const a=this.infos.selectedTFLite.HEAPF32[this.outputOffset+o];this.mask.data[o*4]=this.mask.data[o*4+3]=255*a}return this.mask}isGpuSupported(){return this.infos?.selectedTFLite?._isGPUEnabled()??!1}}class Xf{constructor(){this.reporter=new Js,this.isEnabled=!0}async init(e,t){t.segmentationOptions?.lightWeightEngine===!0?this.selfieSegmentation=new jf:this.selfieSegmentation=new Hf,this.selfieSegmentation?.init(t.modelAssetUriPath,t.mediapipeBaseAssetsUri,t.segmentationOptions?.gpuSupport),this.backgroundFilter=new Of,this.report({variation:"Create"})}async transform(e,t){if(!this.isEnabled)return t.enqueue(e);let n;const i=e.timestamp??0,s=await createImageBitmap(e),o=await this.selfieSegmentation?.process(s);o&&(n=await this.backgroundFilter?.process(s,o)),n?(e.close(),t.enqueue(new VideoFrame(n,{timestamp:i,alpha:"discard"}))):t.enqueue(e)}async setBackgroundOptions(e){this.backgroundOptions=e,this.backgroundFilter?.setBackgroundOptions(e),this.report({variation:"Update"})}setVideoBGReadable(e){this.backgroundFilter?.setVideoBGReadable(e)}async setVirtualBGImage(e){await this.backgroundFilter?.setVirtualBGImage(e)}async profile(e){return this.backgroundFilter?.profile(e)??[]}getTransformerType(){return this.backgroundOptions?.transformerType??"Undefined"}enable(){this.isEnabled=!0}disable(){this.isEnabled=!1}report(e){this.reporter.send({version:Zs,action:"MlTransformers",transformerType:this.backgroundOptions?.transformerType,config:JSON.stringify(this.backgroundOptions),...e})}}const Lr=class Lr{constructor(){this.backgroundTransformer=new Xf,this.mediaProcessor=new Rs,this.rate=30,this.eventsQueue=[],this.frameTransformLatencyMs=[]}async init(e,t){this.frameTransformLatencyMs=[],await this.backgroundTransformer.init(e,t),await this.mediaProcessor.setTransformers([this.backgroundTransformer]),this.mediaProcessor.setTrackExpectedRate(this.rate),this.mediaProcessor.onAny((n,i)=>{this.resolveOnMediaProcessor?(this.resolveOnMediaProcessor({name:n,data:i}),this.resolveOnMediaProcessor=void 0):this.eventsQueue.push({name:n,data:i})})}enable(){this.backgroundTransformer.enable()}disable(){this.backgroundTransformer.disable()}async onMediaProcessorEvent(){return await new Promise(e=>{this.eventsQueue.length>0?e(this.eventsQueue.shift()):this.resolveOnMediaProcessor=e})}async setTrackExpectedRate(e){this.rate=e,this.mediaProcessor.setTrackExpectedRate(e)}async transform(e,t){let n=this.mediaProcessor.transform(e,t),i=performance.now();return this.frameTransformLatencyMs.push(performance.now()-i),n}async setBackgroundOptions(e){await this.backgroundTransformer?.setBackgroundOptions(e)}setVideoBGReadable(e){this.backgroundTransformer.setVideoBGReadable(e)}async setVirtualBGImage(e){await this.backgroundTransformer.setVirtualBGImage(e)}async terminate(){await this.mediaProcessor.destroy();const t=this.frameTransformLatencyMs.reduce((n,i)=>n+i,0)/this.frameTransformLatencyMs.length||0;console.log(`Transform latency average is: ${t} ms`)}setVonageMetadata(e){_s(e)}async profile(e){return JSON.stringify(await this.backgroundTransformer.profile(e))}};Vi("ProcessorWorker",Lr);let ki=Lr})();\n//# sourceMappingURL=processor-worker-BCzl4yxZ.js.map\n',vo=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",xo],{type:"text/javascript;charset=utf-8"});function Jf(r){let e;try{if(e=vo&&(self.URL||self.webkitURL).createObjectURL(vo),!e)throw"";const t=new Worker(e,{name:r?.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(xo),{name:r?.name})}}const ur=class ur extends Qe{constructor(e){super(),this.rate=30,this.isEnabled=!0,this.config=e}async setTrackExpectedRate(e){await this.startWorker(),await this.worker?.setTrackExpectedRate(e)}async setBackgroundOptions(e){this.backgroundOptions=e,await this.updateBackgroundOptions(e)}async transform(e,t){return await this.startWorker(),await this.worker?.transform(e,t)}async destroy(){await this.worker?.terminate(),this.worker=void 0}async profile(e){const t=await this.worker?.profile(e);return JSON.parse(t??"[]")}async enable(){this.isEnabled=!0,await this.worker?.enable()}async disable(){this.isEnabled=!1,await this.worker?.disable()}async listenWorker(){for(;this.worker?.workerContext.worker;){const{name:e,data:t}=await this.worker?.onMediaProcessorEvent();switch(e){case"error":case"warn":this.emit(e,t);break;case"pipelineInfo":switch(this.emit(e,t),t){case"pipeline_ended":case"pipeline_ended_with_error":await this.destroy();return}break}}}async startWorker(){!this.config||this.worker||(this.worker=await ks(ln,Jf),this.isEnabled||await this.worker.disable(),await this.worker.init(`worker_${ur.initCount++}`,this.config),await this.worker.setVonageMetadata(wt()),this.backgroundOptions?await this.setBackgroundOptions(this.backgroundOptions):await this.setBackgroundOptions(this.config),this.listenWorker())}async updateBackgroundOptions(e){await this.startWorker();const{transformerType:t}=e;switch(t){case"VideoBackground":await this.worker?.setVideoBGReadable(await Hn.createVideoReadable(e.backgroundAssetUri));break;case"VirtualBackground":await this.worker?.setVirtualBGImage(await Hn.createImageCanvas(e.backgroundAssetUri));break}await this.worker?.setBackgroundOptions(e)}};ur.initCount=0;let fn=ur;class Zf{constructor(e){this.queries=e}async downloadSpeedscope(){this.download(await this.convertToSpeedscope())}download(e){const t=document.createElement("a");t.href=URL.createObjectURL(new Blob([e],{type:"application/json"})),t.download=`profile-${+new Date}.speedscope.json`,document.body.appendChild(t),t.click(),document.body.removeChild(t)}convertToSpeedscope(){const e=[],t={},n=[];let i=0;for(const s of this.queries){const a=[];for(const c of s)t[c.name]===void 0&&(t[c.name]=e.length,e.push({name:c.name})),a.push({type:c.action==po.PUSH?"O":"C",frame:t[c.name],at:c.timestamp}),i=Math.max(i,c.timestamp+c.duration);n.push({events:a,type:"evented",name:"GPU Profile",unit:"nanoseconds",startValue:0,endValue:i})}return JSON.stringify({$schema:"https://www.speedscope.app/file-format-schema.json",shared:{frames:e},profiles:n},null,2)}}const hn=class hn extends Qe{constructor(e){super(),this.worker=new fn(e),this.connector=new gs(this.worker),this.worker.onAny((t,n)=>this.emit(t,n))}async setBackgroundOptions(e){await this.worker.setBackgroundOptions(e)}async enable(){await this.worker.enable()}async disable(){await this.worker.disable()}setTrackExpectedRate(e){this.worker.setTrackExpectedRate(e)}getConnector(){return this.connector}async profile(e){return this.worker.profile(e)}static async profile(e){const t=await Promise.all(this.instances.map(n=>n.profile(e)));return new Zf(t)}static async create(e){const t=new this(e);return this.instances.push(t),t}};hn.instances=[];let cr=hn;async function ed(r){return await cr.create(r)}k.BackgroundTransformer=wo,k.BackgroundTransformerType=Cn,k.BlurRadius=He,k.ErrorFunction=Pn,k.PipelineInfoData=vt,k.RenderingType=je,k.VonageMediaProcessor=cr,k.WarningType=kn,k.WebglSelfieSegmentationType=_t,k.createVonageMediaProcessor=ed,k.getSupportedBrowserFeatures=On,k.isSupported=bs,Object.defineProperty(k,Symbol.toStringTag,{value:"Module"})}));
194
194
  //# sourceMappingURL=ml-transformers.umd.js.map