@100mslive/hms-video-store 0.13.3-alpha.7 → 0.13.3-alpha.8

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.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var an=Object.create;var Pt=Object.defineProperty,on=Object.defineProperties,nn=Object.getOwnPropertyDescriptor,cn=Object.getOwnPropertyDescriptors,dn=Object.getOwnPropertyNames,gi=Object.getOwnPropertySymbols,ea=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty,ta=Object.prototype.propertyIsEnumerable,ln=Reflect.get;var Zs=(a,e,t)=>e in a?Pt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))Gr.call(e,t)&&Zs(a,t,e[t]);if(gi)for(var t of gi(e))ta.call(e,t)&&Zs(a,t,e[t]);return a},M=(a,e)=>on(a,cn(e));var Wr=(a,e)=>{var t={};for(var i in a)Gr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&gi)for(var i of gi(a))e.indexOf(i)<0&&ta.call(a,i)&&(t[i]=a[i]);return t};var un=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),pn=(a,e)=>{for(var t in e)Pt(a,t,{get:e[t],enumerable:!0})},ia=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of dn(e))!Gr.call(a,r)&&r!==t&&Pt(a,r,{get:()=>e[r],enumerable:!(i=nn(e,r))||i.enumerable});return a};var $e=(a,e,t)=>(t=a!=null?an(ea(a)):{},ia(e||!a||!a.__esModule?Pt(t,"default",{value:a,enumerable:!0}):t,a)),hn=a=>ia(Pt({},"__esModule",{value:!0}),a);var pe=(a,e,t)=>ln(ea(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 Zr=un((Zl,vn)=>{vn.exports={version:"0.13.3-alpha.7",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"],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":"^2.0.6",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.39","@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:"d6ee0b945aece0a65a5279792dada3b7eed2cabb"}});var pl={};pn(pl,{ConnectivityState:()=>wo,DeviceType:()=>cs,Diagnostics:()=>St,DomainCategory:()=>Jr,EventBus:()=>gt,HLSPlaylistType:()=>ss,HLSStreamType:()=>as,HMSAudioDeviceCategory:()=>Ri,HMSAudioMode:()=>Ai,HMSAudioPluginType:()=>ki,HMSLogLevel:()=>qr,HMSMessageType:()=>ra,HMSNotificationSeverity:()=>$r,HMSNotificationTypes:()=>fi,HMSPeerType:()=>Ii,HMSPlaylistType:()=>Kr,HMSPluginUnsupportedTypes:()=>Ei,HMSReactiveStore:()=>et,HMSRecordingState:()=>rs,HMSRoomState:()=>Ti,HMSStats:()=>yt,HMSTrackExceptionTrackType:()=>zr,HMSTranscriptionMode:()=>ns,HMSTranscriptionState:()=>os,HMSVideoPluginCanvasContextType:()=>Ni,HMSVideoPluginType:()=>_i,createDefaultStatsStore:()=>It,createDefaultStoreState:()=>bt,getAudioDeviceCategory:()=>Hi,parsedUserAgent:()=>he,selectAppData:()=>Dc,selectAppDataByPath:()=>_c,selectAudioPlaylist:()=>Cs,selectAudioPlaylistTrackByPeerID:()=>Jc,selectAudioTrackByID:()=>xc,selectAudioTrackByPeerID:()=>To,selectAudioTrackVolume:()=>Us,selectAudioVolumeByPeerID:()=>td,selectAuxiliaryAudioByPeerID:()=>qc,selectAuxiliaryTracksByPeerID:()=>Fc,selectAvailableRoleNames:()=>cc,selectBroadcastMessages:()=>yo,selectBroadcastMessagesUnreadCount:()=>od,selectCameraStreamByPeerID:()=>Vc,selectConnectionQualities:()=>Fn,selectConnectionQualityByPeerID:()=>Kc,selectDegradedTracks:()=>ic,selectDevices:()=>Vn,selectDidIJoinWithin:()=>Cd,selectDominantSpeaker:()=>Jn,selectEffectsKey:()=>vc,selectErrors:()=>to,selectFullAppData:()=>Ki,selectHLSState:()=>pc,selectHMSBroadcastMessages:()=>so,selectHMSMessages:()=>ht,selectHMSMessagesCount:()=>rc,selectHMSStats:()=>sn,selectHandRaisedPeers:()=>Ec,selectHasPeerHandRaised:()=>md,selectIsAllowedToPreviewMedia:()=>kd,selectIsAllowedToPublish:()=>yd,selectIsAllowedToSubscribe:()=>dc,selectIsAudioLocallyMuted:()=>xs,selectIsConnectedToRoom:()=>He,selectIsEffectsEnabled:()=>Tc,selectIsInPreview:()=>Ps,selectIsLargeRoom:()=>gc,selectIsLocalAudioEnabled:()=>zn,selectIsLocalAudioPluginPresent:()=>Ad,selectIsLocalScreenShared:()=>ji,selectIsLocalVideoDisplayEnabled:()=>Es,selectIsLocalVideoEnabled:()=>qi,selectIsLocalVideoPluginPresent:()=>Id,selectIsLocallyMutedByPeerID:()=>Zc,selectIsPeerAudioEnabled:()=>Yc,selectIsPeerVideoEnabled:()=>Xc,selectIsRoleAllowedToPublish:()=>Ed,selectIsScreenShareLocallyMutedByPeerID:()=>ed,selectIsSomeoneScreenSharing:()=>Yn,selectIsTranscriptionAllowedByMode:()=>Td,selectIsTranscriptionEnabled:()=>nc,selectIsVBEnabled:()=>fc,selectLocalAudioTrackID:()=>de,selectLocalMediaSettings:()=>ys,selectLocalPeer:()=>se,selectLocalPeerID:()=>be,selectLocalPeerName:()=>Kn,selectLocalPeerRole:()=>ze,selectLocalPeerRoleName:()=>qn,selectLocalTrackIDs:()=>ks,selectLocalVideoTrackID:()=>ee,selectMessageByMessageID:()=>gd,selectMessageIDsInOrder:()=>Ms,selectMessagesByPeerID:()=>nd,selectMessagesByRole:()=>cd,selectMessagesMap:()=>$t,selectMessagesUnreadCountByPeerID:()=>ld,selectMessagesUnreadCountByRole:()=>dd,selectPeerAudioByID:()=>$c,selectPeerByCondition:()=>Rd,selectPeerByID:()=>ie,selectPeerCount:()=>Gn,selectPeerMetadata:()=>hd,selectPeerName:()=>Sd,selectPeerNameByID:()=>Nc,selectPeerScreenSharing:()=>ro,selectPeerSharingAudio:()=>Xn,selectPeerSharingAudioPlaylist:()=>tc,selectPeerSharingVideoPlaylist:()=>ec,selectPeerTypeByID:()=>Oc,selectPeers:()=>ve,selectPeersByCondition:()=>Hd,selectPeersByRole:()=>ud,selectPeersByRoles:()=>pd,selectPeersMap:()=>z,selectPeersScreenSharing:()=>Zn,selectPeersWithAudioStatus:()=>fd,selectPermissions:()=>Is,selectPollByID:()=>Bs,selectPolls:()=>kc,selectPollsMap:()=>As,selectPreviewRole:()=>bs,selectPreviewRoleName:()=>ao,selectRTMPState:()=>uc,selectRecentError:()=>Un,selectRecordingState:()=>lc,selectRemotePeers:()=>Qn,selectRoleByRoleName:()=>ko,selectRoleChangeRequest:()=>Md,selectRolesMap:()=>Me,selectRoom:()=>F,selectRoomID:()=>Bn,selectRoomStartTime:()=>Sc,selectRoomStarted:()=>oc,selectRoomState:()=>ae,selectScreenAudioTrackByID:()=>Uc,selectScreenShareAudioByPeerID:()=>Os,selectScreenShareByPeerID:()=>zc,selectScreenSharesByPeerId:()=>Ns,selectScreenVideoTrackByID:()=>Bc,selectScreenshareAudioVolumeByPeerID:()=>id,selectSessionId:()=>mc,selectSessionMetadata:()=>yc,selectSessionStore:()=>wc,selectSimulcastLayerByTrack:()=>rd,selectSpeakers:()=>io,selectTemplateAppData:()=>Mc,selectTrackAudioByID:()=>Gc,selectTrackByID:()=>jt,selectTracksMap:()=>_,selectTranscriptionsState:()=>hc,selectUnreadHMSBroadcastMessagesCount:()=>ac,selectUnreadHMSMessagesCount:()=>sc,selectVideoPlaylist:()=>Ls,selectVideoPlaylistAudioTrackByPeerID:()=>Qc,selectVideoPlaylistVideoTrackByPeerID:()=>jc,selectVideoTrackByID:()=>_s,selectVideoTrackByPeerID:()=>go,selectWhiteboard:()=>Pc,selectWhiteboards:()=>oo,simulcastMapping:()=>Ue});module.exports=hn(pl);var Ti=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Ti||{});var bt=()=>({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}),It=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var ra=(e=>(e.CHAT="chat",e))(ra||{});var $r=(t=>(t.INFO="info",t.ERROR="error",t))($r||{}),fi=(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))(fi||{});var Kr=(t=>(t.audio="audio",t.video="video",t))(Kr||{});var I=require("reselect");function Ke(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];mn(s)&&(i=At(s)?s:i,t=Rt(s)?s:t)}return{video:t,audio:i}}function At(a){return a&&a.type==="audio"}function Rt(a){return a&&a.type==="video"}function mn(a){return a&&a.source==="screen"}function vi(a){return a&&a.source==="audioplaylist"}function Ht(a){return a&&a.source==="videoplaylist"}function sa(a){return a?!!(a!=null&&a.degraded):!1}function tt(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function aa(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function Ct(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 qr=(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))(qr||{}),Sn=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=Sn?7:0;var it=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var ha=require("ua-parser-js");var jr=new ha.UAParser,Lt=null,Qr=null,B=typeof window!="undefined";if(B)try{let a=jr.getResult(),e=a.withClientHints();e&&typeof e.then=="function"?(Qr=e,Qr.then(t=>{Lt=t}).catch(()=>{Lt=a})):(l.d("UAParser","Client Hints not supported, using standard UA parsing"),Lt=e)}catch(a){Lt=jr.getResult()}var _e=()=>Lt||jr.getResult(),he={getBrowser:()=>_e().browser,getOS:()=>_e().os,getDevice:()=>_e().device,getCPU:()=>_e().cpu,getEngine:()=>_e().engine,getUA:()=>_e().ua,getResult:_e,withClientHints:()=>Qr||Promise.resolve(_e())},oa,qe=typeof window=="undefined"&&!((oa=he.getBrowser().name)!=null&&oa.toLowerCase().includes("electron"));var gn=()=>!qe,El=gn(),Dt=()=>he.getDevice().type==="mobile",ma=()=>typeof document!="undefined"&&document.hidden,Sa=()=>{var a;return((a=he.getOS().name)==null?void 0:a.toLowerCase())==="ios"},na,ca,ga=(ca=(na=he.getBrowser())==null?void 0:na.name)==null?void 0:ca.toLowerCase().includes("safari"),da,la,Ta=((la=(da=he.getBrowser())==null?void 0:da.name)==null?void 0:la.toLowerCase())==="firefox",ua,pa,fa=((pa=(ua=he.getEngine())==null?void 0:ua.name)==null?void 0:pa.toLowerCase())==="blink";var ba=require("uuid");var Jr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Jr||{});function Tn(){if(B&&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 rt=Tn();var Ma=require("uuid");var k={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 E=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
+ "use strict";var an=Object.create;var Pt=Object.defineProperty,on=Object.defineProperties,nn=Object.getOwnPropertyDescriptor,cn=Object.getOwnPropertyDescriptors,dn=Object.getOwnPropertyNames,gi=Object.getOwnPropertySymbols,ea=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty,ta=Object.prototype.propertyIsEnumerable,ln=Reflect.get;var Zs=(a,e,t)=>e in a?Pt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))Gr.call(e,t)&&Zs(a,t,e[t]);if(gi)for(var t of gi(e))ta.call(e,t)&&Zs(a,t,e[t]);return a},M=(a,e)=>on(a,cn(e));var Wr=(a,e)=>{var t={};for(var i in a)Gr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&gi)for(var i of gi(a))e.indexOf(i)<0&&ta.call(a,i)&&(t[i]=a[i]);return t};var un=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),pn=(a,e)=>{for(var t in e)Pt(a,t,{get:e[t],enumerable:!0})},ia=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of dn(e))!Gr.call(a,r)&&r!==t&&Pt(a,r,{get:()=>e[r],enumerable:!(i=nn(e,r))||i.enumerable});return a};var $e=(a,e,t)=>(t=a!=null?an(ea(a)):{},ia(e||!a||!a.__esModule?Pt(t,"default",{value:a,enumerable:!0}):t,a)),hn=a=>ia(Pt({},"__esModule",{value:!0}),a);var pe=(a,e,t)=>ln(ea(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 Zr=un((Zl,vn)=>{vn.exports={version:"0.13.3-alpha.8",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"],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":"^2.0.6",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.39","@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:"ce778f84bd26fe6c451dbdde03ecffc1f3c83998"}});var pl={};pn(pl,{ConnectivityState:()=>wo,DeviceType:()=>cs,Diagnostics:()=>St,DomainCategory:()=>Jr,EventBus:()=>gt,HLSPlaylistType:()=>ss,HLSStreamType:()=>as,HMSAudioDeviceCategory:()=>Ri,HMSAudioMode:()=>Ai,HMSAudioPluginType:()=>ki,HMSLogLevel:()=>qr,HMSMessageType:()=>ra,HMSNotificationSeverity:()=>$r,HMSNotificationTypes:()=>fi,HMSPeerType:()=>Ii,HMSPlaylistType:()=>Kr,HMSPluginUnsupportedTypes:()=>Ei,HMSReactiveStore:()=>et,HMSRecordingState:()=>rs,HMSRoomState:()=>Ti,HMSStats:()=>yt,HMSTrackExceptionTrackType:()=>zr,HMSTranscriptionMode:()=>ns,HMSTranscriptionState:()=>os,HMSVideoPluginCanvasContextType:()=>Ni,HMSVideoPluginType:()=>_i,createDefaultStatsStore:()=>It,createDefaultStoreState:()=>bt,getAudioDeviceCategory:()=>Hi,parsedUserAgent:()=>he,selectAppData:()=>Dc,selectAppDataByPath:()=>_c,selectAudioPlaylist:()=>Cs,selectAudioPlaylistTrackByPeerID:()=>Jc,selectAudioTrackByID:()=>xc,selectAudioTrackByPeerID:()=>To,selectAudioTrackVolume:()=>Us,selectAudioVolumeByPeerID:()=>td,selectAuxiliaryAudioByPeerID:()=>qc,selectAuxiliaryTracksByPeerID:()=>Fc,selectAvailableRoleNames:()=>cc,selectBroadcastMessages:()=>yo,selectBroadcastMessagesUnreadCount:()=>od,selectCameraStreamByPeerID:()=>Vc,selectConnectionQualities:()=>Fn,selectConnectionQualityByPeerID:()=>Kc,selectDegradedTracks:()=>ic,selectDevices:()=>Vn,selectDidIJoinWithin:()=>Cd,selectDominantSpeaker:()=>Jn,selectEffectsKey:()=>vc,selectErrors:()=>to,selectFullAppData:()=>Ki,selectHLSState:()=>pc,selectHMSBroadcastMessages:()=>so,selectHMSMessages:()=>ht,selectHMSMessagesCount:()=>rc,selectHMSStats:()=>sn,selectHandRaisedPeers:()=>Ec,selectHasPeerHandRaised:()=>md,selectIsAllowedToPreviewMedia:()=>kd,selectIsAllowedToPublish:()=>yd,selectIsAllowedToSubscribe:()=>dc,selectIsAudioLocallyMuted:()=>xs,selectIsConnectedToRoom:()=>He,selectIsEffectsEnabled:()=>Tc,selectIsInPreview:()=>Ps,selectIsLargeRoom:()=>gc,selectIsLocalAudioEnabled:()=>zn,selectIsLocalAudioPluginPresent:()=>Ad,selectIsLocalScreenShared:()=>ji,selectIsLocalVideoDisplayEnabled:()=>Es,selectIsLocalVideoEnabled:()=>qi,selectIsLocalVideoPluginPresent:()=>Id,selectIsLocallyMutedByPeerID:()=>Zc,selectIsPeerAudioEnabled:()=>Yc,selectIsPeerVideoEnabled:()=>Xc,selectIsRoleAllowedToPublish:()=>Ed,selectIsScreenShareLocallyMutedByPeerID:()=>ed,selectIsSomeoneScreenSharing:()=>Yn,selectIsTranscriptionAllowedByMode:()=>Td,selectIsTranscriptionEnabled:()=>nc,selectIsVBEnabled:()=>fc,selectLocalAudioTrackID:()=>de,selectLocalMediaSettings:()=>ys,selectLocalPeer:()=>se,selectLocalPeerID:()=>be,selectLocalPeerName:()=>Kn,selectLocalPeerRole:()=>ze,selectLocalPeerRoleName:()=>qn,selectLocalTrackIDs:()=>ks,selectLocalVideoTrackID:()=>ee,selectMessageByMessageID:()=>gd,selectMessageIDsInOrder:()=>Ms,selectMessagesByPeerID:()=>nd,selectMessagesByRole:()=>cd,selectMessagesMap:()=>$t,selectMessagesUnreadCountByPeerID:()=>ld,selectMessagesUnreadCountByRole:()=>dd,selectPeerAudioByID:()=>$c,selectPeerByCondition:()=>Rd,selectPeerByID:()=>ie,selectPeerCount:()=>Gn,selectPeerMetadata:()=>hd,selectPeerName:()=>Sd,selectPeerNameByID:()=>Nc,selectPeerScreenSharing:()=>ro,selectPeerSharingAudio:()=>Xn,selectPeerSharingAudioPlaylist:()=>tc,selectPeerSharingVideoPlaylist:()=>ec,selectPeerTypeByID:()=>Oc,selectPeers:()=>ve,selectPeersByCondition:()=>Hd,selectPeersByRole:()=>ud,selectPeersByRoles:()=>pd,selectPeersMap:()=>z,selectPeersScreenSharing:()=>Zn,selectPeersWithAudioStatus:()=>fd,selectPermissions:()=>Is,selectPollByID:()=>Bs,selectPolls:()=>kc,selectPollsMap:()=>As,selectPreviewRole:()=>bs,selectPreviewRoleName:()=>ao,selectRTMPState:()=>uc,selectRecentError:()=>Un,selectRecordingState:()=>lc,selectRemotePeers:()=>Qn,selectRoleByRoleName:()=>ko,selectRoleChangeRequest:()=>Md,selectRolesMap:()=>Me,selectRoom:()=>F,selectRoomID:()=>Bn,selectRoomStartTime:()=>Sc,selectRoomStarted:()=>oc,selectRoomState:()=>ae,selectScreenAudioTrackByID:()=>Uc,selectScreenShareAudioByPeerID:()=>Os,selectScreenShareByPeerID:()=>zc,selectScreenSharesByPeerId:()=>Ns,selectScreenVideoTrackByID:()=>Bc,selectScreenshareAudioVolumeByPeerID:()=>id,selectSessionId:()=>mc,selectSessionMetadata:()=>yc,selectSessionStore:()=>wc,selectSimulcastLayerByTrack:()=>rd,selectSpeakers:()=>io,selectTemplateAppData:()=>Mc,selectTrackAudioByID:()=>Gc,selectTrackByID:()=>jt,selectTracksMap:()=>_,selectTranscriptionsState:()=>hc,selectUnreadHMSBroadcastMessagesCount:()=>ac,selectUnreadHMSMessagesCount:()=>sc,selectVideoPlaylist:()=>Ls,selectVideoPlaylistAudioTrackByPeerID:()=>Qc,selectVideoPlaylistVideoTrackByPeerID:()=>jc,selectVideoTrackByID:()=>_s,selectVideoTrackByPeerID:()=>go,selectWhiteboard:()=>Pc,selectWhiteboards:()=>oo,simulcastMapping:()=>Ue});module.exports=hn(pl);var Ti=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Ti||{});var bt=()=>({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}),It=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var ra=(e=>(e.CHAT="chat",e))(ra||{});var $r=(t=>(t.INFO="info",t.ERROR="error",t))($r||{}),fi=(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))(fi||{});var Kr=(t=>(t.audio="audio",t.video="video",t))(Kr||{});var I=require("reselect");function Ke(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];mn(s)&&(i=At(s)?s:i,t=Rt(s)?s:t)}return{video:t,audio:i}}function At(a){return a&&a.type==="audio"}function Rt(a){return a&&a.type==="video"}function mn(a){return a&&a.source==="screen"}function vi(a){return a&&a.source==="audioplaylist"}function Ht(a){return a&&a.source==="videoplaylist"}function sa(a){return a?!!(a!=null&&a.degraded):!1}function tt(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function aa(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function Ct(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 qr=(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))(qr||{}),Sn=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=Sn?7:0;var it=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var ha=require("ua-parser-js");var jr=new ha.UAParser,Lt=null,Qr=null,B=typeof window!="undefined";if(B)try{let a=jr.getResult(),e=a.withClientHints();e&&typeof e.then=="function"?(Qr=e,Qr.then(t=>{Lt=t}).catch(()=>{Lt=a})):(l.d("UAParser","Client Hints not supported, using standard UA parsing"),Lt=e)}catch(a){Lt=jr.getResult()}var _e=()=>Lt||jr.getResult(),he={getBrowser:()=>_e().browser,getOS:()=>_e().os,getDevice:()=>_e().device,getCPU:()=>_e().cpu,getEngine:()=>_e().engine,getUA:()=>_e().ua,getResult:_e,withClientHints:()=>Qr||Promise.resolve(_e())},oa,qe=typeof window=="undefined"&&!((oa=he.getBrowser().name)!=null&&oa.toLowerCase().includes("electron"));var gn=()=>!qe,El=gn(),Dt=()=>he.getDevice().type==="mobile",ma=()=>typeof document!="undefined"&&document.hidden,Sa=()=>{var a;return((a=he.getOS().name)==null?void 0:a.toLowerCase())==="ios"},na,ca,ga=(ca=(na=he.getBrowser())==null?void 0:na.name)==null?void 0:ca.toLowerCase().includes("safari"),da,la,Ta=((la=(da=he.getBrowser())==null?void 0:da.name)==null?void 0:la.toLowerCase())==="firefox",ua,pa,fa=((pa=(ua=he.getEngine())==null?void 0:ua.name)==null?void 0:pa.toLowerCase())==="blink";var ba=require("uuid");var Jr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Jr||{});function Tn(){if(B&&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 rt=Tn();var Ma=require("uuid");var k={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 E=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 @@
44
44
  break;
45
45
  }
46
46
  };
47
- })()`;function Z(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function Fe(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return Z(a);let e=new Worker(URL.createObjectURL(new Blob([Ra],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function Ha(){if(typeof Worker=="undefined")return{sleep:e=>Z(e)};let a=new Worker(URL.createObjectURL(new Blob([Ra],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function Di(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var Pn=35,bn=5,wi=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 Ve(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 Z(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 Z(this.interval)})}sendAudioLevel(e=0){if(e=e>Pn?e:0,Math.abs(this.audioLevel-e)>bn){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=me.getAudioContext(),i=t.createMediaStreamSource(e),r=t.createAnalyser();return r.fftSize=2048,i.connect(r),r}};function Ca(a,e){return function(i){return!(0,La.default)(a[i],e[i])}}var Se=class a extends Oe{constructor(t,i,r,s,o=new X().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{if(this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"})),this.permissionState&&this.permissionState!=="granted"){l.d(this.TAG,"On visibile not replacing track as permission is not granted");return}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.trackPermissions=()=>{Li("microphone",t=>{this.permissionState=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"),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"track-muted-natively"})),this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmute=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively"),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"track-unmuted-natively"}));try{yield this.setEnabled(this.enabled,!0),this.eventBus.localAudioUnmutedNatively.publish()}catch(t){this.eventBus.error.publish(t)}});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=()=>Ee(this.nativeTrack)||this.isTrackNotPublishing();this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Ca(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(Ca(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&&(re.updateSelection("audioInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"audioInput",selection:{deviceId:t.deviceId,groupId:s,label:this.nativeTrack.label}}))}});t.tracks.push(this),this.addTrackEventListeners(i),this.trackPermissions(),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!Ee(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Ot(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 us(t);this.addTrackEventListeners(r),this.tracksCreated.add(r),this.eventBus.analytics.publish(y.mediaConstraints({requestedConstraints:{audio:t.toConstraints()},appliedConstraints:{audio:r.getConstraints()},trackSettings:{audio:r.getSettings()}})),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),yield this.updateTrack(r)}catch(r){let s=r;if(s.code===k.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE||s.code===k.TracksErrors.SYSTEM_DENIED_PERMISSION){let n=yield Te.getEmptyAudioTrack();throw this.addTrackEventListeners(n),this.tracksCreated.add(n),yield this.updateTrack(n),s}let o=yield us(this.settings);throw this.addTrackEventListeners(o),this.tracksCreated.add(o),this.eventBus.analytics.publish(y.mediaConstraints({requestedConstraints:{audio:this.settings.toConstraints()},appliedConstraints:{audio:o.getConstraints()},trackSettings:{audio:o.getSettings()}})),yield this.updateTrack(o),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 pe(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(Ee(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 wi(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;pe(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 je(i,r,s,o,n,d)}};var ce=class a extends Oe{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield pe(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var at=class extends Ne{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){ga||(t.autoplay=!0),t.playsInline=!0,t.muted=!0,t.controls=!1}};var Ua=$e(require("lodash.isequal"));var Na=require("uuid");var xt={none:-1,low:0,medium:1,high:2},In=.5,Da=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>xt[o.layer]-xt[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)<In){t=d;break}}}return t};var hs=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=B&&typeof window.IntersectionObserver!="undefined";return e||l.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},wa=new hs;var ms=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(Di(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=B&&typeof window.ResizeObserver!="undefined";return e||l.w(this.TAG,"Resize Observer is not supported"),e}},_a=new ms;var ot=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 x)||(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=(0,Na.v4)()}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):B&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof x&&(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(){B&&(this.resizeObserver=_a,this.intersectionObserver=wa)}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 x)||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=Da(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=xt[o]>xt[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 _i=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(_i||{}),Ni=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(Ni||{});var Ut=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 nt=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new Ut,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 Ut,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(ge.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(ge.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ge.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 Oa=24,An=320,Rn=240,Bt=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=Ha();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new nt(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||Oa,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 Fe(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||Oa,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=An,height:t=Rn}=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 Oi=class{constructor(e,t){this.TAG="[MediaStreamPluginsManager]";this.plugins=new Set,this.analytics=new nt(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))})}};function xa(a,e){return function(i){return!(0,Ua.default)(a[i],e[i])}}var K=class a extends at{constructor(t,i,r,s,o=new J().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 Qe(i,r,s,o,d,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=xa(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(xa(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&&(re.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s,label:this.nativeTrack.label}}))}});this.trackPermissions=()=>{Li("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),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"track-muted-natively"})),this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmuteNatively=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively"),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"track-unmuted-natively"})),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(this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"})),this.permissionState&&this.permissionState!=="granted"){l.d(this.TAG,"On visibile not replacing track as permission is not granted");return}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.trackPermissions(),t.tracks.push(this),this.setVideoHandler(new ot(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Bt(this,s),this.mediaStreamPluginsManager=new Oi(s,n),this.setFirstTrackId(this.trackId),this.eventBus.localAudioUnmutedNatively.subscribe(this.handleTrackUnmute),B&&r==="regular"&&Dt()&&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 pe(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||Ee(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()}getPluginsMetrics(){let t={};for(let i of this.mediaStreamPluginsManager.plugins)i.getMetrics&&(t[i.getName()]=i.getMetrics());return t}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(),pe(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,B&&Dt()&&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}),re.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 ps(t);return this.eventBus.analytics.publish(y.mediaConstraints({requestedConstraints:{video:t.toConstraints()},appliedConstraints:{video:r.getConstraints()},trackSettings:{video:r.getSettings()}})),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=r;if(s.code===k.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE||s.code===k.TracksErrors.SYSTEM_DENIED_PERMISSION){let n=yield this.replaceTrackWithBlank();throw this.addTrackEventListeners(n),yield this.replaceSender(n,this.enabled),this.nativeTrack=n,this.videoHandler.updateSinks(),s}let o=yield ps(this.settings);throw this.eventBus.analytics.publish(y.mediaConstraints({requestedConstraints:{video:this.settings.toConstraints()},appliedConstraints:{video:o.getConstraints()},trackSettings:{video:o.getSettings()}})),yield this.replaceSender(o,this.enabled),this.nativeTrack=o,yield this.processPlugins(),this.videoHandler.updateSinks(),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:s})),s}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=Te.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 ct="renegotiation-callback-id",xi="ion-sfu";var dt="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var Ba="https://event.100ms.live/v2/client/report",Va="https://event-nonprod.100ms.live/v2/client/report";var Vt=Math.pow(2,31)-1,G={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"},Fa="2.5",Ga="20250115",Re="_handraise",Ss=1e3,gs=64,Wa="https://whiteboard.100ms.live",$a="https://whiteboard-qa.100ms.live";var x=class a extends at{constructor(t,i,r,s){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new Ts;this.preferredLayer="high";this.disableNoneLayerRequest=!1;this.disableNoneLayerRequest=!!s,this.setVideoHandler(new ot(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&&(pe(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 Z(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function Fe(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return Z(a);let e=new Worker(URL.createObjectURL(new Blob([Ra],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function Ha(){if(typeof Worker=="undefined")return{sleep:e=>Z(e)};let a=new Worker(URL.createObjectURL(new Blob([Ra],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function Di(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var Pn=35,bn=5,wi=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 Ve(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 Z(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 Z(this.interval)})}sendAudioLevel(e=0){if(e=e>Pn?e:0,Math.abs(this.audioLevel-e)>bn){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=me.getAudioContext(),i=t.createMediaStreamSource(e),r=t.createAnalyser();return r.fftSize=2048,i.connect(r),r}};function Ca(a,e){return function(i){return!(0,La.default)(a[i],e[i])}}var Se=class a extends Oe{constructor(t,i,r,s,o=new X().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{if(this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"})),this.permissionState&&this.permissionState!=="granted"){l.d(this.TAG,"On visibile not replacing track as permission is not granted");return}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.trackPermissions=()=>{Li("microphone",t=>{this.permissionState=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"),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"track-muted-natively"})),this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmute=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively"),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"track-unmuted-natively"}));try{yield this.setEnabled(this.enabled,!0),this.eventBus.localAudioUnmutedNatively.publish()}catch(t){this.eventBus.error.publish(t)}});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=()=>Ee(this.nativeTrack)||this.isTrackNotPublishing();this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Ca(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(Ca(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&&(re.updateSelection("audioInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"audioInput",selection:{deviceId:t.deviceId,groupId:s,label:this.nativeTrack.label}}))}});t.tracks.push(this),this.addTrackEventListeners(i),this.trackPermissions(),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!Ee(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Ot(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 us(t);this.addTrackEventListeners(r),this.tracksCreated.add(r),this.eventBus.analytics.publish(y.mediaConstraints({requestedConstraints:{audio:t.toConstraints()},appliedConstraints:{audio:r.getConstraints()},trackSettings:{audio:r.getSettings()}})),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),yield this.updateTrack(r)}catch(r){let s=r;if(s.code===k.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE||s.code===k.TracksErrors.SYSTEM_DENIED_PERMISSION){let n=yield Te.getEmptyAudioTrack();throw this.addTrackEventListeners(n),this.tracksCreated.add(n),yield this.updateTrack(n),s}let o=yield us(this.settings);throw this.addTrackEventListeners(o),this.tracksCreated.add(o),this.eventBus.analytics.publish(y.mediaConstraints({requestedConstraints:{audio:this.settings.toConstraints()},appliedConstraints:{audio:o.getConstraints()},trackSettings:{audio:o.getSettings()}})),yield this.updateTrack(o),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 pe(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(Ee(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 wi(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;pe(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 je(i,r,s,o,n,d)}};var ce=class a extends Oe{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield pe(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var at=class extends Ne{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){ga||(t.autoplay=!0),t.playsInline=!0,t.muted=!0,t.controls=!1}};var Ua=$e(require("lodash.isequal"));var Na=require("uuid");var xt={none:-1,low:0,medium:1,high:2},In=.5,Da=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>xt[o.layer]-xt[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)<In){t=d;break}}}return t};var hs=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=B&&typeof window.IntersectionObserver!="undefined";return e||l.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},wa=new hs;var ms=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(Di(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=B&&typeof window.ResizeObserver!="undefined";return e||l.w(this.TAG,"Resize Observer is not supported"),e}},_a=new ms;var ot=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 x)||(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=(0,Na.v4)()}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):B&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof x&&(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(){B&&(this.resizeObserver=_a,this.intersectionObserver=wa)}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 x)||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=Da(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=xt[o]>xt[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 _i=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(_i||{}),Ni=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(Ni||{});var Ut=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 nt=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new Ut,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 Ut,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(ge.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(ge.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ge.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 Oa=24,An=320,Rn=240,Bt=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=Ha();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new nt(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||Oa,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 Fe(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||Oa,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=An,height:t=Rn}=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 Oi=class{constructor(e,t){this.TAG="[MediaStreamPluginsManager]";this.plugins=new Set,this.analytics=new nt(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))})}};function xa(a,e){return function(i){return!(0,Ua.default)(a[i],e[i])}}var K=class a extends at{constructor(t,i,r,s,o=new J().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 Qe(i,r,s,o,d,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=xa(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(xa(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&&(re.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s,label:this.nativeTrack.label}}))}});this.trackPermissions=()=>{Li("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),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"track-muted-natively"})),this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmuteNatively=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively"),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"track-unmuted-natively"})),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(this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"})),this.permissionState&&this.permissionState!=="granted"){l.d(this.TAG,"On visibile not replacing track as permission is not granted");return}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.trackPermissions(),t.tracks.push(this),this.setVideoHandler(new ot(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Bt(this,s),this.mediaStreamPluginsManager=new Oi(s,n),this.setFirstTrackId(this.trackId),this.eventBus.localAudioUnmutedNatively.subscribe(this.handleTrackUnmute),B&&r==="regular"&&Dt()&&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 pe(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||Ee(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()}getPluginsMetrics(){let t={};for(let i of this.mediaStreamPluginsManager.plugins)i.getMetrics&&(t[i.getName()]=i.getMetrics());return t}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(),pe(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,B&&Dt()&&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}),re.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 ps(t);return this.eventBus.analytics.publish(y.mediaConstraints({requestedConstraints:{video:t.toConstraints()},appliedConstraints:{video:r.getConstraints()},trackSettings:{video:r.getSettings()}})),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=r;if(s.code===k.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE||s.code===k.TracksErrors.SYSTEM_DENIED_PERMISSION){let n=yield this.replaceTrackWithBlank();throw yield this.replaceSender(n,this.enabled),this.nativeTrack=n,this.videoHandler.updateSinks(),s}let o=yield ps(this.settings);throw this.eventBus.analytics.publish(y.mediaConstraints({requestedConstraints:{video:this.settings.toConstraints()},appliedConstraints:{video:o.getConstraints()},trackSettings:{video:o.getSettings()}})),yield this.replaceSender(o,this.enabled),this.nativeTrack=o,yield this.processPlugins(),this.videoHandler.updateSinks(),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:s})),s}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=Te.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 ct="renegotiation-callback-id",xi="ion-sfu";var dt="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var Ba="https://event.100ms.live/v2/client/report",Va="https://event-nonprod.100ms.live/v2/client/report";var Vt=Math.pow(2,31)-1,G={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"},Fa="2.5",Ga="20250115",Re="_handraise",Ss=1e3,gs=64,Wa="https://whiteboard.100ms.live",$a="https://whiteboard-qa.100ms.live";var x=class a extends at{constructor(t,i,r,s){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new Ts;this.preferredLayer="high";this.disableNoneLayerRequest=!1;this.disableNoneLayerRequest=!!s,this.setVideoHandler(new ot(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&&(pe(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}