@webex/internal-media-core 2.17.0 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -3267,11 +3267,11 @@ shimAddIceCandidateNullOrEmpty$1(window,browserDetails);shimParameterlessSetLoca
3267
3267
  * Creates an instance of the RTCPeerConnection.
3268
3268
  *
3269
3269
  * @param configuration - Config to the RTCPeerConnection constructor.
3270
- */constructor(configuration){super();logger$3.log('PeerConnection init');this.pc=createRTCPeerConnection(configuration);this.connectionStateHandler=new ConnectionStateHandler(()=>{return {connectionState:this.pc.connectionState,iceState:this.pc.iceConnectionState};});this.connectionStateHandler.on(ConnectionStateHandler.Events.PeerConnectionStateChanged,state=>{this.emit(PeerConnection.Events.PeerConnectionStateChange,state);});this.connectionStateHandler.on(ConnectionStateHandler.Events.IceConnectionStateChanged,state=>{this.emit(PeerConnection.Events.IceConnectionStateChange,state);});// Forward the connection state related events to connection state handler
3270
+ */constructor(configuration){super();this.iceCandidates=[];logger$3.log('PeerConnection init');this.pc=createRTCPeerConnection(configuration);this.connectionStateHandler=new ConnectionStateHandler(()=>{return {connectionState:this.pc.connectionState,iceState:this.pc.iceConnectionState};});this.connectionStateHandler.on(ConnectionStateHandler.Events.PeerConnectionStateChanged,state=>{this.emit(PeerConnection.Events.PeerConnectionStateChange,state);});this.connectionStateHandler.on(ConnectionStateHandler.Events.IceConnectionStateChanged,state=>{this.emit(PeerConnection.Events.IceConnectionStateChange,state);});// Forward the connection state related events to connection state handler
3271
3271
  // eslint-disable-next-line jsdoc/require-jsdoc
3272
3272
  this.pc.oniceconnectionstatechange=()=>this.connectionStateHandler.onIceConnectionStateChange();// eslint-disable-next-line jsdoc/require-jsdoc
3273
3273
  this.pc.onconnectionstatechange=()=>this.connectionStateHandler.onPeerConnectionStateChange();// Subscribe to underlying PeerConnection events and emit them via the EventEmitter
3274
- /* eslint-disable jsdoc/require-jsdoc */this.pc.onicegatheringstatechange=ev=>{this.emit(PeerConnection.Events.IceGatheringStateChange,ev);};/* eslint-disable jsdoc/require-jsdoc */this.pc.onicecandidate=ev=>{this.emit(PeerConnection.Events.IceCandidate,ev);};this.pc.onicecandidateerror=ev=>{this.emit(PeerConnection.Events.IceCandidateError,ev);};}/**
3274
+ /* eslint-disable jsdoc/require-jsdoc */this.pc.onicegatheringstatechange=ev=>{this.emit(PeerConnection.Events.IceGatheringStateChange,ev);};/* eslint-disable jsdoc/require-jsdoc */this.pc.onicecandidate=ev=>{if(ev.candidate){this.iceCandidates.push(ev.candidate);}this.emit(PeerConnection.Events.IceCandidate,ev);};this.pc.onicecandidateerror=ev=>{this.emit(PeerConnection.Events.IceCandidateError,ev);};}/**
3275
3275
  * Get the underlying RTCPeerConnection.
3276
3276
  *
3277
3277
  * @returns The underlying RTCPeerConnection.
@@ -3288,6 +3288,10 @@ this.pc.onconnectionstatechange=()=>this.connectionStateHandler.onPeerConnection
3288
3288
  *
3289
3289
  * @returns The underlying RTCPeerConnection ICE connection state.
3290
3290
  */getIceConnectionState(){return this.connectionStateHandler.getIceConnectionState();}/**
3291
+ * Gets the list of ICE candidates that have been gathered.
3292
+ *
3293
+ * @returns An array of RTCIceCandidate objects representing the ICE candidates.
3294
+ */getIceCandidates(){return this.iceCandidates;}/**
3291
3295
  * Adds a new media track to the set of tracks which will be transmitted to the other peer.
3292
3296
  *
3293
3297
  * @param track - A MediaStreamTrack object representing the media track to add to the peer connection.
@@ -3452,7 +3456,7 @@ if(context.level===Logger.WARN&&console.warn){hdlr=console.warn;}else if(context
3452
3456
  // `options` hash can be used to configure the default logLevel and provide a custom message formatter.
3453
3457
  Logger.useDefaults=function(options){Logger.setLevel(options&&options.defaultLevel||Logger.DEBUG);Logger.setHandler(Logger.createDefaultHandler(options));};// Createa an alias to useDefaults to avoid reaking a react-hooks rule.
3454
3458
  Logger.setDefaults=Logger.useDefaults;// Export to popular environments boilerplate.
3455
- if(module.exports){module.exports=Logger;}else {Logger._prevLogger=global.Logger;Logger.noConflict=function(){global.Logger=Logger._prevLogger;return Logger;};global.Logger=Logger;}})(commonjsGlobal$2);})(logger$2);var Logger$1=logger$2.exports;Logger$1.useDefaults({defaultLevel:Logger$1.DEBUG,formatter:(messages,context)=>{messages.unshift("[".concat(context.name,"] "));}});function areNamedMediaGroupsEqual(left,right){return left.type===right.type&&left.value===right.value;}var MediaFamily;(function(MediaFamily){MediaFamily["Audio"]="AUDIO";MediaFamily["Video"]="VIDEO";})(MediaFamily||(MediaFamily={}));var MediaContent;(function(MediaContent){MediaContent["Main"]="MAIN";MediaContent["Slides"]="SLIDES";})(MediaContent||(MediaContent={}));var Policy;(function(Policy){Policy["ActiveSpeaker"]="active-speaker";Policy["ReceiverSelected"]="receiver-selected";})(Policy||(Policy={}));var MediaType;(function(MediaType){MediaType["VideoMain"]="VIDEO-MAIN";MediaType["VideoSlides"]="VIDEO-SLIDES";MediaType["AudioMain"]="AUDIO-MAIN";MediaType["AudioSlides"]="AUDIO-SLIDES";})(MediaType||(MediaType={}));function randomInteger(min,max){return Math.floor(Math.random()*(max-min+1))+min;}function generateSceneId(){return randomInteger(0,0x7fffff);}function generateCsi(mediaFamily,sceneId){var av;if(mediaFamily===MediaFamily.Audio){av=0;}else {av=1;}return sceneId<<8|av;}function getMediaType(mediaFamily,mediaContent){if(mediaFamily===MediaFamily.Video&&mediaContent===MediaContent.Main){return MediaType.VideoMain;}if(mediaFamily===MediaFamily.Video&&mediaContent===MediaContent.Slides){return MediaType.VideoSlides;}if(mediaFamily===MediaFamily.Audio&&mediaContent===MediaContent.Main){return MediaType.AudioMain;}return MediaType.AudioSlides;}function getMediaFamily(mediaType){return [MediaType.VideoMain,MediaType.VideoSlides].includes(mediaType)?MediaFamily.Video:MediaFamily.Audio;}function getMediaContent(mediaType){return [MediaType.VideoMain,MediaType.AudioMain].includes(mediaType)?MediaContent.Main:MediaContent.Slides;}var isTruthyOrZero=value=>value===0||Boolean(value);function areArraysEqual(left,right,predicate){if(left.length!==right.length){return false;}for(var i=0;i<left.length;i+=1){if(!predicate(left[i],right[i])){return false;}}return true;}class ActiveSpeakerInfo{constructor(priority,crossPriorityDuplication,crossPolicyDuplication,preferLiveVideo,namedMediaGroups){this.priority=priority;this.crossPriorityDuplication=crossPriorityDuplication;this.crossPolicyDuplication=crossPolicyDuplication;this.preferLiveVideo=preferLiveVideo;this.namedMediaGroups=namedMediaGroups;}toString(){return "ActiveSpeakerInfo(priority=".concat(this.priority,", crossPriorityDuplication=").concat(this.crossPriorityDuplication,", crossPolicyDuplication=").concat(this.crossPolicyDuplication,", preferLiveVideo=").concat(this.preferLiveVideo,"), namedMediaGroups=").concat(this.namedMediaGroups);}}function isValidActiveSpeakerInfo(msg){var maybeActiveSpeakerInfo=msg;return Boolean('priority'in maybeActiveSpeakerInfo&&'crossPriorityDuplication'in maybeActiveSpeakerInfo&&'crossPolicyDuplication'in maybeActiveSpeakerInfo&&'preferLiveVideo'in maybeActiveSpeakerInfo);}function areActiveSpeakerInfosEqual(left,right){return left.priority===right.priority&&left.crossPriorityDuplication===right.crossPriorityDuplication&&left.crossPolicyDuplication===right.crossPolicyDuplication&&left.preferLiveVideo===right.preferLiveVideo&&areArraysEqual(left.namedMediaGroups||[],right.namedMediaGroups||[],areNamedMediaGroupsEqual);}function isValidActiveSpeakerNotificationMsg(msg){var maybeActiveSpeakerNotificationMsg=msg;return Boolean(maybeActiveSpeakerNotificationMsg.seqNum&&maybeActiveSpeakerNotificationMsg.csis);}class H264Codec{constructor(maxFs,maxFps,maxMbps,maxWidth,maxHeight){this.maxFs=maxFs;this.maxFps=maxFps;this.maxMbps=maxMbps;this.maxWidth=maxWidth;this.maxHeight=maxHeight;}}function areH264CodecsEqual(left,right){if(left===undefined||right===undefined){return left===right;}return left.maxFs===right.maxFs&&left.maxFps===right.maxFps&&left.maxMbps===right.maxMbps&&left.maxWidth===right.maxWidth&&left.maxHeight===right.maxHeight;}class CodecInfo$1{constructor(payloadType,h264){this.payloadType=payloadType;this.h264=h264;}}function areCodecInfosEqual(left,right){return left.payloadType===right.payloadType&&areH264CodecsEqual(left.h264,right.h264);}var JmpMsgType;(function(JmpMsgType){JmpMsgType["MediaRequest"]="mediaRequest";JmpMsgType["MediaRequestAck"]="mediaRequestAck";JmpMsgType["MediaRequestStatus"]="mediaRequestStatus";JmpMsgType["MediaRequestStatusAck"]="mediaRequestStatusAck";JmpMsgType["SourceAdvertisement"]="sourceAdvertisement";JmpMsgType["SourceAdvertisementAck"]="sourceAdvertisementAck";JmpMsgType["ActiveSpeakerNotification"]="activeSpeakerNotification";})(JmpMsgType||(JmpMsgType={}));class JmpMsg{constructor(mediaFamily,mediaContent,payload){this.mediaFamily=mediaFamily;this.mediaContent=mediaContent;this.payload=payload;}toString(){return "JmpMsg(mediaFamily=".concat(this.mediaFamily,", mediaContent=").concat(this.mediaContent,", payload=").concat(this.payload,")");}}function isValidJmpMsgPayload(msg){var maybeJmpMsgPayload=msg;return Boolean(maybeJmpMsgPayload.msgType&&maybeJmpMsgPayload.payload);}function isValidJmpMsg(msg){var maybeJmpMsg=msg;return Boolean(maybeJmpMsg.mediaContent&&maybeJmpMsg.mediaFamily&&maybeJmpMsg.payload&&isValidJmpMsgPayload(maybeJmpMsg.payload));}class MediaRequestAckMsg{constructor(mediaRequestSeqNum){this.mediaRequestSeqNum=mediaRequestSeqNum;}toString(){return "MediaRequestAckMsg(seqNum=".concat(this.mediaRequestSeqNum,")");}}function isValidMediaRequestAckMsg(msg){var maybeMediaRequestAckMsg=msg;return Boolean(maybeMediaRequestAckMsg.mediaRequestSeqNum);}class MediaRequestMsg{constructor(seqNum,requests){this.seqNum=seqNum;this.requests=requests;}toString(){return "JmpMediaMsg(seqNum=".concat(this.seqNum,", requests=[").concat(this.requests,"])");}}function isValidMediaRequestMsg(msg){var maybeMediaRequestMsg=msg;return Boolean(maybeMediaRequestMsg.seqNum&&maybeMediaRequestMsg.requests);}class MediaRequestStatusAckMsg{constructor(mediaRequestStatusSeqNum){this.mediaRequestStatusSeqNum=mediaRequestStatusSeqNum;}toString(){return "MediaRequestStatusAckMsg(seqNum=".concat(this.mediaRequestStatusSeqNum,")");}}function isValidMediaRequestStatusAckMsg(msg){var maybeMediaRequestStatusAckMsg=msg;return Boolean(maybeMediaRequestStatusAckMsg.mediaRequestStatusSeqNum);}function isValidMidRidStreamId(obj){if(typeof obj!=='object'||obj===null)return false;var maybeMidRidStreamId=obj;return typeof maybeMidRidStreamId.mid==='string'&&(maybeMidRidStreamId.rid===undefined||typeof maybeMidRidStreamId.rid==='string')&&!('ssrc'in maybeMidRidStreamId);}function isValidSsrcStreamId(obj){if(typeof obj!=='object'||obj===null)return false;var maybeSsrcStreamId=obj;return typeof maybeSsrcStreamId.ssrc==='number'&&(maybeSsrcStreamId.rtxSsrc===undefined||typeof maybeSsrcStreamId.rtxSsrc==='number')&&!('mid'in maybeSsrcStreamId);}function isValidStreamId(obj){return isValidMidRidStreamId(obj)||isValidSsrcStreamId(obj);}function areStreamIdsEqual(id1,id2){var keys1=Object.keys(id1);var keys2=Object.keys(id2);if(keys1.length!==keys2.length){return false;}return keys1.every(key=>id1[key]===id2[key]);}function isValidStreamInfo(obj){var maybeStreamInfo=obj;return Boolean(maybeStreamInfo.id&&isValidStreamId(maybeStreamInfo.id)&&['no source','invalid source','live','avatar','bandwidth disabled','away'].includes(maybeStreamInfo.state));}function areStreamInfosEqual(left,right){return areStreamIdsEqual(left.id,right.id)&&left.state===right.state&&left.csi===right.csi;}class MediaRequestStatusMsg{constructor(seqNum,streamStates){this.seqNum=seqNum;this.streamStates=streamStates;}}function isValidMediaRequestStatusMsg(msg){var maybeMediaRequestStatusMsg=msg;return Boolean(maybeMediaRequestStatusMsg.seqNum)&&maybeMediaRequestStatusMsg.streamStates&&maybeMediaRequestStatusMsg.streamStates.every(streamInfo=>isValidStreamInfo(streamInfo));}class ReceiverSelectedInfo{constructor(csi){this.csi=csi;}toString(){return "ReceiverSelectedInfo(csi=".concat(this.csi,")");}}function isValidReceiverSelectedInfo(msg){var maybeReceiverSelectedInfo=msg;return Boolean(maybeReceiverSelectedInfo.csi);}function areReceiverSelectedInfosEqual(left,right){return left.csi===right.csi;}function arePolicySpecificInfosEqual(left,right){if(isValidActiveSpeakerInfo(left)){if(!isValidActiveSpeakerInfo(right)){return false;}return areActiveSpeakerInfosEqual(left,right);}if(isValidReceiverSelectedInfo(left)){if(!isValidReceiverSelectedInfo(right)){return false;}return areReceiverSelectedInfosEqual(left,right);}throw new Error('Invalid PolicySpecificInfo');}class SourceAdvertisementAckMsg{constructor(sourceAdvertisementSeqNum){this.sourceAdvertisementSeqNum=sourceAdvertisementSeqNum;}toString(){return "SourceAdvertisementAckMsg(sourceAdvertisementSeqNum=".concat(this.sourceAdvertisementSeqNum,")");}}function isValidSourceAdvertisementAckMsg(msg){var maybeSourceAdvertisementAckMsg=msg;return Boolean(maybeSourceAdvertisementAckMsg.sourceAdvertisementSeqNum);}class SourceAdvertisementMsg{constructor(seqNum,numTotalSources,numLiveSources,namedMediaGroups,videoContentHint){this.seqNum=seqNum;this.numTotalSources=numTotalSources;this.numLiveSources=numLiveSources;this.namedMediaGroups=namedMediaGroups;this.videoContentHint=videoContentHint;}toString(){return "SourceAdvertisement(seqNum=".concat(this.seqNum,", numTotalSources=").concat(this.numTotalSources,", numLiveSources=").concat(this.numLiveSources,", namedMediaGroups=").concat(this.namedMediaGroups,", videoContentHint=").concat(this.videoContentHint);}}function isValidSourceAdvertisementMsg(msg){var maybeSourceAdvertisementMsg=msg;return Boolean(maybeSourceAdvertisementMsg.seqNum&&isTruthyOrZero(maybeSourceAdvertisementMsg.numTotalSources)&&isTruthyOrZero(maybeSourceAdvertisementMsg.numLiveSources));}function areSourceAdvertisementMsgsEqual(sourceAdvertisementMsg1,sourceAdvertisementMsg2){return sourceAdvertisementMsg1.numLiveSources===sourceAdvertisementMsg2.numLiveSources&&sourceAdvertisementMsg1.numTotalSources===sourceAdvertisementMsg2.numTotalSources&&areArraysEqual(sourceAdvertisementMsg1.namedMediaGroups||[],sourceAdvertisementMsg2.namedMediaGroups||[],areNamedMediaGroupsEqual)&&sourceAdvertisementMsg1.videoContentHint===sourceAdvertisementMsg2.videoContentHint;}class StreamRequest$1{constructor(policy,policySpecificInfo,ids,maxPayloadBitsPerSecond){var codecInfos=arguments.length>4&&arguments[4]!==undefined?arguments[4]:[];this.policy=policy;this.policySpecificInfo=policySpecificInfo;this.ids=ids;this.maxPayloadBitsPerSecond=maxPayloadBitsPerSecond;this.codecInfos=codecInfos;}toString(){return "Request(policy=".concat(this.policy,", info=").concat(this.policySpecificInfo,", ids=[").concat(this.ids,"], maxPayloadBitsPerSecond=[").concat(this.maxPayloadBitsPerSecond,"], codecInfos=[").concat(this.codecInfos,"])");}}function areStreamRequestsEqual(left,right){if(left.policy!==right.policy){return false;}if(!arePolicySpecificInfosEqual(left.policySpecificInfo,right.policySpecificInfo)){return false;}if(!areArraysEqual(left.ids,right.ids,areStreamIdsEqual)){return false;}if(left.maxPayloadBitsPerSecond!==right.maxPayloadBitsPerSecond){return false;}return areArraysEqual(left.codecInfos,right.codecInfos,areCodecInfosEqual);}class RetransmitHandler{constructor(msg,maxNumRetransmits,retransmitIntervalMs,transmitCallback,expirationCallback){this.timerHandle=undefined;this.msg=msg;this.numRetransmitsLeft=maxNumRetransmits;this.retransmitIntervalMs=retransmitIntervalMs;this.transmitCallback=transmitCallback;this.expirationCallback=expirationCallback;this.scheduleTimer();}onTimer(){var _a;if(this.numRetransmitsLeft>0){--this.numRetransmitsLeft;this.transmitCallback(this.msg);this.scheduleTimer();}else {(_a=this.expirationCallback)===null||_a===void 0?void 0:_a.call(this,this.msg);}}scheduleTimer(){this.timerHandle=window.setTimeout(()=>this.onTimer(),this.retransmitIntervalMs);}cancel(){if(this.timerHandle){clearTimeout(this.timerHandle);}this.timerHandle=undefined;}}var JmpSessionEvents;(function(JmpSessionEvents){JmpSessionEvents["ActiveSpeaker"]="active-speaker";JmpSessionEvents["MediaRequestReceived"]="media-request-received";JmpSessionEvents["MediaRequestStatusReceived"]="media-request-status-received";JmpSessionEvents["SourceAdvertisementReceived"]="source-advertisement-received";})(JmpSessionEvents||(JmpSessionEvents={}));class JmpSession extends EventEmitter$6{constructor(mediaFamily,mediaContent){var maxNumRetransmits=arguments.length>2&&arguments[2]!==undefined?arguments[2]:200;var retransmitIntervalMs=arguments.length>3&&arguments[3]!==undefined?arguments[3]:250;super();this.currMediaRequestSeqNum=1;this.currSourceAdvertisementSeqNum=1;this.currMediaRequestStatusSeqNum=1;this.txCallback=undefined;this.lastSentMediaRequest=undefined;this.lastSentMediaRequestAck=undefined;this.lastReceivedMediaRequest=undefined;this.mediaFamily=mediaFamily;this.mediaContent=mediaContent;this.logger=Logger$1.get("JmpSession ".concat(this.mediaFamily,"-").concat(this.mediaContent));this.maxNumRetransmits=maxNumRetransmits;this.retransmitIntervalMs=retransmitIntervalMs;}getLogger(){return this.logger;}sendRequests(requests){var _a;var mediaRequestMsg=new MediaRequestMsg(this.currMediaRequestSeqNum,requests);if(!this.lastSentMediaRequest||!areArraysEqual(this.lastSentMediaRequest.msg.requests,requests,areStreamRequestsEqual)){this.sendJmpMsg(JmpMsgType.MediaRequest,mediaRequestMsg);(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.cancel();this.lastSentMediaRequest=new RetransmitHandler(mediaRequestMsg,this.maxNumRetransmits,this.retransmitIntervalMs,()=>{this.logger.info("Retransmitting previously sent MediaRequest...");this.sendJmpMsg(JmpMsgType.MediaRequest,mediaRequestMsg);},expiredJmpMsg=>{this.logger.warn("Retransmits for message expired: ".concat(expiredJmpMsg));});this.currMediaRequestSeqNum++;}else {this.logger.info("Duplicate MediaRequest detected and will not be sent: ".concat(mediaRequestMsg));}}sendSourceAdvertisement(numTotalSources,numLiveSources,namedMediaGroups,videoContentHint){var _a;var sourceAdvertisementMsg=new SourceAdvertisementMsg(this.currSourceAdvertisementSeqNum,numTotalSources,numLiveSources,namedMediaGroups,videoContentHint);if(!this.lastSentSourceAdvertisement||!areSourceAdvertisementMsgsEqual(this.lastSentSourceAdvertisement.msg,sourceAdvertisementMsg)){this.sendJmpMsg(JmpMsgType.SourceAdvertisement,sourceAdvertisementMsg);(_a=this.lastSentSourceAdvertisement)===null||_a===void 0?void 0:_a.cancel();this.lastSentSourceAdvertisement=new RetransmitHandler(sourceAdvertisementMsg,this.maxNumRetransmits,this.retransmitIntervalMs,()=>{this.logger.info("Retransmitting previously sent SourceAdvertisement...");this.sendJmpMsg(JmpMsgType.SourceAdvertisement,sourceAdvertisementMsg);},expiredMsg=>{this.logger.warn("Retransmits for message expired: ",expiredMsg);});this.currSourceAdvertisementSeqNum++;}else {this.logger.info("Duplicate SourceAdvertisement detected and will not be sent: ",sourceAdvertisementMsg);}}sendMediaRequestStatus(streamStates){var _a,_b;var filteredStreamStates=streamStates.filter(streamState=>{var _a;return (_a=this.lastReceivedMediaRequest)===null||_a===void 0?void 0:_a.requests.some(req=>req.ids.find(streamId=>areStreamIdsEqual(streamId,streamState.id)));});var mediaRequestStatus=new MediaRequestStatusMsg(this.currMediaRequestStatusSeqNum,filteredStreamStates);if(!((_a=this.lastSentMediaRequestStatus)===null||_a===void 0?void 0:_a.msg.streamStates)||!areArraysEqual(filteredStreamStates,this.lastSentMediaRequestStatus.msg.streamStates,areStreamInfosEqual)){this.sendJmpMsg(JmpMsgType.MediaRequestStatus,mediaRequestStatus);(_b=this.lastSentMediaRequestStatus)===null||_b===void 0?void 0:_b.cancel();this.lastSentMediaRequestStatus=new RetransmitHandler(mediaRequestStatus,this.maxNumRetransmits,this.retransmitIntervalMs,()=>{this.logger.info("Retransmitting previously sent MediaRequestStatus...");this.sendJmpMsg(JmpMsgType.MediaRequestStatus,mediaRequestStatus);},expiredMsg=>{this.logger.warn("Retransmits for message expired: ",expiredMsg);});this.currMediaRequestStatusSeqNum++;}else {this.logger.info("Duplicate MediaRequestStatus detected and will not be sent: ",mediaRequestStatus);}}receive(jmpMsg){if(jmpMsg.mediaContent!==this.mediaContent||jmpMsg.mediaFamily!==this.mediaFamily){this.logger.error("JmpMsg ".concat(JSON.stringify(jmpMsg)," sent to incorrect JmpSession"));return;}this.logger.debug("Received JmpMsg",JSON.stringify(jmpMsg));var{payload}=jmpMsg;if(payload.msgType===JmpMsgType.MediaRequest){var mediaRequestMsg=payload.payload;if(!isValidMediaRequestMsg(mediaRequestMsg)){this.logger.error("Received invalid MediaRequest:",JSON.stringify(mediaRequestMsg));return;}this.handleIncomingMediaRequest(mediaRequestMsg);}else if(payload.msgType===JmpMsgType.MediaRequestAck){var mediaRequestAckMsg=payload.payload;if(!isValidMediaRequestAckMsg(mediaRequestAckMsg)){this.logger.error("Received invalid MediaRequest ACK:",JSON.stringify(mediaRequestAckMsg));return;}this.handleIncomingMediaRequestAck(mediaRequestAckMsg);}else if(payload.msgType===JmpMsgType.ActiveSpeakerNotification){var activeSpeakerNotification=payload.payload;if(!isValidActiveSpeakerNotificationMsg(activeSpeakerNotification)){this.logger.info("Received invalid Active Speaker Notification:",JSON.stringify(activeSpeakerNotification));return;}this.handleIncomingActiveSpeakerNotification(activeSpeakerNotification);}else if(payload.msgType===JmpMsgType.SourceAdvertisement){var sourceAdvertisement=payload.payload;if(!isValidSourceAdvertisementMsg(sourceAdvertisement)){this.logger.error("Received invalid SourceAdvertisementMsg:",JSON.stringify(sourceAdvertisement));return;}this.handleIncomingSourceAdvertisement(sourceAdvertisement);}else if(payload.msgType===JmpMsgType.SourceAdvertisementAck){var sourceAdvertisementAck=payload.payload;if(!isValidSourceAdvertisementAckMsg(sourceAdvertisementAck)){this.logger.error("Received invalid SourceAdvertisementAckMsg:",JSON.stringify(sourceAdvertisementAck));return;}this.handleIncomingSourceAdvertisementAck(sourceAdvertisementAck);}else if(payload.msgType===JmpMsgType.MediaRequestStatus){var mediaRequestStatus=payload.payload;if(!isValidMediaRequestStatusMsg(mediaRequestStatus)){this.logger.error("Received invalid MediaRequestStatusMsg:",JSON.stringify(mediaRequestStatus));return;}this.handleIncomingMediaRequestStatus(mediaRequestStatus);}else if(payload.msgType===JmpMsgType.MediaRequestStatusAck){var mediaRequestStatusAck=payload.payload;if(!isValidMediaRequestStatusAckMsg(mediaRequestStatusAck)){this.logger.error("Received invalid MediaRequestStatusAckMsg:",JSON.stringify(mediaRequestStatusAck));return;}this.handleIncomingMediaRequestStatusAck(mediaRequestStatusAck);}else {this.logger.error("Received unknown JmpMsg");}}setTxCallback(callback){this.txCallback=callback;}close(){var _a,_b,_c;this.logger.info("closing");(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.cancel();(_b=this.lastSentMediaRequestStatus)===null||_b===void 0?void 0:_b.cancel();(_c=this.lastSentSourceAdvertisement)===null||_c===void 0?void 0:_c.cancel();}sendJmpMsg(msgType,payload){var _a;var jmpMsg=new JmpMsg(this.mediaFamily,this.mediaContent,{msgType,payload});(_a=this.txCallback)===null||_a===void 0?void 0:_a.call(this,jmpMsg);}handleIncomingMediaRequest(mediaRequestMsg){var _a;if(this.lastReceivedMediaRequest&&mediaRequestMsg.seqNum<((_a=this.lastReceivedMediaRequest)===null||_a===void 0?void 0:_a.seqNum)){this.logger.info("Received old MediaRequest, ignoring");}else if(this.lastReceivedMediaRequest&&mediaRequestMsg.seqNum===this.lastReceivedMediaRequest.seqNum){if(this.lastSentMediaRequestAck){this.logger.info("Received duplicate MediaRequest, re-sending ACK");this.sendJmpMsg(JmpMsgType.MediaRequestAck,this.lastSentMediaRequestAck);}else {this.logger.warn("Received duplicate MediaRequest, but there was no ACK previously sent");}}else {this.logger.info("Received new MediaRequest, sending ACK");var mediaRequestAck=new MediaRequestAckMsg(mediaRequestMsg.seqNum);this.lastReceivedMediaRequest=mediaRequestMsg;this.lastSentMediaRequestAck=mediaRequestAck;this.sendJmpMsg(JmpMsgType.MediaRequestAck,mediaRequestAck);this.emit(JmpSessionEvents.MediaRequestReceived,mediaRequestMsg);}}handleIncomingMediaRequestAck(mediaRequestAckMsg){var _a,_b,_c;if(mediaRequestAckMsg.mediaRequestSeqNum===((_b=(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent MediaRequest");(_c=this.lastSentMediaRequest)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old MediaRequest");}}handleIncomingActiveSpeakerNotification(activeSpeakerNotification){this.logger.debug("Received Active Speaker Notification:",activeSpeakerNotification);this.emit(JmpSessionEvents.ActiveSpeaker,activeSpeakerNotification);}handleIncomingSourceAdvertisement(sourceAdvertisement){if(this.lastReceivedSourceAdvertisement&&sourceAdvertisement.seqNum<this.lastReceivedSourceAdvertisement.seqNum){this.logger.info("Received old SourceAdvertisement, ignoring");}else if(this.lastReceivedSourceAdvertisement&&sourceAdvertisement.seqNum===this.lastReceivedSourceAdvertisement.seqNum){if(this.lastSentSourceAdvertisementAck){this.logger.info("Received duplicate SourceAdvertisement, re-sending ACK");this.sendJmpMsg(JmpMsgType.SourceAdvertisementAck,this.lastSentSourceAdvertisementAck);}else {this.logger.warn("Received duplicate SourceAdvertisement, but there was no ACK previously sent");}}else {this.logger.info("Received new SourceAdvertisement, sending ACK");var sourceAdvertisementAck=new SourceAdvertisementAckMsg(sourceAdvertisement.seqNum);this.lastReceivedSourceAdvertisement=sourceAdvertisement;this.lastSentSourceAdvertisementAck=sourceAdvertisementAck;this.sendJmpMsg(JmpMsgType.SourceAdvertisementAck,sourceAdvertisementAck);this.emit(JmpSessionEvents.SourceAdvertisementReceived,sourceAdvertisement);}}handleIncomingSourceAdvertisementAck(sourceAdvertisementAck){var _a,_b,_c;if(sourceAdvertisementAck.sourceAdvertisementSeqNum===((_b=(_a=this.lastSentSourceAdvertisement)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent SourceAdvertisement");(_c=this.lastSentSourceAdvertisement)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old SourceAdvertisement");}}handleIncomingMediaRequestStatus(mediaRequestStatus){if(this.lastReceivedMediaRequestStatus&&mediaRequestStatus.seqNum<this.lastReceivedMediaRequestStatus.seqNum){this.logger.info("Received old MediaRequestStatus, ignoring");}else if(this.lastReceivedMediaRequestStatus&&mediaRequestStatus.seqNum===this.lastReceivedMediaRequestStatus.seqNum){if(this.lastSentMediaRequestStatusAck){this.logger.info("Received duplicate MediaRequestStatus, re-sending ACK");this.sendJmpMsg(JmpMsgType.MediaRequestStatusAck,this.lastSentMediaRequestStatusAck);}else {this.logger.warn("Received duplicate MediaRequestStatus, but there was no ACK previously sent");}}else {this.logger.info("Received new MediaRequestStatus, sending ACK");var mediaRequestStatusAck=new MediaRequestStatusAckMsg(mediaRequestStatus.seqNum);this.lastReceivedMediaRequestStatus=mediaRequestStatus;this.lastSentMediaRequestStatusAck=mediaRequestStatusAck;this.sendJmpMsg(JmpMsgType.MediaRequestStatusAck,mediaRequestStatusAck);this.emit(JmpSessionEvents.MediaRequestStatusReceived,mediaRequestStatus);}}handleIncomingMediaRequestStatusAck(mediaRequestStatusAck){var _a,_b,_c;if(mediaRequestStatusAck.mediaRequestStatusSeqNum===((_b=(_a=this.lastSentMediaRequestStatus)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent MediaRequestStatus");(_c=this.lastSentMediaRequestStatus)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old MediaRequestStatus");}}}var WcmeErrorType;(function(WcmeErrorType){WcmeErrorType["CREATE_OFFER_FAILED"]="CREATE_OFFER_FAILED";WcmeErrorType["SET_ANSWER_FAILED"]="SET_ANSWER_FAILED";WcmeErrorType["OFFER_ANSWER_MISMATCH"]="OFFER_ANSWER_MISMATCH";WcmeErrorType["SDP_MUNGE_FAILED"]="SDP_MUNGE_FAILED";WcmeErrorType["SDP_MUNGE_MISSING_CODECS"]="SDP_MUNGE_MISSING_CODECS";WcmeErrorType["INVALID_STREAM_REQUEST"]="INVALID_STREAM_REQUEST";WcmeErrorType["GET_TRANSCEIVER_FAILED"]="GET_TRANSCEIVER_FAILED";WcmeErrorType["GET_MAX_BITRATE_FAILED"]="GET_MAX_BITRATE_FAILED";WcmeErrorType["GET_PAYLOAD_TYPE_FAILED"]="GET_PAYLOAD_TYPE_FAILED";WcmeErrorType["SET_NMG_FAILED"]="SET_NMG_FAILED";WcmeErrorType["DATA_CHANNEL_SEND_FAILED"]="DATA_CHANNEL_SEND_FAILED";WcmeErrorType["RENEW_PEER_CONNECTION_FAILED"]="RENEW_PEER_CONNECTION_FAILED";})(WcmeErrorType||(WcmeErrorType={}));class WcmeError{constructor(type){var message=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';this.type=type;this.message=message;}}var commonjsGlobal$1=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global$1!=='undefined'?global$1:typeof self!=='undefined'?self:{};var logger$1={exports:{}};/*!
3459
+ if(module.exports){module.exports=Logger;}else {Logger._prevLogger=global.Logger;Logger.noConflict=function(){global.Logger=Logger._prevLogger;return Logger;};global.Logger=Logger;}})(commonjsGlobal$2);})(logger$2);var Logger$1=logger$2.exports;Logger$1.useDefaults({defaultLevel:Logger$1.DEBUG,formatter:(messages,context)=>{messages.unshift("[".concat(context.name,"] "));}});function areNamedMediaGroupsEqual(left,right){return left.type===right.type&&left.value===right.value;}var MediaFamily;(function(MediaFamily){MediaFamily["Audio"]="AUDIO";MediaFamily["Video"]="VIDEO";})(MediaFamily||(MediaFamily={}));var MediaContent;(function(MediaContent){MediaContent["Main"]="MAIN";MediaContent["Slides"]="SLIDES";})(MediaContent||(MediaContent={}));var Policy;(function(Policy){Policy["ActiveSpeaker"]="active-speaker";Policy["ReceiverSelected"]="receiver-selected";})(Policy||(Policy={}));var MediaType;(function(MediaType){MediaType["VideoMain"]="VIDEO-MAIN";MediaType["VideoSlides"]="VIDEO-SLIDES";MediaType["AudioMain"]="AUDIO-MAIN";MediaType["AudioSlides"]="AUDIO-SLIDES";})(MediaType||(MediaType={}));function randomInteger(min,max){return Math.floor(Math.random()*(max-min+1))+min;}function generateSceneId(){return randomInteger(0,0x7fffff);}function generateCsi(mediaFamily,sceneId){var av;if(mediaFamily===MediaFamily.Audio){av=0;}else {av=1;}return sceneId<<8|av;}function getMediaType(mediaFamily,mediaContent){if(mediaFamily===MediaFamily.Video&&mediaContent===MediaContent.Main){return MediaType.VideoMain;}if(mediaFamily===MediaFamily.Video&&mediaContent===MediaContent.Slides){return MediaType.VideoSlides;}if(mediaFamily===MediaFamily.Audio&&mediaContent===MediaContent.Main){return MediaType.AudioMain;}return MediaType.AudioSlides;}function getMediaFamily(mediaType){return [MediaType.VideoMain,MediaType.VideoSlides].includes(mediaType)?MediaFamily.Video:MediaFamily.Audio;}function getMediaContent(mediaType){return [MediaType.VideoMain,MediaType.AudioMain].includes(mediaType)?MediaContent.Main:MediaContent.Slides;}var isTruthyOrZero=value=>value===0||Boolean(value);function areArraysEqual(left,right,predicate){if(left.length!==right.length){return false;}for(var i=0;i<left.length;i+=1){if(!predicate(left[i],right[i])){return false;}}return true;}class ActiveSpeakerInfo{constructor(priority,crossPriorityDuplication,crossPolicyDuplication,preferLiveVideo,namedMediaGroups){this.priority=priority;this.crossPriorityDuplication=crossPriorityDuplication;this.crossPolicyDuplication=crossPolicyDuplication;this.preferLiveVideo=preferLiveVideo;this.namedMediaGroups=namedMediaGroups;}toString(){return "ActiveSpeakerInfo(priority=".concat(this.priority,", crossPriorityDuplication=").concat(this.crossPriorityDuplication,", crossPolicyDuplication=").concat(this.crossPolicyDuplication,", preferLiveVideo=").concat(this.preferLiveVideo,"), namedMediaGroups=").concat(this.namedMediaGroups);}}function isValidActiveSpeakerInfo(msg){var maybeActiveSpeakerInfo=msg;return Boolean('priority'in maybeActiveSpeakerInfo&&'crossPriorityDuplication'in maybeActiveSpeakerInfo&&'crossPolicyDuplication'in maybeActiveSpeakerInfo&&'preferLiveVideo'in maybeActiveSpeakerInfo);}function areActiveSpeakerInfosEqual(left,right){return left.priority===right.priority&&left.crossPriorityDuplication===right.crossPriorityDuplication&&left.crossPolicyDuplication===right.crossPolicyDuplication&&left.preferLiveVideo===right.preferLiveVideo&&areArraysEqual(left.namedMediaGroups||[],right.namedMediaGroups||[],areNamedMediaGroupsEqual);}function isValidActiveSpeakerNotificationMsg(msg){var maybeActiveSpeakerNotificationMsg=msg;return Boolean(maybeActiveSpeakerNotificationMsg.seqNum&&maybeActiveSpeakerNotificationMsg.csis);}class H264Codec{constructor(maxFs,maxFps,maxMbps,maxWidth,maxHeight){this.maxFs=maxFs;this.maxFps=maxFps;this.maxMbps=maxMbps;this.maxWidth=maxWidth;this.maxHeight=maxHeight;}}function areH264CodecsEqual(left,right){if(left===undefined||right===undefined){return left===right;}return left.maxFs===right.maxFs&&left.maxFps===right.maxFps&&left.maxMbps===right.maxMbps&&left.maxWidth===right.maxWidth&&left.maxHeight===right.maxHeight;}class CodecInfo$1{constructor(payloadType,h264){this.payloadType=payloadType;this.h264=h264;}}function areCodecInfosEqual(left,right){return left.payloadType===right.payloadType&&areH264CodecsEqual(left.h264,right.h264);}var JmpMsgType;(function(JmpMsgType){JmpMsgType["MediaRequest"]="mediaRequest";JmpMsgType["MediaRequestAck"]="mediaRequestAck";JmpMsgType["MediaRequestStatus"]="mediaRequestStatus";JmpMsgType["MediaRequestStatusAck"]="mediaRequestStatusAck";JmpMsgType["SourceAdvertisement"]="sourceAdvertisement";JmpMsgType["SourceAdvertisementAck"]="sourceAdvertisementAck";JmpMsgType["ActiveSpeakerNotification"]="activeSpeakerNotification";})(JmpMsgType||(JmpMsgType={}));class JmpMsg{constructor(mediaFamily,mediaContent,payload){this.mediaFamily=mediaFamily;this.mediaContent=mediaContent;this.payload=payload;}toString(){return "JmpMsg(mediaFamily=".concat(this.mediaFamily,", mediaContent=").concat(this.mediaContent,", payload=").concat(this.payload,")");}}function isValidJmpMsgPayload(msg){var maybeJmpMsgPayload=msg;return Boolean(maybeJmpMsgPayload.msgType&&maybeJmpMsgPayload.payload);}function isValidJmpMsg(msg){var maybeJmpMsg=msg;return Boolean(maybeJmpMsg.mediaContent&&maybeJmpMsg.mediaFamily&&maybeJmpMsg.payload&&isValidJmpMsgPayload(maybeJmpMsg.payload));}class MediaRequestAckMsg{constructor(mediaRequestSeqNum){this.mediaRequestSeqNum=mediaRequestSeqNum;}toString(){return "MediaRequestAckMsg(seqNum=".concat(this.mediaRequestSeqNum,")");}}function isValidMediaRequestAckMsg(msg){var maybeMediaRequestAckMsg=msg;return Boolean(maybeMediaRequestAckMsg.mediaRequestSeqNum);}class MediaRequestMsg{constructor(seqNum,requests){this.seqNum=seqNum;this.requests=requests;}toString(){return "JmpMediaMsg(seqNum=".concat(this.seqNum,", requests=[").concat(this.requests,"])");}}function isValidMediaRequestMsg(msg){var maybeMediaRequestMsg=msg;return Boolean(maybeMediaRequestMsg.seqNum&&maybeMediaRequestMsg.requests);}class MediaRequestStatusAckMsg{constructor(mediaRequestStatusSeqNum){this.mediaRequestStatusSeqNum=mediaRequestStatusSeqNum;}toString(){return "MediaRequestStatusAckMsg(seqNum=".concat(this.mediaRequestStatusSeqNum,")");}}function isValidMediaRequestStatusAckMsg(msg){var maybeMediaRequestStatusAckMsg=msg;return Boolean(maybeMediaRequestStatusAckMsg.mediaRequestStatusSeqNum);}function isValidMidRidStreamId(obj){if(typeof obj!=='object'||obj===null)return false;var maybeMidRidStreamId=obj;return typeof maybeMidRidStreamId.mid==='string'&&(maybeMidRidStreamId.rid===undefined||typeof maybeMidRidStreamId.rid==='string')&&!('ssrc'in maybeMidRidStreamId);}function isValidSsrcStreamId(obj){if(typeof obj!=='object'||obj===null)return false;var maybeSsrcStreamId=obj;return typeof maybeSsrcStreamId.ssrc==='number'&&(maybeSsrcStreamId.rtxSsrc===undefined||typeof maybeSsrcStreamId.rtxSsrc==='number')&&!('mid'in maybeSsrcStreamId);}function isValidStreamId(obj){return isValidMidRidStreamId(obj)||isValidSsrcStreamId(obj);}function areStreamIdsEqual(id1,id2){var keys1=Object.keys(id1);var keys2=Object.keys(id2);if(keys1.length!==keys2.length){return false;}return keys1.every(key=>id1[key]===id2[key]);}function isValidStreamInfo(obj){var maybeStreamInfo=obj;return Boolean(maybeStreamInfo.id&&isValidStreamId(maybeStreamInfo.id)&&['no source','invalid source','live','avatar','bandwidth disabled','away'].includes(maybeStreamInfo.state));}function areStreamInfosEqual(left,right){return areStreamIdsEqual(left.id,right.id)&&left.state===right.state&&left.csi===right.csi;}class MediaRequestStatusMsg{constructor(seqNum,streamStates){this.seqNum=seqNum;this.streamStates=streamStates;}}function isValidMediaRequestStatusMsg(msg){var maybeMediaRequestStatusMsg=msg;return Boolean(maybeMediaRequestStatusMsg.seqNum)&&maybeMediaRequestStatusMsg.streamStates&&maybeMediaRequestStatusMsg.streamStates.every(streamInfo=>isValidStreamInfo(streamInfo));}class ReceiverSelectedInfo{constructor(csi){this.csi=csi;}toString(){return "ReceiverSelectedInfo(csi=".concat(this.csi,")");}}function isValidReceiverSelectedInfo(msg){var maybeReceiverSelectedInfo=msg;return Boolean(maybeReceiverSelectedInfo.csi);}function areReceiverSelectedInfosEqual(left,right){return left.csi===right.csi;}function arePolicySpecificInfosEqual(left,right){if(isValidActiveSpeakerInfo(left)){if(!isValidActiveSpeakerInfo(right)){return false;}return areActiveSpeakerInfosEqual(left,right);}if(isValidReceiverSelectedInfo(left)){if(!isValidReceiverSelectedInfo(right)){return false;}return areReceiverSelectedInfosEqual(left,right);}throw new Error('Invalid PolicySpecificInfo');}class SourceAdvertisementAckMsg{constructor(sourceAdvertisementSeqNum){this.sourceAdvertisementSeqNum=sourceAdvertisementSeqNum;}toString(){return "SourceAdvertisementAckMsg(sourceAdvertisementSeqNum=".concat(this.sourceAdvertisementSeqNum,")");}}function isValidSourceAdvertisementAckMsg(msg){var maybeSourceAdvertisementAckMsg=msg;return Boolean(maybeSourceAdvertisementAckMsg.sourceAdvertisementSeqNum);}class SourceAdvertisementMsg{constructor(seqNum,numTotalSources,numLiveSources,namedMediaGroups,videoContentHint){this.seqNum=seqNum;this.numTotalSources=numTotalSources;this.numLiveSources=numLiveSources;this.namedMediaGroups=namedMediaGroups;this.videoContentHint=videoContentHint;}toString(){return "SourceAdvertisement(seqNum=".concat(this.seqNum,", numTotalSources=").concat(this.numTotalSources,", numLiveSources=").concat(this.numLiveSources,", namedMediaGroups=").concat(this.namedMediaGroups,", videoContentHint=").concat(this.videoContentHint);}}function isValidSourceAdvertisementMsg(msg){var maybeSourceAdvertisementMsg=msg;return Boolean(maybeSourceAdvertisementMsg.seqNum&&isTruthyOrZero(maybeSourceAdvertisementMsg.numTotalSources)&&isTruthyOrZero(maybeSourceAdvertisementMsg.numLiveSources));}function areSourceAdvertisementMsgsEqual(sourceAdvertisementMsg1,sourceAdvertisementMsg2){return sourceAdvertisementMsg1.numLiveSources===sourceAdvertisementMsg2.numLiveSources&&sourceAdvertisementMsg1.numTotalSources===sourceAdvertisementMsg2.numTotalSources&&areArraysEqual(sourceAdvertisementMsg1.namedMediaGroups||[],sourceAdvertisementMsg2.namedMediaGroups||[],areNamedMediaGroupsEqual)&&sourceAdvertisementMsg1.videoContentHint===sourceAdvertisementMsg2.videoContentHint;}class StreamRequest$1{constructor(policy,policySpecificInfo,ids,maxPayloadBitsPerSecond){var codecInfos=arguments.length>4&&arguments[4]!==undefined?arguments[4]:[];this.policy=policy;this.policySpecificInfo=policySpecificInfo;this.ids=ids;this.maxPayloadBitsPerSecond=maxPayloadBitsPerSecond;this.codecInfos=codecInfos;}toString(){return "Request(policy=".concat(this.policy,", info=").concat(this.policySpecificInfo,", ids=[").concat(this.ids,"], maxPayloadBitsPerSecond=[").concat(this.maxPayloadBitsPerSecond,"], codecInfos=[").concat(this.codecInfos,"])");}}function areStreamRequestsEqual(left,right){if(left.policy!==right.policy){return false;}if(!arePolicySpecificInfosEqual(left.policySpecificInfo,right.policySpecificInfo)){return false;}if(!areArraysEqual(left.ids,right.ids,areStreamIdsEqual)){return false;}if(left.maxPayloadBitsPerSecond!==right.maxPayloadBitsPerSecond){return false;}return areArraysEqual(left.codecInfos,right.codecInfos,areCodecInfosEqual);}class RetransmitHandler{constructor(msg,maxNumRetransmits,retransmitIntervalMs,transmitCallback,expirationCallback){this.timerHandle=undefined;this.msg=msg;this.numRetransmitsLeft=maxNumRetransmits;this.retransmitIntervalMs=retransmitIntervalMs;this.transmitCallback=transmitCallback;this.expirationCallback=expirationCallback;this.scheduleTimer();}onTimer(){var _a;if(this.numRetransmitsLeft>0){--this.numRetransmitsLeft;this.transmitCallback(this.msg);this.scheduleTimer();}else {(_a=this.expirationCallback)===null||_a===void 0?void 0:_a.call(this,this.msg);}}scheduleTimer(){this.timerHandle=window.setTimeout(()=>this.onTimer(),this.retransmitIntervalMs);}cancel(){if(this.timerHandle){clearTimeout(this.timerHandle);}this.timerHandle=undefined;}}var JmpSessionEvents;(function(JmpSessionEvents){JmpSessionEvents["ActiveSpeaker"]="active-speaker";JmpSessionEvents["MediaRequestReceived"]="media-request-received";JmpSessionEvents["MediaRequestStatusReceived"]="media-request-status-received";JmpSessionEvents["SourceAdvertisementReceived"]="source-advertisement-received";})(JmpSessionEvents||(JmpSessionEvents={}));class JmpSession extends EventEmitter$6{constructor(mediaFamily,mediaContent){var maxNumRetransmits=arguments.length>2&&arguments[2]!==undefined?arguments[2]:200;var retransmitIntervalMs=arguments.length>3&&arguments[3]!==undefined?arguments[3]:250;super();this.currMediaRequestSeqNum=1;this.currSourceAdvertisementSeqNum=1;this.currMediaRequestStatusSeqNum=1;this.txCallback=undefined;this.lastSentMediaRequest=undefined;this.lastSentMediaRequestAck=undefined;this.lastReceivedMediaRequest=undefined;this.mediaFamily=mediaFamily;this.mediaContent=mediaContent;this.logger=Logger$1.get("JmpSession ".concat(this.mediaFamily,"-").concat(this.mediaContent));this.maxNumRetransmits=maxNumRetransmits;this.retransmitIntervalMs=retransmitIntervalMs;}getLogger(){return this.logger;}sendRequests(requests){var _a;var mediaRequestMsg=new MediaRequestMsg(this.currMediaRequestSeqNum,requests);if(!this.lastSentMediaRequest||!areArraysEqual(this.lastSentMediaRequest.msg.requests,requests,areStreamRequestsEqual)){this.sendJmpMsg(JmpMsgType.MediaRequest,mediaRequestMsg);(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.cancel();this.lastSentMediaRequest=new RetransmitHandler(mediaRequestMsg,this.maxNumRetransmits,this.retransmitIntervalMs,()=>{this.logger.info("Retransmitting previously sent MediaRequest...");this.sendJmpMsg(JmpMsgType.MediaRequest,mediaRequestMsg);},expiredJmpMsg=>{this.logger.warn("Retransmits for message expired: ".concat(expiredJmpMsg));});this.currMediaRequestSeqNum++;}else {this.logger.info("Duplicate MediaRequest detected and will not be sent: ".concat(mediaRequestMsg));}}sendSourceAdvertisement(numTotalSources,numLiveSources,namedMediaGroups,videoContentHint){var _a;var sourceAdvertisementMsg=new SourceAdvertisementMsg(this.currSourceAdvertisementSeqNum,numTotalSources,numLiveSources,namedMediaGroups,videoContentHint);if(!this.lastSentSourceAdvertisement||!areSourceAdvertisementMsgsEqual(this.lastSentSourceAdvertisement.msg,sourceAdvertisementMsg)){this.sendJmpMsg(JmpMsgType.SourceAdvertisement,sourceAdvertisementMsg);(_a=this.lastSentSourceAdvertisement)===null||_a===void 0?void 0:_a.cancel();this.lastSentSourceAdvertisement=new RetransmitHandler(sourceAdvertisementMsg,this.maxNumRetransmits,this.retransmitIntervalMs,()=>{this.logger.info("Retransmitting previously sent SourceAdvertisement...");this.sendJmpMsg(JmpMsgType.SourceAdvertisement,sourceAdvertisementMsg);},expiredMsg=>{this.logger.warn("Retransmits for message expired: ",expiredMsg);});this.currSourceAdvertisementSeqNum++;}else {this.logger.info("Duplicate SourceAdvertisement detected and will not be sent: ",sourceAdvertisementMsg);}}sendMediaRequestStatus(streamStates){var _a,_b;var filteredStreamStates=streamStates.filter(streamState=>{var _a;return (_a=this.lastReceivedMediaRequest)===null||_a===void 0?void 0:_a.requests.some(req=>req.ids.find(streamId=>areStreamIdsEqual(streamId,streamState.id)));});var mediaRequestStatus=new MediaRequestStatusMsg(this.currMediaRequestStatusSeqNum,filteredStreamStates);if(!((_a=this.lastSentMediaRequestStatus)===null||_a===void 0?void 0:_a.msg.streamStates)||!areArraysEqual(filteredStreamStates,this.lastSentMediaRequestStatus.msg.streamStates,areStreamInfosEqual)){this.sendJmpMsg(JmpMsgType.MediaRequestStatus,mediaRequestStatus);(_b=this.lastSentMediaRequestStatus)===null||_b===void 0?void 0:_b.cancel();this.lastSentMediaRequestStatus=new RetransmitHandler(mediaRequestStatus,this.maxNumRetransmits,this.retransmitIntervalMs,()=>{this.logger.info("Retransmitting previously sent MediaRequestStatus...");this.sendJmpMsg(JmpMsgType.MediaRequestStatus,mediaRequestStatus);},expiredMsg=>{this.logger.warn("Retransmits for message expired: ",expiredMsg);});this.currMediaRequestStatusSeqNum++;}else {this.logger.info("Duplicate MediaRequestStatus detected and will not be sent: ",mediaRequestStatus);}}receive(jmpMsg){if(jmpMsg.mediaContent!==this.mediaContent||jmpMsg.mediaFamily!==this.mediaFamily){this.logger.error("JmpMsg ".concat(JSON.stringify(jmpMsg)," sent to incorrect JmpSession"));return;}this.logger.debug("Received JmpMsg",JSON.stringify(jmpMsg));var{payload}=jmpMsg;if(payload.msgType===JmpMsgType.MediaRequest){var mediaRequestMsg=payload.payload;if(!isValidMediaRequestMsg(mediaRequestMsg)){this.logger.error("Received invalid MediaRequest:",JSON.stringify(mediaRequestMsg));return;}this.handleIncomingMediaRequest(mediaRequestMsg);}else if(payload.msgType===JmpMsgType.MediaRequestAck){var mediaRequestAckMsg=payload.payload;if(!isValidMediaRequestAckMsg(mediaRequestAckMsg)){this.logger.error("Received invalid MediaRequest ACK:",JSON.stringify(mediaRequestAckMsg));return;}this.handleIncomingMediaRequestAck(mediaRequestAckMsg);}else if(payload.msgType===JmpMsgType.ActiveSpeakerNotification){var activeSpeakerNotification=payload.payload;if(!isValidActiveSpeakerNotificationMsg(activeSpeakerNotification)){this.logger.info("Received invalid Active Speaker Notification:",JSON.stringify(activeSpeakerNotification));return;}this.handleIncomingActiveSpeakerNotification(activeSpeakerNotification);}else if(payload.msgType===JmpMsgType.SourceAdvertisement){var sourceAdvertisement=payload.payload;if(!isValidSourceAdvertisementMsg(sourceAdvertisement)){this.logger.error("Received invalid SourceAdvertisementMsg:",JSON.stringify(sourceAdvertisement));return;}this.handleIncomingSourceAdvertisement(sourceAdvertisement);}else if(payload.msgType===JmpMsgType.SourceAdvertisementAck){var sourceAdvertisementAck=payload.payload;if(!isValidSourceAdvertisementAckMsg(sourceAdvertisementAck)){this.logger.error("Received invalid SourceAdvertisementAckMsg:",JSON.stringify(sourceAdvertisementAck));return;}this.handleIncomingSourceAdvertisementAck(sourceAdvertisementAck);}else if(payload.msgType===JmpMsgType.MediaRequestStatus){var mediaRequestStatus=payload.payload;if(!isValidMediaRequestStatusMsg(mediaRequestStatus)){this.logger.error("Received invalid MediaRequestStatusMsg:",JSON.stringify(mediaRequestStatus));return;}this.handleIncomingMediaRequestStatus(mediaRequestStatus);}else if(payload.msgType===JmpMsgType.MediaRequestStatusAck){var mediaRequestStatusAck=payload.payload;if(!isValidMediaRequestStatusAckMsg(mediaRequestStatusAck)){this.logger.error("Received invalid MediaRequestStatusAckMsg:",JSON.stringify(mediaRequestStatusAck));return;}this.handleIncomingMediaRequestStatusAck(mediaRequestStatusAck);}else {this.logger.error("Received unknown JmpMsg");}}setTxCallback(callback){this.txCallback=callback;}close(){var _a,_b,_c;this.logger.info("closing");(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.cancel();(_b=this.lastSentMediaRequestStatus)===null||_b===void 0?void 0:_b.cancel();(_c=this.lastSentSourceAdvertisement)===null||_c===void 0?void 0:_c.cancel();}sendJmpMsg(msgType,payload){var _a;var jmpMsg=new JmpMsg(this.mediaFamily,this.mediaContent,{msgType,payload});(_a=this.txCallback)===null||_a===void 0?void 0:_a.call(this,jmpMsg);}handleIncomingMediaRequest(mediaRequestMsg){var _a;if(this.lastReceivedMediaRequest&&mediaRequestMsg.seqNum<((_a=this.lastReceivedMediaRequest)===null||_a===void 0?void 0:_a.seqNum)){this.logger.info("Received old MediaRequest, ignoring");}else if(this.lastReceivedMediaRequest&&mediaRequestMsg.seqNum===this.lastReceivedMediaRequest.seqNum){if(this.lastSentMediaRequestAck){this.logger.info("Received duplicate MediaRequest, re-sending ACK");this.sendJmpMsg(JmpMsgType.MediaRequestAck,this.lastSentMediaRequestAck);}else {this.logger.warn("Received duplicate MediaRequest, but there was no ACK previously sent");}}else {this.logger.info("Received new MediaRequest, sending ACK");var mediaRequestAck=new MediaRequestAckMsg(mediaRequestMsg.seqNum);this.lastReceivedMediaRequest=mediaRequestMsg;this.lastSentMediaRequestAck=mediaRequestAck;this.sendJmpMsg(JmpMsgType.MediaRequestAck,mediaRequestAck);this.emit(JmpSessionEvents.MediaRequestReceived,mediaRequestMsg);}}handleIncomingMediaRequestAck(mediaRequestAckMsg){var _a,_b,_c;if(mediaRequestAckMsg.mediaRequestSeqNum===((_b=(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent MediaRequest");(_c=this.lastSentMediaRequest)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old MediaRequest");}}handleIncomingActiveSpeakerNotification(activeSpeakerNotification){this.logger.debug("Received Active Speaker Notification:",activeSpeakerNotification);this.emit(JmpSessionEvents.ActiveSpeaker,activeSpeakerNotification);}handleIncomingSourceAdvertisement(sourceAdvertisement){if(this.lastReceivedSourceAdvertisement&&sourceAdvertisement.seqNum<this.lastReceivedSourceAdvertisement.seqNum){this.logger.info("Received old SourceAdvertisement, ignoring");}else if(this.lastReceivedSourceAdvertisement&&sourceAdvertisement.seqNum===this.lastReceivedSourceAdvertisement.seqNum){if(this.lastSentSourceAdvertisementAck){this.logger.info("Received duplicate SourceAdvertisement, re-sending ACK");this.sendJmpMsg(JmpMsgType.SourceAdvertisementAck,this.lastSentSourceAdvertisementAck);}else {this.logger.warn("Received duplicate SourceAdvertisement, but there was no ACK previously sent");}}else {this.logger.info("Received new SourceAdvertisement, sending ACK");var sourceAdvertisementAck=new SourceAdvertisementAckMsg(sourceAdvertisement.seqNum);this.lastReceivedSourceAdvertisement=sourceAdvertisement;this.lastSentSourceAdvertisementAck=sourceAdvertisementAck;this.sendJmpMsg(JmpMsgType.SourceAdvertisementAck,sourceAdvertisementAck);this.emit(JmpSessionEvents.SourceAdvertisementReceived,sourceAdvertisement);}}handleIncomingSourceAdvertisementAck(sourceAdvertisementAck){var _a,_b,_c;if(sourceAdvertisementAck.sourceAdvertisementSeqNum===((_b=(_a=this.lastSentSourceAdvertisement)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent SourceAdvertisement");(_c=this.lastSentSourceAdvertisement)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old SourceAdvertisement");}}handleIncomingMediaRequestStatus(mediaRequestStatus){if(this.lastReceivedMediaRequestStatus&&mediaRequestStatus.seqNum<this.lastReceivedMediaRequestStatus.seqNum){this.logger.info("Received old MediaRequestStatus, ignoring");}else if(this.lastReceivedMediaRequestStatus&&mediaRequestStatus.seqNum===this.lastReceivedMediaRequestStatus.seqNum){if(this.lastSentMediaRequestStatusAck){this.logger.info("Received duplicate MediaRequestStatus, re-sending ACK");this.sendJmpMsg(JmpMsgType.MediaRequestStatusAck,this.lastSentMediaRequestStatusAck);}else {this.logger.warn("Received duplicate MediaRequestStatus, but there was no ACK previously sent");}}else {this.logger.info("Received new MediaRequestStatus, sending ACK");var mediaRequestStatusAck=new MediaRequestStatusAckMsg(mediaRequestStatus.seqNum);this.lastReceivedMediaRequestStatus=mediaRequestStatus;this.lastSentMediaRequestStatusAck=mediaRequestStatusAck;this.sendJmpMsg(JmpMsgType.MediaRequestStatusAck,mediaRequestStatusAck);this.emit(JmpSessionEvents.MediaRequestStatusReceived,mediaRequestStatus);}}handleIncomingMediaRequestStatusAck(mediaRequestStatusAck){var _a,_b,_c;if(mediaRequestStatusAck.mediaRequestStatusSeqNum===((_b=(_a=this.lastSentMediaRequestStatus)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent MediaRequestStatus");(_c=this.lastSentMediaRequestStatus)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old MediaRequestStatus");}}}var WcmeErrorType;(function(WcmeErrorType){WcmeErrorType["CREATE_OFFER_FAILED"]="CREATE_OFFER_FAILED";WcmeErrorType["SET_ANSWER_FAILED"]="SET_ANSWER_FAILED";WcmeErrorType["OFFER_ANSWER_MISMATCH"]="OFFER_ANSWER_MISMATCH";WcmeErrorType["SDP_MUNGE_FAILED"]="SDP_MUNGE_FAILED";WcmeErrorType["SDP_MUNGE_MISSING_CODECS"]="SDP_MUNGE_MISSING_CODECS";WcmeErrorType["INVALID_STREAM_REQUEST"]="INVALID_STREAM_REQUEST";WcmeErrorType["GET_TRANSCEIVER_FAILED"]="GET_TRANSCEIVER_FAILED";WcmeErrorType["GET_MAX_BITRATE_FAILED"]="GET_MAX_BITRATE_FAILED";WcmeErrorType["GET_PAYLOAD_TYPE_FAILED"]="GET_PAYLOAD_TYPE_FAILED";WcmeErrorType["SET_NMG_FAILED"]="SET_NMG_FAILED";WcmeErrorType["SET_SOURCE_STATE_OVERRIDE_FAILED"]="SET_SOURCE_STATE_OVERRIDE_FAILED";WcmeErrorType["DATA_CHANNEL_SEND_FAILED"]="DATA_CHANNEL_SEND_FAILED";WcmeErrorType["RENEW_PEER_CONNECTION_FAILED"]="RENEW_PEER_CONNECTION_FAILED";})(WcmeErrorType||(WcmeErrorType={}));class WcmeError{constructor(type){var message=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';this.type=type;this.message=message;}}var commonjsGlobal$1=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global$1!=='undefined'?global$1:typeof self!=='undefined'?self:{};var logger$1={exports:{}};/*!
3456
3460
  * js-logger - http://github.com/jonnyreeves/js-logger
3457
3461
  * Jonny Reeves, http://jonnyreeves.co.uk/
3458
3462
  * js-logger may be freely distributed under the MIT license.
@@ -5604,7 +5608,7 @@ var{hasOwnProperty}=Object.prototype;for(var i=0;i<mapResults.length;i++){if(map
5604
5608
  * // arg1 now equals 'three'
5605
5609
  * callback(null, 'done');
5606
5610
  * }
5607
- */function waterfall(tasks,callback){callback=once(callback);if(!Array.isArray(tasks))return callback(new Error('First argument to waterfall must be an array of functions'));if(!tasks.length)return callback();var taskIndex=0;function nextTask(args){var task=wrapAsync(tasks[taskIndex++]);task(...args,onlyOnce(next));}function next(err){if(err===false)return;for(var _len22=arguments.length,args=new Array(_len22>1?_len22-1:0),_key22=1;_key22<_len22;_key22++){args[_key22-1]=arguments[_key22];}if(err||taskIndex===tasks.length){return callback(err,...args);}nextTask(args);}nextTask([]);}awaitify(waterfall);function processTasks(task,finishedCallback){return __awaiter$1(this,void 0,void 0,function*(){try{yield task();finishedCallback();}catch(e){finishedCallback(e);}});}class AsyncQueue{constructor(){this.queue=queue$1(processTasks,1);}push(task){return this.queue.pushAsync(task);}empty(){return this.queue.empty();}}var NOISE_REDUCTION_KIND='noise-reduction-effect';var VIRTUAL_BACKGROUND_KIND='virtual-background-effect';var isNoiseReductionEffect=effect=>{return (effect===null||effect===void 0?void 0:effect.kind)===NOISE_REDUCTION_KIND;};var isVirtualBackgroundEffect=effect=>{return (effect===null||effect===void 0?void 0:effect.kind)===VIRTUAL_BACKGROUND_KIND;};var OfferAnswerType;(function(OfferAnswerType){OfferAnswerType[OfferAnswerType["LocalOnly"]=0]="LocalOnly";OfferAnswerType[OfferAnswerType["Remote"]=1]="Remote";})(OfferAnswerType||(OfferAnswerType={}));class SendOnlyTransceiver extends Transceiver{constructor(config){super(config);this.rtxEnabled=false;this.dtxDisabled=true;this.streamMuteStateChange=new TypedEvent();this.streamPublishStateChange=new TypedEvent();this.negotiationNeeded=new TypedEvent();this.namedMediaGroupsChange=new TypedEvent();this.requestedIdEncodingParamsMap=new Map();this.updateSendParametersQueue=new AsyncQueue();this.sourceStateOverrideChange=new TypedEvent();this.metadata={lastRequestedUpdateTimestampsMap:new Map()};this.munger=config.munger;this.csi=config.csi;this.direction='sendrecv';this.handleTrackChange=this.handleTrackChange.bind(this);this.handleStreamConstraintsChange=this.handleStreamConstraintsChange.bind(this);this.handleStreamMuteStateChange=this.handleStreamMuteStateChange.bind(this);}replaceSenderSource(stream){var _a,_b;return __awaiter$1(this,void 0,void 0,function*(){var trackOrNull=(_a=stream===null||stream===void 0?void 0:stream.outputStream.getTracks()[0])!==null&&_a!==void 0?_a:null;if(((_b=this.sender.track)===null||_b===void 0?void 0:_b.id)!==(trackOrNull===null||trackOrNull===void 0?void 0:trackOrNull.id)){yield this.sender.replaceTrack(trackOrNull);if(trackOrNull){logger.log("Sender source for ".concat(this.mediaType," replaced with track ID ").concat(trackOrNull.id));}else {logger.log("Sender source for ".concat(this.mediaType," set to null, sender stopped"));}}});}handleTrackChange(){return __awaiter$1(this,void 0,void 0,function*(){if(this.requested){yield this.replaceSenderSource(this.publishedStream);}});}handleStreamConstraintsChange(){return __awaiter$1(this,void 0,void 0,function*(){yield this.updateSendParameters(this.requestedIdEncodingParamsMap);});}handleStreamMuteStateChange(){this.streamMuteStateChange.emit();}get requested(){return this.requestedIdEncodingParamsMap.size>0;}replaceTransceiver(newRtcRtpTransceiver){var _super=Object.create(null,{replaceTransceiver:{get:()=>super.replaceTransceiver}});return __awaiter$1(this,void 0,void 0,function*(){_super.replaceTransceiver.call(this,newRtcRtpTransceiver);newRtcRtpTransceiver.direction=this.direction;if(this.requested){yield this.replaceSenderSource(this.publishedStream);}});}replacePublishedStream(newStream){return __awaiter$1(this,void 0,void 0,function*(){var oldStream=this.publishedStream;oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.UserMuteStateChange,this.handleStreamMuteStateChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.SystemMuteStateChange,this.handleStreamMuteStateChange);if(this.requested){yield this.replaceSenderSource(newStream);}this.publishedStream=newStream;newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.UserMuteStateChange,this.handleStreamMuteStateChange);newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.SystemMuteStateChange,this.handleStreamMuteStateChange);if(!oldStream&&newStream&&!newStream.muted||oldStream&&!newStream&&!oldStream.muted){this.streamPublishStateChange.emit();}else if((oldStream===null||oldStream===void 0?void 0:oldStream.muted)!==(newStream===null||newStream===void 0?void 0:newStream.muted)){this.streamMuteStateChange.emit();}});}setNamedMediaGroups(namedMediaGroups){if(this.mediaType!==MediaType.AudioMain){logErrorAndThrow(WcmeErrorType.SET_NMG_FAILED,"Named media groups can only be set for audio.");}this.namedMediaGroups=namedMediaGroups;this.namedMediaGroupsChange.emit();}publishStream(stream){return this.replacePublishedStream(stream);}unpublishStream(){return this.replacePublishedStream();}get active(){return this._rtcRtpTransceiver.direction==='sendrecv';}set active(enabled){this.direction=enabled?'sendrecv':'inactive';this._rtcRtpTransceiver.direction=this.direction;if(this._rtcRtpTransceiver.direction!==this._rtcRtpTransceiver.currentDirection){this.negotiationNeeded.emit(OfferAnswerType.Remote);}}getStats(){return __awaiter$1(this,void 0,void 0,function*(){var statsMap=new Map();var statsReport=yield this.sender.getStats();statsReport.forEach((stats,key)=>{var _a,_b,_c,_d,_e;if(stats.type==='outbound-rtp'){stats.mid=this.mid;stats.csi=this.csi;stats.calliopeMediaType=this.mediaType;var senderId=this.munger.getSenderIds().find(id=>id.ssrc===stats.ssrc);if(senderId){var encodingIndex=this.getEncodingIndexForStreamId(senderId);var encodingParams=this.requestedIdEncodingParamsMap.get(encodingIndex);stats.requestedBitrate=encodingParams===null||encodingParams===void 0?void 0:encodingParams.maxPayloadBitsPerSecond;stats.requestedFrameSize=encodingParams===null||encodingParams===void 0?void 0:encodingParams.maxFs;stats.isRequested=!!encodingParams;stats.lastRequestedUpdateTimestamp=this.metadata.lastRequestedUpdateTimestampsMap.get(encodingIndex);}var effect=(_b=(_a=this.publishedStream)===null||_a===void 0?void 0:_a.getEffects())===null||_b===void 0?void 0:_b[0];if(effect===null||effect===void 0?void 0:effect.isEnabled){if(isNoiseReductionEffect(effect)){stats.effect={kind:effect.kind,noiseReductionMode:'LOW_POWER'};}else if(isVirtualBackgroundEffect(effect)){stats.effect={kind:effect.kind,virtualBackgroundMode:(_c=effect.options)===null||_c===void 0?void 0:_c.mode};}else {stats.effect={kind:effect.kind};}}var trackSettings=(_d=this.publishedStream)===null||_d===void 0?void 0:_d.getSettings();if(trackSettings===null||trackSettings===void 0?void 0:trackSettings.frameRate){stats.targetFrameRate=trackSettings===null||trackSettings===void 0?void 0:trackSettings.frameRate;}}else if(stats.type==='media-source'){stats.calliopeMediaType=this.mediaType;stats.trackLabel=(_e=this.publishedStream)===null||_e===void 0?void 0:_e.label;}statsMap.set(key,stats);});return statsMap;});}updateSendParameters(requestedIdEncodingParamsMap){return __awaiter$1(this,void 0,void 0,function*(){return this.updateSendParametersQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var sendParameters=this.sender.getParameters();sendParameters.encodings.forEach((encoding,index)=>{var _a,_b;var encodingParams=requestedIdEncodingParamsMap.get(index);encoding.active=!!encodingParams;if(encodingParams){var{maxPayloadBitsPerSecond,maxFs,maxWidth,maxHeight}=encodingParams;var scaleDownRatio=getScaleDownRatio((_a=this.publishedStream)===null||_a===void 0?void 0:_a.getSettings().width,(_b=this.publishedStream)===null||_b===void 0?void 0:_b.getSettings().height,maxFs,maxWidth,maxHeight);if(maxPayloadBitsPerSecond!==undefined&&maxPayloadBitsPerSecond>=0){encoding.maxBitrate=maxPayloadBitsPerSecond;}if(scaleDownRatio!==undefined&&scaleDownRatio>=1.0){encoding.scaleResolutionDownBy=scaleDownRatio;}}});yield this.sender.setParameters(sendParameters);logger.log("Sender parameters for ".concat(this.mediaType," set to ").concat(JSON.stringify(sendParameters)));var timestamp=getCurrentTimestamp();requestedIdEncodingParamsMap.forEach((_,index)=>{if(!this.requestedIdEncodingParamsMap.has(index)){this.metadata.lastRequestedUpdateTimestampsMap.set(index,timestamp);}});this.requestedIdEncodingParamsMap.forEach((_,index)=>{if(!requestedIdEncodingParamsMap.has(index)){this.metadata.lastRequestedUpdateTimestampsMap.set(index,timestamp);}});var oldRequested=this.requested;var newRequested=requestedIdEncodingParamsMap.size>0;this.requestedIdEncodingParamsMap=requestedIdEncodingParamsMap;if(oldRequested!==newRequested){yield this.replaceSenderSource(newRequested?this.publishedStream:null);}}));});}isSimulcastEnabled(){var params=this.sender.getParameters();return params.encodings.length>1;}mungeLocalDescription(mediaDescription){this.munger.mungeLocalDescription(mediaDescription,{simulcastEnabled:this.isSimulcastEnabled(),rtxEnabled:this.rtxEnabled,twccDisabled:this.twccDisabled,forceSoftwareEncoder:this.mediaType===MediaType.VideoSlides&&(BrowserInfo.isWindows()||BrowserInfo.isMac())&&(BrowserInfo.isChrome()||BrowserInfo.isEdge())});}mungeLocalDescriptionForRemoteServer(mediaDescription){var mungeOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{injectDummyCandidates:true};this.munger.mungeLocalDescriptionForRemoteServer(mediaDescription,getMediaContent(this.mediaType),this.csi,mungeOptions);}mungeRemoteDescription(mediaDescription){this.munger.mungeRemoteDescription(mediaDescription,{dtxDisabled:this.dtxDisabled});}get senderIds(){return this.munger.getSenderIds();}get numActiveSimulcastLayers(){var _a;if(getMediaFamily(this.mediaType)===MediaFamily.Video){return (_a=this.publishedStream)===null||_a===void 0?void 0:_a.getNumActiveSimulcastLayers();}return this.publishedStream?0:undefined;}getEncodingIndexForStreamId(id){return this.munger.getEncodingIndexForStreamId(id);}resetSdpMunger(){this.munger.reset();}setCodecParameters(parameters){this.munger.setCodecParameters(parameters);this.negotiationNeeded.emit(OfferAnswerType.LocalOnly);}deleteCodecParameters(parameters){this.munger.deleteCodecParameters(parameters);this.negotiationNeeded.emit(OfferAnswerType.LocalOnly);}setSourceStateOverride(state){this.sourceStateOverride=state;this.sourceStateOverrideChange.emit();}get currentSourceState(){if(this.sourceStateOverride){return this.sourceStateOverride;}if(!this.publishedStream){return 'no source';}if(this.publishedStream.muted){return 'avatar';}return 'live';}}class SendSlot{constructor(sendTransceiver){this.sendTransceiver=sendTransceiver;}publishStream(stream){return __awaiter$1(this,void 0,void 0,function*(){if(stream===this.sendTransceiver.publishedStream){return Promise.resolve();}return this.sendTransceiver.publishStream(stream);});}unpublishStream(){return __awaiter$1(this,void 0,void 0,function*(){if(!this.sendTransceiver.publishedStream){return Promise.resolve();}return this.sendTransceiver.unpublishStream();});}setNamedMediaGroups(namedMediaGroups){this.sendTransceiver.setNamedMediaGroups(namedMediaGroups);}clearNamedMediaGroups(){this.setNamedMediaGroups([]);}get active(){return this.sendTransceiver.active;}set active(active){this.sendTransceiver.active=active;}setCodecParameters(parameters){return __awaiter$1(this,void 0,void 0,function*(){this.sendTransceiver.setCodecParameters(parameters);});}deleteCodecParameters(parameters){return __awaiter$1(this,void 0,void 0,function*(){this.sendTransceiver.deleteCodecParameters(parameters);});}setSourceStateOverride(state){this.sendTransceiver.setSourceStateOverride(state);}clearSourceStateOverride(){this.sendTransceiver.setSourceStateOverride(undefined);}}var organizeTransceiverStats=(sendTransceivers,recvTransceivers,peerConnectionStats)=>__awaiter$1(void 0,void 0,void 0,function*(){var result={audio:{senders:[],receivers:[]},video:{senders:[],receivers:[]},screenShareAudio:{senders:[],receivers:[]},screenShareVideo:{senders:[],receivers:[]}};yield Promise.all([...sendTransceivers.entries()].map(_ref7=>{var[mediaType,transceiver]=_ref7;return __awaiter$1(void 0,void 0,void 0,function*(){var _a;var item={report:yield transceiver.getStats(),mid:transceiver.mid,csi:transceiver.csi,currentDirection:'sendonly',localTrackLabel:(_a=transceiver.publishedStream)===null||_a===void 0?void 0:_a.label};if(peerConnectionStats&&peerConnectionStats.id){item.report.set(peerConnectionStats.id,peerConnectionStats);}if(mediaType===MediaType.AudioMain){result.audio.senders.push(item);}if(mediaType===MediaType.VideoMain){result.video.senders.push(item);}if(mediaType===MediaType.AudioSlides){result.screenShareAudio.senders.push(item);}if(mediaType===MediaType.VideoSlides){result.screenShareVideo.senders.push(item);}});}));yield Promise.all([...recvTransceivers.entries()].map(_ref8=>{var[mediaType,transceivers]=_ref8;return __awaiter$1(void 0,void 0,void 0,function*(){return Promise.all(transceivers.map(t=>__awaiter$1(void 0,void 0,void 0,function*(){var _b;var item={report:yield t.getStats(),csi:t.receiveSlot.currentRxCsi,currentDirection:'recvonly',localTrackLabel:(_b=t.receiveSlot.stream.getTracks()[0])===null||_b===void 0?void 0:_b.label};if(peerConnectionStats&&peerConnectionStats.id){item.report.set(peerConnectionStats.id,peerConnectionStats);}if(mediaType===MediaType.AudioMain){result.audio.receivers.push(item);}if(mediaType===MediaType.VideoMain){result.video.receivers.push(item);}if(mediaType===MediaType.AudioSlides){result.screenShareAudio.receivers.push(item);}if(mediaType===MediaType.VideoSlides){result.screenShareVideo.receivers.push(item);}})));});}));return result;});function toMediaStreamTrackKind(mediaType){return [MediaType.VideoMain,MediaType.VideoSlides].includes(mediaType)?MediaStreamTrackKind.Video:MediaStreamTrackKind.Audio;}function webRtcVideoContentHintToJmpVideoContentHint(hint){if(hint==='motion'){return 'motion';}if(hint==='detail'){return 'sharpness';}return undefined;}var MultistreamConnectionEventNames;(function(MultistreamConnectionEventNames){MultistreamConnectionEventNames["VideoSourceCountUpdate"]="video-source-count-update";MultistreamConnectionEventNames["AudioSourceCountUpdate"]="audio-source-count-update";MultistreamConnectionEventNames["ActiveSpeakerNotification"]="active-speaker-notification";MultistreamConnectionEventNames["PeerConnectionStateUpdate"]="peer-connection-state-update";MultistreamConnectionEventNames["IceConnectionStateUpdate"]="ice-connection-state-update";MultistreamConnectionEventNames["IceGatheringStateUpdate"]="ice-gathering-state-update";MultistreamConnectionEventNames["NegotiationNeeded"]="negotiation-needed";MultistreamConnectionEventNames["CreateOfferOnSuccess"]="createofferonsuccess";MultistreamConnectionEventNames["CreateAnswerOnSuccess"]="createansweronsuccess";MultistreamConnectionEventNames["SetLocalDescriptionOnSuccess"]="setlocaldescriptiononsuccess";MultistreamConnectionEventNames["SetRemoteDescriptionOnSuccess"]="setremotedescriptiononsuccess";MultistreamConnectionEventNames["IceCandidate"]="icecandidate";MultistreamConnectionEventNames["IceCandidateError"]="icecandidateerror";})(MultistreamConnectionEventNames||(MultistreamConnectionEventNames={}));var defaultMultistreamConnectionOptions={disableSimulcast:BrowserInfo.isFirefox(),bundlePolicy:'max-compat',iceServers:undefined,iceTransportPolicy:'all',disableContentSimulcast:true,disableAudioTwcc:true,doFullIce:BrowserInfo.isFirefox(),stopIceGatheringAfterFirstRelayCandidate:false,disableAudioMainDtx:true,metricsCallback:()=>{}};class MultistreamConnection extends EventEmitter$2{constructor(){var userOptions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};super();this.sendTransceivers=new Map();this.recvTransceivers=new Map();this.jmpSessions=new Map();this.pendingJmpTasks=[];this.overuseUpdateCallback=()=>{};this.midPredictor=new MidPredictor();this.offerAnswerQueue=new AsyncQueue();this.currentCreateOfferId=0;this.iceCandidates=[];this.metadata={isMediaBypassEdge:false};this.options=Object.assign(Object.assign({},defaultMultistreamConnectionOptions),userOptions);logger.info("Creating multistream connection with options ".concat(JSON.stringify(this.options)));this.metricsCallback=this.options.metricsCallback;this.initializePeerConnection();this.overuseStateManager=new OveruseStateManager(overuseState=>this.overuseUpdateCallback(overuseState));this.overuseStateManager.start();this.statsManager=new StatsManager(()=>this.pc.getStats(),stats=>this.preProcessStats(stats));var mainSceneId=generateSceneId();var slidesSceneId=generateSceneId();var videoMainEncodingOptions=this.getVideoEncodingOptions(MediaContent.Main);var videoSlidesEncodingOptions=this.getVideoEncodingOptions(MediaContent.Slides);this.createSendTransceiver(MediaType.VideoMain,mainSceneId,videoMainEncodingOptions);this.createSendTransceiver(MediaType.AudioMain,mainSceneId);this.createSendTransceiver(MediaType.VideoSlides,slidesSceneId,videoSlidesEncodingOptions);this.createSendTransceiver(MediaType.AudioSlides,slidesSceneId);}initializePeerConnection(){this.pc=new PeerConnection({iceServers:this.options.iceServers,bundlePolicy:this.options.bundlePolicy,iceTransportPolicy:this.options.iceTransportPolicy});this.propagatePeerConnectionEvents();this.attachMetricsObserver();this.createDataChannel();}propagatePeerConnectionEvents(){this.pc.on(PeerConnection.Events.PeerConnectionStateChange,state=>{this.emit(MultistreamConnectionEventNames.PeerConnectionStateUpdate,state);});this.pc.on(PeerConnection.Events.IceConnectionStateChange,state=>{this.emit(MultistreamConnectionEventNames.IceConnectionStateUpdate,state);});this.pc.on(PeerConnection.Events.CreateOfferOnSuccess,description=>{this.emit(MultistreamConnectionEventNames.CreateOfferOnSuccess,description);});this.pc.on(PeerConnection.Events.CreateAnswerOnSuccess,description=>{this.emit(MultistreamConnectionEventNames.CreateAnswerOnSuccess,description);});this.pc.on(PeerConnection.Events.SetLocalDescriptionOnSuccess,description=>{this.emit(MultistreamConnectionEventNames.SetLocalDescriptionOnSuccess,description);});this.pc.on(PeerConnection.Events.SetRemoteDescriptionOnSuccess,description=>{this.emit(MultistreamConnectionEventNames.SetRemoteDescriptionOnSuccess,description);});this.pc.on(PeerConnection.Events.IceGatheringStateChange,()=>{this.emit(MultistreamConnectionEventNames.IceGatheringStateUpdate,this.getIceGatheringState());});this.pc.on(PeerConnection.Events.IceCandidate,candidate=>{if(candidate.candidate){this.iceCandidates.push(candidate.candidate);}this.emit(MultistreamConnectionEventNames.IceCandidate,candidate);});this.pc.on(PeerConnection.Events.IceCandidateError,error=>{this.emit(MultistreamConnectionEventNames.IceCandidateError,error);});}getConnectionState(){return this.pc.getConnectionState();}getPeerConnectionState(){return this.pc.getPeerConnectionState();}getIceConnectionState(){return this.pc.getIceConnectionState();}getCurrentConnectionType(){return this.pc.getCurrentConnectionType();}getIceGatheringState(){return this.pc.iceGatheringState;}getVideoEncodingOptions(content){var enabledSimulcast=content===MediaContent.Main?!this.options.disableSimulcast:!this.options.disableContentSimulcast;return enabledSimulcast?[{scaleResolutionDownBy:4,active:false},{scaleResolutionDownBy:2,active:false},{active:false}]:[{active:false}];}createSendTransceiver(mediaType,sceneId,sendEncodingsOptions){var rtcRtpTransceiver;try{rtcRtpTransceiver=this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'sendrecv',sendEncodings:sendEncodingsOptions});}catch(e){logger.error("addTransceiver failed due to : ".concat(e));throw e;}var mid=this.midPredictor.getNextMid(mediaType);var csi=generateCsi(getMediaFamily(mediaType),sceneId);var munger=new EgressSdpMunger();var transceiver=new SendOnlyTransceiver({rtcRtpTransceiver,mid,mediaType,munger,csi});if(getMediaFamily(mediaType)===MediaFamily.Video){transceiver.rtxEnabled=true;transceiver.setCodecParameters({'max-mbps':"".concat(defaultMaxVideoEncodeMbps),'max-fs':"".concat(defaultMaxVideoEncodeFrameSize)});}transceiver.twccDisabled=getMediaFamily(mediaType)===MediaFamily.Audio?this.options.disableAudioTwcc:false;transceiver.dtxDisabled=mediaType!==MediaType.AudioMain||this.options.disableAudioMainDtx;transceiver.active=false;transceiver.streamMuteStateChange.on(()=>{this.sendSourceAdvertisement(mediaType);this.sendMediaRequestStatus(mediaType);});transceiver.streamPublishStateChange.on(()=>{this.sendSourceAdvertisement(mediaType);this.sendMediaRequestStatus(mediaType);});transceiver.negotiationNeeded.on(offerAnswerType=>{if(offerAnswerType===OfferAnswerType.Remote){this.emit(MultistreamConnectionEventNames.NegotiationNeeded);}else if(this.pc.getRemoteDescription()){this.queueLocalOfferAnswer();}});transceiver.namedMediaGroupsChange.on(()=>{this.sendSourceAdvertisement(mediaType);});transceiver.sourceStateOverrideChange.on(()=>{this.sendMediaRequestStatus(mediaType);});this.sendTransceivers.set(mediaType,transceiver);this.createJmpSession(mediaType);}createSendSlot(mediaType){var active=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var transceiver=this.getSendTransceiverOrThrow(mediaType);transceiver.active=active;return new SendSlot(transceiver);}createJmpSession(mediaType){var jmpSession=new JmpSession(getMediaFamily(mediaType),getMediaContent(mediaType));jmpSession.setTxCallback(jmpMessage=>{var _a;if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)!=='open'){logger.error("DataChannel not created or not connected. Unable to send JMP message.");return;}var homerMsg=new HomerMsg(HomerMsgType.Multistream,jmpMessage);var serializedHomerMsg=JSON.stringify(homerMsg);try{logger.info("Sending JMP message: ".concat(serializedHomerMsg));this.dataChannel.send(serializedHomerMsg);}catch(err){var{bufferedAmount,readyState}=this.dataChannel;var{sctp}=this.pc.getUnderlyingRTCPeerConnection();var{maxMessageSize,state}=sctp||{};logErrorAndThrow(WcmeErrorType.DATA_CHANNEL_SEND_FAILED,"Sending JMP message failed with error: ".concat(err,",\nMessage size: ").concat(serializedHomerMsg.length,",\nData Channel State: ").concat(readyState,",\nData Channel Buffered amount: ").concat(bufferedAmount,",\nSCTP State: ").concat(state,",\nSCTP Max Message Size: ").concat(maxMessageSize));}});var prevNumTotalSources=0;var prevNumLiveSources=0;jmpSession.on(JmpSessionEvents.SourceAdvertisementReceived,data=>{logger.log("SourceAdvertisement received: ".concat(JSON.stringify(data)));if(data.numTotalSources!==prevNumTotalSources||data.numLiveSources!==prevNumLiveSources){prevNumTotalSources=data.numTotalSources;prevNumLiveSources=data.numLiveSources;var eventName=getMediaFamily(mediaType)===MediaFamily.Video?MultistreamConnectionEventNames.VideoSourceCountUpdate:MultistreamConnectionEventNames.AudioSourceCountUpdate;this.emit(eventName,data.numTotalSources,data.numLiveSources,getMediaContent(mediaType));}else {logger.log('Number of sources was unchanged, ignoring message');}});jmpSession.on(JmpSessionEvents.MediaRequestStatusReceived,data=>{logger.log("MediaRequestStatus received: ".concat(JSON.stringify(data)));data.streamStates.forEach(s=>{if(!isValidSsrcStreamId(s.id)){logger.error("Received MediaRequestStatus with non-SSRC based stream ID, which is currently not supported: ".concat(JSON.stringify(s.id)));return;}var receiveSlot=this.getReceiveSlotById(s.id);if(!receiveSlot){logger.warn("Got MediaRequestStatus for unknown receive slot: ".concat(JSON.stringify(s.id)));return;}if(!receiveSlot._isRequested){logger.info("MediaRequestStatus ignored due to transceiver's receive slot unrequested: ".concat(JSON.stringify(s.id)," csi ").concat(s.csi));return;}receiveSlot._updateSource(s.state,s.csi);});});jmpSession.on(JmpSessionEvents.MediaRequestReceived,data=>{logger.log("MediaRequest received: ".concat(JSON.stringify(data)));this.updateRequestedStreams(mediaType,data.requests).then(()=>{if(getMediaFamily(mediaType)===MediaFamily.Video){this.sendMediaRequestStatus(mediaType);}});});jmpSession.on(JmpSessionEvents.ActiveSpeaker,data=>{this.emit(MultistreamConnectionEventNames.ActiveSpeakerNotification,data.csis);this.recvTransceivers.forEach(transceivers=>{transceivers.forEach(t=>{var{currentRxCsi}=t.receiveSlot;if(currentRxCsi!==undefined){var isActiveSpeaker=data.csis.some(activeCsi=>(activeCsi&0xfffffffe)===(currentRxCsi&0xfffffffe));t.handleActiveSpeakerUpdate(isActiveSpeaker);}});});});this.jmpSessions.set(mediaType,jmpSession);}updateRequestedStreams(mediaType,requests){var sendTransceiver=this.getSendTransceiverOrThrow(mediaType);var mediaFamily=getMediaFamily(mediaType);var requestedIdEncodingParamsMap=new Map();var rsRequests=requests.filter(r=>isValidReceiverSelectedInfo(r.policySpecificInfo));if(rsRequests.length!==requests.length){logger.warn('Ignoring non-receiver-selected requests');}rsRequests.forEach(_ref9=>{var{ids,policySpecificInfo,codecInfos,maxPayloadBitsPerSecond}=_ref9;var _a,_b,_c;if(ids.length>1){logErrorAndThrow(WcmeErrorType.INVALID_STREAM_REQUEST,"Stream request cannot have more than one ID.");}if(ids.length===0){return;}if(sendTransceiver.csi!==policySpecificInfo.csi){logger.warn('csi in the StreamRequest does not match');return;}var id=ids[0];var codecInfo=codecInfos[0];if(!isValidSsrcStreamId(id)){logger.warn("".concat(mediaType,": The stream ID is not a valid SsrcStreamId: ").concat(JSON.stringify(id)));return;}var streamIdsMatched=sendTransceiver.senderIds.some(validId=>areStreamIdsEqual(id,validId));if(streamIdsMatched){var encodingIndex=sendTransceiver.getEncodingIndexForStreamId(id);if(encodingIndex!==-1){var encodingParams={maxPayloadBitsPerSecond};if(mediaFamily===MediaFamily.Video){encodingParams.maxFs=(_a=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_a===void 0?void 0:_a.maxFs;encodingParams.maxWidth=(_b=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_b===void 0?void 0:_b.maxWidth;encodingParams.maxHeight=(_c=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_c===void 0?void 0:_c.maxHeight;}requestedIdEncodingParamsMap.set(encodingIndex,encodingParams);}else {logger.warn("".concat(mediaType,": Unable to get encoding index for stream ID: ").concat(JSON.stringify(id)));}}else {logger.warn("".concat(mediaType,": Unable to find matching stream ID for requested ID: ").concat(JSON.stringify(id)));}});return sendTransceiver.updateSendParameters(requestedIdEncodingParamsMap);}createDataChannel(){var dataChannel=this.pc.createDataChannel('datachannel',{ordered:false,maxRetransmits:0});dataChannel.onopen=event=>{logger.info('DataChannel opened:',JSON.stringify(event));[...this.sendTransceivers.keys()].forEach(mediaType=>{this.sendSourceAdvertisement(mediaType);});logger.info("Flushing pending JMP task queue");this.pendingJmpTasks.forEach(t=>t());this.pendingJmpTasks=[];};dataChannel.onmessage=e=>{var parsed;try{parsed=JSON.parse(e.data);}catch(err){logger.error("Error parsing datachannel JSON: ".concat(err));return;}logger.debug('DataChannel got msg:',e.data);var homerMsg=HomerMsg.fromJson(parsed);if(!homerMsg){logger.error("Received invalid datachannel message: ".concat(e));return;}var jmpMsg=homerMsg.payload;if(!isValidJmpMsg(jmpMsg)){logger.error("Received invalid JMP msg: ".concat(JSON.stringify(jmpMsg)));return;}var mediaType=getMediaType(jmpMsg.mediaFamily,jmpMsg.mediaContent);var jmpSession=this.jmpSessions.get(mediaType);if(!jmpSession){logger.error("Unable to find JMP session for media type ".concat(mediaType,"."));return;}jmpSession.receive(jmpMsg);};dataChannel.onclose=event=>{logger.info('DataChannel closed:',JSON.stringify(event));};dataChannel.onerror=event=>{logger.info('DataChannel error:',JSON.stringify(event));};this.dataChannel=dataChannel;}close(){this.sendTransceivers.forEach(t=>t.close());this.recvTransceivers.forEach(recvTransceivers=>{recvTransceivers.forEach(t=>t.close());});this.jmpSessions.forEach(jmpSession=>jmpSession.close());this.pc.close();}sendMediaRequestStatus(mediaType){var _a;if(getMediaFamily(mediaType)!==MediaFamily.Video){return;}if(!this.getSendTransceiverOrThrow(mediaType).requested){return;}var streamStates=this.getVideoStreamStates(mediaType);var task=()=>{var _a;(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendMediaRequestStatus(streamStates);};if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}sendSourceAdvertisement(mediaType){var _a,_b;var transceiver=this.getSendTransceiverOrThrow(mediaType);var numLiveSources=((_a=transceiver.publishedStream)===null||_a===void 0?void 0:_a.muted)===false?1:0;var task;if(getMediaFamily(mediaType)===MediaFamily.Video){var sources=this.getVideoStreamStates(mediaType);if(sources===null){return;}var contentHint;if(transceiver.publishedStream&&mediaType===MediaType.VideoSlides){contentHint=transceiver.publishedStream.contentHint;}task=()=>{var _a;(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendSourceAdvertisement(1,numLiveSources,[],webRtcVideoContentHintToJmpVideoContentHint(contentHint));};}else {task=()=>{var _a;return (_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendSourceAdvertisement(1,numLiveSources,mediaType===MediaType.AudioMain?transceiver.namedMediaGroups:[]);};}if(((_b=this.dataChannel)===null||_b===void 0?void 0:_b.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}getVideoStreamStates(mediaType){var sendTransceiver=this.getSendTransceiverOrThrow(mediaType);return sendTransceiver.senderIds.map(id=>({id,state:sendTransceiver.currentSourceState,csi:sendTransceiver.csi}));}createReceiveTransceiver(mediaType){var rtcRtpTransceiver=this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'recvonly'});var mid=this.midPredictor.getNextMid(mediaType);var munger=new IngressSdpMunger();var recvOnlyTransceiver=new ReceiveOnlyTransceiver({rtcRtpTransceiver,mid,mediaType,munger});if(getMediaFamily(mediaType)===MediaFamily.Video){recvOnlyTransceiver.setCodecParameters({'sps-pps-idr-in-keyframe':'1'});recvOnlyTransceiver.setRtxCodecParameters({'rtx-time':mediaType===MediaType.VideoMain?defaultVideoMainRtxTime:defaultVideoSlidesRtxTime});}recvOnlyTransceiver.twccDisabled=getMediaFamily(mediaType)===MediaFamily.Audio?this.options.disableAudioTwcc:false;this.recvTransceivers.set(mediaType,[...(this.recvTransceivers.get(mediaType)||[]),recvOnlyTransceiver]);return recvOnlyTransceiver;}createReceiveSlot(mediaType){return __awaiter$1(this,void 0,void 0,function*(){return (yield this.createReceiveSlots(mediaType,1))[0];});}createReceiveSlots(mediaType){var count=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;return __awaiter$1(this,void 0,void 0,function*(){return new Promise(createReceiveSlotsResolve=>{this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var createdReceiveOnlyTransceivers=[];for(var i=0;i<count;i++){var recvOnlyTransceiver=this.createReceiveTransceiver(mediaType);createdReceiveOnlyTransceivers.push(recvOnlyTransceiver);}if(this.pc.getRemoteDescription()){yield this.doLocalOfferAnswer();}var receiveSlots=createdReceiveOnlyTransceivers.map(transceiver=>transceiver.receiveSlot);createReceiveSlotsResolve(receiveSlots);}));});});}getIngressPayloadType(mediaType,mimeType){var _a,_b,_c;var requestedMediaCodecType=mimeType.split('/')[1];var requestedMid=(_a=this.sendTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.mid;var parsedOffer=parse$1((_b=this.pc.getLocalDescription())===null||_b===void 0?void 0:_b.sdp);var parsedAnswer=parse$1((_c=this.pc.getRemoteDescription())===null||_c===void 0?void 0:_c.sdp);var senderCodecs=parsedAnswer.avMedia.filter(media=>requestedMid===media.mid).map(media=>[...media.codecs.values()]).flat().filter(ci=>ci.name===requestedMediaCodecType);var receiverCodecs=parsedOffer.avMedia.filter(media=>requestedMid===media.mid).map(media=>[...media.codecs.values()]).flat().filter(ci=>ci.name===requestedMediaCodecType);if(!senderCodecs||!receiverCodecs||senderCodecs.length===0||receiverCodecs.length===0){logErrorAndThrow(WcmeErrorType.GET_PAYLOAD_TYPE_FAILED,"Sender codecs or receiver codecs is undefined or empty.");}var senderCodec=senderCodecs[0];var targetCodec=receiverCodecs.find(receiverCodec=>{return areCodecsCompatible(senderCodec,receiverCodec);});if(!targetCodec||!targetCodec.pt){logErrorAndThrow(WcmeErrorType.GET_PAYLOAD_TYPE_FAILED,"Cannot find matching receiver codec for the given mediaType/mimeType.");}return targetCodec.pt;}waitForIceGatheringComplete(){return __awaiter$1(this,void 0,void 0,function*(){return new Promise(resolve=>{if(this.pc.iceGatheringState==='complete'){resolve();}else {this.pc.on(PeerConnection.Events.IceCandidate,candidate=>{if(candidate.candidate===null||this.options.stopIceGatheringAfterFirstRelayCandidate&&candidate.candidate.type==='relay'){resolve();}});this.pc.on(PeerConnection.Events.IceGatheringStateChange,()=>{if(this.pc.iceGatheringState==='complete'){resolve();}});}});});}createOffer(){return __awaiter$1(this,void 0,void 0,function*(){if(!this.pc.getLocalDescription()){this.midPredictor.allocateMidForDatachannel();}if(this.setAnswerResolve){logger.info('Canceling previous offer since setAnswer was never called for it');this.setAnswerResolve();this.setAnswerResolve=undefined;}var createOfferId=++this.currentCreateOfferId;return new Promise((createOfferResolve,createOfferReject)=>{this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var _a;try{var offer=yield this.pc.createOffer();if(!offer.sdp){logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,'SDP not found in offer.');}offer.sdp=this.preProcessLocalOffer(offer.sdp);yield this.pc.setLocalDescription(offer).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setLocalDescription() resolved');})).catch(error=>{var _a;logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,"Error: ".concat(error,". SDP: ").concat(maskIp((_a=offer.sdp)!==null&&_a!==void 0?_a:'')));});if(this.options.doFullIce){yield this.waitForIceGatheringComplete();}var sdpToSend=this.prepareLocalOfferForRemoteServer((_a=this.pc.getLocalDescription())===null||_a===void 0?void 0:_a.sdp);createOfferResolve({type:'offer',sdp:sdpToSend});if(this.currentCreateOfferId>createOfferId){logger.log('Canceling previous offer since createOffer was called while it was being created');}else {yield new Promise(setAnswerResolve=>{this.setAnswerResolve=setAnswerResolve;});}}catch(error){createOfferReject(error);}}));});});}setAnswer(answer){return __awaiter$1(this,void 0,void 0,function*(){var sdp=this.preProcessRemoteAnswer(answer);if(!this.setAnswerResolve){logErrorAndThrow(WcmeErrorType.SET_ANSWER_FAILED,"Call to setAnswer without having previously called createOffer.");}logger.info('calling this.pc.setRemoteDescription()');return this.pc.setRemoteDescription({type:'answer',sdp}).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setRemoteDescription() resolved');if(this.setAnswerResolve){this.setAnswerResolve();this.setAnswerResolve=undefined;}else {logger.debug("setAnswerResolve function was cleared between setAnswer and result of setRemoteDescription");}})).catch(error=>{logErrorAndThrow(WcmeErrorType.SET_ANSWER_FAILED,"Error: ".concat(error,". SDP: ").concat(maskIp(answer)));});});}doLocalOfferAnswer(){var _a;return __awaiter$1(this,void 0,void 0,function*(){var offer=yield this.pc.createOffer();if(!offer.sdp){logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,'SDP not found in offer.');}offer.sdp=this.preProcessLocalOffer(offer.sdp);yield this.pc.setLocalDescription(offer).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setLocalDescription() resolved');})).catch(error=>{var _a;logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,"Error: ".concat(error,". SDP: ").concat(maskIp((_a=offer.sdp)!==null&&_a!==void 0?_a:'')));});var answer=this.preProcessRemoteAnswer((_a=this.pc.getRemoteDescription())===null||_a===void 0?void 0:_a.sdp);return this.pc.setRemoteDescription({type:'answer',sdp:answer}).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setRemoteDescription() resolved');})).catch(error=>{logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,"Error: ".concat(error,". SDP: ").concat(maskIp(answer)));});});}queueLocalOfferAnswer(){return __awaiter$1(this,void 0,void 0,function*(){return this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){yield this.doLocalOfferAnswer();}));});}preProcessLocalOffer(offer){var parsedOffer=parse$1(offer);parsedOffer.avMedia.filter(av=>av.direction==='recvonly').forEach(av=>{var recvTransceiver=this.getRecvTransceiverByMidOrThrow(av.mid);recvTransceiver.mungeLocalDescription(av);});parsedOffer.avMedia.filter(av=>av.direction==='sendrecv'||av.direction==='inactive').forEach(av=>{var sendTransceiver=this.getSendTransceiverByMidOrThrow(av.mid);sendTransceiver.mungeLocalDescription(av);});if(BrowserInfo.isFirefox()){setupBundle(parsedOffer,this.options.bundlePolicy,this.midPredictor.getMidMap());}return parsedOffer.toString();}prepareLocalOfferForRemoteServer(offer){var parsedOffer=parse$1(offer);var shouldInjectDummyCandidates=()=>{if(!this.options.doFullIce){return true;}return !hasIceCandidates(parsedOffer);};var mungeOptions={injectDummyCandidates:shouldInjectDummyCandidates()};parsedOffer.avMedia.filter(av=>av.direction==='sendrecv'||av.direction==='inactive').forEach(av=>{var sendTransceiver=this.getSendTransceiverByMidOrThrow(av.mid);sendTransceiver.mungeLocalDescriptionForRemoteServer(av,mungeOptions);});if(mungeOptions.injectDummyCandidates){parsedOffer.media.filter(media=>media instanceof ApplicationMediaDescription$1).forEach(media=>{injectDummyCandidates(media);});}if(BrowserInfo.isFirefox()&&this.options.doFullIce){parsedOffer.media.forEach(media=>{media.iceInfo.candidates=[];this.iceCandidates.forEach(iceCandidate=>{var candidateLine=CandidateLine$1.fromSdpLine(iceCandidate.candidate.toString());if(candidateLine){media.addLine(candidateLine);}});});}if(BrowserInfo.isFirefox()){setupBundle(parsedOffer,this.options.bundlePolicy,this.midPredictor.getMidMap());if(this.options.bundlePolicy==='max-bundle'){parsedOffer.media.forEach((media,index)=>{if(index>0){media.port=parsedOffer.media[0].port;}});}}filterRecvOnlyMediaDescriptions(parsedOffer);return parsedOffer.toString();}preProcessRemoteAnswer(answer){var _a,_b;var parsedAnswer=parse$1(answer);var parsedOffer=parse$1((_a=this.pc.getLocalDescription())===null||_a===void 0?void 0:_a.sdp);matchMediaDescriptionsInAnswer(parsedOffer,parsedAnswer);parsedAnswer.avMedia.filter(av=>av.direction==='sendonly').forEach(av=>{var recvTransceiver=this.getRecvTransceiverByMidOrThrow(av.mid);recvTransceiver.mungeRemoteDescription(av);});parsedAnswer.avMedia.filter(av=>av.direction==='sendrecv'||av.direction==='recvonly').forEach(av=>{var sendTransceiver=this.getSendTransceiverByMidOrThrow(av.mid);sendTransceiver.mungeRemoteDescription(av);});parsedAnswer.media.filter(media=>media instanceof ApplicationMediaDescription$1).forEach(media=>{if(retainCandidatesByTransportType(media,['udp','tcp'])){logger.log("Some unsupported remote candidates have been removed from mid ".concat(media.mid));}});if(BrowserInfo.isFirefox()){setupBundle(parsedAnswer,this.options.bundlePolicy,this.midPredictor.getMidMap());}if((_b=parsedAnswer.session.information)===null||_b===void 0?void 0:_b.info){this.metadata.isMediaBypassEdge=!parsedAnswer.session.information.info.includes('linus');}return parsedAnswer.toString();}getSendTransceiverOrThrow(mediaType){var sendTransceiver=this.sendTransceivers.get(mediaType);if(!sendTransceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find send transceiver for media type ".concat(mediaType,"."));}return sendTransceiver;}getSendTransceiverByMidOrThrow(mid){var transceiver=[...this.sendTransceivers.values()].find(t=>t.mid===mid);if(!transceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find send transceiver with MID ".concat(mid,"."));}return transceiver;}getRecvTransceiverByMidOrThrow(mid){var transceiver=[...this.recvTransceivers.values()].flat().find(t=>t.mid===mid);if(!transceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find recv transceiver with MID ".concat(mid,"."));}return transceiver;}requestMedia(mediaType,streamRequests){var _a;var task=()=>{var _a;var jmpSession=this.jmpSessions.get(mediaType);if(!jmpSession){logger.error("Unable to find jmp session for ".concat(mediaType));return;}var requestedReceiveSlotIds=[];streamRequests.forEach(request=>{if(request.receiveSlots.length===0){logger.error('Stream request ids cannot be empty.');return;}request.receiveSlots.forEach(slot=>{if(!slot.id){logger.error('Running stream request task, but ReceiveSlot ID is missing.');}if(!requestedReceiveSlotIds.some(id=>areStreamIdsEqual(id,slot.id))){requestedReceiveSlotIds.push(slot.id);}else {logger.error("Stream id duplicate found ".concat(JSON.stringify(slot.id),"."));}});});jmpSession.sendRequests(streamRequests.map(sr=>sr._toJmpStreamRequest()));(_a=this.recvTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.forEach(transceiver=>{if(requestedReceiveSlotIds.some(id=>areStreamIdsEqual(id,transceiver.receiveSlot.id))){var relevantRequest=streamRequests.find(request=>request.receiveSlots.some(slot=>areStreamIdsEqual(slot.id,transceiver.receiveSlot.id)));transceiver.handleRequested(relevantRequest);}else {transceiver.handleUnrequested();}});};if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}renewPeerConnection(userOptions){var _a;return __awaiter$1(this,void 0,void 0,function*(){(_a=this.pc)===null||_a===void 0?void 0:_a.close();try{if(userOptions){this.options=Object.assign(Object.assign({},this.options),yield userOptions);}}catch(error){logErrorAndThrow(WcmeErrorType.RENEW_PEER_CONNECTION_FAILED,"Error while awaiting user options: ".concat(error));}logger.info("Renewing multistream connection with options ".concat(JSON.stringify(this.options)));this.midPredictor.reset();this.initializePeerConnection();var mainSceneId=generateSceneId();var slidesSceneId=generateSceneId();this.sendTransceivers.forEach((transceiver,mediaType)=>{var _a;var mediaContent=getMediaContent(mediaType);var sceneId=mediaContent===MediaContent.Main?mainSceneId:slidesSceneId;var mid=this.midPredictor.getNextMid(mediaType);transceiver.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'sendrecv',sendEncodings:getMediaFamily(mediaType)===MediaFamily.Video?this.getVideoEncodingOptions(mediaContent):undefined}));transceiver.mid=mid;transceiver.csi=generateCsi(getMediaFamily(mediaType),sceneId);transceiver.resetSdpMunger();(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.close();this.createJmpSession(mediaType);});this.recvTransceivers.forEach((transceivers,mediaType)=>{transceivers.forEach(t=>{var mid=this.midPredictor.getNextMid(mediaType);t.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'recvonly'}));t.mid=mid;});});});}getReceiveSlotById(id){return [...this.recvTransceivers.values()].flat().map(transceiver=>transceiver.receiveSlot).find(receiveSlot=>{var receiveSlotId=receiveSlot.id||{};return Object.keys(receiveSlotId).length===Object.keys(id).length&&Object.keys(receiveSlotId).every(key=>Object.prototype.hasOwnProperty.call(id,key)&&receiveSlotId[key]===id[key]);});}getStats(){return this.statsManager.getStats();}getTransceiverStats(){return __awaiter$1(this,void 0,void 0,function*(){var stats=yield this.getStats();var peerConnectionStats=[...stats.values()].find(stat=>stat.type==='peer-connection');return organizeTransceiverStats(this.sendTransceivers,this.recvTransceivers,peerConnectionStats);});}preProcessStats(stats){return __awaiter$1(this,void 0,void 0,function*(){stats.forEach(stat=>{if(stat.type==='peer-connection'){stat.isMediaBypassEdge=this.metadata.isMediaBypassEdge;}});yield Promise.all([...this.sendTransceivers.values()].map(transceiver=>__awaiter$1(this,void 0,void 0,function*(){(yield transceiver.getStats()).forEach(senderStats=>{if(senderStats.type==='outbound-rtp'||senderStats.type==='media-source'){stats.set(senderStats.id,senderStats);}});})));yield Promise.all([...this.recvTransceivers.values()].map(transceivers=>__awaiter$1(this,void 0,void 0,function*(){yield Promise.all(transceivers.map(transceiver=>__awaiter$1(this,void 0,void 0,function*(){(yield transceiver.getStats()).forEach(receiverStats=>{if(receiverStats.type==='inbound-rtp'){stats.set(receiverStats.id,receiverStats);}});})));})));});}attachMetricsObserver(){this.forceStatsReport=rtcStats_1(this.pc.getUnderlyingRTCPeerConnection(),data=>this.metricsCallback(data),5000,stats=>this.preProcessStats(stats)).forceStatsReport;}forceRtcMetricsCallback(){var _a;return (_a=this.forceStatsReport)===null||_a===void 0?void 0:_a.call(this);}setOveruseUpdateCallback(callback){this.overuseUpdateCallback=callback;}getCsiByMediaType(mediaType){var _a;return (_a=this.sendTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.csi;}getAllCsis(){return {audioMain:this.getCsiByMediaType(MediaType.AudioMain),audioSlides:this.getCsiByMediaType(MediaType.AudioSlides),videoMain:this.getCsiByMediaType(MediaType.VideoMain),videoSlides:this.getCsiByMediaType(MediaType.VideoSlides)};}}class StreamRequest{constructor(policy,policySpecificInfo,receiveSlots,maxPayloadBitsPerSecond){var codecInfos=arguments.length>4&&arguments[4]!==undefined?arguments[4]:[];this.policy=policy;this.policySpecificInfo=policySpecificInfo;this.receiveSlots=receiveSlots;this.maxPayloadBitsPerSecond=maxPayloadBitsPerSecond;this.codecInfos=codecInfos;}_toJmpStreamRequest(){return new StreamRequest$1(this.policy,this.policySpecificInfo,this.receiveSlots.map(rs=>rs.id),this.maxPayloadBitsPerSecond,this.codecInfos);}}
5611
+ */function waterfall(tasks,callback){callback=once(callback);if(!Array.isArray(tasks))return callback(new Error('First argument to waterfall must be an array of functions'));if(!tasks.length)return callback();var taskIndex=0;function nextTask(args){var task=wrapAsync(tasks[taskIndex++]);task(...args,onlyOnce(next));}function next(err){if(err===false)return;for(var _len22=arguments.length,args=new Array(_len22>1?_len22-1:0),_key22=1;_key22<_len22;_key22++){args[_key22-1]=arguments[_key22];}if(err||taskIndex===tasks.length){return callback(err,...args);}nextTask(args);}nextTask([]);}awaitify(waterfall);function processTasks(task,finishedCallback){return __awaiter$1(this,void 0,void 0,function*(){try{yield task();finishedCallback();}catch(e){finishedCallback(e);}});}class AsyncQueue{constructor(){this.queue=queue$1(processTasks,1);}push(task){return this.queue.pushAsync(task);}empty(){return this.queue.empty();}}var NOISE_REDUCTION_KIND='noise-reduction-effect';var VIRTUAL_BACKGROUND_KIND='virtual-background-effect';var isNoiseReductionEffect=effect=>{return (effect===null||effect===void 0?void 0:effect.kind)===NOISE_REDUCTION_KIND;};var isVirtualBackgroundEffect=effect=>{return (effect===null||effect===void 0?void 0:effect.kind)===VIRTUAL_BACKGROUND_KIND;};var OfferAnswerType;(function(OfferAnswerType){OfferAnswerType[OfferAnswerType["LocalOnly"]=0]="LocalOnly";OfferAnswerType[OfferAnswerType["Remote"]=1]="Remote";})(OfferAnswerType||(OfferAnswerType={}));class SendOnlyTransceiver extends Transceiver{constructor(config){super(config);this.rtxEnabled=false;this.dtxDisabled=true;this.streamMuteStateChange=new TypedEvent();this.streamReadyStateChanged=new TypedEvent();this.streamPublishStateChange=new TypedEvent();this.negotiationNeeded=new TypedEvent();this.namedMediaGroupsChange=new TypedEvent();this.requestedIdEncodingParamsMap=new Map();this.updateSendParametersQueue=new AsyncQueue();this.sourceStateOverrideChange=new TypedEvent();this.metadata={lastRequestedUpdateTimestampsMap:new Map()};this.munger=config.munger;this.csi=config.csi;this.direction='sendrecv';this.handleTrackChange=this.handleTrackChange.bind(this);this.handleStreamConstraintsChange=this.handleStreamConstraintsChange.bind(this);this.handleStreamMuteStateChange=this.handleStreamMuteStateChange.bind(this);this.handleStreamEnded=this.handleStreamEnded.bind(this);}replaceSenderSource(stream){var _a,_b;return __awaiter$1(this,void 0,void 0,function*(){var trackOrNull=(_a=stream===null||stream===void 0?void 0:stream.outputStream.getTracks()[0])!==null&&_a!==void 0?_a:null;if(((_b=this.sender.track)===null||_b===void 0?void 0:_b.id)!==(trackOrNull===null||trackOrNull===void 0?void 0:trackOrNull.id)){yield this.sender.replaceTrack(trackOrNull);if(trackOrNull){logger.log("Sender source for ".concat(this.mediaType," replaced with track ID ").concat(trackOrNull.id));}else {logger.log("Sender source for ".concat(this.mediaType," set to null, sender stopped"));}}});}handleTrackChange(){return __awaiter$1(this,void 0,void 0,function*(){if(this.requested){yield this.replaceSenderSource(this.publishedStream);}});}handleStreamConstraintsChange(){return __awaiter$1(this,void 0,void 0,function*(){yield this.updateSendParameters(this.requestedIdEncodingParamsMap);});}handleStreamMuteStateChange(){this.streamMuteStateChange.emit();}handleStreamEnded(){this.streamReadyStateChanged.emit();}get requested(){return this.requestedIdEncodingParamsMap.size>0;}replaceTransceiver(newRtcRtpTransceiver){var _super=Object.create(null,{replaceTransceiver:{get:()=>super.replaceTransceiver}});return __awaiter$1(this,void 0,void 0,function*(){_super.replaceTransceiver.call(this,newRtcRtpTransceiver);newRtcRtpTransceiver.direction=this.direction;if(this.requested){yield this.replaceSenderSource(this.publishedStream);}});}replacePublishedStream(newStream){return __awaiter$1(this,void 0,void 0,function*(){var oldStream=this.publishedStream;oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.UserMuteStateChange,this.handleStreamMuteStateChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.SystemMuteStateChange,this.handleStreamMuteStateChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(StreamEventNames.Ended,this.handleStreamEnded);if(this.requested){yield this.replaceSenderSource(newStream);}this.publishedStream=newStream;newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.UserMuteStateChange,this.handleStreamMuteStateChange);newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.SystemMuteStateChange,this.handleStreamMuteStateChange);newStream===null||newStream===void 0?void 0:newStream.on(StreamEventNames.Ended,this.handleStreamEnded);if(!oldStream&&newStream||oldStream&&!newStream){this.streamPublishStateChange.emit();}if(oldStream&&newStream){if(oldStream.muted!==newStream.muted){this.streamMuteStateChange.emit();}if(oldStream.readyState!==newStream.readyState){this.streamReadyStateChanged.emit();}}});}setNamedMediaGroups(namedMediaGroups){if(this.mediaType!==MediaType.AudioMain){logErrorAndThrow(WcmeErrorType.SET_NMG_FAILED,"Named media groups can only be set for audio.");}this.namedMediaGroups=namedMediaGroups;this.namedMediaGroupsChange.emit();}publishStream(stream){return this.replacePublishedStream(stream);}unpublishStream(){return this.replacePublishedStream();}get active(){return this._rtcRtpTransceiver.direction==='sendrecv';}set active(enabled){this.direction=enabled?'sendrecv':'inactive';this._rtcRtpTransceiver.direction=this.direction;if(this._rtcRtpTransceiver.direction!==this._rtcRtpTransceiver.currentDirection){this.negotiationNeeded.emit(OfferAnswerType.Remote);}}getStats(){return __awaiter$1(this,void 0,void 0,function*(){var statsMap=new Map();var statsReport=yield this.sender.getStats();statsReport.forEach((stats,key)=>{var _a,_b,_c,_d,_e;if(stats.type==='outbound-rtp'){stats.mid=this.mid;stats.csi=this.csi;stats.sourceState=this.currentSourceState;stats.calliopeMediaType=this.mediaType;var senderId=this.munger.getSenderIds().find(id=>id.ssrc===stats.ssrc);if(senderId){var encodingIndex=this.getEncodingIndexForStreamId(senderId);var encodingParams=this.requestedIdEncodingParamsMap.get(encodingIndex);stats.requestedBitrate=encodingParams===null||encodingParams===void 0?void 0:encodingParams.maxPayloadBitsPerSecond;stats.requestedFrameSize=encodingParams===null||encodingParams===void 0?void 0:encodingParams.maxFs;stats.isRequested=!!encodingParams;stats.lastRequestedUpdateTimestamp=this.metadata.lastRequestedUpdateTimestampsMap.get(encodingIndex);}var effect=(_b=(_a=this.publishedStream)===null||_a===void 0?void 0:_a.getEffects())===null||_b===void 0?void 0:_b[0];if(effect===null||effect===void 0?void 0:effect.isEnabled){if(isNoiseReductionEffect(effect)){stats.effect={kind:effect.kind,noiseReductionMode:'LOW_POWER'};}else if(isVirtualBackgroundEffect(effect)){stats.effect={kind:effect.kind,virtualBackgroundMode:(_c=effect.options)===null||_c===void 0?void 0:_c.mode};}else {stats.effect={kind:effect.kind};}}var trackSettings=(_d=this.publishedStream)===null||_d===void 0?void 0:_d.getSettings();if(trackSettings===null||trackSettings===void 0?void 0:trackSettings.frameRate){stats.targetFrameRate=trackSettings===null||trackSettings===void 0?void 0:trackSettings.frameRate;}}else if(stats.type==='media-source'){stats.calliopeMediaType=this.mediaType;stats.trackLabel=(_e=this.publishedStream)===null||_e===void 0?void 0:_e.label;}statsMap.set(key,stats);});return statsMap;});}updateSendParameters(requestedIdEncodingParamsMap){return __awaiter$1(this,void 0,void 0,function*(){return this.updateSendParametersQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var sendParameters=this.sender.getParameters();sendParameters.encodings.forEach((encoding,index)=>{var _a,_b;var encodingParams=requestedIdEncodingParamsMap.get(index);encoding.active=!!encodingParams;if(encodingParams){var{maxPayloadBitsPerSecond,maxFs,maxWidth,maxHeight}=encodingParams;var scaleDownRatio=getScaleDownRatio((_a=this.publishedStream)===null||_a===void 0?void 0:_a.getSettings().width,(_b=this.publishedStream)===null||_b===void 0?void 0:_b.getSettings().height,maxFs,maxWidth,maxHeight);if(maxPayloadBitsPerSecond!==undefined&&maxPayloadBitsPerSecond>=0){encoding.maxBitrate=maxPayloadBitsPerSecond;}if(scaleDownRatio!==undefined&&scaleDownRatio>=1.0){encoding.scaleResolutionDownBy=scaleDownRatio;}}});yield this.sender.setParameters(sendParameters);logger.log("Sender parameters for ".concat(this.mediaType," set to ").concat(JSON.stringify(sendParameters)));var timestamp=getCurrentTimestamp();requestedIdEncodingParamsMap.forEach((_,index)=>{if(!this.requestedIdEncodingParamsMap.has(index)){this.metadata.lastRequestedUpdateTimestampsMap.set(index,timestamp);}});this.requestedIdEncodingParamsMap.forEach((_,index)=>{if(!requestedIdEncodingParamsMap.has(index)){this.metadata.lastRequestedUpdateTimestampsMap.set(index,timestamp);}});var oldRequested=this.requested;var newRequested=requestedIdEncodingParamsMap.size>0;this.requestedIdEncodingParamsMap=requestedIdEncodingParamsMap;if(oldRequested!==newRequested){yield this.replaceSenderSource(newRequested?this.publishedStream:null);}}));});}isSimulcastEnabled(){var params=this.sender.getParameters();return params.encodings.length>1;}mungeLocalDescription(mediaDescription){this.munger.mungeLocalDescription(mediaDescription,{simulcastEnabled:this.isSimulcastEnabled(),rtxEnabled:this.rtxEnabled,twccDisabled:this.twccDisabled,forceSoftwareEncoder:this.mediaType===MediaType.VideoSlides&&(BrowserInfo.isWindows()||BrowserInfo.isMac())&&(BrowserInfo.isChrome()||BrowserInfo.isEdge())});}mungeLocalDescriptionForRemoteServer(mediaDescription){var mungeOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{injectDummyCandidates:true};this.munger.mungeLocalDescriptionForRemoteServer(mediaDescription,getMediaContent(this.mediaType),this.csi,mungeOptions);}mungeRemoteDescription(mediaDescription){this.munger.mungeRemoteDescription(mediaDescription,{dtxDisabled:this.dtxDisabled});}get senderIds(){return this.munger.getSenderIds();}get numActiveSimulcastLayers(){var _a;if(getMediaFamily(this.mediaType)===MediaFamily.Video){return (_a=this.publishedStream)===null||_a===void 0?void 0:_a.getNumActiveSimulcastLayers();}return this.publishedStream?0:undefined;}getEncodingIndexForStreamId(id){return this.munger.getEncodingIndexForStreamId(id);}resetSdpMunger(){this.munger.reset();}setCodecParameters(parameters){this.munger.setCodecParameters(parameters);this.negotiationNeeded.emit(OfferAnswerType.LocalOnly);}deleteCodecParameters(parameters){this.munger.deleteCodecParameters(parameters);this.negotiationNeeded.emit(OfferAnswerType.LocalOnly);}setSourceStateOverride(state){if(getMediaFamily(this.mediaType)!==MediaFamily.Video){logErrorAndThrow(WcmeErrorType.SET_SOURCE_STATE_OVERRIDE_FAILED,"Source state can only be overridden for video.");}this.sourceStateOverride=state;this.sourceStateOverrideChange.emit();}get currentSourceState(){if(getMediaFamily(this.mediaType)!==MediaFamily.Video){return undefined;}if(this.sourceStateOverride){return this.sourceStateOverride;}if(!this.publishedStream){return 'no source';}if(this.publishedStream.muted){return 'avatar';}return 'live';}}class SendSlot{constructor(sendTransceiver){this.sendTransceiver=sendTransceiver;}publishStream(stream){return __awaiter$1(this,void 0,void 0,function*(){if(stream===this.sendTransceiver.publishedStream){return Promise.resolve();}return this.sendTransceiver.publishStream(stream);});}unpublishStream(){return __awaiter$1(this,void 0,void 0,function*(){if(!this.sendTransceiver.publishedStream){return Promise.resolve();}return this.sendTransceiver.unpublishStream();});}setNamedMediaGroups(namedMediaGroups){this.sendTransceiver.setNamedMediaGroups(namedMediaGroups);}clearNamedMediaGroups(){this.setNamedMediaGroups([]);}get active(){return this.sendTransceiver.active;}set active(active){this.sendTransceiver.active=active;}setCodecParameters(parameters){return __awaiter$1(this,void 0,void 0,function*(){this.sendTransceiver.setCodecParameters(parameters);});}deleteCodecParameters(parameters){return __awaiter$1(this,void 0,void 0,function*(){this.sendTransceiver.deleteCodecParameters(parameters);});}setSourceStateOverride(state){this.sendTransceiver.setSourceStateOverride(state);}clearSourceStateOverride(){this.sendTransceiver.setSourceStateOverride(undefined);}}var organizeTransceiverStats=(sendTransceivers,recvTransceivers,peerConnectionStats)=>__awaiter$1(void 0,void 0,void 0,function*(){var result={audio:{senders:[],receivers:[]},video:{senders:[],receivers:[]},screenShareAudio:{senders:[],receivers:[]},screenShareVideo:{senders:[],receivers:[]}};yield Promise.all([...sendTransceivers.entries()].map(_ref7=>{var[mediaType,transceiver]=_ref7;return __awaiter$1(void 0,void 0,void 0,function*(){var _a;var item={report:yield transceiver.getStats(),mid:transceiver.mid,csi:transceiver.csi,currentDirection:'sendonly',localTrackLabel:(_a=transceiver.publishedStream)===null||_a===void 0?void 0:_a.label};if(peerConnectionStats&&peerConnectionStats.id){item.report.set(peerConnectionStats.id,peerConnectionStats);}if(mediaType===MediaType.AudioMain){result.audio.senders.push(item);}if(mediaType===MediaType.VideoMain){result.video.senders.push(item);}if(mediaType===MediaType.AudioSlides){result.screenShareAudio.senders.push(item);}if(mediaType===MediaType.VideoSlides){result.screenShareVideo.senders.push(item);}});}));yield Promise.all([...recvTransceivers.entries()].map(_ref8=>{var[mediaType,transceivers]=_ref8;return __awaiter$1(void 0,void 0,void 0,function*(){return Promise.all(transceivers.map(t=>__awaiter$1(void 0,void 0,void 0,function*(){var _b;var item={report:yield t.getStats(),csi:t.receiveSlot.currentRxCsi,currentDirection:'recvonly',localTrackLabel:(_b=t.receiveSlot.stream.getTracks()[0])===null||_b===void 0?void 0:_b.label};if(peerConnectionStats&&peerConnectionStats.id){item.report.set(peerConnectionStats.id,peerConnectionStats);}if(mediaType===MediaType.AudioMain){result.audio.receivers.push(item);}if(mediaType===MediaType.VideoMain){result.video.receivers.push(item);}if(mediaType===MediaType.AudioSlides){result.screenShareAudio.receivers.push(item);}if(mediaType===MediaType.VideoSlides){result.screenShareVideo.receivers.push(item);}})));});}));return result;});function toMediaStreamTrackKind(mediaType){return [MediaType.VideoMain,MediaType.VideoSlides].includes(mediaType)?MediaStreamTrackKind.Video:MediaStreamTrackKind.Audio;}function webRtcVideoContentHintToJmpVideoContentHint(hint){if(hint==='motion'){return 'motion';}if(hint==='detail'){return 'sharpness';}return undefined;}var MultistreamConnectionEventNames;(function(MultistreamConnectionEventNames){MultistreamConnectionEventNames["VideoSourceCountUpdate"]="video-source-count-update";MultistreamConnectionEventNames["AudioSourceCountUpdate"]="audio-source-count-update";MultistreamConnectionEventNames["ActiveSpeakerNotification"]="active-speaker-notification";MultistreamConnectionEventNames["PeerConnectionStateUpdate"]="peer-connection-state-update";MultistreamConnectionEventNames["IceConnectionStateUpdate"]="ice-connection-state-update";MultistreamConnectionEventNames["IceGatheringStateUpdate"]="ice-gathering-state-update";MultistreamConnectionEventNames["NegotiationNeeded"]="negotiation-needed";MultistreamConnectionEventNames["CreateOfferOnSuccess"]="createofferonsuccess";MultistreamConnectionEventNames["CreateAnswerOnSuccess"]="createansweronsuccess";MultistreamConnectionEventNames["SetLocalDescriptionOnSuccess"]="setlocaldescriptiononsuccess";MultistreamConnectionEventNames["SetRemoteDescriptionOnSuccess"]="setremotedescriptiononsuccess";MultistreamConnectionEventNames["IceCandidate"]="icecandidate";MultistreamConnectionEventNames["IceCandidateError"]="icecandidateerror";})(MultistreamConnectionEventNames||(MultistreamConnectionEventNames={}));var defaultMultistreamConnectionOptions={disableSimulcast:BrowserInfo.isFirefox(),bundlePolicy:'max-compat',iceServers:undefined,iceTransportPolicy:'all',disableContentSimulcast:true,disableAudioTwcc:true,doFullIce:BrowserInfo.isFirefox(),stopIceGatheringAfterFirstRelayCandidate:false,disableAudioMainDtx:true,metricsCallback:()=>{}};class MultistreamConnection extends EventEmitter$2{constructor(){var userOptions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};super();this.sendTransceivers=new Map();this.recvTransceivers=new Map();this.jmpSessions=new Map();this.pendingJmpTasks=[];this.overuseUpdateCallback=()=>{};this.midPredictor=new MidPredictor();this.offerAnswerQueue=new AsyncQueue();this.currentCreateOfferId=0;this.metadata={isMediaBypassEdge:false};this.options=Object.assign(Object.assign({},defaultMultistreamConnectionOptions),userOptions);logger.info("Creating multistream connection with options ".concat(JSON.stringify(this.options)));this.metricsCallback=this.options.metricsCallback;this.initializePeerConnection();this.overuseStateManager=new OveruseStateManager(overuseState=>this.overuseUpdateCallback(overuseState));this.overuseStateManager.start();this.statsManager=new StatsManager(()=>this.pc.getStats(),stats=>this.preProcessStats(stats));var mainSceneId=generateSceneId();var slidesSceneId=generateSceneId();var videoMainEncodingOptions=this.getVideoEncodingOptions(MediaContent.Main);var videoSlidesEncodingOptions=this.getVideoEncodingOptions(MediaContent.Slides);this.createSendTransceiver(MediaType.VideoMain,mainSceneId,videoMainEncodingOptions);this.createSendTransceiver(MediaType.AudioMain,mainSceneId);this.createSendTransceiver(MediaType.VideoSlides,slidesSceneId,videoSlidesEncodingOptions);this.createSendTransceiver(MediaType.AudioSlides,slidesSceneId);}initializePeerConnection(){this.pc=new PeerConnection({iceServers:this.options.iceServers,bundlePolicy:this.options.bundlePolicy,iceTransportPolicy:this.options.iceTransportPolicy});this.propagatePeerConnectionEvents();this.attachMetricsObserver();this.createDataChannel();}propagatePeerConnectionEvents(){this.pc.on(PeerConnection.Events.PeerConnectionStateChange,state=>{this.emit(MultistreamConnectionEventNames.PeerConnectionStateUpdate,state);});this.pc.on(PeerConnection.Events.IceConnectionStateChange,state=>{this.emit(MultistreamConnectionEventNames.IceConnectionStateUpdate,state);});this.pc.on(PeerConnection.Events.CreateOfferOnSuccess,description=>{this.emit(MultistreamConnectionEventNames.CreateOfferOnSuccess,description);});this.pc.on(PeerConnection.Events.CreateAnswerOnSuccess,description=>{this.emit(MultistreamConnectionEventNames.CreateAnswerOnSuccess,description);});this.pc.on(PeerConnection.Events.SetLocalDescriptionOnSuccess,description=>{this.emit(MultistreamConnectionEventNames.SetLocalDescriptionOnSuccess,description);});this.pc.on(PeerConnection.Events.SetRemoteDescriptionOnSuccess,description=>{this.emit(MultistreamConnectionEventNames.SetRemoteDescriptionOnSuccess,description);});this.pc.on(PeerConnection.Events.IceGatheringStateChange,()=>{this.emit(MultistreamConnectionEventNames.IceGatheringStateUpdate,this.getIceGatheringState());});this.pc.on(PeerConnection.Events.IceCandidate,candidate=>{this.emit(MultistreamConnectionEventNames.IceCandidate,candidate);});this.pc.on(PeerConnection.Events.IceCandidateError,error=>{this.emit(MultistreamConnectionEventNames.IceCandidateError,error);});}getConnectionState(){return this.pc.getConnectionState();}getPeerConnectionState(){return this.pc.getPeerConnectionState();}getIceConnectionState(){return this.pc.getIceConnectionState();}getCurrentConnectionType(){return this.pc.getCurrentConnectionType();}getIceGatheringState(){return this.pc.iceGatheringState;}getVideoEncodingOptions(content){var enabledSimulcast=content===MediaContent.Main?!this.options.disableSimulcast:!this.options.disableContentSimulcast;return enabledSimulcast?[{scaleResolutionDownBy:4,active:false},{scaleResolutionDownBy:2,active:false},{active:false}]:[{active:false}];}createSendTransceiver(mediaType,sceneId,sendEncodingsOptions){var rtcRtpTransceiver;try{rtcRtpTransceiver=this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'sendrecv',sendEncodings:sendEncodingsOptions});}catch(e){logger.error("addTransceiver failed due to : ".concat(e));throw e;}var mid=this.midPredictor.getNextMid(mediaType);var csi=generateCsi(getMediaFamily(mediaType),sceneId);var munger=new EgressSdpMunger();var transceiver=new SendOnlyTransceiver({rtcRtpTransceiver,mid,mediaType,munger,csi});if(getMediaFamily(mediaType)===MediaFamily.Video){transceiver.rtxEnabled=true;transceiver.setCodecParameters({'max-mbps':"".concat(defaultMaxVideoEncodeMbps),'max-fs':"".concat(defaultMaxVideoEncodeFrameSize)});}transceiver.twccDisabled=getMediaFamily(mediaType)===MediaFamily.Audio?this.options.disableAudioTwcc:false;transceiver.dtxDisabled=mediaType!==MediaType.AudioMain||this.options.disableAudioMainDtx;transceiver.active=false;transceiver.streamMuteStateChange.on(()=>{this.sendSourceAdvertisement(mediaType);this.sendMediaRequestStatus(mediaType);});transceiver.streamPublishStateChange.on(()=>{this.sendSourceAdvertisement(mediaType);this.sendMediaRequestStatus(mediaType);});transceiver.streamReadyStateChanged.on(()=>{this.sendSourceAdvertisement(mediaType);this.sendMediaRequestStatus(mediaType);});transceiver.negotiationNeeded.on(offerAnswerType=>{if(offerAnswerType===OfferAnswerType.Remote){this.emit(MultistreamConnectionEventNames.NegotiationNeeded);}else if(this.pc.getRemoteDescription()){this.queueLocalOfferAnswer();}});transceiver.namedMediaGroupsChange.on(()=>{this.sendSourceAdvertisement(mediaType);});transceiver.sourceStateOverrideChange.on(()=>{this.sendMediaRequestStatus(mediaType);});this.sendTransceivers.set(mediaType,transceiver);this.createJmpSession(mediaType);}createSendSlot(mediaType){var active=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var transceiver=this.getSendTransceiverOrThrow(mediaType);transceiver.active=active;return new SendSlot(transceiver);}createJmpSession(mediaType){var jmpSession=new JmpSession(getMediaFamily(mediaType),getMediaContent(mediaType));jmpSession.setTxCallback(jmpMessage=>{var _a;if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)!=='open'){logger.error("DataChannel not created or not connected. Unable to send JMP message.");return;}var homerMsg=new HomerMsg(HomerMsgType.Multistream,jmpMessage);var serializedHomerMsg=JSON.stringify(homerMsg);try{logger.info("Sending JMP message: ".concat(serializedHomerMsg));this.dataChannel.send(serializedHomerMsg);}catch(err){var{bufferedAmount,readyState}=this.dataChannel;var{sctp}=this.pc.getUnderlyingRTCPeerConnection();var{maxMessageSize,state}=sctp||{};logErrorAndThrow(WcmeErrorType.DATA_CHANNEL_SEND_FAILED,"Sending JMP message failed with error: ".concat(err,",\nMessage size: ").concat(serializedHomerMsg.length,",\nData Channel State: ").concat(readyState,",\nData Channel Buffered amount: ").concat(bufferedAmount,",\nSCTP State: ").concat(state,",\nSCTP Max Message Size: ").concat(maxMessageSize));}});var prevNumTotalSources=0;var prevNumLiveSources=0;jmpSession.on(JmpSessionEvents.SourceAdvertisementReceived,data=>{logger.log("SourceAdvertisement received: ".concat(JSON.stringify(data)));if(data.numTotalSources!==prevNumTotalSources||data.numLiveSources!==prevNumLiveSources){prevNumTotalSources=data.numTotalSources;prevNumLiveSources=data.numLiveSources;var eventName=getMediaFamily(mediaType)===MediaFamily.Video?MultistreamConnectionEventNames.VideoSourceCountUpdate:MultistreamConnectionEventNames.AudioSourceCountUpdate;this.emit(eventName,data.numTotalSources,data.numLiveSources,getMediaContent(mediaType));}else {logger.log('Number of sources was unchanged, ignoring message');}});jmpSession.on(JmpSessionEvents.MediaRequestStatusReceived,data=>{logger.log("MediaRequestStatus received: ".concat(JSON.stringify(data)));data.streamStates.forEach(s=>{if(!isValidSsrcStreamId(s.id)){logger.error("Received MediaRequestStatus with non-SSRC based stream ID, which is currently not supported: ".concat(JSON.stringify(s.id)));return;}var receiveSlot=this.getReceiveSlotById(s.id);if(!receiveSlot){logger.warn("Got MediaRequestStatus for unknown receive slot: ".concat(JSON.stringify(s.id)));return;}if(!receiveSlot._isRequested){logger.info("MediaRequestStatus ignored due to transceiver's receive slot unrequested: ".concat(JSON.stringify(s.id)," csi ").concat(s.csi));return;}receiveSlot._updateSource(s.state,s.csi);});});jmpSession.on(JmpSessionEvents.MediaRequestReceived,data=>{logger.log("MediaRequest received: ".concat(JSON.stringify(data)));this.updateRequestedStreams(mediaType,data.requests).then(()=>{if(getMediaFamily(mediaType)===MediaFamily.Video){this.sendMediaRequestStatus(mediaType);}});});jmpSession.on(JmpSessionEvents.ActiveSpeaker,data=>{this.emit(MultistreamConnectionEventNames.ActiveSpeakerNotification,data.csis);this.recvTransceivers.forEach(transceivers=>{transceivers.forEach(t=>{var{currentRxCsi}=t.receiveSlot;if(currentRxCsi!==undefined){var isActiveSpeaker=data.csis.some(activeCsi=>(activeCsi&0xfffffffe)===(currentRxCsi&0xfffffffe));t.handleActiveSpeakerUpdate(isActiveSpeaker);}});});});this.jmpSessions.set(mediaType,jmpSession);}updateRequestedStreams(mediaType,requests){var sendTransceiver=this.getSendTransceiverOrThrow(mediaType);var mediaFamily=getMediaFamily(mediaType);var requestedIdEncodingParamsMap=new Map();var rsRequests=requests.filter(r=>isValidReceiverSelectedInfo(r.policySpecificInfo));if(rsRequests.length!==requests.length){logger.warn('Ignoring non-receiver-selected requests');}rsRequests.forEach(_ref9=>{var{ids,policySpecificInfo,codecInfos,maxPayloadBitsPerSecond}=_ref9;var _a,_b,_c;if(ids.length>1){logErrorAndThrow(WcmeErrorType.INVALID_STREAM_REQUEST,"Stream request cannot have more than one ID.");}if(ids.length===0){return;}if(sendTransceiver.csi!==policySpecificInfo.csi){logger.warn('csi in the StreamRequest does not match');return;}var id=ids[0];var codecInfo=codecInfos[0];if(!isValidSsrcStreamId(id)){logger.warn("".concat(mediaType,": The stream ID is not a valid SsrcStreamId: ").concat(JSON.stringify(id)));return;}var streamIdsMatched=sendTransceiver.senderIds.some(validId=>areStreamIdsEqual(id,validId));if(streamIdsMatched){var encodingIndex=sendTransceiver.getEncodingIndexForStreamId(id);if(encodingIndex!==-1){var encodingParams={maxPayloadBitsPerSecond};if(mediaFamily===MediaFamily.Video){encodingParams.maxFs=(_a=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_a===void 0?void 0:_a.maxFs;encodingParams.maxWidth=(_b=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_b===void 0?void 0:_b.maxWidth;encodingParams.maxHeight=(_c=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_c===void 0?void 0:_c.maxHeight;}requestedIdEncodingParamsMap.set(encodingIndex,encodingParams);}else {logger.warn("".concat(mediaType,": Unable to get encoding index for stream ID: ").concat(JSON.stringify(id)));}}else {logger.warn("".concat(mediaType,": Unable to find matching stream ID for requested ID: ").concat(JSON.stringify(id)));}});return sendTransceiver.updateSendParameters(requestedIdEncodingParamsMap);}createDataChannel(){var dataChannel=this.pc.createDataChannel('datachannel',{ordered:false,maxRetransmits:0});dataChannel.onopen=event=>{logger.info('DataChannel opened:',JSON.stringify(event));[...this.sendTransceivers.keys()].forEach(mediaType=>{this.sendSourceAdvertisement(mediaType);});logger.info("Flushing pending JMP task queue");this.pendingJmpTasks.forEach(t=>t());this.pendingJmpTasks=[];};dataChannel.onmessage=e=>{var parsed;try{parsed=JSON.parse(e.data);}catch(err){logger.error("Error parsing datachannel JSON: ".concat(err));return;}logger.debug('DataChannel got msg:',e.data);var homerMsg=HomerMsg.fromJson(parsed);if(!homerMsg){logger.error("Received invalid datachannel message: ".concat(e));return;}var jmpMsg=homerMsg.payload;if(!isValidJmpMsg(jmpMsg)){logger.error("Received invalid JMP msg: ".concat(JSON.stringify(jmpMsg)));return;}var mediaType=getMediaType(jmpMsg.mediaFamily,jmpMsg.mediaContent);var jmpSession=this.jmpSessions.get(mediaType);if(!jmpSession){logger.error("Unable to find JMP session for media type ".concat(mediaType,"."));return;}jmpSession.receive(jmpMsg);};dataChannel.onclose=event=>{logger.info('DataChannel closed:',JSON.stringify(event));};dataChannel.onerror=event=>{logger.info('DataChannel error:',JSON.stringify(event));};this.dataChannel=dataChannel;}close(){this.sendTransceivers.forEach(t=>t.close());this.recvTransceivers.forEach(recvTransceivers=>{recvTransceivers.forEach(t=>t.close());});this.jmpSessions.forEach(jmpSession=>jmpSession.close());this.pc.close();}sendMediaRequestStatus(mediaType){var _a;if(getMediaFamily(mediaType)!==MediaFamily.Video){return;}if(!this.getSendTransceiverOrThrow(mediaType).requested){return;}var streamStates=this.getVideoStreamStates(getMediaContent(mediaType));var task=()=>{var _a;(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendMediaRequestStatus(streamStates);};if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}sendSourceAdvertisement(mediaType){var _a,_b,_c;var transceiver=this.getSendTransceiverOrThrow(mediaType);var numLiveSources=((_a=transceiver.publishedStream)===null||_a===void 0?void 0:_a.muted)===false&&((_b=transceiver.publishedStream)===null||_b===void 0?void 0:_b.readyState)==='live'?1:0;var task;if(getMediaFamily(mediaType)===MediaFamily.Video){var sources=this.getVideoStreamStates(getMediaContent(mediaType));if(sources===null){return;}var contentHint;if(transceiver.publishedStream&&mediaType===MediaType.VideoSlides){contentHint=transceiver.publishedStream.contentHint;}task=()=>{var _a;(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendSourceAdvertisement(1,numLiveSources,[],webRtcVideoContentHintToJmpVideoContentHint(contentHint));};}else {task=()=>{var _a;return (_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendSourceAdvertisement(1,numLiveSources,mediaType===MediaType.AudioMain?transceiver.namedMediaGroups:[]);};}if(((_c=this.dataChannel)===null||_c===void 0?void 0:_c.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}getVideoStreamStates(mediaContent){var sendTransceiver=this.getSendTransceiverOrThrow(getMediaType(MediaFamily.Video,mediaContent));return sendTransceiver.senderIds.map(id=>({id,state:sendTransceiver.currentSourceState,csi:sendTransceiver.csi}));}createReceiveTransceiver(mediaType){var rtcRtpTransceiver=this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'recvonly'});var mid=this.midPredictor.getNextMid(mediaType);var munger=new IngressSdpMunger();var recvOnlyTransceiver=new ReceiveOnlyTransceiver({rtcRtpTransceiver,mid,mediaType,munger});if(getMediaFamily(mediaType)===MediaFamily.Video){recvOnlyTransceiver.setCodecParameters({'sps-pps-idr-in-keyframe':'1'});recvOnlyTransceiver.setRtxCodecParameters({'rtx-time':mediaType===MediaType.VideoMain?defaultVideoMainRtxTime:defaultVideoSlidesRtxTime});}recvOnlyTransceiver.twccDisabled=getMediaFamily(mediaType)===MediaFamily.Audio?this.options.disableAudioTwcc:false;this.recvTransceivers.set(mediaType,[...(this.recvTransceivers.get(mediaType)||[]),recvOnlyTransceiver]);return recvOnlyTransceiver;}createReceiveSlot(mediaType){return __awaiter$1(this,void 0,void 0,function*(){return (yield this.createReceiveSlots(mediaType,1))[0];});}createReceiveSlots(mediaType){var count=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;return __awaiter$1(this,void 0,void 0,function*(){return new Promise(createReceiveSlotsResolve=>{this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var createdReceiveOnlyTransceivers=[];for(var i=0;i<count;i++){var recvOnlyTransceiver=this.createReceiveTransceiver(mediaType);createdReceiveOnlyTransceivers.push(recvOnlyTransceiver);}if(this.pc.getRemoteDescription()){yield this.doLocalOfferAnswer();}var receiveSlots=createdReceiveOnlyTransceivers.map(transceiver=>transceiver.receiveSlot);createReceiveSlotsResolve(receiveSlots);}));});});}getIngressPayloadType(mediaType,mimeType){var _a,_b,_c;var requestedMediaCodecType=mimeType.split('/')[1];var requestedMid=(_a=this.sendTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.mid;var parsedOffer=parse$1((_b=this.pc.getLocalDescription())===null||_b===void 0?void 0:_b.sdp);var parsedAnswer=parse$1((_c=this.pc.getRemoteDescription())===null||_c===void 0?void 0:_c.sdp);var senderCodecs=parsedAnswer.avMedia.filter(media=>requestedMid===media.mid).map(media=>[...media.codecs.values()]).flat().filter(ci=>ci.name===requestedMediaCodecType);var receiverCodecs=parsedOffer.avMedia.filter(media=>requestedMid===media.mid).map(media=>[...media.codecs.values()]).flat().filter(ci=>ci.name===requestedMediaCodecType);if(!senderCodecs||!receiverCodecs||senderCodecs.length===0||receiverCodecs.length===0){logErrorAndThrow(WcmeErrorType.GET_PAYLOAD_TYPE_FAILED,"Sender codecs or receiver codecs is undefined or empty.");}var senderCodec=senderCodecs[0];var targetCodec=receiverCodecs.find(receiverCodec=>{return areCodecsCompatible(senderCodec,receiverCodec);});if(!targetCodec||!targetCodec.pt){logErrorAndThrow(WcmeErrorType.GET_PAYLOAD_TYPE_FAILED,"Cannot find matching receiver codec for the given mediaType/mimeType.");}return targetCodec.pt;}waitForIceGatheringComplete(){return __awaiter$1(this,void 0,void 0,function*(){return new Promise(resolve=>{if(this.pc.iceGatheringState==='complete'){resolve();}else {this.pc.on(PeerConnection.Events.IceCandidate,candidate=>{if(candidate.candidate===null||this.options.stopIceGatheringAfterFirstRelayCandidate&&candidate.candidate.type==='relay'){resolve();}});this.pc.on(PeerConnection.Events.IceGatheringStateChange,()=>{if(this.pc.iceGatheringState==='complete'){resolve();}});}});});}createOffer(){return __awaiter$1(this,void 0,void 0,function*(){if(!this.pc.getLocalDescription()){this.midPredictor.allocateMidForDatachannel();}if(this.setAnswerResolve){logger.info('Canceling previous offer since setAnswer was never called for it');this.setAnswerResolve();this.setAnswerResolve=undefined;}var createOfferId=++this.currentCreateOfferId;return new Promise((createOfferResolve,createOfferReject)=>{this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var _a;try{var offer=yield this.pc.createOffer();if(!offer.sdp){logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,'SDP not found in offer.');}offer.sdp=this.preProcessLocalOffer(offer.sdp);yield this.pc.setLocalDescription(offer).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setLocalDescription() resolved');})).catch(error=>{var _a;logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,"Error: ".concat(error,". SDP: ").concat(maskIp((_a=offer.sdp)!==null&&_a!==void 0?_a:'')));});if(this.options.doFullIce){yield this.waitForIceGatheringComplete();}var sdpToSend=this.prepareLocalOfferForRemoteServer((_a=this.pc.getLocalDescription())===null||_a===void 0?void 0:_a.sdp);createOfferResolve({type:'offer',sdp:sdpToSend});if(this.currentCreateOfferId>createOfferId){logger.log('Canceling previous offer since createOffer was called while it was being created');}else {yield new Promise(setAnswerResolve=>{this.setAnswerResolve=setAnswerResolve;});}}catch(error){createOfferReject(error);}}));});});}setAnswer(answer){return __awaiter$1(this,void 0,void 0,function*(){var sdp=this.preProcessRemoteAnswer(answer);if(!this.setAnswerResolve){logErrorAndThrow(WcmeErrorType.SET_ANSWER_FAILED,"Call to setAnswer without having previously called createOffer.");}logger.info('calling this.pc.setRemoteDescription()');return this.pc.setRemoteDescription({type:'answer',sdp}).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setRemoteDescription() resolved');if(this.setAnswerResolve){this.setAnswerResolve();this.setAnswerResolve=undefined;}else {logger.debug("setAnswerResolve function was cleared between setAnswer and result of setRemoteDescription");}})).catch(error=>{logErrorAndThrow(WcmeErrorType.SET_ANSWER_FAILED,"Error: ".concat(error,". SDP: ").concat(maskIp(answer)));});});}doLocalOfferAnswer(){var _a;return __awaiter$1(this,void 0,void 0,function*(){var offer=yield this.pc.createOffer();if(!offer.sdp){logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,'SDP not found in offer.');}offer.sdp=this.preProcessLocalOffer(offer.sdp);yield this.pc.setLocalDescription(offer).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setLocalDescription() resolved');})).catch(error=>{var _a;logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,"Error: ".concat(error,". SDP: ").concat(maskIp((_a=offer.sdp)!==null&&_a!==void 0?_a:'')));});var answer=this.preProcessRemoteAnswer((_a=this.pc.getRemoteDescription())===null||_a===void 0?void 0:_a.sdp);return this.pc.setRemoteDescription({type:'answer',sdp:answer}).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setRemoteDescription() resolved');})).catch(error=>{logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,"Error: ".concat(error,". SDP: ").concat(maskIp(answer)));});});}queueLocalOfferAnswer(){return __awaiter$1(this,void 0,void 0,function*(){return this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){yield this.doLocalOfferAnswer();}));});}preProcessLocalOffer(offer){var parsedOffer=parse$1(offer);parsedOffer.avMedia.filter(av=>av.direction==='recvonly').forEach(av=>{var recvTransceiver=this.getRecvTransceiverByMidOrThrow(av.mid);recvTransceiver.mungeLocalDescription(av);});parsedOffer.avMedia.filter(av=>av.direction==='sendrecv'||av.direction==='inactive').forEach(av=>{var sendTransceiver=this.getSendTransceiverByMidOrThrow(av.mid);sendTransceiver.mungeLocalDescription(av);});if(BrowserInfo.isFirefox()){setupBundle(parsedOffer,this.options.bundlePolicy,this.midPredictor.getMidMap());}return parsedOffer.toString();}prepareLocalOfferForRemoteServer(offer){var parsedOffer=parse$1(offer);var shouldInjectDummyCandidates=()=>{if(!this.options.doFullIce){return true;}return !hasIceCandidates(parsedOffer);};var mungeOptions={injectDummyCandidates:shouldInjectDummyCandidates()};parsedOffer.avMedia.filter(av=>av.direction==='sendrecv'||av.direction==='inactive').forEach(av=>{var sendTransceiver=this.getSendTransceiverByMidOrThrow(av.mid);sendTransceiver.mungeLocalDescriptionForRemoteServer(av,mungeOptions);});if(mungeOptions.injectDummyCandidates){parsedOffer.media.filter(media=>media instanceof ApplicationMediaDescription$1).forEach(media=>{injectDummyCandidates(media);});}if(BrowserInfo.isFirefox()&&this.options.doFullIce){var iceCandidates=this.pc.getIceCandidates();parsedOffer.media.forEach(media=>{media.iceInfo.candidates=[];iceCandidates.forEach(iceCandidate=>{var candidateLine=CandidateLine$1.fromSdpLine(iceCandidate.candidate.toString());if(candidateLine){media.addLine(candidateLine);}});});}if(BrowserInfo.isFirefox()){setupBundle(parsedOffer,this.options.bundlePolicy,this.midPredictor.getMidMap());if(this.options.bundlePolicy==='max-bundle'){parsedOffer.media.forEach((media,index)=>{if(index>0){media.port=parsedOffer.media[0].port;}});}}filterRecvOnlyMediaDescriptions(parsedOffer);return parsedOffer.toString();}preProcessRemoteAnswer(answer){var _a,_b;var parsedAnswer=parse$1(answer);var parsedOffer=parse$1((_a=this.pc.getLocalDescription())===null||_a===void 0?void 0:_a.sdp);matchMediaDescriptionsInAnswer(parsedOffer,parsedAnswer);parsedAnswer.avMedia.filter(av=>av.direction==='sendonly').forEach(av=>{var recvTransceiver=this.getRecvTransceiverByMidOrThrow(av.mid);recvTransceiver.mungeRemoteDescription(av);});parsedAnswer.avMedia.filter(av=>av.direction==='sendrecv'||av.direction==='recvonly').forEach(av=>{var sendTransceiver=this.getSendTransceiverByMidOrThrow(av.mid);sendTransceiver.mungeRemoteDescription(av);});parsedAnswer.media.filter(media=>media instanceof ApplicationMediaDescription$1).forEach(media=>{if(retainCandidatesByTransportType(media,['udp','tcp'])){logger.log("Some unsupported remote candidates have been removed from mid ".concat(media.mid));}});if(BrowserInfo.isFirefox()){setupBundle(parsedAnswer,this.options.bundlePolicy,this.midPredictor.getMidMap());}if((_b=parsedAnswer.session.information)===null||_b===void 0?void 0:_b.info){this.metadata.isMediaBypassEdge=!parsedAnswer.session.information.info.includes('linus');}return parsedAnswer.toString();}getSendTransceiverOrThrow(mediaType){var sendTransceiver=this.sendTransceivers.get(mediaType);if(!sendTransceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find send transceiver for media type ".concat(mediaType,"."));}return sendTransceiver;}getSendTransceiverByMidOrThrow(mid){var transceiver=[...this.sendTransceivers.values()].find(t=>t.mid===mid);if(!transceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find send transceiver with MID ".concat(mid,"."));}return transceiver;}getRecvTransceiverByMidOrThrow(mid){var transceiver=[...this.recvTransceivers.values()].flat().find(t=>t.mid===mid);if(!transceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find recv transceiver with MID ".concat(mid,"."));}return transceiver;}requestMedia(mediaType,streamRequests){var _a;var task=()=>{var _a;var jmpSession=this.jmpSessions.get(mediaType);if(!jmpSession){logger.error("Unable to find jmp session for ".concat(mediaType));return;}var requestedReceiveSlotIds=[];streamRequests.forEach(request=>{if(request.receiveSlots.length===0){logger.error('Stream request ids cannot be empty.');return;}request.receiveSlots.forEach(slot=>{if(!slot.id){logger.error('Running stream request task, but ReceiveSlot ID is missing.');}if(!requestedReceiveSlotIds.some(id=>areStreamIdsEqual(id,slot.id))){requestedReceiveSlotIds.push(slot.id);}else {logger.error("Stream id duplicate found ".concat(JSON.stringify(slot.id),"."));}});});jmpSession.sendRequests(streamRequests.map(sr=>sr._toJmpStreamRequest()));(_a=this.recvTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.forEach(transceiver=>{if(requestedReceiveSlotIds.some(id=>areStreamIdsEqual(id,transceiver.receiveSlot.id))){var relevantRequest=streamRequests.find(request=>request.receiveSlots.some(slot=>areStreamIdsEqual(slot.id,transceiver.receiveSlot.id)));transceiver.handleRequested(relevantRequest);}else {transceiver.handleUnrequested();}});};if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}renewPeerConnection(userOptions){var _a;return __awaiter$1(this,void 0,void 0,function*(){(_a=this.pc)===null||_a===void 0?void 0:_a.close();try{if(userOptions){this.options=Object.assign(Object.assign({},this.options),yield userOptions);}}catch(error){logErrorAndThrow(WcmeErrorType.RENEW_PEER_CONNECTION_FAILED,"Error while awaiting user options: ".concat(error));}logger.info("Renewing multistream connection with options ".concat(JSON.stringify(this.options)));this.midPredictor.reset();this.initializePeerConnection();var mainSceneId=generateSceneId();var slidesSceneId=generateSceneId();this.sendTransceivers.forEach((transceiver,mediaType)=>{var _a;var mediaContent=getMediaContent(mediaType);var sceneId=mediaContent===MediaContent.Main?mainSceneId:slidesSceneId;var mid=this.midPredictor.getNextMid(mediaType);transceiver.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'sendrecv',sendEncodings:getMediaFamily(mediaType)===MediaFamily.Video?this.getVideoEncodingOptions(mediaContent):undefined}));transceiver.mid=mid;transceiver.csi=generateCsi(getMediaFamily(mediaType),sceneId);transceiver.resetSdpMunger();(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.close();this.createJmpSession(mediaType);});this.recvTransceivers.forEach((transceivers,mediaType)=>{transceivers.forEach(t=>{var mid=this.midPredictor.getNextMid(mediaType);t.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'recvonly'}));t.mid=mid;});});});}getReceiveSlotById(id){return [...this.recvTransceivers.values()].flat().map(transceiver=>transceiver.receiveSlot).find(receiveSlot=>{var receiveSlotId=receiveSlot.id||{};return Object.keys(receiveSlotId).length===Object.keys(id).length&&Object.keys(receiveSlotId).every(key=>Object.prototype.hasOwnProperty.call(id,key)&&receiveSlotId[key]===id[key]);});}getStats(){return this.statsManager.getStats();}getTransceiverStats(){return __awaiter$1(this,void 0,void 0,function*(){var stats=yield this.getStats();var peerConnectionStats=[...stats.values()].find(stat=>stat.type==='peer-connection');return organizeTransceiverStats(this.sendTransceivers,this.recvTransceivers,peerConnectionStats);});}preProcessStats(stats){return __awaiter$1(this,void 0,void 0,function*(){stats.forEach(stat=>{if(stat.type==='peer-connection'){stat.isMediaBypassEdge=this.metadata.isMediaBypassEdge;}});yield Promise.all([...this.sendTransceivers.values()].map(transceiver=>__awaiter$1(this,void 0,void 0,function*(){(yield transceiver.getStats()).forEach(senderStats=>{if(senderStats.type==='outbound-rtp'||senderStats.type==='media-source'){stats.set(senderStats.id,senderStats);}});})));yield Promise.all([...this.recvTransceivers.values()].map(transceivers=>__awaiter$1(this,void 0,void 0,function*(){yield Promise.all(transceivers.map(transceiver=>__awaiter$1(this,void 0,void 0,function*(){(yield transceiver.getStats()).forEach(receiverStats=>{if(receiverStats.type==='inbound-rtp'){stats.set(receiverStats.id,receiverStats);}});})));})));});}attachMetricsObserver(){this.forceStatsReport=rtcStats_1(this.pc.getUnderlyingRTCPeerConnection(),data=>this.metricsCallback(data),5000,stats=>this.preProcessStats(stats)).forceStatsReport;}forceRtcMetricsCallback(){var _a;return (_a=this.forceStatsReport)===null||_a===void 0?void 0:_a.call(this);}setOveruseUpdateCallback(callback){this.overuseUpdateCallback=callback;}getCsiByMediaType(mediaType){var _a;return (_a=this.sendTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.csi;}getAllCsis(){return {audioMain:this.getCsiByMediaType(MediaType.AudioMain),audioSlides:this.getCsiByMediaType(MediaType.AudioSlides),videoMain:this.getCsiByMediaType(MediaType.VideoMain),videoSlides:this.getCsiByMediaType(MediaType.VideoSlides)};}}class StreamRequest{constructor(policy,policySpecificInfo,receiveSlots,maxPayloadBitsPerSecond){var codecInfos=arguments.length>4&&arguments[4]!==undefined?arguments[4]:[];this.policy=policy;this.policySpecificInfo=policySpecificInfo;this.receiveSlots=receiveSlots;this.maxPayloadBitsPerSecond=maxPayloadBitsPerSecond;this.codecInfos=codecInfos;}_toJmpStreamRequest(){return new StreamRequest$1(this.policy,this.policySpecificInfo,this.receiveSlots.map(rs=>rs.id),this.maxPayloadBitsPerSecond,this.codecInfos);}}
5608
5612
 
5609
5613
  var defaultLogger = {
5610
5614
  info: function info() {
@@ -15800,29 +15804,35 @@ class RoapMediaConnection extends EventEmitter$5 {
15800
15804
  this.roap.stop();
15801
15805
  this.roap.removeAllListeners();
15802
15806
  }
15803
- reconnect(iceServers) {
15804
- var initiateOffer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
15805
- this.log('reconnect()', "iceServers: ".concat(JSON.stringify(iceServers)));
15806
- var config = _objectSpread$6(_objectSpread$6({}, this.mediaConnection.getConfig()), {}, {
15807
- iceServers
15808
- });
15809
- var options = this.mediaConnection.getSendReceiveOptions();
15810
- var seq = this.roap.getSeq();
15811
- var callback = this.mediaConnection.getMetricsCallback();
15812
- this.stopRoapSession();
15813
- this.closeMediaConnection();
15814
- this.sdpNegotiationStarted = false;
15815
- this.mediaConnection = this.createMediaConnection({
15816
- mediaConnectionConfig: config,
15817
- options,
15818
- metricsCallback: callback,
15819
- debugId: this.debugId
15820
- });
15821
- this.roap = this.createRoap(this.debugId, seq);
15822
- if (initiateOffer) {
15823
- return this.initiateOffer();
15824
- }
15825
- return Promise.resolve();
15807
+ reconnect(iceServersPromise) {
15808
+ var _arguments = arguments,
15809
+ _this3 = this;
15810
+ return _asyncToGenerator(function* () {
15811
+ var initiateOffer = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true;
15812
+ _this3.log('reconnect()', "initiated");
15813
+ var options = _this3.mediaConnection.getSendReceiveOptions();
15814
+ var seq = _this3.roap.getSeq();
15815
+ var callback = _this3.mediaConnection.getMetricsCallback();
15816
+ _this3.stopRoapSession();
15817
+ _this3.closeMediaConnection();
15818
+ _this3.sdpNegotiationStarted = false;
15819
+ var iceServers = yield iceServersPromise;
15820
+ _this3.log('reconnect()', "iceServers: ".concat(JSON.stringify(iceServers)));
15821
+ var config = _objectSpread$6(_objectSpread$6({}, _this3.mediaConnection.getConfig()), {}, {
15822
+ iceServers
15823
+ });
15824
+ _this3.mediaConnection = _this3.createMediaConnection({
15825
+ mediaConnectionConfig: config,
15826
+ options,
15827
+ metricsCallback: callback,
15828
+ debugId: _this3.debugId
15829
+ });
15830
+ _this3.roap = _this3.createRoap(_this3.debugId, seq);
15831
+ if (initiateOffer) {
15832
+ return _this3.initiateOffer();
15833
+ }
15834
+ return Promise.resolve();
15835
+ })();
15826
15836
  }
15827
15837
  updateLocalTracks(tracks) {
15828
15838
  this.log('updateLocalTracks()', "called with ".concat(JSON.stringify(tracks)));
@@ -16033,20 +16043,27 @@ class MultistreamRoapMediaConnection extends EventEmitter$5 {
16033
16043
  this.roap.stop();
16034
16044
  this.roap.removeAllListeners();
16035
16045
  }
16036
- reconnect(iceServers) {
16037
- var initiateOffer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
16038
- this.log('reconnect()', "iceServers: ".concat(JSON.stringify(iceServers)));
16039
- var seq = this.roap.getSeq();
16040
- this.stopRoapSession();
16041
- this.sdpNegotiationStarted = false;
16042
- this.multistreamConnection.renewPeerConnection({
16043
- iceServers
16044
- });
16045
- this.roap = this.createRoap(this.debugId, seq);
16046
- if (initiateOffer) {
16047
- return this.initiateOffer();
16048
- }
16049
- return Promise.resolve();
16046
+ reconnect(iceServersPromise) {
16047
+ var _arguments = arguments,
16048
+ _this2 = this;
16049
+ return _asyncToGenerator(function* () {
16050
+ var initiateOffer = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true;
16051
+ _this2.log('reconnect()', "initiated");
16052
+ var seq = _this2.roap.getSeq();
16053
+ _this2.stopRoapSession();
16054
+ _this2.sdpNegotiationStarted = false;
16055
+ var userOptionsPromise = Promise.resolve(iceServersPromise).then(iceServers => ({
16056
+ iceServers
16057
+ })).catch(() => {
16058
+ throw new Error('Failed to collect user options for reconnect');
16059
+ });
16060
+ yield _this2.multistreamConnection.renewPeerConnection(userOptionsPromise);
16061
+ _this2.roap = _this2.createRoap(_this2.debugId, seq);
16062
+ if (initiateOffer) {
16063
+ return _this2.initiateOffer();
16064
+ }
16065
+ return Promise.resolve();
16066
+ })();
16050
16067
  }
16051
16068
  getConnectionState() {
16052
16069
  var connectionState = this.multistreamConnection.getConnectionState();
@@ -16127,26 +16144,26 @@ class MultistreamRoapMediaConnection extends EventEmitter$5 {
16127
16144
  });
16128
16145
  }
16129
16146
  handleRemoteAnswer(sdp) {
16130
- var _this2 = this;
16147
+ var _this3 = this;
16131
16148
  return _asyncToGenerator(function* () {
16132
- _this2.log('handleRemoteAnswer()', "called: sdp=".concat(sdp ? 'non-empty' : 'empty'));
16149
+ _this3.log('handleRemoteAnswer()', "called: sdp=".concat(sdp ? 'non-empty' : 'empty'));
16133
16150
  if (sdp) {
16134
16151
  try {
16135
- yield _this2.waitForIceCandidates();
16152
+ yield _this3.waitForIceCandidates();
16136
16153
  } catch (e) {
16137
16154
  var {
16138
16155
  message
16139
16156
  } = e;
16140
- _this2.warn('handleRemoteAnswer()', "".concat(message));
16157
+ _this3.warn('handleRemoteAnswer()', "".concat(message));
16141
16158
  }
16142
16159
  var mungedSdp = mungeRemoteSdp({}, sdp);
16143
- _this2.log('handleRemoteAnswer()', 'calling this.multistreamConnection.setAnswer');
16144
- return _this2.multistreamConnection.setAnswer(mungedSdp).then(result => {
16145
- _this2.log('handleRemoteAnswer()', 'this.multistreamConnection.setAnswer resolved');
16146
- _this2.emit(MediaConnectionEventNames.REMOTE_SDP_ANSWER_PROCESSED);
16160
+ _this3.log('handleRemoteAnswer()', 'calling this.multistreamConnection.setAnswer');
16161
+ return _this3.multistreamConnection.setAnswer(mungedSdp).then(result => {
16162
+ _this3.log('handleRemoteAnswer()', 'this.multistreamConnection.setAnswer resolved');
16163
+ _this3.emit(MediaConnectionEventNames.REMOTE_SDP_ANSWER_PROCESSED);
16147
16164
  return result;
16148
16165
  }).catch(error => {
16149
- _this2.log('handleRemoteAnswer()', "this.multistreamConnection.setAnswer failed");
16166
+ _this3.log('handleRemoteAnswer()', "this.multistreamConnection.setAnswer failed");
16150
16167
  throw new SdpAnswerHandlingError("handleRemoteAnswer() failure: ".concat(error.message), {
16151
16168
  cause: error
16152
16169
  });
@@ -18062,11 +18079,15 @@ var getH264ProfileFromStatsByStreamStatsId = (intervalStats, streamStatsId) => {
18062
18079
  }
18063
18080
  return undefined;
18064
18081
  };
18065
- var isStreamRequested = stats => {
18066
- var now = performance.timeOrigin + performance.now();
18067
- var lastRequestedUpdateTimestamp = stats.lastRequestedUpdateTimestamp;
18068
- var isCurrentlyRequested = stats.isRequested;
18069
- return isCurrentlyRequested || !!(lastRequestedUpdateTimestamp && now - lastRequestedUpdateTimestamp < MQE_INTERVAL);
18082
+ var isStreamRequested = streamStats => {
18083
+ var _isRequestedArray$som;
18084
+ var isRequestedArray = streamStats.isRequestedArray;
18085
+ return (_isRequestedArray$som = isRequestedArray === null || isRequestedArray === void 0 ? void 0 : isRequestedArray.some(isRequested => isRequested === true)) !== null && _isRequestedArray$som !== void 0 ? _isRequestedArray$som : false;
18086
+ };
18087
+ var isStreamLive = streamStats => {
18088
+ var _sourceStateArray$som;
18089
+ var sourceStateArray = streamStats.sourceStateArray;
18090
+ return (_sourceStateArray$som = sourceStateArray === null || sourceStateArray === void 0 ? void 0 : sourceStateArray.some(state => state === 'live')) !== null && _sourceStateArray$som !== void 0 ? _sourceStateArray$som : false;
18070
18091
  };
18071
18092
  var pixelsToFrameSize = (width, height) => {
18072
18093
  var round16 = n => Math.ceil(n / 16) * 16;
@@ -18105,6 +18126,8 @@ class MqeBuilder {
18105
18126
  };
18106
18127
  if (stats.type === 'inbound-rtp') {
18107
18128
  var _current$rtpPacketSiz, _stats$bytesReceived, _stats$packetsReceive;
18129
+ storeValueInArray('isRequestedArray', stats.isRequested);
18130
+ storeValueInArray('sourceStateArray', stats.sourceState);
18108
18131
  storeValueInArray('jitterArray', stats.jitter);
18109
18132
  storeValueInArray('requestedBitrateArray', stats.requestedBitrate);
18110
18133
  storeValueInArray('csiArray', stats.csi);
@@ -18148,6 +18171,8 @@ class MqeBuilder {
18148
18171
  }
18149
18172
  } else if (stats.type === 'outbound-rtp') {
18150
18173
  var _current$rtpPacketSiz2, _stats$bytesSent, _stats$packetsSent;
18174
+ storeValueInArray('isRequestedArray', stats.isRequested);
18175
+ storeValueInArray('sourceStateArray', stats.sourceState);
18151
18176
  storeValueInArray('requestedBitrateArray', stats.requestedBitrate);
18152
18177
  var lastUsedEffect = current === null || current === void 0 ? void 0 : current.lastUsedEffect;
18153
18178
  var effect = stats === null || stats === void 0 ? void 0 : stats.effect;
@@ -18205,6 +18230,8 @@ class MqeBuilder {
18205
18230
  this.previousIntervalStats = new Map(this.currentIntervalStats);
18206
18231
  this.currentIntervalStats.forEach(stats => {
18207
18232
  if (stats.type === 'inbound-rtp') {
18233
+ delete stats.isRequestedArray;
18234
+ delete stats.sourceStateArray;
18208
18235
  delete stats.jitterArray;
18209
18236
  delete stats.requestedBitrateArray;
18210
18237
  delete stats.csiArray;
@@ -18216,9 +18243,10 @@ class MqeBuilder {
18216
18243
  delete stats.maxDecodedFrameRateForMaxRequestedFrameSize;
18217
18244
  delete stats.maxFrameSizeHeightForMaxRequestedFrameSize;
18218
18245
  delete stats.maxFrameSizeWidthForMaxRequestedFrameSize;
18219
- delete stats.isRequested;
18220
18246
  delete stats.rtpPacketSizeArray;
18221
18247
  } else if (stats.type === 'outbound-rtp') {
18248
+ delete stats.isRequestedArray;
18249
+ delete stats.sourceStateArray;
18222
18250
  delete stats.requestedBitrateArray;
18223
18251
  delete stats.lastUsedEffect;
18224
18252
  delete stats.maxRequestedFrameSize;
@@ -18228,7 +18256,6 @@ class MqeBuilder {
18228
18256
  delete stats.maxTransmittedFrameRateForMaxRequestedFrameSize;
18229
18257
  delete stats.maxFrameSizeHeightForMaxRequestedFrameSize;
18230
18258
  delete stats.maxFrameSizeWidthForMaxRequestedFrameSize;
18231
- delete stats.isRequested;
18232
18259
  delete stats.rtpPacketSizeArray;
18233
18260
  } else if (stats.type === 'remote-inbound-rtp') {
18234
18261
  delete stats.roundTripTimeArray;
@@ -18561,7 +18588,7 @@ class MqeIntervalSessionReceiveVideoBuilder extends MqeBuilder {
18561
18588
  streams: []
18562
18589
  };
18563
18590
  this.currentIntervalStats.forEach((stats, key) => {
18564
- if (stats.type === 'inbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats))) {
18591
+ if (stats.type === 'inbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats) && isStreamLive(stats))) {
18565
18592
  result.streams.push(this.buildMqeIntervalStreamReceiveVideo(key));
18566
18593
  }
18567
18594
  });
@@ -18607,7 +18634,7 @@ class MqeIntervalSessionTransmitVideoBuilder extends MqeBuilder {
18607
18634
  streams: []
18608
18635
  };
18609
18636
  this.currentIntervalStats.forEach((stats, key) => {
18610
- if (stats.type === 'outbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats))) {
18637
+ if (stats.type === 'outbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats) && isStreamLive(stats))) {
18611
18638
  result.streams.push(this.buildMqeIntervalStreamTransmitVideo(key));
18612
18639
  }
18613
18640
  });