@100mslive/hms-video-store 0.12.36-alpha.0 → 0.12.36
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 +3 -3
- package/dist/index.cjs.js.map +3 -3
- package/dist/index.js +3 -3
- package/dist/index.js.map +3 -3
- package/package.json +2 -2
- package/src/media/tracks/HMSLocalVideoTrack.ts +7 -9
- package/src/utils/track.ts +10 -2
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var $o=Object.create;var yt=Object.defineProperty,Ko=Object.defineProperties,qo=Object.getOwnPropertyDescriptor,jo=Object.getOwnPropertyDescriptors,Jo=Object.getOwnPropertyNames,pi=Object.getOwnPropertySymbols,Js=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty,Qs=Object.prototype.propertyIsEnumerable,Qo=Reflect.get;var js=(a,e,t)=>e in a?yt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))xr.call(e,t)&&js(a,t,e[t]);if(pi)for(var t of pi(e))Qs.call(e,t)&&js(a,t,e[t]);return a},M=(a,e)=>Ko(a,jo(e));var Ur=(a,e)=>{var t={};for(var i in a)xr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&pi)for(var i of pi(a))e.indexOf(i)<0&&Qs.call(a,i)&&(t[i]=a[i]);return t};var zo=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Yo=(a,e)=>{for(var t in e)yt(a,t,{get:e[t],enumerable:!0})},zs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jo(e))!xr.call(a,r)&&r!==t&&yt(a,r,{get:()=>e[r],enumerable:!(i=qo(e,r))||i.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?$o(Js(a)):{},zs(e||!a||!a.__esModule?yt(t,"default",{value:a,enumerable:!0}):t,a)),Xo=a=>zs(yt({},"__esModule",{value:!0}),a);var ce=(a,e,t)=>Qo(Js(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 qr=zo((Ll,an)=>{an.exports={version:"0.12.36-alpha.0",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist","src"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^1.0.1",uuid:"^8.3.2","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/lodash.isequal":"^4.5.8","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.36","@types/uuid":"^8.3.0","jest-canvas-mock":"^2.3.1","jsdom-worker":"^0.3.0",tslib:"^2.2.0"},description:"@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow",keywords:["video","webrtc","conferencing","100ms"],gitHead:"85a1503c44806a779fe0c0bc54258b0065ec476c"}});var Kd={};Yo(Kd,{ConnectivityState:()=>vo,DeviceType:()=>rs,Diagnostics:()=>ht,DomainCategory:()=>Gr,EventBus:()=>mt,HLSPlaylistType:()=>Zr,HLSStreamType:()=>es,HMSAudioDeviceCategory:()=>Ei,HMSAudioMode:()=>Ri,HMSAudioPluginType:()=>vi,HMSLogLevel:()=>Fr,HMSMessageType:()=>Ys,HMSNotificationSeverity:()=>Br,HMSNotificationTypes:()=>mi,HMSPeerType:()=>Ii,HMSPlaylistType:()=>Vr,HMSPluginUnsupportedTypes:()=>Mi,HMSReactiveStore:()=>Xe,HMSRecordingState:()=>Xr,HMSRoomState:()=>hi,HMSStats:()=>vt,HMSTrackExceptionTrackType:()=>Wr,HMSTranscriptionMode:()=>is,HMSTranscriptionState:()=>ts,HMSVideoPluginCanvasContextType:()=>Ci,HMSVideoPluginType:()=>Hi,createDefaultStatsStore:()=>Et,createDefaultStoreState:()=>kt,getAudioDeviceCategory:()=>Pi,parsedUserAgent:()=>he,selectAppData:()=>uc,selectAppDataByPath:()=>hc,selectAudioPlaylist:()=>Ps,selectAudioPlaylistTrackByPeerID:()=>Rc,selectAudioTrackByID:()=>gc,selectAudioTrackByPeerID:()=>io,selectAudioTrackVolume:()=>Ds,selectAudioVolumeByPeerID:()=>_c,selectAuxiliaryAudioByPeerID:()=>bc,selectAuxiliaryTracksByPeerID:()=>Mc,selectAvailableRoleNames:()=>Fn,selectBroadcastMessages:()=>oo,selectBroadcastMessagesUnreadCount:()=>Bc,selectCameraStreamByPeerID:()=>vc,selectConnectionQualities:()=>Mn,selectConnectionQualityByPeerID:()=>Pc,selectDegradedTracks:()=>Nn,selectDevices:()=>vn,selectDidIJoinWithin:()=>dd,selectDominantSpeaker:()=>Rn,selectEffectsKey:()=>Xn,selectErrors:()=>Fa,selectFullAppData:()=>Fi,selectHLSState:()=>Kn,selectHMSBroadcastMessages:()=>$a,selectHMSMessages:()=>ut,selectHMSMessagesCount:()=>On,selectHMSStats:()=>Wo,selectHandRaisedPeers:()=>ic,selectHasPeerHandRaised:()=>jc,selectIsAllowedToPreviewMedia:()=>td,selectIsAllowedToPublish:()=>ed,selectIsAllowedToSubscribe:()=>Gn,selectIsAudioLocallyMuted:()=>Ls,selectIsConnectedToRoom:()=>He,selectIsEffectsEnabled:()=>zn,selectIsInPreview:()=>fs,selectIsLargeRoom:()=>Qn,selectIsLocalAudioEnabled:()=>Hn,selectIsLocalAudioPluginPresent:()=>od,selectIsLocalScreenShared:()=>Wi,selectIsLocalVideoDisplayEnabled:()=>Ts,selectIsLocalVideoEnabled:()=>Gi,selectIsLocalVideoPluginPresent:()=>ad,selectIsLocallyMutedByPeerID:()=>Dc,selectIsPeerAudioEnabled:()=>Cc,selectIsPeerVideoEnabled:()=>Lc,selectIsRoleAllowedToPublish:()=>id,selectIsScreenShareLocallyMutedByPeerID:()=>wc,selectIsSomeoneScreenSharing:()=>Cn,selectIsTranscriptionAllowedByMode:()=>zc,selectIsTranscriptionEnabled:()=>Vn,selectIsVBEnabled:()=>Yn,selectLocalAudioTrackID:()=>ae,selectLocalMediaSettings:()=>Ss,selectLocalPeer:()=>te,selectLocalPeerID:()=>Pe,selectLocalPeerName:()=>Pn,selectLocalPeerRole:()=>Je,selectLocalPeerRoleName:()=>bn,selectLocalTrackIDs:()=>gs,selectLocalVideoTrackID:()=>Y,selectMessageByMessageID:()=>Qc,selectMessageIDsInOrder:()=>ms,selectMessagesByPeerID:()=>Vc,selectMessagesByRole:()=>Fc,selectMessagesMap:()=>Vt,selectMessagesUnreadCountByPeerID:()=>Wc,selectMessagesUnreadCountByRole:()=>Gc,selectPeerAudioByID:()=>Ec,selectPeerByCondition:()=>nd,selectPeerByID:()=>Z,selectPeerCount:()=>yn,selectPeerMetadata:()=>qc,selectPeerName:()=>Jc,selectPeerNameByID:()=>mc,selectPeerScreenSharing:()=>Wa,selectPeerSharingAudio:()=>Ln,selectPeerSharingAudioPlaylist:()=>_n,selectPeerSharingVideoPlaylist:()=>wn,selectPeerTypeByID:()=>Sc,selectPeers:()=>Te,selectPeersByCondition:()=>cd,selectPeersByRole:()=>$c,selectPeersByRoles:()=>Kc,selectPeersMap:()=>j,selectPeersScreenSharing:()=>Dn,selectPeersWithAudioStatus:()=>Yc,selectPermissions:()=>Ms,selectPollByID:()=>ws,selectPolls:()=>tc,selectPollsMap:()=>ys,selectPreviewRole:()=>vs,selectPreviewRoleName:()=>Ka,selectRTMPState:()=>$n,selectRecentError:()=>Tn,selectRecordingState:()=>Wn,selectRemotePeers:()=>In,selectRoleByRoleName:()=>no,selectRoleChangeRequest:()=>Zc,selectRolesMap:()=>fe,selectRoom:()=>B,selectRoomID:()=>fn,selectRoomStartTime:()=>Jn,selectRoomStarted:()=>Bn,selectRoomState:()=>ie,selectScreenAudioTrackByID:()=>Tc,selectScreenShareAudioByPeerID:()=>Cs,selectScreenShareByPeerID:()=>Hc,selectScreenSharesByPeerId:()=>Hs,selectScreenVideoTrackByID:()=>fc,selectScreenshareAudioVolumeByPeerID:()=>Nc,selectSessionId:()=>jn,selectSessionMetadata:()=>ec,selectSessionStore:()=>pc,selectSimulcastLayerByTrack:()=>Oc,selectSpeakers:()=>Ga,selectTemplateAppData:()=>Zn,selectTrackAudioByID:()=>yc,selectTrackByID:()=>Wt,selectTracksMap:()=>_,selectTranscriptionsState:()=>qn,selectUnreadHMSBroadcastMessagesCount:()=>Un,selectUnreadHMSMessagesCount:()=>xn,selectVideoPlaylist:()=>bs,selectVideoPlaylistAudioTrackByPeerID:()=>Ic,selectVideoPlaylistVideoTrackByPeerID:()=>Ac,selectVideoTrackByID:()=>Rs,selectVideoTrackByPeerID:()=>to,selectWhiteboard:()=>rc,selectWhiteboards:()=>qa,simulcastMapping:()=>Ue});module.exports=Xo(Kd);var hi=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(hi||{});var kt=()=>({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}),Et=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var Ys=(e=>(e.CHAT="chat",e))(Ys||{});var Br=(t=>(t.INFO="info",t.ERROR="error",t))(Br||{}),mi=(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))(mi||{});var Vr=(t=>(t.audio="audio",t.video="video",t))(Vr||{});var A=require("reselect");function We(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];Zo(s)&&(i=Pt(s)?s:i,t=bt(s)?s:t)}return{video:t,audio:i}}function Pt(a){return a&&a.type==="audio"}function bt(a){return a&&a.type==="video"}function Zo(a){return a&&a.source==="screen"}function Si(a){return a&&a.source==="audioplaylist"}function At(a){return a&&a.source==="videoplaylist"}function Xs(a){return a?!!(a!=null&&a.degraded):!1}function Ze(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function Zs(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function It(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 Fr=(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))(Fr||{}),en=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=en?7:0;var et=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var aa=require("ua-parser-js"),he=new aa.UAParser,U=typeof window!="undefined",ea,$e=typeof window=="undefined"&&!((ea=he.getBrowser().name)!=null&&ea.toLowerCase().includes("electron"));var tn=()=>!$e,tl=tn(),Rt=()=>he.getDevice().type==="mobile",oa=()=>typeof document!="undefined"&&document.hidden,na=()=>{var a;return((a=he.getOS().name)==null?void 0:a.toLowerCase())==="ios"},ta,ia,ca=(ia=(ta=he.getBrowser())==null?void 0:ta.name)==null?void 0:ia.toLowerCase().includes("safari"),ra,sa,gi=((sa=(ra=he.getBrowser())==null?void 0:ra.name)==null?void 0:sa.toLowerCase())==="firefox";var Sa=require("uuid");var Gr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Gr||{});function rn(){if(U&&window){let a=window.location.hostname;return a==="localhost"||a==="127.0.0.1"?"LOCAL":a.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var tt=rn();var la=require("uuid");var P={WebSocketConnectionErrors:{FAILED_TO_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003,ABNORMAL_CLOSE:1006},APIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3004,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010,SYSTEM_DENIED_PERMISSION:3011,CURRENT_TAB_NOT_SHARED:3012,AUDIO_PLAYBACK_ERROR:3013,SELECTED_DEVICE_MISSING:3014,NO_DATA:3015},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005,ICE_DISCONNECTED:4006,STATS_FAILED:4007},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011,LOCAL_STORAGE_ACCESS_DENIED:6012,VALIDATION_FAILED:6013},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}};var k=class a extends Error{constructor(t,i,r,s,o,n=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=o;this.isTerminal=n;Object.setPrototypeOf(this,a.prototype),this.action=r.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{
|
|
1
|
+
"use strict";var $o=Object.create;var yt=Object.defineProperty,Ko=Object.defineProperties,qo=Object.getOwnPropertyDescriptor,jo=Object.getOwnPropertyDescriptors,Jo=Object.getOwnPropertyNames,pi=Object.getOwnPropertySymbols,Js=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty,Qs=Object.prototype.propertyIsEnumerable,Qo=Reflect.get;var js=(a,e,t)=>e in a?yt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))xr.call(e,t)&&js(a,t,e[t]);if(pi)for(var t of pi(e))Qs.call(e,t)&&js(a,t,e[t]);return a},M=(a,e)=>Ko(a,jo(e));var Ur=(a,e)=>{var t={};for(var i in a)xr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&pi)for(var i of pi(a))e.indexOf(i)<0&&Qs.call(a,i)&&(t[i]=a[i]);return t};var zo=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Yo=(a,e)=>{for(var t in e)yt(a,t,{get:e[t],enumerable:!0})},zs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jo(e))!xr.call(a,r)&&r!==t&&yt(a,r,{get:()=>e[r],enumerable:!(i=qo(e,r))||i.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?$o(Js(a)):{},zs(e||!a||!a.__esModule?yt(t,"default",{value:a,enumerable:!0}):t,a)),Xo=a=>zs(yt({},"__esModule",{value:!0}),a);var ce=(a,e,t)=>Qo(Js(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 qr=zo((Ll,an)=>{an.exports={version:"0.12.36",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist","src"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^1.0.1",uuid:"^8.3.2","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/lodash.isequal":"^4.5.8","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.36","@types/uuid":"^8.3.0","jest-canvas-mock":"^2.3.1","jsdom-worker":"^0.3.0",tslib:"^2.2.0"},description:"@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow",keywords:["video","webrtc","conferencing","100ms"],gitHead:"777fbe43235a3488b310cd0a390a7e36150f6229"}});var Kd={};Yo(Kd,{ConnectivityState:()=>vo,DeviceType:()=>rs,Diagnostics:()=>ht,DomainCategory:()=>Gr,EventBus:()=>mt,HLSPlaylistType:()=>Zr,HLSStreamType:()=>es,HMSAudioDeviceCategory:()=>Ei,HMSAudioMode:()=>Ri,HMSAudioPluginType:()=>vi,HMSLogLevel:()=>Fr,HMSMessageType:()=>Ys,HMSNotificationSeverity:()=>Br,HMSNotificationTypes:()=>mi,HMSPeerType:()=>Ii,HMSPlaylistType:()=>Vr,HMSPluginUnsupportedTypes:()=>Mi,HMSReactiveStore:()=>Xe,HMSRecordingState:()=>Xr,HMSRoomState:()=>hi,HMSStats:()=>vt,HMSTrackExceptionTrackType:()=>Wr,HMSTranscriptionMode:()=>is,HMSTranscriptionState:()=>ts,HMSVideoPluginCanvasContextType:()=>Ci,HMSVideoPluginType:()=>Hi,createDefaultStatsStore:()=>Et,createDefaultStoreState:()=>kt,getAudioDeviceCategory:()=>Pi,parsedUserAgent:()=>he,selectAppData:()=>uc,selectAppDataByPath:()=>hc,selectAudioPlaylist:()=>Ps,selectAudioPlaylistTrackByPeerID:()=>Rc,selectAudioTrackByID:()=>gc,selectAudioTrackByPeerID:()=>io,selectAudioTrackVolume:()=>Ds,selectAudioVolumeByPeerID:()=>_c,selectAuxiliaryAudioByPeerID:()=>bc,selectAuxiliaryTracksByPeerID:()=>Mc,selectAvailableRoleNames:()=>Fn,selectBroadcastMessages:()=>oo,selectBroadcastMessagesUnreadCount:()=>Bc,selectCameraStreamByPeerID:()=>vc,selectConnectionQualities:()=>Mn,selectConnectionQualityByPeerID:()=>Pc,selectDegradedTracks:()=>Nn,selectDevices:()=>vn,selectDidIJoinWithin:()=>dd,selectDominantSpeaker:()=>Rn,selectEffectsKey:()=>Xn,selectErrors:()=>Fa,selectFullAppData:()=>Fi,selectHLSState:()=>Kn,selectHMSBroadcastMessages:()=>$a,selectHMSMessages:()=>ut,selectHMSMessagesCount:()=>On,selectHMSStats:()=>Wo,selectHandRaisedPeers:()=>ic,selectHasPeerHandRaised:()=>jc,selectIsAllowedToPreviewMedia:()=>td,selectIsAllowedToPublish:()=>ed,selectIsAllowedToSubscribe:()=>Gn,selectIsAudioLocallyMuted:()=>Ls,selectIsConnectedToRoom:()=>He,selectIsEffectsEnabled:()=>zn,selectIsInPreview:()=>fs,selectIsLargeRoom:()=>Qn,selectIsLocalAudioEnabled:()=>Hn,selectIsLocalAudioPluginPresent:()=>od,selectIsLocalScreenShared:()=>Wi,selectIsLocalVideoDisplayEnabled:()=>Ts,selectIsLocalVideoEnabled:()=>Gi,selectIsLocalVideoPluginPresent:()=>ad,selectIsLocallyMutedByPeerID:()=>Dc,selectIsPeerAudioEnabled:()=>Cc,selectIsPeerVideoEnabled:()=>Lc,selectIsRoleAllowedToPublish:()=>id,selectIsScreenShareLocallyMutedByPeerID:()=>wc,selectIsSomeoneScreenSharing:()=>Cn,selectIsTranscriptionAllowedByMode:()=>zc,selectIsTranscriptionEnabled:()=>Vn,selectIsVBEnabled:()=>Yn,selectLocalAudioTrackID:()=>ae,selectLocalMediaSettings:()=>Ss,selectLocalPeer:()=>te,selectLocalPeerID:()=>Pe,selectLocalPeerName:()=>Pn,selectLocalPeerRole:()=>Je,selectLocalPeerRoleName:()=>bn,selectLocalTrackIDs:()=>gs,selectLocalVideoTrackID:()=>Y,selectMessageByMessageID:()=>Qc,selectMessageIDsInOrder:()=>ms,selectMessagesByPeerID:()=>Vc,selectMessagesByRole:()=>Fc,selectMessagesMap:()=>Vt,selectMessagesUnreadCountByPeerID:()=>Wc,selectMessagesUnreadCountByRole:()=>Gc,selectPeerAudioByID:()=>Ec,selectPeerByCondition:()=>nd,selectPeerByID:()=>Z,selectPeerCount:()=>yn,selectPeerMetadata:()=>qc,selectPeerName:()=>Jc,selectPeerNameByID:()=>mc,selectPeerScreenSharing:()=>Wa,selectPeerSharingAudio:()=>Ln,selectPeerSharingAudioPlaylist:()=>_n,selectPeerSharingVideoPlaylist:()=>wn,selectPeerTypeByID:()=>Sc,selectPeers:()=>Te,selectPeersByCondition:()=>cd,selectPeersByRole:()=>$c,selectPeersByRoles:()=>Kc,selectPeersMap:()=>j,selectPeersScreenSharing:()=>Dn,selectPeersWithAudioStatus:()=>Yc,selectPermissions:()=>Ms,selectPollByID:()=>ws,selectPolls:()=>tc,selectPollsMap:()=>ys,selectPreviewRole:()=>vs,selectPreviewRoleName:()=>Ka,selectRTMPState:()=>$n,selectRecentError:()=>Tn,selectRecordingState:()=>Wn,selectRemotePeers:()=>In,selectRoleByRoleName:()=>no,selectRoleChangeRequest:()=>Zc,selectRolesMap:()=>fe,selectRoom:()=>B,selectRoomID:()=>fn,selectRoomStartTime:()=>Jn,selectRoomStarted:()=>Bn,selectRoomState:()=>ie,selectScreenAudioTrackByID:()=>Tc,selectScreenShareAudioByPeerID:()=>Cs,selectScreenShareByPeerID:()=>Hc,selectScreenSharesByPeerId:()=>Hs,selectScreenVideoTrackByID:()=>fc,selectScreenshareAudioVolumeByPeerID:()=>Nc,selectSessionId:()=>jn,selectSessionMetadata:()=>ec,selectSessionStore:()=>pc,selectSimulcastLayerByTrack:()=>Oc,selectSpeakers:()=>Ga,selectTemplateAppData:()=>Zn,selectTrackAudioByID:()=>yc,selectTrackByID:()=>Wt,selectTracksMap:()=>_,selectTranscriptionsState:()=>qn,selectUnreadHMSBroadcastMessagesCount:()=>Un,selectUnreadHMSMessagesCount:()=>xn,selectVideoPlaylist:()=>bs,selectVideoPlaylistAudioTrackByPeerID:()=>Ic,selectVideoPlaylistVideoTrackByPeerID:()=>Ac,selectVideoTrackByID:()=>Rs,selectVideoTrackByPeerID:()=>to,selectWhiteboard:()=>rc,selectWhiteboards:()=>qa,simulcastMapping:()=>Ue});module.exports=Xo(Kd);var hi=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(hi||{});var kt=()=>({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}),Et=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var Ys=(e=>(e.CHAT="chat",e))(Ys||{});var Br=(t=>(t.INFO="info",t.ERROR="error",t))(Br||{}),mi=(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))(mi||{});var Vr=(t=>(t.audio="audio",t.video="video",t))(Vr||{});var A=require("reselect");function We(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];Zo(s)&&(i=Pt(s)?s:i,t=bt(s)?s:t)}return{video:t,audio:i}}function Pt(a){return a&&a.type==="audio"}function bt(a){return a&&a.type==="video"}function Zo(a){return a&&a.source==="screen"}function Si(a){return a&&a.source==="audioplaylist"}function At(a){return a&&a.source==="videoplaylist"}function Xs(a){return a?!!(a!=null&&a.degraded):!1}function Ze(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function Zs(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function It(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 Fr=(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))(Fr||{}),en=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=en?7:0;var et=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var aa=require("ua-parser-js"),he=new aa.UAParser,U=typeof window!="undefined",ea,$e=typeof window=="undefined"&&!((ea=he.getBrowser().name)!=null&&ea.toLowerCase().includes("electron"));var tn=()=>!$e,tl=tn(),Rt=()=>he.getDevice().type==="mobile",oa=()=>typeof document!="undefined"&&document.hidden,na=()=>{var a;return((a=he.getOS().name)==null?void 0:a.toLowerCase())==="ios"},ta,ia,ca=(ia=(ta=he.getBrowser())==null?void 0:ta.name)==null?void 0:ia.toLowerCase().includes("safari"),ra,sa,gi=((sa=(ra=he.getBrowser())==null?void 0:ra.name)==null?void 0:sa.toLowerCase())==="firefox";var Sa=require("uuid");var Gr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Gr||{});function rn(){if(U&&window){let a=window.location.hostname;return a==="localhost"||a==="127.0.0.1"?"LOCAL":a.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var tt=rn();var la=require("uuid");var P={WebSocketConnectionErrors:{FAILED_TO_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003,ABNORMAL_CLOSE:1006},APIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3004,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010,SYSTEM_DENIED_PERMISSION:3011,CURRENT_TAB_NOT_SHARED:3012,AUDIO_PLAYBACK_ERROR:3013,SELECTED_DEVICE_MISSING:3014,NO_DATA:3015},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005,ICE_DISCONNECTED:4006,STATS_FAILED:4007},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011,LOCAL_STORAGE_ACCESS_DENIED:6012,VALIDATION_FAILED:6013},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}};var k=class a extends Error{constructor(t,i,r,s,o,n=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=o;this.isTerminal=n;Object.setPrototypeOf(this,a.prototype),this.action=r.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{
|
|
2
2
|
code: ${this.code};
|
|
3
3
|
name: ${this.name};
|
|
4
4
|
action: ${this.action};
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
source: ${this.source};
|
|
31
31
|
enabled: ${this.enabled};
|
|
32
32
|
nativeTrack: ${fi(this.nativeTrack)};
|
|
33
|
-
}`}};var _e=class extends we{constructor(t,i,r){super(t,i,r);this.type="audio";this.audioElement=null;if(i.kind!=="audio")throw new Error("Expected 'track' kind = 'audio'")}getVolume(){return this.audioElement?Math.floor(this.audioElement.volume*100):null}setVolume(t){return c(this,null,function*(){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");yield this.subscribeToAudio(t===0?!1:this.enabled),this.audioElement&&(this.audioElement.volume=t/100)})}setAudioElement(t){l.d("[HMSAudioTrack]",this.logIdentifier,"adding audio element",`${this}`,t),this.audioElement=t}getAudioElement(){return this.audioElement}getOutputDevice(){return this.outputDevice}cleanup(){super.cleanup(),this.audioElement&&(this.audioElement.srcObject=null,this.audioElement.remove(),this.audioElement=null)}setOutputDevice(t){return c(this,null,function*(){var i;if(!t){l.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){l.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&(gi||(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId)),this.outputDevice=t)}catch(r){l.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof Ae&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};var Ma=Ge(require("lodash.isequal"));var Jr=class{constructor(){this.storage=new Me("hms-device-selection");this.remember=!1;this.TAG="[HMSDeviceStorage]"}setDevices(e){this.devices=e}rememberDevices(e){this.remember=e}updateSelection(e,{deviceId:t,groupId:i}){if(!this.devices||!this.remember)return;let r=this.devices[e].find(o=>this.isSame({deviceId:t,groupId:i},o));if(!r){l.w(this.TAG,`Could not find device with deviceId: ${t}, groupId: ${i}`);return}let s=this.storage.get()||{};s[e]=r,this.storage.set(s)}getSelection(){if(this.remember)return this.storage.get()}cleanup(){this.remember=!1,this.devices=void 0}isSame(e,t){return e.deviceId===t.deviceId&&(e.groupId===t.groupId||!e.groupId)}},ee=new Jr;var vi=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(vi||{}),Mi=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(Mi||{});var Se=class{static failure(e,t){let i="mediaPlugin.failed",r=2,s=m({plugin_name:e},t.toAnalyticsProperties());return new C({name:i,level:r,properties:s})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",s=2,o=m({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new C({name:r,level:s,properties:o})}static audioPluginStats({pluginName:e,duration:t,loadTime:i,sampleRate:r}){let s="mediaPlugin.stats",o=1,n={plugin_name:e,duration:t,load_time:i,sampleRate:r};return new C({name:s,level:o,properties:n})}static added(e,t){let i="mediaPlugin.added",r=1,s={plugin_name:e,added_at:t};return new C({name:i,level:r,properties:s})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:s,inputFrameRate:o,pluginFrameRate:n}){let d="mediaPlugin.stats",u=1,p={plugin_name:e,duration:t,load_time:i,avg_preprocessing_time:r,avg_processing_time:s,input_frame_rate:o,plugin_frame_rate:n};return new C({name:d,level:u,properties:p})}};var yi=class{constructor(e){this.eventBus=e;this.TAG="[AudioPluginsAnalytics]";this.initTime={},this.addedTimestamps={},this.pluginAdded={},this.pluginSampleRate={}}added(e,t){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.pluginSampleRate[e]=t,this.eventBus.analytics.publish(Se.added(e,this.addedTimestamps[e]))}removed(e){if(this.pluginAdded[e]){let t={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],sampleRate:this.pluginSampleRate[e]};this.eventBus.analytics.publish(Se.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(Se.audioPluginFailure(e,this.pluginSampleRate[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("AUDIO_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)})}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.pluginAdded[e],delete this.pluginSampleRate[e]}};var Dt=class{constructor(e,t,i){this.eventBus=t;this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new yi(t),this.audioContext=de.getAudioContext(),this.room=i}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){l.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let s=S.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,s),l.w("can't add another plugin when previous add is in progress"),s}switch(e.getName()){case"HMSKrispPlugin":{if(!((r=this.room)!=null&&r.isNoiseCancellationEnabled)){let s="Krisp Noise Cancellation is not enabled for this room";if(this.pluginsMap.size===0)throw Error(s);l.w(this.TAG,s);return}this.eventBus.analytics.publish(y.krispStart());break}default:}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} already added.`);return}yield this.validateAndThrow(t,e),(r=e.setEventBus)==null||r.call(e,this.eventBus);try{this.pluginsMap.size===0?yield this.initAudioNodes():this.prevAudioNode&&this.prevAudioNode.disconnect(),this.analytics.added(t,this.audioContext.sampleRate),yield this.analytics.initWithTime(t,()=>c(this,null,function*(){return e.init()})),this.pluginsMap.set(t,e),yield this.processPlugin(e),yield this.connectToDestination(),yield this.updateProcessedTrack()}catch(s){throw l.e(this.TAG,"failed to add plugin",s),s}})}validatePlugin(e){return e.checkSupport(this.audioContext)}validateAndThrow(e,t){return c(this,null,function*(){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=S.MediaPluginErrors.PlatformNotSupported("AUDIO_PLUGINS","platform not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}else if(i.errType==="DEVICE_NOT_SUPPORTED"){let r=S.MediaPluginErrors.DeviceNotSupported("AUDIO_PLUGINS","audio device not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}})}removePlugin(e){return c(this,null,function*(){switch(e.getName()){case"HMSKrispPlugin":{this.eventBus.analytics.publish(y.krispStop());break}default:break}yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.hmsTrack.setProcessedTrack(void 0)):yield this.reprocessPlugins()})}cleanup(){return c(this,null,function*(){var e,t,i;for(let r of this.pluginsMap.values())yield this.removePluginInternal(r);yield this.hmsTrack.setProcessedTrack(void 0),(e=this.sourceNode)==null||e.disconnect(),(t=this.prevAudioNode)==null||t.disconnect(),(i=this.outputTrack)==null||i.stop(),this.sourceNode=void 0,this.destinationNode=void 0,this.prevAudioNode=void 0,this.outputTrack=void 0})}closeContext(){return c(this,null,function*(){this.audioContext=void 0})}reprocessPlugins(){return c(this,null,function*(){if(this.pluginsMap.size===0||!this.sourceNode)return;let e=Array.from(this.pluginsMap.values());yield this.cleanup(),yield this.initAudioNodes();for(let t of e)yield this.addPlugin(t);yield this.updateProcessedTrack()})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e),this.destinationNode||(this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0])}})}updateProcessedTrack(){return c(this,null,function*(){try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw l.e(this.TAG,"error in setting processed track",e),e}})}processPlugin(e){return c(this,null,function*(){try{let t=yield e.processAudioTrack(this.audioContext,this.prevAudioNode||this.sourceNode);this.prevAudioNode&&this.prevAudioNode.connect(t),this.prevAudioNode=t}catch(t){let i=e.getName();l.e(this.TAG,`error in processing plugin ${i}`,t),yield this.removePluginInternal(e)}})}connectToDestination(){return c(this,null,function*(){try{this.prevAudioNode&&this.destinationNode&&this.prevAudioNode.context===this.destinationNode.context&&this.prevAudioNode.connect(this.destinationNode)}catch(e){l.e(this.TAG,"error in connecting to destination node",e)}})}removePluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}};var Qr=Ge(require("webrtc-adapter"));function on(a,e){let t=a.toLowerCase(),i=S.TracksErrors.GenericTrack("TRACK",a);return t.includes("device not found")?i=S.TracksErrors.DeviceNotAvailable("TRACK",e,a):t.includes("permission denied")&&(i=S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a)),i}function nn(a,e=""){if(Qr.default.browserDetails.browser==="chrome"&&a.name==="NotAllowedError"&&a.message.includes("denied by system"))return S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);if(Qr.default.browserDetails.browser==="firefox"&&a.name==="NotFoundError"){let i=S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);return i.description=`Capture device is either blocked at Operating System level or not available - ${e}`,i}switch(a.name){case"OverconstrainedError":return S.TracksErrors.OverConstrained("TRACK",e,a.constraint);case"NotAllowedError":return S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a.message);case"NotFoundError":return S.TracksErrors.DeviceNotAvailable("TRACK",e,a.message);case"NotReadableError":return S.TracksErrors.DeviceInUse("TRACK",e,a.message);case"TypeError":return S.TracksErrors.NothingToReturn("TRACK",a.message);default:return on(a.message,e)}}function Ne(a,e){let t=nn(a,e);return t.addNativeError(a),t}function zr(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({audio:a?a.toConstraints():!1})).getAudioTracks()[0]}catch(e){throw Ne(e,"audio")}})}function Yr(a){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({video:a?a.toConstraints():!1})).getVideoTracks()[0]}catch(e){throw Ne(e,"video")}})}function ye(a){return"canvas"in a||a.label==="MediaStreamAudioDestinationNode"||a.label===""}var ki=(a,e)=>{if(!navigator.permissions){l.d("Permissions API not supported");return}navigator.permissions.query({name:a}).then(t=>{t.onchange=()=>{e(t.state)}}).catch(t=>{l.e(`${a} not supported`,t.message)})};var cn=32e3;var de={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=gi?new AudioContext:new AudioContext({sampleRate:cn})),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(a){l.e("AudioContext",a)}})}},Ei=(r=>(r.SPEAKERPHONE="SPEAKERPHONE",r.WIRED="WIRED",r.BLUETOOTH="BLUETOOTH",r.EARPIECE="EARPIECE",r))(Ei||{}),Pi=a=>{if(!a)return l.w("[DeviceManager]:","No device label provided"),"SPEAKERPHONE";let e=a.toLowerCase();return e.includes("speakerphone")?"SPEAKERPHONE":e.includes("wired")?"WIRED":/airpods|buds|wireless|bluetooth/gi.test(e)?"BLUETOOTH":e.includes("earpiece")?"EARPIECE":"SPEAKERPHONE"};var Oe=class{constructor(e=1/0){this.capacity=e;this.storage=[]}size(){return this.storage.length}toList(){return this.storage.slice(0)}enqueue(e){this.size()===this.capacity&&this.dequeue(),this.storage.push(e)}dequeue(){return this.storage.shift()}aggregate(e){return e(this.storage)}};var ga=`(function workerSetup() {
|
|
33
|
+
}`}};var _e=class extends we{constructor(t,i,r){super(t,i,r);this.type="audio";this.audioElement=null;if(i.kind!=="audio")throw new Error("Expected 'track' kind = 'audio'")}getVolume(){return this.audioElement?Math.floor(this.audioElement.volume*100):null}setVolume(t){return c(this,null,function*(){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");yield this.subscribeToAudio(t===0?!1:this.enabled),this.audioElement&&(this.audioElement.volume=t/100)})}setAudioElement(t){l.d("[HMSAudioTrack]",this.logIdentifier,"adding audio element",`${this}`,t),this.audioElement=t}getAudioElement(){return this.audioElement}getOutputDevice(){return this.outputDevice}cleanup(){super.cleanup(),this.audioElement&&(this.audioElement.srcObject=null,this.audioElement.remove(),this.audioElement=null)}setOutputDevice(t){return c(this,null,function*(){var i;if(!t){l.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){l.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&(gi||(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId)),this.outputDevice=t)}catch(r){l.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof Ae&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};var Ma=Ge(require("lodash.isequal"));var Jr=class{constructor(){this.storage=new Me("hms-device-selection");this.remember=!1;this.TAG="[HMSDeviceStorage]"}setDevices(e){this.devices=e}rememberDevices(e){this.remember=e}updateSelection(e,{deviceId:t,groupId:i}){if(!this.devices||!this.remember)return;let r=this.devices[e].find(o=>this.isSame({deviceId:t,groupId:i},o));if(!r){l.w(this.TAG,`Could not find device with deviceId: ${t}, groupId: ${i}`);return}let s=this.storage.get()||{};s[e]=r,this.storage.set(s)}getSelection(){if(this.remember)return this.storage.get()}cleanup(){this.remember=!1,this.devices=void 0}isSame(e,t){return e.deviceId===t.deviceId&&(e.groupId===t.groupId||!e.groupId)}},ee=new Jr;var vi=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(vi||{}),Mi=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(Mi||{});var Se=class{static failure(e,t){let i="mediaPlugin.failed",r=2,s=m({plugin_name:e},t.toAnalyticsProperties());return new C({name:i,level:r,properties:s})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",s=2,o=m({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new C({name:r,level:s,properties:o})}static audioPluginStats({pluginName:e,duration:t,loadTime:i,sampleRate:r}){let s="mediaPlugin.stats",o=1,n={plugin_name:e,duration:t,load_time:i,sampleRate:r};return new C({name:s,level:o,properties:n})}static added(e,t){let i="mediaPlugin.added",r=1,s={plugin_name:e,added_at:t};return new C({name:i,level:r,properties:s})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:s,inputFrameRate:o,pluginFrameRate:n}){let d="mediaPlugin.stats",u=1,p={plugin_name:e,duration:t,load_time:i,avg_preprocessing_time:r,avg_processing_time:s,input_frame_rate:o,plugin_frame_rate:n};return new C({name:d,level:u,properties:p})}};var yi=class{constructor(e){this.eventBus=e;this.TAG="[AudioPluginsAnalytics]";this.initTime={},this.addedTimestamps={},this.pluginAdded={},this.pluginSampleRate={}}added(e,t){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.pluginSampleRate[e]=t,this.eventBus.analytics.publish(Se.added(e,this.addedTimestamps[e]))}removed(e){if(this.pluginAdded[e]){let t={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],sampleRate:this.pluginSampleRate[e]};this.eventBus.analytics.publish(Se.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(Se.audioPluginFailure(e,this.pluginSampleRate[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("AUDIO_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)})}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.pluginAdded[e],delete this.pluginSampleRate[e]}};var Dt=class{constructor(e,t,i){this.eventBus=t;this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new yi(t),this.audioContext=de.getAudioContext(),this.room=i}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){l.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let s=S.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,s),l.w("can't add another plugin when previous add is in progress"),s}switch(e.getName()){case"HMSKrispPlugin":{if(!((r=this.room)!=null&&r.isNoiseCancellationEnabled)){let s="Krisp Noise Cancellation is not enabled for this room";if(this.pluginsMap.size===0)throw Error(s);l.w(this.TAG,s);return}this.eventBus.analytics.publish(y.krispStart());break}default:}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} already added.`);return}yield this.validateAndThrow(t,e),(r=e.setEventBus)==null||r.call(e,this.eventBus);try{this.pluginsMap.size===0?yield this.initAudioNodes():this.prevAudioNode&&this.prevAudioNode.disconnect(),this.analytics.added(t,this.audioContext.sampleRate),yield this.analytics.initWithTime(t,()=>c(this,null,function*(){return e.init()})),this.pluginsMap.set(t,e),yield this.processPlugin(e),yield this.connectToDestination(),yield this.updateProcessedTrack()}catch(s){throw l.e(this.TAG,"failed to add plugin",s),s}})}validatePlugin(e){return e.checkSupport(this.audioContext)}validateAndThrow(e,t){return c(this,null,function*(){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=S.MediaPluginErrors.PlatformNotSupported("AUDIO_PLUGINS","platform not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}else if(i.errType==="DEVICE_NOT_SUPPORTED"){let r=S.MediaPluginErrors.DeviceNotSupported("AUDIO_PLUGINS","audio device not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}})}removePlugin(e){return c(this,null,function*(){switch(e.getName()){case"HMSKrispPlugin":{this.eventBus.analytics.publish(y.krispStop());break}default:break}yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.hmsTrack.setProcessedTrack(void 0)):yield this.reprocessPlugins()})}cleanup(){return c(this,null,function*(){var e,t,i;for(let r of this.pluginsMap.values())yield this.removePluginInternal(r);yield this.hmsTrack.setProcessedTrack(void 0),(e=this.sourceNode)==null||e.disconnect(),(t=this.prevAudioNode)==null||t.disconnect(),(i=this.outputTrack)==null||i.stop(),this.sourceNode=void 0,this.destinationNode=void 0,this.prevAudioNode=void 0,this.outputTrack=void 0})}closeContext(){return c(this,null,function*(){this.audioContext=void 0})}reprocessPlugins(){return c(this,null,function*(){if(this.pluginsMap.size===0||!this.sourceNode)return;let e=Array.from(this.pluginsMap.values());yield this.cleanup(),yield this.initAudioNodes();for(let t of e)yield this.addPlugin(t);yield this.updateProcessedTrack()})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e),this.destinationNode||(this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0])}})}updateProcessedTrack(){return c(this,null,function*(){try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw l.e(this.TAG,"error in setting processed track",e),e}})}processPlugin(e){return c(this,null,function*(){try{let t=yield e.processAudioTrack(this.audioContext,this.prevAudioNode||this.sourceNode);this.prevAudioNode&&this.prevAudioNode.connect(t),this.prevAudioNode=t}catch(t){let i=e.getName();l.e(this.TAG,`error in processing plugin ${i}`,t),yield this.removePluginInternal(e)}})}connectToDestination(){return c(this,null,function*(){try{this.prevAudioNode&&this.destinationNode&&this.prevAudioNode.context===this.destinationNode.context&&this.prevAudioNode.connect(this.destinationNode)}catch(e){l.e(this.TAG,"error in connecting to destination node",e)}})}removePluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}};var Qr=Ge(require("webrtc-adapter"));function on(a,e){let t=a.toLowerCase(),i=S.TracksErrors.GenericTrack("TRACK",a);return t.includes("device not found")?i=S.TracksErrors.DeviceNotAvailable("TRACK",e,a):t.includes("permission denied")&&(i=S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a)),i}function nn(a,e=""){if(Qr.default.browserDetails.browser==="chrome"&&a.name==="NotAllowedError"&&a.message.includes("denied by system"))return S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);if(Qr.default.browserDetails.browser==="firefox"&&a.name==="NotFoundError"){let i=S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);return i.description=`Capture device is either blocked at Operating System level or not available - ${e}`,i}switch(a.name){case"OverconstrainedError":return S.TracksErrors.OverConstrained("TRACK",e,a.constraint);case"NotAllowedError":return S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a.message);case"NotFoundError":return S.TracksErrors.DeviceNotAvailable("TRACK",e,a.message);case"NotReadableError":return S.TracksErrors.DeviceInUse("TRACK",e,a.message);case"TypeError":return S.TracksErrors.NothingToReturn("TRACK",a.message);default:return on(a.message,e)}}function Ne(a,e){let t=nn(a,e);return t.addNativeError(a),t}function zr(a){return c(this,null,function*(){try{let e=a?a.toConstraints():!1;return e&&typeof e=="object"&&(a!=null&&a.deviceId)&&(e.deviceId={exact:a.deviceId}),(yield navigator.mediaDevices.getUserMedia({audio:e})).getAudioTracks()[0]}catch(e){throw Ne(e,"audio")}})}function Yr(a){return c(this,null,function*(){try{let e=a?a.toConstraints():!1;return e&&typeof e=="object"&&(a!=null&&a.deviceId)&&(e.deviceId={exact:a.deviceId}),(yield navigator.mediaDevices.getUserMedia({video:e})).getVideoTracks()[0]}catch(e){throw Ne(e,"video")}})}function ye(a){return"canvas"in a||a.label==="MediaStreamAudioDestinationNode"||a.label===""}var ki=(a,e)=>{if(!navigator.permissions){l.d("Permissions API not supported");return}navigator.permissions.query({name:a}).then(t=>{t.onchange=()=>{e(t.state)}}).catch(t=>{l.e(`${a} not supported`,t.message)})};var cn=32e3;var de={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=gi?new AudioContext:new AudioContext({sampleRate:cn})),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(a){l.e("AudioContext",a)}})}},Ei=(r=>(r.SPEAKERPHONE="SPEAKERPHONE",r.WIRED="WIRED",r.BLUETOOTH="BLUETOOTH",r.EARPIECE="EARPIECE",r))(Ei||{}),Pi=a=>{if(!a)return l.w("[DeviceManager]:","No device label provided"),"SPEAKERPHONE";let e=a.toLowerCase();return e.includes("speakerphone")?"SPEAKERPHONE":e.includes("wired")?"WIRED":/airpods|buds|wireless|bluetooth/gi.test(e)?"BLUETOOTH":e.includes("earpiece")?"EARPIECE":"SPEAKERPHONE"};var Oe=class{constructor(e=1/0){this.capacity=e;this.storage=[]}size(){return this.storage.length}toList(){return this.storage.slice(0)}enqueue(e){this.size()===this.capacity&&this.dequeue(),this.storage.push(e)}dequeue(){return this.storage.shift()}aggregate(e){return e(this.storage)}};var ga=`(function workerSetup() {
|
|
34
34
|
function ticker() {
|
|
35
35
|
self.postMessage('tick');
|
|
36
36
|
}
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
break;
|
|
45
45
|
}
|
|
46
46
|
};
|
|
47
|
-
})()`;function Q(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function xe(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return Q(a);let e=new Worker(URL.createObjectURL(new Blob([ga],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function Ta(){if(typeof Worker=="undefined")return{sleep:e=>Q(e)};let a=new Worker(URL.createObjectURL(new Blob([ga],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function bi(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var dn=35,ln=5,Ai=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 Oe(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 Q(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 Q(this.interval)})}sendAudioLevel(e=0){if(e=e>dn?e:0,Math.abs(this.audioLevel-e)>ln){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=de.getAudioContext(),i=t.createMediaStreamSource(e),r=t.createAnalyser();return r.fftSize=2048,i.connect(r),r}};var Ii=(t=>(t.SIP="sip",t.REGULAR="regular",t))(Ii||{});var Xr=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Xr||{});var Zr=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(Zr||{}),es=(i=>(i.REGULAR="regular",i.SCREEN="screen",i.COMPOSITE="composite",i))(es||{}),ts=(r=>(r.INITIALISED="initialised",r.STARTED="started",r.STOPPED="stopped",r.FAILED="failed",r))(ts||{}),is=(e=>(e.CAPTION="caption",e))(is||{});var Ue={f:"high",h:"medium",q:"low"};var Ri=(t=>(t.VOICE="voice",t.MUSIC="music",t))(Ri||{});var rs=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(rs||{});var z=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._audioMode="voice";this._advanced=[{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{highpassFilter:{exact:!0}},{audioMirroring:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=this._audioMode==="music"?320:e,this}deviceId(e){return this._deviceId=e,this}audioMode(e="voice"){return this._audioMode=e,this._audioMode==="music"?this._maxBitrate=320:this._maxBitrate=32,this}advanced(e){return this._advanced=e,this}build(){return new Ke(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced,this._audioMode)}},Ke=class{constructor(e,t,i,r,s,o){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s,this.audioMode=o,this.audioMode==="music"?this.maxBitrate=320:this.maxBitrate=32}toConstraints(){return{deviceId:this.deviceId,advanced:this.audioMode==="music"?[]:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var q=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new qe(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},qe=class{constructor(e,t,i,r,s,o,n,d){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=d}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId,facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Rt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var Be=class{constructor(){this._video=new q().build();this._audio=new z().build();this._screen=new q().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw S.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw S.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new it(this._video,this._audio,this._simulcast,this._screen||void 0)}},it=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=m(m({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=m(m({},this.video.toAnalyticsProperties()),e)),e}};function va(a,e){return function(i){return!(0,Ma.default)(a[i],e[i])}}var le=class a extends _e{constructor(t,i,r,s,o=new z().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this.TAG="[HMSLocalAudioTrack]";this.tracksCreated=new Set;this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){if(!this.shouldReacquireTrack()){l.d(this.TAG,`visibiltiy: ${document.visibilityState}`,`${this}`);return}if(document.visibilityState==="hidden")this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{l.d(this.TAG,"On visibile replacing track as it is not publishing");try{yield this.replaceTrackWith(this.settings)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.trackPermissions=()=>{ki("microphone",t=>{this.eventBus.analytics.publish(y.permissionChange(this.type,t)),t==="denied"&&this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})})};this.handleTrackMute=()=>{l.d(this.TAG,"muted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmute=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t}));try{yield this.setEnabled(this.enabled,!0),this.eventBus.localAudioUnmutedNatively.publish()}catch(i){this.eventBus.error.publish(i)}});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.shouldReacquireTrack=()=>ye(this.nativeTrack)||this.isTrackNotPublishing();this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=va(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(va(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&&(ee.updateSelection("audioInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"audioInput",selection:{deviceId:t.deviceId,groupId:s}}))}});t.tracks.push(this),this.addTrackEventListeners(i),this.trackPermissions(),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!ye(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Dt(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 zr(t);this.addTrackEventListeners(r),this.tracksCreated.add(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),yield this.updateTrack(r)}catch(r){let s=yield zr(this.settings);throw this.addTrackEventListeners(s),this.tracksCreated.add(s),yield this.updateTrack(s),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}try{yield this.pluginsManager.reprocessPlugins()}catch(r){this.eventBus.audioPluginFailed.publish(r)}})}setEnabled(t,i=!1){return c(this,null,function*(){t===this.enabled&&!i||(t&&this.shouldReacquireTrack()&&(yield this.replaceTrackWith(this.settings)),yield ce(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(ye(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 Ai(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;ce(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 Ke(i,r,s,o,n,d)}};var se=class a extends _e{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield ce(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var rt=class extends we{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){ca||(t.autoplay=!0),t.playsInline=!0,t.muted=!0,t.controls=!1}};var Ra=Ge(require("lodash.isequal"));var Pa=require("uuid");var wt={none:-1,low:0,medium:1,high:2},un=.5,ya=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>wt[o.layer]-wt[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)<un){t=d;break}}}return t};var ss=class{constructor(){this.TAG="[HMSIntersectionObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t)=>{var i;this.createObserver(),this.unobserve(e),(i=this.intersectionObserver)==null||i.observe(e),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.intersectionObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.intersectionObserver&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersection))};this.handleIntersection=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.IntersectionObserver!="undefined";return e||l.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},ka=new ss;var as=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(bi(this.handleResize,300)))};this.handleResize=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.ResizeObserver!="undefined";return e||l.w(this.TAG,"Resize Observer is not supported"),e}},Ea=new as;var st=class{constructor(e){this.track=e;this.TAG="[VideoElementManager]";this.videoElements=new Set;this.entries=new WeakMap;this.handleIntersection=e=>c(this,null,function*(){let t=getComputedStyle(e.target).visibility==="visible";this.track.enabled&&(e.isIntersecting&&t||!document.contains(e.target))?(l.d(this.TAG,"add sink intersection",`${this.track}`,this.id),this.entries.set(e.target,e.boundingClientRect),yield this.selectMaxLayer(),yield this.track.addSink(e.target)):(l.d(this.TAG,"remove sink intersection",`${this.track}`,this.id),yield this.track.removeSink(e.target))});this.handleResize=e=>c(this,null,function*(){!this.track.enabled||!(this.track instanceof O)||(this.entries.set(e.target,e.contentRect),yield this.selectMaxLayer())});this.cleanup=()=>{this.videoElements.forEach(e=>{var t,i;e.srcObject=null,(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e)}),this.videoElements.clear(),this.resizeObserver=void 0,this.intersectionObserver=void 0};this.init(),this.id=(0,Pa.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):U&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof O&&(yield this.track.setPreferredLayer(this.track.getPreferredLayer())))})}removeVideoElement(e){var t,i;this.track.removeSink(e),this.videoElements.delete(e),this.entries.delete(e),(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e),l.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){U&&(this.resizeObserver=Ea,this.intersectionObserver=ka)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:n,display:d}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,t+=e.offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&i+r>window.pageXOffset&&!o&&(n!==""?parseFloat(n)>0:!0)&&d!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof O)||this.videoElements.size===0)return;let e;for(let t of this.videoElements){let i=this.entries.get(t);if(!i)continue;let{width:r,height:s}=i;if(r===0||s===0)continue;let o=ya(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=wt[o]>wt[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 Hi=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Hi||{}),Ci=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(Ci||{});var _t=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 at=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new _t,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 _t,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(Se.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(Se.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(Se.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 ba=24,pn=320,hn=240,Nt=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=Ta();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new at(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||ba,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 xe(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||ba,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=pn,height:t=hn}=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 Li=class{constructor(e,t){this.TAG="[MediaStreamPluginsManager]";this.plugins=new Set,this.analytics=new at(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))})}};var Aa=require("uuid");var mn=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],Di=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),l.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){l.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...mn,...e].reduce((t,i)=>M(m({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var os={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default",audioMode:"voice"},ke,wi,Ie=class a{constructor(e,t,i,r,s){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=s;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=os){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),d=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let h={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};h.audio&&this.analyticsTimer.start("local_audio_track_time"),h.video&&this.analyticsTimer.start("local_video_track_time");try{l.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:h}),s=yield this.getLocalTracks(h,t,d)}catch(T){s=yield this.retryGetLocalTracks(T,t,h,d)}return h.audio&&this.analyticsTimer.end("local_audio_track_time"),h.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&s.push(o),n&&i&&!p&&s.push(n),s})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new it(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}optimizeScreenShareConstraint(e,t){return c(this,null,function*(){var s,o,n;if(typeof t.video=="boolean"||!((s=t.video)!=null&&s.width)||!((o=t.video)!=null&&o.height))return;let i=this.store.getPublishParams();if(!i||!((n=i.allowed)!=null&&n.includes("screen")))return;let r=document.createElement("video");r.srcObject=e,r.addEventListener("loadedmetadata",()=>c(this,null,function*(){let{videoWidth:d,videoHeight:u}=r,p=i.screen,h=p.width*p.height,T=d/u,g=p.width/p.height;if(T>g){let f=t.video,E=T/g,v=Math.sqrt(E);d*u>h?(f.width=d/v,f.height=u/v):(f.height=u*v,f.width=d*v),yield e.getVideoTracks()[0].applyConstraints(f)}}))})}getLocalScreen(e,t=!1){return c(this,null,function*(){var T;let i=yield this.getOrDefaultScreenshareConfig(e),r=this.getScreenshareSettings(i.videoOnly),s={video:M(m({},r==null?void 0:r.video.toConstraints(!0)),{displaySurface:i.displaySurface}),preferCurrentTab:i.preferCurrentTab,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio};if(r!=null&&r.audio){let g=(T=r==null?void 0:r.audio)==null?void 0:T.toConstraints();delete g.advanced,s.audio=M(m({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}else e!=null&&e.forceCurrentTab&&e.preferCurrentTab&&e.cropElement&&(s.audio={echoCancellation:!0,noiseSuppression:!0});let o;try{l.d("retrieving screenshare with ",{config:i},{constraints:s}),o=yield navigator.mediaDevices.getDisplayMedia(s),t&&(yield this.optimizeScreenShareConstraint(o,s))}catch(g){l.w(this.TAG,"error in getting screenshare - ",g);let f=Ne(g,"screen");throw this.eventBus.analytics.publish(y.publish({error:f,devices:this.deviceManager.getDevices(),settings:new it(r==null?void 0:r.video,r==null?void 0:r.audio,!1)})),f}let n=[],d=new ge(o),u=o.getVideoTracks()[0],p=new G(d,u,"screen",this.eventBus,r==null?void 0:r.video,this.store.getRoom());p.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(p,i.forceCurrentTab);p.isCurrentTab=g,yield p.cropTo(i.cropTarget)}catch(g){throw o.getTracks().forEach(f=>f.stop()),g}n.push(p);let h=o.getAudioTracks()[0];if(h){let g=new le(d,h,"screen",this.eventBus,r==null?void 0:r.audio,this.store.getRoom());n.push(g)}return l.v(this.TAG,"getLocalScreen",n),n})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:(0,Aa.v4)(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),l.d("setting capture handle - ",e.handle),navigator.mediaDevices.setCaptureHandleConfig(e),this.captureHandleIdentifier=e.handle)}validateCurrentTabCapture(e,t){let i=e.getCaptureHandle(),r=!!(this.captureHandleIdentifier&&(i==null?void 0:i.handle)===this.captureHandleIdentifier);if(t&&!r)throw l.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),S.TracksErrors.CurrentTabNotShared();return r}requestPermissions(){return c(this,null,function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})).getTracks().forEach(t=>t.stop())}catch(e){l.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,d,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((d=e==null?void 0:e.getSettings())==null?void 0:d.height)||240,r=1;ke||(ke=document.createElement("canvas"),ke.width=t,ke.height=i,(u=ke.getContext("2d"))==null||u.fillRect(0,0,t,i)),wi||(wi=setInterval(()=>{let p=ke==null?void 0:ke.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=ke.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=de.getAudioContext(),t=e.createOscillator(),i=e.createMediaStreamDestination();t.connect(i),t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}static cleanup(){clearInterval(wi),wi=void 0,ke=void 0}getAVTracks(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:e.audio?e.audio.toConstraints():!1,video:e.video?e.video.toConstraints():!1});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){yield this.deviceManager.init();let i=!!(!this.deviceManager.hasWebcamPermission&&e.video),r=!!(!this.deviceManager.hasMicrophonePermission&&e.audio),s=this.getErrorType(i,r);throw Ne(t,s)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new Be().video(i).audio(t).build()}isInIframe(){try{return window.self!==window.top}catch(e){return!0}}retryGetLocalTracks(e,t,i,r){return c(this,null,function*(){if(e instanceof k&&e.action==="TRACK"){this.observer.onFailure(e);let s=e.code===P.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(s){let d=new Be().video(new qe).audio(new Ke).build();l.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,d,r)}catch(u){let p=u instanceof k?u.nativeError:u,h=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let T=S.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");T.addNativeError(p),h=T}return yield this.retryGetLocalTracks(h,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,l.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(d){return l.w(this.TAG,"Fetch empty tacks failed",d),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(d),yield this.getLocalTracks(i,t,r)}}else return l.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(e),[]})}getErrorType(e,t){return e&&t?"audio, video":e?"video":t?"audio":"audio, video"}getEmptyTracks(e){let t=[];return e.audio==="empty"&&t.push(a.getEmptyAudioTrack()),e.video==="empty"&&t.push(a.getEmptyVideoTrack()),t}updateCurrentLocalTrackSettings(e){return c(this,null,function*(){let t=this.store.getLocalPeerTracks(),i=t.find(n=>n.type==="video"&&n.source==="regular"),r=t.find(n=>n.type==="audio"&&n.source==="regular"),s=t.find(n=>n.type==="video"&&n.source==="screen");e!=null&&e.video&&(yield i==null?void 0:i.setSettings(e.video)),e!=null&&e.audio&&(yield r==null?void 0:r.setSettings(e.audio));let o=this.getScreenshareSettings(!0);return o!=null&&o.video&&(yield s==null?void 0:s.setSettings(o==null?void 0:o.video)),{videoTrack:i,audioTrack:r}})}getAudioSettings(e){var o;let t=this.store.getPublishParams();if(!t||!((o=t.allowed)!=null&&o.includes("audio")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.audioTrack,s=(r==null?void 0:r.settings.deviceId)||e.audioInputDeviceId;return new z().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(s||os.audioInputDeviceId).build()}getVideoSettings(e){var n;let t=this.store.getPublishParams();if(!t||!((n=t.allowed)!=null&&n.includes("video")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.videoTrack,s=(r==null?void 0:r.settings.deviceId)||e.videoDeviceId,o=t.video;return new q().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(s||os.videoDeviceId).build()}getScreenshareSettings(e=!1){var r;let t=this.store.getPublishParams();if(!t||!((r=t.allowed)!=null&&r.includes("screen")))return null;let i=t.screen;return{video:new q().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new z().build()}}getOrDefaultScreenshareConfig(e){return c(this,null,function*(){var i;let t=Object.assign({videoOnly:!1,audioOnly:!1,forceCurrentTab:!1,preferCurrentTab:!1,selfBrowserSurface:"exclude",surfaceSwitching:"include",systemAudio:"exclude",displaySurface:"monitor"},e||{});return t.forceCurrentTab&&(t.videoOnly=!0,t.preferCurrentTab=!0,t.selfBrowserSurface="include",t.surfaceSwitching="exclude"),t.preferCurrentTab&&(t.selfBrowserSurface="include",t.displaySurface=void 0),t.cropElement&&((i=window.CropTarget)!=null&&i.fromElement)&&(t.cropTarget=yield window.CropTarget.fromElement(t.cropElement)),t})}createHMSLocalTracks(e,t,i){let r=e.find(n=>n.kind==="video"),s=e.find(n=>n.kind==="audio");i?e.forEach(n=>i==null?void 0:i.nativeStream.addTrack(n)):i=new ge(new MediaStream(e));let o=[];if(s&&(t!=null&&t.audio)){let n=new le(i,s,"regular",this.eventBus,t.audio,this.store.getRoom());o.push(n)}if(r&&(t!=null&&t.video)){let n=new G(i,r,"regular",this.eventBus,t.video,this.store.getRoom());n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function Ia(a,e){return function(i){return!(0,Ra.default)(a[i],e[i])}}var G=class a extends rt{constructor(t,i,r,s,o=new q().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this._layerDefinitions=[];this.TAG="[HMSLocalVideoTrack]";this.enabledStateBeforeBackground=!1;this.isCurrentTab=!1;this.isPublished=!1;this.replaceSenderTrack=t=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(t)});this.buildNewSettings=t=>{let{width:i,height:r,codec:s,maxFramerate:o,maxBitrate:n,deviceId:d,advanced:u,facingMode:p}=m(m({},this.settings),t);return new qe(i,r,s,o,d,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Ia(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(Ia(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&&(ee.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s}}))}});this.trackPermissions=()=>{ki("camera",t=>{this.eventBus.analytics.publish(y.permissionChange(this.type,t)),t==="denied"&&this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})})};this.handleTrackMute=()=>{l.d(this.TAG,"muted natively",document.visibilityState);let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmuteNatively=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t})),this.handleTrackUnmute(),this.eventBus.localVideoEnabled.publish({enabled:this.enabled,track:this}),this.eventBus.localVideoUnmutedNatively.publish(),yield this.setEnabled(this.enabled)});this.removeOrReplaceProcessedTrack=t=>c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack(this.processedTrack||this.nativeTrack)});this.handleVisibilityChange=()=>c(this,null,function*(){if(document.visibilityState==="hidden")this.enabledStateBeforeBackground=this.enabled,this.enabled&&(yield this.setEnabled(!1)),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{if(l.d(this.TAG,"visibility visible, restoring track state",this.enabledStateBeforeBackground),this.enabledStateBeforeBackground)try{yield this.setEnabled(!0)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.trackPermissions(),t.tracks.push(this),this.setVideoHandler(new st(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Nt(this,s),this.mediaStreamPluginsManager=new Li(s,n),this.setFirstTrackId(this.trackId),this.eventBus.localAudioUnmutedNatively.subscribe(this.handleTrackUnmute),U&&r==="regular"&&Rt()&&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 ce(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||ye(this.nativeTrack)){this.settings=r;return}else yield this.pluginsManager.waitForRestart();yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.mediaStreamPluginsManager.getPlugins().length>0?this.mediaStreamPluginsManager.getPlugins():this.pluginsManager.getPlugins()}addPlugin(t,i){return c(this,null,function*(){if(this.mediaStreamPluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSVideoPlugin and HMSMediaStreamPlugin cannot be used together");return this.pluginsManager.addPlugin(t,i)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}cleanup(){return c(this,null,function*(){var t;this.eventBus.localAudioUnmutedNatively.unsubscribe(this.handleTrackUnmute),yield this.mediaStreamPluginsManager.cleanup(),yield this.pluginsManager.cleanup(),ce(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,U&&Rt()&&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}),ee.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 Yr(t);return l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),this.settings.deviceId==="default"&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),r}catch(r){let s=yield Yr(this.settings);throw yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks(),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=Ie.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 ot="renegotiation-callback-id",_i="ion-sfu";var nt="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var Ha="https://event.100ms.live/v2/client/report",Ca="https://event-nonprod.100ms.live/v2/client/report";var Ot=Math.pow(2,31)-1,F={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"},La="2.5",Da="20250115",Re="_handraise",cs=1e3,ds=64,wa="https://whiteboard.100ms.live",_a="https://whiteboard-qa.100ms.live";var O=class a extends rt{constructor(t,i,r,s){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new ls;this.preferredLayer="high";this.disableNoneLayerRequest=!1;this.disableNoneLayerRequest=!!s,this.setVideoHandler(new st(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&&(ce(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 Q(a){if(a<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,a)})}function xe(a){if(a<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return Q(a);let e=new Worker(URL.createObjectURL(new Blob([ga],{type:"application/javascript"})));return e.postMessage(["start",a]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function Ta(){if(typeof Worker=="undefined")return{sleep:e=>Q(e)};let a=new Worker(URL.createObjectURL(new Blob([ga],{type:"application/javascript"})));return{sleep:e=>(a.postMessage(["start",e]),new Promise(t=>{a.onmessage=i=>{i.data==="tick"&&t()}}))}}function bi(a,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{a.apply(r,i)},e)}}var dn=35,ln=5,Ai=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 Oe(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 Q(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 Q(this.interval)})}sendAudioLevel(e=0){if(e=e>dn?e:0,Math.abs(this.audioLevel-e)>ln){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=de.getAudioContext(),i=t.createMediaStreamSource(e),r=t.createAnalyser();return r.fftSize=2048,i.connect(r),r}};var Ii=(t=>(t.SIP="sip",t.REGULAR="regular",t))(Ii||{});var Xr=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Xr||{});var Zr=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(Zr||{}),es=(i=>(i.REGULAR="regular",i.SCREEN="screen",i.COMPOSITE="composite",i))(es||{}),ts=(r=>(r.INITIALISED="initialised",r.STARTED="started",r.STOPPED="stopped",r.FAILED="failed",r))(ts||{}),is=(e=>(e.CAPTION="caption",e))(is||{});var Ue={f:"high",h:"medium",q:"low"};var Ri=(t=>(t.VOICE="voice",t.MUSIC="music",t))(Ri||{});var rs=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(rs||{});var z=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._audioMode="voice";this._advanced=[{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{highpassFilter:{exact:!0}},{audioMirroring:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=this._audioMode==="music"?320:e,this}deviceId(e){return this._deviceId=e,this}audioMode(e="voice"){return this._audioMode=e,this._audioMode==="music"?this._maxBitrate=320:this._maxBitrate=32,this}advanced(e){return this._advanced=e,this}build(){return new Ke(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced,this._audioMode)}},Ke=class{constructor(e,t,i,r,s,o){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s,this.audioMode=o,this.audioMode==="music"?this.maxBitrate=320:this.maxBitrate=32}toConstraints(){return{deviceId:this.deviceId,advanced:this.audioMode==="music"?[]:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var q=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new qe(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},qe=class{constructor(e,t,i,r,s,o,n,d){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=d}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId,facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Rt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var Be=class{constructor(){this._video=new q().build();this._audio=new z().build();this._screen=new q().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw S.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw S.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new it(this._video,this._audio,this._simulcast,this._screen||void 0)}},it=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=m(m({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=m(m({},this.video.toAnalyticsProperties()),e)),e}};function va(a,e){return function(i){return!(0,Ma.default)(a[i],e[i])}}var le=class a extends _e{constructor(t,i,r,s,o=new z().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this.TAG="[HMSLocalAudioTrack]";this.tracksCreated=new Set;this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){if(!this.shouldReacquireTrack()){l.d(this.TAG,`visibiltiy: ${document.visibilityState}`,`${this}`);return}if(document.visibilityState==="hidden")this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{l.d(this.TAG,"On visibile replacing track as it is not publishing");try{yield this.replaceTrackWith(this.settings)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.trackPermissions=()=>{ki("microphone",t=>{this.eventBus.analytics.publish(y.permissionChange(this.type,t)),t==="denied"&&this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})})};this.handleTrackMute=()=>{l.d(this.TAG,"muted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localAudioEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmute=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t}));try{yield this.setEnabled(this.enabled,!0),this.eventBus.localAudioUnmutedNatively.publish()}catch(i){this.eventBus.error.publish(i)}});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.shouldReacquireTrack=()=>ye(this.nativeTrack)||this.isTrackNotPublishing();this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=va(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(va(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&&(ee.updateSelection("audioInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"audioInput",selection:{deviceId:t.deviceId,groupId:s}}))}});t.tracks.push(this),this.addTrackEventListeners(i),this.trackPermissions(),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!ye(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Dt(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 zr(t);this.addTrackEventListeners(r),this.tracksCreated.add(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),yield this.updateTrack(r)}catch(r){let s=yield zr(this.settings);throw this.addTrackEventListeners(s),this.tracksCreated.add(s),yield this.updateTrack(s),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}try{yield this.pluginsManager.reprocessPlugins()}catch(r){this.eventBus.audioPluginFailed.publish(r)}})}setEnabled(t,i=!1){return c(this,null,function*(){t===this.enabled&&!i||(t&&this.shouldReacquireTrack()&&(yield this.replaceTrackWith(this.settings)),yield ce(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(ye(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 Ai(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;ce(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 Ke(i,r,s,o,n,d)}};var se=class a extends _e{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield ce(a.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var rt=class extends we{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){ca||(t.autoplay=!0),t.playsInline=!0,t.muted=!0,t.controls=!1}};var Ra=Ge(require("lodash.isequal"));var Pa=require("uuid");var wt={none:-1,low:0,medium:1,high:2},un=.5,ya=(a,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...a].sort((o,n)=>wt[o.layer]-wt[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)<un){t=d;break}}}return t};var ss=class{constructor(){this.TAG="[HMSIntersectionObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t)=>{var i;this.createObserver(),this.unobserve(e),(i=this.intersectionObserver)==null||i.observe(e),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.intersectionObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.intersectionObserver&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersection))};this.handleIntersection=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.IntersectionObserver!="undefined";return e||l.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},ka=new ss;var as=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(bi(this.handleResize,300)))};this.handleResize=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=U&&typeof window.ResizeObserver!="undefined";return e||l.w(this.TAG,"Resize Observer is not supported"),e}},Ea=new as;var st=class{constructor(e){this.track=e;this.TAG="[VideoElementManager]";this.videoElements=new Set;this.entries=new WeakMap;this.handleIntersection=e=>c(this,null,function*(){let t=getComputedStyle(e.target).visibility==="visible";this.track.enabled&&(e.isIntersecting&&t||!document.contains(e.target))?(l.d(this.TAG,"add sink intersection",`${this.track}`,this.id),this.entries.set(e.target,e.boundingClientRect),yield this.selectMaxLayer(),yield this.track.addSink(e.target)):(l.d(this.TAG,"remove sink intersection",`${this.track}`,this.id),yield this.track.removeSink(e.target))});this.handleResize=e=>c(this,null,function*(){!this.track.enabled||!(this.track instanceof O)||(this.entries.set(e.target,e.contentRect),yield this.selectMaxLayer())});this.cleanup=()=>{this.videoElements.forEach(e=>{var t,i;e.srcObject=null,(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e)}),this.videoElements.clear(),this.resizeObserver=void 0,this.intersectionObserver=void 0};this.init(),this.id=(0,Pa.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):U&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof O&&(yield this.track.setPreferredLayer(this.track.getPreferredLayer())))})}removeVideoElement(e){var t,i;this.track.removeSink(e),this.videoElements.delete(e),this.entries.delete(e),(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e),l.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){U&&(this.resizeObserver=Ea,this.intersectionObserver=ka)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:n,display:d}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,t+=e.offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&i+r>window.pageXOffset&&!o&&(n!==""?parseFloat(n)>0:!0)&&d!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof O)||this.videoElements.size===0)return;let e;for(let t of this.videoElements){let i=this.entries.get(t);if(!i)continue;let{width:r,height:s}=i;if(r===0||s===0)continue;let o=ya(this.track.getSimulcastDefinitions(),{width:r,height:s});e?e=wt[o]>wt[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 Hi=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Hi||{}),Ci=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(Ci||{});var _t=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 at=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new _t,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 _t,t&&(this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t),this.eventBus.analytics.publish(Se.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(Se.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(Se.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 ba=24,pn=320,hn=240,Nt=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.reusableWorker=Ta();this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new at(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||ba,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 xe(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||ba,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=pn,height:t=hn}=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 Li=class{constructor(e,t){this.TAG="[MediaStreamPluginsManager]";this.plugins=new Set,this.analytics=new at(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))})}};var Aa=require("uuid");var mn=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],Di=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),l.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){l.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...mn,...e].reduce((t,i)=>M(m({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var os={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default",audioMode:"voice"},ke,wi,Ie=class a{constructor(e,t,i,r,s){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=s;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=os){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),d=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let h={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};h.audio&&this.analyticsTimer.start("local_audio_track_time"),h.video&&this.analyticsTimer.start("local_video_track_time");try{l.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:h}),s=yield this.getLocalTracks(h,t,d)}catch(T){s=yield this.retryGetLocalTracks(T,t,h,d)}return h.audio&&this.analyticsTimer.end("local_audio_track_time"),h.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&s.push(o),n&&i&&!p&&s.push(n),s})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new it(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}optimizeScreenShareConstraint(e,t){return c(this,null,function*(){var s,o,n;if(typeof t.video=="boolean"||!((s=t.video)!=null&&s.width)||!((o=t.video)!=null&&o.height))return;let i=this.store.getPublishParams();if(!i||!((n=i.allowed)!=null&&n.includes("screen")))return;let r=document.createElement("video");r.srcObject=e,r.addEventListener("loadedmetadata",()=>c(this,null,function*(){let{videoWidth:d,videoHeight:u}=r,p=i.screen,h=p.width*p.height,T=d/u,g=p.width/p.height;if(T>g){let f=t.video,E=T/g,v=Math.sqrt(E);d*u>h?(f.width=d/v,f.height=u/v):(f.height=u*v,f.width=d*v),yield e.getVideoTracks()[0].applyConstraints(f)}}))})}getLocalScreen(e,t=!1){return c(this,null,function*(){var T;let i=yield this.getOrDefaultScreenshareConfig(e),r=this.getScreenshareSettings(i.videoOnly),s={video:M(m({},r==null?void 0:r.video.toConstraints(!0)),{displaySurface:i.displaySurface}),preferCurrentTab:i.preferCurrentTab,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio};if(r!=null&&r.audio){let g=(T=r==null?void 0:r.audio)==null?void 0:T.toConstraints();delete g.advanced,s.audio=M(m({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}else e!=null&&e.forceCurrentTab&&e.preferCurrentTab&&e.cropElement&&(s.audio={echoCancellation:!0,noiseSuppression:!0});let o;try{l.d("retrieving screenshare with ",{config:i},{constraints:s}),o=yield navigator.mediaDevices.getDisplayMedia(s),t&&(yield this.optimizeScreenShareConstraint(o,s))}catch(g){l.w(this.TAG,"error in getting screenshare - ",g);let f=Ne(g,"screen");throw this.eventBus.analytics.publish(y.publish({error:f,devices:this.deviceManager.getDevices(),settings:new it(r==null?void 0:r.video,r==null?void 0:r.audio,!1)})),f}let n=[],d=new ge(o),u=o.getVideoTracks()[0],p=new G(d,u,"screen",this.eventBus,r==null?void 0:r.video,this.store.getRoom());p.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(p,i.forceCurrentTab);p.isCurrentTab=g,yield p.cropTo(i.cropTarget)}catch(g){throw o.getTracks().forEach(f=>f.stop()),g}n.push(p);let h=o.getAudioTracks()[0];if(h){let g=new le(d,h,"screen",this.eventBus,r==null?void 0:r.audio,this.store.getRoom());n.push(g)}return l.v(this.TAG,"getLocalScreen",n),n})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:(0,Aa.v4)(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),l.d("setting capture handle - ",e.handle),navigator.mediaDevices.setCaptureHandleConfig(e),this.captureHandleIdentifier=e.handle)}validateCurrentTabCapture(e,t){let i=e.getCaptureHandle(),r=!!(this.captureHandleIdentifier&&(i==null?void 0:i.handle)===this.captureHandleIdentifier);if(t&&!r)throw l.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),S.TracksErrors.CurrentTabNotShared();return r}requestPermissions(){return c(this,null,function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})).getTracks().forEach(t=>t.stop())}catch(e){l.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,d,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((d=e==null?void 0:e.getSettings())==null?void 0:d.height)||240,r=1;ke||(ke=document.createElement("canvas"),ke.width=t,ke.height=i,(u=ke.getContext("2d"))==null||u.fillRect(0,0,t,i)),wi||(wi=setInterval(()=>{let p=ke==null?void 0:ke.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=ke.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=de.getAudioContext(),t=e.createOscillator(),i=e.createMediaStreamDestination();t.connect(i),t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}static cleanup(){clearInterval(wi),wi=void 0,ke=void 0}getAVTracks(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:e.audio?e.audio.toConstraints():!1,video:e.video?e.video.toConstraints():!1});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){yield this.deviceManager.init();let i=!!(!this.deviceManager.hasWebcamPermission&&e.video),r=!!(!this.deviceManager.hasMicrophonePermission&&e.audio),s=this.getErrorType(i,r);throw Ne(t,s)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new Be().video(i).audio(t).build()}isInIframe(){try{return window.self!==window.top}catch(e){return!0}}retryGetLocalTracks(e,t,i,r){return c(this,null,function*(){if(e instanceof k&&e.action==="TRACK"){this.observer.onFailure(e);let s=e.code===P.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(s){let d=new Be().video(new qe).audio(new Ke).build();l.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,d,r)}catch(u){let p=u instanceof k?u.nativeError:u,h=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let T=S.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");T.addNativeError(p),h=T}return yield this.retryGetLocalTracks(h,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,l.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(d){return l.w(this.TAG,"Fetch empty tacks failed",d),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(d),yield this.getLocalTracks(i,t,r)}}else return l.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(e),[]})}getErrorType(e,t){return e&&t?"audio, video":e?"video":t?"audio":"audio, video"}getEmptyTracks(e){let t=[];return e.audio==="empty"&&t.push(a.getEmptyAudioTrack()),e.video==="empty"&&t.push(a.getEmptyVideoTrack()),t}updateCurrentLocalTrackSettings(e){return c(this,null,function*(){let t=this.store.getLocalPeerTracks(),i=t.find(n=>n.type==="video"&&n.source==="regular"),r=t.find(n=>n.type==="audio"&&n.source==="regular"),s=t.find(n=>n.type==="video"&&n.source==="screen");e!=null&&e.video&&(yield i==null?void 0:i.setSettings(e.video)),e!=null&&e.audio&&(yield r==null?void 0:r.setSettings(e.audio));let o=this.getScreenshareSettings(!0);return o!=null&&o.video&&(yield s==null?void 0:s.setSettings(o==null?void 0:o.video)),{videoTrack:i,audioTrack:r}})}getAudioSettings(e){var o;let t=this.store.getPublishParams();if(!t||!((o=t.allowed)!=null&&o.includes("audio")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.audioTrack,s=(r==null?void 0:r.settings.deviceId)||e.audioInputDeviceId;return new z().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(s||os.audioInputDeviceId).build()}getVideoSettings(e){var n;let t=this.store.getPublishParams();if(!t||!((n=t.allowed)!=null&&n.includes("video")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.videoTrack,s=(r==null?void 0:r.settings.deviceId)||e.videoDeviceId,o=t.video;return new q().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(s||os.videoDeviceId).build()}getScreenshareSettings(e=!1){var r;let t=this.store.getPublishParams();if(!t||!((r=t.allowed)!=null&&r.includes("screen")))return null;let i=t.screen;return{video:new q().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new z().build()}}getOrDefaultScreenshareConfig(e){return c(this,null,function*(){var i;let t=Object.assign({videoOnly:!1,audioOnly:!1,forceCurrentTab:!1,preferCurrentTab:!1,selfBrowserSurface:"exclude",surfaceSwitching:"include",systemAudio:"exclude",displaySurface:"monitor"},e||{});return t.forceCurrentTab&&(t.videoOnly=!0,t.preferCurrentTab=!0,t.selfBrowserSurface="include",t.surfaceSwitching="exclude"),t.preferCurrentTab&&(t.selfBrowserSurface="include",t.displaySurface=void 0),t.cropElement&&((i=window.CropTarget)!=null&&i.fromElement)&&(t.cropTarget=yield window.CropTarget.fromElement(t.cropElement)),t})}createHMSLocalTracks(e,t,i){let r=e.find(n=>n.kind==="video"),s=e.find(n=>n.kind==="audio");i?e.forEach(n=>i==null?void 0:i.nativeStream.addTrack(n)):i=new ge(new MediaStream(e));let o=[];if(s&&(t!=null&&t.audio)){let n=new le(i,s,"regular",this.eventBus,t.audio,this.store.getRoom());o.push(n)}if(r&&(t!=null&&t.video)){let n=new G(i,r,"regular",this.eventBus,t.video,this.store.getRoom());n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function Ia(a,e){return function(i){return!(0,Ra.default)(a[i],e[i])}}var G=class a extends rt{constructor(t,i,r,s,o=new q().build(),n){super(t,i,r);this.eventBus=s;this.room=n;this._layerDefinitions=[];this.TAG="[HMSLocalVideoTrack]";this.enabledStateBeforeBackground=!1;this.isCurrentTab=!1;this.isPublished=!1;this.replaceSenderTrack=t=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){l.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(t)});this.buildNewSettings=t=>{let{width:i,height:r,codec:s,maxFramerate:o,maxBitrate:n,deviceId:d,advanced:u,facingMode:p}=m(m({},this.settings),t);return new qe(i,r,s,o,d,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Ia(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(Ia(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&&(ee.updateSelection("videoInput",{deviceId:t.deviceId,groupId:s}),this.eventBus.deviceChange.publish({isUserSelection:!0,type:"video",selection:{deviceId:t.deviceId,groupId:s}}))}});this.trackPermissions=()=>{ki("camera",t=>{this.eventBus.analytics.publish(y.permissionChange(this.type,t)),t==="denied"&&this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})})};this.handleTrackMute=()=>{l.d(this.TAG,"muted natively",document.visibilityState);let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:t})),this.eventBus.localVideoEnabled.publish({enabled:!1,track:this})};this.handleTrackUnmuteNatively=()=>c(this,null,function*(){l.d(this.TAG,"unmuted natively");let t=document.visibilityState==="hidden"?"visibility-change":"incoming-call";this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:t})),this.handleTrackUnmute(),this.eventBus.localVideoEnabled.publish({enabled:this.enabled,track:this}),this.eventBus.localVideoUnmutedNatively.publish(),yield this.setEnabled(this.enabled)});this.removeOrReplaceProcessedTrack=t=>c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack(this.processedTrack||this.nativeTrack)});this.handleVisibilityChange=()=>c(this,null,function*(){if(document.visibilityState==="hidden")this.enabledStateBeforeBackground=this.enabled,this.enabled&&(yield this.setEnabled(!1)),this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!0,reason:"visibility-change"}));else{if(l.d(this.TAG,"visibility visible, restoring track state",this.enabledStateBeforeBackground),this.enabledStateBeforeBackground)try{yield this.setEnabled(!0)}catch(t){this.eventBus.error.publish(t)}this.eventBus.analytics.publish(this.sendInterruptionEvent({started:!1,reason:"visibility-change"}))}});this.addTrackEventListeners(i),this.trackPermissions(),t.tracks.push(this),this.setVideoHandler(new st(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new Nt(this,s),this.mediaStreamPluginsManager=new Li(s,n),this.setFirstTrackId(this.trackId),this.eventBus.localAudioUnmutedNatively.subscribe(this.handleTrackUnmute),U&&r==="regular"&&Rt()&&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 ce(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||ye(this.nativeTrack)){this.settings=r;return}else yield this.pluginsManager.waitForRestart();yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.mediaStreamPluginsManager.getPlugins().length>0?this.mediaStreamPluginsManager.getPlugins():this.pluginsManager.getPlugins()}addPlugin(t,i){return c(this,null,function*(){if(this.mediaStreamPluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSVideoPlugin and HMSMediaStreamPlugin cannot be used together");return this.pluginsManager.addPlugin(t,i)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}cleanup(){return c(this,null,function*(){var t;this.eventBus.localAudioUnmutedNatively.unsubscribe(this.handleTrackUnmute),this.removeTrackEventListeners(this.nativeTrack),yield this.mediaStreamPluginsManager.cleanup(),yield this.pluginsManager.cleanup(),ce(a.prototype,this,"cleanup").call(this),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,U&&Rt()&&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}),ee.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;this.removeTrackEventListeners(i),i==null||i.stop();try{let r=yield Yr(t);return this.addTrackEventListeners(r),l.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),this.settings.deviceId==="default"&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),r}catch(r){let s=yield Yr(this.settings);throw this.addTrackEventListeners(s),yield this.replaceSender(s,this.enabled),this.nativeTrack=s,yield this.processPlugins(),this.videoHandler.updateSinks(),this.isPublished&&this.eventBus.analytics.publish(y.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=Ie.getEmptyVideoTrack(t);return this.removeTrackEventListeners(t),this.addTrackEventListeners(i),t==null||t.stop(),l.d(this.TAG,"replaceTrackWithBlank, Previous track stopped",t,"newTrack",i),i})}replaceSender(t,i){return c(this,null,function*(){i?yield this.replaceSenderTrack(this.processedTrack||t):yield this.replaceSenderTrack(t),this.stream.replaceStreamTrack(this.nativeTrack,t)})}addTrackEventListeners(t){t.addEventListener("mute",this.handleTrackMute),t.addEventListener("unmute",this.handleTrackUnmuteNatively)}removeTrackEventListeners(t){t.removeEventListener("mute",this.handleTrackMute),t.removeEventListener("unmute",this.handleTrackUnmuteNatively)}};var ot="renegotiation-callback-id",_i="ion-sfu";var nt="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var Ha="https://event.100ms.live/v2/client/report",Ca="https://event-nonprod.100ms.live/v2/client/report";var Ot=Math.pow(2,31)-1,F={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"},La="2.5",Da="20250115",Re="_handraise",cs=1e3,ds=64,wa="https://whiteboard.100ms.live",_a="https://whiteboard-qa.100ms.live";var O=class a extends rt{constructor(t,i,r,s){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new ls;this.preferredLayer="high";this.disableNoneLayerRequest=!1;this.disableNoneLayerRequest=!!s,this.setVideoHandler(new st(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&&(ce(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}
|