@webex/internal-media-core 2.17.0 → 2.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +86 -59
- package/dist/esm/index.js +86 -59
- package/dist/types/MediaConnection/MultistreamRoapMediaConnection.d.ts +1 -1
- package/dist/types/MediaConnection/MultistreamRoapMediaConnection.d.ts.map +1 -1
- package/dist/types/MediaConnection/RoapMediaConnection.d.ts +1 -1
- package/dist/types/MediaConnection/RoapMediaConnection.d.ts.map +1 -1
- package/dist/types/StatsAnalyzer/MqeBuilder.d.ts.map +1 -1
- package/dist/types/StatsAnalyzer/MqeIntervalSessionReceiveVideoBuilder.d.ts.map +1 -1
- package/dist/types/StatsAnalyzer/MqeIntervalSessionTransmitVideoBuilder.d.ts.map +1 -1
- package/dist/types/StatsAnalyzer/utils.d.ts +2 -1
- package/dist/types/StatsAnalyzer/utils.d.ts.map +1 -1
- package/package.json +2 -2
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() {
|
|
@@ -15804,29 +15808,35 @@ class RoapMediaConnection extends EventEmitter$5 {
|
|
|
15804
15808
|
this.roap.stop();
|
|
15805
15809
|
this.roap.removeAllListeners();
|
|
15806
15810
|
}
|
|
15807
|
-
reconnect(
|
|
15808
|
-
var
|
|
15809
|
-
|
|
15810
|
-
|
|
15811
|
-
|
|
15812
|
-
|
|
15813
|
-
|
|
15814
|
-
|
|
15815
|
-
|
|
15816
|
-
|
|
15817
|
-
|
|
15818
|
-
|
|
15819
|
-
|
|
15820
|
-
|
|
15821
|
-
|
|
15822
|
-
|
|
15823
|
-
|
|
15824
|
-
|
|
15825
|
-
|
|
15826
|
-
|
|
15827
|
-
|
|
15828
|
-
|
|
15829
|
-
|
|
15811
|
+
reconnect(iceServersPromise) {
|
|
15812
|
+
var _arguments = arguments,
|
|
15813
|
+
_this3 = this;
|
|
15814
|
+
return _asyncToGenerator(function* () {
|
|
15815
|
+
var initiateOffer = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true;
|
|
15816
|
+
_this3.log('reconnect()', "initiated");
|
|
15817
|
+
var options = _this3.mediaConnection.getSendReceiveOptions();
|
|
15818
|
+
var seq = _this3.roap.getSeq();
|
|
15819
|
+
var callback = _this3.mediaConnection.getMetricsCallback();
|
|
15820
|
+
_this3.stopRoapSession();
|
|
15821
|
+
_this3.closeMediaConnection();
|
|
15822
|
+
_this3.sdpNegotiationStarted = false;
|
|
15823
|
+
var iceServers = yield iceServersPromise;
|
|
15824
|
+
_this3.log('reconnect()', "iceServers: ".concat(JSON.stringify(iceServers)));
|
|
15825
|
+
var config = _objectSpread$6(_objectSpread$6({}, _this3.mediaConnection.getConfig()), {}, {
|
|
15826
|
+
iceServers
|
|
15827
|
+
});
|
|
15828
|
+
_this3.mediaConnection = _this3.createMediaConnection({
|
|
15829
|
+
mediaConnectionConfig: config,
|
|
15830
|
+
options,
|
|
15831
|
+
metricsCallback: callback,
|
|
15832
|
+
debugId: _this3.debugId
|
|
15833
|
+
});
|
|
15834
|
+
_this3.roap = _this3.createRoap(_this3.debugId, seq);
|
|
15835
|
+
if (initiateOffer) {
|
|
15836
|
+
return _this3.initiateOffer();
|
|
15837
|
+
}
|
|
15838
|
+
return Promise.resolve();
|
|
15839
|
+
})();
|
|
15830
15840
|
}
|
|
15831
15841
|
updateLocalTracks(tracks) {
|
|
15832
15842
|
this.log('updateLocalTracks()', "called with ".concat(JSON.stringify(tracks)));
|
|
@@ -16037,20 +16047,27 @@ class MultistreamRoapMediaConnection extends EventEmitter$5 {
|
|
|
16037
16047
|
this.roap.stop();
|
|
16038
16048
|
this.roap.removeAllListeners();
|
|
16039
16049
|
}
|
|
16040
|
-
reconnect(
|
|
16041
|
-
var
|
|
16042
|
-
|
|
16043
|
-
|
|
16044
|
-
|
|
16045
|
-
|
|
16046
|
-
|
|
16047
|
-
|
|
16048
|
-
|
|
16049
|
-
|
|
16050
|
-
|
|
16051
|
-
|
|
16052
|
-
|
|
16053
|
-
|
|
16050
|
+
reconnect(iceServersPromise) {
|
|
16051
|
+
var _arguments = arguments,
|
|
16052
|
+
_this2 = this;
|
|
16053
|
+
return _asyncToGenerator(function* () {
|
|
16054
|
+
var initiateOffer = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true;
|
|
16055
|
+
_this2.log('reconnect()', "initiated");
|
|
16056
|
+
var seq = _this2.roap.getSeq();
|
|
16057
|
+
_this2.stopRoapSession();
|
|
16058
|
+
_this2.sdpNegotiationStarted = false;
|
|
16059
|
+
var userOptionsPromise = Promise.resolve(iceServersPromise).then(iceServers => ({
|
|
16060
|
+
iceServers
|
|
16061
|
+
})).catch(() => {
|
|
16062
|
+
throw new Error('Failed to collect user options for reconnect');
|
|
16063
|
+
});
|
|
16064
|
+
yield _this2.multistreamConnection.renewPeerConnection(userOptionsPromise);
|
|
16065
|
+
_this2.roap = _this2.createRoap(_this2.debugId, seq);
|
|
16066
|
+
if (initiateOffer) {
|
|
16067
|
+
return _this2.initiateOffer();
|
|
16068
|
+
}
|
|
16069
|
+
return Promise.resolve();
|
|
16070
|
+
})();
|
|
16054
16071
|
}
|
|
16055
16072
|
getConnectionState() {
|
|
16056
16073
|
var connectionState = this.multistreamConnection.getConnectionState();
|
|
@@ -16131,26 +16148,26 @@ class MultistreamRoapMediaConnection extends EventEmitter$5 {
|
|
|
16131
16148
|
});
|
|
16132
16149
|
}
|
|
16133
16150
|
handleRemoteAnswer(sdp) {
|
|
16134
|
-
var
|
|
16151
|
+
var _this3 = this;
|
|
16135
16152
|
return _asyncToGenerator(function* () {
|
|
16136
|
-
|
|
16153
|
+
_this3.log('handleRemoteAnswer()', "called: sdp=".concat(sdp ? 'non-empty' : 'empty'));
|
|
16137
16154
|
if (sdp) {
|
|
16138
16155
|
try {
|
|
16139
|
-
yield
|
|
16156
|
+
yield _this3.waitForIceCandidates();
|
|
16140
16157
|
} catch (e) {
|
|
16141
16158
|
var {
|
|
16142
16159
|
message
|
|
16143
16160
|
} = e;
|
|
16144
|
-
|
|
16161
|
+
_this3.warn('handleRemoteAnswer()', "".concat(message));
|
|
16145
16162
|
}
|
|
16146
16163
|
var mungedSdp = mungeRemoteSdp({}, sdp);
|
|
16147
|
-
|
|
16148
|
-
return
|
|
16149
|
-
|
|
16150
|
-
|
|
16164
|
+
_this3.log('handleRemoteAnswer()', 'calling this.multistreamConnection.setAnswer');
|
|
16165
|
+
return _this3.multistreamConnection.setAnswer(mungedSdp).then(result => {
|
|
16166
|
+
_this3.log('handleRemoteAnswer()', 'this.multistreamConnection.setAnswer resolved');
|
|
16167
|
+
_this3.emit(exports.MediaConnectionEventNames.REMOTE_SDP_ANSWER_PROCESSED);
|
|
16151
16168
|
return result;
|
|
16152
16169
|
}).catch(error => {
|
|
16153
|
-
|
|
16170
|
+
_this3.log('handleRemoteAnswer()', "this.multistreamConnection.setAnswer failed");
|
|
16154
16171
|
throw new SdpAnswerHandlingError("handleRemoteAnswer() failure: ".concat(error.message), {
|
|
16155
16172
|
cause: error
|
|
16156
16173
|
});
|
|
@@ -18066,11 +18083,15 @@ var getH264ProfileFromStatsByStreamStatsId = (intervalStats, streamStatsId) => {
|
|
|
18066
18083
|
}
|
|
18067
18084
|
return undefined;
|
|
18068
18085
|
};
|
|
18069
|
-
var isStreamRequested =
|
|
18070
|
-
var
|
|
18071
|
-
var
|
|
18072
|
-
|
|
18073
|
-
|
|
18086
|
+
var isStreamRequested = streamStats => {
|
|
18087
|
+
var _isRequestedArray$som;
|
|
18088
|
+
var isRequestedArray = streamStats.isRequestedArray;
|
|
18089
|
+
return (_isRequestedArray$som = isRequestedArray === null || isRequestedArray === void 0 ? void 0 : isRequestedArray.some(isRequested => isRequested === true)) !== null && _isRequestedArray$som !== void 0 ? _isRequestedArray$som : false;
|
|
18090
|
+
};
|
|
18091
|
+
var isStreamLive = streamStats => {
|
|
18092
|
+
var _sourceStateArray$som;
|
|
18093
|
+
var sourceStateArray = streamStats.sourceStateArray;
|
|
18094
|
+
return (_sourceStateArray$som = sourceStateArray === null || sourceStateArray === void 0 ? void 0 : sourceStateArray.some(state => state === 'live')) !== null && _sourceStateArray$som !== void 0 ? _sourceStateArray$som : false;
|
|
18074
18095
|
};
|
|
18075
18096
|
var pixelsToFrameSize = (width, height) => {
|
|
18076
18097
|
var round16 = n => Math.ceil(n / 16) * 16;
|
|
@@ -18109,6 +18130,8 @@ class MqeBuilder {
|
|
|
18109
18130
|
};
|
|
18110
18131
|
if (stats.type === 'inbound-rtp') {
|
|
18111
18132
|
var _current$rtpPacketSiz, _stats$bytesReceived, _stats$packetsReceive;
|
|
18133
|
+
storeValueInArray('isRequestedArray', stats.isRequested);
|
|
18134
|
+
storeValueInArray('sourceStateArray', stats.sourceState);
|
|
18112
18135
|
storeValueInArray('jitterArray', stats.jitter);
|
|
18113
18136
|
storeValueInArray('requestedBitrateArray', stats.requestedBitrate);
|
|
18114
18137
|
storeValueInArray('csiArray', stats.csi);
|
|
@@ -18152,6 +18175,8 @@ class MqeBuilder {
|
|
|
18152
18175
|
}
|
|
18153
18176
|
} else if (stats.type === 'outbound-rtp') {
|
|
18154
18177
|
var _current$rtpPacketSiz2, _stats$bytesSent, _stats$packetsSent;
|
|
18178
|
+
storeValueInArray('isRequestedArray', stats.isRequested);
|
|
18179
|
+
storeValueInArray('sourceStateArray', stats.sourceState);
|
|
18155
18180
|
storeValueInArray('requestedBitrateArray', stats.requestedBitrate);
|
|
18156
18181
|
var lastUsedEffect = current === null || current === void 0 ? void 0 : current.lastUsedEffect;
|
|
18157
18182
|
var effect = stats === null || stats === void 0 ? void 0 : stats.effect;
|
|
@@ -18209,6 +18234,8 @@ class MqeBuilder {
|
|
|
18209
18234
|
this.previousIntervalStats = new Map(this.currentIntervalStats);
|
|
18210
18235
|
this.currentIntervalStats.forEach(stats => {
|
|
18211
18236
|
if (stats.type === 'inbound-rtp') {
|
|
18237
|
+
delete stats.isRequestedArray;
|
|
18238
|
+
delete stats.sourceStateArray;
|
|
18212
18239
|
delete stats.jitterArray;
|
|
18213
18240
|
delete stats.requestedBitrateArray;
|
|
18214
18241
|
delete stats.csiArray;
|
|
@@ -18220,9 +18247,10 @@ class MqeBuilder {
|
|
|
18220
18247
|
delete stats.maxDecodedFrameRateForMaxRequestedFrameSize;
|
|
18221
18248
|
delete stats.maxFrameSizeHeightForMaxRequestedFrameSize;
|
|
18222
18249
|
delete stats.maxFrameSizeWidthForMaxRequestedFrameSize;
|
|
18223
|
-
delete stats.isRequested;
|
|
18224
18250
|
delete stats.rtpPacketSizeArray;
|
|
18225
18251
|
} else if (stats.type === 'outbound-rtp') {
|
|
18252
|
+
delete stats.isRequestedArray;
|
|
18253
|
+
delete stats.sourceStateArray;
|
|
18226
18254
|
delete stats.requestedBitrateArray;
|
|
18227
18255
|
delete stats.lastUsedEffect;
|
|
18228
18256
|
delete stats.maxRequestedFrameSize;
|
|
@@ -18232,7 +18260,6 @@ class MqeBuilder {
|
|
|
18232
18260
|
delete stats.maxTransmittedFrameRateForMaxRequestedFrameSize;
|
|
18233
18261
|
delete stats.maxFrameSizeHeightForMaxRequestedFrameSize;
|
|
18234
18262
|
delete stats.maxFrameSizeWidthForMaxRequestedFrameSize;
|
|
18235
|
-
delete stats.isRequested;
|
|
18236
18263
|
delete stats.rtpPacketSizeArray;
|
|
18237
18264
|
} else if (stats.type === 'remote-inbound-rtp') {
|
|
18238
18265
|
delete stats.roundTripTimeArray;
|
|
@@ -18565,7 +18592,7 @@ class MqeIntervalSessionReceiveVideoBuilder extends MqeBuilder {
|
|
|
18565
18592
|
streams: []
|
|
18566
18593
|
};
|
|
18567
18594
|
this.currentIntervalStats.forEach((stats, key) => {
|
|
18568
|
-
if (stats.type === 'inbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats))) {
|
|
18595
|
+
if (stats.type === 'inbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats) && isStreamLive(stats))) {
|
|
18569
18596
|
result.streams.push(this.buildMqeIntervalStreamReceiveVideo(key));
|
|
18570
18597
|
}
|
|
18571
18598
|
});
|
|
@@ -18611,7 +18638,7 @@ class MqeIntervalSessionTransmitVideoBuilder extends MqeBuilder {
|
|
|
18611
18638
|
streams: []
|
|
18612
18639
|
};
|
|
18613
18640
|
this.currentIntervalStats.forEach((stats, key) => {
|
|
18614
|
-
if (stats.type === 'outbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats))) {
|
|
18641
|
+
if (stats.type === 'outbound-rtp' && (!this.multistreamEnabled || isStreamRequested(stats) && isStreamLive(stats))) {
|
|
18615
18642
|
result.streams.push(this.buildMqeIntervalStreamTransmitVideo(key));
|
|
18616
18643
|
}
|
|
18617
18644
|
});
|