@100mslive/hms-video-store 0.12.35 → 0.12.36-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var co=Object.defineProperty,lo=Object.defineProperties;var uo=Object.getOwnPropertyDescriptors;var ai=Object.getOwnPropertySymbols,po=Object.getPrototypeOf,gs=Object.prototype.hasOwnProperty,Ts=Object.prototype.propertyIsEnumerable,ho=Reflect.get;var Ss=(a,e,t)=>e in a?co(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))gs.call(e,t)&&Ss(a,t,e[t]);if(ai)for(var t of ai(e))Ts.call(e,t)&&Ss(a,t,e[t]);return a},M=(a,e)=>lo(a,uo(e));var kr=(a,e)=>{var t={};for(var i in a)gs.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&ai)for(var i of ai(a))e.indexOf(i)<0&&Ts.call(a,i)&&(t[i]=a[i]);return t};var mo=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var ne=(a,e,t)=>ho(po(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=d=>{try{n(t.next(d))}catch(u){r(u)}},o=d=>{try{n(t.throw(d))}catch(u){r(u)}},n=d=>d.done?i(d.value):Promise.resolve(d.value).then(s,o);n((t=t.apply(a,e)).next())});var Ir=mo((Jc,Eo)=>{Eo.exports={version:"0.12.35",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist","src"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^1.0.1",uuid:"^8.3.2","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/lodash.isequal":"^4.5.8","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.36","@types/uuid":"^8.3.0","jest-canvas-mock":"^2.3.1","jsdom-worker":"^0.3.0",tslib:"^2.2.0"},description:"@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow",keywords:["video","webrtc","conferencing","100ms"],gitHead:"21175fa295899839b6bfd2a7fa5af06150de1df9"}});var Er=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Er||{});var oi=()=>({room:{id:"",isConnected:!1,name:"",peers:[],localPeer:"",roomState:"Disconnected",recording:{browser:{running:!1},server:{running:!1},hls:{running:!1}},rtmp:{running:!1},hls:{running:!1,variants:[]},sessionId:""},peers:{},tracks:{},playlist:{audio:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1},video:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1}},messages:{byID:{},allIDs:[]},speakers:{},connectionQualities:{},settings:{audioInputDeviceId:"",audioOutputDeviceId:"",videoInputDeviceId:""},devices:{audioInput:[],audioOutput:[],videoInput:[]},roles:{},roleChangeRequests:[],errors:[],sessionStore:{},templateAppData:{},polls:{},whiteboards:{},hideLocalPeer:!1}),ni=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var So=(e=>(e.CHAT="chat",e))(So||{});var fs=(t=>(t.INFO="info",t.ERROR="error",t))(fs||{}),Pr=(w=>(w.PEER_JOINED="PEER_JOINED",w.PEER_LEFT="PEER_LEFT",w.PEER_LIST="PEER_LIST",w.NEW_MESSAGE="NEW_MESSAGE",w.ERROR="ERROR",w.RECONNECTING="RECONNECTING",w.RECONNECTED="RECONNECTED",w.TRACK_ADDED="TRACK_ADDED",w.TRACK_REMOVED="TRACK_REMOVED",w.TRACK_MUTED="TRACK_MUTED",w.TRACK_UNMUTED="TRACK_UNMUTED",w.TRACK_DEGRADED="TRACK_DEGRADED",w.TRACK_RESTORED="TRACK_RESTORED",w.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",w.ROLE_UPDATED="ROLE_UPDATED",w.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",w.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",w.ROOM_ENDED="ROOM_ENDED",w.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",w.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",w.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",w.NAME_UPDATED="NAME_UPDATED",w.METADATA_UPDATED="METADATA_UPDATED",w.POLL_CREATED="POLL_CREATED",w.POLL_STARTED="POLL_STARTED",w.POLL_STOPPED="POLL_STOPPED",w.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",w.POLLS_LIST="POLLS_LIST",w.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",w.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",w))(Pr||{});var vs=(t=>(t.audio="audio",t.video="video",t))(vs||{});import{createSelector as A}from"reselect";function Fe(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];go(s)&&(i=gt(s)?s:i,t=Tt(s)?s:t)}return{video:t,audio:i}}function gt(a){return a&&a.type==="audio"}function Tt(a){return a&&a.type==="video"}function go(a){return a&&a.source==="screen"}function ci(a){return a&&a.source==="audioplaylist"}function ft(a){return a&&a.source==="videoplaylist"}function Ms(a){return a?!!(a!=null&&a.degraded):!1}function ze(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function ys(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function vt(a){var r;let e=!1,t=!1,i=!1;return(r=a==null?void 0:a.publishParams)!=null&&r.allowed&&(e=a.publishParams.allowed.includes("video"),t=a.publishParams.allowed.includes("audio"),i=a.publishParams.allowed.includes("screen")),{video:e,audio:t,screen:i}}var ks=(d=>(d[d.VERBOSE=0]="VERBOSE",d[d.DEBUG=1]="DEBUG",d[d.INFO=2]="INFO",d[d.WARN=3]="WARN",d[d.TIME=4]="TIME",d[d.TIMEEND=5]="TIMEEND",d[d.ERROR=6]="ERROR",d[d.NONE=7]="NONE",d))(ks||{}),To=typeof window!="undefined"&&typeof window.expect!="undefined",l=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(t,...i);break}case 1:{console.debug(t,...i);break}case 2:{console.info(t,...i);break}case 3:{console.warn(t,...i);break}case 6:{console.error(t,...i);break}case 4:{performance.mark(i[0]);break}case 5:{let r=i[0];try{let s=performance.measure(r,r);this.log(1,t,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,t,r,s)}break}}}};l.level=To?7:0;var Ye=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};import{UAParser as fo}from"ua-parser-js";var Te=new fo,U=typeof window!="undefined",Es,Ge=typeof window=="undefined"&&!((Es=Te.getBrowser().name)!=null&&Es.toLowerCase().includes("electron"));var vo=()=>!Ge,Tc=vo(),Mt=()=>Te.getDevice().type==="mobile",Rs=()=>typeof document!="undefined"&&document.hidden,Hs=()=>{var a;return((a=Te.getOS().name)==null?void 0:a.toLowerCase())==="ios"},Ps,bs,Cs=(bs=(Ps=Te.getBrowser())==null?void 0:Ps.name)==null?void 0:bs.toLowerCase().includes("safari"),As,Is,di=((Is=(As=Te.getBrowser())==null?void 0:As.name)==null?void 0:Is.toLowerCase())==="firefox";import{v4 as Po}from"uuid";var Ls=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Ls||{});function Mo(){if(U&&window){let a=window.location.hostname;return a==="localhost"||a==="127.0.0.1"?"LOCAL":a.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var Xe=Mo();import{v4 as ko}from"uuid";var P={WebSocketConnectionErrors:{FAILED_TO_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003,ABNORMAL_CLOSE:1006},APIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3004,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010,SYSTEM_DENIED_PERMISSION:3011,CURRENT_TAB_NOT_SHARED:3012,AUDIO_PLAYBACK_ERROR:3013,SELECTED_DEVICE_MISSING:3014,NO_DATA:3015},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005,ICE_DISCONNECTED:4006,STATS_FAILED:4007},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011,LOCAL_STORAGE_ACCESS_DENIED:6012,VALIDATION_FAILED:6013},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}};var k=class a extends Error{constructor(t,i,r,s,o,n=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=o;this.isTerminal=n;Object.setPrototypeOf(this,a.prototype),this.action=r.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{
1
+ var co=Object.defineProperty,lo=Object.defineProperties;var uo=Object.getOwnPropertyDescriptors;var ai=Object.getOwnPropertySymbols,po=Object.getPrototypeOf,gs=Object.prototype.hasOwnProperty,Ts=Object.prototype.propertyIsEnumerable,ho=Reflect.get;var Ss=(a,e,t)=>e in a?co(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))gs.call(e,t)&&Ss(a,t,e[t]);if(ai)for(var t of ai(e))Ts.call(e,t)&&Ss(a,t,e[t]);return a},M=(a,e)=>lo(a,uo(e));var kr=(a,e)=>{var t={};for(var i in a)gs.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&ai)for(var i of ai(a))e.indexOf(i)<0&&Ts.call(a,i)&&(t[i]=a[i]);return t};var mo=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var ne=(a,e,t)=>ho(po(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=d=>{try{n(t.next(d))}catch(u){r(u)}},o=d=>{try{n(t.throw(d))}catch(u){r(u)}},n=d=>d.done?i(d.value):Promise.resolve(d.value).then(s,o);n((t=t.apply(a,e)).next())});var Ir=mo((Jc,Eo)=>{Eo.exports={version:"0.12.36-alpha.0",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist","src"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^1.0.1",uuid:"^8.3.2","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/lodash.isequal":"^4.5.8","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.36","@types/uuid":"^8.3.0","jest-canvas-mock":"^2.3.1","jsdom-worker":"^0.3.0",tslib:"^2.2.0"},description:"@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow",keywords:["video","webrtc","conferencing","100ms"],gitHead:"85a1503c44806a779fe0c0bc54258b0065ec476c"}});var Er=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Er||{});var oi=()=>({room:{id:"",isConnected:!1,name:"",peers:[],localPeer:"",roomState:"Disconnected",recording:{browser:{running:!1},server:{running:!1},hls:{running:!1}},rtmp:{running:!1},hls:{running:!1,variants:[]},sessionId:""},peers:{},tracks:{},playlist:{audio:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1},video:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1}},messages:{byID:{},allIDs:[]},speakers:{},connectionQualities:{},settings:{audioInputDeviceId:"",audioOutputDeviceId:"",videoInputDeviceId:""},devices:{audioInput:[],audioOutput:[],videoInput:[]},roles:{},roleChangeRequests:[],errors:[],sessionStore:{},templateAppData:{},polls:{},whiteboards:{},hideLocalPeer:!1}),ni=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var So=(e=>(e.CHAT="chat",e))(So||{});var fs=(t=>(t.INFO="info",t.ERROR="error",t))(fs||{}),Pr=(w=>(w.PEER_JOINED="PEER_JOINED",w.PEER_LEFT="PEER_LEFT",w.PEER_LIST="PEER_LIST",w.NEW_MESSAGE="NEW_MESSAGE",w.ERROR="ERROR",w.RECONNECTING="RECONNECTING",w.RECONNECTED="RECONNECTED",w.TRACK_ADDED="TRACK_ADDED",w.TRACK_REMOVED="TRACK_REMOVED",w.TRACK_MUTED="TRACK_MUTED",w.TRACK_UNMUTED="TRACK_UNMUTED",w.TRACK_DEGRADED="TRACK_DEGRADED",w.TRACK_RESTORED="TRACK_RESTORED",w.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",w.ROLE_UPDATED="ROLE_UPDATED",w.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",w.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",w.ROOM_ENDED="ROOM_ENDED",w.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",w.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",w.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",w.NAME_UPDATED="NAME_UPDATED",w.METADATA_UPDATED="METADATA_UPDATED",w.POLL_CREATED="POLL_CREATED",w.POLL_STARTED="POLL_STARTED",w.POLL_STOPPED="POLL_STOPPED",w.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",w.POLLS_LIST="POLLS_LIST",w.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",w.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",w))(Pr||{});var vs=(t=>(t.audio="audio",t.video="video",t))(vs||{});import{createSelector as A}from"reselect";function Fe(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];go(s)&&(i=gt(s)?s:i,t=Tt(s)?s:t)}return{video:t,audio:i}}function gt(a){return a&&a.type==="audio"}function Tt(a){return a&&a.type==="video"}function go(a){return a&&a.source==="screen"}function ci(a){return a&&a.source==="audioplaylist"}function ft(a){return a&&a.source==="videoplaylist"}function Ms(a){return a?!!(a!=null&&a.degraded):!1}function ze(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function ys(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function vt(a){var r;let e=!1,t=!1,i=!1;return(r=a==null?void 0:a.publishParams)!=null&&r.allowed&&(e=a.publishParams.allowed.includes("video"),t=a.publishParams.allowed.includes("audio"),i=a.publishParams.allowed.includes("screen")),{video:e,audio:t,screen:i}}var ks=(d=>(d[d.VERBOSE=0]="VERBOSE",d[d.DEBUG=1]="DEBUG",d[d.INFO=2]="INFO",d[d.WARN=3]="WARN",d[d.TIME=4]="TIME",d[d.TIMEEND=5]="TIMEEND",d[d.ERROR=6]="ERROR",d[d.NONE=7]="NONE",d))(ks||{}),To=typeof window!="undefined"&&typeof window.expect!="undefined",l=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(t,...i);break}case 1:{console.debug(t,...i);break}case 2:{console.info(t,...i);break}case 3:{console.warn(t,...i);break}case 6:{console.error(t,...i);break}case 4:{performance.mark(i[0]);break}case 5:{let r=i[0];try{let s=performance.measure(r,r);this.log(1,t,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,t,r,s)}break}}}};l.level=To?7:0;var Ye=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};import{UAParser as fo}from"ua-parser-js";var Te=new fo,U=typeof window!="undefined",Es,Ge=typeof window=="undefined"&&!((Es=Te.getBrowser().name)!=null&&Es.toLowerCase().includes("electron"));var vo=()=>!Ge,Tc=vo(),Mt=()=>Te.getDevice().type==="mobile",Rs=()=>typeof document!="undefined"&&document.hidden,Hs=()=>{var a;return((a=Te.getOS().name)==null?void 0:a.toLowerCase())==="ios"},Ps,bs,Cs=(bs=(Ps=Te.getBrowser())==null?void 0:Ps.name)==null?void 0:bs.toLowerCase().includes("safari"),As,Is,di=((Is=(As=Te.getBrowser())==null?void 0:As.name)==null?void 0:Is.toLowerCase())==="firefox";import{v4 as Po}from"uuid";var Ls=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Ls||{});function Mo(){if(U&&window){let a=window.location.hostname;return a==="localhost"||a==="127.0.0.1"?"LOCAL":a.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var Xe=Mo();import{v4 as ko}from"uuid";var P={WebSocketConnectionErrors:{FAILED_TO_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003,ABNORMAL_CLOSE:1006},APIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3004,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010,SYSTEM_DENIED_PERMISSION:3011,CURRENT_TAB_NOT_SHARED:3012,AUDIO_PLAYBACK_ERROR:3013,SELECTED_DEVICE_MISSING:3014,NO_DATA:3015},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005,ICE_DISCONNECTED:4006,STATS_FAILED:4007},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011,LOCAL_STORAGE_ACCESS_DENIED:6012,VALIDATION_FAILED:6013},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}};var k=class a extends Error{constructor(t,i,r,s,o,n=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=o;this.isTerminal=n;Object.setPrototypeOf(this,a.prototype),this.action=r.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{
2
2
  code: ${this.code};
3
3
  name: ${this.name};
4
4
  action: ${this.action};
@@ -44,7 +44,7 @@ var co=Object.defineProperty,lo=Object.defineProperties;var uo=Object.getOwnProp
44
44
  break;
45
45
  }
46
46
  };
