@vonage/ml-transformers 7.0.2-alpha.1 → 7.0.2-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- async function os(){return new Promise(async(e,t)=>{as()||!await ai()&&!si()?t("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."):e()})}function si(){return void 0!==self.MediaStreamTrackProcessor&&void 0!==self.MediaStreamTrackGenerator||ss()}function ss(){return 0===[self.ReadableStream,self.WritableStream,self.MediaStream,self.OffscreenCanvas,self.VideoFrame,self.AudioContext,self.AudioWorkletNode].filter(e=>void 0===e).length}function as(){const e=navigator.userAgent.toLowerCase();return!(!(navigator.vendor&&navigator.vendor.toLowerCase().indexOf("apple")>-1)||e.indexOf("applewebkit")>-1&&-1===e.indexOf("version"))&&parseInt((e.split(" ").find(e=>e.includes("version/"))??"/0").split("/")[1])<26}function ai(){return new Promise(e=>{new Worker(`data:text/javascript,(${function(){self.postMessage(typeof MediaStreamTrackProcessor<"u"&&typeof VideoTrackGenerator<"u")}.toString()})()`).onmessage=({data:t})=>e(t)})}const ee=new WeakMap,me=new WeakMap,q=new WeakMap,Rt=Symbol("anyProducer"),Tn=Promise.resolve(),kt=Symbol("listenerAdded"),Pt=Symbol("listenerRemoved");let Ft=!1,mr=!1;const Ct=e=>"string"==typeof e||"symbol"==typeof e||"number"==typeof e;function Te(e){if(!Ct(e))throw new TypeError("`eventName` must be a string, symbol, or number")}function ft(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function Se(e,t){const r=me.get(e);if(r.has(t))return r.get(t)}function je(e,t){const r=Ct(t)?t:Rt,n=q.get(e);if(n.has(r))return n.get(r)}function cs(e,t,r){const n=q.get(e);if(n.has(t))for(const e of n.get(t))e.enqueue(r);if(n.has(Rt)){const e=Promise.all([t,r]);for(const t of n.get(Rt))t.enqueue(e)}}function Sn(e,t){t=Array.isArray(t)?t:[t];let r=!1,n=()=>{},i=[];const o={enqueue(e){i.push(e),n()},finish(){r=!0,n()}};for(const r of t){let t=je(e,r);t||(t=new Set,q.get(e).set(r,t)),t.add(o)}return{async next(){return i?0===i.length?r?(i=void 0,this.next()):(await new Promise(e=>{n=e}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(r){i=void 0;for(const r of t){const t=je(e,r);t&&(t.delete(o),0===t.size&&q.get(e).delete(r))}return n(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function In(e){if(void 0===e)return Rn;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!Rn.includes(t))throw"string"!=typeof t?new TypeError("`methodNames` element must be a string"):new Error(`${t} is not Emittery method`);return e}const Be=e=>e===kt||e===Pt;function dt(e,t,r){if(Be(t))try{Ft=!0,e.emit(t,r)}finally{Ft=!1}}class J{static mixin(e,t){return t=In(t),r=>{if("function"!=typeof r)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==r.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(r.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new J}),this[e]}});const n=t=>function(...r){return this[e][t](...r)};for(const e of t)Object.defineProperty(r.prototype,e,{enumerable:!1,value:n(e)});return r}}static get isDebugEnabled(){if("object"!=typeof globalThis.process?.env)return mr;const{env:e}=globalThis.process??{env:{}};return"emittery"===e.DEBUG||"*"===e.DEBUG||mr}static set isDebugEnabled(e){mr=e}constructor(e={}){ee.set(this,new Set),me.set(this,new Map),q.set(this,new Map),q.get(this).set(Rt,new Set),this.debug=e.debug??{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,r,n)=>{try{n=JSON.stringify(n)}catch{n=`Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`}("symbol"==typeof r||"number"==typeof r)&&(r=r.toString());const i=new Date,o=`${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}.${i.getMilliseconds()}`;console.log(`[${o}][emittery:${e}][${t}] Event Name: ${r}\n\tdata: ${n}`)})}logIfDebugEnabled(e,t,r){(J.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,r)}on(e,t,{signal:r}={}){ft(t),e=Array.isArray(e)?e:[e];for(const r of e){Te(r);let e=Se(this,r);e||(e=new Set,me.get(this).set(r,e)),e.add(t),this.logIfDebugEnabled("subscribe",r,void 0),Be(r)||dt(this,kt,{eventName:r,listener:t})}const n=()=>{this.off(e,t),r?.removeEventListener("abort",n)};return r?.addEventListener("abort",n,{once:!0}),r?.aborted&&n(),n}off(e,t){ft(t),e=Array.isArray(e)?e:[e];for(const r of e){Te(r);const e=Se(this,r);e&&(e.delete(t),0===e.size&&me.get(this).delete(r)),this.logIfDebugEnabled("unsubscribe",r,void 0),Be(r)||dt(this,Pt,{eventName:r,listener:t})}}once(e,t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("predicate must be a function");let r;const n=new Promise(n=>{r=this.on(e,e=>{t&&!t(e)||(r(),n(e))})});return n.off=r,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Te(t);return Sn(this,e)}async emit(e,t){if(Te(e),Be(e)&&!Ft)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),cs(this,e,t);const r=Se(this,e)??new Set,n=ee.get(this),i=[...r],o=Be(e)?[]:[...n];await Tn,await Promise.all([...i.map(async e=>{if(r.has(e))return e(t)}),...o.map(async r=>{if(n.has(r))return r(e,t)})])}async emitSerial(e,t){if(Te(e),Be(e)&&!Ft)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const r=Se(this,e)??new Set,n=ee.get(this),i=[...r],o=[...n];await Tn;for(const e of i)r.has(e)&&await e(t);for(const r of o)n.has(r)&&await r(e,t)}onAny(e,{signal:t}={}){ft(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),ee.get(this).add(e),dt(this,kt,{listener:e});const r=()=>{this.offAny(e),t?.removeEventListener("abort",r)};return t?.addEventListener("abort",r,{once:!0}),t?.aborted&&r(),r}anyEvent(){return Sn(this)}offAny(e){ft(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),dt(this,Pt,{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),Ct(t)){const e=Se(this,t);e&&e.clear();const r=je(this,t);if(r){for(const e of r)e.finish();r.clear()}}else{ee.get(this).clear();for(const[e,t]of me.get(this).entries())t.clear(),me.get(this).delete(e);for(const[e,t]of q.get(this).entries()){for(const e of t)e.finish();t.clear(),q.get(this).delete(e)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const r of e)if(Ct(r))t+=ee.get(this).size+(Se(this,r)?.size??0)+(je(this,r)?.size??0)+(je(this)?.size??0);else{void 0!==r&&Te(r),t+=ee.get(this).size;for(const e of me.get(this).values())t+=e.size;for(const e of q.get(this).values())t+=e.size}return t}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=In(t);for(const r of t){if(void 0!==e[r])throw new Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}}const Rn=Object.getOwnPropertyNames(J.prototype).filter(e=>"constructor"!==e);Object.defineProperty(J,"listenerAdded",{value:kt,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(J,"listenerRemoved",{value:Pt,writable:!1,enumerable:!0,configurable:!1});var us=Object.defineProperty,ls=(e,t,r)=>t in e?us(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,fs=(e,t,r)=>(ls(e,t+"",r),r);const ds="hlg.tokbox.com/prod/logging/vcp_webrtc",hs="https://",ms=1e4;let ht;const ps=new Uint8Array(16);function gs(){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(ps)}const F=[];for(let e=0;e<256;++e)F.push((e+256).toString(16).slice(1));function ys(e,t=0){return(F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+"-"+F[e[t+4]]+F[e[t+5]]+"-"+F[e[t+6]]+F[e[t+7]]+"-"+F[e[t+8]]+F[e[t+9]]+"-"+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]).toLowerCase()}const bs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),kn={randomUUID:bs};function ws(e,t,r){if(kn.randomUUID&&!e)return kn.randomUUID();const n=(e=e||{}).random||(e.rng||gs)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,ys(n)}function Ur(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[e]||(r[e]=t),r[e]}const ie=Ur("globals",{});var be=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e))(be||{});function ci(e){return[ImageBitmap,ReadableStream,WritableStream].some(t=>e instanceof t)}let xs=0;function vs(e,t,r,n,i){const o=xs++;return e.postMessage({id:o,type:t,functionName:r,args:n},n.filter(e=>ci(e))),new Promise(e=>{i?.set(o,e)})}function Ze(e,t){const{id:r,type:n}=e,i=Array.isArray(t)?t:[t];postMessage({id:r,type:n,result:t},i.filter(e=>ci(e)))}const Pn=Ur("workerized",{});function ui(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function _s(){if(ui())Ze({type:be.GLOBALS_SYNC},ie);else{const e=[];for(const t in Pn){const{worker:r,resolvers:n}=Pn[t].workerContext;r&&e.push(vs(r,be.GLOBALS_SYNC,"",[ie],n))}await Promise.all(e)}}function Ot(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const r in e)Array.isArray(e[r])?(t[r]=[],Ot(e[r],t[r])):"object"==typeof e[r]?(t[r]={},Ot(e[r],t[r])):t[r]=e[r]}async function Es(e,t){const{functionName:r,args:n}=e;if(!t.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!t.instance[r])throw`undefined function [${r}] in class ${t.instance.constructor.workerId}`;Ze(e,await t.instance[r](...n??[]))}const As=Ur("registeredWorkers",{});function Ts(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,n]=e.args,i=As[r];if(!i)throw`unknown worker class ${r}`;t.instance=new i(e.args.slice(1)),Ot(n,ie),Ze(e,void 0!==typeof t.instance)}async function Ss(e,t){const{args:r}=e;if(!t.instance)throw"instance not initialized";let n;t.instance.terminate&&(n=await t.instance.terminate(...r??[])),Ze(e,n)}function Is(e){if(!e.args)throw"Missing globals while syncing";Ot(e.args[0],ie),Ze(e,{})}function Rs(){const e={};onmessage=async t=>{const r=t.data;switch(r.type){case be.INIT:Ts(r,e);break;case be.FORWARD:Es(r,e);break;case be.TERMINATE:Ss(r,e);break;case be.GLOBALS_SYNC:Is(r)}}}function ks(e,t){return ie[e]||(ie[e]=t),[()=>ie[e],async t=>{ie[e]=t,await _s()}]}function Ps(e,t){return ks(e,t)}ui()&&Rs();const[Fs,Cs]=Ps("metadata");function Os(e){Cs(e)}function Tt(){return Fs()}let Lr=class{constructor(e,t){fs(this,"uuid"),this.config=e,this.uuid=t??ws()}async send(e){var t,r,n;const{appId:i,sourceType:o}=null!=(t=Tt())?t:{};if(!i||!o)return"metadata missing";const s=new AbortController,a=setTimeout(()=>s.abort(),ms);return await(null!=(n=null==(r=this.config)?void 0:r.fetch)?n:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:s.signal}),clearTimeout(a),"success"}getUrl(){var e;let t=null!=(e=Tt().proxyUrl)?e:hs;return t+=("/"===t.at(-1)?"":"/")+ds,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=Tt();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}};const St="3.0.2",_r=class{};_r.updates={transformer_new:"New transformer",transformer_null:"Null transformer"},_r.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 we=_r;function Ms(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}function Bs(e){if(Ms(e))return e;try{return new Error(JSON.stringify(e))}catch{return new Error(String(e))}}function pr(e){return Bs(e).message}class Ds{constructor(e,t){this.config=e,this.frameTransformedCount=0,this.frameFromSourceCount=0,this.startAt=0,this.reporter=new Lr(e,t)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:t}=this;return t/((Date.now()-e)/1e3)}async onFrameTransformed(e={},t=!1){0===this.startAt&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:r,frameTransformedCount:n,frameFromSourceCount:i}=this,o=Date.now(),s=(o-r)/1e3,a=n/s,c=i/s;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:c,transformedFps:a,framesTransformed:n,...e})):"success"}}var Us=(e=>(e.FPS_DROP="fps_drop",e))(Us||{}),Ls=(e=>(e.start="start",e.transform="transform",e.flush="flush",e))(Ls||{}),Er=(e=>(e.pipeline_ended="pipeline_ended",e.pipeline_ended_with_error="pipeline_ended_with_error",e.pipeline_started="pipeline_started",e.pipeline_started_with_error="pipeline_started_with_error",e.pipeline_restarted="pipeline_restarted",e.pipeline_restarted_with_error="pipeline_restarted_with_error",e))(Er||{});const zs=500,Ns=.8;class $s extends J{constructor(e,t){super(),this.reporter_=new Lr,this.reporterQos_=new Ds({loggingIntervalFrameCount:zs,report:{version:St}}),this.index_=t,this.transformer_=e,this.shouldStop_=!1,this.isFlashed_=!1,this.mediaTransformerQosReportStartTimestamp_=0,this.videoHeight_=0,this.videoWidth_=0,this.trackExpectedRate_=-1,this.transformerType_="Custom","getTransformerType"in e&&(this.transformerType_=e.getTransformerType()),this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e}async start(e){if(this.controller_=e,this.transformer_&&"function"==typeof this.transformer_.start)try{await this.transformer_.start(e)}catch(e){this.report({message:we.errors.transformer_start,variation:"Error",error:pr(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"start"};this.emit("error",t)}}async transform(e,t){if(0===this.mediaTransformerQosReportStartTimestamp_&&(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(e){this.report({message:we.errors.transformer_transform,variation:"Error",error:pr(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"transform"};this.emit("error",t)}if(-1!=this.trackExpectedRate_&&this.trackExpectedRate_*Ns>this.reporterQos_.fps){const e={eventMetaData:{transformerIndex:this.index_},warningType:"fps_drop",dropInfo:{requested:this.trackExpectedRate_,current:this.reporterQos_.fps}};this.emit("warn",e)}}}async flush(e){if(this.transformer_&&"function"==typeof this.transformer_.flush&&!this.isFlashed_){this.isFlashed_=!0;try{await this.transformer_.flush(e)}catch(e){this.report({message:we.errors.transformer_flush,variation:"Error",error:pr(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"flush"};this.emit("error",t)}}this.reportQos(!0),this.report({variation:"Delete"})}stop(){console.log("[Pipeline] Stop stream."),this.controller_&&(this.flush(this.controller_),this.controller_.terminate()),this.shouldStop_=!0}report(e){this.reporter_.send({version:St,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:St,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class Ws extends J{constructor(e){super(),this.transformers_=[],this.trackExpectedRate_=-1;for(let t=0;t<e.length;t++){let r=new $s(e[t],t);r.on("error",e=>{this.emit("error",e)}),r.on("warn",e=>{this.emit("warn",e)}),this.transformers_.push(r)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let e of this.transformers_)e.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,t){if(this.transformers_&&0!==this.transformers_.length){try{let r=e;for(let t of this.transformers_)e=e.pipeThrough(new TransformStream(t));e.pipeTo(t).then(async()=>{console.log("[Pipeline] Setup."),await t.abort(),await r.cancel(),this.emit("pipelineInfo","pipeline_ended")}).catch(async n=>{e.cancel().then(()=>{console.log("[Pipeline] Shutting down streams after abort.")}).catch(e=>{console.error("[Pipeline] Error from stream transform:",e)}),await t.abort(n),await r.cancel(n),this.emit("pipelineInfo","pipeline_ended_with_error")})}catch{return this.emit("pipelineInfo","pipeline_started_with_error"),void this.destroy()}this.emit("pipelineInfo","pipeline_started"),console.log("[Pipeline] Pipeline started.")}else console.log("[Pipeline] No transformers.")}async destroy(){console.log("[Pipeline] Destroying Pipeline.");for(let e of this.transformers_)e.stop()}}class li extends J{constructor(){super(),this.reporter_=new Lr,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("video"===e.kind){const t=new MediaStreamTrackProcessor({track:e}),r=new VideoTrackGenerator;return this.readable_=t.readable,this.writable_=r.writable,await this.transformInternal(),r.track}throw Error("Cannot process audio tracks inside a web worker when passing a track to transform")}return this.readable_=e,this.writable_=t,this.transformInternal()}transformInternal(){return new Promise(async(e,t)=>{if(!this.transformers_||0===this.transformers_.length)return this.report({message:we.errors.transformer_none,variation:"Error"}),void t("[MediaProcessor] Need to set transformers.");if(!this.readable_)return this.report({variation:"Error",message:we.errors.readable_null}),void t("[MediaProcessor] Readable is null.");if(!this.writable_)return this.report({variation:"Error",message:we.errors.writable_null}),void t("[MediaProcessor] Writable is null.");let r=!1;this.pipeline_&&(r=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new Ws(this.transformers_),this.pipeline_.on("warn",e=>{this.emit("warn",e)}),this.pipeline_.on("error",e=>{this.emit("error",e)}),this.pipeline_.on("pipelineInfo",e=>{r&&("pipeline_started"===e?e=Er.pipeline_restarted:"pipeline_started_with_error"===e&&(e=Er.pipeline_restarted_with_error)),this.emit("pipelineInfo",e)}),-1!=this.trackExpectedRate_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_),this.pipeline_.start(this.readable_,this.writable_).then(()=>{e()}).catch(e=>{t(e)})})}setTransformers(e){return this.report({variation:"Update",message:we.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:St,action:"MediaProcessor",...e})}isTrack(e){return"kind"in e}}class Gs{constructor({kind:e}){if("video"==e){const e=document.createElement("canvas"),t=e.getContext("2d",{desynchronized:!0}),r=e.captureStream().getVideoTracks()[0];return r.writable=new WritableStream({write(r){e.width=r.displayWidth,e.height=r.displayHeight,t.drawImage(r,0,0,e.width,e.height),r.close()}}),r}if("audio"==e){const e=new AudioContext,t=e.createMediaStreamDestination(),[r]=t.stream.getAudioTracks();return r.writable=new WritableStream({async start(n){return this.arrays=[],await e.audioWorklet.addModule(`data:text/javascript,(${function(){registerProcessor("mstg-shim",class extends AudioWorkletProcessor{constructor(){super(),this.arrays=[],this.arrayOffset=0,this.port.onmessage=({data:e})=>this.arrays.push(e),this.emptyArray=new Float32Array(0)}process(e,[[t]]){for(let e=0;e<t.length;e++)(!this.array||this.arrayOffset>=this.array.length)&&(this.array=this.arrays.shift()||this.emptyArray,this.arrayOffset=0),t[e]=this.array[this.arrayOffset++]||0;return!0}})}.toString()})()`),this.node=new AudioWorkletNode(e,"mstg-shim"),this.node.connect(t),r},write(e){const t=new Float32Array(e.numberOfFrames*e.numberOfChannels);e.copyTo(t,{planeIndex:0}),this.node.port.postMessage(t,[t.buffer]),e.close()}}),r}}}function Vs(){return self.MediaStreamTrackGenerator?self.MediaStreamTrackGenerator:Gs}class Hs{constructor(e){const t=e.track??e;"video"==t.kind?this.readable=new ReadableStream({async start(e){t.addEventListener("ended",()=>{try{e.close()}catch{}},{once:!0}),this.video=document.createElement("video"),this.video.srcObject=new MediaStream([t]),await Promise.all([this.video.play(),new Promise(e=>this.video.onloadedmetadata=e)]),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(e){if("ended"==t.readyState){try{e.close()}catch{}return}const r=t.getSettings().frameRate||30;for(;performance.now()-this.t1<1e3/r;)if(await new Promise(e=>requestAnimationFrame(e)),"ended"==t.readyState){try{e.close()}catch{}return}this.canvas.width=this.video.videoWidth,this.canvas.height=this.video.videoHeight,this.t1=performance.now(),this.ctx.drawImage(this.video,0,0),e.enqueue(new VideoFrame(this.canvas,{timestamp:this.t1}))}}):"audio"==t.kind&&(this.readable=new ReadableStream({async start(e){t.addEventListener("ended",()=>{try{e.close()}catch{}},{once:!0}),this.ac=new AudioContext,this.arrays=[],await this.ac.audioWorklet.addModule(`data:text/javascript,(${function(){registerProcessor("mstp-shim",class extends AudioWorkletProcessor{process(e){return this.port.postMessage(e),!0}})}.toString()})()`),this.node=new AudioWorkletNode(this.ac,"mstp-shim"),this.ac.createMediaStreamSource(new MediaStream([t])).connect(this.node),this.node.port.addEventListener("message",({data:e})=>e[0][0]&&this.arrays.push(e))},async pull(e){if("ended"==t.readyState){try{e.close()}catch{}return}for(;!this.arrays.length;)if(await new Promise(e=>this.node.port.onmessage=e),"ended"==t.readyState){try{e.close()}catch{}return}const[r]=this.arrays.shift(),n=new Float32Array(r.reduce((e,t)=>e+t.length,0));r.reduce((e,t)=>(n.set(t,e),e+t.length),0),e.enqueue(new AudioData({format:"f32-planar",sampleRate:this.ac.sampleRate,numberOfFrames:r[0].length,numberOfChannels:r.length,timestamp:1e6*this.ac.currentTime|0,data:n,transfer:[n.buffer]}))}}))}}function js(){return self.MediaStreamTrackProcessor?self.MediaStreamTrackProcessor:Hs}class Ys{constructor(){this.processor_=null,this.generator_=null}init(e){return new Promise((t,r)=>{try{const t=js();this.processor_=new t(e)}catch(e){console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${e}`),r(e)}try{const t=Vs();"audio"===e.kind?this.generator_=new t({kind:"audio"}):"video"===e.kind?this.generator_=new t({kind:"video"}):r("kind not supported")}catch(e){console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${e}`),r(e)}t()})}getReadable(){return this.processor_.readable}getWriteable(){return this.generator_.writable}getProccesorTrack(){return this.generator_}}class Qs{constructor(e){this.mediaProcessor_=e}async setTrack(e){if(!(this.mediaProcessor_ instanceof li)&&await ai()){if("audio"===e.kind)throw Error("Cannot process audio tracks inside a web worker when passing a track to transform");return await this.mediaProcessor_.transform(e)}if(si()){const t=new Ys;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(e=>{t(e)}):t("no processor")})}}var It=(e=>(e.Low="Low",e.High="High",e))(It||{}),qs=(e=>(e.BackgroundBlur="BackgroundBlur",e.VirtualBackground="VirtualBackground",e.VideoBackground="VideoBackground",e.SilhouetteBlur="SilhouetteBlur",e))(qs||{}),Ar=(e=>(e.FAST="FAST",e.PRECISE="PRECISE",e))(Ar||{}),Mt=(e=>(e.CANVAS="CANVAS",e.WEBGL="WEBGL",e))(Mt||{});const Xs=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 Bd(){const{wasm:e,insertableStreams:t,simd:r,webgl:n}=await Ks();if(!e.supported)throw e.message;if(!t.supported)throw t.message;if(!r.supported)throw r.message;if(!n.supported)throw n.message}async function Ks(){const e={wasm:{supported:"object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate,message:"Your browser does not support WebAssembly features."},simd:{supported:await Xs(),message:"Your browser does not support simd features."},insertableStreams:{supported:!0},gpu:{message:"Your browser does not support gpu features.",supported:!0},webgl:Js(),performance:fi()};try{await os()}catch(t){e.insertableStreams.supported=!1,e.insertableStreams.message=t}return e}function Js(){if(!OffscreenCanvas)return{supported:!1,message:"Your browser does not support offscreen canvas"};const e=new OffscreenCanvas(0,0).getContext("webgl2");if(!e)return{supported:!1,message:"Your browser does not support webgl 2"};{const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}return{supported:!0}}function fi(){const e=new OffscreenCanvas(0,0).getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(!e)return{supported:!1,message:"Your hardware does not perform good enough to run the library efficiently"};{const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}return{supported:!0}}const te=new WeakMap,pe=new WeakMap,X=new WeakMap,Bt=Symbol("anyProducer"),Fn=Promise.resolve(),Dt=Symbol("listenerAdded"),Ut=Symbol("listenerRemoved");let Lt=!1,gr=!1;const zt=e=>"string"==typeof e||"symbol"==typeof e||"number"==typeof e;function Ie(e){if(!zt(e))throw new TypeError("`eventName` must be a string, symbol, or number")}function mt(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function Re(e,t){const r=pe.get(e);if(r.has(t))return r.get(t)}function Ye(e,t){const r=zt(t)?t:Bt,n=X.get(e);if(n.has(r))return n.get(r)}function Cn(e,t,r){const n=X.get(e);if(n.has(t))for(const e of n.get(t))e.enqueue(r);if(n.has(Bt)){const e=Promise.all([t,r]);for(const t of n.get(Bt))t.enqueue(e)}}function On(e,t){t=Array.isArray(t)?t:[t];let r=!1,n=()=>{},i=[];const o={enqueue(e){i.push(e),n()},finish(){r=!0,n()}};for(const r of t){let t=Ye(e,r);t||(t=new Set,X.get(e).set(r,t)),t.add(o)}return{async next(){return i?0===i.length?r?(i=void 0,this.next()):(await new Promise(e=>{n=e}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(r){i=void 0;for(const r of t){const t=Ye(e,r);t&&(t.delete(o),0===t.size&&X.get(e).delete(r))}return n(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Mn(e){if(void 0===e)return Bn;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!Bn.includes(t))throw"string"!=typeof t?new TypeError("`methodNames` element must be a string"):new Error(`${t} is not Emittery method`);return e}const ge=e=>e===Dt||e===Ut;function pt(e,t,r){if(ge(t))try{Lt=!0,e.emit(t,r)}finally{Lt=!1}}let et=class e{static mixin(t,r){return r=Mn(r),n=>{if("function"!=typeof n)throw new TypeError("`target` must be function");for(const e of r)if(void 0!==n.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(n.prototype,t,{enumerable:!1,get:function(){return Object.defineProperty(this,t,{enumerable:!1,value:new e}),this[t]}});const i=e=>function(...r){return this[t][e](...r)};for(const e of r)Object.defineProperty(n.prototype,e,{enumerable:!1,value:i(e)});return n}}static get isDebugEnabled(){if("object"!=typeof globalThis.process?.env)return gr;const{env:e}=globalThis.process??{env:{}};return"emittery"===e.DEBUG||"*"===e.DEBUG||gr}static set isDebugEnabled(e){gr=e}constructor(e={}){te.set(this,new Set),pe.set(this,new Map),X.set(this,new Map),X.get(this).set(Bt,new Set),this.debug=e.debug??{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,r,n)=>{try{n=JSON.stringify(n)}catch{n=`Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`}("symbol"==typeof r||"number"==typeof r)&&(r=r.toString());const i=new Date,o=`${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}.${i.getMilliseconds()}`;console.log(`[${o}][emittery:${e}][${t}] Event Name: ${r}\n\tdata: ${n}`)})}logIfDebugEnabled(t,r,n){(e.isDebugEnabled||this.debug.enabled)&&this.debug.logger(t,this.debug.name,r,n)}on(e,t,{signal:r}={}){mt(t),e=Array.isArray(e)?e:[e];for(const r of e){Ie(r);let e=Re(this,r);e||(e=new Set,pe.get(this).set(r,e)),e.add(t),this.logIfDebugEnabled("subscribe",r,void 0),ge(r)||pt(this,Dt,{eventName:r,listener:t})}const n=()=>{this.off(e,t),r?.removeEventListener("abort",n)};return r?.addEventListener("abort",n,{once:!0}),r?.aborted&&n(),n}off(e,t){mt(t),e=Array.isArray(e)?e:[e];for(const r of e){Ie(r);const e=Re(this,r);e&&(e.delete(t),0===e.size&&pe.get(this).delete(r)),this.logIfDebugEnabled("unsubscribe",r,void 0),ge(r)||pt(this,Ut,{eventName:r,listener:t})}}once(e,t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("predicate must be a function");let r;const n=new Promise(n=>{r=this.on(e,e=>{t&&!t(e)||(r(),n(e))})});return n.off=r,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Ie(t);return On(this,e)}async emit(e,t){if(Ie(e),ge(e)&&!Lt)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),Cn(this,e,t);const r=Re(this,e)??new Set,n=te.get(this),i=[...r],o=ge(e)?[]:[...n];await Fn,await Promise.all([...i.map(async e=>{if(r.has(e))return e(t)}),...o.map(async r=>{if(n.has(r))return r(e,t)})])}async emitSerial(e,t){if(Ie(e),ge(e)&&!Lt)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t),Cn(this,e,t);const r=Re(this,e)??new Set,n=te.get(this),i=[...r],o=ge(e)?[]:[...n];await Fn;for(const e of i)r.has(e)&&await e(t);for(const r of o)n.has(r)&&await r(e,t)}onAny(e,{signal:t}={}){mt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),te.get(this).add(e),pt(this,Dt,{listener:e});const r=()=>{this.offAny(e),t?.removeEventListener("abort",r)};return t?.addEventListener("abort",r,{once:!0}),t?.aborted&&r(),r}anyEvent(){return On(this)}offAny(e){mt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),pt(this,Ut,{listener:e}),te.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),zt(t)){const e=Re(this,t);e&&e.clear();const r=Ye(this,t);if(r){for(const e of r)e.finish();r.clear()}}else{te.get(this).clear();for(const[e,t]of pe.get(this).entries())t.clear(),pe.get(this).delete(e);for(const[e,t]of X.get(this).entries()){for(const e of t)e.finish();t.clear(),X.get(this).delete(e)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const r of e)if(zt(r))t+=te.get(this).size+(Re(this,r)?.size??0)+(Ye(this,r)?.size??0)+(Ye(this)?.size??0);else{void 0!==r&&Ie(r),t+=te.get(this).size;for(const e of pe.get(this).values())t+=e.size;for(const e of X.get(this).values())t+=e.size}return t}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=Mn(t);for(const r of t){if(void 0!==e[r])throw new Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}};const Bn=Object.getOwnPropertyNames(et.prototype).filter(e=>"constructor"!==e);function zr(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[e]||(r[e]=t),r[e]}Object.defineProperty(et,"listenerAdded",{value:Dt,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(et,"listenerRemoved",{value:Ut,writable:!1,enumerable:!0,configurable:!1});const Le=zr("globals",{});var z=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e.EVENT="EVENT",e))(z||{});function di(e){return[ImageBitmap,ReadableStream,WritableStream].some(t=>e instanceof t)}let Zs=0;function Nt(e,t,r,n,i){const o=Zs++;return e.postMessage({id:o,type:t,functionName:r,args:n},n.filter(e=>di(e))),new Promise(e=>{i?.set(o,e)})}function ze(e,t){const{id:r,type:n}=e,i=Array.isArray(t)?t:[t];postMessage({id:r,type:n,result:t},i.filter(e=>di(e)))}const $t=zr("workerized",{});function Nr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function ea(){if(Nr())ze({type:z.GLOBALS_SYNC},Le);else{const e=[];for(const t in $t){const{worker:r,resolvers:n}=$t[t].workerContext;r&&e.push(Nt(r,z.GLOBALS_SYNC,"",[Le],n))}await Promise.all(e)}}function qe(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const r in e)Array.isArray(e[r])?(t[r]=[],qe(e[r],t[r])):"object"==typeof e[r]?(t[r]={},qe(e[r],t[r])):t[r]=e[r]}async function ta(e,t,r,n){const i=new t;if(i.addEventListener("message",async({data:e})=>{var t,i,o,s,a,c,u;switch(e.type){case z.GLOBALS_SYNC:e.id?(null==(i=r.get(null!=(t=e.id)?t:-1))||i(e.result),r.delete(null!=(o=e.id)?o:-1)):(qe(null!=(s=e.result)?s:{},Le),await ea());break;case z.EVENT:const{result:l}=e,f=l;if(null==f?.name)throw"Missing event name";n(f.name,f.data);break;default:null==(c=r.get(null!=(a=e.id)?a:-1))||c(e.result),r.delete(null!=(u=e.id)?u:-1)}}),!await Nt(i,z.INIT,"",[e.workerId,Le],r))throw"Failed to instantiate workerized class";return i}const re=new WeakMap,ye=new WeakMap,K=new WeakMap,Wt=Symbol("anyProducer"),Dn=Promise.resolve(),Gt=Symbol("listenerAdded"),Vt=Symbol("listenerRemoved");let Ht=!1,yr=!1;function ke(e){if("string"!=typeof e&&"symbol"!=typeof e&&"number"!=typeof e)throw new TypeError("`eventName` must be a string, symbol, or number")}function gt(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function Pe(e,t){const r=ye.get(e);if(r.has(t))return r.get(t)}function Qe(e,t){const r="string"==typeof t||"symbol"==typeof t||"number"==typeof t?t:Wt,n=K.get(e);if(n.has(r))return n.get(r)}function ra(e,t,r){const n=K.get(e);if(n.has(t))for(const e of n.get(t))e.enqueue(r);if(n.has(Wt)){const e=Promise.all([t,r]);for(const t of n.get(Wt))t.enqueue(e)}}function Un(e,t){t=Array.isArray(t)?t:[t];let r=!1,n=()=>{},i=[];const o={enqueue(e){i.push(e),n()},finish(){r=!0,n()}};for(const r of t){let t=Qe(e,r);t||(t=new Set,K.get(e).set(r,t)),t.add(o)}return{async next(){return i?0===i.length?r?(i=void 0,this.next()):(await new Promise(e=>{n=e}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(r){i=void 0;for(const r of t){const t=Qe(e,r);t&&(t.delete(o),0===t.size&&K.get(e).delete(r))}return n(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Ln(e){if(void 0===e)return zn;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!zn.includes(t))throw"string"!=typeof t?new TypeError("`methodNames` element must be a string"):new Error(`${t} is not Emittery method`);return e}const De=e=>e===Gt||e===Vt;function yt(e,t,r){if(De(t))try{Ht=!0,e.emit(t,r)}finally{Ht=!1}}class _e{static mixin(e,t){return t=Ln(t),r=>{if("function"!=typeof r)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==r.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(r.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new _e}),this[e]}});const n=t=>function(...r){return this[e][t](...r)};for(const e of t)Object.defineProperty(r.prototype,e,{enumerable:!1,value:n(e)});return r}}static get isDebugEnabled(){var e,t;if("object"!=typeof(null==(e=globalThis.process)?void 0:e.env))return yr;const{env:r}=null!=(t=globalThis.process)?t:{env:{}};return"emittery"===r.DEBUG||"*"===r.DEBUG||yr}static set isDebugEnabled(e){yr=e}constructor(e={}){var t;re.set(this,new Set),ye.set(this,new Map),K.set(this,new Map),K.get(this).set(Wt,new Set),this.debug=null!=(t=e.debug)?t:{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,r,n)=>{try{n=JSON.stringify(n)}catch{n=`Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`}("symbol"==typeof r||"number"==typeof r)&&(r=r.toString());const i=new Date,o=`${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}.${i.getMilliseconds()}`;console.log(`[${o}][emittery:${e}][${t}] Event Name: ${r}\n\tdata: ${n}`)})}logIfDebugEnabled(e,t,r){(_e.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,r)}on(e,t){gt(t),e=Array.isArray(e)?e:[e];for(const r of e){ke(r);let e=Pe(this,r);e||(e=new Set,ye.get(this).set(r,e)),e.add(t),this.logIfDebugEnabled("subscribe",r,void 0),De(r)||yt(this,Gt,{eventName:r,listener:t})}return this.off.bind(this,e,t)}off(e,t){gt(t),e=Array.isArray(e)?e:[e];for(const r of e){ke(r);const e=Pe(this,r);e&&(e.delete(t),0===e.size&&ye.get(this).delete(r)),this.logIfDebugEnabled("unsubscribe",r,void 0),De(r)||yt(this,Vt,{eventName:r,listener:t})}}once(e){let t;const r=new Promise(r=>{t=this.on(e,e=>{t(),r(e)})});return r.off=t,r}events(e){e=Array.isArray(e)?e:[e];for(const t of e)ke(t);return Un(this,e)}async emit(e,t){var r;if(ke(e),De(e)&&!Ht)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),ra(this,e,t);const n=null!=(r=Pe(this,e))?r:new Set,i=re.get(this),o=[...n],s=De(e)?[]:[...i];await Dn,await Promise.all([...o.map(async e=>{if(n.has(e))return e(t)}),...s.map(async r=>{if(i.has(r))return r(e,t)})])}async emitSerial(e,t){var r;if(ke(e),De(e)&&!Ht)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const n=null!=(r=Pe(this,e))?r:new Set,i=re.get(this),o=[...n],s=[...i];await Dn;for(const e of o)n.has(e)&&await e(t);for(const r of s)i.has(r)&&await r(e,t)}onAny(e){return gt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),re.get(this).add(e),yt(this,Gt,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return Un(this)}offAny(e){gt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),yt(this,Vt,{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),"string"==typeof t||"symbol"==typeof t||"number"==typeof t){const e=Pe(this,t);e&&e.clear();const r=Qe(this,t);if(r){for(const e of r)e.finish();r.clear()}}else{re.get(this).clear();for(const[e,t]of ye.get(this).entries())t.clear(),ye.get(this).delete(e);for(const[e,t]of K.get(this).entries()){for(const e of t)e.finish();t.clear(),K.get(this).delete(e)}}}listenerCount(e){var t,r,n,i,o,s;e=Array.isArray(e)?e:[e];let a=0;for(const c of e)if("string"!=typeof c){typeof c<"u"&&ke(c),a+=re.get(this).size;for(const e of ye.get(this).values())a+=e.size;for(const e of K.get(this).values())a+=e.size}else a+=re.get(this).size+(null!=(r=null==(t=Pe(this,c))?void 0:t.size)?r:0)+(null!=(i=null==(n=Qe(this,c))?void 0:n.size)?i:0)+(null!=(s=null==(o=Qe(this))?void 0:o.size)?s:0);return a}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=Ln(t);for(const r of t){if(void 0!==e[r])throw new Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}}const zn=Object.getOwnPropertyNames(_e.prototype).filter(e=>"constructor"!==e);function na(e){return e.onAny&&e.emit}function ia(e){return e.prototype.onAny&&e.prototype.emit}Object.defineProperty(_e,"listenerAdded",{value:Gt,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(_e,"listenerRemoved",{value:Vt,writable:!1,enumerable:!0,configurable:!1});let oa=0;async function sa(e,t,r){const n=ia(e)?new _e:{},i=oa++;return Object.getOwnPropertyNames(e.prototype).forEach(e=>{n[e]=(...n)=>Nt(t,z.FORWARD,e,n,r)}),n.terminate=async(...e)=>{const o=await Nt(t,z.TERMINATE,"",e,r);return delete $t[i],t.terminate(),n.workerContext.worker=void 0,o},n.workerContext={id:i,worker:t,resolvers:r},$t[i]=n,n}async function aa(e,t){const r=new Map;let n;const i=await ta(e,t,r,(e,t)=>{n?.emit&&n?.emit(e,t)});return n=await sa(e,i,r),n}async function ca(e,t){const{functionName:r,args:n}=e;if(!t.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!t.instance[r])throw`undefined function [${r}] in class ${t.instance.constructor.workerId}`;ze(e,await t.instance[r](...n??[]))}const hi=zr("registeredWorkers",{});function ua(e,t){t.workerId=e,Nr()&&(hi[t.workerId]=t)}function la(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,n]=e.args,i=hi[r];if(!i)throw`unknown worker class ${r}`;t.instance=new i(e.args.slice(1)),qe(n,Le),na(t.instance)&&t.instance.onAny((e,t)=>{ze({type:z.EVENT},{name:e,data:t})}),ze(e,void 0!==typeof t.instance)}async function fa(e,t){const{args:r}=e;if(!t.instance)throw"instance not initialized";let n;t.instance.terminate&&(n=await t.instance.terminate(...r??[])),ze(e,n)}function da(e){if(!e.args)throw"Missing globals while syncing";qe(e.args[0],Le),ze(e,{})}function ha(){const e={};onmessage=async t=>{const r=t.data;switch(r.type){case z.INIT:la(r,e);break;case z.FORWARD:ca(r,e);break;case z.TERMINATE:fa(r,e);break;case z.GLOBALS_SYNC:da(r)}}}Nr()&&ha();class Nn{static async createVideoReadable(e){return new Promise((t,r)=>{const n=document.createElement("video");let i=new AbortController,o=new AbortController;n.addEventListener("canplay",()=>{i.abort(),n.muted=!0,n.loop=!0,n.play().then(()=>{try{const e=n.captureStream(),r=new MediaStreamTrackProcessor(e.getVideoTracks()[0]);t(r.readable)}catch(e){r(e)}})},{once:!0,signal:o.signal}),n.addEventListener("error",e=>{o.abort(),r("loading error:"+e)},{once:!0,signal:i.signal}),n.crossOrigin="anonymous",n.src=e})}static async createImageCanvas(e){const t=await(await fetch(e)).blob();return await createImageBitmap(t)}}var ma=Object.defineProperty,pa=(e,t,r)=>t in e?ma(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ga=(e,t,r)=>(pa(e,t+"",r),r);const ya="hlg.tokbox.com/prod/logging/vcp_webrtc",ba="https://",wa=1e4;let bt;const xa=new Uint8Array(16);function va(){if(!bt&&(bt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!bt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return bt(xa)}const C=[];for(let e=0;e<256;++e)C.push((e+256).toString(16).slice(1));function _a(e,t=0){return(C[e[t+0]]+C[e[t+1]]+C[e[t+2]]+C[e[t+3]]+"-"+C[e[t+4]]+C[e[t+5]]+"-"+C[e[t+6]]+C[e[t+7]]+"-"+C[e[t+8]]+C[e[t+9]]+"-"+C[e[t+10]]+C[e[t+11]]+C[e[t+12]]+C[e[t+13]]+C[e[t+14]]+C[e[t+15]]).toLowerCase()}const Ea=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),$n={randomUUID:Ea};function Aa(e,t,r){if($n.randomUUID&&!t&&!e)return $n.randomUUID();const n=(e=e||{}).random||(e.rng||va)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,_a(n)}function $r(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[e]||(r[e]=t),r[e]}const oe=$r("globals",{});var xe=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e))(xe||{});function mi(e){return[ImageBitmap,ReadableStream,WritableStream].some(t=>e instanceof t)}let Ta=0;function Sa(e,t,r,n,i){const o=Ta++;return e.postMessage({id:o,type:t,functionName:r,args:n},n.filter(e=>mi(e))),new Promise(e=>{i?.set(o,e)})}function tt(e,t){const{id:r,type:n}=e,i=Array.isArray(t)?t:[t];postMessage({id:r,type:n,result:t},i.filter(e=>mi(e)))}const Wn=$r("workerized",{});function pi(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function Ia(){if(pi())tt({type:xe.GLOBALS_SYNC},oe);else{const e=[];for(const t in Wn){const{worker:r,resolvers:n}=Wn[t].workerContext;r&&e.push(Sa(r,xe.GLOBALS_SYNC,"",[oe],n))}await Promise.all(e)}}function jt(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const r in e)Array.isArray(e[r])?(t[r]=[],jt(e[r],t[r])):"object"==typeof e[r]?(t[r]={},jt(e[r],t[r])):t[r]=e[r]}async function Ra(e,t){const{functionName:r,args:n}=e;if(!t.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!t.instance[r])throw`undefined function [${r}] in class ${t.instance.constructor.workerId}`;tt(e,await t.instance[r](...n??[]))}const ka=$r("registeredWorkers",{});function Pa(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,n]=e.args,i=ka[r];if(!i)throw`unknown worker class ${r}`;t.instance=new i(e.args.slice(1)),jt(n,oe),tt(e,void 0!==typeof t.instance)}async function Fa(e,t){const{args:r}=e;if(!t.instance)throw"instance not initialized";let n;t.instance.terminate&&(n=await t.instance.terminate(...r??[])),tt(e,n)}function Ca(e){if(!e.args)throw"Missing globals while syncing";jt(e.args[0],oe),tt(e,{})}function Oa(){const e={};onmessage=async t=>{const r=t.data;switch(r.type){case xe.INIT:Pa(r,e);break;case xe.FORWARD:Ra(r,e);break;case xe.TERMINATE:Fa(r,e);break;case xe.GLOBALS_SYNC:Ca(r)}}}function Ma(e,t){return oe[e]||(oe[e]=t),[()=>oe[e],async t=>{oe[e]=t,await Ia()}]}function Ba(e,t){return Ma(e,t)}pi()&&Oa();const[Da]=Ba("metadata");function br(){return Da()}class Ua{constructor(e){ga(this,"uuid",Aa()),this.config=e}async send(e){var t,r,n;const{appId:i,sourceType:o}=null!=(t=br())?t:{};if(!i||!o)return"metadata missing";const s=new AbortController,a=setTimeout(()=>s.abort(),wa);return await(null!=(n=null==(r=this.config)?void 0:r.fetch)?n:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:s.signal}),clearTimeout(a),"success"}getUrl(){var e;let t=null!=(e=br().proxyUrl)?e:ba;return t+=("/"===t.at(-1)?"":"/")+ya,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=br();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}}const La="7.0.2-alpha.1";class Wr{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:r}=e;this.canvas.width=t,this.canvas.height=r}renderSilhouette(e,t,r="none"){const{width:n,height:i}=e;this.context.save(),this.context.drawImage(t,0,0,t.width,t.height,0,0,n,i),this.context.filter="blur(5px)",this.context.globalCompositeOperation="source-in",this.context.drawImage(t,0,0,t.width,t.height,0,0,n,i),this.context.globalCompositeOperation="source-in",this.context.filter=r,this.context.drawImage(e,0,0,n,i,0,0,this.canvas.width,this.canvas.height),this.context.restore()}destroy(){}}class za extends Wr{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const r=await createImageBitmap(t);return this.renderSilhouette(e,r),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 Na extends Wr{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const r=await createImageBitmap(t);return this.renderSilhouette(e,r,`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 $a extends Wr{setBackgroundImage(e){this.backgroundImage=e}async render(e,t){super.resizeCanvas(e);const r=await createImageBitmap(t);return this.renderSilhouette(e,r),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 Gr=5120,Xe=5121,Vr=5122,Hr=5123,jr=5124,Yr=5125,Qr=5126,Wa=32819,Ga=32820,Va=33635,Ha=5131,ja=33640,Ya=35899,Qa=35902,qa=36269,Xa=34042,gi={};{const e=gi;e[Gr]=Int8Array,e[Xe]=Uint8Array,e[Vr]=Int16Array,e[Hr]=Uint16Array,e[jr]=Int32Array,e[Yr]=Uint32Array,e[Qr]=Float32Array,e[Wa]=Uint16Array,e[Ga]=Uint16Array,e[Va]=Uint16Array,e[Ha]=Uint16Array,e[ja]=Uint32Array,e[Ya]=Uint32Array,e[Qa]=Uint32Array,e[qa]=Uint32Array,e[Xa]=Uint32Array}function qr(e){if(e instanceof Int8Array)return Gr;if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)return Xe;if(e instanceof Int16Array)return Vr;if(e instanceof Uint16Array)return Hr;if(e instanceof Int32Array)return jr;if(e instanceof Uint32Array)return Yr;if(e instanceof Float32Array)return Qr;throw new Error("unsupported typed array type")}function yi(e){if(e===Int8Array)return Gr;if(e===Uint8Array||e===Uint8ClampedArray)return Xe;if(e===Int16Array)return Vr;if(e===Uint16Array)return Hr;if(e===Int32Array)return jr;if(e===Uint32Array)return Yr;if(e===Float32Array)return Qr;throw new Error("unsupported typed array type")}function bi(e){const t=gi[e];if(!t)throw new Error("unknown gl type");return t}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 wi(...e){console.error(...e)}const Gn=new Map;function Zt(e,t){if(!e||"object"!=typeof e)return!1;let r=Gn.get(t);r||(r=new WeakMap,Gn.set(t,r));let n=r.get(e);if(void 0===n){const i=Object.prototype.toString.call(e);n=i.substring(8,i.length-1)===t,r.set(e,n)}return n}function Ka(e,t){return typeof WebGLBuffer<"u"&&Zt(t,"WebGLBuffer")}function Ja(e,t){return typeof WebGLRenderbuffer<"u"&&Zt(t,"WebGLRenderbuffer")}function Xr(e,t){return typeof WebGLTexture<"u"&&Zt(t,"WebGLTexture")}function Za(e,t){return typeof WebGLSampler<"u"&&Zt(t,"WebGLSampler")}const xi=35044,ve=34962,ec=34963,tc=34660,rc=5120,nc=5121,ic=5122,oc=5123,sc=5124,ac=5125,vi=5126,_i={attribPrefix:""};function cc(e,t,r,n,i){e.bindBuffer(t,r),e.bufferData(t,n,i||xi)}function Ei(e,t,r,n){if(Ka(e,t))return t;r=r||ve;const i=e.createBuffer();return cc(e,r,i,t,n),i}function Ai(e){return"indices"===e}function uc(e){return e===Int8Array||e===Uint8Array}function lc(e){return e.length?e:e.data}const fc=/coord|texture/i,dc=/color|colour/i;function hc(e,t){let r;if(r=fc.test(e)?2:dc.test(e)?4:3,t%r>0)throw new Error(`Can not guess numComponents for attribute '${e}'. Tried ${r} but ${t} values is not evenly divisible by ${r}. You should specify it.`);return r}function mc(e,t,r){return e.numComponents||e.size||hc(t,r||lc(e).length)}function Ti(e,t){if(Yt(e))return e;if(Yt(e.data))return e.data;Array.isArray(e)&&(e={data:e});let r=e.type?Kr(e.type):void 0;return r||(r=Ai(t)?Uint16Array:Float32Array),new r(e.data)}function pc(e){return"number"==typeof e?e:e?yi(e):vi}function Kr(e){return"number"==typeof e?bi(e):e||Float32Array}function gc(e,t){return{buffer:t.buffer,numValues:24,type:pc(t.type),arrayType:Kr(t.type)}}function yc(e,t){const r=t.data||t,n=Kr(t.type),i=r*n.BYTES_PER_ELEMENT,o=e.createBuffer();return e.bindBuffer(ve,o),e.bufferData(ve,i,t.drawType||xi),{buffer:o,numValues:r,type:yi(n),arrayType:n}}function bc(e,t,r){const n=Ti(t,r);return{arrayType:n.constructor,buffer:Ei(e,n,void 0,t.drawType),type:qr(n),numValues:0}}function wc(e,t){const r={};return Object.keys(t).forEach(function(n){if(!Ai(n)){const i=t[n],o=i.attrib||i.name||i.attribName||_i.attribPrefix+n;if(i.value){if(!Array.isArray(i.value)&&!Yt(i.value))throw new Error("array.value is not array or typedarray");r[o]={value:i.value}}else{let t;t=i.buffer&&i.buffer instanceof WebGLBuffer?gc:"number"==typeof i||"number"==typeof i.data?yc:bc;const{buffer:s,type:a,numValues:c,arrayType:u}=t(e,i,n),l=void 0!==i.normalize?i.normalize:uc(u),f=mc(i,n,c);r[o]={buffer:s,numComponents:f,type:a,normalize:l,stride:i.stride||0,offset:i.offset||0,divisor:void 0===i.divisor?void 0:i.divisor,drawType:i.drawType}}}}),e.bindBuffer(ve,null),r}function xc(e,t){return t===rc||t===nc?1:t===ic||t===oc?2:t===sc||t===ac||t===vi?4:0}const wr=["position","positions","a_position"];function vc(e,t){let r,n;for(n=0;n<wr.length&&(r=wr[n],!(r in t)&&(r=_i.attribPrefix+r,!(r in t)));++n);n===wr.length&&(r=Object.keys(t)[0]);const i=t[r];if(!i.buffer)return 1;e.bindBuffer(ve,i.buffer);const o=e.getBufferParameter(ve,tc);e.bindBuffer(ve,null);const s=o/xc(e,i.type),a=i.numComponents||i.size,c=s/a;if(c%1!=0)throw new Error(`numComponents ${a} not correct for length ${length}`);return c}function _c(e,t,r){const n=wc(e,t),i=Object.assign({},r||{});i.attribs=Object.assign({},r?r.attribs:{},n);const o=t.indices;if(o){const t=Ti(o,"indices");i.indices=Ei(e,t,ec),i.numElements=t.length,i.elementType=qr(t)}else i.numElements||(i.numElements=vc(e,i.attribs));return i}function rt(e){return!!e.texStorage2D}const Si=function(){const e={},t={};return function(r,n){return function(r){const n=r.constructor.name;if(!e[n]){for(const e in r)if("number"==typeof r[e]){const n=t[r[e]];t[r[e]]=n?`${n} | ${e}`:e}e[n]=!0}}(r),t[n]||("number"==typeof n?`0x${n.toString(16)}`:n)}}(),ae={textureColor:new Uint8Array([128,192,255,255]),textureOptions:{},crossOrigin:void 0},Ke=Yt,Ii=function(){let e;return function(){return e=e||(typeof document<"u"&&document.createElement?document.createElement("canvas").getContext("2d"):null),e}}(),Vn=6406,j=6407,T=6408,Hn=6409,jn=6410,Ve=6402,Yn=34041,Qt=33071,Ec=9728,Ac=9729,ce=3553,se=34067,Ee=32879,Ae=35866,Jr=34069,Tc=34070,Sc=34071,Ic=34072,Rc=34073,kc=34074,Sr=10241,Ir=10240,qt=10242,Xt=10243,Qn=32882,Pc=33082,Fc=33083,Cc=33084,Oc=33085,Mc=34892,Bc=34893,Zr=3317,Ri=3314,ki=32878,Pi=3316,Fi=3315,Ci=32877,Dc=37443,Uc=37441,Lc=37440,zc=33321,Nc=36756,$c=33325,Wc=33326,Gc=33330,Vc=33329,Hc=33338,jc=33337,Yc=33340,Qc=33339,qc=33323,Xc=36757,Kc=33327,Jc=33328,Zc=33336,eu=33335,tu=33332,ru=33331,nu=33334,iu=33333,ou=32849,su=35905,au=36194,cu=36758,uu=35898,lu=35901,fu=34843,du=34837,hu=36221,mu=36239,pu=36215,gu=36233,yu=36209,bu=36227,wu=32856,xu=35907,vu=36759,_u=32855,Eu=32854,Au=32857,Tu=34842,Su=34836,Iu=36220,Ru=36238,ku=36975,Pu=36214,Fu=36232,Cu=36226,Ou=36208,Mu=33189,Bu=33190,Du=36012,Uu=36013,Lu=35056,ne=5120,A=5121,wt=5122,Fe=5123,xt=5124,de=5125,M=5126,qn=32819,Xn=32820,Kn=33635,G=5131,He=36193,xr=33640,zu=35899,Nu=35902,$u=36269,Wu=34042,vt=33319,Ce=33320,_t=6403,Oe=36244,Me=36248,he=36249;let vr;function er(e){if(!vr){const e={};e[Vn]={textureFormat:Vn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[A,G,He,M]},e[Hn]={textureFormat:Hn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[A,G,He,M]},e[jn]={textureFormat:jn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2,4,4,8],type:[A,G,He,M]},e[j]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,6,6,12,2],type:[A,G,He,M,Kn]},e[T]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,8,8,16,2,2],type:[A,G,He,M,qn,Xn]},e[Ve]={textureFormat:Ve,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[de,Fe]},e[zc]={textureFormat:_t,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1],type:[A]},e[Nc]={textureFormat:_t,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[1],type:[ne]},e[$c]={textureFormat:_t,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4,2],type:[M,G]},e[Wc]={textureFormat:_t,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[Gc]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[A]},e[Vc]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[ne]},e[tu]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Fe]},e[ru]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[wt]},e[nu]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[de]},e[iu]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[xt]},e[qc]={textureFormat:vt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2],type:[A]},e[Xc]={textureFormat:vt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[2],type:[ne]},e[Kc]={textureFormat:vt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[8,4],type:[M,G]},e[Jc]={textureFormat:vt,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[8],type:[M]},e[Zc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[A]},e[eu]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[ne]},e[Hc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Fe]},e[jc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[wt]},e[Yc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[de]},e[Qc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[xt]},e[ou]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3],type:[A]},e[su]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[A]},e[au]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,2],type:[A,Kn]},e[cu]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[ne]},e[uu]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,G,zu]},e[lu]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,G,Nu]},e[fu]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6],type:[M,G]},e[du]={textureFormat:j,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[M]},e[hu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[A]},e[mu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[ne]},e[pu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Fe]},e[gu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[wt]},e[yu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[de]},e[bu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[xt]},e[wu]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[A]},e[xu]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[A]},e[vu]={textureFormat:T,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4],type:[ne]},e[_u]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2,4],type:[A,Xn,xr]},e[Eu]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2],type:[A,qn]},e[Au]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[xr]},e[Tu]={textureFormat:T,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[16,8],type:[M,G]},e[Su]={textureFormat:T,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[16],type:[M]},e[Iu]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[A]},e[Ru]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ne]},e[ku]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[xr]},e[Pu]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Fe]},e[Fu]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[wt]},e[Cu]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[xt]},e[Ou]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[de]},e[Mu]={textureFormat:Ve,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[Fe,de]},e[Bu]={textureFormat:Ve,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[de]},e[Du]={textureFormat:Ve,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[Lu]={textureFormat:Yn,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Wu]},e[Uu]={textureFormat:Yn,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[$u]},Object.keys(e).forEach(function(t){const r=e[t];r.bytesPerElementMap={},r.bytesPerElement.forEach(function(e,t){const n=r.type[t];r.bytesPerElementMap[n]=e})}),vr=e}return vr[e]}function Gu(e,t){const r=er(e);if(!r)throw"unknown internal format";const n=r.bytesPerElementMap[t];if(void 0===n)throw"unknown internal format";return n}function nt(e){const t=er(e);if(!t)throw"unknown internal format";return{format:t.textureFormat,type:t.type[0]}}function Jn(e){return!(e&e-1)}function Vu(e,t,r,n){if(!rt(e))return Jn(t)&&Jn(r);const i=er(n);if(!i)throw"unknown internal format";return i.colorRenderable&&i.textureFilterable}function Hu(e){const t=er(e);if(!t)throw"unknown internal format";return t.textureFilterable}function ju(e,t,r){return Ke(t)?qr(t):r||A}function Et(e,t,r,n,i){if(i%1!=0)throw"can't guess dimensions";if(r||n){if(n){if(!r&&(r=i/n)%1)throw"can't guess dimensions"}else if((n=i/r)%1)throw"can't guess dimensions"}else{const e=Math.sqrt(i/(t===se?6:1));e%1==0?(r=e,n=e):(r=i,n=1)}return{width:r,height:n}}function Ne(e,t){void 0!==t.colorspaceConversion&&e.pixelStorei(Dc,t.colorspaceConversion),void 0!==t.premultiplyAlpha&&e.pixelStorei(Uc,t.premultiplyAlpha),void 0!==t.flipY&&e.pixelStorei(Lc,t.flipY)}function Oi(e){e.pixelStorei(Zr,4),rt(e)&&(e.pixelStorei(Ri,0),e.pixelStorei(ki,0),e.pixelStorei(Pi,0),e.pixelStorei(Fi,0),e.pixelStorei(Ci,0))}function Yu(e,t,r,n){n.minMag&&(r.call(e,t,Sr,n.minMag),r.call(e,t,Ir,n.minMag)),n.min&&r.call(e,t,Sr,n.min),n.mag&&r.call(e,t,Ir,n.mag),n.wrap&&(r.call(e,t,qt,n.wrap),r.call(e,t,Xt,n.wrap),(t===Ee||Za(e,t))&&r.call(e,t,Qn,n.wrap)),n.wrapR&&r.call(e,t,Qn,n.wrapR),n.wrapS&&r.call(e,t,qt,n.wrapS),n.wrapT&&r.call(e,t,Xt,n.wrapT),void 0!==n.minLod&&r.call(e,t,Pc,n.minLod),void 0!==n.maxLod&&r.call(e,t,Fc,n.maxLod),void 0!==n.baseLevel&&r.call(e,t,Cc,n.baseLevel),void 0!==n.maxLevel&&r.call(e,t,Oc,n.maxLevel),void 0!==n.compareFunc&&r.call(e,t,Bc,n.compareFunc),void 0!==n.compareMode&&r.call(e,t,Mc,n.compareMode)}function Mi(e,t,r){const n=r.target||ce;e.bindTexture(n,t),Yu(e,n,e.texParameteri,r)}function Qu(e){return Ke(e=e||ae.textureColor)?e:new Uint8Array([255*e[0],255*e[1],255*e[2],255*e[3]])}function Rr(e,t,r,n,i,o){o=o||T;const s=(r=r||ae.textureOptions).target||ce;if(n=n||r.width,i=i||r.height,e.bindTexture(s,t),Vu(e,n,i,o))e.generateMipmap(s);else{const t=Hu(o)?Ac:Ec;e.texParameteri(s,Sr,t),e.texParameteri(s,Ir,t),e.texParameteri(s,qt,Qt),e.texParameteri(s,Xt,Qt)}}function Je(e){return!0===e.auto||void 0===e.auto&&void 0===e.level}function kr(e,t){return(t=t||{}).cubeFaceOrder||[Jr,Tc,Sc,Ic,Rc,kc]}function Pr(e,t){const r=kr(e,t).map(function(e,t){return{face:e,ndx:t}});return r.sort(function(e,t){return e.face-t.face}),r}function Bi(e,t,r,n){const i=(n=n||ae.textureOptions).target||ce,o=n.level||0;let s=r.width,a=r.height;const c=n.internalFormat||n.format||T,u=nt(c),l=n.format||u.format,f=n.type||u.type;if(Ne(e,n),e.bindTexture(i,t),i===se){const u=r.width,h=r.height;let d,m;if(u/6===h)d=h,m=[0,0,1,0,2,0,3,0,4,0,5,0];else if(h/6===u)d=u,m=[0,0,0,1,0,2,0,3,0,4,0,5];else if(u/3==h/2)d=u/3,m=[0,0,1,0,2,0,0,1,1,1,2,1];else{if(u/2!=h/3)throw"can't figure out cube map from element: "+(r.src?r.src:r.nodeName);d=u/2,m=[0,0,1,0,0,1,1,1,0,2,1,2]}const p=Ii();p?(p.canvas.width=d,p.canvas.height=d,s=d,a=d,Pr(e,n).forEach(function(t){const n=m[2*t.ndx+0]*d,i=m[2*t.ndx+1]*d;p.drawImage(r,n,i,d,d,0,0,d,d),e.texImage2D(t.face,o,c,l,f,p.canvas)}),p.canvas.width=1,p.canvas.height=1):typeof createImageBitmap<"u"&&(s=d,a=d,Pr(e,n).forEach(function(u){const h=m[2*u.ndx+0]*d,p=m[2*u.ndx+1]*d;e.texImage2D(u.face,o,c,d,d,0,l,f,null),createImageBitmap(r,h,p,d,d,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(function(r){Ne(e,n),e.bindTexture(i,t),e.texImage2D(u.face,o,c,l,f,r),Je(n)&&Rr(e,t,n,s,a,c)})}))}else if(i===Ee||i===Ae){const t=Math.min(r.width,r.height),n=Math.max(r.width,r.height),s=n/t;if(s%1!=0)throw"can not compute 3D dimensions of element";const a=r.width===n?1:0,u=r.height===n?1:0;e.pixelStorei(Zr,1),e.pixelStorei(Ri,r.width),e.pixelStorei(ki,0),e.pixelStorei(Ci,0),e.texImage3D(i,o,c,t,t,t,0,l,f,null);for(let n=0;n<s;++n){const s=n*t*a,c=n*t*u;e.pixelStorei(Pi,s),e.pixelStorei(Fi,c),e.texSubImage3D(i,o,0,0,n,t,t,1,l,f,r)}Oi(e)}else e.texImage2D(i,o,c,l,f,r);Je(n)&&Rr(e,t,n,s,a,c),Mi(e,t,n)}function it(){}function qu(e){if(typeof document<"u"){const t=document.createElement("a");return t.href=e,t.hostname===location.hostname&&t.port===location.port&&t.protocol===location.protocol}{const t=new URL(location.href).origin;return new URL(e,location.href).origin===t}}function Xu(e,t){return void 0!==t||qu(e)?t:"anonymous"}function Ku(e,t,r){let n;if(r=r||it,t=Xu(e,t=void 0!==t?t:ae.crossOrigin),typeof Image<"u"){n=new Image,void 0!==t&&(n.crossOrigin=t);const i=function(){n.removeEventListener("error",o),n.removeEventListener("load",s),n=null},o=function(){const t="couldn't load image: "+e;wi(t),r(t,n),i()},s=function(){r(null,n),i()};return n.addEventListener("error",o),n.addEventListener("load",s),n.src=e,n}if(typeof ImageBitmap<"u"){let i,o;const s=function(){r(i,o)},a={};t&&(a.mode="cors"),fetch(e,a).then(function(e){if(!e.ok)throw e;return e.blob()}).then(function(e){return createImageBitmap(e,{premultiplyAlpha:"none",colorSpaceConversion:"none"})}).then(function(e){o=e,setTimeout(s)}).catch(function(e){i=e,setTimeout(s)}),n=null}return n}function Di(e){return typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof ImageData<"u"&&e instanceof ImageData||typeof HTMLElement<"u"&&e instanceof HTMLElement}function en(e,t,r){return Di(e)?(setTimeout(function(){r(null,e)}),e):Ku(e,t,r)}function tn(e,t,r){const n=(r=r||ae.textureOptions).target||ce;if(e.bindTexture(n,t),!1===r.color)return;const i=Qu(r.color);if(n===se)for(let t=0;t<6;++t)e.texImage2D(Jr+t,0,T,1,1,0,T,A,i);else n===Ee||n===Ae?e.texImage3D(n,0,T,1,1,1,0,T,A,i):e.texImage2D(n,0,T,1,1,0,T,A,i)}function Ju(e,t,r,n){return n=n||it,tn(e,t,r=r||ae.textureOptions),en((r=Object.assign({},r)).src,r.crossOrigin,function(i,o){i?n(i,t,o):(Bi(e,t,o,r),n(null,t,o))})}function Zu(e,t,r,n){n=n||it;const i=r.src;if(6!==i.length)throw"there must be 6 urls for a cubemap";const o=r.level||0,s=r.internalFormat||r.format||T,a=nt(s),c=r.format||a.format,u=r.type||A,l=r.target||ce;if(l!==se)throw"target must be TEXTURE_CUBE_MAP";tn(e,t,r),r=Object.assign({},r);let f=6;const h=[],d=kr(e,r);let m;m=i.map(function(i,a){return en(i,r.crossOrigin,function(i){return function(a,d){--f,a?h.push(a):d.width!==d.height?h.push("cubemap face img is not a square: "+d.src):(Ne(e,r),e.bindTexture(l,t),5===f?kr().forEach(function(t){e.texImage2D(t,o,s,c,u,d)}):e.texImage2D(i,o,s,c,u,d),Je(r)&&e.generateMipmap(l)),0===f&&n(h.length?h:void 0,t,m)}}(d[a]))})}function el(e,t,r,n){n=n||it;const i=r.src,o=r.internalFormat||r.format||T,s=nt(o),a=r.format||s.format,c=r.type||A,u=r.target||Ae;if(u!==Ee&&u!==Ae)throw"target must be TEXTURE_3D or TEXTURE_2D_ARRAY";tn(e,t,r),r=Object.assign({},r);let l=i.length;const f=[];let h;const d=r.level||0;let m=r.width,p=r.height;const g=i.length;let y=!0;h=i.map(function(i,s){return en(i,r.crossOrigin,function(i){return function(s,b){if(--l,s)f.push(s);else{if(Ne(e,r),e.bindTexture(u,t),y){y=!1,m=r.width||b.width,p=r.height||b.height,e.texImage3D(u,d,o,m,p,g,0,a,c,null);for(let t=0;t<g;++t)e.texSubImage3D(u,d,0,0,t,m,p,1,a,c,b)}else{let t,r=b;(b.width!==m||b.height!==p)&&(t=Ii(),r=t.canvas,t.canvas.width=m,t.canvas.height=p,t.drawImage(b,0,0,m,p)),e.texSubImage3D(u,d,0,0,i,m,p,1,a,c,r),t&&r===t.canvas&&(t.canvas.width=0,t.canvas.height=0)}Je(r)&&e.generateMipmap(u)}0===l&&n(f.length?f:void 0,t,h)}}(s))})}function tl(e,t,r,n){const i=(n=n||ae.textureOptions).target||ce;e.bindTexture(i,t);let o=n.width,s=n.height,a=n.depth;const c=n.level||0,u=n.internalFormat||n.format||T,l=nt(u),f=n.format||l.format,h=n.type||ju(e,r,l.type);if(Ke(r))r instanceof Uint8ClampedArray&&(r=new Uint8Array(r.buffer));else{const e=bi(h);r=new e(r)}const d=Gu(u,h),m=r.byteLength/d;if(m%1)throw"length wrong size for format: "+Si(e,f);let p;if(i===Ee||i===Ae)if(o||s||a)!o||s&&a?!s||o&&a?(p=Et(e,i,o,s,m/a),o=p.width,s=p.height):(p=Et(e,i,o,a,m/s),o=p.width,a=p.height):(p=Et(e,i,s,a,m/o),s=p.width,a=p.height);else{const e=Math.cbrt(m);if(e%1!=0)throw"can't guess cube size of array of numElements: "+m;o=e,s=e,a=e}else p=Et(e,i,o,s,m),o=p.width,s=p.height;if(Oi(e),e.pixelStorei(Zr,n.unpackAlignment||1),Ne(e,n),i===se){const t=m/6*(d/r.BYTES_PER_ELEMENT);Pr(e,n).forEach(n=>{const i=t*n.ndx,a=r.subarray(i,i+t);e.texImage2D(n.face,c,u,o,s,0,f,h,a)})}else i===Ee||i===Ae?e.texImage3D(i,c,u,o,s,a,0,f,h,r):e.texImage2D(i,c,u,o,s,0,f,h,r);return{width:o,height:s,depth:a,type:h}}function rl(e,t,r){const n=r.target||ce;e.bindTexture(n,t);const i=r.level||0,o=r.internalFormat||r.format||T,s=nt(o),a=r.format||s.format,c=r.type||s.type;if(Ne(e,r),n===se)for(let t=0;t<6;++t)e.texImage2D(Jr+t,i,o,r.width,r.height,0,a,c,null);else n===Ee||n===Ae?e.texImage3D(n,i,o,r.width,r.height,r.depth,0,a,c,null):e.texImage2D(n,i,o,r.width,r.height,0,a,c,null)}function Ui(e,t,r){r=r||it,t=t||ae.textureOptions;const n=e.createTexture(),i=t.target||ce;let o=t.width||1,s=t.height||1;const a=t.internalFormat||T;e.bindTexture(i,n),i===se&&(e.texParameteri(i,qt,Qt),e.texParameteri(i,Xt,Qt));let c=t.src;if(c)if("function"==typeof c&&(c=c(e,t)),"string"==typeof c)Ju(e,n,t,r);else if(Ke(c)||Array.isArray(c)&&("number"==typeof c[0]||Array.isArray(c[0])||Ke(c[0]))){const r=tl(e,n,c,t);o=r.width,s=r.height}else Array.isArray(c)&&("string"==typeof c[0]||Di(c[0]))?i===se?Zu(e,n,t,r):el(e,n,t,r):(Bi(e,n,c,t),o=c.width,s=c.height);else rl(e,n,t);return Je(t)&&Rr(e,n,t,o,s,a),Mi(e,n,t),n}const rn=wi;function Li(e){return typeof document<"u"&&document.getElementById?document.getElementById(e):null}const Kt=33984,tr=34962,nl=34963,il=35713,ol=35714,sl=35632,al=35633,cl=35981,zi=35718,ul=35721,ll=35971,fl=35382,dl=35396,hl=35398,ml=35392,pl=35395,rr=5126,Ni=35664,$i=35665,Wi=35666,nn=5124,Gi=35667,Vi=35668,Hi=35669,ji=35670,Yi=35671,Qi=35672,qi=35673,Xi=35674,Ki=35675,Ji=35676,gl=35678,yl=35680,bl=35679,wl=35682,xl=35685,vl=35686,_l=35687,El=35688,Al=35689,Tl=35690,Sl=36289,Il=36292,Rl=36293,on=5125,Zi=36294,eo=36295,to=36296,kl=36298,Pl=36299,Fl=36300,Cl=36303,Ol=36306,Ml=36307,Bl=36308,Dl=36311,nr=3553,ir=34067,sn=32879,or=35866,w={};function ro(e,t){return w[t].bindPoint}function Ul(e,t){return function(r){e.uniform1f(t,r)}}function Ll(e,t){return function(r){e.uniform1fv(t,r)}}function zl(e,t){return function(r){e.uniform2fv(t,r)}}function Nl(e,t){return function(r){e.uniform3fv(t,r)}}function $l(e,t){return function(r){e.uniform4fv(t,r)}}function no(e,t){return function(r){e.uniform1i(t,r)}}function io(e,t){return function(r){e.uniform1iv(t,r)}}function oo(e,t){return function(r){e.uniform2iv(t,r)}}function so(e,t){return function(r){e.uniform3iv(t,r)}}function ao(e,t){return function(r){e.uniform4iv(t,r)}}function Wl(e,t){return function(r){e.uniform1ui(t,r)}}function Gl(e,t){return function(r){e.uniform1uiv(t,r)}}function Vl(e,t){return function(r){e.uniform2uiv(t,r)}}function Hl(e,t){return function(r){e.uniform3uiv(t,r)}}function jl(e,t){return function(r){e.uniform4uiv(t,r)}}function Yl(e,t){return function(r){e.uniformMatrix2fv(t,!1,r)}}function Ql(e,t){return function(r){e.uniformMatrix3fv(t,!1,r)}}function ql(e,t){return function(r){e.uniformMatrix4fv(t,!1,r)}}function Xl(e,t){return function(r){e.uniformMatrix2x3fv(t,!1,r)}}function Kl(e,t){return function(r){e.uniformMatrix3x2fv(t,!1,r)}}function Jl(e,t){return function(r){e.uniformMatrix2x4fv(t,!1,r)}}function Zl(e,t){return function(r){e.uniformMatrix4x2fv(t,!1,r)}}function ef(e,t){return function(r){e.uniformMatrix3x4fv(t,!1,r)}}function tf(e,t){return function(r){e.uniformMatrix4x3fv(t,!1,r)}}function D(e,t,r,n){const i=ro(e,t);return rt(e)?function(t){let o,s;!t||Xr(e,t)?(o=t,s=null):(o=t.texture,s=t.sampler),e.uniform1i(n,r),e.activeTexture(Kt+r),e.bindTexture(i,o),e.bindSampler(r,s)}:function(t){e.uniform1i(n,r),e.activeTexture(Kt+r),e.bindTexture(i,t)}}function U(e,t,r,n,i){const o=ro(e,t),s=new Int32Array(i);for(let e=0;e<i;++e)s[e]=r+e;return rt(e)?function(t){e.uniform1iv(n,s),t.forEach(function(t,n){let i,a;e.activeTexture(Kt+s[n]),!t||Xr(e,t)?(i=t,a=null):(i=t.texture,a=t.sampler),e.bindSampler(r,a),e.bindTexture(o,i)})}:function(t){e.uniform1iv(n,s),t.forEach(function(t,r){e.activeTexture(Kt+s[r]),e.bindTexture(o,t)})}}function sr(e,t){return function(r){if(r.value)switch(e.disableVertexAttribArray(t),r.value.length){case 4:e.vertexAttrib4fv(t,r.value);break;case 3:e.vertexAttrib3fv(t,r.value);break;case 2:e.vertexAttrib2fv(t,r.value);break;case 1:e.vertexAttrib1fv(t,r.value);break;default:throw new Error("the length of a float constant value must be between 1 and 4!")}else e.bindBuffer(tr,r.buffer),e.enableVertexAttribArray(t),e.vertexAttribPointer(t,r.numComponents||r.size,r.type||rr,r.normalize||!1,r.stride||0,r.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,r.divisor||0)}}function ue(e,t){return function(r){if(r.value){if(e.disableVertexAttribArray(t),4!==r.value.length)throw new Error("The length of an integer constant value must be 4!");e.vertexAttrib4iv(t,r.value)}else e.bindBuffer(tr,r.buffer),e.enableVertexAttribArray(t),e.vertexAttribIPointer(t,r.numComponents||r.size,r.type||nn,r.stride||0,r.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,r.divisor||0)}}function ar(e,t){return function(r){if(r.value){if(e.disableVertexAttribArray(t),4!==r.value.length)throw new Error("The length of an unsigned integer constant value must be 4!");e.vertexAttrib4uiv(t,r.value)}else e.bindBuffer(tr,r.buffer),e.enableVertexAttribArray(t),e.vertexAttribIPointer(t,r.numComponents||r.size,r.type||on,r.stride||0,r.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,r.divisor||0)}}function an(e,t,r){const n=r.size,i=r.count;return function(r){e.bindBuffer(tr,r.buffer);const o=r.size||r.numComponents||n,s=o/i,a=r.type||rr,c=w[a].size*o,u=r.normalize||!1,l=r.offset||0,f=c/i;for(let n=0;n<i;++n)e.enableVertexAttribArray(t+n),e.vertexAttribPointer(t+n,s,a,u,c,l+f*n),e.vertexAttribDivisor&&e.vertexAttribDivisor(t+n,r.divisor||0)}}w[rr]={Type:Float32Array,size:4,setter:Ul,arraySetter:Ll},w[Ni]={Type:Float32Array,size:8,setter:zl,cols:2},w[$i]={Type:Float32Array,size:12,setter:Nl,cols:3},w[Wi]={Type:Float32Array,size:16,setter:$l,cols:4},w[nn]={Type:Int32Array,size:4,setter:no,arraySetter:io},w[Gi]={Type:Int32Array,size:8,setter:oo,cols:2},w[Vi]={Type:Int32Array,size:12,setter:so,cols:3},w[Hi]={Type:Int32Array,size:16,setter:ao,cols:4},w[on]={Type:Uint32Array,size:4,setter:Wl,arraySetter:Gl},w[Zi]={Type:Uint32Array,size:8,setter:Vl,cols:2},w[eo]={Type:Uint32Array,size:12,setter:Hl,cols:3},w[to]={Type:Uint32Array,size:16,setter:jl,cols:4},w[ji]={Type:Uint32Array,size:4,setter:no,arraySetter:io},w[Yi]={Type:Uint32Array,size:8,setter:oo,cols:2},w[Qi]={Type:Uint32Array,size:12,setter:so,cols:3},w[qi]={Type:Uint32Array,size:16,setter:ao,cols:4},w[Xi]={Type:Float32Array,size:32,setter:Yl,rows:2,cols:2},w[Ki]={Type:Float32Array,size:48,setter:Ql,rows:3,cols:3},w[Ji]={Type:Float32Array,size:64,setter:ql,rows:4,cols:4},w[xl]={Type:Float32Array,size:32,setter:Xl,rows:2,cols:3},w[vl]={Type:Float32Array,size:32,setter:Jl,rows:2,cols:4},w[_l]={Type:Float32Array,size:48,setter:Kl,rows:3,cols:2},w[El]={Type:Float32Array,size:48,setter:ef,rows:3,cols:4},w[Al]={Type:Float32Array,size:64,setter:Zl,rows:4,cols:2},w[Tl]={Type:Float32Array,size:64,setter:tf,rows:4,cols:3},w[gl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:nr},w[yl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:ir},w[bl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:sn},w[wl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:nr},w[Sl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:or},w[Il]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:or},w[Rl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:ir},w[kl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:nr},w[Pl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:sn},w[Fl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:ir},w[Cl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:or},w[Ol]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:nr},w[Ml]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:sn},w[Bl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:ir},w[Dl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:or};const I={};I[rr]={size:4,setter:sr},I[Ni]={size:8,setter:sr},I[$i]={size:12,setter:sr},I[Wi]={size:16,setter:sr},I[nn]={size:4,setter:ue},I[Gi]={size:8,setter:ue},I[Vi]={size:12,setter:ue},I[Hi]={size:16,setter:ue},I[on]={size:4,setter:ar},I[Zi]={size:8,setter:ar},I[eo]={size:12,setter:ar},I[to]={size:16,setter:ar},I[ji]={size:4,setter:ue},I[Yi]={size:8,setter:ue},I[Qi]={size:12,setter:ue},I[qi]={size:16,setter:ue},I[Xi]={size:4,setter:an,count:2},I[Ki]={size:9,setter:an,count:3},I[Ji]={size:16,setter:an,count:4};const rf=/ERROR:\s*\d+:(\d+)/gi;function nf(e,t="",r=0){const n=[...t.matchAll(rf)],i=new Map(n.map((e,r)=>{const i=parseInt(e[1]),o=n[r+1],s=o?o.index:t.length;return[i-1,t.substring(e.index,s)]}));return e.split("\n").map((e,t)=>{const n=i.get(t);return`${t+1+r}: ${e}${n?`\n\n^^^ ${n}`:""}`}).join("\n")}const Zn=/^[ \t]*\n/;function co(e){let t=0;return Zn.test(e)&&(t=1,e=e.replace(Zn,"")),{lineOffset:t,shaderSource:e}}function of(e,t){return e.errorCallback(t),e.callback&&setTimeout(()=>{e.callback(`${t}\n${e.errors.join("\n")}`)}),null}function sf(e,t,r,n){if(n=n||rn,!e.getShaderParameter(r,il)){const i=e.getShaderInfoLog(r),{lineOffset:o,shaderSource:s}=co(e.getShaderSource(r)),a=`${nf(s,i,o)}\nError compiling ${Si(e,t)}: ${i}`;return n(a),a}return""}function cn(e,t,r){let n,i,o;if("function"==typeof t&&(r=t,t=void 0),"function"==typeof e)r=e,e=void 0;else if(e&&!Array.isArray(e)){const t=e;r=t.errorCallback,e=t.attribLocations,n=t.transformFeedbackVaryings,i=t.transformFeedbackMode,o=t.callback}const s=r||rn,a=[],c={errorCallback(e,...t){a.push(e),s(e,...t)},transformFeedbackVaryings:n,transformFeedbackMode:i,callback:o,errors:a};{let r={};Array.isArray(e)?e.forEach(function(e,n){r[e]=t?t[n]:n}):r=e||{},c.attribLocations=r}return c}const af=["VERTEX_SHADER","FRAGMENT_SHADER"];function cf(e,t){return t.indexOf("frag")>=0?sl:t.indexOf("vert")>=0?al:void 0}function uf(e,t,r){const n=e.getAttachedShaders(t);for(const t of n)r.has(t)&&e.deleteShader(t);e.deleteProgram(t)}const lf=(e=0)=>new Promise(t=>setTimeout(t,e));function ff(e,t,r){const n=e.createProgram(),{attribLocations:i,transformFeedbackVaryings:o,transformFeedbackMode:s}=cn(r);for(let r=0;r<t.length;++r){let i=t[r];if("string"==typeof i){const t=Li(i),o=t?t.text:i;let s=e[af[r]];t&&t.type&&(s=cf(e,t.type)||s),i=e.createShader(s),e.shaderSource(i,co(o).shaderSource),e.compileShader(i),e.attachShader(n,i)}}Object.entries(i).forEach(([t,r])=>e.bindAttribLocation(n,r,t));{let t=o;t&&(t.attribs&&(t=t.attribs),Array.isArray(t)||(t=Object.keys(t)),e.transformFeedbackVaryings(n,t,s||cl))}return e.linkProgram(n),n}function df(e,t,r,n,i){const o=cn(r,n,i),s=new Set(t),a=ff(e,t,o);function c(e,t){const r=mf(e,t,o.errorCallback);return r&&uf(e,t,s),r}if(!o.callback)return c(e,a)?void 0:a;hf(e,a).then(()=>{const t=c(e,a);o.callback(t,t?void 0:a)})}async function hf(e,t){const r=e.getExtension("KHR_parallel_shader_compile"),n=r?(e,t)=>e.getProgramParameter(t,r.COMPLETION_STATUS_KHR):()=>!0;let i=0;do{await lf(i),i=1e3/60}while(!n(e,t))}function mf(e,t,r){if(r=r||rn,!e.getProgramParameter(t,ol)){const n=e.getProgramInfoLog(t);r(`Error in program linking: ${n}`);return`${n}\n${e.getAttachedShaders(t).map(t=>sf(e,e.getShaderParameter(t,e.SHADER_TYPE),t,r)).filter(e=>e).join("\n")}`}}function pf(e,t,r,n,i){return df(e,t,r,n,i)}function uo(e){const t=e.name;return t.startsWith("gl_")||t.startsWith("webgl_")}const gf=/(\.|\[|]|\w+)/g,yf=e=>e>="0"&&e<="9";function bf(e,t,r,n){const i=e.split(gf).filter(e=>""!==e);let o=0,s="";for(;;){const e=i[o++];s+=e;const a=yf(e[0]),c=a?parseInt(e):e;if(a&&(s+=i[o++]),o===i.length){r[c]=t;break}{const e=i[o++],t="["===e,a=r[c]||(t?[]:{});r[c]=a,r=a,n[s]=n[s]||function(e){return function(t){lo(e,t)}}(a),s+=e}}}function wf(e,t){let r=0;function n(t,n,i){const o=n.name.endsWith("[0]"),s=n.type,a=w[s];if(!a)throw new Error(`unknown type: 0x${s.toString(16)}`);let c;if(a.bindPoint){const t=r;r+=n.size,c=o?a.arraySetter(e,s,t,i,n.size):a.setter(e,s,t,i,n.size)}else c=a.arraySetter&&o?a.arraySetter(e,i):a.setter(e,i);return c.location=i,c}const i={},o={},s=e.getProgramParameter(t,zi);for(let r=0;r<s;++r){const s=e.getActiveUniform(t,r);if(uo(s))continue;let a=s.name;a.endsWith("[0]")&&(a=a.substr(0,a.length-3));const c=e.getUniformLocation(t,s.name);if(c){const e=n(0,s,c);i[a]=e,bf(a,e,o,i)}}return i}function xf(e,t){const r={},n=e.getProgramParameter(t,ll);for(let i=0;i<n;++i){const n=e.getTransformFeedbackVarying(t,i);r[n.name]={index:i,type:n.type,size:n.size}}return r}function vf(e,t){const r=e.getProgramParameter(t,zi),n=[],i=[];for(let o=0;o<r;++o){i.push(o),n.push({});const r=e.getActiveUniform(t,o);n[o].name=r.name}[["UNIFORM_TYPE","type"],["UNIFORM_SIZE","size"],["UNIFORM_BLOCK_INDEX","blockNdx"],["UNIFORM_OFFSET","offset"]].forEach(function(r){const o=r[0],s=r[1];e.getActiveUniforms(t,i,e[o]).forEach(function(e,t){n[t][s]=e})});const o={},s=e.getProgramParameter(t,fl);for(let r=0;r<s;++r){const n=e.getActiveUniformBlockName(t,r),i={index:e.getUniformBlockIndex(t,n),usedByVertexShader:e.getActiveUniformBlockParameter(t,r,dl),usedByFragmentShader:e.getActiveUniformBlockParameter(t,r,hl),size:e.getActiveUniformBlockParameter(t,r,ml),uniformIndices:e.getActiveUniformBlockParameter(t,r,pl)};i.used=i.usedByVertexShader||i.usedByFragmentShader,o[n]=i}return{blockSpecs:o,uniformData:n}}function lo(e,t){for(const r in t){const n=e[r];"function"==typeof n?n(t[r]):lo(e[r],t[r])}}function fo(e,...t){const r=e.uniformSetters||e,n=t.length;for(let e=0;e<n;++e){const n=t[e];if(Array.isArray(n)){const e=n.length;for(let t=0;t<e;++t)fo(r,n[t])}else for(const e in n){const t=r[e];t&&t(n[e])}}}function _f(e,t){const r={},n=e.getProgramParameter(t,ul);for(let i=0;i<n;++i){const n=e.getActiveAttrib(t,i);if(uo(n))continue;const o=e.getAttribLocation(t,n.name),s=I[n.type],a=s.setter(e,o,s);a.location=o,r[n.name]=a}return r}function Ef(e,t){for(const r in t){const n=e[r];n&&n(t[r])}}function Af(e,t,r){r.vertexArrayObject?e.bindVertexArray(r.vertexArrayObject):(Ef(t.attribSetters||t,r.attribs),r.indices&&e.bindBuffer(nl,r.indices))}function ei(e,t){const r={program:t,uniformSetters:wf(e,t),attribSetters:_f(e,t)};return rt(e)&&(r.uniformBlockSpec=vf(e,t),r.transformFeedbackInfo=xf(e,t)),r}const Tf=/\s|{|}|;/;function Sf(e,t,r,n,i){const o=cn(r,n,i),s=[];if(t=t.map(function(e){if(!Tf.test(e)){const t=Li(e);if(t)e=t.text;else{const t=`no element with id: ${e}`;o.errorCallback(t),s.push(t)}}return e}),s.length)return of(o,"");const a=o.callback;a&&(o.callback=(t,r)=>{a(t,t?void 0:ei(e,r))});const c=pf(e,t,o);return c?ei(e,c):null}const If=4,ti=5123;function Rf(e,t,r,n,i,o){r=void 0===r?4:r;const s=t.indices,a=t.elementType,c=void 0===n?t.numElements:n;i=void 0===i?0:i,a||s?void 0!==o?e.drawElementsInstanced(r,c,void 0===a?ti:t.elementType,i,o):e.drawElements(r,c,void 0===a?ti:t.elementType,i):void 0!==o?e.drawArraysInstanced(r,i,c,o):e.drawArrays(r,i,c)}const ho=36160,At=36161,kf=3553,Pf=5121,Ff=6402,Cf=6408,Of=33190,Mf=36012,Bf=35056,Df=36013,Uf=32854,Lf=32855,zf=36194,mo=33189,po=6401,go=36168,un=34041,Fr=36064,cr=36096,yo=36128,ln=33306,Cr=33071,Or=9729,Nf=[{format:Cf,type:Pf,min:Or,wrap:Cr},{format:un}],V={};function $f(e,t){return V[e]||V[t]}V[un]=ln,V[po]=yo,V[go]=yo,V[Ff]=cr,V[mo]=cr,V[Of]=cr,V[Mf]=cr,V[Bf]=ln,V[Df]=ln;const le={};function Wf(e){return le[e]}le[Uf]=!0,le[Lf]=!0,le[zf]=!0,le[un]=!0,le[mo]=!0,le[po]=!0,le[go]=!0;const Gf=32;function Vf(e){return e>=Fr&&e<36096}function ri(e,t,r,n){const i=ho,o=e.createFramebuffer();e.bindFramebuffer(i,o),r=r||e.drawingBufferWidth,n=n||e.drawingBufferHeight;const s=[],a={framebuffer:o,attachments:[],width:r,height:n};return(t=t||Nf).forEach(function(t,o){let c=t.attachment;const u=t.samples,l=t.format;let f=t.attachmentPoint||$f(l,t.internalFormat);if(f||(f=Fr+o),Vf(f)&&s.push(f),!c)if(void 0!==u||Wf(l))c=e.createRenderbuffer(),e.bindRenderbuffer(At,c),u>1?e.renderbufferStorageMultisample(At,u,l,r,n):e.renderbufferStorage(At,l,r,n);else{const i=Object.assign({},t);i.width=r,i.height=n,void 0===i.auto&&(i.auto=!1,i.min=i.min||i.minMag||Or,i.mag=i.mag||i.minMag||Or,i.wrapS=i.wrapS||i.wrap||Cr,i.wrapT=i.wrapT||i.wrap||Cr),c=Ui(e,i)}if(Ja(e,c))e.framebufferRenderbuffer(i,f,At,c);else{if(!Xr(e,c))throw new Error("unknown attachment type");void 0!==t.layer?e.framebufferTextureLayer(i,f,c,t.level||0,t.layer):e.framebufferTexture2D(i,f,t.target||kf,c,t.level||0)}a.attachments.push(c)}),e.drawBuffers&&e.drawBuffers(s),a}function Hf(e,t,r){r=r||ho,t?(e.bindFramebuffer(r,t.framebuffer),e.viewport(0,0,t.width,t.height)):(e.bindFramebuffer(r,null),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight))}function B(e,t){return()=>t instanceof WebGLTexture?t:Ui(e,{src:t,wrap:e.CLAMP_TO_EDGE})}const Ue=2;class ot{constructor(e){this.id="_";const{context:t,width:r,height:n}=e;this.context=t,this.options=e;const i=this.buildDefines();this.programInfo=Sf(this.context,[i+this.getVertexShader(),i+this.getFragmentShader()]),this.bufferInfo=_c(this.context,this.getBuffers()),this.fbi=ri(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],r,n),this.output=this.fbi.attachments[0]}resizeOutput(e,t){this.fbi=ri(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 r in t)e+=`#define ${r} ${t[r].toFixed(1)}\n`;return e}run(e){this.profiler?.pushContext(`[${this.id}] PROG : ${this.constructor.name}`),this.profiler?.pushContext(`[${this.id}] UNIFORMS`);for(const t in e)"function"==typeof e[t]&&(this.profiler?.pushContext(`[${this.id}] UNI : ${t}`),e[t]=e[t](),this.profiler?.popContext(`[${this.id}] UNI : ${t}`));this.profiler?.popContext(`[${this.id}] UNIFORMS`);const t=Date.now();let r=0;this.lastRun&&(r=(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),Af(this.context,this.programInfo,this.bufferInfo),fo(this.programInfo,{delta:r,canvas:[this.context.canvas.width,this.context.canvas.height],...e}),Hf(this.context,this.options.disableFramebuffer?null:this.fbi),Rf(this.context,this.bufferInfo),this.profiler?.popContext(`[${this.id}] PROG : ${this.constructor.name}`)}setProfiler(e){this.profiler=e}}const jf="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",Yf="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 fn extends ot{getFragmentShader(){return jf}getVertexShader(){return Yf}}class dn{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 r of this.steps)r.preventResize||r.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 hn extends dn{constructor(){super(...arguments),this.preciseMaskEnabled=!1}}class bo extends hn{constructor(e){super(),this.context=e,this.preciseMaskEnabled=!0;const t={context:e,height:e.canvas.height,width:e.canvas.width},r=new fn({...t,disableFramebuffer:!0});this.addStep({program:r,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 Qf="precision mediump float;\n\nvarying vec2 _texture_coord;\nuniform sampler2D texture;\n\nvoid main() { gl_FragColor = texture2D(texture, _texture_coord); }\n",qf="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 Xf extends ot{getFragmentShader(){return Qf}getVertexShader(){return qf}}class Kf extends dn{constructor(e,t,r){super(),this.context=e;const n={context:e,height:r,width:t};this.addStep({program:new Xf({...n,disableFramebuffer:!0}),getUniforms:()=>({texture:B(e,this.inputImage),invert_y:!0})})}setData(e){this.inputImage=e}}async function wo(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const Jf="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",Zf="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";var mn=(e=>(e[e.LINEAR=0]="LINEAR",e[e.GAUSSIAN=1]="GAUSSIAN",e))(mn||{});class xo extends ot{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return Jf+this.createLoopFunction()}getVertexShader(){return Zf}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 }`}}const ed="#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}",td="#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 rd extends ot{getFragmentShader(){return ed}getVertexShader(){return td}}class nd extends dn{constructor(e,t,r){super(),this.context=e;const n={context:e,height:r,width:t},i=new xo({...n,radius:1,type:mn.GAUSSIAN});this.jointBilateral=new rd(n),this.addStep({program:i,getUniforms:()=>({inputs:B(e,this.inputMask)})}),this.addStep({program:this.jointBilateral,getUniforms:()=>{const t=this.inputImage?.width??1,r=this.inputImage?.height??1;this.inputMask,this.inputMask;const n=Math.max(1,.66*Math.sqrt(3)),i=1/t,o=1/r;return{input_frame:B(e,this.inputImage),segmentation_mask:B(e,this.inputMask),texel_size:[i,o],step:n,radius:3,offset:n>1?.5*n:0,sigma_texel:3*Math.max(i,o),sigma_color:3}}}),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 vo=(e=>(e.PUSH="PUSH",e.POP="POP",e))(vo||{});class id{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(e=>this.resolveQuery(e)))).filter(e=>e);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)){if(!this.context.getParameter(this.extension.GPU_DISJOINT_EXT))return{...e,duration:this.context.getQueryParameter(e.query,this.context.QUERY_RESULT),timestamp:0};console.log("Disjointed query",e)}else console.log("Unawaitable query",e)}async awaitQueryAvailable(e){for(let t=0;t<10;++t){if(this.context.getQueryParameter(e.query,this.context.QUERY_RESULT_AVAILABLE))return e;await wo(200)}}}class ur{constructor(){this.previousImageWidth=0,this.previousImageHeight=0,this.previousMaskWidth=2,this.previousMaskHeight=2,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 nd(this.context,2,2)}enablePostProcessing(){this.postProcessingEnabled=!0}disablePostProcessing(){this.postProcessingEnabled=!1}async profileWebgl(e){const t=new id(this.context);return this.profiler=t,t.start(),await wo(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 r="renderer";this.profiler?.pushContext(r),this.improveMask.setProfiler(this.profiler),this.pipeline.setProfiler(this.profiler);const n=await createImageBitmap(t);let i=n;return this.postProcessingEnabled&&(this.improveMask.setData(e,n),this.improveMask.run(),i=this.improveMask.output),this.pipeline.setData(e,i),await this.pipeline.run(),this.profiler?.popContext(r),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 _o extends ur{constructor(){super(),this.pipeline=new bo(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 Kf(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 od extends _o{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 ni{blurBackground(e){return new za(e)}blurSilhouette(e){return new Na(e)}imageBackground(){return new $a}videoBackground(){return new od}}const sd="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",ad="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 cd extends ot{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return sd+this.createLoopFunction()}getVertexShader(){return ad}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 ud=10,ld=2,fd=8;class dd extends hn{constructor(e,t){super(),this.context=e,this.radius=t;const r={context:e,height:e.canvas.height,width:e.canvas.width};this.blur=new cd({...r,radius:t,...this.getBlurTextureSize(e.canvas.width,e.canvas.height)});const n=new fn({...r,disableFramebuffer:!0});this.addStep({program:this.blur,preventResize:!0,getUniforms:()=>({texture:B(e,this.inputImage),mask:B(e,this.inputMask)})}),this.addStep({program:n,getUniforms:()=>({background:B(e,this.blur.output),foreground:B(e,this.inputImage),threshold:B(e,this.inputMask)})})}getBlurTextureSize(e,t){const r=this.radius>10?8:2;return{width:Math.max(2,e/r),height:Math.max(2,t/r)}}setData(e,t){this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t);const r=this.getBlurTextureSize(e,t);this.blur.resizeOutput(r.width,r.height)}}class hd extends ur{constructor(e){super(),this.pipeline=new dd(this.context,e),this.disablePostProcessing()}}class md extends hn{constructor(e,t){super(),this.context=e;const r={context:e,height:e.canvas.height,width:e.canvas.width},n=new xo({...r,radius:t,type:mn.GAUSSIAN}),i=new fn({...r,disableFramebuffer:!0});this.addStep({program:n,getUniforms:()=>({texture:B(e,this.inputImage)})}),this.addStep({program:i,getUniforms:()=>({background:B(e,this.inputImage),foreground:B(e,n.output),threshold:B(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}class pd extends ur{constructor(e){super(),this.pipeline=new md(this.context,e),this.disablePostProcessing()}}class gd extends bo{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 yd extends ur{constructor(){super(),this.pipeline=new gd(this.context)}setBackgroundVideo(e){this.pipeline.reader=e}}class ii{blurBackground(e){return new hd(e)}blurSilhouette(e){return new pd(e)}imageBackground(){return new _o}videoBackground(){return new yd}}class bd{constructor(e){switch(e){case Mt.CANVAS:this.factory=new ni;break;case Mt.WEBGL:this.factory=new ii;break;default:const e=fi();this.factory=e.supported?new ii:new ni}}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 wd{setBackgroundOptions(e){this.renderer&&this.renderer.destroy();const t=new bd(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 r=t.videoBackground();this.backgroundVideo&&r.setBackgroundVideo(this.backgroundVideo),this.renderer=r;break;case"VirtualBackground":const n=t.imageBackground();this.backgroundImage&&n.setBackgroundImage(this.backgroundImage),this.renderer=n;break;default:throw`Unknown rendering type [${e.transformerType}]`}e.renderingOptions?.type===Mt.WEBGL&&(e.renderingOptions.selfieSegmentationType===Ar.PRECISE?this.renderer.enablePostProcessing():e.renderingOptions.selfieSegmentationType===Ar.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=It.Low){switch(e){case It.Low:return 5;case It.High:return 12}return e}async profile(e){return this.renderer?.profileWebgl(e)??[]}}var xd=function(){var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(t){var r,n,i=typeof(t=t||{})<"u"?t:{};i.ready=new Promise(function(e,t){r=e,n=t});var o,s={};for(o in i)i.hasOwnProperty(o)&&(s[o]=i[o]);var a="./this.program",c=function(e,t){throw t},u="";typeof document<"u"&&document.currentScript&&(u=document.currentScript.src),e&&(u=e),u=0!==u.indexOf("blob:")?u.substr(0,u.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var l,f=i.print||console.log.bind(console),h=i.printErr||console.warn.bind(console);for(o in s)s.hasOwnProperty(o)&&(i[o]=s[o]);s=null,i.arguments&&i.arguments,i.thisProgram&&(a=i.thisProgram),i.quit&&(c=i.quit),i.wasmBinary&&(l=i.wasmBinary),i.noExitRuntime,"object"!=typeof WebAssembly&&O("no native wasm support detected");var d,m,p,g,y,b=!1,w=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function v(e,t,r){for(var n=t+r,i=t;e[i]&&!(i>=n);)++i;if(i-t>16&&e.subarray&&w)return w.decode(e.subarray(t,i));for(var o="";t<i;){var s=e[t++];if(128&s){var a=63&e[t++];if(192!=(224&s)){var c=63&e[t++];if((s=224==(240&s)?(15&s)<<12|a<<6|c:(7&s)<<18|a<<12|c<<6|63&e[t++])<65536)o+=String.fromCharCode(s);else{var u=s-65536;o+=String.fromCharCode(55296|u>>10,56320|1023&u)}}else o+=String.fromCharCode((31&s)<<6|a)}else o+=String.fromCharCode(s)}return o}function x(e,t){return e?v(g,e,t):""}function _(e,t){return e%t>0&&(e+=t-e%t),e}function k(e){m=e,i.HEAP8=p=new Int8Array(e),i.HEAP16=new Int16Array(e),i.HEAP32=y=new Int32Array(e),i.HEAPU8=g=new Uint8Array(e),i.HEAPU16=new Uint16Array(e),i.HEAPU32=new Uint32Array(e),i.HEAPF32=new Float32Array(e),i.HEAPF64=new Float64Array(e)}i.INITIAL_MEMORY;var A,E=[],I=[],S=[];function T(e){E.unshift(e)}function P(e){S.unshift(e)}var F=0,R=null;function O(e){i.onAbort&&i.onAbort(e),h(e="Aborted("+e+")"),b=!0,e+=". Build with -s ASSERTIONS=1 for more info.";var t=new WebAssembly.RuntimeError(e);throw n(t),t}i.preloadedImages={},i.preloadedAudios={};var C,M,z;function B(e){return e.startsWith("data:application/octet-stream;base64,")}function D(e){try{if(e==C&&l)return new Uint8Array(l);throw"both async and sync fetching of the wasm failed"}catch(e){O(e)}}function U(e){for(;e.length>0;){var t=e.shift();if("function"!=typeof t){var r=t.func;"number"==typeof r?void 0===t.arg?A.get(r)():A.get(r)(t.arg):r(void 0===t.arg?null:t.arg)}else t(i)}}B(C="tflite-simd.wasm")||(M=C,C=i.locateFile?i.locateFile(M,u):u+M),z=function(){return performance.now()};function L(e){try{return d.grow(e-m.byteLength+65535>>>16),k(d.buffer),1}catch{}}var N={};function W(){if(!W.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:a||"./this.program"};for(var t in N)void 0===N[t]?delete e[t]:e[t]=N[t];var r=[];for(var t in e)r.push(t+"="+e[t]);W.strings=r}return W.strings}var j={mappings:{},buffers:[null,[],[]],printChar:function(e,t){var r=j.buffers[e];0===t||10===t?((1===e?f:h)(v(r,0)),r.length=0):r.push(t)},varargs:void 0,get:function(){return j.varargs+=4,y[j.varargs-4>>2]},getStr:function(e){return x(e)},get64:function(e,t){return e}};var V={a:function(e,t,r,n){O("Assertion failed: "+x(e)+", at: "+[t?x(t):"unknown filename",r,n?x(n):"unknown function"])},e:function(e,t){O("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},d:function(e,t){O("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},b:function(){O("")},n:function(e,t){var r;if(0===e)r=Date.now();else{if(1!==e&&4!==e)return function(e){y[G()>>2]=e}(28),-1;r=z()}return y[t>>2]=r/1e3|0,y[t+4>>2]=r%1e3*1e3*1e3|0,0},h:function(){return 2147483648},l:function(e,t,r){g.copyWithin(e,t,t+r)},m:function(e){var t=g.length,r=2147483648;if((e>>>=0)>r)return!1;for(var n=1;n<=4;n*=2){var i=t*(1+.2/n);if(i=Math.min(i,e+100663296),L(Math.min(r,_(Math.max(e,i),65536))))return!0}return!1},p:function(e){for(var t=z();z()-t<e;);},f:function(e,t){var r=0;return W().forEach(function(n,i){var o=t+r;y[e+4*i>>2]=o,function(e,t){for(var r=0;r<e.length;++r)p[0|t++]=e.charCodeAt(r);p[0|t]=0}(n,o),r+=n.length+1}),0},g:function(e,t){var r=W();y[e>>2]=r.length;var n=0;return r.forEach(function(e){n+=e.length+1}),y[t>>2]=n,0},j:function(e){!function(e){!function(e){c(e,new H(e))}(e)}(e)},i:function(e){return 0},k:function(e,t,r,n,i){},c:function(e,t,r,n){for(var i=0,o=0;o<r;o++){for(var s=y[t+8*o>>2],a=y[t+(8*o+4)>>2],c=0;c<a;c++)j.printChar(e,g[s+c]);i+=a}return y[n>>2]=i,0},o:function e(t,r){e.randomDevice||(e.randomDevice=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return function(){return crypto.getRandomValues(e),e[0]}}return function(){O("randomDevice")}}());for(var n=0;n<r;n++)p[t+n|0]=e.randomDevice();return 0}};(function(){var e={a:V};function t(e,t){var r=e.exports;i.asm=r,k((d=i.asm.q).buffer),A=i.asm.E,function(e){I.unshift(e)}(i.asm.r),function(){if(F--,i.monitorRunDependencies&&i.monitorRunDependencies(F),0==F&&R){var e=R;R=null,e()}}()}function r(e){t(e.instance)}function o(t){return(l||"function"!=typeof fetch?Promise.resolve().then(function(){return D(C)}):fetch(C,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load wasm binary file at '"+C+"'";return e.arrayBuffer()}).catch(function(){return D(C)})).then(function(t){return WebAssembly.instantiate(t,e)}).then(function(e){return e}).then(t,function(e){h("failed to asynchronously prepare wasm: "+e),O(e)})}if(F++,i.monitorRunDependencies&&i.monitorRunDependencies(F),i.instantiateWasm)try{return i.instantiateWasm(e,t)}catch(e){return h("Module.instantiateWasm callback failed with error: "+e),!1}(l||"function"!=typeof WebAssembly.instantiateStreaming||B(C)||"function"!=typeof fetch?o(r):fetch(C,{credentials:"same-origin"}).then(function(t){return WebAssembly.instantiateStreaming(t,e).then(r,function(e){return h("wasm streaming compile failed: "+e),h("falling back to ArrayBuffer instantiation"),o(r)})})).catch(n)})(),i.___wasm_call_ctors=function(){return(i.___wasm_call_ctors=i.asm.r).apply(null,arguments)},i._getModelBufferMemoryOffset=function(){return(i._getModelBufferMemoryOffset=i.asm.s).apply(null,arguments)},i._getInputMemoryOffset=function(){return(i._getInputMemoryOffset=i.asm.t).apply(null,arguments)},i._getInputHeight=function(){return(i._getInputHeight=i.asm.u).apply(null,arguments)},i._getInputWidth=function(){return(i._getInputWidth=i.asm.v).apply(null,arguments)},i._getInputChannelCount=function(){return(i._getInputChannelCount=i.asm.w).apply(null,arguments)},i._getOutputMemoryOffset=function(){return(i._getOutputMemoryOffset=i.asm.x).apply(null,arguments)},i._getOutputHeight=function(){return(i._getOutputHeight=i.asm.y).apply(null,arguments)},i._getOutputWidth=function(){return(i._getOutputWidth=i.asm.z).apply(null,arguments)},i._getOutputChannelCount=function(){return(i._getOutputChannelCount=i.asm.A).apply(null,arguments)},i._loadModel=function(){return(i._loadModel=i.asm.B).apply(null,arguments)},i._runInference=function(){return(i._runInference=i.asm.C).apply(null,arguments)},i._isGPUEnabled=function(){return(i._isGPUEnabled=i.asm.D).apply(null,arguments)};var $,G=i.___errno_location=function(){return(G=i.___errno_location=i.asm.F).apply(null,arguments)};function H(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function q(e){function t(){$||($=!0,i.calledRun=!0,!b&&(U(I),r(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for("function"==typeof i.postRun&&(i.postRun=[i.postRun]);i.postRun.length;)P(i.postRun.shift());U(S)}()))}F>0||(function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)T(i.preRun.shift());U(E)}(),F>0)||(i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),t()},1)):t())}if(R=function e(){$||q(),$||(R=e)},i.run=q,i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return q(),t.ready}}();class vd{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 _d="https://d3opqjmqzxf057.cloudfront.net/vonage-tensorflow-wasm/tflite-simd-wasm/1.1.3/",Ed="https://d3opqjmqzxf057.cloudfront.net/ml/selfie_segmentation/4.0.0/selfie_segmentation_landscape.tflite";async function Ad(e=_d,t=Ed){let r=new vd;return new Promise(function(n,i){(async function(){return xd({locateFile:function(t){return e+t}})})().then(e=>{if(null===e)throw console.error("loadTFLite null"),"loadTFLite null";(async function(e){return new Promise(async(n,i)=>{const o=e;if(typeof o>"u")return i("TFLite backend unavailable: wasmSimd");let s=t;console.log("TFLite modelUrl: "+s);try{const e=await(await fetch(s)).arrayBuffer();console.log("Model buffer size:",e.byteLength);const t=o._getModelBufferMemoryOffset();console.log("Model buffer memory offset:",t),console.log("Loading model buffer..."),o.HEAPU8.set(new Uint8Array(e),t);const n=o._loadModel(e.byteLength);if(console.log("Load model result:",n),0!==n)return void i("Cannot load model");r.inputWidth=o._getInputWidth(),r.inputHeight=o._getInputHeight(),r.inputChannelCount=o._getInputChannelCount(),r.inputMemoryOffset=o._getInputMemoryOffset(),console.log("Input memory offset:",r.inputMemoryOffset),console.log("Input height:",r.inputHeight),console.log("Input width:",r.inputWidth),console.log("Input channels:",r.inputChannelCount),r.outputMemoryOffset=o._getOutputMemoryOffset(),r.outputWidth=o._getOutputWidth(),r.outputHeight=o._getOutputHeight(),r.outputChannelCount=o._getOutputChannelCount(),console.log("Output memory offset:",r.outputMemoryOffset),console.log("Output height:",r.outputHeight),console.log("Output width:",r.outputWidth),console.log("Output channels:",r.outputChannelCount),r.selectedTFLite=o}catch(e){return void i(e)}n()})})(e).then(e=>{n(r)}).catch(e=>{console.error("loadTFLiteModel error"),i("loadTFLiteModel error")})}).catch(e=>{console.error("loadTFLite error:",e),i("loadTFLite error:"+e)})})}const Td=.1,Sd=.7,Id="https://d3opqjmqzxf057.cloudfront.net/ml/vonage_selfie_segmenter/float16/v1/vonage_selfie_segmenter.tflite";class Rd{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(){this.ImageSegmenter&&this.wasmFileset?this.imageSegmenter=await this.ImageSegmenter.createFromOptions(this.wasmFileset,{baseOptions:{modelAssetPath:this.modelAssetUriPath,delegate:this.gpuDelegate?"GPU":"CPU"},runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!0}):console.warn("Mediapipe objects not loaded")}async loadMediapipeAssets(e,t){this.modelAssetUriPath=e||Id;const r=t?`${t}/task-vision.js`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/+esm",n=t?`${t}/wasm`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/wasm",{FilesetResolver:i,ImageSegmenter:o}=await import(r);this.ImageSegmenter=o,this.wasmFileset=await i.forVisionTasks(n)}async init(e,t,r){!1===r&&(this.gpuDelegate=!1),await this.loadMediapipeAssets(e,t),globalThis.document={},await this.createImageSegmenter()}async process(e){if(!this.imageSegmenter)return void console.warn("ImageSegmenter instance not available");(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 r;try{this.imageSegmenter?.segmentForVideo(this.context.getImageData(0,0,e.width,e.height),t,e=>{r=e.confidenceMasks?.[0]?.getAsFloat32Array()})}catch{return void await this.createImageSegmenter()}if(!r)return;if(!this.previousConfidenceMask)return void(this.previousConfidenceMask=r.slice());const n=r.map((e,t)=>{const r=this.previousConfidenceMask?.[t];return void 0!==r?this.blend(r,e):e}),i=[255,0,0];for(let e=0;e<n?.length;e++){const t=1-n[e];t>Td?(t<Sd?(this.mask.data[4*e]=i[0]*t,this.mask.data[4*e+3]=255*t):(this.mask.data[4*e]=i[0],this.mask.data[4*e+3]=255),this.mask.data[4*e+1]=i[1],this.mask.data[4*e+2]=i[2]):this.mask.data[4*e]=this.mask.data[4*e+1]=this.mask.data[4*e+2]=this.mask.data[4*e+3]=0}return this.previousConfidenceMask=n.slice(),this.mask}isGpuSupported(){return!0}blend(e,t){const r=t-.5,n=r*r;return t+.9*(1-Math.min(1,n*(5.68842+n*(n*(n*(291.309+-624.717*n)-57.8051)-.748699))))*(e-t)}}class kd{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,r){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 Ad(e,t)}async process(e){if(!this.mask||!this.infos)return;const t=this.infos.inputWidth,r=this.infos.inputHeight;this.context.drawImage(e,0,0,e.width,e.height,0,0,t,r);const n=this.context.getImageData(0,0,t,r),i=this.infos.selectedTFLite.HEAPF32;for(let e=0;e<this.pixelCount;e++){const t=this.inputOffset+3*e;i[t]=n.data[4*e]/255,i[t+1]=n.data[4*e+1]/255,i[t+2]=n.data[4*e+2]/255}this.infos.selectedTFLite._runInference();for(let e=0;e<this.pixelCount;e++){const t=this.infos.selectedTFLite.HEAPF32[this.outputOffset+e];this.mask.data[4*e]=this.mask.data[4*e+3]=255*t}return this.mask}isGpuSupported(){return this.infos?.selectedTFLite?._isGPUEnabled()??!1}}class Pd{constructor(){this.reporter=new Ua,this.isEnabled=!0}async init(e,t){!0===t.segmentationOptions?.lightWeightEngine?this.selfieSegmentation=new kd:this.selfieSegmentation=new Rd,this.selfieSegmentation?.init(t.modelAssetUriPath,t.mediapipeBaseAssetsUri,t.segmentationOptions?.gpuSupport),this.backgroundFilter=new wd,this.report({variation:"Create"})}async transform(e,t){if(!this.isEnabled)return t.enqueue(e);let r;const n=e.timestamp??0,i=await createImageBitmap(e),o=await(this.selfieSegmentation?.process(i));o&&(r=await(this.backgroundFilter?.process(i,o))),r||(r=new OffscreenCanvas(i.width,i.height)),e.close(),t.enqueue(new VideoFrame(r,{timestamp:n,alpha:"discard"}))}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:La,action:"MlTransformers",transformerType:this.backgroundOptions?.transformerType,config:JSON.stringify(this.backgroundOptions),...e})}}const pn=class{constructor(){this.backgroundTransformer=new Pd,this.mediaProcessor=new li,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((e,t)=>{this.resolveOnMediaProcessor?(this.resolveOnMediaProcessor({name:e,data:t}),this.resolveOnMediaProcessor=void 0):this.eventsQueue.push({name:e,data:t})})}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 r=this.mediaProcessor.transform(e,t),n=performance.now();return this.frameTransformLatencyMs.push(performance.now()-n),r}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 e=this.frameTransformLatencyMs.reduce((e,t)=>e+t,0)/this.frameTransformLatencyMs.length||0;console.log(`Transform latency average is: ${e} ms`)}setVonageMetadata(e){Os(e)}async profile(e){return JSON.stringify(await this.backgroundTransformer.profile(e))}};ua("ProcessorWorker",pn);let Mr=pn;const Eo='(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\tdata: ${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\tdata: ${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.2",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.2-alpha.1";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||(n=new OffscreenCanvas(s.width,s.height)),e.close(),t.enqueue(new VideoFrame(n,{timestamp:i,alpha:"discard"}))}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-BCFqxflP.js.map\n',oi=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Eo],{type:"text/javascript;charset=utf-8"});function Fd(e){let t;try{if(t=oi&&(self.URL||self.webkitURL).createObjectURL(oi),!t)throw"";const r=new Worker(t,{name:e?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Eo),{name:e?.name})}}const Jt=class e extends et{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":return void await this.destroy()}}}}async startWorker(){!this.config||this.worker||(this.worker=await aa(Mr,Fd),this.isEnabled||await this.worker.disable(),await this.worker.init("worker_"+e.initCount++,this.config),await this.worker.setVonageMetadata(Tt()),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 Nn.createVideoReadable(e.backgroundAssetUri)));break;case"VirtualBackground":await(this.worker?.setVirtualBGImage(await Nn.createImageCanvas(e.backgroundAssetUri)))}await(this.worker?.setBackgroundOptions(e))}};Jt.initCount=0;let Br=Jt;class Cd{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={},r=[];let n=0;for(const i of this.queries){const o=[];for(const r of i)void 0===t[r.name]&&(t[r.name]=e.length,e.push({name:r.name})),o.push({type:r.action==vo.PUSH?"O":"C",frame:t[r.name],at:r.timestamp}),n=Math.max(n,r.timestamp+r.duration);r.push({events:o,type:"evented",name:"GPU Profile",unit:"nanoseconds",startValue:0,endValue:n})}return JSON.stringify({$schema:"https://www.speedscope.app/file-format-schema.json",shared:{frames:e},profiles:r},null,2)}}const gn=class extends et{constructor(e){super(),this.worker=new Br(e),this.connector=new Qs(this.worker),this.worker.onAny((e,t)=>this.emit(e,t))}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(t=>t.profile(e)));return new Cd(t)}static async create(e){const t=new this(e);return this.instances.push(t),t}};gn.instances=[];let Dr=gn;async function Dd(e){return await Dr.create(e)}export{Pd as BackgroundTransformer,qs as BackgroundTransformerType,It as BlurRadius,Ls as ErrorFunction,Er as PipelineInfoData,Mt as RenderingType,Dr as VonageMediaProcessor,Us as WarningType,Ar as WebglSelfieSegmentationType,Dd as createVonageMediaProcessor,Ks as getSupportedBrowserFeatures,Bd as isSupported};
1
+ async function os(){return new Promise(async(e,t)=>{as()||!await ai()&&!si()?t("Your browser does not support the MediaStreamTrack API for Insertable Streams of Media."):e()})}function si(){return void 0!==self.MediaStreamTrackProcessor&&void 0!==self.MediaStreamTrackGenerator||ss()}function ss(){return 0===[self.ReadableStream,self.WritableStream,self.MediaStream,self.OffscreenCanvas,self.VideoFrame,self.AudioContext,self.AudioWorkletNode].filter(e=>void 0===e).length}function as(){const e=navigator.userAgent.toLowerCase();return!(!(navigator.vendor&&navigator.vendor.toLowerCase().indexOf("apple")>-1)||e.indexOf("applewebkit")>-1&&-1===e.indexOf("version"))&&parseInt((e.split(" ").find(e=>e.includes("version/"))??"/0").split("/")[1])<26}function ai(){return new Promise(e=>{new Worker(`data:text/javascript,(${function(){self.postMessage(typeof MediaStreamTrackProcessor<"u"&&typeof VideoTrackGenerator<"u")}.toString()})()`).onmessage=({data:t})=>e(t)})}const ee=new WeakMap,me=new WeakMap,q=new WeakMap,kt=Symbol("anyProducer"),Tn=Promise.resolve(),Rt=Symbol("listenerAdded"),Pt=Symbol("listenerRemoved");let Ft=!1,mr=!1;const Ct=e=>"string"==typeof e||"symbol"==typeof e||"number"==typeof e;function Te(e){if(!Ct(e))throw new TypeError("`eventName` must be a string, symbol, or number")}function ft(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function Se(e,t){const r=me.get(e);if(r.has(t))return r.get(t)}function je(e,t){const r=Ct(t)?t:kt,n=q.get(e);if(n.has(r))return n.get(r)}function cs(e,t,r){const n=q.get(e);if(n.has(t))for(const e of n.get(t))e.enqueue(r);if(n.has(kt)){const e=Promise.all([t,r]);for(const t of n.get(kt))t.enqueue(e)}}function Sn(e,t){t=Array.isArray(t)?t:[t];let r=!1,n=()=>{},i=[];const o={enqueue(e){i.push(e),n()},finish(){r=!0,n()}};for(const r of t){let t=je(e,r);t||(t=new Set,q.get(e).set(r,t)),t.add(o)}return{async next(){return i?0===i.length?r?(i=void 0,this.next()):(await new Promise(e=>{n=e}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(r){i=void 0;for(const r of t){const t=je(e,r);t&&(t.delete(o),0===t.size&&q.get(e).delete(r))}return n(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function In(e){if(void 0===e)return kn;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!kn.includes(t))throw"string"!=typeof t?new TypeError("`methodNames` element must be a string"):new Error(`${t} is not Emittery method`);return e}const Be=e=>e===Rt||e===Pt;function dt(e,t,r){if(Be(t))try{Ft=!0,e.emit(t,r)}finally{Ft=!1}}class J{static mixin(e,t){return t=In(t),r=>{if("function"!=typeof r)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==r.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(r.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new J}),this[e]}});const n=t=>function(...r){return this[e][t](...r)};for(const e of t)Object.defineProperty(r.prototype,e,{enumerable:!1,value:n(e)});return r}}static get isDebugEnabled(){if("object"!=typeof globalThis.process?.env)return mr;const{env:e}=globalThis.process??{env:{}};return"emittery"===e.DEBUG||"*"===e.DEBUG||mr}static set isDebugEnabled(e){mr=e}constructor(e={}){ee.set(this,new Set),me.set(this,new Map),q.set(this,new Map),q.get(this).set(kt,new Set),this.debug=e.debug??{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,r,n)=>{try{n=JSON.stringify(n)}catch{n=`Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`}("symbol"==typeof r||"number"==typeof r)&&(r=r.toString());const i=new Date,o=`${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}.${i.getMilliseconds()}`;console.log(`[${o}][emittery:${e}][${t}] Event Name: ${r}\n\tdata: ${n}`)})}logIfDebugEnabled(e,t,r){(J.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,r)}on(e,t,{signal:r}={}){ft(t),e=Array.isArray(e)?e:[e];for(const r of e){Te(r);let e=Se(this,r);e||(e=new Set,me.get(this).set(r,e)),e.add(t),this.logIfDebugEnabled("subscribe",r,void 0),Be(r)||dt(this,Rt,{eventName:r,listener:t})}const n=()=>{this.off(e,t),r?.removeEventListener("abort",n)};return r?.addEventListener("abort",n,{once:!0}),r?.aborted&&n(),n}off(e,t){ft(t),e=Array.isArray(e)?e:[e];for(const r of e){Te(r);const e=Se(this,r);e&&(e.delete(t),0===e.size&&me.get(this).delete(r)),this.logIfDebugEnabled("unsubscribe",r,void 0),Be(r)||dt(this,Pt,{eventName:r,listener:t})}}once(e,t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("predicate must be a function");let r;const n=new Promise(n=>{r=this.on(e,e=>{t&&!t(e)||(r(),n(e))})});return n.off=r,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Te(t);return Sn(this,e)}async emit(e,t){if(Te(e),Be(e)&&!Ft)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),cs(this,e,t);const r=Se(this,e)??new Set,n=ee.get(this),i=[...r],o=Be(e)?[]:[...n];await Tn,await Promise.all([...i.map(async e=>{if(r.has(e))return e(t)}),...o.map(async r=>{if(n.has(r))return r(e,t)})])}async emitSerial(e,t){if(Te(e),Be(e)&&!Ft)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const r=Se(this,e)??new Set,n=ee.get(this),i=[...r],o=[...n];await Tn;for(const e of i)r.has(e)&&await e(t);for(const r of o)n.has(r)&&await r(e,t)}onAny(e,{signal:t}={}){ft(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),ee.get(this).add(e),dt(this,Rt,{listener:e});const r=()=>{this.offAny(e),t?.removeEventListener("abort",r)};return t?.addEventListener("abort",r,{once:!0}),t?.aborted&&r(),r}anyEvent(){return Sn(this)}offAny(e){ft(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),dt(this,Pt,{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),Ct(t)){const e=Se(this,t);e&&e.clear();const r=je(this,t);if(r){for(const e of r)e.finish();r.clear()}}else{ee.get(this).clear();for(const[e,t]of me.get(this).entries())t.clear(),me.get(this).delete(e);for(const[e,t]of q.get(this).entries()){for(const e of t)e.finish();t.clear(),q.get(this).delete(e)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const r of e)if(Ct(r))t+=ee.get(this).size+(Se(this,r)?.size??0)+(je(this,r)?.size??0)+(je(this)?.size??0);else{void 0!==r&&Te(r),t+=ee.get(this).size;for(const e of me.get(this).values())t+=e.size;for(const e of q.get(this).values())t+=e.size}return t}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=In(t);for(const r of t){if(void 0!==e[r])throw new Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}}const kn=Object.getOwnPropertyNames(J.prototype).filter(e=>"constructor"!==e);Object.defineProperty(J,"listenerAdded",{value:Rt,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(J,"listenerRemoved",{value:Pt,writable:!1,enumerable:!0,configurable:!1});var us=Object.defineProperty,ls=(e,t,r)=>t in e?us(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,fs=(e,t,r)=>(ls(e,t+"",r),r);const ds="hlg.tokbox.com/prod/logging/vcp_webrtc",hs="https://",ms=1e4;let ht;const ps=new Uint8Array(16);function gs(){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(ps)}const F=[];for(let e=0;e<256;++e)F.push((e+256).toString(16).slice(1));function ys(e,t=0){return(F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+"-"+F[e[t+4]]+F[e[t+5]]+"-"+F[e[t+6]]+F[e[t+7]]+"-"+F[e[t+8]]+F[e[t+9]]+"-"+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]).toLowerCase()}const bs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Rn={randomUUID:bs};function ws(e,t,r){if(Rn.randomUUID&&!e)return Rn.randomUUID();const n=(e=e||{}).random||(e.rng||gs)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,ys(n)}function Ur(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[e]||(r[e]=t),r[e]}const ie=Ur("globals",{});var be=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e))(be||{});function ci(e){return[ImageBitmap,ReadableStream,WritableStream].some(t=>e instanceof t)}let xs=0;function vs(e,t,r,n,i){const o=xs++;return e.postMessage({id:o,type:t,functionName:r,args:n},n.filter(e=>ci(e))),new Promise(e=>{i?.set(o,e)})}function Ze(e,t){const{id:r,type:n}=e,i=Array.isArray(t)?t:[t];postMessage({id:r,type:n,result:t},i.filter(e=>ci(e)))}const Pn=Ur("workerized",{});function ui(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function _s(){if(ui())Ze({type:be.GLOBALS_SYNC},ie);else{const e=[];for(const t in Pn){const{worker:r,resolvers:n}=Pn[t].workerContext;r&&e.push(vs(r,be.GLOBALS_SYNC,"",[ie],n))}await Promise.all(e)}}function Ot(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const r in e)Array.isArray(e[r])?(t[r]=[],Ot(e[r],t[r])):"object"==typeof e[r]?(t[r]={},Ot(e[r],t[r])):t[r]=e[r]}async function Es(e,t){const{functionName:r,args:n}=e;if(!t.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!t.instance[r])throw`undefined function [${r}] in class ${t.instance.constructor.workerId}`;Ze(e,await t.instance[r](...n??[]))}const As=Ur("registeredWorkers",{});function Ts(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,n]=e.args,i=As[r];if(!i)throw`unknown worker class ${r}`;t.instance=new i(e.args.slice(1)),Ot(n,ie),Ze(e,void 0!==typeof t.instance)}async function Ss(e,t){const{args:r}=e;if(!t.instance)throw"instance not initialized";let n;t.instance.terminate&&(n=await t.instance.terminate(...r??[])),Ze(e,n)}function Is(e){if(!e.args)throw"Missing globals while syncing";Ot(e.args[0],ie),Ze(e,{})}function ks(){const e={};onmessage=async t=>{const r=t.data;switch(r.type){case be.INIT:Ts(r,e);break;case be.FORWARD:Es(r,e);break;case be.TERMINATE:Ss(r,e);break;case be.GLOBALS_SYNC:Is(r)}}}function Rs(e,t){return ie[e]||(ie[e]=t),[()=>ie[e],async t=>{ie[e]=t,await _s()}]}function Ps(e,t){return Rs(e,t)}ui()&&ks();const[Fs,Cs]=Ps("metadata");function Os(e){Cs(e)}function Tt(){return Fs()}let Lr=class{constructor(e,t){fs(this,"uuid"),this.config=e,this.uuid=t??ws()}async send(e){var t,r,n;const{appId:i,sourceType:o}=null!=(t=Tt())?t:{};if(!i||!o)return"metadata missing";const s=new AbortController,a=setTimeout(()=>s.abort(),ms);return await(null!=(n=null==(r=this.config)?void 0:r.fetch)?n:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:s.signal}),clearTimeout(a),"success"}getUrl(){var e;let t=null!=(e=Tt().proxyUrl)?e:hs;return t+=("/"===t.at(-1)?"":"/")+ds,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=Tt();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}};const St="3.0.2",_r=class{};_r.updates={transformer_new:"New transformer",transformer_null:"Null transformer"},_r.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 we=_r;function Ms(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}function Bs(e){if(Ms(e))return e;try{return new Error(JSON.stringify(e))}catch{return new Error(String(e))}}function pr(e){return Bs(e).message}class Ds{constructor(e,t){this.config=e,this.frameTransformedCount=0,this.frameFromSourceCount=0,this.startAt=0,this.reporter=new Lr(e,t)}async onFrameFromSource(){this.frameFromSourceCount++}get fps(){const{startAt:e,frameFromSourceCount:t}=this;return t/((Date.now()-e)/1e3)}async onFrameTransformed(e={},t=!1){0===this.startAt&&(this.startAt=Date.now()),this.frameTransformedCount++;const{startAt:r,frameTransformedCount:n,frameFromSourceCount:i}=this,o=Date.now(),s=(o-r)/1e3,a=n/s,c=i/s;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:c,transformedFps:a,framesTransformed:n,...e})):"success"}}var Us=(e=>(e.FPS_DROP="fps_drop",e))(Us||{}),Ls=(e=>(e.start="start",e.transform="transform",e.flush="flush",e))(Ls||{}),Er=(e=>(e.pipeline_ended="pipeline_ended",e.pipeline_ended_with_error="pipeline_ended_with_error",e.pipeline_started="pipeline_started",e.pipeline_started_with_error="pipeline_started_with_error",e.pipeline_restarted="pipeline_restarted",e.pipeline_restarted_with_error="pipeline_restarted_with_error",e))(Er||{});const zs=500,Ns=.8;class $s extends J{constructor(e,t){super(),this.reporter_=new Lr,this.reporterQos_=new Ds({loggingIntervalFrameCount:zs,report:{version:St}}),this.index_=t,this.transformer_=e,this.shouldStop_=!1,this.isFlashed_=!1,this.mediaTransformerQosReportStartTimestamp_=0,this.videoHeight_=0,this.videoWidth_=0,this.trackExpectedRate_=-1,this.transformerType_="Custom","getTransformerType"in e&&(this.transformerType_=e.getTransformerType()),this.report({variation:"Create"})}setTrackExpectedRate(e){this.trackExpectedRate_=e}async start(e){if(this.controller_=e,this.transformer_&&"function"==typeof this.transformer_.start)try{await this.transformer_.start(e)}catch(e){this.report({message:we.errors.transformer_start,variation:"Error",error:pr(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"start"};this.emit("error",t)}}async transform(e,t){if(0===this.mediaTransformerQosReportStartTimestamp_&&(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(e){this.report({message:we.errors.transformer_transform,variation:"Error",error:pr(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"transform"};this.emit("error",t)}if(-1!=this.trackExpectedRate_&&this.trackExpectedRate_*Ns>this.reporterQos_.fps){const e={eventMetaData:{transformerIndex:this.index_},warningType:"fps_drop",dropInfo:{requested:this.trackExpectedRate_,current:this.reporterQos_.fps}};this.emit("warn",e)}}}async flush(e){if(this.transformer_&&"function"==typeof this.transformer_.flush&&!this.isFlashed_){this.isFlashed_=!0;try{await this.transformer_.flush(e)}catch(e){this.report({message:we.errors.transformer_flush,variation:"Error",error:pr(e)});const t={eventMetaData:{transformerIndex:this.index_},error:e,function:"flush"};this.emit("error",t)}}this.reportQos(!0),this.report({variation:"Delete"})}stop(){console.log("[Pipeline] Stop stream."),this.controller_&&(this.flush(this.controller_),this.controller_.terminate()),this.shouldStop_=!0}report(e){this.reporter_.send({version:St,action:"MediaTransformer",transformerType:this.transformerType_,...e})}reportQos(e=!1){this.reporterQos_.config={...this.reporterQos_.config},this.reporterQos_.onFrameTransformed({version:St,action:"MediaTransformer",transformerType:this.transformerType_,videoWidth:this.videoWidth_,videoHeight:this.videoHeight_},e)}}class Ws extends J{constructor(e){super(),this.transformers_=[],this.trackExpectedRate_=-1;for(let t=0;t<e.length;t++){let r=new $s(e[t],t);r.on("error",e=>{this.emit("error",e)}),r.on("warn",e=>{this.emit("warn",e)}),this.transformers_.push(r)}}setTrackExpectedRate(e){this.trackExpectedRate_=e;for(let e of this.transformers_)e.setTrackExpectedRate(this.trackExpectedRate_)}async start(e,t){if(this.transformers_&&0!==this.transformers_.length){try{let r=e;for(let t of this.transformers_)e=e.pipeThrough(new TransformStream(t));e.pipeTo(t).then(async()=>{console.log("[Pipeline] Setup."),await t.abort(),await r.cancel(),this.emit("pipelineInfo","pipeline_ended")}).catch(async n=>{e.cancel().then(()=>{console.log("[Pipeline] Shutting down streams after abort.")}).catch(e=>{console.error("[Pipeline] Error from stream transform:",e)}),await t.abort(n),await r.cancel(n),this.emit("pipelineInfo","pipeline_ended_with_error")})}catch{return this.emit("pipelineInfo","pipeline_started_with_error"),void this.destroy()}this.emit("pipelineInfo","pipeline_started"),console.log("[Pipeline] Pipeline started.")}else console.log("[Pipeline] No transformers.")}async destroy(){console.log("[Pipeline] Destroying Pipeline.");for(let e of this.transformers_)e.stop()}}class li extends J{constructor(){super(),this.reporter_=new Lr,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("video"===e.kind){const t=new MediaStreamTrackProcessor({track:e}),r=new VideoTrackGenerator;return this.readable_=t.readable,this.writable_=r.writable,await this.transformInternal(),r.track}throw Error("Cannot process audio tracks inside a web worker when passing a track to transform")}return this.readable_=e,this.writable_=t,this.transformInternal()}transformInternal(){return new Promise(async(e,t)=>{if(!this.transformers_||0===this.transformers_.length)return this.report({message:we.errors.transformer_none,variation:"Error"}),void t("[MediaProcessor] Need to set transformers.");if(!this.readable_)return this.report({variation:"Error",message:we.errors.readable_null}),void t("[MediaProcessor] Readable is null.");if(!this.writable_)return this.report({variation:"Error",message:we.errors.writable_null}),void t("[MediaProcessor] Writable is null.");let r=!1;this.pipeline_&&(r=!0,this.pipeline_.clearListeners(),this.pipeline_.destroy()),this.pipeline_=new Ws(this.transformers_),this.pipeline_.on("warn",e=>{this.emit("warn",e)}),this.pipeline_.on("error",e=>{this.emit("error",e)}),this.pipeline_.on("pipelineInfo",e=>{r&&("pipeline_started"===e?e=Er.pipeline_restarted:"pipeline_started_with_error"===e&&(e=Er.pipeline_restarted_with_error)),this.emit("pipelineInfo",e)}),-1!=this.trackExpectedRate_&&this.pipeline_.setTrackExpectedRate(this.trackExpectedRate_),this.pipeline_.start(this.readable_,this.writable_).then(()=>{e()}).catch(e=>{t(e)})})}setTransformers(e){return this.report({variation:"Update",message:we.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:St,action:"MediaProcessor",...e})}isTrack(e){return"kind"in e}}class Gs{constructor({kind:e}){if("video"==e){const e=document.createElement("canvas"),t=e.getContext("2d",{desynchronized:!0}),r=e.captureStream().getVideoTracks()[0];return r.writable=new WritableStream({write(r){e.width=r.displayWidth,e.height=r.displayHeight,t.drawImage(r,0,0,e.width,e.height),r.close()}}),r}if("audio"==e){const e=new AudioContext,t=e.createMediaStreamDestination(),[r]=t.stream.getAudioTracks();return r.writable=new WritableStream({async start(n){return this.arrays=[],await e.audioWorklet.addModule(`data:text/javascript,(${function(){registerProcessor("mstg-shim",class extends AudioWorkletProcessor{constructor(){super(),this.arrays=[],this.arrayOffset=0,this.port.onmessage=({data:e})=>this.arrays.push(e),this.emptyArray=new Float32Array(0)}process(e,[[t]]){for(let e=0;e<t.length;e++)(!this.array||this.arrayOffset>=this.array.length)&&(this.array=this.arrays.shift()||this.emptyArray,this.arrayOffset=0),t[e]=this.array[this.arrayOffset++]||0;return!0}})}.toString()})()`),this.node=new AudioWorkletNode(e,"mstg-shim"),this.node.connect(t),r},write(e){const t=new Float32Array(e.numberOfFrames*e.numberOfChannels);e.copyTo(t,{planeIndex:0}),this.node.port.postMessage(t,[t.buffer]),e.close()}}),r}}}function Vs(){return self.MediaStreamTrackGenerator?self.MediaStreamTrackGenerator:Gs}class Hs{constructor(e){const t=e.track??e;"video"==t.kind?this.readable=new ReadableStream({async start(e){t.addEventListener("ended",()=>{try{e.close()}catch{}},{once:!0}),this.video=document.createElement("video"),this.video.srcObject=new MediaStream([t]),await Promise.all([this.video.play(),new Promise(e=>this.video.onloadedmetadata=e)]),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(e){if("ended"==t.readyState){try{e.close()}catch{}return}const r=t.getSettings().frameRate||30;for(;performance.now()-this.t1<1e3/r;)if(await new Promise(e=>requestAnimationFrame(e)),"ended"==t.readyState){try{e.close()}catch{}return}this.canvas.width=this.video.videoWidth,this.canvas.height=this.video.videoHeight,this.t1=performance.now(),this.ctx.drawImage(this.video,0,0),e.enqueue(new VideoFrame(this.canvas,{timestamp:this.t1}))}}):"audio"==t.kind&&(this.readable=new ReadableStream({async start(e){t.addEventListener("ended",()=>{try{e.close()}catch{}},{once:!0}),this.ac=new AudioContext,this.arrays=[],await this.ac.audioWorklet.addModule(`data:text/javascript,(${function(){registerProcessor("mstp-shim",class extends AudioWorkletProcessor{process(e){return this.port.postMessage(e),!0}})}.toString()})()`),this.node=new AudioWorkletNode(this.ac,"mstp-shim"),this.ac.createMediaStreamSource(new MediaStream([t])).connect(this.node),this.node.port.addEventListener("message",({data:e})=>e[0][0]&&this.arrays.push(e))},async pull(e){if("ended"==t.readyState){try{e.close()}catch{}return}for(;!this.arrays.length;)if(await new Promise(e=>this.node.port.onmessage=e),"ended"==t.readyState){try{e.close()}catch{}return}const[r]=this.arrays.shift(),n=new Float32Array(r.reduce((e,t)=>e+t.length,0));r.reduce((e,t)=>(n.set(t,e),e+t.length),0),e.enqueue(new AudioData({format:"f32-planar",sampleRate:this.ac.sampleRate,numberOfFrames:r[0].length,numberOfChannels:r.length,timestamp:1e6*this.ac.currentTime|0,data:n,transfer:[n.buffer]}))}}))}}function js(){return self.MediaStreamTrackProcessor?self.MediaStreamTrackProcessor:Hs}class Ys{constructor(){this.processor_=null,this.generator_=null}init(e){return new Promise((t,r)=>{try{const t=js();this.processor_=new t(e)}catch(e){console.log(`[InsertableStreamHelper] MediaStreamTrackProcessor failed: ${e}`),r(e)}try{const t=Vs();"audio"===e.kind?this.generator_=new t({kind:"audio"}):"video"===e.kind?this.generator_=new t({kind:"video"}):r("kind not supported")}catch(e){console.log(`[InsertableStreamHelper] MediaStreamTrackGenerator failed: ${e}`),r(e)}t()})}getReadable(){return this.processor_.readable}getWriteable(){return this.generator_.writable}getProccesorTrack(){return this.generator_}}class Qs{constructor(e){this.mediaProcessor_=e}async setTrack(e){if(!(this.mediaProcessor_ instanceof li)&&await ai()){if("audio"===e.kind)throw Error("Cannot process audio tracks inside a web worker when passing a track to transform");return await this.mediaProcessor_.transform(e)}if(si()){const t=new Ys;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(e=>{t(e)}):t("no processor")})}}var It=(e=>(e.Low="Low",e.High="High",e))(It||{}),qs=(e=>(e.BackgroundBlur="BackgroundBlur",e.VirtualBackground="VirtualBackground",e.VideoBackground="VideoBackground",e.SilhouetteBlur="SilhouetteBlur",e))(qs||{}),Ar=(e=>(e.FAST="FAST",e.PRECISE="PRECISE",e))(Ar||{}),Mt=(e=>(e.CANVAS="CANVAS",e.WEBGL="WEBGL",e))(Mt||{});const Xs=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 Bd(){const{wasm:e,insertableStreams:t,simd:r,webgl:n}=await Ks();if(!e.supported)throw e.message;if(!t.supported)throw t.message;if(!r.supported)throw r.message;if(!n.supported)throw n.message}async function Ks(){const e={wasm:{supported:"object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate,message:"Your browser does not support WebAssembly features."},simd:{supported:await Xs(),message:"Your browser does not support simd features."},insertableStreams:{supported:!0},gpu:{message:"Your browser does not support gpu features.",supported:!0},webgl:Js(),performance:fi()};try{await os()}catch(t){e.insertableStreams.supported=!1,e.insertableStreams.message=t}return e}function Js(){if(!OffscreenCanvas)return{supported:!1,message:"Your browser does not support offscreen canvas"};const e=new OffscreenCanvas(0,0).getContext("webgl2");if(!e)return{supported:!1,message:"Your browser does not support webgl 2"};{const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}return{supported:!0}}function fi(){const e=new OffscreenCanvas(0,0).getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(!e)return{supported:!1,message:"Your hardware does not perform good enough to run the library efficiently"};{const t=e?.getExtension("WEBGL_lose_context");t&&t.loseContext()}return{supported:!0}}const te=new WeakMap,pe=new WeakMap,X=new WeakMap,Bt=Symbol("anyProducer"),Fn=Promise.resolve(),Dt=Symbol("listenerAdded"),Ut=Symbol("listenerRemoved");let Lt=!1,gr=!1;const zt=e=>"string"==typeof e||"symbol"==typeof e||"number"==typeof e;function Ie(e){if(!zt(e))throw new TypeError("`eventName` must be a string, symbol, or number")}function mt(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function ke(e,t){const r=pe.get(e);if(r.has(t))return r.get(t)}function Ye(e,t){const r=zt(t)?t:Bt,n=X.get(e);if(n.has(r))return n.get(r)}function Cn(e,t,r){const n=X.get(e);if(n.has(t))for(const e of n.get(t))e.enqueue(r);if(n.has(Bt)){const e=Promise.all([t,r]);for(const t of n.get(Bt))t.enqueue(e)}}function On(e,t){t=Array.isArray(t)?t:[t];let r=!1,n=()=>{},i=[];const o={enqueue(e){i.push(e),n()},finish(){r=!0,n()}};for(const r of t){let t=Ye(e,r);t||(t=new Set,X.get(e).set(r,t)),t.add(o)}return{async next(){return i?0===i.length?r?(i=void 0,this.next()):(await new Promise(e=>{n=e}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(r){i=void 0;for(const r of t){const t=Ye(e,r);t&&(t.delete(o),0===t.size&&X.get(e).delete(r))}return n(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Mn(e){if(void 0===e)return Bn;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!Bn.includes(t))throw"string"!=typeof t?new TypeError("`methodNames` element must be a string"):new Error(`${t} is not Emittery method`);return e}const ge=e=>e===Dt||e===Ut;function pt(e,t,r){if(ge(t))try{Lt=!0,e.emit(t,r)}finally{Lt=!1}}let et=class e{static mixin(t,r){return r=Mn(r),n=>{if("function"!=typeof n)throw new TypeError("`target` must be function");for(const e of r)if(void 0!==n.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(n.prototype,t,{enumerable:!1,get:function(){return Object.defineProperty(this,t,{enumerable:!1,value:new e}),this[t]}});const i=e=>function(...r){return this[t][e](...r)};for(const e of r)Object.defineProperty(n.prototype,e,{enumerable:!1,value:i(e)});return n}}static get isDebugEnabled(){if("object"!=typeof globalThis.process?.env)return gr;const{env:e}=globalThis.process??{env:{}};return"emittery"===e.DEBUG||"*"===e.DEBUG||gr}static set isDebugEnabled(e){gr=e}constructor(e={}){te.set(this,new Set),pe.set(this,new Map),X.set(this,new Map),X.get(this).set(Bt,new Set),this.debug=e.debug??{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,r,n)=>{try{n=JSON.stringify(n)}catch{n=`Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`}("symbol"==typeof r||"number"==typeof r)&&(r=r.toString());const i=new Date,o=`${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}.${i.getMilliseconds()}`;console.log(`[${o}][emittery:${e}][${t}] Event Name: ${r}\n\tdata: ${n}`)})}logIfDebugEnabled(t,r,n){(e.isDebugEnabled||this.debug.enabled)&&this.debug.logger(t,this.debug.name,r,n)}on(e,t,{signal:r}={}){mt(t),e=Array.isArray(e)?e:[e];for(const r of e){Ie(r);let e=ke(this,r);e||(e=new Set,pe.get(this).set(r,e)),e.add(t),this.logIfDebugEnabled("subscribe",r,void 0),ge(r)||pt(this,Dt,{eventName:r,listener:t})}const n=()=>{this.off(e,t),r?.removeEventListener("abort",n)};return r?.addEventListener("abort",n,{once:!0}),r?.aborted&&n(),n}off(e,t){mt(t),e=Array.isArray(e)?e:[e];for(const r of e){Ie(r);const e=ke(this,r);e&&(e.delete(t),0===e.size&&pe.get(this).delete(r)),this.logIfDebugEnabled("unsubscribe",r,void 0),ge(r)||pt(this,Ut,{eventName:r,listener:t})}}once(e,t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("predicate must be a function");let r;const n=new Promise(n=>{r=this.on(e,e=>{t&&!t(e)||(r(),n(e))})});return n.off=r,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Ie(t);return On(this,e)}async emit(e,t){if(Ie(e),ge(e)&&!Lt)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),Cn(this,e,t);const r=ke(this,e)??new Set,n=te.get(this),i=[...r],o=ge(e)?[]:[...n];await Fn,await Promise.all([...i.map(async e=>{if(r.has(e))return e(t)}),...o.map(async r=>{if(n.has(r))return r(e,t)})])}async emitSerial(e,t){if(Ie(e),ge(e)&&!Lt)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t),Cn(this,e,t);const r=ke(this,e)??new Set,n=te.get(this),i=[...r],o=ge(e)?[]:[...n];await Fn;for(const e of i)r.has(e)&&await e(t);for(const r of o)n.has(r)&&await r(e,t)}onAny(e,{signal:t}={}){mt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),te.get(this).add(e),pt(this,Dt,{listener:e});const r=()=>{this.offAny(e),t?.removeEventListener("abort",r)};return t?.addEventListener("abort",r,{once:!0}),t?.aborted&&r(),r}anyEvent(){return On(this)}offAny(e){mt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),pt(this,Ut,{listener:e}),te.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),zt(t)){const e=ke(this,t);e&&e.clear();const r=Ye(this,t);if(r){for(const e of r)e.finish();r.clear()}}else{te.get(this).clear();for(const[e,t]of pe.get(this).entries())t.clear(),pe.get(this).delete(e);for(const[e,t]of X.get(this).entries()){for(const e of t)e.finish();t.clear(),X.get(this).delete(e)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let t=0;for(const r of e)if(zt(r))t+=te.get(this).size+(ke(this,r)?.size??0)+(Ye(this,r)?.size??0)+(Ye(this)?.size??0);else{void 0!==r&&Ie(r),t+=te.get(this).size;for(const e of pe.get(this).values())t+=e.size;for(const e of X.get(this).values())t+=e.size}return t}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=Mn(t);for(const r of t){if(void 0!==e[r])throw new Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}};const Bn=Object.getOwnPropertyNames(et.prototype).filter(e=>"constructor"!==e);function zr(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[e]||(r[e]=t),r[e]}Object.defineProperty(et,"listenerAdded",{value:Dt,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(et,"listenerRemoved",{value:Ut,writable:!1,enumerable:!0,configurable:!1});const Le=zr("globals",{});var z=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e.EVENT="EVENT",e))(z||{});function di(e){return[ImageBitmap,ReadableStream,WritableStream].some(t=>e instanceof t)}let Zs=0;function Nt(e,t,r,n,i){const o=Zs++;return e.postMessage({id:o,type:t,functionName:r,args:n},n.filter(e=>di(e))),new Promise(e=>{i?.set(o,e)})}function ze(e,t){const{id:r,type:n}=e,i=Array.isArray(t)?t:[t];postMessage({id:r,type:n,result:t},i.filter(e=>di(e)))}const $t=zr("workerized",{});function Nr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function ea(){if(Nr())ze({type:z.GLOBALS_SYNC},Le);else{const e=[];for(const t in $t){const{worker:r,resolvers:n}=$t[t].workerContext;r&&e.push(Nt(r,z.GLOBALS_SYNC,"",[Le],n))}await Promise.all(e)}}function qe(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const r in e)Array.isArray(e[r])?(t[r]=[],qe(e[r],t[r])):"object"==typeof e[r]?(t[r]={},qe(e[r],t[r])):t[r]=e[r]}async function ta(e,t,r,n){const i=new t;if(i.addEventListener("message",async({data:e})=>{var t,i,o,s,a,c,u;switch(e.type){case z.GLOBALS_SYNC:e.id?(null==(i=r.get(null!=(t=e.id)?t:-1))||i(e.result),r.delete(null!=(o=e.id)?o:-1)):(qe(null!=(s=e.result)?s:{},Le),await ea());break;case z.EVENT:const{result:l}=e,f=l;if(null==f?.name)throw"Missing event name";n(f.name,f.data);break;default:null==(c=r.get(null!=(a=e.id)?a:-1))||c(e.result),r.delete(null!=(u=e.id)?u:-1)}}),!await Nt(i,z.INIT,"",[e.workerId,Le],r))throw"Failed to instantiate workerized class";return i}const re=new WeakMap,ye=new WeakMap,K=new WeakMap,Wt=Symbol("anyProducer"),Dn=Promise.resolve(),Gt=Symbol("listenerAdded"),Vt=Symbol("listenerRemoved");let Ht=!1,yr=!1;function Re(e){if("string"!=typeof e&&"symbol"!=typeof e&&"number"!=typeof e)throw new TypeError("`eventName` must be a string, symbol, or number")}function gt(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function Pe(e,t){const r=ye.get(e);if(r.has(t))return r.get(t)}function Qe(e,t){const r="string"==typeof t||"symbol"==typeof t||"number"==typeof t?t:Wt,n=K.get(e);if(n.has(r))return n.get(r)}function ra(e,t,r){const n=K.get(e);if(n.has(t))for(const e of n.get(t))e.enqueue(r);if(n.has(Wt)){const e=Promise.all([t,r]);for(const t of n.get(Wt))t.enqueue(e)}}function Un(e,t){t=Array.isArray(t)?t:[t];let r=!1,n=()=>{},i=[];const o={enqueue(e){i.push(e),n()},finish(){r=!0,n()}};for(const r of t){let t=Qe(e,r);t||(t=new Set,K.get(e).set(r,t)),t.add(o)}return{async next(){return i?0===i.length?r?(i=void 0,this.next()):(await new Promise(e=>{n=e}),this.next()):{done:!1,value:await i.shift()}:{done:!0}},async return(r){i=void 0;for(const r of t){const t=Qe(e,r);t&&(t.delete(o),0===t.size&&K.get(e).delete(r))}return n(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function Ln(e){if(void 0===e)return zn;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!zn.includes(t))throw"string"!=typeof t?new TypeError("`methodNames` element must be a string"):new Error(`${t} is not Emittery method`);return e}const De=e=>e===Gt||e===Vt;function yt(e,t,r){if(De(t))try{Ht=!0,e.emit(t,r)}finally{Ht=!1}}class _e{static mixin(e,t){return t=Ln(t),r=>{if("function"!=typeof r)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==r.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(r.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new _e}),this[e]}});const n=t=>function(...r){return this[e][t](...r)};for(const e of t)Object.defineProperty(r.prototype,e,{enumerable:!1,value:n(e)});return r}}static get isDebugEnabled(){var e,t;if("object"!=typeof(null==(e=globalThis.process)?void 0:e.env))return yr;const{env:r}=null!=(t=globalThis.process)?t:{env:{}};return"emittery"===r.DEBUG||"*"===r.DEBUG||yr}static set isDebugEnabled(e){yr=e}constructor(e={}){var t;re.set(this,new Set),ye.set(this,new Map),K.set(this,new Map),K.get(this).set(Wt,new Set),this.debug=null!=(t=e.debug)?t:{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,r,n)=>{try{n=JSON.stringify(n)}catch{n=`Object with the following keys failed to stringify: ${Object.keys(n).join(",")}`}("symbol"==typeof r||"number"==typeof r)&&(r=r.toString());const i=new Date,o=`${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}.${i.getMilliseconds()}`;console.log(`[${o}][emittery:${e}][${t}] Event Name: ${r}\n\tdata: ${n}`)})}logIfDebugEnabled(e,t,r){(_e.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,r)}on(e,t){gt(t),e=Array.isArray(e)?e:[e];for(const r of e){Re(r);let e=Pe(this,r);e||(e=new Set,ye.get(this).set(r,e)),e.add(t),this.logIfDebugEnabled("subscribe",r,void 0),De(r)||yt(this,Gt,{eventName:r,listener:t})}return this.off.bind(this,e,t)}off(e,t){gt(t),e=Array.isArray(e)?e:[e];for(const r of e){Re(r);const e=Pe(this,r);e&&(e.delete(t),0===e.size&&ye.get(this).delete(r)),this.logIfDebugEnabled("unsubscribe",r,void 0),De(r)||yt(this,Vt,{eventName:r,listener:t})}}once(e){let t;const r=new Promise(r=>{t=this.on(e,e=>{t(),r(e)})});return r.off=t,r}events(e){e=Array.isArray(e)?e:[e];for(const t of e)Re(t);return Un(this,e)}async emit(e,t){var r;if(Re(e),De(e)&&!Ht)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),ra(this,e,t);const n=null!=(r=Pe(this,e))?r:new Set,i=re.get(this),o=[...n],s=De(e)?[]:[...i];await Dn,await Promise.all([...o.map(async e=>{if(n.has(e))return e(t)}),...s.map(async r=>{if(i.has(r))return r(e,t)})])}async emitSerial(e,t){var r;if(Re(e),De(e)&&!Ht)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const n=null!=(r=Pe(this,e))?r:new Set,i=re.get(this),o=[...n],s=[...i];await Dn;for(const e of o)n.has(e)&&await e(t);for(const r of s)i.has(r)&&await r(e,t)}onAny(e){return gt(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),re.get(this).add(e),yt(this,Gt,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return Un(this)}offAny(e){gt(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),yt(this,Vt,{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),"string"==typeof t||"symbol"==typeof t||"number"==typeof t){const e=Pe(this,t);e&&e.clear();const r=Qe(this,t);if(r){for(const e of r)e.finish();r.clear()}}else{re.get(this).clear();for(const[e,t]of ye.get(this).entries())t.clear(),ye.get(this).delete(e);for(const[e,t]of K.get(this).entries()){for(const e of t)e.finish();t.clear(),K.get(this).delete(e)}}}listenerCount(e){var t,r,n,i,o,s;e=Array.isArray(e)?e:[e];let a=0;for(const c of e)if("string"!=typeof c){typeof c<"u"&&Re(c),a+=re.get(this).size;for(const e of ye.get(this).values())a+=e.size;for(const e of K.get(this).values())a+=e.size}else a+=re.get(this).size+(null!=(r=null==(t=Pe(this,c))?void 0:t.size)?r:0)+(null!=(i=null==(n=Qe(this,c))?void 0:n.size)?i:0)+(null!=(s=null==(o=Qe(this))?void 0:o.size)?s:0);return a}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=Ln(t);for(const r of t){if(void 0!==e[r])throw new Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}}const zn=Object.getOwnPropertyNames(_e.prototype).filter(e=>"constructor"!==e);function na(e){return e.onAny&&e.emit}function ia(e){return e.prototype.onAny&&e.prototype.emit}Object.defineProperty(_e,"listenerAdded",{value:Gt,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(_e,"listenerRemoved",{value:Vt,writable:!1,enumerable:!0,configurable:!1});let oa=0;async function sa(e,t,r){const n=ia(e)?new _e:{},i=oa++;return Object.getOwnPropertyNames(e.prototype).forEach(e=>{n[e]=(...n)=>Nt(t,z.FORWARD,e,n,r)}),n.terminate=async(...e)=>{const o=await Nt(t,z.TERMINATE,"",e,r);return delete $t[i],t.terminate(),n.workerContext.worker=void 0,o},n.workerContext={id:i,worker:t,resolvers:r},$t[i]=n,n}async function aa(e,t){const r=new Map;let n;const i=await ta(e,t,r,(e,t)=>{n?.emit&&n?.emit(e,t)});return n=await sa(e,i,r),n}async function ca(e,t){const{functionName:r,args:n}=e;if(!t.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!t.instance[r])throw`undefined function [${r}] in class ${t.instance.constructor.workerId}`;ze(e,await t.instance[r](...n??[]))}const hi=zr("registeredWorkers",{});function ua(e,t){t.workerId=e,Nr()&&(hi[t.workerId]=t)}function la(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,n]=e.args,i=hi[r];if(!i)throw`unknown worker class ${r}`;t.instance=new i(e.args.slice(1)),qe(n,Le),na(t.instance)&&t.instance.onAny((e,t)=>{ze({type:z.EVENT},{name:e,data:t})}),ze(e,void 0!==typeof t.instance)}async function fa(e,t){const{args:r}=e;if(!t.instance)throw"instance not initialized";let n;t.instance.terminate&&(n=await t.instance.terminate(...r??[])),ze(e,n)}function da(e){if(!e.args)throw"Missing globals while syncing";qe(e.args[0],Le),ze(e,{})}function ha(){const e={};onmessage=async t=>{const r=t.data;switch(r.type){case z.INIT:la(r,e);break;case z.FORWARD:ca(r,e);break;case z.TERMINATE:fa(r,e);break;case z.GLOBALS_SYNC:da(r)}}}Nr()&&ha();class Nn{static async createVideoReadable(e){return new Promise((t,r)=>{const n=document.createElement("video");let i=new AbortController,o=new AbortController;n.addEventListener("canplay",()=>{i.abort(),n.muted=!0,n.loop=!0,n.play().then(()=>{try{const e=n.captureStream(),r=new MediaStreamTrackProcessor(e.getVideoTracks()[0]);t(r.readable)}catch(e){r(e)}})},{once:!0,signal:o.signal}),n.addEventListener("error",e=>{o.abort(),r("loading error:"+e)},{once:!0,signal:i.signal}),n.crossOrigin="anonymous",n.src=e})}static async createImageCanvas(e){const t=await(await fetch(e)).blob();return await createImageBitmap(t)}}var ma=Object.defineProperty,pa=(e,t,r)=>t in e?ma(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ga=(e,t,r)=>(pa(e,t+"",r),r);const ya="hlg.tokbox.com/prod/logging/vcp_webrtc",ba="https://",wa=1e4;let bt;const xa=new Uint8Array(16);function va(){if(!bt&&(bt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!bt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return bt(xa)}const C=[];for(let e=0;e<256;++e)C.push((e+256).toString(16).slice(1));function _a(e,t=0){return(C[e[t+0]]+C[e[t+1]]+C[e[t+2]]+C[e[t+3]]+"-"+C[e[t+4]]+C[e[t+5]]+"-"+C[e[t+6]]+C[e[t+7]]+"-"+C[e[t+8]]+C[e[t+9]]+"-"+C[e[t+10]]+C[e[t+11]]+C[e[t+12]]+C[e[t+13]]+C[e[t+14]]+C[e[t+15]]).toLowerCase()}const Ea=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),$n={randomUUID:Ea};function Aa(e,t,r){if($n.randomUUID&&!t&&!e)return $n.randomUUID();const n=(e=e||{}).random||(e.rng||va)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,_a(n)}function $r(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let r=globalThis.vonage.workerizer;return r[e]||(r[e]=t),r[e]}const oe=$r("globals",{});var xe=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e))(xe||{});function mi(e){return[ImageBitmap,ReadableStream,WritableStream].some(t=>e instanceof t)}let Ta=0;function Sa(e,t,r,n,i){const o=Ta++;return e.postMessage({id:o,type:t,functionName:r,args:n},n.filter(e=>mi(e))),new Promise(e=>{i?.set(o,e)})}function tt(e,t){const{id:r,type:n}=e,i=Array.isArray(t)?t:[t];postMessage({id:r,type:n,result:t},i.filter(e=>mi(e)))}const Wn=$r("workerized",{});function pi(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}async function Ia(){if(pi())tt({type:xe.GLOBALS_SYNC},oe);else{const e=[];for(const t in Wn){const{worker:r,resolvers:n}=Wn[t].workerContext;r&&e.push(Sa(r,xe.GLOBALS_SYNC,"",[oe],n))}await Promise.all(e)}}function jt(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const r in e)Array.isArray(e[r])?(t[r]=[],jt(e[r],t[r])):"object"==typeof e[r]?(t[r]={},jt(e[r],t[r])):t[r]=e[r]}async function ka(e,t){const{functionName:r,args:n}=e;if(!t.instance)throw"instance not initialized";if(!r)throw"missing function name to call";if(!t.instance[r])throw`undefined function [${r}] in class ${t.instance.constructor.workerId}`;tt(e,await t.instance[r](...n??[]))}const Ra=$r("registeredWorkers",{});function Pa(e,t){if(!e.args)throw"Missing className while initializing worker";const[r,n]=e.args,i=Ra[r];if(!i)throw`unknown worker class ${r}`;t.instance=new i(e.args.slice(1)),jt(n,oe),tt(e,void 0!==typeof t.instance)}async function Fa(e,t){const{args:r}=e;if(!t.instance)throw"instance not initialized";let n;t.instance.terminate&&(n=await t.instance.terminate(...r??[])),tt(e,n)}function Ca(e){if(!e.args)throw"Missing globals while syncing";jt(e.args[0],oe),tt(e,{})}function Oa(){const e={};onmessage=async t=>{const r=t.data;switch(r.type){case xe.INIT:Pa(r,e);break;case xe.FORWARD:ka(r,e);break;case xe.TERMINATE:Fa(r,e);break;case xe.GLOBALS_SYNC:Ca(r)}}}function Ma(e,t){return oe[e]||(oe[e]=t),[()=>oe[e],async t=>{oe[e]=t,await Ia()}]}function Ba(e,t){return Ma(e,t)}pi()&&Oa();const[Da]=Ba("metadata");function br(){return Da()}class Ua{constructor(e){ga(this,"uuid",Aa()),this.config=e}async send(e){var t,r,n;const{appId:i,sourceType:o}=null!=(t=br())?t:{};if(!i||!o)return"metadata missing";const s=new AbortController,a=setTimeout(()=>s.abort(),wa);return await(null!=(n=null==(r=this.config)?void 0:r.fetch)?n:fetch)(this.getUrl(),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(this.buildReport(e)),signal:s.signal}),clearTimeout(a),"success"}getUrl(){var e;let t=null!=(e=br().proxyUrl)?e:ba;return t+=("/"===t.at(-1)?"":"/")+ya,t}getHeaders(){return{"Content-Type":"application/json"}}buildReport(e){const t=br();return{guid:this.uuid,...e,applicationId:t.appId,timestamp:Date.now(),proxyUrl:t.proxyUrl,source:t.sourceType}}}const La="7.0.2-alpha.2";class Wr{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:r}=e;this.canvas.width=t,this.canvas.height=r}renderSilhouette(e,t,r="none"){const{width:n,height:i}=e;this.context.save(),this.context.drawImage(t,0,0,t.width,t.height,0,0,n,i),this.context.filter="blur(5px)",this.context.globalCompositeOperation="source-in",this.context.drawImage(t,0,0,t.width,t.height,0,0,n,i),this.context.globalCompositeOperation="source-in",this.context.filter=r,this.context.drawImage(e,0,0,n,i,0,0,this.canvas.width,this.canvas.height),this.context.restore()}destroy(){}}class za extends Wr{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const r=await createImageBitmap(t);return this.renderSilhouette(e,r),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 Na extends Wr{constructor(e){super(),this.radius=e}async render(e,t){super.resizeCanvas(e);const r=await createImageBitmap(t);return this.renderSilhouette(e,r,`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 $a extends Wr{setBackgroundImage(e){this.backgroundImage=e}async render(e,t){super.resizeCanvas(e);const r=await createImageBitmap(t);return this.renderSilhouette(e,r),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 Gr=5120,Xe=5121,Vr=5122,Hr=5123,jr=5124,Yr=5125,Qr=5126,Wa=32819,Ga=32820,Va=33635,Ha=5131,ja=33640,Ya=35899,Qa=35902,qa=36269,Xa=34042,gi={};{const e=gi;e[Gr]=Int8Array,e[Xe]=Uint8Array,e[Vr]=Int16Array,e[Hr]=Uint16Array,e[jr]=Int32Array,e[Yr]=Uint32Array,e[Qr]=Float32Array,e[Wa]=Uint16Array,e[Ga]=Uint16Array,e[Va]=Uint16Array,e[Ha]=Uint16Array,e[ja]=Uint32Array,e[Ya]=Uint32Array,e[Qa]=Uint32Array,e[qa]=Uint32Array,e[Xa]=Uint32Array}function qr(e){if(e instanceof Int8Array)return Gr;if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)return Xe;if(e instanceof Int16Array)return Vr;if(e instanceof Uint16Array)return Hr;if(e instanceof Int32Array)return jr;if(e instanceof Uint32Array)return Yr;if(e instanceof Float32Array)return Qr;throw new Error("unsupported typed array type")}function yi(e){if(e===Int8Array)return Gr;if(e===Uint8Array||e===Uint8ClampedArray)return Xe;if(e===Int16Array)return Vr;if(e===Uint16Array)return Hr;if(e===Int32Array)return jr;if(e===Uint32Array)return Yr;if(e===Float32Array)return Qr;throw new Error("unsupported typed array type")}function bi(e){const t=gi[e];if(!t)throw new Error("unknown gl type");return t}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 wi(...e){console.error(...e)}const Gn=new Map;function Zt(e,t){if(!e||"object"!=typeof e)return!1;let r=Gn.get(t);r||(r=new WeakMap,Gn.set(t,r));let n=r.get(e);if(void 0===n){const i=Object.prototype.toString.call(e);n=i.substring(8,i.length-1)===t,r.set(e,n)}return n}function Ka(e,t){return typeof WebGLBuffer<"u"&&Zt(t,"WebGLBuffer")}function Ja(e,t){return typeof WebGLRenderbuffer<"u"&&Zt(t,"WebGLRenderbuffer")}function Xr(e,t){return typeof WebGLTexture<"u"&&Zt(t,"WebGLTexture")}function Za(e,t){return typeof WebGLSampler<"u"&&Zt(t,"WebGLSampler")}const xi=35044,ve=34962,ec=34963,tc=34660,rc=5120,nc=5121,ic=5122,oc=5123,sc=5124,ac=5125,vi=5126,_i={attribPrefix:""};function cc(e,t,r,n,i){e.bindBuffer(t,r),e.bufferData(t,n,i||xi)}function Ei(e,t,r,n){if(Ka(e,t))return t;r=r||ve;const i=e.createBuffer();return cc(e,r,i,t,n),i}function Ai(e){return"indices"===e}function uc(e){return e===Int8Array||e===Uint8Array}function lc(e){return e.length?e:e.data}const fc=/coord|texture/i,dc=/color|colour/i;function hc(e,t){let r;if(r=fc.test(e)?2:dc.test(e)?4:3,t%r>0)throw new Error(`Can not guess numComponents for attribute '${e}'. Tried ${r} but ${t} values is not evenly divisible by ${r}. You should specify it.`);return r}function mc(e,t,r){return e.numComponents||e.size||hc(t,r||lc(e).length)}function Ti(e,t){if(Yt(e))return e;if(Yt(e.data))return e.data;Array.isArray(e)&&(e={data:e});let r=e.type?Kr(e.type):void 0;return r||(r=Ai(t)?Uint16Array:Float32Array),new r(e.data)}function pc(e){return"number"==typeof e?e:e?yi(e):vi}function Kr(e){return"number"==typeof e?bi(e):e||Float32Array}function gc(e,t){return{buffer:t.buffer,numValues:24,type:pc(t.type),arrayType:Kr(t.type)}}function yc(e,t){const r=t.data||t,n=Kr(t.type),i=r*n.BYTES_PER_ELEMENT,o=e.createBuffer();return e.bindBuffer(ve,o),e.bufferData(ve,i,t.drawType||xi),{buffer:o,numValues:r,type:yi(n),arrayType:n}}function bc(e,t,r){const n=Ti(t,r);return{arrayType:n.constructor,buffer:Ei(e,n,void 0,t.drawType),type:qr(n),numValues:0}}function wc(e,t){const r={};return Object.keys(t).forEach(function(n){if(!Ai(n)){const i=t[n],o=i.attrib||i.name||i.attribName||_i.attribPrefix+n;if(i.value){if(!Array.isArray(i.value)&&!Yt(i.value))throw new Error("array.value is not array or typedarray");r[o]={value:i.value}}else{let t;t=i.buffer&&i.buffer instanceof WebGLBuffer?gc:"number"==typeof i||"number"==typeof i.data?yc:bc;const{buffer:s,type:a,numValues:c,arrayType:u}=t(e,i,n),l=void 0!==i.normalize?i.normalize:uc(u),f=mc(i,n,c);r[o]={buffer:s,numComponents:f,type:a,normalize:l,stride:i.stride||0,offset:i.offset||0,divisor:void 0===i.divisor?void 0:i.divisor,drawType:i.drawType}}}}),e.bindBuffer(ve,null),r}function xc(e,t){return t===rc||t===nc?1:t===ic||t===oc?2:t===sc||t===ac||t===vi?4:0}const wr=["position","positions","a_position"];function vc(e,t){let r,n;for(n=0;n<wr.length&&(r=wr[n],!(r in t)&&(r=_i.attribPrefix+r,!(r in t)));++n);n===wr.length&&(r=Object.keys(t)[0]);const i=t[r];if(!i.buffer)return 1;e.bindBuffer(ve,i.buffer);const o=e.getBufferParameter(ve,tc);e.bindBuffer(ve,null);const s=o/xc(e,i.type),a=i.numComponents||i.size,c=s/a;if(c%1!=0)throw new Error(`numComponents ${a} not correct for length ${length}`);return c}function _c(e,t,r){const n=wc(e,t),i=Object.assign({},r||{});i.attribs=Object.assign({},r?r.attribs:{},n);const o=t.indices;if(o){const t=Ti(o,"indices");i.indices=Ei(e,t,ec),i.numElements=t.length,i.elementType=qr(t)}else i.numElements||(i.numElements=vc(e,i.attribs));return i}function rt(e){return!!e.texStorage2D}const Si=function(){const e={},t={};return function(r,n){return function(r){const n=r.constructor.name;if(!e[n]){for(const e in r)if("number"==typeof r[e]){const n=t[r[e]];t[r[e]]=n?`${n} | ${e}`:e}e[n]=!0}}(r),t[n]||("number"==typeof n?`0x${n.toString(16)}`:n)}}(),ae={textureColor:new Uint8Array([128,192,255,255]),textureOptions:{},crossOrigin:void 0},Ke=Yt,Ii=function(){let e;return function(){return e=e||(typeof document<"u"&&document.createElement?document.createElement("canvas").getContext("2d"):null),e}}(),Vn=6406,j=6407,T=6408,Hn=6409,jn=6410,Ve=6402,Yn=34041,Qt=33071,Ec=9728,Ac=9729,ce=3553,se=34067,Ee=32879,Ae=35866,Jr=34069,Tc=34070,Sc=34071,Ic=34072,kc=34073,Rc=34074,Sr=10241,Ir=10240,qt=10242,Xt=10243,Qn=32882,Pc=33082,Fc=33083,Cc=33084,Oc=33085,Mc=34892,Bc=34893,Zr=3317,ki=3314,Ri=32878,Pi=3316,Fi=3315,Ci=32877,Dc=37443,Uc=37441,Lc=37440,zc=33321,Nc=36756,$c=33325,Wc=33326,Gc=33330,Vc=33329,Hc=33338,jc=33337,Yc=33340,Qc=33339,qc=33323,Xc=36757,Kc=33327,Jc=33328,Zc=33336,eu=33335,tu=33332,ru=33331,nu=33334,iu=33333,ou=32849,su=35905,au=36194,cu=36758,uu=35898,lu=35901,fu=34843,du=34837,hu=36221,mu=36239,pu=36215,gu=36233,yu=36209,bu=36227,wu=32856,xu=35907,vu=36759,_u=32855,Eu=32854,Au=32857,Tu=34842,Su=34836,Iu=36220,ku=36238,Ru=36975,Pu=36214,Fu=36232,Cu=36226,Ou=36208,Mu=33189,Bu=33190,Du=36012,Uu=36013,Lu=35056,ne=5120,A=5121,wt=5122,Fe=5123,xt=5124,de=5125,M=5126,qn=32819,Xn=32820,Kn=33635,G=5131,He=36193,xr=33640,zu=35899,Nu=35902,$u=36269,Wu=34042,vt=33319,Ce=33320,_t=6403,Oe=36244,Me=36248,he=36249;let vr;function er(e){if(!vr){const e={};e[Vn]={textureFormat:Vn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[A,G,He,M]},e[Hn]={textureFormat:Hn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[A,G,He,M]},e[jn]={textureFormat:jn,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2,4,4,8],type:[A,G,He,M]},e[j]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,6,6,12,2],type:[A,G,He,M,Kn]},e[T]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,8,8,16,2,2],type:[A,G,He,M,qn,Xn]},e[Ve]={textureFormat:Ve,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[de,Fe]},e[zc]={textureFormat:_t,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1],type:[A]},e[Nc]={textureFormat:_t,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[1],type:[ne]},e[$c]={textureFormat:_t,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4,2],type:[M,G]},e[Wc]={textureFormat:_t,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[Gc]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[A]},e[Vc]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[ne]},e[tu]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Fe]},e[ru]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[wt]},e[nu]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[de]},e[iu]={textureFormat:Oe,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[xt]},e[qc]={textureFormat:vt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2],type:[A]},e[Xc]={textureFormat:vt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[2],type:[ne]},e[Kc]={textureFormat:vt,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[8,4],type:[M,G]},e[Jc]={textureFormat:vt,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[8],type:[M]},e[Zc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[A]},e[eu]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[ne]},e[Hc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Fe]},e[jc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[wt]},e[Yc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[de]},e[Qc]={textureFormat:Ce,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[xt]},e[ou]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3],type:[A]},e[su]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[A]},e[au]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,2],type:[A,Kn]},e[cu]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[ne]},e[uu]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,G,zu]},e[lu]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[M,G,Nu]},e[fu]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6],type:[M,G]},e[du]={textureFormat:j,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[M]},e[hu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[A]},e[mu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[ne]},e[pu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Fe]},e[gu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[wt]},e[yu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[de]},e[bu]={textureFormat:Me,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[xt]},e[wu]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[A]},e[xu]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[A]},e[vu]={textureFormat:T,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4],type:[ne]},e[_u]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2,4],type:[A,Xn,xr]},e[Eu]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2],type:[A,qn]},e[Au]={textureFormat:T,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[xr]},e[Tu]={textureFormat:T,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[16,8],type:[M,G]},e[Su]={textureFormat:T,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[16],type:[M]},e[Iu]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[A]},e[ku]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ne]},e[Ru]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[xr]},e[Pu]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Fe]},e[Fu]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[wt]},e[Cu]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[xt]},e[Ou]={textureFormat:he,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[de]},e[Mu]={textureFormat:Ve,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[Fe,de]},e[Bu]={textureFormat:Ve,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[de]},e[Du]={textureFormat:Ve,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[M]},e[Lu]={textureFormat:Yn,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Wu]},e[Uu]={textureFormat:Yn,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[$u]},Object.keys(e).forEach(function(t){const r=e[t];r.bytesPerElementMap={},r.bytesPerElement.forEach(function(e,t){const n=r.type[t];r.bytesPerElementMap[n]=e})}),vr=e}return vr[e]}function Gu(e,t){const r=er(e);if(!r)throw"unknown internal format";const n=r.bytesPerElementMap[t];if(void 0===n)throw"unknown internal format";return n}function nt(e){const t=er(e);if(!t)throw"unknown internal format";return{format:t.textureFormat,type:t.type[0]}}function Jn(e){return!(e&e-1)}function Vu(e,t,r,n){if(!rt(e))return Jn(t)&&Jn(r);const i=er(n);if(!i)throw"unknown internal format";return i.colorRenderable&&i.textureFilterable}function Hu(e){const t=er(e);if(!t)throw"unknown internal format";return t.textureFilterable}function ju(e,t,r){return Ke(t)?qr(t):r||A}function Et(e,t,r,n,i){if(i%1!=0)throw"can't guess dimensions";if(r||n){if(n){if(!r&&(r=i/n)%1)throw"can't guess dimensions"}else if((n=i/r)%1)throw"can't guess dimensions"}else{const e=Math.sqrt(i/(t===se?6:1));e%1==0?(r=e,n=e):(r=i,n=1)}return{width:r,height:n}}function Ne(e,t){void 0!==t.colorspaceConversion&&e.pixelStorei(Dc,t.colorspaceConversion),void 0!==t.premultiplyAlpha&&e.pixelStorei(Uc,t.premultiplyAlpha),void 0!==t.flipY&&e.pixelStorei(Lc,t.flipY)}function Oi(e){e.pixelStorei(Zr,4),rt(e)&&(e.pixelStorei(ki,0),e.pixelStorei(Ri,0),e.pixelStorei(Pi,0),e.pixelStorei(Fi,0),e.pixelStorei(Ci,0))}function Yu(e,t,r,n){n.minMag&&(r.call(e,t,Sr,n.minMag),r.call(e,t,Ir,n.minMag)),n.min&&r.call(e,t,Sr,n.min),n.mag&&r.call(e,t,Ir,n.mag),n.wrap&&(r.call(e,t,qt,n.wrap),r.call(e,t,Xt,n.wrap),(t===Ee||Za(e,t))&&r.call(e,t,Qn,n.wrap)),n.wrapR&&r.call(e,t,Qn,n.wrapR),n.wrapS&&r.call(e,t,qt,n.wrapS),n.wrapT&&r.call(e,t,Xt,n.wrapT),void 0!==n.minLod&&r.call(e,t,Pc,n.minLod),void 0!==n.maxLod&&r.call(e,t,Fc,n.maxLod),void 0!==n.baseLevel&&r.call(e,t,Cc,n.baseLevel),void 0!==n.maxLevel&&r.call(e,t,Oc,n.maxLevel),void 0!==n.compareFunc&&r.call(e,t,Bc,n.compareFunc),void 0!==n.compareMode&&r.call(e,t,Mc,n.compareMode)}function Mi(e,t,r){const n=r.target||ce;e.bindTexture(n,t),Yu(e,n,e.texParameteri,r)}function Qu(e){return Ke(e=e||ae.textureColor)?e:new Uint8Array([255*e[0],255*e[1],255*e[2],255*e[3]])}function kr(e,t,r,n,i,o){o=o||T;const s=(r=r||ae.textureOptions).target||ce;if(n=n||r.width,i=i||r.height,e.bindTexture(s,t),Vu(e,n,i,o))e.generateMipmap(s);else{const t=Hu(o)?Ac:Ec;e.texParameteri(s,Sr,t),e.texParameteri(s,Ir,t),e.texParameteri(s,qt,Qt),e.texParameteri(s,Xt,Qt)}}function Je(e){return!0===e.auto||void 0===e.auto&&void 0===e.level}function Rr(e,t){return(t=t||{}).cubeFaceOrder||[Jr,Tc,Sc,Ic,kc,Rc]}function Pr(e,t){const r=Rr(e,t).map(function(e,t){return{face:e,ndx:t}});return r.sort(function(e,t){return e.face-t.face}),r}function Bi(e,t,r,n){const i=(n=n||ae.textureOptions).target||ce,o=n.level||0;let s=r.width,a=r.height;const c=n.internalFormat||n.format||T,u=nt(c),l=n.format||u.format,f=n.type||u.type;if(Ne(e,n),e.bindTexture(i,t),i===se){const u=r.width,h=r.height;let d,m;if(u/6===h)d=h,m=[0,0,1,0,2,0,3,0,4,0,5,0];else if(h/6===u)d=u,m=[0,0,0,1,0,2,0,3,0,4,0,5];else if(u/3==h/2)d=u/3,m=[0,0,1,0,2,0,0,1,1,1,2,1];else{if(u/2!=h/3)throw"can't figure out cube map from element: "+(r.src?r.src:r.nodeName);d=u/2,m=[0,0,1,0,0,1,1,1,0,2,1,2]}const p=Ii();p?(p.canvas.width=d,p.canvas.height=d,s=d,a=d,Pr(e,n).forEach(function(t){const n=m[2*t.ndx+0]*d,i=m[2*t.ndx+1]*d;p.drawImage(r,n,i,d,d,0,0,d,d),e.texImage2D(t.face,o,c,l,f,p.canvas)}),p.canvas.width=1,p.canvas.height=1):typeof createImageBitmap<"u"&&(s=d,a=d,Pr(e,n).forEach(function(u){const h=m[2*u.ndx+0]*d,p=m[2*u.ndx+1]*d;e.texImage2D(u.face,o,c,d,d,0,l,f,null),createImageBitmap(r,h,p,d,d,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(function(r){Ne(e,n),e.bindTexture(i,t),e.texImage2D(u.face,o,c,l,f,r),Je(n)&&kr(e,t,n,s,a,c)})}))}else if(i===Ee||i===Ae){const t=Math.min(r.width,r.height),n=Math.max(r.width,r.height),s=n/t;if(s%1!=0)throw"can not compute 3D dimensions of element";const a=r.width===n?1:0,u=r.height===n?1:0;e.pixelStorei(Zr,1),e.pixelStorei(ki,r.width),e.pixelStorei(Ri,0),e.pixelStorei(Ci,0),e.texImage3D(i,o,c,t,t,t,0,l,f,null);for(let n=0;n<s;++n){const s=n*t*a,c=n*t*u;e.pixelStorei(Pi,s),e.pixelStorei(Fi,c),e.texSubImage3D(i,o,0,0,n,t,t,1,l,f,r)}Oi(e)}else e.texImage2D(i,o,c,l,f,r);Je(n)&&kr(e,t,n,s,a,c),Mi(e,t,n)}function it(){}function qu(e){if(typeof document<"u"){const t=document.createElement("a");return t.href=e,t.hostname===location.hostname&&t.port===location.port&&t.protocol===location.protocol}{const t=new URL(location.href).origin;return new URL(e,location.href).origin===t}}function Xu(e,t){return void 0!==t||qu(e)?t:"anonymous"}function Ku(e,t,r){let n;if(r=r||it,t=Xu(e,t=void 0!==t?t:ae.crossOrigin),typeof Image<"u"){n=new Image,void 0!==t&&(n.crossOrigin=t);const i=function(){n.removeEventListener("error",o),n.removeEventListener("load",s),n=null},o=function(){const t="couldn't load image: "+e;wi(t),r(t,n),i()},s=function(){r(null,n),i()};return n.addEventListener("error",o),n.addEventListener("load",s),n.src=e,n}if(typeof ImageBitmap<"u"){let i,o;const s=function(){r(i,o)},a={};t&&(a.mode="cors"),fetch(e,a).then(function(e){if(!e.ok)throw e;return e.blob()}).then(function(e){return createImageBitmap(e,{premultiplyAlpha:"none",colorSpaceConversion:"none"})}).then(function(e){o=e,setTimeout(s)}).catch(function(e){i=e,setTimeout(s)}),n=null}return n}function Di(e){return typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof ImageData<"u"&&e instanceof ImageData||typeof HTMLElement<"u"&&e instanceof HTMLElement}function en(e,t,r){return Di(e)?(setTimeout(function(){r(null,e)}),e):Ku(e,t,r)}function tn(e,t,r){const n=(r=r||ae.textureOptions).target||ce;if(e.bindTexture(n,t),!1===r.color)return;const i=Qu(r.color);if(n===se)for(let t=0;t<6;++t)e.texImage2D(Jr+t,0,T,1,1,0,T,A,i);else n===Ee||n===Ae?e.texImage3D(n,0,T,1,1,1,0,T,A,i):e.texImage2D(n,0,T,1,1,0,T,A,i)}function Ju(e,t,r,n){return n=n||it,tn(e,t,r=r||ae.textureOptions),en((r=Object.assign({},r)).src,r.crossOrigin,function(i,o){i?n(i,t,o):(Bi(e,t,o,r),n(null,t,o))})}function Zu(e,t,r,n){n=n||it;const i=r.src;if(6!==i.length)throw"there must be 6 urls for a cubemap";const o=r.level||0,s=r.internalFormat||r.format||T,a=nt(s),c=r.format||a.format,u=r.type||A,l=r.target||ce;if(l!==se)throw"target must be TEXTURE_CUBE_MAP";tn(e,t,r),r=Object.assign({},r);let f=6;const h=[],d=Rr(e,r);let m;m=i.map(function(i,a){return en(i,r.crossOrigin,function(i){return function(a,d){--f,a?h.push(a):d.width!==d.height?h.push("cubemap face img is not a square: "+d.src):(Ne(e,r),e.bindTexture(l,t),5===f?Rr().forEach(function(t){e.texImage2D(t,o,s,c,u,d)}):e.texImage2D(i,o,s,c,u,d),Je(r)&&e.generateMipmap(l)),0===f&&n(h.length?h:void 0,t,m)}}(d[a]))})}function el(e,t,r,n){n=n||it;const i=r.src,o=r.internalFormat||r.format||T,s=nt(o),a=r.format||s.format,c=r.type||A,u=r.target||Ae;if(u!==Ee&&u!==Ae)throw"target must be TEXTURE_3D or TEXTURE_2D_ARRAY";tn(e,t,r),r=Object.assign({},r);let l=i.length;const f=[];let h;const d=r.level||0;let m=r.width,p=r.height;const g=i.length;let y=!0;h=i.map(function(i,s){return en(i,r.crossOrigin,function(i){return function(s,b){if(--l,s)f.push(s);else{if(Ne(e,r),e.bindTexture(u,t),y){y=!1,m=r.width||b.width,p=r.height||b.height,e.texImage3D(u,d,o,m,p,g,0,a,c,null);for(let t=0;t<g;++t)e.texSubImage3D(u,d,0,0,t,m,p,1,a,c,b)}else{let t,r=b;(b.width!==m||b.height!==p)&&(t=Ii(),r=t.canvas,t.canvas.width=m,t.canvas.height=p,t.drawImage(b,0,0,m,p)),e.texSubImage3D(u,d,0,0,i,m,p,1,a,c,r),t&&r===t.canvas&&(t.canvas.width=0,t.canvas.height=0)}Je(r)&&e.generateMipmap(u)}0===l&&n(f.length?f:void 0,t,h)}}(s))})}function tl(e,t,r,n){const i=(n=n||ae.textureOptions).target||ce;e.bindTexture(i,t);let o=n.width,s=n.height,a=n.depth;const c=n.level||0,u=n.internalFormat||n.format||T,l=nt(u),f=n.format||l.format,h=n.type||ju(e,r,l.type);if(Ke(r))r instanceof Uint8ClampedArray&&(r=new Uint8Array(r.buffer));else{const e=bi(h);r=new e(r)}const d=Gu(u,h),m=r.byteLength/d;if(m%1)throw"length wrong size for format: "+Si(e,f);let p;if(i===Ee||i===Ae)if(o||s||a)!o||s&&a?!s||o&&a?(p=Et(e,i,o,s,m/a),o=p.width,s=p.height):(p=Et(e,i,o,a,m/s),o=p.width,a=p.height):(p=Et(e,i,s,a,m/o),s=p.width,a=p.height);else{const e=Math.cbrt(m);if(e%1!=0)throw"can't guess cube size of array of numElements: "+m;o=e,s=e,a=e}else p=Et(e,i,o,s,m),o=p.width,s=p.height;if(Oi(e),e.pixelStorei(Zr,n.unpackAlignment||1),Ne(e,n),i===se){const t=m/6*(d/r.BYTES_PER_ELEMENT);Pr(e,n).forEach(n=>{const i=t*n.ndx,a=r.subarray(i,i+t);e.texImage2D(n.face,c,u,o,s,0,f,h,a)})}else i===Ee||i===Ae?e.texImage3D(i,c,u,o,s,a,0,f,h,r):e.texImage2D(i,c,u,o,s,0,f,h,r);return{width:o,height:s,depth:a,type:h}}function rl(e,t,r){const n=r.target||ce;e.bindTexture(n,t);const i=r.level||0,o=r.internalFormat||r.format||T,s=nt(o),a=r.format||s.format,c=r.type||s.type;if(Ne(e,r),n===se)for(let t=0;t<6;++t)e.texImage2D(Jr+t,i,o,r.width,r.height,0,a,c,null);else n===Ee||n===Ae?e.texImage3D(n,i,o,r.width,r.height,r.depth,0,a,c,null):e.texImage2D(n,i,o,r.width,r.height,0,a,c,null)}function Ui(e,t,r){r=r||it,t=t||ae.textureOptions;const n=e.createTexture(),i=t.target||ce;let o=t.width||1,s=t.height||1;const a=t.internalFormat||T;e.bindTexture(i,n),i===se&&(e.texParameteri(i,qt,Qt),e.texParameteri(i,Xt,Qt));let c=t.src;if(c)if("function"==typeof c&&(c=c(e,t)),"string"==typeof c)Ju(e,n,t,r);else if(Ke(c)||Array.isArray(c)&&("number"==typeof c[0]||Array.isArray(c[0])||Ke(c[0]))){const r=tl(e,n,c,t);o=r.width,s=r.height}else Array.isArray(c)&&("string"==typeof c[0]||Di(c[0]))?i===se?Zu(e,n,t,r):el(e,n,t,r):(Bi(e,n,c,t),o=c.width,s=c.height);else rl(e,n,t);return Je(t)&&kr(e,n,t,o,s,a),Mi(e,n,t),n}const rn=wi;function Li(e){return typeof document<"u"&&document.getElementById?document.getElementById(e):null}const Kt=33984,tr=34962,nl=34963,il=35713,ol=35714,sl=35632,al=35633,cl=35981,zi=35718,ul=35721,ll=35971,fl=35382,dl=35396,hl=35398,ml=35392,pl=35395,rr=5126,Ni=35664,$i=35665,Wi=35666,nn=5124,Gi=35667,Vi=35668,Hi=35669,ji=35670,Yi=35671,Qi=35672,qi=35673,Xi=35674,Ki=35675,Ji=35676,gl=35678,yl=35680,bl=35679,wl=35682,xl=35685,vl=35686,_l=35687,El=35688,Al=35689,Tl=35690,Sl=36289,Il=36292,kl=36293,on=5125,Zi=36294,eo=36295,to=36296,Rl=36298,Pl=36299,Fl=36300,Cl=36303,Ol=36306,Ml=36307,Bl=36308,Dl=36311,nr=3553,ir=34067,sn=32879,or=35866,w={};function ro(e,t){return w[t].bindPoint}function Ul(e,t){return function(r){e.uniform1f(t,r)}}function Ll(e,t){return function(r){e.uniform1fv(t,r)}}function zl(e,t){return function(r){e.uniform2fv(t,r)}}function Nl(e,t){return function(r){e.uniform3fv(t,r)}}function $l(e,t){return function(r){e.uniform4fv(t,r)}}function no(e,t){return function(r){e.uniform1i(t,r)}}function io(e,t){return function(r){e.uniform1iv(t,r)}}function oo(e,t){return function(r){e.uniform2iv(t,r)}}function so(e,t){return function(r){e.uniform3iv(t,r)}}function ao(e,t){return function(r){e.uniform4iv(t,r)}}function Wl(e,t){return function(r){e.uniform1ui(t,r)}}function Gl(e,t){return function(r){e.uniform1uiv(t,r)}}function Vl(e,t){return function(r){e.uniform2uiv(t,r)}}function Hl(e,t){return function(r){e.uniform3uiv(t,r)}}function jl(e,t){return function(r){e.uniform4uiv(t,r)}}function Yl(e,t){return function(r){e.uniformMatrix2fv(t,!1,r)}}function Ql(e,t){return function(r){e.uniformMatrix3fv(t,!1,r)}}function ql(e,t){return function(r){e.uniformMatrix4fv(t,!1,r)}}function Xl(e,t){return function(r){e.uniformMatrix2x3fv(t,!1,r)}}function Kl(e,t){return function(r){e.uniformMatrix3x2fv(t,!1,r)}}function Jl(e,t){return function(r){e.uniformMatrix2x4fv(t,!1,r)}}function Zl(e,t){return function(r){e.uniformMatrix4x2fv(t,!1,r)}}function ef(e,t){return function(r){e.uniformMatrix3x4fv(t,!1,r)}}function tf(e,t){return function(r){e.uniformMatrix4x3fv(t,!1,r)}}function D(e,t,r,n){const i=ro(e,t);return rt(e)?function(t){let o,s;!t||Xr(e,t)?(o=t,s=null):(o=t.texture,s=t.sampler),e.uniform1i(n,r),e.activeTexture(Kt+r),e.bindTexture(i,o),e.bindSampler(r,s)}:function(t){e.uniform1i(n,r),e.activeTexture(Kt+r),e.bindTexture(i,t)}}function U(e,t,r,n,i){const o=ro(e,t),s=new Int32Array(i);for(let e=0;e<i;++e)s[e]=r+e;return rt(e)?function(t){e.uniform1iv(n,s),t.forEach(function(t,n){let i,a;e.activeTexture(Kt+s[n]),!t||Xr(e,t)?(i=t,a=null):(i=t.texture,a=t.sampler),e.bindSampler(r,a),e.bindTexture(o,i)})}:function(t){e.uniform1iv(n,s),t.forEach(function(t,r){e.activeTexture(Kt+s[r]),e.bindTexture(o,t)})}}function sr(e,t){return function(r){if(r.value)switch(e.disableVertexAttribArray(t),r.value.length){case 4:e.vertexAttrib4fv(t,r.value);break;case 3:e.vertexAttrib3fv(t,r.value);break;case 2:e.vertexAttrib2fv(t,r.value);break;case 1:e.vertexAttrib1fv(t,r.value);break;default:throw new Error("the length of a float constant value must be between 1 and 4!")}else e.bindBuffer(tr,r.buffer),e.enableVertexAttribArray(t),e.vertexAttribPointer(t,r.numComponents||r.size,r.type||rr,r.normalize||!1,r.stride||0,r.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,r.divisor||0)}}function ue(e,t){return function(r){if(r.value){if(e.disableVertexAttribArray(t),4!==r.value.length)throw new Error("The length of an integer constant value must be 4!");e.vertexAttrib4iv(t,r.value)}else e.bindBuffer(tr,r.buffer),e.enableVertexAttribArray(t),e.vertexAttribIPointer(t,r.numComponents||r.size,r.type||nn,r.stride||0,r.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,r.divisor||0)}}function ar(e,t){return function(r){if(r.value){if(e.disableVertexAttribArray(t),4!==r.value.length)throw new Error("The length of an unsigned integer constant value must be 4!");e.vertexAttrib4uiv(t,r.value)}else e.bindBuffer(tr,r.buffer),e.enableVertexAttribArray(t),e.vertexAttribIPointer(t,r.numComponents||r.size,r.type||on,r.stride||0,r.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,r.divisor||0)}}function an(e,t,r){const n=r.size,i=r.count;return function(r){e.bindBuffer(tr,r.buffer);const o=r.size||r.numComponents||n,s=o/i,a=r.type||rr,c=w[a].size*o,u=r.normalize||!1,l=r.offset||0,f=c/i;for(let n=0;n<i;++n)e.enableVertexAttribArray(t+n),e.vertexAttribPointer(t+n,s,a,u,c,l+f*n),e.vertexAttribDivisor&&e.vertexAttribDivisor(t+n,r.divisor||0)}}w[rr]={Type:Float32Array,size:4,setter:Ul,arraySetter:Ll},w[Ni]={Type:Float32Array,size:8,setter:zl,cols:2},w[$i]={Type:Float32Array,size:12,setter:Nl,cols:3},w[Wi]={Type:Float32Array,size:16,setter:$l,cols:4},w[nn]={Type:Int32Array,size:4,setter:no,arraySetter:io},w[Gi]={Type:Int32Array,size:8,setter:oo,cols:2},w[Vi]={Type:Int32Array,size:12,setter:so,cols:3},w[Hi]={Type:Int32Array,size:16,setter:ao,cols:4},w[on]={Type:Uint32Array,size:4,setter:Wl,arraySetter:Gl},w[Zi]={Type:Uint32Array,size:8,setter:Vl,cols:2},w[eo]={Type:Uint32Array,size:12,setter:Hl,cols:3},w[to]={Type:Uint32Array,size:16,setter:jl,cols:4},w[ji]={Type:Uint32Array,size:4,setter:no,arraySetter:io},w[Yi]={Type:Uint32Array,size:8,setter:oo,cols:2},w[Qi]={Type:Uint32Array,size:12,setter:so,cols:3},w[qi]={Type:Uint32Array,size:16,setter:ao,cols:4},w[Xi]={Type:Float32Array,size:32,setter:Yl,rows:2,cols:2},w[Ki]={Type:Float32Array,size:48,setter:Ql,rows:3,cols:3},w[Ji]={Type:Float32Array,size:64,setter:ql,rows:4,cols:4},w[xl]={Type:Float32Array,size:32,setter:Xl,rows:2,cols:3},w[vl]={Type:Float32Array,size:32,setter:Jl,rows:2,cols:4},w[_l]={Type:Float32Array,size:48,setter:Kl,rows:3,cols:2},w[El]={Type:Float32Array,size:48,setter:ef,rows:3,cols:4},w[Al]={Type:Float32Array,size:64,setter:Zl,rows:4,cols:2},w[Tl]={Type:Float32Array,size:64,setter:tf,rows:4,cols:3},w[gl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:nr},w[yl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:ir},w[bl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:sn},w[wl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:nr},w[Sl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:or},w[Il]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:or},w[kl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:ir},w[Rl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:nr},w[Pl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:sn},w[Fl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:ir},w[Cl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:or},w[Ol]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:nr},w[Ml]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:sn},w[Bl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:ir},w[Dl]={Type:null,size:0,setter:D,arraySetter:U,bindPoint:or};const I={};I[rr]={size:4,setter:sr},I[Ni]={size:8,setter:sr},I[$i]={size:12,setter:sr},I[Wi]={size:16,setter:sr},I[nn]={size:4,setter:ue},I[Gi]={size:8,setter:ue},I[Vi]={size:12,setter:ue},I[Hi]={size:16,setter:ue},I[on]={size:4,setter:ar},I[Zi]={size:8,setter:ar},I[eo]={size:12,setter:ar},I[to]={size:16,setter:ar},I[ji]={size:4,setter:ue},I[Yi]={size:8,setter:ue},I[Qi]={size:12,setter:ue},I[qi]={size:16,setter:ue},I[Xi]={size:4,setter:an,count:2},I[Ki]={size:9,setter:an,count:3},I[Ji]={size:16,setter:an,count:4};const rf=/ERROR:\s*\d+:(\d+)/gi;function nf(e,t="",r=0){const n=[...t.matchAll(rf)],i=new Map(n.map((e,r)=>{const i=parseInt(e[1]),o=n[r+1],s=o?o.index:t.length;return[i-1,t.substring(e.index,s)]}));return e.split("\n").map((e,t)=>{const n=i.get(t);return`${t+1+r}: ${e}${n?`\n\n^^^ ${n}`:""}`}).join("\n")}const Zn=/^[ \t]*\n/;function co(e){let t=0;return Zn.test(e)&&(t=1,e=e.replace(Zn,"")),{lineOffset:t,shaderSource:e}}function of(e,t){return e.errorCallback(t),e.callback&&setTimeout(()=>{e.callback(`${t}\n${e.errors.join("\n")}`)}),null}function sf(e,t,r,n){if(n=n||rn,!e.getShaderParameter(r,il)){const i=e.getShaderInfoLog(r),{lineOffset:o,shaderSource:s}=co(e.getShaderSource(r)),a=`${nf(s,i,o)}\nError compiling ${Si(e,t)}: ${i}`;return n(a),a}return""}function cn(e,t,r){let n,i,o;if("function"==typeof t&&(r=t,t=void 0),"function"==typeof e)r=e,e=void 0;else if(e&&!Array.isArray(e)){const t=e;r=t.errorCallback,e=t.attribLocations,n=t.transformFeedbackVaryings,i=t.transformFeedbackMode,o=t.callback}const s=r||rn,a=[],c={errorCallback(e,...t){a.push(e),s(e,...t)},transformFeedbackVaryings:n,transformFeedbackMode:i,callback:o,errors:a};{let r={};Array.isArray(e)?e.forEach(function(e,n){r[e]=t?t[n]:n}):r=e||{},c.attribLocations=r}return c}const af=["VERTEX_SHADER","FRAGMENT_SHADER"];function cf(e,t){return t.indexOf("frag")>=0?sl:t.indexOf("vert")>=0?al:void 0}function uf(e,t,r){const n=e.getAttachedShaders(t);for(const t of n)r.has(t)&&e.deleteShader(t);e.deleteProgram(t)}const lf=(e=0)=>new Promise(t=>setTimeout(t,e));function ff(e,t,r){const n=e.createProgram(),{attribLocations:i,transformFeedbackVaryings:o,transformFeedbackMode:s}=cn(r);for(let r=0;r<t.length;++r){let i=t[r];if("string"==typeof i){const t=Li(i),o=t?t.text:i;let s=e[af[r]];t&&t.type&&(s=cf(e,t.type)||s),i=e.createShader(s),e.shaderSource(i,co(o).shaderSource),e.compileShader(i),e.attachShader(n,i)}}Object.entries(i).forEach(([t,r])=>e.bindAttribLocation(n,r,t));{let t=o;t&&(t.attribs&&(t=t.attribs),Array.isArray(t)||(t=Object.keys(t)),e.transformFeedbackVaryings(n,t,s||cl))}return e.linkProgram(n),n}function df(e,t,r,n,i){const o=cn(r,n,i),s=new Set(t),a=ff(e,t,o);function c(e,t){const r=mf(e,t,o.errorCallback);return r&&uf(e,t,s),r}if(!o.callback)return c(e,a)?void 0:a;hf(e,a).then(()=>{const t=c(e,a);o.callback(t,t?void 0:a)})}async function hf(e,t){const r=e.getExtension("KHR_parallel_shader_compile"),n=r?(e,t)=>e.getProgramParameter(t,r.COMPLETION_STATUS_KHR):()=>!0;let i=0;do{await lf(i),i=1e3/60}while(!n(e,t))}function mf(e,t,r){if(r=r||rn,!e.getProgramParameter(t,ol)){const n=e.getProgramInfoLog(t);r(`Error in program linking: ${n}`);return`${n}\n${e.getAttachedShaders(t).map(t=>sf(e,e.getShaderParameter(t,e.SHADER_TYPE),t,r)).filter(e=>e).join("\n")}`}}function pf(e,t,r,n,i){return df(e,t,r,n,i)}function uo(e){const t=e.name;return t.startsWith("gl_")||t.startsWith("webgl_")}const gf=/(\.|\[|]|\w+)/g,yf=e=>e>="0"&&e<="9";function bf(e,t,r,n){const i=e.split(gf).filter(e=>""!==e);let o=0,s="";for(;;){const e=i[o++];s+=e;const a=yf(e[0]),c=a?parseInt(e):e;if(a&&(s+=i[o++]),o===i.length){r[c]=t;break}{const e=i[o++],t="["===e,a=r[c]||(t?[]:{});r[c]=a,r=a,n[s]=n[s]||function(e){return function(t){lo(e,t)}}(a),s+=e}}}function wf(e,t){let r=0;function n(t,n,i){const o=n.name.endsWith("[0]"),s=n.type,a=w[s];if(!a)throw new Error(`unknown type: 0x${s.toString(16)}`);let c;if(a.bindPoint){const t=r;r+=n.size,c=o?a.arraySetter(e,s,t,i,n.size):a.setter(e,s,t,i,n.size)}else c=a.arraySetter&&o?a.arraySetter(e,i):a.setter(e,i);return c.location=i,c}const i={},o={},s=e.getProgramParameter(t,zi);for(let r=0;r<s;++r){const s=e.getActiveUniform(t,r);if(uo(s))continue;let a=s.name;a.endsWith("[0]")&&(a=a.substr(0,a.length-3));const c=e.getUniformLocation(t,s.name);if(c){const e=n(0,s,c);i[a]=e,bf(a,e,o,i)}}return i}function xf(e,t){const r={},n=e.getProgramParameter(t,ll);for(let i=0;i<n;++i){const n=e.getTransformFeedbackVarying(t,i);r[n.name]={index:i,type:n.type,size:n.size}}return r}function vf(e,t){const r=e.getProgramParameter(t,zi),n=[],i=[];for(let o=0;o<r;++o){i.push(o),n.push({});const r=e.getActiveUniform(t,o);n[o].name=r.name}[["UNIFORM_TYPE","type"],["UNIFORM_SIZE","size"],["UNIFORM_BLOCK_INDEX","blockNdx"],["UNIFORM_OFFSET","offset"]].forEach(function(r){const o=r[0],s=r[1];e.getActiveUniforms(t,i,e[o]).forEach(function(e,t){n[t][s]=e})});const o={},s=e.getProgramParameter(t,fl);for(let r=0;r<s;++r){const n=e.getActiveUniformBlockName(t,r),i={index:e.getUniformBlockIndex(t,n),usedByVertexShader:e.getActiveUniformBlockParameter(t,r,dl),usedByFragmentShader:e.getActiveUniformBlockParameter(t,r,hl),size:e.getActiveUniformBlockParameter(t,r,ml),uniformIndices:e.getActiveUniformBlockParameter(t,r,pl)};i.used=i.usedByVertexShader||i.usedByFragmentShader,o[n]=i}return{blockSpecs:o,uniformData:n}}function lo(e,t){for(const r in t){const n=e[r];"function"==typeof n?n(t[r]):lo(e[r],t[r])}}function fo(e,...t){const r=e.uniformSetters||e,n=t.length;for(let e=0;e<n;++e){const n=t[e];if(Array.isArray(n)){const e=n.length;for(let t=0;t<e;++t)fo(r,n[t])}else for(const e in n){const t=r[e];t&&t(n[e])}}}function _f(e,t){const r={},n=e.getProgramParameter(t,ul);for(let i=0;i<n;++i){const n=e.getActiveAttrib(t,i);if(uo(n))continue;const o=e.getAttribLocation(t,n.name),s=I[n.type],a=s.setter(e,o,s);a.location=o,r[n.name]=a}return r}function Ef(e,t){for(const r in t){const n=e[r];n&&n(t[r])}}function Af(e,t,r){r.vertexArrayObject?e.bindVertexArray(r.vertexArrayObject):(Ef(t.attribSetters||t,r.attribs),r.indices&&e.bindBuffer(nl,r.indices))}function ei(e,t){const r={program:t,uniformSetters:wf(e,t),attribSetters:_f(e,t)};return rt(e)&&(r.uniformBlockSpec=vf(e,t),r.transformFeedbackInfo=xf(e,t)),r}const Tf=/\s|{|}|;/;function Sf(e,t,r,n,i){const o=cn(r,n,i),s=[];if(t=t.map(function(e){if(!Tf.test(e)){const t=Li(e);if(t)e=t.text;else{const t=`no element with id: ${e}`;o.errorCallback(t),s.push(t)}}return e}),s.length)return of(o,"");const a=o.callback;a&&(o.callback=(t,r)=>{a(t,t?void 0:ei(e,r))});const c=pf(e,t,o);return c?ei(e,c):null}const If=4,ti=5123;function kf(e,t,r,n,i,o){r=void 0===r?4:r;const s=t.indices,a=t.elementType,c=void 0===n?t.numElements:n;i=void 0===i?0:i,a||s?void 0!==o?e.drawElementsInstanced(r,c,void 0===a?ti:t.elementType,i,o):e.drawElements(r,c,void 0===a?ti:t.elementType,i):void 0!==o?e.drawArraysInstanced(r,i,c,o):e.drawArrays(r,i,c)}const ho=36160,At=36161,Rf=3553,Pf=5121,Ff=6402,Cf=6408,Of=33190,Mf=36012,Bf=35056,Df=36013,Uf=32854,Lf=32855,zf=36194,mo=33189,po=6401,go=36168,un=34041,Fr=36064,cr=36096,yo=36128,ln=33306,Cr=33071,Or=9729,Nf=[{format:Cf,type:Pf,min:Or,wrap:Cr},{format:un}],V={};function $f(e,t){return V[e]||V[t]}V[un]=ln,V[po]=yo,V[go]=yo,V[Ff]=cr,V[mo]=cr,V[Of]=cr,V[Mf]=cr,V[Bf]=ln,V[Df]=ln;const le={};function Wf(e){return le[e]}le[Uf]=!0,le[Lf]=!0,le[zf]=!0,le[un]=!0,le[mo]=!0,le[po]=!0,le[go]=!0;const Gf=32;function Vf(e){return e>=Fr&&e<36096}function ri(e,t,r,n){const i=ho,o=e.createFramebuffer();e.bindFramebuffer(i,o),r=r||e.drawingBufferWidth,n=n||e.drawingBufferHeight;const s=[],a={framebuffer:o,attachments:[],width:r,height:n};return(t=t||Nf).forEach(function(t,o){let c=t.attachment;const u=t.samples,l=t.format;let f=t.attachmentPoint||$f(l,t.internalFormat);if(f||(f=Fr+o),Vf(f)&&s.push(f),!c)if(void 0!==u||Wf(l))c=e.createRenderbuffer(),e.bindRenderbuffer(At,c),u>1?e.renderbufferStorageMultisample(At,u,l,r,n):e.renderbufferStorage(At,l,r,n);else{const i=Object.assign({},t);i.width=r,i.height=n,void 0===i.auto&&(i.auto=!1,i.min=i.min||i.minMag||Or,i.mag=i.mag||i.minMag||Or,i.wrapS=i.wrapS||i.wrap||Cr,i.wrapT=i.wrapT||i.wrap||Cr),c=Ui(e,i)}if(Ja(e,c))e.framebufferRenderbuffer(i,f,At,c);else{if(!Xr(e,c))throw new Error("unknown attachment type");void 0!==t.layer?e.framebufferTextureLayer(i,f,c,t.level||0,t.layer):e.framebufferTexture2D(i,f,t.target||Rf,c,t.level||0)}a.attachments.push(c)}),e.drawBuffers&&e.drawBuffers(s),a}function Hf(e,t,r){r=r||ho,t?(e.bindFramebuffer(r,t.framebuffer),e.viewport(0,0,t.width,t.height)):(e.bindFramebuffer(r,null),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight))}function B(e,t){return()=>t instanceof WebGLTexture?t:Ui(e,{src:t,wrap:e.CLAMP_TO_EDGE})}const Ue=2;class ot{constructor(e){this.id="_";const{context:t,width:r,height:n}=e;this.context=t,this.options=e;const i=this.buildDefines();this.programInfo=Sf(this.context,[i+this.getVertexShader(),i+this.getFragmentShader()]),this.bufferInfo=_c(this.context,this.getBuffers()),this.fbi=ri(this.context,[{format:this.context.RGBA,type:this.context.UNSIGNED_BYTE,min:this.context.LINEAR,wrap:this.context.CLAMP_TO_EDGE}],r,n),this.output=this.fbi.attachments[0]}resizeOutput(e,t){this.fbi=ri(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 r in t)e+=`#define ${r} ${t[r].toFixed(1)}\n`;return e}run(e){this.profiler?.pushContext(`[${this.id}] PROG : ${this.constructor.name}`),this.profiler?.pushContext(`[${this.id}] UNIFORMS`);for(const t in e)"function"==typeof e[t]&&(this.profiler?.pushContext(`[${this.id}] UNI : ${t}`),e[t]=e[t](),this.profiler?.popContext(`[${this.id}] UNI : ${t}`));this.profiler?.popContext(`[${this.id}] UNIFORMS`);const t=Date.now();let r=0;this.lastRun&&(r=(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),Af(this.context,this.programInfo,this.bufferInfo),fo(this.programInfo,{delta:r,canvas:[this.context.canvas.width,this.context.canvas.height],...e}),Hf(this.context,this.options.disableFramebuffer?null:this.fbi),kf(this.context,this.bufferInfo),this.profiler?.popContext(`[${this.id}] PROG : ${this.constructor.name}`)}setProfiler(e){this.profiler=e}}const jf="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",Yf="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 fn extends ot{getFragmentShader(){return jf}getVertexShader(){return Yf}}class dn{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 r of this.steps)r.preventResize||r.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 hn extends dn{constructor(){super(...arguments),this.preciseMaskEnabled=!1}}class bo extends hn{constructor(e){super(),this.context=e,this.preciseMaskEnabled=!0;const t={context:e,height:e.canvas.height,width:e.canvas.width},r=new fn({...t,disableFramebuffer:!0});this.addStep({program:r,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 Qf="precision mediump float;\n\nvarying vec2 _texture_coord;\nuniform sampler2D texture;\n\nvoid main() { gl_FragColor = texture2D(texture, _texture_coord); }\n",qf="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 Xf extends ot{getFragmentShader(){return Qf}getVertexShader(){return qf}}class Kf extends dn{constructor(e,t,r){super(),this.context=e;const n={context:e,height:r,width:t};this.addStep({program:new Xf({...n,disableFramebuffer:!0}),getUniforms:()=>({texture:B(e,this.inputImage),invert_y:!0})})}setData(e){this.inputImage=e}}async function wo(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}const Jf="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",Zf="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";var mn=(e=>(e[e.LINEAR=0]="LINEAR",e[e.GAUSSIAN=1]="GAUSSIAN",e))(mn||{});class xo extends ot{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return Jf+this.createLoopFunction()}getVertexShader(){return Zf}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 }`}}const ed="#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}",td="#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 rd extends ot{getFragmentShader(){return ed}getVertexShader(){return td}}class nd extends dn{constructor(e,t,r){super(),this.context=e;const n={context:e,height:r,width:t},i=new xo({...n,radius:1,type:mn.GAUSSIAN});this.jointBilateral=new rd(n),this.addStep({program:i,getUniforms:()=>({inputs:B(e,this.inputMask)})}),this.addStep({program:this.jointBilateral,getUniforms:()=>{const t=this.inputImage?.width??1,r=this.inputImage?.height??1;this.inputMask,this.inputMask;const n=Math.max(1,.66*Math.sqrt(3)),i=1/t,o=1/r;return{input_frame:B(e,this.inputImage),segmentation_mask:B(e,this.inputMask),texel_size:[i,o],step:n,radius:3,offset:n>1?.5*n:0,sigma_texel:3*Math.max(i,o),sigma_color:3}}}),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 vo=(e=>(e.PUSH="PUSH",e.POP="POP",e))(vo||{});class id{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(e=>this.resolveQuery(e)))).filter(e=>e);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)){if(!this.context.getParameter(this.extension.GPU_DISJOINT_EXT))return{...e,duration:this.context.getQueryParameter(e.query,this.context.QUERY_RESULT),timestamp:0};console.log("Disjointed query",e)}else console.log("Unawaitable query",e)}async awaitQueryAvailable(e){for(let t=0;t<10;++t){if(this.context.getQueryParameter(e.query,this.context.QUERY_RESULT_AVAILABLE))return e;await wo(200)}}}class ur{constructor(){this.previousImageWidth=0,this.previousImageHeight=0,this.previousMaskWidth=2,this.previousMaskHeight=2,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 nd(this.context,2,2)}enablePostProcessing(){this.postProcessingEnabled=!0}disablePostProcessing(){this.postProcessingEnabled=!1}async profileWebgl(e){const t=new id(this.context);return this.profiler=t,t.start(),await wo(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 r="renderer";this.profiler?.pushContext(r),this.improveMask.setProfiler(this.profiler),this.pipeline.setProfiler(this.profiler);const n=await createImageBitmap(t);let i=n;return this.postProcessingEnabled&&(this.improveMask.setData(e,n),this.improveMask.run(),i=this.improveMask.output),this.pipeline.setData(e,i),await this.pipeline.run(),this.profiler?.popContext(r),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 _o extends ur{constructor(){super(),this.pipeline=new bo(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 Kf(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 od extends _o{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 ni{blurBackground(e){return new za(e)}blurSilhouette(e){return new Na(e)}imageBackground(){return new $a}videoBackground(){return new od}}const sd="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",ad="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 cd extends ot{getDefines(){return{RADIUS:this.options.radius??1}}getFragmentShader(){return sd+this.createLoopFunction()}getVertexShader(){return ad}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 ud=10,ld=2,fd=8;class dd extends hn{constructor(e,t){super(),this.context=e,this.radius=t;const r={context:e,height:e.canvas.height,width:e.canvas.width};this.blur=new cd({...r,radius:t,...this.getBlurTextureSize(e.canvas.width,e.canvas.height)});const n=new fn({...r,disableFramebuffer:!0});this.addStep({program:this.blur,preventResize:!0,getUniforms:()=>({texture:B(e,this.inputImage),mask:B(e,this.inputMask)})}),this.addStep({program:n,getUniforms:()=>({background:B(e,this.blur.output),foreground:B(e,this.inputImage),threshold:B(e,this.inputMask)})})}getBlurTextureSize(e,t){const r=this.radius>10?8:2;return{width:Math.max(2,e/r),height:Math.max(2,t/r)}}setData(e,t){this.inputImage=e,this.inputMask=t}resizeOutput(e,t){super.resizeOutput(e,t);const r=this.getBlurTextureSize(e,t);this.blur.resizeOutput(r.width,r.height)}}class hd extends ur{constructor(e){super(),this.pipeline=new dd(this.context,e),this.disablePostProcessing()}}class md extends hn{constructor(e,t){super(),this.context=e;const r={context:e,height:e.canvas.height,width:e.canvas.width},n=new xo({...r,radius:t,type:mn.GAUSSIAN}),i=new fn({...r,disableFramebuffer:!0});this.addStep({program:n,getUniforms:()=>({texture:B(e,this.inputImage)})}),this.addStep({program:i,getUniforms:()=>({background:B(e,this.inputImage),foreground:B(e,n.output),threshold:B(e,this.inputMask)})})}setData(e,t){this.inputImage=e,this.inputMask=t}}class pd extends ur{constructor(e){super(),this.pipeline=new md(this.context,e),this.disablePostProcessing()}}class gd extends bo{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 yd extends ur{constructor(){super(),this.pipeline=new gd(this.context)}setBackgroundVideo(e){this.pipeline.reader=e}}class ii{blurBackground(e){return new hd(e)}blurSilhouette(e){return new pd(e)}imageBackground(){return new _o}videoBackground(){return new yd}}class bd{constructor(e){switch(e){case Mt.CANVAS:this.factory=new ni;break;case Mt.WEBGL:this.factory=new ii;break;default:const e=fi();this.factory=e.supported?new ii:new ni}}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 wd{setBackgroundOptions(e){this.renderer&&this.renderer.destroy();const t=new bd(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 r=t.videoBackground();this.backgroundVideo&&r.setBackgroundVideo(this.backgroundVideo),this.renderer=r;break;case"VirtualBackground":const n=t.imageBackground();this.backgroundImage&&n.setBackgroundImage(this.backgroundImage),this.renderer=n;break;default:throw`Unknown rendering type [${e.transformerType}]`}e.renderingOptions?.type===Mt.WEBGL&&(e.renderingOptions.selfieSegmentationType===Ar.PRECISE?this.renderer.enablePostProcessing():e.renderingOptions.selfieSegmentationType===Ar.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=It.Low){switch(e){case It.Low:return 5;case It.High:return 12}return e}async profile(e){return this.renderer?.profileWebgl(e)??[]}}var xd=function(){var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(t){var r,n,i=typeof(t=t||{})<"u"?t:{};i.ready=new Promise(function(e,t){r=e,n=t});var o,s={};for(o in i)i.hasOwnProperty(o)&&(s[o]=i[o]);var a="./this.program",c=function(e,t){throw t},u="";typeof document<"u"&&document.currentScript&&(u=document.currentScript.src),e&&(u=e),u=0!==u.indexOf("blob:")?u.substr(0,u.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var l,f=i.print||console.log.bind(console),h=i.printErr||console.warn.bind(console);for(o in s)s.hasOwnProperty(o)&&(i[o]=s[o]);s=null,i.arguments&&i.arguments,i.thisProgram&&(a=i.thisProgram),i.quit&&(c=i.quit),i.wasmBinary&&(l=i.wasmBinary),i.noExitRuntime,"object"!=typeof WebAssembly&&O("no native wasm support detected");var d,m,p,g,y,b=!1,w=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function v(e,t,r){for(var n=t+r,i=t;e[i]&&!(i>=n);)++i;if(i-t>16&&e.subarray&&w)return w.decode(e.subarray(t,i));for(var o="";t<i;){var s=e[t++];if(128&s){var a=63&e[t++];if(192!=(224&s)){var c=63&e[t++];if((s=224==(240&s)?(15&s)<<12|a<<6|c:(7&s)<<18|a<<12|c<<6|63&e[t++])<65536)o+=String.fromCharCode(s);else{var u=s-65536;o+=String.fromCharCode(55296|u>>10,56320|1023&u)}}else o+=String.fromCharCode((31&s)<<6|a)}else o+=String.fromCharCode(s)}return o}function x(e,t){return e?v(g,e,t):""}function k(e,t){return e%t>0&&(e+=t-e%t),e}function _(e){m=e,i.HEAP8=p=new Int8Array(e),i.HEAP16=new Int16Array(e),i.HEAP32=y=new Int32Array(e),i.HEAPU8=g=new Uint8Array(e),i.HEAPU16=new Uint16Array(e),i.HEAPU32=new Uint32Array(e),i.HEAPF32=new Float32Array(e),i.HEAPF64=new Float64Array(e)}i.INITIAL_MEMORY;var A,E=[],T=[],I=[];function S(e){E.unshift(e)}function P(e){I.unshift(e)}var F=0,R=null;function O(e){i.onAbort&&i.onAbort(e),h(e="Aborted("+e+")"),b=!0,e+=". Build with -s ASSERTIONS=1 for more info.";var t=new WebAssembly.RuntimeError(e);throw n(t),t}i.preloadedImages={},i.preloadedAudios={};var C,M,z;function B(e){return e.startsWith("data:application/octet-stream;base64,")}function D(e){try{if(e==C&&l)return new Uint8Array(l);throw"both async and sync fetching of the wasm failed"}catch(e){O(e)}}function U(e){for(;e.length>0;){var t=e.shift();if("function"!=typeof t){var r=t.func;"number"==typeof r?void 0===t.arg?A.get(r)():A.get(r)(t.arg):r(void 0===t.arg?null:t.arg)}else t(i)}}B(C="tflite-simd.wasm")||(M=C,C=i.locateFile?i.locateFile(M,u):u+M),z=function(){return performance.now()};function L(e){try{return d.grow(e-m.byteLength+65535>>>16),_(d.buffer),1}catch{}}var N={};function W(){if(!W.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:a||"./this.program"};for(var t in N)void 0===N[t]?delete e[t]:e[t]=N[t];var r=[];for(var t in e)r.push(t+"="+e[t]);W.strings=r}return W.strings}var j={mappings:{},buffers:[null,[],[]],printChar:function(e,t){var r=j.buffers[e];0===t||10===t?((1===e?f:h)(v(r,0)),r.length=0):r.push(t)},varargs:void 0,get:function(){return j.varargs+=4,y[j.varargs-4>>2]},getStr:function(e){return x(e)},get64:function(e,t){return e}};var V={a:function(e,t,r,n){O("Assertion failed: "+x(e)+", at: "+[t?x(t):"unknown filename",r,n?x(n):"unknown function"])},e:function(e,t){O("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},d:function(e,t){O("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},b:function(){O("")},n:function(e,t){var r;if(0===e)r=Date.now();else{if(1!==e&&4!==e)return function(e){y[G()>>2]=e}(28),-1;r=z()}return y[t>>2]=r/1e3|0,y[t+4>>2]=r%1e3*1e3*1e3|0,0},h:function(){return 2147483648},l:function(e,t,r){g.copyWithin(e,t,t+r)},m:function(e){var t=g.length,r=2147483648;if((e>>>=0)>r)return!1;for(var n=1;n<=4;n*=2){var i=t*(1+.2/n);if(i=Math.min(i,e+100663296),L(Math.min(r,k(Math.max(e,i),65536))))return!0}return!1},p:function(e){for(var t=z();z()-t<e;);},f:function(e,t){var r=0;return W().forEach(function(n,i){var o=t+r;y[e+4*i>>2]=o,function(e,t){for(var r=0;r<e.length;++r)p[0|t++]=e.charCodeAt(r);p[0|t]=0}(n,o),r+=n.length+1}),0},g:function(e,t){var r=W();y[e>>2]=r.length;var n=0;return r.forEach(function(e){n+=e.length+1}),y[t>>2]=n,0},j:function(e){!function(e){!function(e){c(e,new H(e))}(e)}(e)},i:function(e){return 0},k:function(e,t,r,n,i){},c:function(e,t,r,n){for(var i=0,o=0;o<r;o++){for(var s=y[t+8*o>>2],a=y[t+(8*o+4)>>2],c=0;c<a;c++)j.printChar(e,g[s+c]);i+=a}return y[n>>2]=i,0},o:function e(t,r){e.randomDevice||(e.randomDevice=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return function(){return crypto.getRandomValues(e),e[0]}}return function(){O("randomDevice")}}());for(var n=0;n<r;n++)p[t+n|0]=e.randomDevice();return 0}};(function(){var e={a:V};function t(e,t){var r=e.exports;i.asm=r,_((d=i.asm.q).buffer),A=i.asm.E,function(e){T.unshift(e)}(i.asm.r),function(){if(F--,i.monitorRunDependencies&&i.monitorRunDependencies(F),0==F&&R){var e=R;R=null,e()}}()}function r(e){t(e.instance)}function o(t){return(l||"function"!=typeof fetch?Promise.resolve().then(function(){return D(C)}):fetch(C,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load wasm binary file at '"+C+"'";return e.arrayBuffer()}).catch(function(){return D(C)})).then(function(t){return WebAssembly.instantiate(t,e)}).then(function(e){return e}).then(t,function(e){h("failed to asynchronously prepare wasm: "+e),O(e)})}if(F++,i.monitorRunDependencies&&i.monitorRunDependencies(F),i.instantiateWasm)try{return i.instantiateWasm(e,t)}catch(e){return h("Module.instantiateWasm callback failed with error: "+e),!1}(l||"function"!=typeof WebAssembly.instantiateStreaming||B(C)||"function"!=typeof fetch?o(r):fetch(C,{credentials:"same-origin"}).then(function(t){return WebAssembly.instantiateStreaming(t,e).then(r,function(e){return h("wasm streaming compile failed: "+e),h("falling back to ArrayBuffer instantiation"),o(r)})})).catch(n)})(),i.___wasm_call_ctors=function(){return(i.___wasm_call_ctors=i.asm.r).apply(null,arguments)},i._getModelBufferMemoryOffset=function(){return(i._getModelBufferMemoryOffset=i.asm.s).apply(null,arguments)},i._getInputMemoryOffset=function(){return(i._getInputMemoryOffset=i.asm.t).apply(null,arguments)},i._getInputHeight=function(){return(i._getInputHeight=i.asm.u).apply(null,arguments)},i._getInputWidth=function(){return(i._getInputWidth=i.asm.v).apply(null,arguments)},i._getInputChannelCount=function(){return(i._getInputChannelCount=i.asm.w).apply(null,arguments)},i._getOutputMemoryOffset=function(){return(i._getOutputMemoryOffset=i.asm.x).apply(null,arguments)},i._getOutputHeight=function(){return(i._getOutputHeight=i.asm.y).apply(null,arguments)},i._getOutputWidth=function(){return(i._getOutputWidth=i.asm.z).apply(null,arguments)},i._getOutputChannelCount=function(){return(i._getOutputChannelCount=i.asm.A).apply(null,arguments)},i._loadModel=function(){return(i._loadModel=i.asm.B).apply(null,arguments)},i._runInference=function(){return(i._runInference=i.asm.C).apply(null,arguments)},i._isGPUEnabled=function(){return(i._isGPUEnabled=i.asm.D).apply(null,arguments)};var $,G=i.___errno_location=function(){return(G=i.___errno_location=i.asm.F).apply(null,arguments)};function H(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function q(e){function t(){$||($=!0,i.calledRun=!0,!b&&(U(T),r(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for("function"==typeof i.postRun&&(i.postRun=[i.postRun]);i.postRun.length;)P(i.postRun.shift());U(I)}()))}F>0||(function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)S(i.preRun.shift());U(E)}(),F>0)||(i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),t()},1)):t())}if(R=function e(){$||q(),$||(R=e)},i.run=q,i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return q(),t.ready}}();class vd{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 _d="https://d3opqjmqzxf057.cloudfront.net/vonage-tensorflow-wasm/tflite-simd-wasm/1.1.3/",Ed="https://d3opqjmqzxf057.cloudfront.net/ml/selfie_segmentation/4.0.0/selfie_segmentation_landscape.tflite";async function Ad(e=_d,t=Ed){let r=new vd;return new Promise(function(n,i){(async function(){return xd({locateFile:function(t){return e+t}})})().then(e=>{if(null===e)throw console.error("loadTFLite null"),"loadTFLite null";(async function(e){return new Promise(async(n,i)=>{const o=e;if(typeof o>"u")return i("TFLite backend unavailable: wasmSimd");let s=t;console.log("TFLite modelUrl: "+s);try{const e=await(await fetch(s)).arrayBuffer();console.log("Model buffer size:",e.byteLength);const t=o._getModelBufferMemoryOffset();console.log("Model buffer memory offset:",t),console.log("Loading model buffer..."),o.HEAPU8.set(new Uint8Array(e),t);const n=o._loadModel(e.byteLength);if(console.log("Load model result:",n),0!==n)return void i("Cannot load model");r.inputWidth=o._getInputWidth(),r.inputHeight=o._getInputHeight(),r.inputChannelCount=o._getInputChannelCount(),r.inputMemoryOffset=o._getInputMemoryOffset(),console.log("Input memory offset:",r.inputMemoryOffset),console.log("Input height:",r.inputHeight),console.log("Input width:",r.inputWidth),console.log("Input channels:",r.inputChannelCount),r.outputMemoryOffset=o._getOutputMemoryOffset(),r.outputWidth=o._getOutputWidth(),r.outputHeight=o._getOutputHeight(),r.outputChannelCount=o._getOutputChannelCount(),console.log("Output memory offset:",r.outputMemoryOffset),console.log("Output height:",r.outputHeight),console.log("Output width:",r.outputWidth),console.log("Output channels:",r.outputChannelCount),r.selectedTFLite=o}catch(e){return void i(e)}n()})})(e).then(e=>{n(r)}).catch(e=>{console.error("loadTFLiteModel error"),i("loadTFLiteModel error")})}).catch(e=>{console.error("loadTFLite error:",e),i("loadTFLite error:"+e)})})}const Td=.1,Sd=.7,Id="https://d3opqjmqzxf057.cloudfront.net/ml/vonage_selfie_segmenter/float16/v1/vonage_selfie_segmenter.tflite";class kd{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(){this.ImageSegmenter&&this.wasmFileset?this.imageSegmenter=await this.ImageSegmenter.createFromOptions(this.wasmFileset,{baseOptions:{modelAssetPath:this.modelAssetUriPath,delegate:this.gpuDelegate?"GPU":"CPU"},runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!0}):console.warn("Mediapipe objects not loaded")}async loadMediapipeAssets(e,t){this.modelAssetUriPath=e||Id;const r=t?`${t}/task-vision.js`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/+esm",n=t?`${t}/wasm`:"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.20/wasm",{FilesetResolver:i,ImageSegmenter:o}=await import(r);this.ImageSegmenter=o,this.wasmFileset=await i.forVisionTasks(n)}async init(e,t,r){!1===r&&(this.gpuDelegate=!1),await this.loadMediapipeAssets(e,t),globalThis.document={},await this.createImageSegmenter()}async process(e){if(!this.imageSegmenter)return void console.warn("ImageSegmenter instance not available");(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 r;try{this.imageSegmenter?.segmentForVideo(this.context.getImageData(0,0,e.width,e.height),t,e=>{r=e.confidenceMasks?.[0]?.getAsFloat32Array()})}catch{return void await this.createImageSegmenter()}if(!r)return;if(!this.previousConfidenceMask)return void(this.previousConfidenceMask=r.slice());const n=r.map((e,t)=>{const r=this.previousConfidenceMask?.[t];return void 0!==r?this.blend(r,e):e}),i=[255,0,0];for(let e=0;e<n?.length;e++){const t=1-n[e];t>Td?(t<Sd?(this.mask.data[4*e]=i[0]*t,this.mask.data[4*e+3]=255*t):(this.mask.data[4*e]=i[0],this.mask.data[4*e+3]=255),this.mask.data[4*e+1]=i[1],this.mask.data[4*e+2]=i[2]):this.mask.data[4*e]=this.mask.data[4*e+1]=this.mask.data[4*e+2]=this.mask.data[4*e+3]=0}return this.previousConfidenceMask=n.slice(),this.mask}isGpuSupported(){return!0}blend(e,t){const r=t-.5,n=r*r;return t+.9*(1-Math.min(1,n*(5.68842+n*(n*(n*(291.309+-624.717*n)-57.8051)-.748699))))*(e-t)}}class Rd{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,r){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 Ad(e,t)}async process(e){if(!this.mask||!this.infos)return;const t=this.infos.inputWidth,r=this.infos.inputHeight;this.context.drawImage(e,0,0,e.width,e.height,0,0,t,r);const n=this.context.getImageData(0,0,t,r),i=this.infos.selectedTFLite.HEAPF32;for(let e=0;e<this.pixelCount;e++){const t=this.inputOffset+3*e;i[t]=n.data[4*e]/255,i[t+1]=n.data[4*e+1]/255,i[t+2]=n.data[4*e+2]/255}this.infos.selectedTFLite._runInference();for(let e=0;e<this.pixelCount;e++){const t=this.infos.selectedTFLite.HEAPF32[this.outputOffset+e];this.mask.data[4*e]=this.mask.data[4*e+3]=255*t}return this.mask}isGpuSupported(){return this.infos?.selectedTFLite?._isGPUEnabled()??!1}}class Pd{constructor(){this.reporter=new Ua,this.isEnabled=!0,this.avoidOriginalTrackLeak=!1}async init(e,t){!0===t.segmentationOptions?.lightWeightEngine?this.selfieSegmentation=new Rd:this.selfieSegmentation=new kd,this.selfieSegmentation?.init(t.modelAssetUriPath,t.mediapipeBaseAssetsUri,t.segmentationOptions?.gpuSupport),this.avoidOriginalTrackLeak=t.avoidOriginalTrackLeak,this.backgroundFilter=new wd,this.report({variation:"Create"})}async transform(e,t){if(!this.isEnabled)return t.enqueue(e);let r;const n=e.timestamp??0,i=await createImageBitmap(e),o=await(this.selfieSegmentation?.process(i));o&&(r=await(this.backgroundFilter?.process(i,o))),!r&&this.avoidOriginalTrackLeak&&(r=new OffscreenCanvas(i.width,i.height)),r?(e.close(),t.enqueue(new VideoFrame(r,{timestamp:n,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:La,action:"MlTransformers",transformerType:this.backgroundOptions?.transformerType,config:JSON.stringify(this.backgroundOptions),...e})}}const pn=class{constructor(){this.backgroundTransformer=new Pd,this.mediaProcessor=new li,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((e,t)=>{this.resolveOnMediaProcessor?(this.resolveOnMediaProcessor({name:e,data:t}),this.resolveOnMediaProcessor=void 0):this.eventsQueue.push({name:e,data:t})})}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 r=this.mediaProcessor.transform(e,t),n=performance.now();return this.frameTransformLatencyMs.push(performance.now()-n),r}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 e=this.frameTransformLatencyMs.reduce((e,t)=>e+t,0)/this.frameTransformLatencyMs.length||0;console.log(`Transform latency average is: ${e} ms`)}setVonageMetadata(e){Os(e)}async profile(e){return JSON.stringify(await this.backgroundTransformer.profile(e))}};ua("ProcessorWorker",pn);let Mr=pn;const Eo='(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\tdata: ${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\tdata: ${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.2",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.2-alpha.2";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,this.avoidOriginalTrackLeak=!1}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.avoidOriginalTrackLeak=t.avoidOriginalTrackLeak,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&&this.avoidOriginalTrackLeak&&(n=new OffscreenCanvas(s.width,s.height)),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-DMoxEyvv.js.map\n',oi=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Eo],{type:"text/javascript;charset=utf-8"});function Fd(e){let t;try{if(t=oi&&(self.URL||self.webkitURL).createObjectURL(oi),!t)throw"";const r=new Worker(t,{name:e?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Eo),{name:e?.name})}}const Jt=class e extends et{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":return void await this.destroy()}}}}async startWorker(){!this.config||this.worker||(this.worker=await aa(Mr,Fd),this.isEnabled||await this.worker.disable(),await this.worker.init("worker_"+e.initCount++,this.config),await this.worker.setVonageMetadata(Tt()),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 Nn.createVideoReadable(e.backgroundAssetUri)));break;case"VirtualBackground":await(this.worker?.setVirtualBGImage(await Nn.createImageCanvas(e.backgroundAssetUri)))}await(this.worker?.setBackgroundOptions(e))}};Jt.initCount=0;let Br=Jt;class Cd{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={},r=[];let n=0;for(const i of this.queries){const o=[];for(const r of i)void 0===t[r.name]&&(t[r.name]=e.length,e.push({name:r.name})),o.push({type:r.action==vo.PUSH?"O":"C",frame:t[r.name],at:r.timestamp}),n=Math.max(n,r.timestamp+r.duration);r.push({events:o,type:"evented",name:"GPU Profile",unit:"nanoseconds",startValue:0,endValue:n})}return JSON.stringify({$schema:"https://www.speedscope.app/file-format-schema.json",shared:{frames:e},profiles:r},null,2)}}const gn=class extends et{constructor(e){super(),this.worker=new Br(e),this.connector=new Qs(this.worker),this.worker.onAny((e,t)=>this.emit(e,t))}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(t=>t.profile(e)));return new Cd(t)}static async create(e){const t=new this(e);return this.instances.push(t),t}};gn.instances=[];let Dr=gn;async function Dd(e){return await Dr.create(e)}export{Pd as BackgroundTransformer,qs as BackgroundTransformerType,It as BlurRadius,Ls as ErrorFunction,Er as PipelineInfoData,Mt as RenderingType,Dr as VonageMediaProcessor,Us as WarningType,Ar as WebglSelfieSegmentationType,Dd as createVonageMediaProcessor,Ks as getSupportedBrowserFeatures,Bd as isSupported};