@webex/internal-media-core 2.16.2 → 2.17.1

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/cjs/index.js CHANGED
@@ -3271,11 +3271,11 @@ shimAddIceCandidateNullOrEmpty$1(window,browserDetails);shimParameterlessSetLoca
3271
3271
  * Creates an instance of the RTCPeerConnection.
3272
3272
  *
3273
3273
  * @param configuration - Config to the RTCPeerConnection constructor.
3274
- */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
3274
+ */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
3275
3275
  // eslint-disable-next-line jsdoc/require-jsdoc
3276
3276
  this.pc.oniceconnectionstatechange=()=>this.connectionStateHandler.onIceConnectionStateChange();// eslint-disable-next-line jsdoc/require-jsdoc
3277
3277
  this.pc.onconnectionstatechange=()=>this.connectionStateHandler.onPeerConnectionStateChange();// Subscribe to underlying PeerConnection events and emit them via the EventEmitter
3278
- /* 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);};}/**
3278
+ /* 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);};}/**
3279
3279
  * Get the underlying RTCPeerConnection.
3280
3280
  *
3281
3281
  * @returns The underlying RTCPeerConnection.
@@ -3292,6 +3292,10 @@ this.pc.onconnectionstatechange=()=>this.connectionStateHandler.onPeerConnection
3292
3292
  *
3293
3293
  * @returns The underlying RTCPeerConnection ICE connection state.
3294
3294
  */getIceConnectionState(){return this.connectionStateHandler.getIceConnectionState();}/**
3295
+ * Gets the list of ICE candidates that have been gathered.
3296
+ *
3297
+ * @returns An array of RTCIceCandidate objects representing the ICE candidates.
3298
+ */getIceCandidates(){return this.iceCandidates;}/**
3295
3299
  * Adds a new media track to the set of tracks which will be transmitted to the other peer.
3296
3300
  *
3297
3301
  * @param track - A MediaStreamTrack object representing the media track to add to the peer connection.
@@ -3456,7 +3460,7 @@ if(context.level===Logger.WARN&&console.warn){hdlr=console.warn;}else if(context
3456
3460
  // `options` hash can be used to configure the default logLevel and provide a custom message formatter.
3457
3461
  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.
3458
3462
  Logger.setDefaults=Logger.useDefaults;// Export to popular environments boilerplate.
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;}exports.MediaFamily = void 0;(function(MediaFamily){MediaFamily["Audio"]="AUDIO";MediaFamily["Video"]="VIDEO";})(exports.MediaFamily||(exports.MediaFamily={}));exports.MediaContent = void 0;(function(MediaContent){MediaContent["Main"]="MAIN";MediaContent["Slides"]="SLIDES";})(exports.MediaContent||(exports.MediaContent={}));exports.Policy = void 0;(function(Policy){Policy["ActiveSpeaker"]="active-speaker";Policy["ReceiverSelected"]="receiver-selected";})(exports.Policy||(exports.Policy={}));exports.MediaType = void 0;(function(MediaType){MediaType["VideoMain"]="VIDEO-MAIN";MediaType["VideoSlides"]="VIDEO-SLIDES";MediaType["AudioMain"]="AUDIO-MAIN";MediaType["AudioSlides"]="AUDIO-SLIDES";})(exports.MediaType||(exports.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===exports.MediaFamily.Audio){av=0;}else {av=1;}return sceneId<<8|av;}function getMediaType(mediaFamily,mediaContent){if(mediaFamily===exports.MediaFamily.Video&&mediaContent===exports.MediaContent.Main){return exports.MediaType.VideoMain;}if(mediaFamily===exports.MediaFamily.Video&&mediaContent===exports.MediaContent.Slides){return exports.MediaType.VideoSlides;}if(mediaFamily===exports.MediaFamily.Audio&&mediaContent===exports.MediaContent.Main){return exports.MediaType.AudioMain;}return exports.MediaType.AudioSlides;}function getMediaFamily(mediaType){return [exports.MediaType.VideoMain,exports.MediaType.VideoSlides].includes(mediaType)?exports.MediaFamily.Video:exports.MediaFamily.Audio;}function getMediaContent(mediaType){return [exports.MediaType.VideoMain,exports.MediaType.AudioMain].includes(mediaType)?exports.MediaContent.Main:exports.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");}}}exports.WcmeErrorType = void 0;(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";})(exports.WcmeErrorType||(exports.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:{}};/*!
3463
+ 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;}exports.MediaFamily = void 0;(function(MediaFamily){MediaFamily["Audio"]="AUDIO";MediaFamily["Video"]="VIDEO";})(exports.MediaFamily||(exports.MediaFamily={}));exports.MediaContent = void 0;(function(MediaContent){MediaContent["Main"]="MAIN";MediaContent["Slides"]="SLIDES";})(exports.MediaContent||(exports.MediaContent={}));exports.Policy = void 0;(function(Policy){Policy["ActiveSpeaker"]="active-speaker";Policy["ReceiverSelected"]="receiver-selected";})(exports.Policy||(exports.Policy={}));exports.MediaType = void 0;(function(MediaType){MediaType["VideoMain"]="VIDEO-MAIN";MediaType["VideoSlides"]="VIDEO-SLIDES";MediaType["AudioMain"]="AUDIO-MAIN";MediaType["AudioSlides"]="AUDIO-SLIDES";})(exports.MediaType||(exports.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===exports.MediaFamily.Audio){av=0;}else {av=1;}return sceneId<<8|av;}function getMediaType(mediaFamily,mediaContent){if(mediaFamily===exports.MediaFamily.Video&&mediaContent===exports.MediaContent.Main){return exports.MediaType.VideoMain;}if(mediaFamily===exports.MediaFamily.Video&&mediaContent===exports.MediaContent.Slides){return exports.MediaType.VideoSlides;}if(mediaFamily===exports.MediaFamily.Audio&&mediaContent===exports.MediaContent.Main){return exports.MediaType.AudioMain;}return exports.MediaType.AudioSlides;}function getMediaFamily(mediaType){return [exports.MediaType.VideoMain,exports.MediaType.VideoSlides].includes(mediaType)?exports.MediaFamily.Video:exports.MediaFamily.Audio;}function getMediaContent(mediaType){return [exports.MediaType.VideoMain,exports.MediaType.AudioMain].includes(mediaType)?exports.MediaContent.Main:exports.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");}}}exports.WcmeErrorType = void 0;(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";})(exports.WcmeErrorType||(exports.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:{}};/*!
3460
3464
  * js-logger - http://github.com/jonnyreeves/js-logger
3461
3465
  * Jonny Reeves, http://jonnyreeves.co.uk/
3462
3466
  * js-logger may be freely distributed under the MIT license.
@@ -5608,7 +5612,7 @@ var{hasOwnProperty}=Object.prototype;for(var i=0;i<mapResults.length;i++){if(map
5608
5612
  * // arg1 now equals 'three'
5609
5613
  * callback(null, 'done');
5610
5614
  * }
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.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(exports.LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(exports.LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(exports.LocalStreamEventNames.UserMuteStateChange,this.handleStreamMuteStateChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(exports.LocalStreamEventNames.SystemMuteStateChange,this.handleStreamMuteStateChange);if(this.requested){yield this.replaceSenderSource(newStream);}this.publishedStream=newStream;newStream===null||newStream===void 0?void 0:newStream.on(exports.LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);newStream===null||newStream===void 0?void 0:newStream.on(exports.LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);newStream===null||newStream===void 0?void 0:newStream.on(exports.LocalStreamEventNames.UserMuteStateChange,this.handleStreamMuteStateChange);newStream===null||newStream===void 0?void 0:newStream.on(exports.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!==exports.MediaType.AudioMain){logErrorAndThrow(exports.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===exports.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)===exports.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===exports.MediaType.AudioMain){result.audio.senders.push(item);}if(mediaType===exports.MediaType.VideoMain){result.video.senders.push(item);}if(mediaType===exports.MediaType.AudioSlides){result.screenShareAudio.senders.push(item);}if(mediaType===exports.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===exports.MediaType.AudioMain){result.audio.receivers.push(item);}if(mediaType===exports.MediaType.VideoMain){result.video.receivers.push(item);}if(mediaType===exports.MediaType.AudioSlides){result.screenShareAudio.receivers.push(item);}if(mediaType===exports.MediaType.VideoSlides){result.screenShareVideo.receivers.push(item);}})));});}));return result;});function toMediaStreamTrackKind(mediaType){return [exports.MediaType.VideoMain,exports.MediaType.VideoSlides].includes(mediaType)?exports.MediaStreamTrackKind.Video:exports.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(exports.MediaContent.Main);var videoSlidesEncodingOptions=this.getVideoEncodingOptions(exports.MediaContent.Slides);this.createSendTransceiver(exports.MediaType.VideoMain,mainSceneId,videoMainEncodingOptions);this.createSendTransceiver(exports.MediaType.AudioMain,mainSceneId);this.createSendTransceiver(exports.MediaType.VideoSlides,slidesSceneId,videoSlidesEncodingOptions);this.createSendTransceiver(exports.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===exports.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)===exports.MediaFamily.Video){transceiver.rtxEnabled=true;transceiver.setCodecParameters({'max-mbps':"".concat(defaultMaxVideoEncodeMbps),'max-fs':"".concat(defaultMaxVideoEncodeFrameSize)});}transceiver.twccDisabled=getMediaFamily(mediaType)===exports.MediaFamily.Audio?this.options.disableAudioTwcc:false;transceiver.dtxDisabled=mediaType!==exports.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(exports.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)===exports.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)===exports.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(exports.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===exports.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)!==exports.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)===exports.MediaFamily.Video){var sources=this.getVideoStreamStates(mediaType);if(sources===null){return;}var contentHint;if(transceiver.publishedStream&&mediaType===exports.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===exports.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)===exports.MediaFamily.Video){recvOnlyTransceiver.setCodecParameters({'sps-pps-idr-in-keyframe':'1'});recvOnlyTransceiver.setRtxCodecParameters({'rtx-time':mediaType===exports.MediaType.VideoMain?defaultVideoMainRtxTime:defaultVideoSlidesRtxTime});}recvOnlyTransceiver.twccDisabled=getMediaFamily(mediaType)===exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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===exports.MediaContent.Main?mainSceneId:slidesSceneId;var mid=this.midPredictor.getNextMid(mediaType);transceiver.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'sendrecv',sendEncodings:getMediaFamily(mediaType)===exports.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(exports.MediaType.AudioMain),audioSlides:this.getCsiByMediaType(exports.MediaType.AudioSlides),videoMain:this.getCsiByMediaType(exports.MediaType.VideoMain),videoSlides:this.getCsiByMediaType(exports.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);}}
5615
+ */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(exports.LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(exports.LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(exports.LocalStreamEventNames.UserMuteStateChange,this.handleStreamMuteStateChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(exports.LocalStreamEventNames.SystemMuteStateChange,this.handleStreamMuteStateChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(exports.StreamEventNames.Ended,this.handleStreamEnded);if(this.requested){yield this.replaceSenderSource(newStream);}this.publishedStream=newStream;newStream===null||newStream===void 0?void 0:newStream.on(exports.LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);newStream===null||newStream===void 0?void 0:newStream.on(exports.LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);newStream===null||newStream===void 0?void 0:newStream.on(exports.LocalStreamEventNames.UserMuteStateChange,this.handleStreamMuteStateChange);newStream===null||newStream===void 0?void 0:newStream.on(exports.LocalStreamEventNames.SystemMuteStateChange,this.handleStreamMuteStateChange);newStream===null||newStream===void 0?void 0:newStream.on(exports.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!==exports.MediaType.AudioMain){logErrorAndThrow(exports.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===exports.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)===exports.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)!==exports.MediaFamily.Video){logErrorAndThrow(exports.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)!==exports.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===exports.MediaType.AudioMain){result.audio.senders.push(item);}if(mediaType===exports.MediaType.VideoMain){result.video.senders.push(item);}if(mediaType===exports.MediaType.AudioSlides){result.screenShareAudio.senders.push(item);}if(mediaType===exports.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===exports.MediaType.AudioMain){result.audio.receivers.push(item);}if(mediaType===exports.MediaType.VideoMain){result.video.receivers.push(item);}if(mediaType===exports.MediaType.AudioSlides){result.screenShareAudio.receivers.push(item);}if(mediaType===exports.MediaType.VideoSlides){result.screenShareVideo.receivers.push(item);}})));});}));return result;});function toMediaStreamTrackKind(mediaType){return [exports.MediaType.VideoMain,exports.MediaType.VideoSlides].includes(mediaType)?exports.MediaStreamTrackKind.Video:exports.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(exports.MediaContent.Main);var videoSlidesEncodingOptions=this.getVideoEncodingOptions(exports.MediaContent.Slides);this.createSendTransceiver(exports.MediaType.VideoMain,mainSceneId,videoMainEncodingOptions);this.createSendTransceiver(exports.MediaType.AudioMain,mainSceneId);this.createSendTransceiver(exports.MediaType.VideoSlides,slidesSceneId,videoSlidesEncodingOptions);this.createSendTransceiver(exports.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===exports.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)===exports.MediaFamily.Video){transceiver.rtxEnabled=true;transceiver.setCodecParameters({'max-mbps':"".concat(defaultMaxVideoEncodeMbps),'max-fs':"".concat(defaultMaxVideoEncodeFrameSize)});}transceiver.twccDisabled=getMediaFamily(mediaType)===exports.MediaFamily.Audio?this.options.disableAudioTwcc:false;transceiver.dtxDisabled=mediaType!==exports.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(exports.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)===exports.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)===exports.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(exports.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===exports.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)!==exports.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)===exports.MediaFamily.Video){var sources=this.getVideoStreamStates(getMediaContent(mediaType));if(sources===null){return;}var contentHint;if(transceiver.publishedStream&&mediaType===exports.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===exports.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(exports.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)===exports.MediaFamily.Video){recvOnlyTransceiver.setCodecParameters({'sps-pps-idr-in-keyframe':'1'});recvOnlyTransceiver.setRtxCodecParameters({'rtx-time':mediaType===exports.MediaType.VideoMain?defaultVideoMainRtxTime:defaultVideoSlidesRtxTime});}recvOnlyTransceiver.twccDisabled=getMediaFamily(mediaType)===exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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(exports.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===exports.MediaContent.Main?mainSceneId:slidesSceneId;var mid=this.midPredictor.getNextMid(mediaType);transceiver.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'sendrecv',sendEncodings:getMediaFamily(mediaType)===exports.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(exports.MediaType.AudioMain),audioSlides:this.getCsiByMediaType(exports.MediaType.AudioSlides),videoMain:this.getCsiByMediaType(exports.MediaType.VideoMain),videoSlides:this.getCsiByMediaType(exports.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);}}
5612
5616
 