47
- })()`;function J(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function Oe(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return J(a);let e=new Worker(URL.createObjectURL(new Blob([Bs],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function Vs(){if(typeof Worker=="undefined")return{sleep:e=>J(e)};let a=new Worker(URL.createObjectURL(new Blob([Bs],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function mi(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var Ro=35,Ho=5,Si=class{constructor(e,t,i){this.track=e;this.audioLevelEvent=t;this.silenceEvent=i;this.TAG="[TrackAudioLevelMonitor]";this.audioLevel=0;this.isMonitored=!1;this.interval=100;this.historyInterval=700;this.history=new Ne(this.historyInterval/this.interval);this.detectSilence=()=>c(this,null,function*(){let i=0;for(;this.isMonitored;){if(this.track.enabled)if(this.isSilentThisInstant()){if(i++,i>50){this.silenceEvent.publish({track:this.track});break}}else break;yield J(20)}});try{let r=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(r);let s=this.analyserNode.frequencyBinCount;this.dataArray=new Uint8Array(s)}catch(r){l.w(this.TAG,"Unable to initialize AudioContext",r)}}start(){this.stop(),this.isMonitored=!0,l.d(this.TAG,"Starting track Monitor",`${this.track}`),this.loop().then(()=>l.d(this.TAG,"Stopping track Monitor",`${this.track}`))}stop(){if(!this.analyserNode){l.d(this.TAG,"AudioContext not initialized");return}this.sendAudioLevel(0),this.isMonitored=!1}loop(){return c(this,null,function*(){for(;this.isMonitored;)this.sendAudioLevel(this.getMaxAudioLevelOverPeriod()),yield J(this.interval)})}sendAudioLevel(e=0){if(e=e>Ro?e:0,Math.abs(this.audioLevel-e)>Ho){this.audioLevel=e;let i={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(i)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode){l.d(this.TAG,"AudioContext not initialized");return}let e=this.calculateAudioLevel();return e!==void 0&&this.history.enqueue(e),this.history.aggregate(t=>Math.max(...t))}calculateAudioLevel(){if(!this.analyserNode||!this.dataArray){l.d(this.TAG,"AudioContext not initialized");return}this.analyserNode.getByteTimeDomainData(this.dataArray);let e=.009,t=e;for(let s of this.dataArray)t=Math.max(t,(s-128)/128);let i=(Math.log(e)-Math.log(t))/Math.log(e);return Math.ceil(Math.min(Math.max(i*100,0),100))}isSilentThisInstant(){if(!this.analyserNode||!this.dataArray){l.d(this.TAG,"AudioContext not initialized");return}return this.analyserNode.getByteTimeDomainData(this.dataArray),this.dataArray.every(e=>e===128||e===0)}createAnalyserNodeForStream(e){let t=ce.getAudioContext(),i=t.createMediaStreamSource(e),r=t.createAnalyser();return r.fftSize=2048,i.connect(r),r}};var Or=(t=>(t.SIP="sip",t.REGULAR="regular",t))(Or||{});var Fs=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Fs||{});var Gs=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(Gs||{}),Ws=(i=>(i.REGULAR="regular",i.SCREEN="screen",i.COMPOSITE="composite",i))(Ws||{}),$s=(r=>(r.INITIALISED="initialised",r.STARTED="started",r.STOPPED="stopped",r.FAILED="failed",r))($s||{}),Ks=(e=>(e.CAPTION="caption",e))(Ks||{});var We={f:"high",h:"medium",q:"low"};var xr=(t=>(t.VOICE="voice",t.MUSIC="music",t))(xr||{});var qs=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(qs||{});var Q=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._audioMode="voice";this._advanced=[{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{highpassFilter:{exact:!0}},{audioMirroring:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=this._audioMode==="music"?320:e,this}deviceId(e){return this._deviceId=e,this}audioMode(e="voice"){return this._audioMode=e,this._audioMode==="music"?this._maxBitrate=320:this._maxBitrate=32,this}advanced(e){return this._advanced=e,this}build(){return new $e(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced,this._audioMode)}},$e=class{constructor(e,t,i,r,s,o){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s,this.audioMode=o,this.audioMode==="music"?this.maxBitrate=320:this.maxBitrate=32}toConstraints(){return{deviceId:this.deviceId,advanced:this.audioMode==="music"?[]:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var q=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new Ke(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},Ke=class{constructor(e,t,i,r,s,o,n,d){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=d}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId,facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Mt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var xe=class{constructor(){this._video=new q().build();this._audio=new Q().build();this._screen=new q().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw S.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw S.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new Ze(this._video,this._audio,this._simulcast,this._screen||void 0)}},Ze=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=m(m({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=m(m({},this.video.toAnalyticsProperties()),e)),e}};function Js(a,e){return function(i){return!Co(a[i],e[i])}}var de=class a extends we{constructor(t,i,r,s,o=new Q().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this.TAG="[HMSLocalAudioTrack]";this.tracksCreated=new Set;this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){if(!this.shouldReacquireTrack()){l.d(this.TAG,`visibiltiy: ${document.visibilityState}`,`${this}`);return}if(document.visibilityState==="hidden")this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{l.d(this.TAG,"On visibile replacing track as it is not publishing");try{yield this.replaceTrackWith(this.settings)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.trackPermissions=()=>{hi("microphone",t=>{this.eventBus.analytics.publish(y.permissionChange(this.type,t)),t==="denied"&&this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})})};this.handleTrackMute=()=>{l.d(this.TAG,"muted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmute=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t}));try{yield this.setEnabled(this.enabled,!0),this.eventBus.localAudioUnmutedNatively.publish()}catch(i){this.eventBus.error.publish(i)}});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.shouldReacquireTrack=()=>ve(this.nativeTrack)||this.isTrackNotPublishing();this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Js(t,this.settings);(r("maxBitrate")||r("audioMode"))&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this,t)),(r("advanced")||r("audioMode"))&&(yield this.replaceTrackWith(t))});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(Js(t,this.settings)("deviceId")){this.manuallySelectedDeviceId=i?this.manuallySelectedDeviceId:t.deviceId,l.d(this.TAG,"device change","manual selection:",this.manuallySelectedDeviceId,"new device:",t.deviceId),yield this.replaceTrackWith(t);let s=this.nativeTrack.getSettings().groupId;!i&&t.deviceId&&(X.updateSelection("audioInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"audioInput",selection:{deviceId:t.deviceId,groupId:s}}))}});t.tracks.push(this),this.addTrackEventListeners(i),this.trackPermissions(),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!ve(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Pt(this,s,n),this.setFirstTrackId(i.id),r==="regular"&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}clone(t){let i=this.nativeTrack.clone();t.nativeStream.addTrack(i);let r=new a(t,i,this.source,this.eventBus,this.settings,this.room);return r.peerId=this.peerId,this.pluginsManager.pluginsMap.size>0&&this.pluginsManager.pluginsMap.forEach(s=>{r.addPlugin(s).catch(o=>l.e(this.TAG,"Plugin add failed while migrating",s,o))}),r}getManuallySelectedDeviceId(){return this.manuallySelectedDeviceId}resetManuallySelectedDeviceId(){this.manuallySelectedDeviceId=void 0}updateTrack(t){return c(this,null,function*(){t.enabled=this.enabled,yield this.stream.replaceStreamTrack(this.nativeTrack,t),this.nativeTrack=t,yield this.replaceSenderTrack(),!!this.audioLevelMonitor&&this.initAudioLevelMonitor()})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop(),this.removeTrackEventListeners(i),this.tracksCreated.forEach(r=>r.stop()),this.tracksCreated.clear();try{let r=yield Dr(t);this.addTrackEventListeners(r),this.tracksCreated.add(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),yield this.updateTrack(r)}catch(r){let s=yield Dr(this.settings);throw this.addTrackEventListeners(s),this.tracksCreated.add(s),yield this.updateTrack(s),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}try{yield this.pluginsManager.reprocessPlugins()}catch(r){this.eventBus.audioPluginFailed.publish(r)}})}setEnabled(t,i=!1){return c(this,null,function*(){t===this.enabled&&!i||(t&&this.shouldReacquireTrack()&&(yield this.replaceTrackWith(this.settings)),yield ne(a.prototype,this,"setEnabled").call(this,t),t&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),this.eventBus.localAudioEnabled.publish({enabled:t,track:this}))})}isPublishedTrackId(t){return this.publishedTrackId===t}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(ve(this.nativeTrack)){this.settings=r;return}yield this.handleDeviceChange(r,i),yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.pluginsManager.getPlugins()}addPlugin(t){return c(this,null,function*(){return this.pluginsManager.addPlugin(t)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}setProcessedTrack(t){return c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack()})}initAudioLevelMonitor(){this.audioLevelMonitor&&this.destroyAudioLevelMonitor(),l.d(this.TAG,"Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new Si(this,this.eventBus.trackAudioLevelUpdate,this.eventBus.localAudioSilence),this.audioLevelMonitor.start(),this.audioLevelMonitor.detectSilence()}destroyAudioLevelMonitor(){var t;(t=this.audioLevelMonitor)==null||t.stop(),this.audioLevelMonitor=void 0}cleanup(){return c(this,null,function*(){var t;ne(a.prototype,this,"cleanup").call(this),yield this.pluginsManager.cleanup(),yield this.pluginsManager.closeContext(),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.tracksCreated.forEach(i=>i.stop()),this.tracksCreated.clear(),this.isPublished=!1,this.destroyAudioLevelMonitor(),document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmute)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmute)}buildNewSettings(t){let{volume:i,codec:r,maxBitrate:s,deviceId:o,advanced:n,audioMode:d}=m(m({},this.settings),t);return new $e(i,r,s,o,n,d)}};var ie=class a extends we{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield ne(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var et=class extends De{constructor(t,i,r){super(t,i,r);this.type="video";this.sinkCount=0;this.handleTrackUnmute=()=>{this.getSinks().forEach(t=>this.reTriggerPlay({videoElement:t}))};this.reTriggerPlay=({videoElement:t})=>{setTimeout(()=>{t.play().catch(i=>{l.w("[HMSVideoTrack]","failed to play",i.message)})},0)};if(i.kind!=="video")throw new Error("Expected 'track' kind = 'video'")}setVideoHandler(t){this.videoHandler=t}hasSinks(){return this.sinkCount>0}getSinks(){return this.videoHandler.getVideoElements()||[]}attach(t){this.videoHandler.addVideoElement(t)}detach(t){this.videoHandler.removeVideoElement(t)}addSink(t){this.addSinkInternal(t,this.nativeTrack)}removeSink(t){t.srcObject!==null&&(t.srcObject=null,this.reduceSinkCount())}cleanup(){super.cleanup(),this.videoHandler.cleanup()}addSinkInternal(t,i){let r=t.srcObject;if(r!==null&&r instanceof MediaStream){let o=r.getVideoTracks()[0];if((o==null?void 0:o.id)===i.id){if(!o.muted&&o.readyState==="live")return;this.reduceSinkCount()}else this.reduceSinkCount()}this.addPropertiesToElement(t);let s=new MediaStream([i]);t.srcObject=s,this.reTriggerPlay({videoElement:t}),this.sinkCount++}reduceSinkCount(){this.sinkCount>0&&this.sinkCount--}addPropertiesToElement(t){Cs||(t.autoplay=!0),t.playsInline=!0,t.muted=!0,t.controls=!1}};import xo from"lodash.isequal";import{v4 as Do}from"uuid";var bt={none:-1,low:0,medium:1,high:2},Lo=.5,Qs=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>bt[o.layer]-bt[n.layer]),s=e[i]*((window==null?void 0:window.devicePixelRatio)||1);for(let o=0;o<r.length;o++){let{resolution:n,layer:d}=r[o],u=n[i];if(s<=u){t=d;break}else{let p=r[o+1],h=p?p.resolution[i]:Number.POSITIVE_INFINITY;if((s-u)/(h-u)<Lo){t=d;break}}}return t};var Ur=class{constructor(){this.TAG="[HMSIntersectionObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t)=>{var i;this.createObserver(),this.unobserve(e),(i=this.intersectionObserver)==null||i.observe(e),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.intersectionObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.intersectionObserver&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersection))};this.handleIntersection=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.IntersectionObserver!="undefined";return e||l.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},zs=new Ur;var Br=class{constructor(){this.TAG="[HMSResizeObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t,i={box:"border-box"})=>{var r;this.createObserver(),this.unobserve(e),(r=this.resizeObserver)==null||r.observe(e,i),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.resizeObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(mi(this.handleResize,300)))};this.handleResize=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.ResizeObserver!="undefined";return e||l.w(this.TAG,"Resize Observer is not supported"),e}},Ys=new Br;var tt=class{constructor(e){this.track=e;this.TAG="[VideoElementManager]";this.videoElements=new Set;this.entries=new WeakMap;this.handleIntersection=e=>c(this,null,function*(){let t=getComputedStyle(e.target).visibility==="visible";this.track.enabled&&(e.isIntersecting&&t||!document.contains(e.target))?(l.d(this.TAG,"add sink intersection",`${this.track}`,this.id),this.entries.set(e.target,e.boundingClientRect),yield this.selectMaxLayer(),yield this.track.addSink(e.target)):(l.d(this.TAG,"remove sink intersection",`${this.track}`,this.id),yield this.track.removeSink(e.target))});this.handleResize=e=>c(this,null,function*(){!this.track.enabled||!(this.track instanceof O)||(this.entries.set(e.target,e.contentRect),yield this.selectMaxLayer())});this.cleanup=()=>{this.videoElements.forEach(e=>{var t,i;e.srcObject=null,(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e)}),this.videoElements.clear(),this.resizeObserver=void 0,this.intersectionObserver=void 0};this.init(),this.id=Do()}updateSinks(e=!1){for(let t of this.videoElements)this.track.enabled?this.track.addSink(t,e):this.track.removeSink(t,e)}addVideoElement(e){return c(this,null,function*(){var t;this.videoElements.has(e)||(this.init(),l.d(this.TAG,`Adding video element for ${this.track}`,this.id),this.videoElements.add(e),this.videoElements.size>=10&&l.w(this.TAG,`${this.track}`,`the track is added to ${this.videoElements.size} video elements, while this may be intentional, it's likely that there is a bug leading to unnecessary creation of video elements in the UI`),(t=this.intersectionObserver)!=null&&t.isSupported()?this.intersectionObserver.observe(e,this.handleIntersection):U&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof O&&(yield this.track.setPreferredLayer(this.track.getPreferredLayer())))})}removeVideoElement(e){var t,i;this.track.removeSink(e),this.videoElements.delete(e),this.entries.delete(e),(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e),l.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){U&&(this.resizeObserver=Ys,this.intersectionObserver=zs)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:n,display:d}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,t+=e.offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&i+r>window.pageXOffset&&!o&&(n!==""?parseFloat(n)>0:!0)&&d!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof O)||this.videoElements.size===0)return;let e;for(let t of this.videoElements){let i=this.entries.get(t);if(!i)continue;let{width:r,height:s}=i;if(r===0||s===0)continue;let o=Qs(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=bt[o]>bt[e]?o:e:e=o}e&&(l.d(this.TAG,`selecting max layer ${e} for the track`,`${this.track}`),yield this.track.setPreferredLayer(e))})}};var Vr=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Vr||{}),Fr=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(Fr||{});var At=class{constructor(){this.total=0;this.count=0}add(e){this.count++,this.total+=e}getAvg(){return Math.floor(this.total/this.count)}reset(){this.total=0,this.count=0}};var it=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new At,this.addedTimestamps={},this.processingAvgs={},this.pluginAdded={},this.pluginInputFrameRate={},this.pluginFrameRate={}}added(e,t,i){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.processingAvgs[e]=new At,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(me.added(e,this.addedTimestamps[e]))}removed(e){var t;if(this.pluginAdded[e]){let i={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],avgPreProcessingTime:this.preProcessingAvgs.getAvg(),avgProcessingTime:(t=this.processingAvgs[e])==null?void 0:t.getAvg(),inputFrameRate:this.pluginInputFrameRate[e],pluginFrameRate:this.pluginFrameRate[e]};this.eventBus.analytics.publish(me.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(me.failure(e,t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){l.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),l.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=S.MediaPluginErrors.InitFailed("VIDEO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw l.e(this.TAG,s),this.failure(e,s),s}i&&(this.initTime[e]=i)})}preProcessWithTime(e){return c(this,null,function*(){let t=yield this.timeInMs(e);this.preProcessingAvgs.add(t)})}processWithTime(e,t){return c(this,null,function*(){var r;let i;try{i=yield this.timeInMs(t)}catch(s){let o=S.MediaPluginErrors.ProcessingFailed("VIDEO_PLUGINS",`Failed during processing of plugin${s.message||s}`);throw l.e(this.TAG,o),this.failure(e,o),o}i&&((r=this.processingAvgs[e])==null||r.add(i))})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.processingAvgs[e],delete this.pluginAdded[e],delete this.pluginInputFrameRate[e],delete this.pluginFrameRate[e]}};var Xs=24,wo=320,_o=240,It=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=Vs();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new it(t),this.canvases=new Array}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e,t){return c(this,null,function*(){var i;if(this.pluginAddInProgress){let r=(i=e.getName)==null?void 0:i.call(e);if(!r||r===""){l.w("no name provided by the plugin");return}let s=S.MediaPluginErrors.AddAlreadyInProgress("VIDEO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.failure(r,s),l.w("can't add another plugin when previous add is in progress"),s}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e,t)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e,t){return c(this,null,function*(){var o,n;let i=(o=e.getName)==null?void 0:o.call(e);if(!i||i===""){l.w("no name provided by the plugin");return}if(this.pluginsMap.has(i)){l.w(this.TAG,`plugin - ${e.getName()} already added.`);return}let r=this.hmsTrack.getMediaTrackSettings().frameRate||Xs,s=0;t&&t>0?(l.i(this.TAG,`adding plugin ${e.getName()} with framerate ${t}`),t<r&&(s=Math.ceil(r/t)-1),this.analytics.added(i,r,t)):(l.i(this.TAG,`adding plugin ${e.getName()}`),this.analytics.added(i,r)),l.i(this.TAG,"numFrames to skip processing",s),this.pluginNumFramesToSkip[i]=s,this.pluginNumFramesSkipped[i]=s,this.validateAndThrow(i,e);try{if(yield this.analytics.initWithTime(i,()=>c(this,null,function*(){return yield e.init()})),this.pluginsMap.set(i,e),this.pluginsMap.size+1>this.canvases.length)for(let d=this.canvases.length;d<=this.pluginsMap.size;d++)this.canvases[d]=document.createElement("canvas");yield this.startPluginsLoop((n=e.getContextType)==null?void 0:n.call(e))}catch(d){throw l.e(this.TAG,"failed to add plugin",d),yield this.removePlugin(e),d}})}validatePlugin(e){return e.checkSupport()}validateAndThrow(e,t){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else{let r;switch(i.errType){case"PLATFORM_NOT_SUPPORTED":throw r=S.MediaPluginErrors.PlatformNotSupported("VIDEO_PLUGINS","platform not supported, see docs"),this.analytics.failure(e,r),r;case"DEVICE_NOT_SUPPORTED":throw r=S.MediaPluginErrors.DeviceNotSupported("VIDEO_PLUGINS","video device not supported, see docs"),this.analytics.failure(e,r),r}}}removePlugin(e){return c(this,null,function*(){let t=e.getName();if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.removePluginEntry(t),this.pluginsMap.size===0&&(l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.stopPluginsLoop()),e.stop(),this.analytics.removed(t)})}removePluginEntry(e){this.pluginsMap.delete(e),this.pluginNumFramesToSkip[e]&&delete this.pluginNumFramesToSkip[e],this.pluginNumFramesSkipped[e]&&delete this.pluginNumFramesSkipped[e]}waitForRestart(){return c(this,null,function*(){if(!(!this.pluginsLoopRunning||this.pluginsLoopState==="running"))for(;this.pluginsLoopState==="paused";)yield Oe(100)})}cleanup(){return c(this,null,function*(){var e;for(let t of this.pluginsMap.values())yield this.removePlugin(t);(e=this.outputTrack)==null||e.stop()})}initElementsAndStream(e){this.inputCanvas||(this.inputCanvas=document.createElement("canvas")),this.outputCanvas=document.createElement("canvas"),this.inputVideo||(this.inputVideo=document.createElement("video")),this.inputCanvas.getContext("2d"),this.outputCanvas.getContext(e||"2d");let t=this.outputCanvas.captureStream();this.outputTrack=t.getVideoTracks()[0]}startPluginsLoop(e){return c(this,null,function*(){if(!this.pluginsLoopRunning){this.initElementsAndStream(e),this.pluginsLoopRunning=!0;try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(t){throw this.pluginsLoopRunning=!1,l.e(this.TAG,"error in setting processed track",t),t}this.pluginsLoop().then(()=>{l.d(this.TAG,"processLoop stopped")})}})}stopPluginsLoop(){return c(this,null,function*(){var e;this.pluginsLoopRunning=!1,yield this.hmsTrack.setProcessedTrack(void 0),this.resetCanvases(),(e=this.outputTrack)==null||e.stop(),this.inputVideo&&(this.inputVideo.srcObject=null,this.inputVideo=void 0)})}pluginsLoop(){return c(this,null,function*(){for(;this.pluginsLoopRunning;){let e=this.hmsTrack.getMediaTrackSettings().frameRate||Xs,t=Math.floor(1e3/e);if(!this.hmsTrack.enabled||this.hmsTrack.nativeTrack.readyState==="ended"){this.pluginsLoopState==="running"&&this.resetCanvases(),this.pluginsLoopState="paused",yield this.reusableWorker.sleep(t);continue}let i=0;try{yield this.analytics.preProcessWithTime(()=>c(this,null,function*(){return yield this.doPreProcessing()}));let r=Date.now();yield this.processFramesThroughPlugins(),i=Math.floor(Date.now()-r),i>t&&(i=t)}catch(r){l.e(this.TAG,"error in plugins loop",r)}this.pluginsLoopState="running",yield this.reusableWorker.sleep(t-i)}})}doPreProcessing(){return c(this,null,function*(){yield this.addTrackToVideo(),yield this.updateInputCanvas()})}processFramesThroughPlugins(){return c(this,null,function*(){this.canvases[0]=this.inputCanvas;let e=0;for(let t of this.pluginsMap.values()){let i=t.getName();if(t){try{let r=this.checkIfSkipRequired(i);if(t.getPluginType()==="TRANSFORM"){let s=(o,n)=>c(this,null,function*(){try{yield t.processVideoFrame(o,n,r)}catch(d){l.e(this.TAG,`error in processing plugin ${i}`,d)}});if(r)e===this.pluginsMap.size-1?yield s(this.canvases[e],this.outputCanvas):yield s(this.canvases[e],this.canvases[e+1]);else{let o=this.canvases[e],n=this.canvases[e+1];e===this.pluginsMap.size-1?yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return s(o,this.outputCanvas)})):yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return s(o,n)}))}}else t.getPluginType()==="ANALYZE"&&!r&&(yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return yield t.processVideoFrame(this.inputCanvas)})))}catch(r){l.e(this.TAG,`error in processing plugin ${i}`,r),yield this.removePlugin(t)}e++}}})}addTrackToVideo(){return c(this,null,function*(){var t;if(!this.inputVideo)return;let e=this.inputVideo.srcObject;e!==null&&e instanceof MediaStream&&((t=e.getVideoTracks()[0])==null?void 0:t.id)===this.hmsTrack.nativeTrack.id||(this.inputVideo.pause(),this.inputVideo.srcObject=new MediaStream([this.hmsTrack.nativeTrack]),this.inputVideo.muted=!0,this.inputVideo.playsInline=!0,yield this.inputVideo.play())})}updateInputCanvas(){return c(this,null,function*(){if(!this.inputCanvas||!this.inputVideo)return;let{width:e=wo,height:t=_o}=this.hmsTrack.getMediaTrackSettings();this.inputCanvas.height!==t&&(this.inputCanvas.height=t),this.inputCanvas.width!==e&&(this.inputCanvas.width=e),this.inputCanvas.getContext("2d").drawImage(this.inputVideo,0,0,e,t)})}resetCanvases(){if(!this.outputCanvas||!this.inputCanvas)return;let e=this.inputCanvas.getContext("2d");e&&(e.fillStyle="rgb(0, 0, 0)",e.fillRect(0,0,this.outputCanvas.width,this.outputCanvas.height)),this.canvases=[]}checkIfSkipRequired(e){let t=!1;return this.pluginNumFramesSkipped[e]<this.pluginNumFramesToSkip[e]?(this.pluginNumFramesSkipped[e]++,t=!0):(t=!1,this.pluginNumFramesSkipped[e]=0),t}};var gi=class{constructor(e,t){this.TAG="[MediaStreamPluginsManager]";this.plugins=new Set,this.analytics=new it(e),this.room=t}addPlugins(e){e.forEach(t=>{var i;switch(t.getName()){case"HMSEffectsPlugin":if(!((i=this.room)!=null&&i.isEffectsEnabled)){let r="Effects Virtual Background is not enabled for this room";if(this.plugins.size===0)throw Error(r);l.w(this.TAG,r);return}break;default:}this.plugins.add(t)})}removePlugins(e){e.forEach(t=>{t.stop(),this.analytics.removed(t.getName()),this.plugins.delete(t)})}applyPlugins(e){let t=e;for(let i of this.plugins){let r=i.getName();try{t=i.apply(t),this.analytics.added(r)}catch(s){this.analytics.failure(r,s),l.e("Could not apply plugin",s,r)}}return t}getPlugins(){return Array.from(this.plugins).map(e=>e.getName())}cleanup(){return c(this,null,function*(){this.removePlugins(Array.from(this.plugins))})}};import{v4 as Oo}from"uuid";var No=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],Ti=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),l.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){l.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...No,...e].reduce((t,i)=>M(m({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var Gr={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default",audioMode:"voice"},Me,fi,be=class a{constructor(e,t,i,r,s){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=s;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=Gr){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),d=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let h={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};h.audio&&this.analyticsTimer.start("local_audio_track_time"),h.video&&this.analyticsTimer.start("local_video_track_time");try{l.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:h}),s=yield this.getLocalTracks(h,t,d)}catch(T){s=yield this.retryGetLocalTracks(T,t,h,d)}return h.audio&&this.analyticsTimer.end("local_audio_track_time"),h.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&s.push(o),n&&i&&!p&&s.push(n),s})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new Ze(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}optimizeScreenShareConstraint(e,t){return c(this,null,function*(){var s,o,n;if(typeof t.video=="boolean"||!((s=t.video)!=null&&s.width)||!((o=t.video)!=null&&o.height))return;let i=this.store.getPublishParams();if(!i||!((n=i.allowed)!=null&&n.includes("screen")))return;let r=document.createElement("video");r.srcObject=e,r.addEventListener("loadedmetadata",()=>c(this,null,function*(){let{videoWidth:d,videoHeight:u}=r,p=i.screen,h=p.width*p.height,T=d/u,g=p.width/p.height;if(T>g){let f=t.video,E=T/g,v=Math.sqrt(E);d*u>h?(f.width=d/v,f.height=u/v):(f.height=u*v,f.width=d*v),yield e.getVideoTracks()[0].applyConstraints(f)}}))})}getLocalScreen(e,t=!1){return c(this,null,function*(){var T;let i=yield this.getOrDefaultScreenshareConfig(e),r=this.getScreenshareSettings(i.videoOnly),s={video:M(m({},r==null?void 0:r.video.toConstraints(!0)),{displaySurface:i.displaySurface}),preferCurrentTab:i.preferCurrentTab,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio};if(r!=null&&r.audio){let g=(T=r==null?void 0:r.audio)==null?void 0:T.toConstraints();delete g.advanced,s.audio=M(m({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}else e!=null&&e.forceCurrentTab&&e.preferCurrentTab&&e.cropElement&&(s.audio={echoCancellation:!0,noiseSuppression:!0});let o;try{l.d("retrieving screenshare with ",{config:i},{constraints:s}),o=yield navigator.mediaDevices.getDisplayMedia(s),t&&(yield this.optimizeScreenShareConstraint(o,s))}catch(g){l.w(this.TAG,"error in getting screenshare - ",g);let f=_e(g,"screen");throw this.eventBus.analytics.publish(y.publish({error:f,devices:this.deviceManager.getDevices(),settings:new Ze(r==null?void 0:r.video,r==null?void 0:r.audio,!1)})),f}let n=[],d=new Se(o),u=o.getVideoTracks()[0],p=new G(d,u,"screen",this.eventBus,r==null?void 0:r.video,this.store.getRoom());p.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(p,i.forceCurrentTab);p.isCurrentTab=g,yield p.cropTo(i.cropTarget)}catch(g){throw o.getTracks().forEach(f=>f.stop()),g}n.push(p);let h=o.getAudioTracks()[0];if(h){let g=new de(d,h,"screen",this.eventBus,r==null?void 0:r.audio,this.store.getRoom());n.push(g)}return l.v(this.TAG,"getLocalScreen",n),n})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:Oo(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),l.d("setting capture handle - ",e.handle),navigator.mediaDevices.setCaptureHandleConfig(e),this.captureHandleIdentifier=e.handle)}validateCurrentTabCapture(e,t){let i=e.getCaptureHandle(),r=!!(this.captureHandleIdentifier&&(i==null?void 0:i.handle)===this.captureHandleIdentifier);if(t&&!r)throw l.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),S.TracksErrors.CurrentTabNotShared();return r}requestPermissions(){return c(this,null,function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})).getTracks().forEach(t=>t.stop())}catch(e){l.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,d,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((d=e==null?void 0:e.getSettings())==null?void 0:d.height)||240,r=1;Me||(Me=document.createElement("canvas"),Me.width=t,Me.height=i,(u=Me.getContext("2d"))==null||u.fillRect(0,0,t,i)),fi||(fi=setInterval(()=>{let p=Me==null?void 0:Me.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=Me.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=ce.getAudioContext(),t=e.createOscillator(),i=e.createMediaStreamDestination();t.connect(i),t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}static cleanup(){clearInterval(fi),fi=void 0,Me=void 0}getAVTracks(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:e.audio?e.audio.toConstraints():!1,video:e.video?e.video.toConstraints():!1});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){yield this.deviceManager.init();let i=!!(!this.deviceManager.hasWebcamPermission&&e.video),r=!!(!this.deviceManager.hasMicrophonePermission&&e.audio),s=this.getErrorType(i,r);throw _e(t,s)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new xe().video(i).audio(t).build()}isInIframe(){try{return window.self!==window.top}catch(e){return!0}}retryGetLocalTracks(e,t,i,r){return c(this,null,function*(){if(e instanceof k&&e.action==="TRACK"){this.observer.onFailure(e);let s=e.code===P.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(s){let d=new xe().video(new Ke).audio(new $e).build();l.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,d,r)}catch(u){let p=u instanceof k?u.nativeError:u,h=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let T=S.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");T.addNativeError(p),h=T}return yield this.retryGetLocalTracks(h,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,l.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(d){return l.w(this.TAG,"Fetch empty tacks failed",d),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(d),yield this.getLocalTracks(i,t,r)}}else return l.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(e),[]})}getErrorType(e,t){return e&&t?"audio, video":e?"video":t?"audio":"audio, video"}getEmptyTracks(e){let t=[];return e.audio==="empty"&&t.push(a.getEmptyAudioTrack()),e.video==="empty"&&t.push(a.getEmptyVideoTrack()),t}updateCurrentLocalTrackSettings(e){return c(this,null,function*(){let t=this.store.getLocalPeerTracks(),i=t.find(n=>n.type==="video"&&n.source==="regular"),r=t.find(n=>n.type==="audio"&&n.source==="regular"),s=t.find(n=>n.type==="video"&&n.source==="screen");e!=null&&e.video&&(yield i==null?void 0:i.setSettings(e.video)),e!=null&&e.audio&&(yield r==null?void 0:r.setSettings(e.audio));let o=this.getScreenshareSettings(!0);return o!=null&&o.video&&(yield s==null?void 0:s.setSettings(o==null?void 0:o.video)),{videoTrack:i,audioTrack:r}})}getAudioSettings(e){var o;let t=this.store.getPublishParams();if(!t||!((o=t.allowed)!=null&&o.includes("audio")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.audioTrack,s=(r==null?void 0:r.settings.deviceId)||e.audioInputDeviceId;return new Q().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(s||Gr.audioInputDeviceId).build()}getVideoSettings(e){var n;let t=this.store.getPublishParams();if(!t||!((n=t.allowed)!=null&&n.includes("video")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.videoTrack,s=(r==null?void 0:r.settings.deviceId)||e.videoDeviceId,o=t.video;return new q().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(s||Gr.videoDeviceId).build()}getScreenshareSettings(e=!1){var r;let t=this.store.getPublishParams();if(!t||!((r=t.allowed)!=null&&r.includes("screen")))return null;let i=t.screen;return{video:new q().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new Q().build()}}getOrDefaultScreenshareConfig(e){return c(this,null,function*(){var i;let t=Object.assign({videoOnly:!1,audioOnly:!1,forceCurrentTab:!1,preferCurrentTab:!1,selfBrowserSurface:"exclude",surfaceSwitching:"include",systemAudio:"exclude",displaySurface:"monitor"},e||{});return t.forceCurrentTab&&(t.videoOnly=!0,t.preferCurrentTab=!0,t.selfBrowserSurface="include",t.surfaceSwitching="exclude"),t.preferCurrentTab&&(t.selfBrowserSurface="include",t.displaySurface=void 0),t.cropElement&&((i=window.CropTarget)!=null&&i.fromElement)&&(t.cropTarget=yield window.CropTarget.fromElement(t.cropElement)),t})}createHMSLocalTracks(e,t,i){let r=e.find(n=>n.kind==="video"),s=e.find(n=>n.kind==="audio");i?e.forEach(n=>i==null?void 0:i.nativeStream.addTrack(n)):i=new Se(new MediaStream(e));let o=[];if(s&&(t!=null&&t.audio)){let n=new de(i,s,"regular",this.eventBus,t.audio,this.store.getRoom());o.push(n)}if(r&&(t!=null&&t.video)){let n=new G(i,r,"regular",this.eventBus,t.video,this.store.getRoom());n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function Zs(a,e){return function(i){return!xo(a[i],e[i])}}var G=class a extends et{constructor(t,i,r,s,o=new q().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this._layerDefinitions=[];this.TAG="[HMSLocalVideoTrack]";this.enabledStateBeforeBackground=!1;this.isCurrentTab=!1;this.isPublished=!1;this.replaceSenderTrack=t=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(t)});this.buildNewSettings=t=>{let{width:i,height:r,codec:s,maxFramerate:o,maxBitrate:n,deviceId:d,advanced:u,facingMode:p}=m(m({},this.settings),t);return new Ke(i,r,s,o,d,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Zs(t,this.settings);if(r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("width")||r("height")||r("advanced"))if(this.source==="video"){let s=yield this.replaceTrackWith(t);yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks()}else yield this.nativeTrack.applyConstraints(t.toConstraints())});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(Zs(t,this.settings)("deviceId")&&this.source==="regular"){if(this.enabled){delete t.facingMode;let o=yield this.replaceTrackWith(t);yield this.replaceSender(o,this.enabled),this.nativeTrack=o,yield this.processPlugins(),this.videoHandler.updateSinks()}let s=this.nativeTrack.getSettings().groupId;!i&&t.deviceId&&(X.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s}}))}});this.trackPermissions=()=>{hi("camera",t=>{this.eventBus.analytics.publish(y.permissionChange(this.type,t)),t==="denied"&&this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})})};this.handleTrackMute=()=>{l.d(this.TAG,"muted natively",document.visibilityState);let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmuteNatively=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t})),this.handleTrackUnmute(),this.eventBus.localVideoEnabled.publish({enabled:this.enabled,track:this}),this.eventBus.localVideoUnmutedNatively.publish(),yield this.setEnabled(this.enabled)});this.removeOrReplaceProcessedTrack=t=>c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack(this.processedTrack||this.nativeTrack)});this.handleVisibilityChange=()=>c(this,null,function*(){if(document.visibilityState==="hidden")this.enabledStateBeforeBackground=this.enabled,this.enabled&&(yield this.setEnabled(!1)),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{if(l.d(this.TAG,"visibility visible, restoring track state",this.enabledStateBeforeBackground),this.enabledStateBeforeBackground)try{yield this.setEnabled(!0)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.addTrackEventListeners(i),this.trackPermissions(),t.tracks.push(this),this.setVideoHandler(new tt(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new It(this,s),this.mediaStreamPluginsManager=new gi(s,n),this.setFirstTrackId(this.trackId),this.eventBus.localAudioUnmutedNatively.subscribe(this.handleTrackUnmute),U&&r==="regular"&&Mt()&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}clone(t){let i=this.nativeTrack.clone();t.nativeStream.addTrack(i);let r=new a(t,i,this.source,this.eventBus,this.settings,this.room);return r.peerId=this.peerId,this.pluginsManager.pluginsMap.size>0&&this.pluginsManager.pluginsMap.forEach(s=>{r.addPlugin(s).catch(o=>l.e(this.TAG,"Plugin add failed while migrating",s,o))}),this.mediaStreamPluginsManager.plugins.size>0&&r.addStreamPlugins(Array.from(this.mediaStreamPluginsManager.plugins)),r}setSimulcastDefinitons(t){this._layerDefinitions=t}getSimulcastDefinitions(){return this._layerDefinitions}setEnabled(t){return c(this,null,function*(){var i;if(t!==this.enabled){if(this.source==="regular"){let r;t?r=yield this.replaceTrackWith(this.settings):r=yield this.replaceTrackWithBlank(),yield this.replaceSender(r,t),(i=this.nativeTrack)==null||i.stop(),this.nativeTrack=r,yield ne(a.prototype,this,"setEnabled").call(this,t),t&&(yield this.pluginsManager.waitForRestart(),yield this.processPlugins(),this.settings=this.buildNewSettings({deviceId:r.getSettings().deviceId})),this.videoHandler.updateSinks()}this.eventBus.localVideoEnabled.publish({enabled:t,track:this})}})}processPlugins(){return c(this,null,function*(){try{if(this.pluginsManager.getPlugins().length>0)return;if(this.mediaStreamPluginsManager.getPlugins().length>0){let r=this.mediaStreamPluginsManager.applyPlugins(new MediaStream([this.nativeTrack])).getVideoTracks()[0];yield this.setProcessedTrack(r)}else yield this.setProcessedTrack();this.videoHandler.updateSinks()}catch(t){console.error("error in processing plugin(s)",t)}})}addStreamPlugins(t){return c(this,null,function*(){if(this.pluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSMediaStreamPlugin and HMSVideoPlugin cannot be used together");this.mediaStreamPluginsManager.addPlugins(t),yield this.processPlugins()})}removeStreamPlugins(t){return c(this,null,function*(){this.mediaStreamPluginsManager.removePlugins(t),yield this.processPlugins()})}isPublishedTrackId(t){return this.publishedTrackId===t}addSink(t){this.addSinkInternal(t,this.processedTrack||this.nativeTrack)}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(yield this.handleDeviceChange(r,i),!this.enabled||ve(this.nativeTrack)){this.settings=r;return}else yield this.pluginsManager.waitForRestart();yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.mediaStreamPluginsManager.getPlugins().length>0?this.mediaStreamPluginsManager.getPlugins():this.pluginsManager.getPlugins()}addPlugin(t,i){return c(this,null,function*(){if(this.mediaStreamPluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSVideoPlugin and HMSMediaStreamPlugin cannot be used together");return this.pluginsManager.addPlugin(t,i)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}cleanup(){return c(this,null,function*(){var t;this.eventBus.localAudioUnmutedNatively.unsubscribe(this.handleTrackUnmute),this.removeTrackEventListeners(this.nativeTrack),yield this.mediaStreamPluginsManager.cleanup(),yield this.pluginsManager.cleanup(),ne(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,U&&Mt()&&document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}cropTo(t){return c(this,null,function*(){if(t&&this.source==="screen")try{this.nativeTrack.cropTo&&(yield this.nativeTrack.cropTo(t))}catch(i){throw l.e(this.TAG,"failed to crop screenshare capture - ",i),S.TracksErrors.GenericTrack("TRACK","failed to crop screenshare capture")}})}getCaptureHandle(){if(this.nativeTrack.getCaptureHandle)return this.nativeTrack.getCaptureHandle()}setProcessedTrack(t){return c(this,null,function*(){if(!this.nativeTrack.enabled){this.processedTrack=t;return}yield this.removeOrReplaceProcessedTrack(t),this.videoHandler.updateSinks()})}getTrackIDBeingSent(){return this.getTrackBeingSent().id}getTrackBeingSent(){return this.enabled?this.processedTrack||this.nativeTrack:this.nativeTrack}switchCamera(){return c(this,null,function*(){var s;let t=this.getMediaTrackSettings().facingMode;if(!t||this.source!=="regular"){l.d(this.TAG,"facingMode not supported");return}let i=t==="environment"?"user":"environment";(s=this.nativeTrack)==null||s.stop();let r=yield this.replaceTrackWith(this.buildNewSettings({facingMode:i,deviceId:void 0}));yield this.replaceSender(r,this.enabled),this.nativeTrack=r,yield this.processPlugins(),this.videoHandler.updateSinks(),this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId,facingMode:i}),X.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;this.removeTrackEventListeners(i),i==null||i.stop();try{let r=yield wr(t);return this.addTrackEventListeners(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),this.settings.deviceId==="default"&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),r}catch(r){let s=yield wr(this.settings);throw this.addTrackEventListeners(s),yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks(),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=be.getEmptyVideoTrack(t);return this.removeTrackEventListeners(t),this.addTrackEventListeners(i),t==null||t.stop(),l.d(this.TAG,"replaceTrackWithBlank, Previous track stopped",t,"newTrack",i),i})}replaceSender(t,i){return c(this,null,function*(){i?yield this.replaceSenderTrack(this.processedTrack||t):yield this.replaceSenderTrack(t),this.stream.replaceStreamTrack(this.nativeTrack,t)})}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmuteNatively)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmuteNatively)}};var rt="renegotiation-callback-id",vi="ion-sfu";var st="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var ea="https://event.100ms.live/v2/client/report",ta="https://event-nonprod.100ms.live/v2/client/report";var Rt=Math.pow(2,31)-1,V={DEVICE_CHANGE:"device-change",LOCAL_AUDIO_ENABLED:"local-audio-enabled",LOCAL_VIDEO_ENABLED:"local-video-enabled",LOCAL_VIDEO_UNMUTED_NATIVELY:"local-video-unmuted-natively",LOCAL_AUDIO_UNMUTED_NATIVELY:"local-audio-unmuted-natively",STATS_UPDATE:"stats-update",RTC_STATS_UPDATE:"rtc-stats-update",TRACK_DEGRADED:"track-degraded",TRACK_RESTORED:"track-restored",TRACK_AUDIO_LEVEL_UPDATE:"track-audio-level-update",LOCAL_AUDIO_SILENCE:"local-audio-silence",ANALYTICS:"analytics",AUDIO_PLUGIN_FAILED:"audio-plugin-failed",POLICY_CHANGE:"policy-change",LOCAL_ROLE_UPDATE:"local-role-update",AUDIO_TRACK_UPDATE:"audio-track-update",AUDIO_TRACK_ADDED:"audio-track-added",AUDIO_TRACK_REMOVED:"audio-track-removed",AUTOPLAY_ERROR:"autoplay-error",LEAVE:"leave",ERROR:"error"},ia="2.5",ra="20250115",Ae="_handraise",$r=1e3,Kr=64,sa="https://whiteboard.100ms.live",aa="https://whiteboard-qa.100ms.live";var O=class a extends et{constructor(t,i,r,s){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new qr;this.preferredLayer="high";this.disableNoneLayerRequest=!1;this.disableNoneLayerRequest=!!s,this.setVideoHandler(new tt(this))}setTrackId(t){this.bizTrackId=t}get trackId(){return this.bizTrackId||super.trackId}get degraded(){return this._degraded}get degradedAt(){return this._degradedAt}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(ne(a.prototype,this,"setEnabled").call(this,t),this.videoHandler.updateSinks(!0))})}setPreferredLayer(t){return c(this,null,function*(){if(t==="none"){l.w("layer none will be ignored");return}if(this.preferredLayer=t,!!this.shouldSendVideoLayer(t,"preferLayer")){if(!this.hasSinks()){l.d(`[Remote Track] ${this.logIdentifier}
47
+ })()`;function J(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function Oe(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return J(a);let e=new Worker(URL.createObjectURL(new Blob([Bs],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function Vs(){if(typeof Worker=="undefined")return{sleep:e=>J(e)};let a=new Worker(URL.createObjectURL(new Blob([Bs],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function mi(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var Ro=35,Ho=5,Si=class{constructor(e,t,i){this.track=e;this.audioLevelEvent=t;this.silenceEvent=i;this.TAG="[TrackAudioLevelMonitor]";this.audioLevel=0;this.isMonitored=!1;this.interval=100;this.historyInterval=700;this.history=new Ne(this.historyInterval/this.interval);this.detectSilence=()=>c(this,null,function*(){let i=0;for(;this.isMonitored;){if(this.track.enabled)if(this.isSilentThisInstant()){if(i++,i>50){this.silenceEvent.publish({track:this.track});break}}else break;yield J(20)}});try{let r=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(r);let s=this.analyserNode.frequencyBinCount;this.dataArray=new Uint8Array(s)}catch(r){l.w(this.TAG,"Unable to initialize AudioContext",r)}}start(){this.stop(),this.isMonitored=!0,l.d(this.TAG,"Starting track Monitor",`${this.track}`),this.loop().then(()=>l.d(this.TAG,"Stopping track Monitor",`${this.track}`))}stop(){if(!this.analyserNode){l.d(this.TAG,"AudioContext not initialized");return}this.sendAudioLevel(0),this.isMonitored=!1}loop(){return c(this,null,function*(){for(;this.isMonitored;)this.sendAudioLevel(this.getMaxAudioLevelOverPeriod()),yield J(this.interval)})}sendAudioLevel(e=0){if(e=e>Ro?e:0,Math.abs(this.audioLevel-e)>Ho){this.audioLevel=e;let i={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(i)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode){l.d(this.TAG,"AudioContext not initialized");return}let e=this.calculateAudioLevel();return e!==void 0&&this.history.enqueue(e),this.history.aggregate(t=>Math.max(...t))}calculateAudioLevel(){if(!this.analyserNode||!this.dataArray){l.d(this.TAG,"AudioContext not initialized");return}this.analyserNode.getByteTimeDomainData(this.dataArray);let e=.009,t=e;for(let s of this.dataArray)t=Math.max(t,(s-128)/128);let i=(Math.log(e)-Math.log(t))/Math.log(e);return Math.ceil(Math.min(Math.max(i*100,0),100))}isSilentThisInstant(){if(!this.analyserNode||!this.dataArray){l.d(this.TAG,"AudioContext not initialized");return}return this.analyserNode.getByteTimeDomainData(this.dataArray),this.dataArray.every(e=>e===128||e===0)}createAnalyserNodeForStream(e){let t=ce.getAudioContext(),i=t.createMediaStreamSource(e),r=t.createAnalyser();return r.fftSize=2048,i.connect(r),r}};var Or=(t=>(t.SIP="sip",t.REGULAR="regular",t))(Or||{});var Fs=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Fs||{});var Gs=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(Gs||{}),Ws=(i=>(i.REGULAR="regular",i.SCREEN="screen",i.COMPOSITE="composite",i))(Ws||{}),$s=(r=>(r.INITIALISED="initialised",r.STARTED="started",r.STOPPED="stopped",r.FAILED="failed",r))($s||{}),Ks=(e=>(e.CAPTION="caption",e))(Ks||{});var We={f:"high",h:"medium",q:"low"};var xr=(t=>(t.VOICE="voice",t.MUSIC="music",t))(xr||{});var qs=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(qs||{});var Q=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._audioMode="voice";this._advanced=[{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{highpassFilter:{exact:!0}},{audioMirroring:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=this._audioMode==="music"?320:e,this}deviceId(e){return this._deviceId=e,this}audioMode(e="voice"){return this._audioMode=e,this._audioMode==="music"?this._maxBitrate=320:this._maxBitrate=32,this}advanced(e){return this._advanced=e,this}build(){return new $e(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced,this._audioMode)}},$e=class{constructor(e,t,i,r,s,o){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s,this.audioMode=o,this.audioMode==="music"?this.maxBitrate=320:this.maxBitrate=32}toConstraints(){return{deviceId:this.deviceId,advanced:this.audioMode==="music"?[]:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var q=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new Ke(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},Ke=class{constructor(e,t,i,r,s,o,n,d){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=d}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId,facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Mt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var xe=class{constructor(){this._video=new q().build();this._audio=new Q().build();this._screen=new q().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw S.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw S.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new Ze(this._video,this._audio,this._simulcast,this._screen||void 0)}},Ze=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=m(m({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=m(m({},this.video.toAnalyticsProperties()),e)),e}};function Js(a,e){return function(i){return!Co(a[i],e[i])}}var de=class a extends we{constructor(t,i,r,s,o=new Q().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this.TAG="[HMSLocalAudioTrack]";this.tracksCreated=new Set;this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){if(!this.shouldReacquireTrack()){l.d(this.TAG,`visibiltiy: ${document.visibilityState}`,`${this}`);return}if(document.visibilityState==="hidden")this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{l.d(this.TAG,"On visibile replacing track as it is not publishing");try{yield this.replaceTrackWith(this.settings)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.trackPermissions=()=>{hi("microphone",t=>{this.eventBus.analytics.publish(y.permissionChange(this.type,t)),t==="denied"&&this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})})};this.handleTrackMute=()=>{l.d(this.TAG,"muted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmute=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t}));try{yield this.setEnabled(this.enabled,!0),this.eventBus.localAudioUnmutedNatively.publish()}catch(i){this.eventBus.error.publish(i)}});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.shouldReacquireTrack=()=>ve(this.nativeTrack)||this.isTrackNotPublishing();this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Js(t,this.settings);(r("maxBitrate")||r("audioMode"))&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this,t)),(r("advanced")||r("audioMode"))&&(yield this.replaceTrackWith(t))});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(Js(t,this.settings)("deviceId")){this.manuallySelectedDeviceId=i?this.manuallySelectedDeviceId:t.deviceId,l.d(this.TAG,"device change","manual selection:",this.manuallySelectedDeviceId,"new device:",t.deviceId),yield this.replaceTrackWith(t);let s=this.nativeTrack.getSettings().groupId;!i&&t.deviceId&&(X.updateSelection("audioInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"audioInput",selection:{deviceId:t.deviceId,groupId:s}}))}});t.tracks.push(this),this.addTrackEventListeners(i),this.trackPermissions(),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!ve(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Pt(this,s,n),this.setFirstTrackId(i.id),r==="regular"&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}clone(t){let i=this.nativeTrack.clone();t.nativeStream.addTrack(i);let r=new a(t,i,this.source,this.eventBus,this.settings,this.room);return r.peerId=this.peerId,this.pluginsManager.pluginsMap.size>0&&this.pluginsManager.pluginsMap.forEach(s=>{r.addPlugin(s).catch(o=>l.e(this.TAG,"Plugin add failed while migrating",s,o))}),r}getManuallySelectedDeviceId(){return this.manuallySelectedDeviceId}resetManuallySelectedDeviceId(){this.manuallySelectedDeviceId=void 0}updateTrack(t){return c(this,null,function*(){t.enabled=this.enabled,yield this.stream.replaceStreamTrack(this.nativeTrack,t),this.nativeTrack=t,yield this.replaceSenderTrack(),!!this.audioLevelMonitor&&this.initAudioLevelMonitor()})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop(),this.removeTrackEventListeners(i),this.tracksCreated.forEach(r=>r.stop()),this.tracksCreated.clear();try{let r=yield Dr(t);this.addTrackEventListeners(r),this.tracksCreated.add(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),yield this.updateTrack(r)}catch(r){let s=yield Dr(this.settings);throw this.addTrackEventListeners(s),this.tracksCreated.add(s),yield this.updateTrack(s),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}try{yield this.pluginsManager.reprocessPlugins()}catch(r){this.eventBus.audioPluginFailed.publish(r)}})}setEnabled(t,i=!1){return c(this,null,function*(){t===this.enabled&&!i||(t&&this.shouldReacquireTrack()&&(yield this.replaceTrackWith(this.settings)),yield ne(a.prototype,this,"setEnabled").call(this,t),t&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),this.eventBus.localAudioEnabled.publish({enabled:t,track:this}))})}isPublishedTrackId(t){return this.publishedTrackId===t}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(ve(this.nativeTrack)){this.settings=r;return}yield this.handleDeviceChange(r,i),yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.pluginsManager.getPlugins()}addPlugin(t){return c(this,null,function*(){return this.pluginsManager.addPlugin(t)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}setProcessedTrack(t){return c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack()})}initAudioLevelMonitor(){this.audioLevelMonitor&&this.destroyAudioLevelMonitor(),l.d(this.TAG,"Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new Si(this,this.eventBus.trackAudioLevelUpdate,this.eventBus.localAudioSilence),this.audioLevelMonitor.start(),this.audioLevelMonitor.detectSilence()}destroyAudioLevelMonitor(){var t;(t=this.audioLevelMonitor)==null||t.stop(),this.audioLevelMonitor=void 0}cleanup(){return c(this,null,function*(){var t;ne(a.prototype,this,"cleanup").call(this),yield this.pluginsManager.cleanup(),yield this.pluginsManager.closeContext(),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.tracksCreated.forEach(i=>i.stop()),this.tracksCreated.clear(),this.isPublished=!1,this.destroyAudioLevelMonitor(),document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmute)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmute)}buildNewSettings(t){let{volume:i,codec:r,maxBitrate:s,deviceId:o,advanced:n,audioMode:d}=m(m({},this.settings),t);return new $e(i,r,s,o,n,d)}};var ie=class a extends we{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield ne(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var et=class extends De{constructor(t,i,r){super(t,i,r);this.type="video";this.sinkCount=0;this.handleTrackUnmute=()=>{this.getSinks().forEach(t=>this.reTriggerPlay({videoElement:t}))};this.reTriggerPlay=({videoElement:t})=>{setTimeout(()=>{t.play().catch(i=>{l.w("[HMSVideoTrack]","failed to play",i.message)})},0)};if(i.kind!=="video")throw new Error("Expected 'track' kind = 'video'")}setVideoHandler(t){this.videoHandler=t}hasSinks(){return this.sinkCount>0}getSinks(){return this.videoHandler.getVideoElements()||[]}attach(t){this.videoHandler.addVideoElement(t)}detach(t){this.videoHandler.removeVideoElement(t)}addSink(t){this.addSinkInternal(t,this.nativeTrack)}removeSink(t){t.srcObject!==null&&(t.srcObject=null,this.reduceSinkCount())}cleanup(){super.cleanup(),this.videoHandler.cleanup()}addSinkInternal(t,i){let r=t.srcObject;if(r!==null&&r instanceof MediaStream){let o=r.getVideoTracks()[0];if((o==null?void 0:o.id)===i.id){if(!o.muted&&o.readyState==="live")return;this.reduceSinkCount()}else this.reduceSinkCount()}this.addPropertiesToElement(t);let s=new MediaStream([i]);t.srcObject=s,this.reTriggerPlay({videoElement:t}),this.sinkCount++}reduceSinkCount(){this.sinkCount>0&&this.sinkCount--}addPropertiesToElement(t){Cs||(t.autoplay=!0),t.playsInline=!0,t.muted=!0,t.controls=!1}};import xo from"lodash.isequal";import{v4 as Do}from"uuid";var bt={none:-1,low:0,medium:1,high:2},Lo=.5,Qs=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>bt[o.layer]-bt[n.layer]),s=e[i]*((window==null?void 0:window.devicePixelRatio)||1);for(let o=0;o<r.length;o++){let{resolution:n,layer:d}=r[o],u=n[i];if(s<=u){t=d;break}else{let p=r[o+1],h=p?p.resolution[i]:Number.POSITIVE_INFINITY;if((s-u)/(h-u)<Lo){t=d;break}}}return t};var Ur=class{constructor(){this.TAG="[HMSIntersectionObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t)=>{var i;this.createObserver(),this.unobserve(e),(i=this.intersectionObserver)==null||i.observe(e),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.intersectionObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.intersectionObserver&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersection))};this.handleIntersection=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.IntersectionObserver!="undefined";return e||l.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},zs=new Ur;var Br=class{constructor(){this.TAG="[HMSResizeObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t,i={box:"border-box"})=>{var r;this.createObserver(),this.unobserve(e),(r=this.resizeObserver)==null||r.observe(e,i),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.resizeObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(mi(this.handleResize,300)))};this.handleResize=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.ResizeObserver!="undefined";return e||l.w(this.TAG,"Resize Observer is not supported"),e}},Ys=new Br;var tt=class{constructor(e){this.track=e;this.TAG="[VideoElementManager]";this.videoElements=new Set;this.entries=new WeakMap;this.handleIntersection=e=>c(this,null,function*(){let t=getComputedStyle(e.target).visibility==="visible";this.track.enabled&&(e.isIntersecting&&t||!document.contains(e.target))?(l.d(this.TAG,"add sink intersection",`${this.track}`,this.id),this.entries.set(e.target,e.boundingClientRect),yield this.selectMaxLayer(),yield this.track.addSink(e.target)):(l.d(this.TAG,"remove sink intersection",`${this.track}`,this.id),yield this.track.removeSink(e.target))});this.handleResize=e=>c(this,null,function*(){!this.track.enabled||!(this.track instanceof O)||(this.entries.set(e.target,e.contentRect),yield this.selectMaxLayer())});this.cleanup=()=>{this.videoElements.forEach(e=>{var t,i;e.srcObject=null,(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e)}),this.videoElements.clear(),this.resizeObserver=void 0,this.intersectionObserver=void 0};this.init(),this.id=Do()}updateSinks(e=!1){for(let t of this.videoElements)this.track.enabled?this.track.addSink(t,e):this.track.removeSink(t,e)}addVideoElement(e){return c(this,null,function*(){var t;this.videoElements.has(e)||(this.init(),l.d(this.TAG,`Adding video element for ${this.track}`,this.id),this.videoElements.add(e),this.videoElements.size>=10&&l.w(this.TAG,`${this.track}`,`the track is added to ${this.videoElements.size} video elements, while this may be intentional, it's likely that there is a bug leading to unnecessary creation of video elements in the UI`),(t=this.intersectionObserver)!=null&&t.isSupported()?this.intersectionObserver.observe(e,this.handleIntersection):U&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof O&&(yield this.track.setPreferredLayer(this.track.getPreferredLayer())))})}removeVideoElement(e){var t,i;this.track.removeSink(e),this.videoElements.delete(e),this.entries.delete(e),(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e),l.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){U&&(this.resizeObserver=Ys,this.intersectionObserver=zs)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:n,display:d}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,t+=e.offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&i+r>window.pageXOffset&&!o&&(n!==""?parseFloat(n)>0:!0)&&d!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof O)||this.videoElements.size===0)return;let e;for(let t of this.videoElements){let i=this.entries.get(t);if(!i)continue;let{width:r,height:s}=i;if(r===0||s===0)continue;let o=Qs(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=bt[o]>bt[e]?o:e:e=o}e&&(l.d(this.TAG,`selecting max layer ${e} for the track`,`${this.track}`),yield this.track.setPreferredLayer(e))})}};var Vr=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Vr||{}),Fr=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(Fr||{});var At=class{constructor(){this.total=0;this.count=0}add(e){this.count++,this.total+=e}getAvg(){return Math.floor(this.total/this.count)}reset(){this.total=0,this.count=0}};var it=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new At,this.addedTimestamps={},this.processingAvgs={},this.pluginAdded={},this.pluginInputFrameRate={},this.pluginFrameRate={}}added(e,t,i){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.processingAvgs[e]=new At,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(me.added(e,this.addedTimestamps[e]))}removed(e){var t;if(this.pluginAdded[e]){let i={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],avgPreProcessingTime:this.preProcessingAvgs.getAvg(),avgProcessingTime:(t=this.processingAvgs[e])==null?void 0:t.getAvg(),inputFrameRate:this.pluginInputFrameRate[e],pluginFrameRate:this.pluginFrameRate[e]};this.eventBus.analytics.publish(me.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(me.failure(e,t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){l.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),l.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=S.MediaPluginErrors.InitFailed("VIDEO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw l.e(this.TAG,s),this.failure(e,s),s}i&&(this.initTime[e]=i)})}preProcessWithTime(e){return c(this,null,function*(){let t=yield this.timeInMs(e);this.preProcessingAvgs.add(t)})}processWithTime(e,t){return c(this,null,function*(){var r;let i;try{i=yield this.timeInMs(t)}catch(s){let o=S.MediaPluginErrors.ProcessingFailed("VIDEO_PLUGINS",`Failed during processing of plugin${s.message||s}`);throw l.e(this.TAG,o),this.failure(e,o),o}i&&((r=this.processingAvgs[e])==null||r.add(i))})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.processingAvgs[e],delete this.pluginAdded[e],delete this.pluginInputFrameRate[e],delete this.pluginFrameRate[e]}};var Xs=24,wo=320,_o=240,It=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=Vs();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new it(t),this.canvases=new Array}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e,t){return c(this,null,function*(){var i;if(this.pluginAddInProgress){let r=(i=e.getName)==null?void 0:i.call(e);if(!r||r===""){l.w("no name provided by the plugin");return}let s=S.MediaPluginErrors.AddAlreadyInProgress("VIDEO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.failure(r,s),l.w("can't add another plugin when previous add is in progress"),s}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e,t)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e,t){return c(this,null,function*(){var o,n;let i=(o=e.getName)==null?void 0:o.call(e);if(!i||i===""){l.w("no name provided by the plugin");return}if(this.pluginsMap.has(i)){l.w(this.TAG,`plugin - ${e.getName()} already added.`);return}let r=this.hmsTrack.getMediaTrackSettings().frameRate||Xs,s=0;t&&t>0?(l.i(this.TAG,`adding plugin ${e.getName()} with framerate ${t}`),t<r&&(s=Math.ceil(r/t)-1),this.analytics.added(i,r,t)):(l.i(this.TAG,`adding plugin ${e.getName()}`),this.analytics.added(i,r)),l.i(this.TAG,"numFrames to skip processing",s),this.pluginNumFramesToSkip[i]=s,this.pluginNumFramesSkipped[i]=s,this.validateAndThrow(i,e);try{if(yield this.analytics.initWithTime(i,()=>c(this,null,function*(){return yield e.init()})),this.pluginsMap.set(i,e),this.pluginsMap.size+1>this.canvases.length)for(let d=this.canvases.length;d<=this.pluginsMap.size;d++)this.canvases[d]=document.createElement("canvas");yield this.startPluginsLoop((n=e.getContextType)==null?void 0:n.call(e))}catch(d){throw l.e(this.TAG,"failed to add plugin",d),yield this.removePlugin(e),d}})}validatePlugin(e){return e.checkSupport()}validateAndThrow(e,t){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else{let r;switch(i.errType){case"PLATFORM_NOT_SUPPORTED":throw r=S.MediaPluginErrors.PlatformNotSupported("VIDEO_PLUGINS","platform not supported, see docs"),this.analytics.failure(e,r),r;case"DEVICE_NOT_SUPPORTED":throw r=S.MediaPluginErrors.DeviceNotSupported("VIDEO_PLUGINS","video device not supported, see docs"),this.analytics.failure(e,r),r}}}removePlugin(e){return c(this,null,function*(){let t=e.getName();if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.removePluginEntry(t),this.pluginsMap.size===0&&(l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.stopPluginsLoop()),e.stop(),this.analytics.removed(t)})}removePluginEntry(e){this.pluginsMap.delete(e),this.pluginNumFramesToSkip[e]&&delete this.pluginNumFramesToSkip[e],this.pluginNumFramesSkipped[e]&&delete this.pluginNumFramesSkipped[e]}waitForRestart(){return c(this,null,function*(){if(!(!this.pluginsLoopRunning||this.pluginsLoopState==="running"))for(;this.pluginsLoopState==="paused";)yield Oe(100)})}cleanup(){return c(this,null,function*(){var e;for(let t of this.pluginsMap.values())yield this.removePlugin(t);(e=this.outputTrack)==null||e.stop()})}initElementsAndStream(e){this.inputCanvas||(this.inputCanvas=document.createElement("canvas")),this.outputCanvas=document.createElement("canvas"),this.inputVideo||(this.inputVideo=document.createElement("video")),this.inputCanvas.getContext("2d"),this.outputCanvas.getContext(e||"2d");let t=this.outputCanvas.captureStream();this.outputTrack=t.getVideoTracks()[0]}startPluginsLoop(e){return c(this,null,function*(){if(!this.pluginsLoopRunning){this.initElementsAndStream(e),this.pluginsLoopRunning=!0;try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(t){throw this.pluginsLoopRunning=!1,l.e(this.TAG,"error in setting processed track",t),t}this.pluginsLoop().then(()=>{l.d(this.TAG,"processLoop stopped")})}})}stopPluginsLoop(){return c(this,null,function*(){var e;this.pluginsLoopRunning=!1,yield this.hmsTrack.setProcessedTrack(void 0),this.resetCanvases(),(e=this.outputTrack)==null||e.stop(),this.inputVideo&&(this.inputVideo.srcObject=null,this.inputVideo=void 0)})}pluginsLoop(){return c(this,null,function*(){for(;this.pluginsLoopRunning;){let e=this.hmsTrack.getMediaTrackSettings().frameRate||Xs,t=Math.floor(1e3/e);if(!this.hmsTrack.enabled||this.hmsTrack.nativeTrack.readyState==="ended"){this.pluginsLoopState==="running"&&this.resetCanvases(),this.pluginsLoopState="paused",yield this.reusableWorker.sleep(t);continue}let i=0;try{yield this.analytics.preProcessWithTime(()=>c(this,null,function*(){return yield this.doPreProcessing()}));let r=Date.now();yield this.processFramesThroughPlugins(),i=Math.floor(Date.now()-r),i>t&&(i=t)}catch(r){l.e(this.TAG,"error in plugins loop",r)}this.pluginsLoopState="running",yield this.reusableWorker.sleep(t-i)}})}doPreProcessing(){return c(this,null,function*(){yield this.addTrackToVideo(),yield this.updateInputCanvas()})}processFramesThroughPlugins(){return c(this,null,function*(){this.canvases[0]=this.inputCanvas;let e=0;for(let t of this.pluginsMap.values()){let i=t.getName();if(t){try{let r=this.checkIfSkipRequired(i);if(t.getPluginType()==="TRANSFORM"){let s=(o,n)=>c(this,null,function*(){try{yield t.processVideoFrame(o,n,r)}catch(d){l.e(this.TAG,`error in processing plugin ${i}`,d)}});if(r)e===this.pluginsMap.size-1?yield s(this.canvases[e],this.outputCanvas):yield s(this.canvases[e],this.canvases[e+1]);else{let o=this.canvases[e],n=this.canvases[e+1];e===this.pluginsMap.size-1?yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return s(o,this.outputCanvas)})):yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return s(o,n)}))}}else t.getPluginType()==="ANALYZE"&&!r&&(yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return yield t.processVideoFrame(this.inputCanvas)})))}catch(r){l.e(this.TAG,`error in processing plugin ${i}`,r),yield this.removePlugin(t)}e++}}})}addTrackToVideo(){return c(this,null,function*(){var t;if(!this.inputVideo)return;let e=this.inputVideo.srcObject;e!==null&&e instanceof MediaStream&&((t=e.getVideoTracks()[0])==null?void 0:t.id)===this.hmsTrack.nativeTrack.id||(this.inputVideo.pause(),this.inputVideo.srcObject=new MediaStream([this.hmsTrack.nativeTrack]),this.inputVideo.muted=!0,this.inputVideo.playsInline=!0,yield this.inputVideo.play())})}updateInputCanvas(){return c(this,null,function*(){if(!this.inputCanvas||!this.inputVideo)return;let{width:e=wo,height:t=_o}=this.hmsTrack.getMediaTrackSettings();this.inputCanvas.height!==t&&(this.inputCanvas.height=t),this.inputCanvas.width!==e&&(this.inputCanvas.width=e),this.inputCanvas.getContext("2d").drawImage(this.inputVideo,0,0,e,t)})}resetCanvases(){if(!this.outputCanvas||!this.inputCanvas)return;let e=this.inputCanvas.getContext("2d");e&&(e.fillStyle="rgb(0, 0, 0)",e.fillRect(0,0,this.outputCanvas.width,this.outputCanvas.height)),this.canvases=[]}checkIfSkipRequired(e){let t=!1;return this.pluginNumFramesSkipped[e]<this.pluginNumFramesToSkip[e]?(this.pluginNumFramesSkipped[e]++,t=!0):(t=!1,this.pluginNumFramesSkipped[e]=0),t}};var gi=class{constructor(e,t){this.TAG="[MediaStreamPluginsManager]";this.plugins=new Set,this.analytics=new it(e),this.room=t}addPlugins(e){e.forEach(t=>{var i;switch(t.getName()){case"HMSEffectsPlugin":if(!((i=this.room)!=null&&i.isEffectsEnabled)){let r="Effects Virtual Background is not enabled for this room";if(this.plugins.size===0)throw Error(r);l.w(this.TAG,r);return}break;default:}this.plugins.add(t)})}removePlugins(e){e.forEach(t=>{t.stop(),this.analytics.removed(t.getName()),this.plugins.delete(t)})}applyPlugins(e){let t=e;for(let i of this.plugins){let r=i.getName();try{t=i.apply(t),this.analytics.added(r)}catch(s){this.analytics.failure(r,s),l.e("Could not apply plugin",s,r)}}return t}getPlugins(){return Array.from(this.plugins).map(e=>e.getName())}cleanup(){return c(this,null,function*(){this.removePlugins(Array.from(this.plugins))})}};import{v4 as Oo}from"uuid";var No=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],Ti=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),l.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){l.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...No,...e].reduce((t,i)=>M(m({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var Gr={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default",audioMode:"voice"},Me,fi,be=class a{constructor(e,t,i,r,s){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=s;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=Gr){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),d=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let h={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};h.audio&&this.analyticsTimer.start("local_audio_track_time"),h.video&&this.analyticsTimer.start("local_video_track_time");try{l.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:h}),s=yield this.getLocalTracks(h,t,d)}catch(T){s=yield this.retryGetLocalTracks(T,t,h,d)}return h.audio&&this.analyticsTimer.end("local_audio_track_time"),h.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&s.push(o),n&&i&&!p&&s.push(n),s})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new Ze(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}optimizeScreenShareConstraint(e,t){return c(this,null,function*(){var s,o,n;if(typeof t.video=="boolean"||!((s=t.video)!=null&&s.width)||!((o=t.video)!=null&&o.height))return;let i=this.store.getPublishParams();if(!i||!((n=i.allowed)!=null&&n.includes("screen")))return;let r=document.createElement("video");r.srcObject=e,r.addEventListener("loadedmetadata",()=>c(this,null,function*(){let{videoWidth:d,videoHeight:u}=r,p=i.screen,h=p.width*p.height,T=d/u,g=p.width/p.height;if(T>g){let f=t.video,E=T/g,v=Math.sqrt(E);d*u>h?(f.width=d/v,f.height=u/v):(f.height=u*v,f.width=d*v),yield e.getVideoTracks()[0].applyConstraints(f)}}))})}getLocalScreen(e,t=!1){return c(this,null,function*(){var T;let i=yield this.getOrDefaultScreenshareConfig(e),r=this.getScreenshareSettings(i.videoOnly),s={video:M(m({},r==null?void 0:r.video.toConstraints(!0)),{displaySurface:i.displaySurface}),preferCurrentTab:i.preferCurrentTab,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio};if(r!=null&&r.audio){let g=(T=r==null?void 0:r.audio)==null?void 0:T.toConstraints();delete g.advanced,s.audio=M(m({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}else e!=null&&e.forceCurrentTab&&e.preferCurrentTab&&e.cropElement&&(s.audio={echoCancellation:!0,noiseSuppression:!0});let o;try{l.d("retrieving screenshare with ",{config:i},{constraints:s}),o=yield navigator.mediaDevices.getDisplayMedia(s),t&&(yield this.optimizeScreenShareConstraint(o,s))}catch(g){l.w(this.TAG,"error in getting screenshare - ",g);let f=_e(g,"screen");throw this.eventBus.analytics.publish(y.publish({error:f,devices:this.deviceManager.getDevices(),settings:new Ze(r==null?void 0:r.video,r==null?void 0:r.audio,!1)})),f}let n=[],d=new Se(o),u=o.getVideoTracks()[0],p=new G(d,u,"screen",this.eventBus,r==null?void 0:r.video,this.store.getRoom());p.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(p,i.forceCurrentTab);p.isCurrentTab=g,yield p.cropTo(i.cropTarget)}catch(g){throw o.getTracks().forEach(f=>f.stop()),g}n.push(p);let h=o.getAudioTracks()[0];if(h){let g=new de(d,h,"screen",this.eventBus,r==null?void 0:r.audio,this.store.getRoom());n.push(g)}return l.v(this.TAG,"getLocalScreen",n),n})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:Oo(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),l.d("setting capture handle - ",e.handle),navigator.mediaDevices.setCaptureHandleConfig(e),this.captureHandleIdentifier=e.handle)}validateCurrentTabCapture(e,t){let i=e.getCaptureHandle(),r=!!(this.captureHandleIdentifier&&(i==null?void 0:i.handle)===this.captureHandleIdentifier);if(t&&!r)throw l.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),S.TracksErrors.CurrentTabNotShared();return r}requestPermissions(){return c(this,null,function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})).getTracks().forEach(t=>t.stop())}catch(e){l.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,d,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((d=e==null?void 0:e.getSettings())==null?void 0:d.height)||240,r=1;Me||(Me=document.createElement("canvas"),Me.width=t,Me.height=i,(u=Me.getContext("2d"))==null||u.fillRect(0,0,t,i)),fi||(fi=setInterval(()=>{let p=Me==null?void 0:Me.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=Me.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=ce.getAudioContext(),t=e.createOscillator(),i=e.createMediaStreamDestination();t.connect(i),t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}static cleanup(){clearInterval(fi),fi=void 0,Me=void 0}getAVTracks(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:e.audio?e.audio.toConstraints():!1,video:e.video?e.video.toConstraints():!1});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){yield this.deviceManager.init();let i=!!(!this.deviceManager.hasWebcamPermission&&e.video),r=!!(!this.deviceManager.hasMicrophonePermission&&e.audio),s=this.getErrorType(i,r);throw _e(t,s)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new xe().video(i).audio(t).build()}isInIframe(){try{return window.self!==window.top}catch(e){return!0}}retryGetLocalTracks(e,t,i,r){return c(this,null,function*(){if(e instanceof k&&e.action==="TRACK"){this.observer.onFailure(e);let s=e.code===P.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(s){let d=new xe().video(new Ke).audio(new $e).build();l.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,d,r)}catch(u){let p=u instanceof k?u.nativeError:u,h=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let T=S.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");T.addNativeError(p),h=T}return yield this.retryGetLocalTracks(h,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,l.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(d){return l.w(this.TAG,"Fetch empty tacks failed",d),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(d),yield this.getLocalTracks(i,t,r)}}else return l.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(e),[]})}getErrorType(e,t){return e&&t?"audio, video":e?"video":t?"audio":"audio, video"}getEmptyTracks(e){let t=[];return e.audio==="empty"&&t.push(a.getEmptyAudioTrack()),e.video==="empty"&&t.push(a.getEmptyVideoTrack()),t}updateCurrentLocalTrackSettings(e){return c(this,null,function*(){let t=this.store.getLocalPeerTracks(),i=t.find(n=>n.type==="video"&&n.source==="regular"),r=t.find(n=>n.type==="audio"&&n.source==="regular"),s=t.find(n=>n.type==="video"&&n.source==="screen");e!=null&&e.video&&(yield i==null?void 0:i.setSettings(e.video)),e!=null&&e.audio&&(yield r==null?void 0:r.setSettings(e.audio));let o=this.getScreenshareSettings(!0);return o!=null&&o.video&&(yield s==null?void 0:s.setSettings(o==null?void 0:o.video)),{videoTrack:i,audioTrack:r}})}getAudioSettings(e){var o;let t=this.store.getPublishParams();if(!t||!((o=t.allowed)!=null&&o.includes("audio")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.audioTrack,s=(r==null?void 0:r.settings.deviceId)||e.audioInputDeviceId;return new Q().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(s||Gr.audioInputDeviceId).build()}getVideoSettings(e){var n;let t=this.store.getPublishParams();if(!t||!((n=t.allowed)!=null&&n.includes("video")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.videoTrack,s=(r==null?void 0:r.settings.deviceId)||e.videoDeviceId,o=t.video;return new q().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(s||Gr.videoDeviceId).build()}getScreenshareSettings(e=!1){var r;let t=this.store.getPublishParams();if(!t||!((r=t.allowed)!=null&&r.includes("screen")))return null;let i=t.screen;return{video:new q().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new Q().build()}}getOrDefaultScreenshareConfig(e){return c(this,null,function*(){var i;let t=Object.assign({videoOnly:!1,audioOnly:!1,forceCurrentTab:!1,preferCurrentTab:!1,selfBrowserSurface:"exclude",surfaceSwitching:"include",systemAudio:"exclude",displaySurface:"monitor"},e||{});return t.forceCurrentTab&&(t.videoOnly=!0,t.preferCurrentTab=!0,t.selfBrowserSurface="include",t.surfaceSwitching="exclude"),t.preferCurrentTab&&(t.selfBrowserSurface="include",t.displaySurface=void 0),t.cropElement&&((i=window.CropTarget)!=null&&i.fromElement)&&(t.cropTarget=yield window.CropTarget.fromElement(t.cropElement)),t})}createHMSLocalTracks(e,t,i){let r=e.find(n=>n.kind==="video"),s=e.find(n=>n.kind==="audio");i?e.forEach(n=>i==null?void 0:i.nativeStream.addTrack(n)):i=new Se(new MediaStream(e));let o=[];if(s&&(t!=null&&t.audio)){let n=new de(i,s,"regular",this.eventBus,t.audio,this.store.getRoom());o.push(n)}if(r&&(t!=null&&t.video)){let n=new G(i,r,"regular",this.eventBus,t.video,this.store.getRoom());n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function Zs(a,e){return function(i){return!xo(a[i],e[i])}}var G=class a extends et{constructor(t,i,r,s,o=new q().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this._layerDefinitions=[];this.TAG="[HMSLocalVideoTrack]";this.enabledStateBeforeBackground=!1;this.isCurrentTab=!1;this.isPublished=!1;this.replaceSenderTrack=t=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(t)});this.buildNewSettings=t=>{let{width:i,height:r,codec:s,maxFramerate:o,maxBitrate:n,deviceId:d,advanced:u,facingMode:p}=m(m({},this.settings),t);return new Ke(i,r,s,o,d,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Zs(t,this.settings);if(r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("width")||r("height")||r("advanced"))if(this.source==="video"){let s=yield this.replaceTrackWith(t);yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks()}else yield this.nativeTrack.applyConstraints(t.toConstraints())});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(Zs(t,this.settings)("deviceId")&&this.source==="regular"){if(this.enabled){delete t.facingMode;let o=yield this.replaceTrackWith(t);yield this.replaceSender(o,this.enabled),this.nativeTrack=o,yield this.processPlugins(),this.videoHandler.updateSinks()}let s=this.nativeTrack.getSettings().groupId;!i&&t.deviceId&&(X.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s}}))}});this.trackPermissions=()=>{hi("camera",t=>{this.eventBus.analytics.publish(y.permissionChange(this.type,t)),t==="denied"&&this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})})};this.handleTrackMute=()=>{l.d(this.TAG,"muted natively",document.visibilityState);let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmuteNatively=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t})),this.handleTrackUnmute(),this.eventBus.localVideoEnabled.publish({enabled:this.enabled,track:this}),this.eventBus.localVideoUnmutedNatively.publish(),yield this.setEnabled(this.enabled)});this.removeOrReplaceProcessedTrack=t=>c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack(this.processedTrack||this.nativeTrack)});this.handleVisibilityChange=()=>c(this,null,function*(){if(document.visibilityState==="hidden")this.enabledStateBeforeBackground=this.enabled,this.enabled&&(yield this.setEnabled(!1)),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{if(l.d(this.TAG,"visibility visible, restoring track state",this.enabledStateBeforeBackground),this.enabledStateBeforeBackground)try{yield this.setEnabled(!0)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.trackPermissions(),t.tracks.push(this),this.setVideoHandler(new tt(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new It(this,s),this.mediaStreamPluginsManager=new gi(s,n),this.setFirstTrackId(this.trackId),this.eventBus.localAudioUnmutedNatively.subscribe(this.handleTrackUnmute),U&&r==="regular"&&Mt()&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}clone(t){let i=this.nativeTrack.clone();t.nativeStream.addTrack(i);let r=new a(t,i,this.source,this.eventBus,this.settings,this.room);return r.peerId=this.peerId,this.pluginsManager.pluginsMap.size>0&&this.pluginsManager.pluginsMap.forEach(s=>{r.addPlugin(s).catch(o=>l.e(this.TAG,"Plugin add failed while migrating",s,o))}),this.mediaStreamPluginsManager.plugins.size>0&&r.addStreamPlugins(Array.from(this.mediaStreamPluginsManager.plugins)),r}setSimulcastDefinitons(t){this._layerDefinitions=t}getSimulcastDefinitions(){return this._layerDefinitions}setEnabled(t){return c(this,null,function*(){var i;if(t!==this.enabled){if(this.source==="regular"){let r;t?r=yield this.replaceTrackWith(this.settings):r=yield this.replaceTrackWithBlank(),yield this.replaceSender(r,t),(i=this.nativeTrack)==null||i.stop(),this.nativeTrack=r,yield ne(a.prototype,this,"setEnabled").call(this,t),t&&(yield this.pluginsManager.waitForRestart(),yield this.processPlugins(),this.settings=this.buildNewSettings({deviceId:r.getSettings().deviceId})),this.videoHandler.updateSinks()}this.eventBus.localVideoEnabled.publish({enabled:t,track:this})}})}processPlugins(){return c(this,null,function*(){try{if(this.pluginsManager.getPlugins().length>0)return;if(this.mediaStreamPluginsManager.getPlugins().length>0){let r=this.mediaStreamPluginsManager.applyPlugins(new MediaStream([this.nativeTrack])).getVideoTracks()[0];yield this.setProcessedTrack(r)}else yield this.setProcessedTrack();this.videoHandler.updateSinks()}catch(t){console.error("error in processing plugin(s)",t)}})}addStreamPlugins(t){return c(this,null,function*(){if(this.pluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSMediaStreamPlugin and HMSVideoPlugin cannot be used together");this.mediaStreamPluginsManager.addPlugins(t),yield this.processPlugins()})}removeStreamPlugins(t){return c(this,null,function*(){this.mediaStreamPluginsManager.removePlugins(t),yield this.processPlugins()})}isPublishedTrackId(t){return this.publishedTrackId===t}addSink(t){this.addSinkInternal(t,this.processedTrack||this.nativeTrack)}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(yield this.handleDeviceChange(r,i),!this.enabled||ve(this.nativeTrack)){this.settings=r;return}else yield this.pluginsManager.waitForRestart();yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.mediaStreamPluginsManager.getPlugins().length>0?this.mediaStreamPluginsManager.getPlugins():this.pluginsManager.getPlugins()}addPlugin(t,i){return c(this,null,function*(){if(this.mediaStreamPluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSVideoPlugin and HMSMediaStreamPlugin cannot be used together");return this.pluginsManager.addPlugin(t,i)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}cleanup(){return c(this,null,function*(){var t;this.eventBus.localAudioUnmutedNatively.unsubscribe(this.handleTrackUnmute),yield this.mediaStreamPluginsManager.cleanup(),yield this.pluginsManager.cleanup(),ne(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,U&&Mt()&&document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}cropTo(t){return c(this,null,function*(){if(t&&this.source==="screen")try{this.nativeTrack.cropTo&&(yield this.nativeTrack.cropTo(t))}catch(i){throw l.e(this.TAG,"failed to crop screenshare capture - ",i),S.TracksErrors.GenericTrack("TRACK","failed to crop screenshare capture")}})}getCaptureHandle(){if(this.nativeTrack.getCaptureHandle)return this.nativeTrack.getCaptureHandle()}setProcessedTrack(t){return c(this,null,function*(){if(!this.nativeTrack.enabled){this.processedTrack=t;return}yield this.removeOrReplaceProcessedTrack(t),this.videoHandler.updateSinks()})}getTrackIDBeingSent(){return this.getTrackBeingSent().id}getTrackBeingSent(){return this.enabled?this.processedTrack||this.nativeTrack:this.nativeTrack}switchCamera(){return c(this,null,function*(){var s;let t=this.getMediaTrackSettings().facingMode;if(!t||this.source!=="regular"){l.d(this.TAG,"facingMode not supported");return}let i=t==="environment"?"user":"environment";(s=this.nativeTrack)==null||s.stop();let r=yield this.replaceTrackWith(this.buildNewSettings({facingMode:i,deviceId:void 0}));yield this.replaceSender(r,this.enabled),this.nativeTrack=r,yield this.processPlugins(),this.videoHandler.updateSinks(),this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId,facingMode:i}),X.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();try{let r=yield wr(t);return l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),this.settings.deviceId==="default"&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),r}catch(r){let s=yield wr(this.settings);throw yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks(),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=be.getEmptyVideoTrack(t);return t==null||t.stop(),l.d(this.TAG,"replaceTrackWithBlank, Previous track stopped",t,"newTrack",i),i})}replaceSender(t,i){return c(this,null,function*(){i?yield this.replaceSenderTrack(this.processedTrack||t):yield this.replaceSenderTrack(t),this.stream.replaceStreamTrack(this.nativeTrack,t)})}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmuteNatively)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmuteNatively)}};var rt="renegotiation-callback-id",vi="ion-sfu";var st="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var ea="https://event.100ms.live/v2/client/report",ta="https://event-nonprod.100ms.live/v2/client/report";var Rt=Math.pow(2,31)-1,V={DEVICE_CHANGE:"device-change",LOCAL_AUDIO_ENABLED:"local-audio-enabled",LOCAL_VIDEO_ENABLED:"local-video-enabled",LOCAL_VIDEO_UNMUTED_NATIVELY:"local-video-unmuted-natively",LOCAL_AUDIO_UNMUTED_NATIVELY:"local-audio-unmuted-natively",STATS_UPDATE:"stats-update",RTC_STATS_UPDATE:"rtc-stats-update",TRACK_DEGRADED:"track-degraded",TRACK_RESTORED:"track-restored",TRACK_AUDIO_LEVEL_UPDATE:"track-audio-level-update",LOCAL_AUDIO_SILENCE:"local-audio-silence",ANALYTICS:"analytics",AUDIO_PLUGIN_FAILED:"audio-plugin-failed",POLICY_CHANGE:"policy-change",LOCAL_ROLE_UPDATE:"local-role-update",AUDIO_TRACK_UPDATE:"audio-track-update",AUDIO_TRACK_ADDED:"audio-track-added",AUDIO_TRACK_REMOVED:"audio-track-removed",AUTOPLAY_ERROR:"autoplay-error",LEAVE:"leave",ERROR:"error"},ia="2.5",ra="20250115",Ae="_handraise",$r=1e3,Kr=64,sa="https://whiteboard.100ms.live",aa="https://whiteboard-qa.100ms.live";var O=class a extends et{constructor(t,i,r,s){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new qr;this.preferredLayer="high";this.disableNoneLayerRequest=!1;this.disableNoneLayerRequest=!!s,this.setVideoHandler(new tt(this))}setTrackId(t){this.bizTrackId=t}get trackId(){return this.bizTrackId||super.trackId}get degraded(){return this._degraded}get degradedAt(){return this._degradedAt}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(ne(a.prototype,this,"setEnabled").call(this,t),this.videoHandler.updateSinks(!0))})}setPreferredLayer(t){return c(this,null,function*(){if(t==="none"){l.w("layer none will be ignored");return}if(this.preferredLayer=t,!!this.shouldSendVideoLayer(t,"preferLayer")){if(!this.hasSinks()){l.d(`[Remote Track] ${this.logIdentifier}
48
48
  streamId=${this.stream.id}
49
49
  trackId=${this.trackId}
50
50
  saving ${t}, source=${this.source}