5613
5617
  var defaultLogger = {
5614
5618
  info: function info() {
@@ -18066,11 +18070,15 @@ var getH264ProfileFromStatsByStreamStatsId = (intervalStats, streamStatsId) => {
18066
18070
  }
18067
18071
  return undefined;
18068
18072
  };
18069
- var isStreamRequested = stats => {
18070
- var now = performance.timeOrigin + performance.now();
18071
- var lastRequestedUpdateTimestamp = stats.lastRequestedUpdateTimestamp;
18072
- var isCurrentlyRequested = stats.isRequested;
18073
- return isCurrentlyRequested || !!(lastRequestedUpdateTimestamp && now - lastRequestedUpdateTimestamp < MQE_INTERVAL);
18073
+ var isStreamRequested = streamStats => {
18074
+ var _isRequestedArray$som;
18075
+ var isRequestedArray = streamStats.isRequestedArray;
18076
+ return (_isRequestedArray$som = isRequestedArray === null || isRequestedArray === void 0 ? void 0 : isRequestedArray.some(isRequested => isRequested === true)) !== null && _isRequestedArray$som !== void 0 ? _isRequestedArray$som : false;
18077
+ };
18078
+ var isStreamLive = streamStats => {
18079
+ var _sourceStateArray$som;
18080
+ var sourceStateArray = streamStats.sourceStateArray;
18081
+ return (_sourceStateArray$som = sourceStateArray === null || sourceStateArray === void 0 ? void 0 : sourceStateArray.some(state => state === 'live')) !== null && _sourceStateArray$som !== void 0 ? _sourceStateArray$som : false;
18074
18082
  };
18075
18083
  var pixelsToFrameSize = (width, height) => {
18076
18084
  var round16 = n => Math.ceil(n / 16) * 16;
@@ -18109,6 +18117,8 @@ class MqeBuilder {
18109
18117
  };
18110
18118
  if (stats.type === 'inbound-rtp') {
18111
18119
  var _current$rtpPacketSiz, _stats$bytesReceived, _stats$packetsReceive;
18120
+ storeValueInArray('isRequestedArray', stats.isRequested);
18121
+ storeValueInArray('sourceStateArray', stats.sourceState);
18112
18122
  storeValueInArray('jitterArray', stats.jitter);
18113
18123
  storeValueInArray('requestedBitrateArray', stats.requestedBitrate);
18114
18124
  storeValueInArray('csiArray', stats.csi);
@@ -18152,6 +18162,8 @@ class MqeBuilder {
18152
18162
  }
18153
18163
  } else if (stats.type === 'outbound-rtp') {
18154
18164
  var _current$rtpPacketSiz2, _stats$bytesSent, _stats$packetsSent;
18165
+ storeValueInArray('isRequestedArray', stats.isRequested);
18166
+ storeValueInArray('sourceStateArray', stats.sourceState);
18155
18167
  storeValueInArray('requestedBitrateArray', stats.requestedBitrate);
18156
18168
  var lastUsedEffect = current === null || current === void 0 ? void 0 : current.lastUsedEffect;
18157
18169
  var effect = stats === null || stats === void 0 ? void 0 : stats.effect;
@@ -18209,6 +18221,8 @@ class MqeBuilder {
18209
18221
  this.previousIntervalStats = new Map(this.currentIntervalStats);
18210
18222
  this.currentIntervalStats.forEach(stats => {
18211
18223
  if (stats.type === 'inbound-rtp') {
18224
+ delete stats.isRequestedArray;
18225
+ delete stats.sourceStateArray;
18212
18226
  delete stats.jitterArray;
18213
18227
  delete stats.requestedBitrateArray;
18214
18228
  delete stats.csiArray;
@@ -18220,9 +18234,10 @@ class MqeBuilder {
18220
18234
  delete stats.maxDecodedFrameRateForMaxRequestedFrameSize;
18221
18235
  delete stats.maxFrameSizeHeightForMaxRequestedFrameSize;
18222
18236
  delete stats.maxFrameSizeWidthForMaxRequestedFrameSize;
18223
- delete stats.isRequested;
18224
18237
  delete stats.rtpPacketSizeArray;
18225
18238
  } else if (stats.type === 'outbound-rtp') {
18239
+ delete stats.isRequestedArray;
18240
+ delete stats.sourceStateArray;
18226
18241
  delete stats.requestedBitrateArray;
18227
18242
  delete stats.lastUsedEffect;
18228
18243
  delete stats.maxRequestedFrameSize;
@@ -18232,7 +18247,6 @@ class MqeBuilder {
18232
18247
  delete stats.maxTransmittedFrameRateForMaxRequestedFrameSize;
18233
18248
  delete stats.maxFrameSizeHeightForMaxRequestedFrameSize;
18234
18249
  delete stats.maxFrameSizeWidthForMaxRequestedFrameSize;
18235
- delete stats.isRequested;
18236
18250
  delete stats.rtpPacketSizeArray;
18237
18251
  } else if (stats.type === 'remote-inbound-rtp') {
18238
18252
  delete stats.roundTripTimeArray;
@@ -18565,7 +18579,7 @@ class MqeIntervalSessionReceiveVideoBuilder extends MqeBuilder {
18565
18579
  streams: []
18566
18580
  };
18567
18581
  this.currentIntervalStats.forEach((stats, key) => {
18568
- if (stats.type === 'inbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats))) {
18582
+ if (stats.type === 'inbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats) && isStreamLive(stats))) {
18569
18583
  result.streams.push(this.buildMqeIntervalStreamReceiveVideo(key));
18570
18584
  }
18571
18585
  });
@@ -18611,7 +18625,7 @@ class MqeIntervalSessionTransmitVideoBuilder extends MqeBuilder {
18611
18625
  streams: []
18612
18626
  };
18613
18627
  this.currentIntervalStats.forEach((stats, key) => {
18614
- if (stats.type === 'outbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats))) {
18628
+ if (stats.type === 'outbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats) && isStreamLive(stats))) {
18615
18629
  result.streams.push(this.buildMqeIntervalStreamTransmitVideo(key));
18616
18630
  }
18617
18631
  });
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() {
@@ -18062,11 +18066,15 @@ var getH264ProfileFromStatsByStreamStatsId = (intervalStats, streamStatsId) => {
18062
18066
  }
18063
18067
  return undefined;
18064
18068
  };
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);
18069
+ var isStreamRequested = streamStats => {
18070
+ var _isRequestedArray$som;
18071
+ var isRequestedArray = streamStats.isRequestedArray;
18072
+ return (_isRequestedArray$som = isRequestedArray === null || isRequestedArray === void 0 ? void 0 : isRequestedArray.some(isRequested => isRequested === true)) !== null && _isRequestedArray$som !== void 0 ? _isRequestedArray$som : false;
18073
+ };
18074
+ var isStreamLive = streamStats => {
18075
+ var _sourceStateArray$som;
18076
+ var sourceStateArray = streamStats.sourceStateArray;
18077
+ return (_sourceStateArray$som = sourceStateArray === null || sourceStateArray === void 0 ? void 0 : sourceStateArray.some(state => state === 'live')) !== null && _sourceStateArray$som !== void 0 ? _sourceStateArray$som : false;
18070
18078
  };
18071
18079
  var pixelsToFrameSize = (width, height) => {
18072
18080
  var round16 = n => Math.ceil(n / 16) * 16;
@@ -18105,6 +18113,8 @@ class MqeBuilder {
18105
18113
  };
18106
18114
  if (stats.type === 'inbound-rtp') {
18107
18115
  var _current$rtpPacketSiz, _stats$bytesReceived, _stats$packetsReceive;
18116
+ storeValueInArray('isRequestedArray', stats.isRequested);
18117
+ storeValueInArray('sourceStateArray', stats.sourceState);
18108
18118
  storeValueInArray('jitterArray', stats.jitter);
18109
18119
  storeValueInArray('requestedBitrateArray', stats.requestedBitrate);
18110
18120
  storeValueInArray('csiArray', stats.csi);
@@ -18148,6 +18158,8 @@ class MqeBuilder {
18148
18158
  }
18149
18159
  } else if (stats.type === 'outbound-rtp') {
18150
18160
  var _current$rtpPacketSiz2, _stats$bytesSent, _stats$packetsSent;
18161
+ storeValueInArray('isRequestedArray', stats.isRequested);
18162
+ storeValueInArray('sourceStateArray', stats.sourceState);
18151
18163
  storeValueInArray('requestedBitrateArray', stats.requestedBitrate);
18152
18164
  var lastUsedEffect = current === null || current === void 0 ? void 0 : current.lastUsedEffect;
18153
18165
  var effect = stats === null || stats === void 0 ? void 0 : stats.effect;
@@ -18205,6 +18217,8 @@ class MqeBuilder {
18205
18217
  this.previousIntervalStats = new Map(this.currentIntervalStats);
18206
18218
  this.currentIntervalStats.forEach(stats => {
18207
18219
  if (stats.type === 'inbound-rtp') {
18220
+ delete stats.isRequestedArray;
18221
+ delete stats.sourceStateArray;
18208
18222
  delete stats.jitterArray;
18209
18223
  delete stats.requestedBitrateArray;
18210
18224
  delete stats.csiArray;
@@ -18216,9 +18230,10 @@ class MqeBuilder {
18216
18230
  delete stats.maxDecodedFrameRateForMaxRequestedFrameSize;
18217
18231
  delete stats.maxFrameSizeHeightForMaxRequestedFrameSize;
18218
18232
  delete stats.maxFrameSizeWidthForMaxRequestedFrameSize;
18219
- delete stats.isRequested;
18220
18233
  delete stats.rtpPacketSizeArray;
18221
18234
  } else if (stats.type === 'outbound-rtp') {
18235
+ delete stats.isRequestedArray;
18236
+ delete stats.sourceStateArray;
18222
18237
  delete stats.requestedBitrateArray;
18223
18238
  delete stats.lastUsedEffect;
18224
18239
  delete stats.maxRequestedFrameSize;
@@ -18228,7 +18243,6 @@ class MqeBuilder {
18228
18243
  delete stats.maxTransmittedFrameRateForMaxRequestedFrameSize;
18229
18244
  delete stats.maxFrameSizeHeightForMaxRequestedFrameSize;
18230
18245
  delete stats.maxFrameSizeWidthForMaxRequestedFrameSize;
18231
- delete stats.isRequested;
18232
18246
  delete stats.rtpPacketSizeArray;
18233
18247
  } else if (stats.type === 'remote-inbound-rtp') {
18234
18248
  delete stats.roundTripTimeArray;
@@ -18561,7 +18575,7 @@ class MqeIntervalSessionReceiveVideoBuilder extends MqeBuilder {
18561
18575
  streams: []
18562
18576
  };
18563
18577
  this.currentIntervalStats.forEach((stats, key) => {
18564
- if (stats.type === 'inbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats))) {
18578
+ if (stats.type === 'inbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats) && isStreamLive(stats))) {
18565
18579
  result.streams.push(this.buildMqeIntervalStreamReceiveVideo(key));
18566
18580
  }
18567
18581
  });
@@ -18607,7 +18621,7 @@ class MqeIntervalSessionTransmitVideoBuilder extends MqeBuilder {
18607
18621
  streams: []
18608
18622
  };
18609
18623
  this.currentIntervalStats.forEach((stats, key) => {
18610
- if (stats.type === 'outbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats))) {
18624
+ if (stats.type === 'outbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats) && isStreamLive(stats))) {
18611
18625
  result.streams.push(this.buildMqeIntervalStreamTransmitVideo(key));
18612
18626
  }
18613
18627
  });
@@ -26,5 +26,6 @@ export interface MultistreamConnectionConfig {
26
26
  doFullIce?: boolean;
27
27
  stopIceGatheringAfterFirstRelayCandidate?: boolean;
28
28
  disableAudioMainDtx?: boolean;
29
+ disableAudioTwcc?: boolean;
29
30
  }
30
31
  //# sourceMappingURL=config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/MediaConnection/config.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,gBAAgB;IAC/B,eAAe,CAAC,EAAE,OAAO,CAAoE;IAC7F,gBAAgB,CAAC,EAAE,OAAO,CAAuE;IACjG,kBAAkB,CAAC,EAAE,OAAO,CAAoE;IAChG,eAAe,CAAC,EAAE;QAChB,KAAK,EAAE,MAAM,CAA6E;QAC1F,KAAK,EAAE,MAAM,CAA6E;KAC3F,CAAC;IACF,YAAY,CAAC,EAAE,MAAM,CACmE;IACxF,iBAAiB,CAAC,EAAE,MAAM,CAAqE;IAC/F,aAAa,CAAC,EAAE,OAAO,CACkC;IACzD,UAAU,CAAC,EAAE,OAAO,CAC4C;IAChE,SAAS,CAAC,EAAE,MAAM,CAEkD;IACpE,uBAAuB,CAAC,EAAE,OAAO,CACiC;CACnE;AAED,MAAM,WAAW,qBAAqB;IAEpC,UAAU,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAChC,wBAAwB,EAAE,OAAO,CAmBM;IACvC,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,UAAU,EAAE,gBAAgB,CAAC;CAC9B;AAED,MAAM,WAAW,2BAA2B;IAC1C,UAAU,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAChC,YAAY,CAAC,EAAE,YAAY,GAAG,YAAY,CAAC;IAC3C,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,wCAAwC,CAAC,EAAE,OAAO,CAAC;IACnD,mBAAmB,CAAC,EAAE,OAAO,CAAC;CAC/B"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/MediaConnection/config.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,gBAAgB;IAC/B,eAAe,CAAC,EAAE,OAAO,CAAoE;IAC7F,gBAAgB,CAAC,EAAE,OAAO,CAAuE;IACjG,kBAAkB,CAAC,EAAE,OAAO,CAAoE;IAChG,eAAe,CAAC,EAAE;QAChB,KAAK,EAAE,MAAM,CAA6E;QAC1F,KAAK,EAAE,MAAM,CAA6E;KAC3F,CAAC;IACF,YAAY,CAAC,EAAE,MAAM,CACmE;IACxF,iBAAiB,CAAC,EAAE,MAAM,CAAqE;IAC/F,aAAa,CAAC,EAAE,OAAO,CACkC;IACzD,UAAU,CAAC,EAAE,OAAO,CAC4C;IAChE,SAAS,CAAC,EAAE,MAAM,CAEkD;IACpE,uBAAuB,CAAC,EAAE,OAAO,CACiC;CACnE;AAED,MAAM,WAAW,qBAAqB;IAEpC,UAAU,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAChC,wBAAwB,EAAE,OAAO,CAmBM;IACvC,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,UAAU,EAAE,gBAAgB,CAAC;CAC9B;AAED,MAAM,WAAW,2BAA2B;IAC1C,UAAU,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAChC,YAAY,CAAC,EAAE,YAAY,GAAG,YAAY,CAAC;IAC3C,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,wCAAwC,CAAC,EAAE,OAAO,CAAC;IACnD,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B"}
@@ -1 +1 @@
1
- {"version":3,"file":"MqeBuilder.d.ts","sourceRoot":"","sources":["../../../src/StatsAnalyzer/MqeBuilder.ts"],"names":[],"mappings":"AAGA,OAAO,EAUL,wBAAwB,EACxB,yBAAyB,EACzB,0BAA0B,EAC1B,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,8BAA8B,EAC9B,+BAA+B,EAC/B,8BAA8B,EAC/B,MAAM,YAAY,CAAC;AACpB,OAAO,EAAe,QAAQ,EAAE,MAAM,SAAS,CAAC;AAmBhD,8BAAsB,UAAU;IAE9B,oBAAoB,EAAE,QAAQ,CAAa;IAG3C,qBAAqB,EAAE,QAAQ,CAAa;IAE5C,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC;IAE1B,SAAS,CAAC,kBAAkB,EAAE,OAAO,CAAC;IAEtC,SAAS,CAAC,SAAS,EAAE,wBAAwB,CAAC,WAAW,CAAC,CAAC;IAE3D,SAAS,CAAC,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC;gBAO3B,MAAM,EAAE;QAClB,MAAM,EAAE,OAAO,CAAC;QAChB,kBAAkB,EAAE,OAAO,CAAC;QAC5B,SAAS,EAAE,wBAAwB,CAAC,WAAW,CAAC,CAAC;QACjD,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC;KAC9B;IAYD,QAAQ,CAAC,QAAQ,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAQ5C,0BAA0B,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI;IAwPpD,KAAK,IAAI,IAAI;IAQb,oBAAoB,IAAI,IAAI;IAoD5B,SAAS,CAAC,6BAA6B,IAAI,wBAAwB;IAyBnE,SAAS,CAAC,8BAA8B,IAAI,yBAAyB;IAgHrE,SAAS,CAAC,kCAAkC,CAAC,EAAE,EAAE,MAAM,GAAG,6BAA6B;IAiBvF,SAAS,CAAC,kCAAkC,CAAC,EAAE,EAAE,MAAM,GAAG,6BAA6B;IAkFvF,SAAS,CAAC,mCAAmC,CAAC,EAAE,EAAE,MAAM,GAAG,8BAA8B;IA0JzF,SAAS,CAAC,+BAA+B,IAAI,0BAA0B;IA8GvE,SAAS,CAAC,mCAAmC,CAAC,EAAE,EAAE,MAAM,GAAG,8BAA8B;IA6BzF,SAAS,CAAC,mCAAmC,CAAC,EAAE,EAAE,MAAM,GAAG,8BAA8B;IAwFzF,SAAS,CAAC,oCAAoC,CAAC,EAAE,EAAE,MAAM,GAAG,+BAA+B;CAyF5F"}
1
+ {"version":3,"file":"MqeBuilder.d.ts","sourceRoot":"","sources":["../../../src/StatsAnalyzer/MqeBuilder.ts"],"names":[],"mappings":"AAIA,OAAO,EAUL,wBAAwB,EACxB,yBAAyB,EACzB,0BAA0B,EAC1B,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,8BAA8B,EAC9B,+BAA+B,EAC/B,8BAA8B,EAC/B,MAAM,YAAY,CAAC;AACpB,OAAO,EAAe,QAAQ,EAAE,MAAM,SAAS,CAAC;AAmBhD,8BAAsB,UAAU;IAE9B,oBAAoB,EAAE,QAAQ,CAAa;IAG3C,qBAAqB,EAAE,QAAQ,CAAa;IAE5C,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC;IAE1B,SAAS,CAAC,kBAAkB,EAAE,OAAO,CAAC;IAEtC,SAAS,CAAC,SAAS,EAAE,wBAAwB,CAAC,WAAW,CAAC,CAAC;IAE3D,SAAS,CAAC,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC;gBAO3B,MAAM,EAAE;QAClB,MAAM,EAAE,OAAO,CAAC;QAChB,kBAAkB,EAAE,OAAO,CAAC;QAC5B,SAAS,EAAE,wBAAwB,CAAC,WAAW,CAAC,CAAC;QACjD,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC;KAC9B;IAYD,QAAQ,CAAC,QAAQ,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAQ5C,0BAA0B,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI;IAoQpD,KAAK,IAAI,IAAI;IAQb,oBAAoB,IAAI,IAAI;IAgD5B,SAAS,CAAC,6BAA6B,IAAI,wBAAwB;IAyBnE,SAAS,CAAC,8BAA8B,IAAI,yBAAyB;IAgHrE,SAAS,CAAC,kCAAkC,CAAC,EAAE,EAAE,MAAM,GAAG,6BAA6B;IAiBvF,SAAS,CAAC,kCAAkC,CAAC,EAAE,EAAE,MAAM,GAAG,6BAA6B;IAkFvF,SAAS,CAAC,mCAAmC,CAAC,EAAE,EAAE,MAAM,GAAG,8BAA8B;IA0JzF,SAAS,CAAC,+BAA+B,IAAI,0BAA0B;IA8GvE,SAAS,CAAC,mCAAmC,CAAC,EAAE,EAAE,MAAM,GAAG,8BAA8B;IA6BzF,SAAS,CAAC,mCAAmC,CAAC,EAAE,EAAE,MAAM,GAAG,8BAA8B;IAwFzF,SAAS,CAAC,oCAAoC,CAAC,EAAE,EAAE,MAAM,GAAG,+BAA+B;CAyF5F"}
@@ -1 +1 @@
1
- {"version":3,"file":"MqeIntervalSessionReceiveVideoBuilder.d.ts","sourceRoot":"","sources":["../../../src/StatsAnalyzer/MqeIntervalSessionReceiveVideoBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC;AAG5D,qBAAa,qCAAsC,SAAQ,UAAU;gBACvD,MAAM,EAAE;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,kBAAkB,EAAE,OAAO,CAAA;KAAE;IAIpE,QAAQ,IAAI,8BAA8B;CAgB3C"}
1
+ {"version":3,"file":"MqeIntervalSessionReceiveVideoBuilder.d.ts","sourceRoot":"","sources":["../../../src/StatsAnalyzer/MqeIntervalSessionReceiveVideoBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC;AAG5D,qBAAa,qCAAsC,SAAQ,UAAU;gBACvD,MAAM,EAAE;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,kBAAkB,EAAE,OAAO,CAAA;KAAE;IAIpE,QAAQ,IAAI,8BAA8B;CAmB3C"}
@@ -1 +1 @@
1
- {"version":3,"file":"MqeIntervalSessionTransmitVideoBuilder.d.ts","sourceRoot":"","sources":["../../../src/StatsAnalyzer/MqeIntervalSessionTransmitVideoBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,+BAA+B,EAAE,MAAM,YAAY,CAAC;AAG7D,qBAAa,sCAAuC,SAAQ,UAAU;gBACxD,MAAM,EAAE;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,kBAAkB,EAAE,OAAO,CAAA;KAAE;IAIpE,QAAQ,IAAI,+BAA+B;CAgB5C"}
1
+ {"version":3,"file":"MqeIntervalSessionTransmitVideoBuilder.d.ts","sourceRoot":"","sources":["../../../src/StatsAnalyzer/MqeIntervalSessionTransmitVideoBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,+BAA+B,EAAE,MAAM,YAAY,CAAC;AAG7D,qBAAa,sCAAuC,SAAQ,UAAU;gBACxD,MAAM,EAAE;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,kBAAkB,EAAE,OAAO,CAAA;KAAE;IAIpE,QAAQ,IAAI,+BAA+B;CAmB5C"}
@@ -17,6 +17,7 @@ export declare const getAvailableOutgoingBitrateArrayFromStats: (intervalStats:
17
17
  export declare const getMediaSourceTrackLabelFromStats: (intervalStats: StatsMap) => string | undefined;
18
18
  export declare const getCodecFromStatsByStreamStatsId: (intervalStats: StatsMap, streamStatsId: string) => string | undefined;
19
19
  export declare const getH264ProfileFromStatsByStreamStatsId: (intervalStats: StatsMap, streamStatsId: string) => 'BP' | 'CHP' | undefined;
20
- export declare const isStreamRequested: (stats: Stats) => boolean;
20
+ export declare const isStreamRequested: (streamStats: Stats) => boolean;
21
+ export declare const isStreamLive: (streamStats: Stats) => boolean;
21
22
  export declare const pixelsToFrameSize: (width: number, height: number) => number;
22
23
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/StatsAnalyzer/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAErE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAQ1C,eAAO,MAAM,GAAG,UAAW,MAAM,EAAE,KAAG,MAMrC,CAAC;AAQF,eAAO,MAAM,GAAG,UAAW,MAAM,EAAE,KAAG,MAMrC,CAAC;AAQF,eAAO,MAAM,IAAI,UAAW,MAAM,EAAE,KAAG,MAMtC,CAAC;AASF,eAAO,MAAM,cAAc,UAAW,MAAM,eAAe,MAAM,KAAG,MAMnE,CAAC;AASF,eAAO,MAAM,qBAAqB,YAAa,MAAM,aAAa,MAAM,KAAG,MAU1E,CAAC;AASF,eAAO,MAAM,iBAAiB,WAAY,MAAM,eAAe,MAAM,KAAG,MAMvE,CAAC;AAQF,eAAO,MAAM,iBAAiB,eAAgB,mBAAmB,EAAE,aAQlE,CAAC;AAWF,eAAO,MAAM,wBAAwB,qCAE1B,MAAM,YACL,MAAM,KACf,OAAO,GAAG,SAEZ,CAAC;AAYF,eAAO,MAAM,0BAA0B,uCAE1B,YAAY,YACb,MAAM,KACf,OAAO,GAAG,SAUZ,CAAC;AAYF,eAAO,MAAM,iCAAiC,uCAEjC,YAAY,YACb,MAAM,KACf,OAAO,EAUT,CAAC;AAWF,eAAO,MAAM,qBAAqB,uCAErB,YAAY,YACb,MAAM,KACf,MAeF,CAAC;AAyDF,eAAO,MAAM,+BAA+B,6CAEzB,OAAO,GAAG,QAAQ,KAClC,MAAM,GAAG,SAcX,CAAC;AAYF,eAAO,MAAM,yBAAyB,+BAEnC,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,SA4B1B,CAAC;AAYF,eAAO,MAAM,yCAAyC,+BAEnD,MAAM,EAAE,GAAG,SAgBb,CAAC;AAUF,eAAO,MAAM,iCAAiC,+BAA8B,MAAM,GAAG,SAgBpF,CAAC;AAUF,eAAO,MAAM,gCAAgC,2CAE5B,MAAM,KACpB,MAAM,GAAG,SAgBX,CAAC;AAUF,eAAO,MAAM,sCAAsC,2CAElC,MAAM,KACpB,IAAI,GAAG,KAAK,GAAG,SA2BjB,CAAC;AASF,eAAO,MAAM,iBAAiB,UAAW,KAAK,KAAG,OAUhD,CAAC;AAUF,eAAO,MAAM,iBAAiB,UAAW,MAAM,UAAU,MAAM,KAAG,MAIjE,CAAC"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/StatsAnalyzer/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAQ1C,eAAO,MAAM,GAAG,UAAW,MAAM,EAAE,KAAG,MAMrC,CAAC;AAQF,eAAO,MAAM,GAAG,UAAW,MAAM,EAAE,KAAG,MAMrC,CAAC;AAQF,eAAO,MAAM,IAAI,UAAW,MAAM,EAAE,KAAG,MAMtC,CAAC;AASF,eAAO,MAAM,cAAc,UAAW,MAAM,eAAe,MAAM,KAAG,MAMnE,CAAC;AASF,eAAO,MAAM,qBAAqB,YAAa,MAAM,aAAa,MAAM,KAAG,MAU1E,CAAC;AASF,eAAO,MAAM,iBAAiB,WAAY,MAAM,eAAe,MAAM,KAAG,MAMvE,CAAC;AAQF,eAAO,MAAM,iBAAiB,eAAgB,mBAAmB,EAAE,aAQlE,CAAC;AAWF,eAAO,MAAM,wBAAwB,qCAE1B,MAAM,YACL,MAAM,KACf,OAAO,GAAG,SAEZ,CAAC;AAYF,eAAO,MAAM,0BAA0B,uCAE1B,YAAY,YACb,MAAM,KACf,OAAO,GAAG,SAUZ,CAAC;AAYF,eAAO,MAAM,iCAAiC,uCAEjC,YAAY,YACb,MAAM,KACf,OAAO,EAUT,CAAC;AAWF,eAAO,MAAM,qBAAqB,uCAErB,YAAY,YACb,MAAM,KACf,MAeF,CAAC;AAyDF,eAAO,MAAM,+BAA+B,6CAEzB,OAAO,GAAG,QAAQ,KAClC,MAAM,GAAG,SAcX,CAAC;AAYF,eAAO,MAAM,yBAAyB,+BAEnC,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,SA4B1B,CAAC;AAYF,eAAO,MAAM,yCAAyC,+BAEnD,MAAM,EAAE,GAAG,SAgBb,CAAC;AAUF,eAAO,MAAM,iCAAiC,+BAA8B,MAAM,GAAG,SAgBpF,CAAC;AAUF,eAAO,MAAM,gCAAgC,2CAE5B,MAAM,KACpB,MAAM,GAAG,SAgBX,CAAC;AAUF,eAAO,MAAM,sCAAsC,2CAElC,MAAM,KACpB,IAAI,GAAG,KAAK,GAAG,SA2BjB,CAAC;AASF,eAAO,MAAM,iBAAiB,gBAAiB,KAAK,KAAG,OAItD,CAAC;AASF,eAAO,MAAM,YAAY,gBAAiB,KAAK,KAAG,OAIjD,CAAC;AAUF,eAAO,MAAM,iBAAiB,UAAW,MAAM,UAAU,MAAM,KAAG,MAIjE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webex/internal-media-core",
3
- "version": "2.16.2",
3
+ "version": "2.17.1",
4
4
  "files": [
5
5
  "dist/cjs",
6
6
  "dist/esm",
@@ -60,7 +60,7 @@
60
60
  "@webex/rtcstats": "^1.5.0",
61
61
  "@webex/ts-sdp": "1.7.0",
62
62
  "@webex/web-capabilities": "^1.4.1",
63
- "@webex/web-client-media-engine": "3.31.3",
63
+ "@webex/web-client-media-engine": "3.32.0",
64
64
  "events": "^3.3.0",
65
65
  "ip-anonymize": "^0.1.0",
66
66
  "typed-emitter": "^2.1.0",