@webex/internal-media-core 2.2.1 → 2.2.3
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 +56 -25
- package/dist/esm/index.js +56 -25
- package/package.json +2 -2
package/dist/esm/index.js
CHANGED
|
@@ -2795,7 +2795,7 @@ return devices.filter(device=>deviceKinds.includes(device.kind)).every(device=>d
|
|
|
2795
2795
|
// (Firefox) will allow the user to access device information.
|
|
2796
2796
|
var callbackRes=yield callback();// Stop tracks in the stream so the browser (Safari) will know that there is not an active
|
|
2797
2797
|
// stream running.
|
|
2798
|
-
stream.getTracks().forEach(track=>track.stop());return callbackRes;}return callback();}catch(e){logger$3.error(e);throw new Error('Failed to ensure device permissions.');}});}var media=/*#__PURE__*/Object.freeze({__proto__:null,get DeviceKind(){return DeviceKind;},getUserMedia:getUserMedia,getDisplayMedia:getDisplayMedia,enumerateDevices:enumerateDevices,setOnDeviceChangeHandler:setOnDeviceChangeHandler$1,checkDevicePermissions:checkDevicePermissions,ensureDevicePermissions:ensureDevicePermissions});var WebrtcCoreErrorType;(function(WebrtcCoreErrorType){WebrtcCoreErrorType["DEVICE_PERMISSION_DENIED"]="DEVICE_PERMISSION_DENIED";WebrtcCoreErrorType["CREATE_STREAM_FAILED"]="CREATE_STREAM_FAILED";})(WebrtcCoreErrorType||(WebrtcCoreErrorType={}));/**
|
|
2798
|
+
stream.getTracks().forEach(track=>track.stop());return callbackRes;}return callback();}catch(e){logger$3.error(e);throw new Error('Failed to ensure device permissions.');}});}var media=/*#__PURE__*/Object.freeze({__proto__:null,get DeviceKind(){return DeviceKind;},getUserMedia:getUserMedia,getDisplayMedia:getDisplayMedia,enumerateDevices:enumerateDevices,setOnDeviceChangeHandler:setOnDeviceChangeHandler$1,checkDevicePermissions:checkDevicePermissions,ensureDevicePermissions:ensureDevicePermissions});var WebrtcCoreErrorType;(function(WebrtcCoreErrorType){WebrtcCoreErrorType["DEVICE_PERMISSION_DENIED"]="DEVICE_PERMISSION_DENIED";WebrtcCoreErrorType["CREATE_STREAM_FAILED"]="CREATE_STREAM_FAILED";WebrtcCoreErrorType["ADD_EFFECT_FAILED"]="ADD_EFFECT_FAILED";})(WebrtcCoreErrorType||(WebrtcCoreErrorType={}));/**
|
|
2799
2799
|
* Represents a WebRTC core error, which contains error type and error message.
|
|
2800
2800
|
*/class WebrtcCoreError{/**
|
|
2801
2801
|
* Creates new error.
|
|
@@ -2912,25 +2912,32 @@ this[_a$1$1]=new TypedEvent$1();this[_b$1]=new TypedEvent$1();this.outputStream=
|
|
|
2912
2912
|
* Get the track of the output stream.
|
|
2913
2913
|
*
|
|
2914
2914
|
* @returns The output track.
|
|
2915
|
-
*/get outputTrack(){return this.outputStream.getTracks()[0];}}_a$1$1=StreamEventNames.MuteStateChange,_b$1=StreamEventNames.Ended;var Stream=AddEvents(_Stream);var _a$6$1,_b;var LocalStreamEventNames;(function(LocalStreamEventNames){LocalStreamEventNames["ConstraintsChange"]="constraints-change";LocalStreamEventNames["OutputTrackChange"]="output-track-change";})(LocalStreamEventNames||(LocalStreamEventNames={}));/**
|
|
2915
|
+
*/get outputTrack(){return this.outputStream.getTracks()[0];}}_a$1$1=StreamEventNames.MuteStateChange,_b$1=StreamEventNames.Ended;var Stream=AddEvents(_Stream);var _a$6$1,_b,_c;var LocalStreamEventNames;(function(LocalStreamEventNames){LocalStreamEventNames["ConstraintsChange"]="constraints-change";LocalStreamEventNames["OutputTrackChange"]="output-track-change";LocalStreamEventNames["EffectAdded"]="effect-added";})(LocalStreamEventNames||(LocalStreamEventNames={}));/**
|
|
2916
2916
|
* A stream which originates on the local device.
|
|
2917
2917
|
*/class _LocalStream extends Stream{/**
|
|
2918
2918
|
* Create a LocalStream from the given values.
|
|
2919
2919
|
*
|
|
2920
2920
|
* @param stream - The initial output MediaStream for this Stream.
|
|
2921
|
-
*/constructor(stream){super(stream);this[_a$6$1]=new TypedEvent$1();this[_b]=new TypedEvent$1();this.effects=[];this.loadingEffects=new Map();this.inputStream=stream;}/**
|
|
2921
|
+
*/constructor(stream){super(stream);this[_a$6$1]=new TypedEvent$1();this[_b]=new TypedEvent$1();this[_c]=new TypedEvent$1();this.effects=[];this.loadingEffects=new Map();this.inputStream=stream;}/**
|
|
2922
2922
|
* Get the track within the MediaStream with which this LocalStream was created.
|
|
2923
2923
|
*
|
|
2924
2924
|
* @returns The track within the MediaStream with which this LocalStream
|
|
2925
2925
|
* was created.
|
|
2926
2926
|
*/get inputTrack(){return this.inputStream.getTracks()[0];}/**
|
|
2927
2927
|
* @inheritdoc
|
|
2928
|
-
*/
|
|
2928
|
+
*/handleTrackMuted(){if(this.inputTrack.enabled){super.handleTrackMuted();}}/**
|
|
2929
|
+
* @inheritdoc
|
|
2930
|
+
*/handleTrackUnmuted(){if(this.inputTrack.enabled){super.handleTrackUnmuted();}}/**
|
|
2931
|
+
* @inheritdoc
|
|
2932
|
+
*/get muted(){// Calls to `setMuted` will only affect the "enabled" state, but there are specific cases in
|
|
2933
|
+
// which the browser may mute the track, which will affect the "muted" state but not the
|
|
2934
|
+
// "enabled" state, e.g. minimizing a shared window or unplugging a shared screen.
|
|
2935
|
+
return !this.inputTrack.enabled||this.inputTrack.muted;}/**
|
|
2929
2936
|
* Set the mute state of this stream.
|
|
2930
2937
|
*
|
|
2931
2938
|
* @param isMuted - True to mute, false to unmute.
|
|
2932
2939
|
*/setMuted(isMuted){if(this.inputTrack.enabled===isMuted){this.inputTrack.enabled=!isMuted;// setting `enabled` will not automatically emit MuteStateChange, so we emit it here
|
|
2933
|
-
this[StreamEventNames.MuteStateChange].emit(isMuted);}}/**
|
|
2940
|
+
if(!this.inputTrack.muted){this[StreamEventNames.MuteStateChange].emit(isMuted);}}}/**
|
|
2934
2941
|
* @inheritdoc
|
|
2935
2942
|
*/getSettings(){return this.inputTrack.getSettings();}/**
|
|
2936
2943
|
* Get the label of the input track on this stream.
|
|
@@ -2958,28 +2965,52 @@ if(this.inputTrack.id===this.outputTrack.id){this.inputStream=this.outputStream;
|
|
|
2958
2965
|
this[StreamEventNames.Ended].emit();}/**
|
|
2959
2966
|
* Adds an effect to a local stream.
|
|
2960
2967
|
*
|
|
2961
|
-
* @param name - The name of the effect.
|
|
2962
2968
|
* @param effect - The effect to add.
|
|
2963
|
-
*/addEffect(
|
|
2964
|
-
this.
|
|
2965
|
-
|
|
2966
|
-
this
|
|
2967
|
-
//
|
|
2968
|
-
//
|
|
2969
|
-
|
|
2970
|
-
effect
|
|
2971
|
-
|
|
2969
|
+
*/addEffect(effect){return __awaiter$2(this,void 0,void 0,function*(){// Check if the effect has already been added.
|
|
2970
|
+
if(this.effects.some(e=>e.id===effect.id)){return;}// Load the effect. Because loading is asynchronous, keep track of the loading effects.
|
|
2971
|
+
this.loadingEffects.set(effect.kind,effect);yield effect.load(this.outputTrack);// After loading, check whether or not we still want to use this effect. If another effect of
|
|
2972
|
+
// the same kind was added while this effect was loading, we only want to use the latest effect,
|
|
2973
|
+
// so dispose this one. If the effects list was cleared while this effect was loading, also
|
|
2974
|
+
// dispose it.
|
|
2975
|
+
if(effect!==this.loadingEffects.get(effect.kind)){yield effect.dispose();throw new WebrtcCoreError(WebrtcCoreErrorType.ADD_EFFECT_FAILED,"Another effect with kind ".concat(effect.kind," was added while effect ").concat(effect.id," was loading, or the effects list was cleared."));}this.loadingEffects.delete(effect.kind);/**
|
|
2976
|
+
* Handle when the effect's output track has been changed. This will update the input of the
|
|
2977
|
+
* next effect in the effects list of the output of the stream.
|
|
2978
|
+
*
|
|
2979
|
+
* @param track - The new output track of the effect.
|
|
2980
|
+
*/var handleEffectTrackUpdated=track=>{var _d;var effectIndex=this.effects.findIndex(e=>e.id===effect.id);if(effectIndex===this.effects.length-1){this.changeOutputTrack(track);}else if(effectIndex>=0){(_d=this.effects[effectIndex+1])===null||_d===void 0?void 0:_d.replaceInputTrack(track);}else {logger$3.error("Effect with ID ".concat(effect.id," not found in effects list."));}};/**
|
|
2981
|
+
* Handle when the effect has been disposed. This will remove all event listeners from the
|
|
2982
|
+
* effect.
|
|
2983
|
+
*/var handleEffectDisposed=()=>{effect.off('track-updated',handleEffectTrackUpdated);effect.off('disposed',handleEffectDisposed);};// TODO: using EffectEvent.TrackUpdated or EffectEvent.Disposed will cause the entire
|
|
2984
|
+
// web-media-effects lib to be rebuilt and inflates the size of the webrtc-core build, so
|
|
2985
|
+
// we use type assertion here as a temporary workaround.
|
|
2986
|
+
effect.on('track-updated',handleEffectTrackUpdated);effect.on('disposed',handleEffectDisposed);// Add the effect to the effects list. If an effect of the same kind has already been added,
|
|
2987
|
+
// dispose the existing effect and replace it with the new effect. If the existing effect was
|
|
2988
|
+
// enabled, also enable the new effect.
|
|
2989
|
+
var existingEffectIndex=this.effects.findIndex(e=>e.kind===effect.kind);if(existingEffectIndex>=0){var[existingEffect]=this.effects.splice(existingEffectIndex,1,effect);if(existingEffect.isEnabled){// If the existing effect is not the first effect in the effects list, then the input of the
|
|
2990
|
+
// new effect should be the output of the previous effect in the effects list. We know the
|
|
2991
|
+
// output track of the previous effect must exist because it must have been loaded (and all
|
|
2992
|
+
// loaded effects have an output track).
|
|
2993
|
+
var inputTrack=existingEffectIndex===0?this.inputTrack:this.effects[existingEffectIndex-1].getOutputTrack();yield effect.replaceInputTrack(inputTrack);// Enabling the new effect will trigger the track-updated event, which will handle the new
|
|
2994
|
+
// effect's updated output track.
|
|
2995
|
+
yield effect.enable();}yield existingEffect.dispose();}else {this.effects.push(effect);}// Emit an event with the effect so others can listen to the effect events.
|
|
2996
|
+
this[LocalStreamEventNames.EffectAdded].emit(effect);});}/**
|
|
2997
|
+
* Get an effect from the effects list by ID.
|
|
2998
|
+
*
|
|
2999
|
+
* @param id - The id of the effect you want to get.
|
|
3000
|
+
* @returns The effect or undefined.
|
|
3001
|
+
*/getEffectById(id){return this.effects.find(effect=>effect.id===id);}/**
|
|
3002
|
+
* Get an effect from the effects list by kind.
|
|
2972
3003
|
*
|
|
2973
|
-
* @param
|
|
3004
|
+
* @param kind - The kind of the effect you want to get.
|
|
2974
3005
|
* @returns The effect or undefined.
|
|
2975
|
-
*/
|
|
3006
|
+
*/getEffectByKind(kind){return this.effects.find(effect=>effect.kind===kind);}/**
|
|
2976
3007
|
* Get all the effects from the effects list.
|
|
2977
3008
|
*
|
|
2978
|
-
* @returns A list of
|
|
2979
|
-
*/
|
|
3009
|
+
* @returns A list of effects.
|
|
3010
|
+
*/getEffects(){return this.effects;}/**
|
|
2980
3011
|
* Cleanup the local effects.
|
|
2981
3012
|
*/disposeEffects(){return __awaiter$2(this,void 0,void 0,function*(){this.loadingEffects.clear();// Dispose of any effects currently in use
|
|
2982
|
-
if(this.effects.length>0){this.changeOutputTrack(this.inputTrack);yield Promise.all(this.effects.map(
|
|
3013
|
+
if(this.effects.length>0){this.changeOutputTrack(this.inputTrack);yield Promise.all(this.effects.map(effect=>effect.dispose()));this.effects=[];}});}}_a$6$1=LocalStreamEventNames.ConstraintsChange,_b=LocalStreamEventNames.OutputTrackChange,_c=LocalStreamEventNames.EffectAdded;var LocalStream=AddEvents(_LocalStream);/**
|
|
2983
3014
|
* An audio LocalStream.
|
|
2984
3015
|
*/class LocalAudioStream extends LocalStream{/**
|
|
2985
3016
|
* Apply constraints to the stream.
|
|
@@ -3663,7 +3694,7 @@ if(context.level===Logger.WARN&&console.warn){hdlr=console.warn;}else if(context
|
|
|
3663
3694
|
// `options` hash can be used to configure the default logLevel and provide a custom message formatter.
|
|
3664
3695
|
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.
|
|
3665
3696
|
Logger.setDefaults=Logger.useDefaults;// Export to popular environments boilerplate.
|
|
3666
|
-
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,"] "));}});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 areNamedMediaGroupArraysEqual(left,right){if(left===undefined||right===undefined){return left===right;}if(left.length!==right.length){return false;}for(var i=0;i<left.length;i+=1){if(left[i]!==right[i]){return false;}}return true;}function areActiveSpeakerInfosEqual(left,right){return left.priority===right.priority&&left.crossPriorityDuplication===right.crossPriorityDuplication&&left.crossPolicyDuplication===right.crossPolicyDuplication&&left.preferLiveVideo===right.preferLiveVideo&&areNamedMediaGroupArraysEqual(left.namedMediaGroups,right.namedMediaGroups);}function isValidActiveSpeakerNotificationMsg(msg){var maybeActiveSpeakerNotificationMsg=msg;return Boolean(maybeActiveSpeakerNotificationMsg.seqNum&&maybeActiveSpeakerNotificationMsg.csis);}var HomerMsgType;(function(HomerMsgType){HomerMsgType["Multistream"]="multistream";})(HomerMsgType||(HomerMsgType={}));class HomerMsg{constructor(msgType,payload){this.msgType=msgType;this.payload=payload;}static fromJson(data){if(!data.msgType||!data.payload){return null;}return new HomerMsg(data.msgType,data.payload);}}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 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 MediaRequestAckMsg{constructor(mediaRequestSeqNum){this.mediaRequestSeqNum=mediaRequestSeqNum;}toString(){return "MediaRequestAckMsg(seqNum=".concat(this.mediaRequestSeqNum,")");}}function isValidMediaRequestAckMsg(msg){var maybeMediaRequestAckMsg=msg;return Boolean(maybeMediaRequestAckMsg.mediaRequestSeqNum);}function isValidStreamId(obj){var maybeStreamId=obj;if(maybeStreamId.mid&&maybeStreamId.ssrc){return false;}return Boolean(maybeStreamId.mid)||Boolean(maybeStreamId.ssrc);}function compareStreamIds(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'].includes(maybeStreamInfo.state));}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));}function compareStreamStateArrays(streamStates1,streamStates2){var _a,_b;if(streamStates1.length!==streamStates2.length){return false;}for(var i=0;i<streamStates1.length;i+=1){if(!compareStreamIds(streamStates1[i].id,streamStates2[i].id)){return false;}if(streamStates1[i].state!==streamStates2[i].state){return false;}if(((_a=streamStates1[i])===null||_a===void 0?void 0:_a.csi)!==((_b=streamStates2[i])===null||_b===void 0?void 0:_b.csi)){return false;}}return true;}class MediaRequestStatusAckMsg{constructor(mediaRequestStatusSeqNum){this.mediaRequestStatusSeqNum=mediaRequestStatusSeqNum;}toString(){return "MediaRequestStatusAckMsg(seqNum=".concat(this.mediaRequestStatusSeqNum,")");}}function isValidMediaRequestStatusAckMsg(msg){var maybeMediaRequestStatusAckMsg=msg;return Boolean(maybeMediaRequestStatusAckMsg.mediaRequestStatusSeqNum);}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);}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;}var MediaFamily;(function(MediaFamily){MediaFamily["Audio"]="AUDIO";MediaFamily["Video"]="VIDEO";})(MediaFamily||(MediaFamily={}));var MediaContent;(function(MediaContent){MediaContent["Main"]="MAIN";MediaContent["Slides"]="SLIDES";})(MediaContent||(MediaContent={}));var Policy;(function(Policy){Policy["ActiveSpeaker"]="active-speaker";Policy["ReceiverSelected"]="receiver-selected";})(Policy||(Policy={}));var MediaType;(function(MediaType){MediaType["VideoMain"]="VIDEO-MAIN";MediaType["VideoSlides"]="VIDEO-SLIDES";MediaType["AudioMain"]="AUDIO-MAIN";MediaType["AudioSlides"]="AUDIO-SLIDES";})(MediaType||(MediaType={}));function randomInteger(min,max){return Math.floor(Math.random()*(max-min+1))+min;}function generateSceneId(){return randomInteger(0,0x7fffff);}function generateCsi(mediaFamily,sceneId){var av;if(mediaFamily===MediaFamily.Audio){av=0;}else {av=1;}return sceneId<<8|av;}function getMediaType(mediaFamily,mediaContent){if(mediaFamily===MediaFamily.Video&&mediaContent===MediaContent.Main){return MediaType.VideoMain;}if(mediaFamily===MediaFamily.Video&&mediaContent===MediaContent.Slides){return MediaType.VideoSlides;}if(mediaFamily===MediaFamily.Audio&&mediaContent===MediaContent.Main){return MediaType.AudioMain;}return MediaType.AudioSlides;}function getMediaFamily(mediaType){return [MediaType.VideoMain,MediaType.VideoSlides].includes(mediaType)?MediaFamily.Video:MediaFamily.Audio;}function getMediaContent(mediaType){return [MediaType.VideoMain,MediaType.AudioMain].includes(mediaType)?MediaContent.Main:MediaContent.Slides;}var truthyOrZero=value=>value===0||value;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&&truthyOrZero(maybeSourceAdvertisementMsg.numTotalSources)&&truthyOrZero(maybeSourceAdvertisementMsg.numLiveSources));}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 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 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');}function areCodecInfoArraysEqual(left,right){if(left.length!==right.length){return false;}for(var i=0;i<left.length;i+=1){if(!areCodecInfosEqual(left[i],right[i])){return false;}}return true;}function areStreamIdArraysEqual(left,right){if(left.length!==right.length){return false;}for(var i=0;i<left.length;i+=1){if(!compareStreamIds(left[i],right[i])){return false;}}return true;}function areStreamRequestsEqual(left,right){if(left.policy!==right.policy){return false;}if(!arePolicySpecificInfosEqual(left.policySpecificInfo,right.policySpecificInfo)){return false;}if(!areStreamIdArraysEqual(left.ids,right.ids)){return false;}if(left.maxPayloadBitsPerSecond!==right.maxPayloadBitsPerSecond){return false;}if(!areCodecInfoArraysEqual(left.codecInfos,right.codecInfos)){return false;}return true;}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={}));function areStreamRequestArraysEqual(left,right){if(left.length!==right.length){return false;}for(var i=0;i<left.length;i+=1){if(!areStreamRequestsEqual(left[i],right[i])){return false;}}return true;}class JmpSession extends EventEmitter$6{constructor(mediaFamily,mediaContent){var maxNumRetransmits=arguments.length>2&&arguments[2]!==undefined?arguments[2]:3;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||!areStreamRequestArraysEqual(this.lastSentMediaRequest.msg.requests,requests)){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.sendJmpMsg(JmpMsgType.MediaRequest,mediaRequestMsg),expiredJmpMsg=>{this.logger.warn("Retransmits for message expired: ".concat(expiredJmpMsg));});this.currMediaRequestSeqNum++;}}sendSourceAdvertisement(numTotalSources,numLiveSources,namedMediaGroups,videoContentHint){var sourceAdvertisementMsg=new SourceAdvertisementMsg(this.currSourceAdvertisementSeqNum++,numTotalSources,numLiveSources,namedMediaGroups,videoContentHint);this.sendJmpMsg(JmpMsgType.SourceAdvertisement,sourceAdvertisementMsg);this.lastSentSourceAdvertisement=new RetransmitHandler(sourceAdvertisementMsg,this.maxNumRetransmits,this.retransmitIntervalMs,()=>this.sendJmpMsg(JmpMsgType.SourceAdvertisement,sourceAdvertisementMsg),expiredMsg=>{this.logger.warn("Retransmits for message expired: ",expiredMsg);});}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=>compareStreamIds(streamId,streamState.id)));});var mediaRequestStatus=new MediaRequestStatusMsg(this.currMediaRequestStatusSeqNum,filteredStreamStates);if(!((_a=this.lastSentMediaRequestStatus)===null||_a===void 0?void 0:_a.msg.streamStates)||!compareStreamStateArrays(filteredStreamStates,this.lastSentMediaRequestStatus.msg.streamStates)){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.sendJmpMsg(JmpMsgType.MediaRequestStatus,mediaRequestStatus),expiredMsg=>{this.logger.warn("Retransmits for message expired: ",expiredMsg);});this.currMediaRequestStatusSeqNum++;}}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;this.logger.info("closing");(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.cancel();}sendJmpMsg(msgType,payload){var _a;var jmpMsg=new JmpMsg(this.mediaFamily,this.mediaContent,{msgType,payload});var homerMsg=new HomerMsg(HomerMsgType.Multistream,jmpMsg);(_a=this.txCallback)===null||_a===void 0?void 0:_a.call(this,JSON.stringify(homerMsg));}handleIncomingMediaRequest(mediaRequestMsg){var _a;if(this.lastReceivedMediaRequest&&mediaRequestMsg.seqNum<((_a=this.lastReceivedMediaRequest)===null||_a===void 0?void 0:_a.seqNum)){this.logger.info("Received old MediaRequest, ignoring");}else if(this.lastReceivedMediaRequest&&mediaRequestMsg.seqNum===this.lastReceivedMediaRequest.seqNum){if(this.lastSentMediaRequestAck){this.logger.info("Received duplicate MediaRequest, re-sending ACK");this.sendJmpMsg(JmpMsgType.MediaRequestAck,this.lastSentMediaRequestAck);}else {this.logger.warn("Received duplicate MediaRequest, but there was no ACK previously sent");}}else {this.logger.info("Received new MediaRequest, sending ACK");var mediaRequestAck=new MediaRequestAckMsg(mediaRequestMsg.seqNum);this.lastReceivedMediaRequest=mediaRequestMsg;this.lastSentMediaRequestAck=mediaRequestAck;this.sendJmpMsg(JmpMsgType.MediaRequestAck,mediaRequestAck);this.emit(JmpSessionEvents.MediaRequestReceived,mediaRequestMsg);}}handleIncomingMediaRequestAck(mediaRequestAckMsg){var _a,_b,_c;if(mediaRequestAckMsg.mediaRequestSeqNum===((_b=(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent MediaRequest");(_c=this.lastSentMediaRequest)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old MediaRequest");}}handleIncomingActiveSpeakerNotification(activeSpeakerNotification){this.logger.debug("Received Active Speaker Notification:",activeSpeakerNotification);this.emit(JmpSessionEvents.ActiveSpeaker,activeSpeakerNotification);}handleIncomingSourceAdvertisement(sourceAdvertisement){if(this.lastReceivedSourceAdvertisement&&sourceAdvertisement.seqNum<this.lastReceivedSourceAdvertisement.seqNum){this.logger.info("Received old SourceAdvertisement, ignoring");}else if(this.lastReceivedSourceAdvertisement&&sourceAdvertisement.seqNum===this.lastReceivedSourceAdvertisement.seqNum){if(this.lastSentSourceAdvertisementAck){this.logger.info("Received duplicate SourceAdvertisement, re-sending ACK");this.sendJmpMsg(JmpMsgType.SourceAdvertisementAck,this.lastSentSourceAdvertisementAck);}else {this.logger.warn("Received duplicate SourceAdvertisement, but there was no ACK previously sent");}}else {this.logger.info("Received new SourceAdvertisement, sending ACK");var sourceAdvertisementAck=new SourceAdvertisementAckMsg(sourceAdvertisement.seqNum);this.lastReceivedSourceAdvertisement=sourceAdvertisement;this.lastSentSourceAdvertisementAck=sourceAdvertisementAck;this.sendJmpMsg(JmpMsgType.SourceAdvertisementAck,sourceAdvertisementAck);this.emit(JmpSessionEvents.SourceAdvertisementReceived,sourceAdvertisement);}}handleIncomingSourceAdvertisementAck(sourceAdvertisementAck){var _a,_b,_c;if(sourceAdvertisementAck.sourceAdvertisementSeqNum===((_b=(_a=this.lastSentSourceAdvertisement)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent SourceAdvertisement");(_c=this.lastSentSourceAdvertisement)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old SourceAdvertisement");}}handleIncomingMediaRequestStatus(mediaRequestStatus){if(this.lastReceivedMediaRequestStatus&&mediaRequestStatus.seqNum<this.lastReceivedMediaRequestStatus.seqNum){this.logger.info("Received old MediaRequestStatus, ignoring");}else if(this.lastReceivedMediaRequestStatus&&mediaRequestStatus.seqNum===this.lastReceivedMediaRequestStatus.seqNum){if(this.lastSentMediaRequestStatusAck){this.logger.info("Received duplicate MediaRequestStatus, re-sending ACK");this.sendJmpMsg(JmpMsgType.MediaRequestStatusAck,this.lastSentMediaRequestStatusAck);}else {this.logger.warn("Received duplicate MediaRequestStatus, but there was no ACK previously sent");}}else {this.logger.info("Received new MediaRequestStatus, sending ACK");var mediaRequestStatusAck=new MediaRequestStatusAckMsg(mediaRequestStatus.seqNum);this.lastReceivedMediaRequestStatus=mediaRequestStatus;this.lastSentMediaRequestStatusAck=mediaRequestStatusAck;this.sendJmpMsg(JmpMsgType.MediaRequestStatusAck,mediaRequestStatusAck);this.emit(JmpSessionEvents.MediaRequestStatusReceived,mediaRequestStatus);}}handleIncomingMediaRequestStatusAck(mediaRequestStatusAck){var _a,_b,_c;if(mediaRequestStatusAck.mediaRequestStatusSeqNum===((_b=(_a=this.lastSentMediaRequestStatus)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent MediaRequestStatus");(_c=this.lastSentMediaRequestStatus)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old MediaRequestStatus");}}}var commonjsGlobal$1=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global$1!=='undefined'?global$1:typeof self!=='undefined'?self:{};var logger$1={exports:{}};/*!
|
|
3697
|
+
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,"] "));}});var MediaFamily;(function(MediaFamily){MediaFamily["Audio"]="AUDIO";MediaFamily["Video"]="VIDEO";})(MediaFamily||(MediaFamily={}));var MediaContent;(function(MediaContent){MediaContent["Main"]="MAIN";MediaContent["Slides"]="SLIDES";})(MediaContent||(MediaContent={}));var Policy;(function(Policy){Policy["ActiveSpeaker"]="active-speaker";Policy["ReceiverSelected"]="receiver-selected";})(Policy||(Policy={}));var MediaType;(function(MediaType){MediaType["VideoMain"]="VIDEO-MAIN";MediaType["VideoSlides"]="VIDEO-SLIDES";MediaType["AudioMain"]="AUDIO-MAIN";MediaType["AudioSlides"]="AUDIO-SLIDES";})(MediaType||(MediaType={}));function randomInteger(min,max){return Math.floor(Math.random()*(max-min+1))+min;}function generateSceneId(){return randomInteger(0,0x7fffff);}function generateCsi(mediaFamily,sceneId){var av;if(mediaFamily===MediaFamily.Audio){av=0;}else {av=1;}return sceneId<<8|av;}function getMediaType(mediaFamily,mediaContent){if(mediaFamily===MediaFamily.Video&&mediaContent===MediaContent.Main){return MediaType.VideoMain;}if(mediaFamily===MediaFamily.Video&&mediaContent===MediaContent.Slides){return MediaType.VideoSlides;}if(mediaFamily===MediaFamily.Audio&&mediaContent===MediaContent.Main){return MediaType.AudioMain;}return MediaType.AudioSlides;}function getMediaFamily(mediaType){return [MediaType.VideoMain,MediaType.VideoSlides].includes(mediaType)?MediaFamily.Video:MediaFamily.Audio;}function getMediaContent(mediaType){return [MediaType.VideoMain,MediaType.AudioMain].includes(mediaType)?MediaContent.Main:MediaContent.Slides;}var truthyOrZero=value=>value===0||value;function arraysAreEqual(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 areNamedMediaGroupArraysEqual(left,right){if(left===undefined||right===undefined){return left===right;}return arraysAreEqual(left,right,(l,r)=>l.type===r.type&&l.value===r.value);}function areActiveSpeakerInfosEqual(left,right){return left.priority===right.priority&&left.crossPriorityDuplication===right.crossPriorityDuplication&&left.crossPolicyDuplication===right.crossPolicyDuplication&&left.preferLiveVideo===right.preferLiveVideo&&areNamedMediaGroupArraysEqual(left.namedMediaGroups,right.namedMediaGroups);}function isValidActiveSpeakerNotificationMsg(msg){var maybeActiveSpeakerNotificationMsg=msg;return Boolean(maybeActiveSpeakerNotificationMsg.seqNum&&maybeActiveSpeakerNotificationMsg.csis);}var HomerMsgType;(function(HomerMsgType){HomerMsgType["Multistream"]="multistream";})(HomerMsgType||(HomerMsgType={}));class HomerMsg{constructor(msgType,payload){this.msgType=msgType;this.payload=payload;}static fromJson(data){if(!data.msgType||!data.payload){return null;}return new HomerMsg(data.msgType,data.payload);}}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 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 MediaRequestAckMsg{constructor(mediaRequestSeqNum){this.mediaRequestSeqNum=mediaRequestSeqNum;}toString(){return "MediaRequestAckMsg(seqNum=".concat(this.mediaRequestSeqNum,")");}}function isValidMediaRequestAckMsg(msg){var maybeMediaRequestAckMsg=msg;return Boolean(maybeMediaRequestAckMsg.mediaRequestSeqNum);}function isValidStreamId(obj){var maybeStreamId=obj;if(maybeStreamId.mid&&maybeStreamId.ssrc){return false;}return Boolean(maybeStreamId.mid)||Boolean(maybeStreamId.ssrc);}function compareStreamIds(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'].includes(maybeStreamInfo.state));}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));}function compareStreamStateArrays(streamStates1,streamStates2){var _a,_b;if(streamStates1.length!==streamStates2.length){return false;}for(var i=0;i<streamStates1.length;i+=1){if(!compareStreamIds(streamStates1[i].id,streamStates2[i].id)){return false;}if(streamStates1[i].state!==streamStates2[i].state){return false;}if(((_a=streamStates1[i])===null||_a===void 0?void 0:_a.csi)!==((_b=streamStates2[i])===null||_b===void 0?void 0:_b.csi)){return false;}}return true;}class MediaRequestStatusAckMsg{constructor(mediaRequestStatusSeqNum){this.mediaRequestStatusSeqNum=mediaRequestStatusSeqNum;}toString(){return "MediaRequestStatusAckMsg(seqNum=".concat(this.mediaRequestStatusSeqNum,")");}}function isValidMediaRequestStatusAckMsg(msg){var maybeMediaRequestStatusAckMsg=msg;return Boolean(maybeMediaRequestStatusAckMsg.mediaRequestStatusSeqNum);}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);}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;}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&&truthyOrZero(maybeSourceAdvertisementMsg.numTotalSources)&&truthyOrZero(maybeSourceAdvertisementMsg.numLiveSources));}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 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 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');}function areCodecInfoArraysEqual(left,right){return arraysAreEqual(left,right,areCodecInfosEqual);}function areStreamIdArraysEqual(left,right){return arraysAreEqual(left,right,compareStreamIds);}function areStreamRequestsEqual(left,right){if(left.policy!==right.policy){return false;}if(!arePolicySpecificInfosEqual(left.policySpecificInfo,right.policySpecificInfo)){return false;}if(!areStreamIdArraysEqual(left.ids,right.ids)){return false;}if(left.maxPayloadBitsPerSecond!==right.maxPayloadBitsPerSecond){return false;}if(!areCodecInfoArraysEqual(left.codecInfos,right.codecInfos)){return false;}return true;}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={}));function areStreamRequestArraysEqual(left,right){if(left.length!==right.length){return false;}for(var i=0;i<left.length;i+=1){if(!areStreamRequestsEqual(left[i],right[i])){return false;}}return true;}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||!areStreamRequestArraysEqual(this.lastSentMediaRequest.msg.requests,requests)){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 sourceAdvertisementMsg=new SourceAdvertisementMsg(this.currSourceAdvertisementSeqNum++,numTotalSources,numLiveSources,namedMediaGroups,videoContentHint);this.sendJmpMsg(JmpMsgType.SourceAdvertisement,sourceAdvertisementMsg);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);});}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=>compareStreamIds(streamId,streamState.id)));});var mediaRequestStatus=new MediaRequestStatusMsg(this.currMediaRequestStatusSeqNum,filteredStreamStates);if(!((_a=this.lastSentMediaRequestStatus)===null||_a===void 0?void 0:_a.msg.streamStates)||!compareStreamStateArrays(filteredStreamStates,this.lastSentMediaRequestStatus.msg.streamStates)){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;this.logger.info("closing");(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.cancel();}sendJmpMsg(msgType,payload){var _a;var jmpMsg=new JmpMsg(this.mediaFamily,this.mediaContent,{msgType,payload});var homerMsg=new HomerMsg(HomerMsgType.Multistream,jmpMsg);(_a=this.txCallback)===null||_a===void 0?void 0:_a.call(this,JSON.stringify(homerMsg));}handleIncomingMediaRequest(mediaRequestMsg){var _a;if(this.lastReceivedMediaRequest&&mediaRequestMsg.seqNum<((_a=this.lastReceivedMediaRequest)===null||_a===void 0?void 0:_a.seqNum)){this.logger.info("Received old MediaRequest, ignoring");}else if(this.lastReceivedMediaRequest&&mediaRequestMsg.seqNum===this.lastReceivedMediaRequest.seqNum){if(this.lastSentMediaRequestAck){this.logger.info("Received duplicate MediaRequest, re-sending ACK");this.sendJmpMsg(JmpMsgType.MediaRequestAck,this.lastSentMediaRequestAck);}else {this.logger.warn("Received duplicate MediaRequest, but there was no ACK previously sent");}}else {this.logger.info("Received new MediaRequest, sending ACK");var mediaRequestAck=new MediaRequestAckMsg(mediaRequestMsg.seqNum);this.lastReceivedMediaRequest=mediaRequestMsg;this.lastSentMediaRequestAck=mediaRequestAck;this.sendJmpMsg(JmpMsgType.MediaRequestAck,mediaRequestAck);this.emit(JmpSessionEvents.MediaRequestReceived,mediaRequestMsg);}}handleIncomingMediaRequestAck(mediaRequestAckMsg){var _a,_b,_c;if(mediaRequestAckMsg.mediaRequestSeqNum===((_b=(_a=this.lastSentMediaRequest)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent MediaRequest");(_c=this.lastSentMediaRequest)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old MediaRequest");}}handleIncomingActiveSpeakerNotification(activeSpeakerNotification){this.logger.debug("Received Active Speaker Notification:",activeSpeakerNotification);this.emit(JmpSessionEvents.ActiveSpeaker,activeSpeakerNotification);}handleIncomingSourceAdvertisement(sourceAdvertisement){if(this.lastReceivedSourceAdvertisement&&sourceAdvertisement.seqNum<this.lastReceivedSourceAdvertisement.seqNum){this.logger.info("Received old SourceAdvertisement, ignoring");}else if(this.lastReceivedSourceAdvertisement&&sourceAdvertisement.seqNum===this.lastReceivedSourceAdvertisement.seqNum){if(this.lastSentSourceAdvertisementAck){this.logger.info("Received duplicate SourceAdvertisement, re-sending ACK");this.sendJmpMsg(JmpMsgType.SourceAdvertisementAck,this.lastSentSourceAdvertisementAck);}else {this.logger.warn("Received duplicate SourceAdvertisement, but there was no ACK previously sent");}}else {this.logger.info("Received new SourceAdvertisement, sending ACK");var sourceAdvertisementAck=new SourceAdvertisementAckMsg(sourceAdvertisement.seqNum);this.lastReceivedSourceAdvertisement=sourceAdvertisement;this.lastSentSourceAdvertisementAck=sourceAdvertisementAck;this.sendJmpMsg(JmpMsgType.SourceAdvertisementAck,sourceAdvertisementAck);this.emit(JmpSessionEvents.SourceAdvertisementReceived,sourceAdvertisement);}}handleIncomingSourceAdvertisementAck(sourceAdvertisementAck){var _a,_b,_c;if(sourceAdvertisementAck.sourceAdvertisementSeqNum===((_b=(_a=this.lastSentSourceAdvertisement)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent SourceAdvertisement");(_c=this.lastSentSourceAdvertisement)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old SourceAdvertisement");}}handleIncomingMediaRequestStatus(mediaRequestStatus){if(this.lastReceivedMediaRequestStatus&&mediaRequestStatus.seqNum<this.lastReceivedMediaRequestStatus.seqNum){this.logger.info("Received old MediaRequestStatus, ignoring");}else if(this.lastReceivedMediaRequestStatus&&mediaRequestStatus.seqNum===this.lastReceivedMediaRequestStatus.seqNum){if(this.lastSentMediaRequestStatusAck){this.logger.info("Received duplicate MediaRequestStatus, re-sending ACK");this.sendJmpMsg(JmpMsgType.MediaRequestStatusAck,this.lastSentMediaRequestStatusAck);}else {this.logger.warn("Received duplicate MediaRequestStatus, but there was no ACK previously sent");}}else {this.logger.info("Received new MediaRequestStatus, sending ACK");var mediaRequestStatusAck=new MediaRequestStatusAckMsg(mediaRequestStatus.seqNum);this.lastReceivedMediaRequestStatus=mediaRequestStatus;this.lastSentMediaRequestStatusAck=mediaRequestStatusAck;this.sendJmpMsg(JmpMsgType.MediaRequestStatusAck,mediaRequestStatusAck);this.emit(JmpSessionEvents.MediaRequestStatusReceived,mediaRequestStatus);}}handleIncomingMediaRequestStatusAck(mediaRequestStatusAck){var _a,_b,_c;if(mediaRequestStatusAck.mediaRequestStatusSeqNum===((_b=(_a=this.lastSentMediaRequestStatus)===null||_a===void 0?void 0:_a.msg)===null||_b===void 0?void 0:_b.seqNum)){this.logger.info("Received ACK for last sent MediaRequestStatus");(_c=this.lastSentMediaRequestStatus)===null||_c===void 0?void 0:_c.cancel();}else {this.logger.info("Received ACK for old MediaRequestStatus");}}}var WcmeErrorType;(function(WcmeErrorType){WcmeErrorType["CREATE_OFFER_FAILED"]="CREATE_OFFER_FAILED";WcmeErrorType["SET_ANSWER_FAILED"]="SET_ANSWER_FAILED";WcmeErrorType["OFFER_ANSWER_MISMATCH"]="OFFER_ANSWER_MISMATCH";WcmeErrorType["SDP_MUNGE_FAILED"]="SDP_MUNGE_FAILED";WcmeErrorType["SDP_MUNGE_MISSING_CODECS"]="SDP_MUNGE_MISSING_CODECS";WcmeErrorType["INVALID_STREAM_REQUEST"]="INVALID_STREAM_REQUEST";WcmeErrorType["GET_TRANSCEIVER_FAILED"]="GET_TRANSCEIVER_FAILED";WcmeErrorType["GET_MAX_BITRATE_FAILED"]="GET_MAX_BITRATE_FAILED";WcmeErrorType["GET_PAYLOAD_TYPE_FAILED"]="GET_PAYLOAD_TYPE_FAILED";WcmeErrorType["SET_NMG_FAILED"]="SET_NMG_FAILED";})(WcmeErrorType||(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:{}};/*!
|
|
3667
3698
|
* js-logger - http://github.com/jonnyreeves/js-logger
|
|
3668
3699
|
* Jonny Reeves, http://jonnyreeves.co.uk/
|
|
3669
3700
|
* js-logger may be freely distributed under the MIT license.
|
|
@@ -3712,7 +3743,7 @@ if(context.level===Logger.WARN&&console.warn){hdlr=console.warn;}else if(context
|
|
|
3712
3743
|
// `options` hash can be used to configure the default logLevel and provide a custom message formatter.
|
|
3713
3744
|
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.
|
|
3714
3745
|
Logger.setDefaults=Logger.useDefaults;// Export to popular environments boilerplate.
|
|
3715
|
-
if(module.exports){module.exports=Logger;}else {Logger._prevLogger=global.Logger;Logger.noConflict=function(){global.Logger=Logger._prevLogger;return Logger;};global.Logger=Logger;}})(commonjsGlobal$1);})(logger$1);var Logger=logger$1.exports;var
|
|
3746
|
+
if(module.exports){module.exports=Logger;}else {Logger._prevLogger=global.Logger;Logger.noConflict=function(){global.Logger=Logger._prevLogger;return Logger;};global.Logger=Logger;}})(commonjsGlobal$1);})(logger$1);var Logger=logger$1.exports;var DEFAULT_LOGGER_NAME='web-client-media-engine';var logger=Logger.get(DEFAULT_LOGGER_NAME);logger.setLevel(Logger.DEBUG);function logErrorAndThrow(errorType,message){logger.error(message);throw new WcmeError(errorType,message);}function setLogHandler(logHandler){Logger.setHandler(logHandler);Logger$1.setHandler(logHandler);Logger$2.setHandler(logHandler);}var MediaCodecMimeType;(function(MediaCodecMimeType){MediaCodecMimeType["H264"]="video/H264";MediaCodecMimeType["AV1"]="video/AV1";MediaCodecMimeType["OPUS"]="audio/opus";})(MediaCodecMimeType||(MediaCodecMimeType={}));var defaultMaxVideoEncodeFrameSize=8160;var defaultMaxVideoEncodeMbps=244800;var RecommendedOpusBitrates;(function(RecommendedOpusBitrates){RecommendedOpusBitrates[RecommendedOpusBitrates["NB"]=12000]="NB";RecommendedOpusBitrates[RecommendedOpusBitrates["WB"]=20000]="WB";RecommendedOpusBitrates[RecommendedOpusBitrates["FB"]=40000]="FB";RecommendedOpusBitrates[RecommendedOpusBitrates["FB_MONO_MUSIC"]=64000]="FB_MONO_MUSIC";RecommendedOpusBitrates[RecommendedOpusBitrates["FB_STEREO_MUSIC"]=128000]="FB_STEREO_MUSIC";})(RecommendedOpusBitrates||(RecommendedOpusBitrates={}));var maxFrameSizeToMaxBitrateMap=new Map([[60,99000],[240,199000],[576,300000],[920,640000],[1296,720000],[2304,880000],[3600,2500000],[8160,4000000]]);function areProfileLevelIdsCompatible(senderProfileLevelId,receiverProfileLevelId,levelAsymmetryAllowed){var senderProfile=Number.parseInt("0x".concat(senderProfileLevelId),16);var recvProfile=Number.parseInt("0x".concat(receiverProfileLevelId),16);var senderProfileIdc=senderProfile>>16;var recvProfileIdc=recvProfile>>16;var senderProfileIop=(senderProfile&0x00ff00)>>8;var recvProfileIop=(recvProfile&0x00ff00)>>8;var senderLevelIdc=senderProfile&0x0000ff;var recvLevelIdc=recvProfile&0x0000ff;var areProfileCompatible=senderProfileIdc===recvProfileIdc&&senderProfileIop===recvProfileIop||senderProfileIdc===0x42&&recvProfileIdc===0x42&&(senderProfileIop&0x40)===(recvProfileIop&0x40);var isLevelIdcCompatible=levelAsymmetryAllowed?true:senderLevelIdc<=recvLevelIdc;return areProfileCompatible&&isLevelIdcCompatible;}function areCodecsCompatible(senderCodec,receiverCodec){return Object.keys(receiverCodec).every(key=>{if(key==='clockRate'||key==='name'){return senderCodec[key]===receiverCodec[key];}if(key==='fmtParams'){var fmtpForSender=senderCodec[key];var fmtpForReceiver=receiverCodec[key];var levelAsymmetryAllowed=[...fmtpForSender.keys()].some(senderFmtpParamKey=>{return senderFmtpParamKey==='level-asymmetry-allowed'&&fmtpForReceiver.get(senderFmtpParamKey)==='1'&&fmtpForSender.get(senderFmtpParamKey)==='1';});return [...fmtpForSender.keys()].every(senderFmtpParamKey=>{if(fmtpForReceiver.get(senderFmtpParamKey)){if(senderFmtpParamKey==='profile-level-id'){return areProfileLevelIdsCompatible(fmtpForSender.get(senderFmtpParamKey),fmtpForReceiver.get(senderFmtpParamKey),levelAsymmetryAllowed);}}if(senderFmtpParamKey==='packetization-mode'){return fmtpForSender.get(senderFmtpParamKey)===fmtpForReceiver.get(senderFmtpParamKey);}return true;});}return true;});}function gcd(a,b){return b===0?a:gcd(b,a%b);}function getFrameHeightByMaxFs(sourceAspectRatio,requestedMaxFs){var _gcd=gcd(sourceAspectRatio[0],sourceAspectRatio[1]);var minNumberRatiosForWidth=sourceAspectRatio[0]/_gcd;var minNumberRatiosForHeight=sourceAspectRatio[1]/_gcd;return Math.floor(Math.sqrt(requestedMaxFs*16*16/(minNumberRatiosForWidth*minNumberRatiosForHeight)))*minNumberRatiosForHeight;}function getScaleDownRatio(sourceWidth,sourceHeight,maxFs,maxWidth,maxHeight){if(!sourceWidth||!sourceHeight||!maxFs){return undefined;}var scaleDownRatio=Math.max(sourceHeight/getFrameHeightByMaxFs([sourceWidth,sourceHeight],maxFs),1.0);if(maxWidth&&maxHeight){scaleDownRatio=Math.max(sourceWidth/maxWidth,sourceHeight/maxHeight,scaleDownRatio);}return scaleDownRatio;}function getRecommendedMaxBitrateForFrameSize(requestedMaxFs){if(requestedMaxFs<60){logErrorAndThrow(WcmeErrorType.GET_MAX_BITRATE_FAILED,"Requested max video frame size cannot be less than 60.");}var expectedHeight=[...maxFrameSizeToMaxBitrateMap.keys()].sort((a,b)=>b-a).find(h=>requestedMaxFs>=h);return maxFrameSizeToMaxBitrateMap.get(expectedHeight);}/******************************************************************************
|
|
3716
3747
|
Copyright (c) Microsoft Corporation.
|
|
3717
3748
|
|
|
3718
3749
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -3787,9 +3818,9 @@ Object.keys(updatedStats).forEach(function(id){var report=updatedStats[id];if(re
|
|
|
3787
3818
|
* @param name - Name of the event to log.
|
|
3788
3819
|
* @param payload - Log data pertaining to the event.
|
|
3789
3820
|
* @param timestamp - Time the event happened in milliseconds.
|
|
3790
|
-
*/var trace=function trace(name,payload,timestamp){logger({timestamp:timestamp?Math.round(timestamp):Date.now(),name:name,payload:payload});};var origPeerConnection=window.RTCPeerConnection;pc.addEventListener('icecandidate',function(e){if(e.candidate){trace('onicecandidate',makeEvent(JSON.stringify(e.candidate)));}});pc.addEventListener('icecandidateerror',function(event){var _a=event,errorCode=_a.errorCode,errorText=_a.errorText;trace('onicecandidateerror',makeEvent("".concat(errorCode,": ").concat(errorText)));});pc.addEventListener('track',function(e){trace('ontrack',makeEvent("".concat(e.track.kind,":").concat(e.track.id," ").concat(e.streams.map(function(stream){return "stream:".concat(stream.id);}).join(' '))));});pc.addEventListener('signalingstatechange',function(){trace('onsignalingstatechange',makeEvent(pc.signalingState));});pc.addEventListener('iceconnectionstatechange',function(){trace('oniceconnectionstatechange',makeEvent(pc.iceConnectionState));});pc.addEventListener('icegatheringstatechange',function(){trace('onicegatheringstatechange',makeEvent(pc.iceGatheringState));});pc.addEventListener('connectionstatechange',function(){trace('onconnectionstatechange',makeEvent(pc.connectionState));});pc.addEventListener('negotiationneeded',function(){trace('onnegotiationneeded',makeEvent('negotiationneeded'));});pc.addEventListener('datachannel',function(event){trace('ondatachannel',makeEvent("".concat(event.channel.id,": ").concat(event.channel.label)));});['createDataChannel','close'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){trace(method,makeEvent(method));return nativeMethod.apply(this,arguments);};}});['addStream','removeStream'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var stream=arguments[0];var streamInfo=stream.getTracks().map(function(t){return "".concat(t.kind,":").concat(t.id);}).join(',');trace(method,makeEvent("".concat(stream.id," ").concat(streamInfo)));return nativeMethod.apply(this,arguments);};}});['addTrack'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var track=arguments[0];var streams=[].slice.call(arguments,1);trace(method,makeEvent("".concat(track.kind,":").concat(track.id," ").concat(streams.map(function(s){return "stream:".concat(s.id);}).join(';')||'-')));return nativeMethod.apply(this,arguments);};}});['removeTrack'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var track=arguments[0].track;trace(method,makeEvent(track?"".concat(track.kind,":").concat(track.id):'null'));return nativeMethod.apply(this,arguments);};}});['createOffer','createAnswer'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var opts;var args=arguments;if(arguments.length===1&&typeof arguments[0]==='object'){// eslint-disable-next-line prefer-destructuring
|
|
3821
|
+
*/var trace=function trace(name,payload,timestamp){logger({timestamp:timestamp?Math.round(timestamp):Date.now(),name:name,payload:payload});};var origPeerConnection=window.RTCPeerConnection;pc.addEventListener('icecandidate',function(e){if(e.candidate){trace('onicecandidate',makeEvent(JSON.stringify(e.candidate)));}});pc.addEventListener('icecandidateerror',function(event){var _a=event,errorCode=_a.errorCode,errorText=_a.errorText;trace('onicecandidateerror',makeEvent("".concat(errorCode,": ").concat(errorText)));});pc.addEventListener('track',function(e){trace('ontrack',makeEvent("".concat(e.track.kind,":").concat(e.track.id," ").concat(e.streams.map(function(stream){return "stream:".concat(stream.id);}).join(' '))));});pc.addEventListener('signalingstatechange',function(){trace('onsignalingstatechange',makeEvent(pc.signalingState));});pc.addEventListener('iceconnectionstatechange',function(){trace('oniceconnectionstatechange',makeEvent(pc.iceConnectionState));});pc.addEventListener('icegatheringstatechange',function(){trace('onicegatheringstatechange',makeEvent(pc.iceGatheringState));});pc.addEventListener('connectionstatechange',function(){trace('onconnectionstatechange',makeEvent(pc.connectionState));});pc.addEventListener('negotiationneeded',function(){trace('onnegotiationneeded',makeEvent('negotiationneeded'));});pc.addEventListener('datachannel',function(event){trace('ondatachannel',makeEvent("".concat(event.channel.id,": ").concat(event.channel.label)));});['createDataChannel','close'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){trace("on".concat(method),makeEvent(method));return nativeMethod.apply(this,arguments);};}});['addStream','removeStream'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var stream=arguments[0];var streamInfo=stream.getTracks().map(function(t){return "".concat(t.kind,":").concat(t.id);}).join(',');trace("on".concat(method),makeEvent("".concat(stream.id," ").concat(streamInfo)));return nativeMethod.apply(this,arguments);};}});['addTrack'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var track=arguments[0];var streams=[].slice.call(arguments,1);trace("on".concat(method),makeEvent("".concat(track.kind,":").concat(track.id," ").concat(streams.map(function(s){return "stream:".concat(s.id);}).join(';')||'-')));return nativeMethod.apply(this,arguments);};}});['removeTrack'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var track=arguments[0].track;trace("on".concat(method),makeEvent(track?"".concat(track.kind,":").concat(track.id):'null'));return nativeMethod.apply(this,arguments);};}});['createOffer','createAnswer'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var opts;var args=arguments;if(arguments.length===1&&typeof arguments[0]==='object'){// eslint-disable-next-line prefer-destructuring
|
|
3791
3822
|
opts=arguments[0];}else if(arguments.length===3&&typeof arguments[2]==='object'){// eslint-disable-next-line prefer-destructuring
|
|
3792
|
-
opts=arguments[2];}trace(method,makeEvent(opts||''));return nativeMethod.apply(this,opts?[opts]:undefined).then(function(description){trace("".concat(method,"OnSuccess"),makeEvent(description.sdp));if(args.length>0&&typeof args[0]==='function'){args[0].apply(null,[description]);return undefined;}return description;},function(err){trace("".concat(method,"OnFailure"),makeEvent(err.toString()));if(args.length>1&&typeof args[1]==='function'){args[1].apply(null,[err]);return;}throw err;});};}});['setLocalDescription','setRemoteDescription','addIceCandidate'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var args=arguments;trace(method,makeEvent(method==='addIceCandidate'?arguments[0]:arguments[0].sdp));return nativeMethod.apply(this,[arguments[0]]).then(function(){trace("".concat(method,"OnSuccess"),makeEvent('success'));if(args.length>=2&&typeof args[1]==='function'){args[1].apply(null,[]);return undefined;}return undefined;},function(err){trace("".concat(method,"OnFailure"),makeEvent(err.toString()));if(args.length>=3&&typeof args[2]==='function'){args[2].apply(null,[err]);return undefined;}throw err;});};}});if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var origGetUserMedia_1=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);var gum=function gum(){trace('
|
|
3823
|
+
opts=arguments[2];}trace("on".concat(method),makeEvent(opts||''));return nativeMethod.apply(this,opts?[opts]:undefined).then(function(description){trace("on".concat(method,"OnSuccess"),makeEvent(description.sdp));if(args.length>0&&typeof args[0]==='function'){args[0].apply(null,[description]);return undefined;}return description;},function(err){trace("on".concat(method,"OnFailure"),makeEvent(err.toString()));if(args.length>1&&typeof args[1]==='function'){args[1].apply(null,[err]);return;}throw err;});};}});['setLocalDescription','setRemoteDescription','addIceCandidate'].forEach(function(method){var nativeMethod=origPeerConnection.prototype[method];if(nativeMethod){origPeerConnection.prototype[method]=function(){var args=arguments;trace("on".concat(method),makeEvent(method==='addIceCandidate'?arguments[0]:arguments[0].sdp));return nativeMethod.apply(this,[arguments[0]]).then(function(){trace("on".concat(method,"OnSuccess"),makeEvent('success'));if(args.length>=2&&typeof args[1]==='function'){args[1].apply(null,[]);return undefined;}return undefined;},function(err){trace("on".concat(method,"OnFailure"),makeEvent(err.toString()));if(args.length>=3&&typeof args[2]==='function'){args[2].apply(null,[err]);return undefined;}throw err;});};}});if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var origGetUserMedia_1=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);var gum=function gum(){trace('onnavigator.mediaDevices.getUserMedia',makeEvent(JSON.stringify(arguments[0])));return origGetUserMedia_1.apply(navigator.mediaDevices,arguments).then(function(stream){trace('onnavigator.mediaDevices.getUserMediaOnSuccess',makeEvent(JSON.stringify(dumpStream(stream))));return stream;},function(err){trace('onnavigator.mediaDevices.getUserMediaOnFailure',makeEvent(err.name));return Promise.reject(err);});};navigator.mediaDevices.getUserMedia=gum.bind(navigator.mediaDevices);}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var origGetDisplayMedia_1=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);var gdm=function gdm(){trace('onnavigator.mediaDevices.getDisplayMedia',makeEvent(JSON.stringify(arguments[0])));return origGetDisplayMedia_1.apply(navigator.mediaDevices,arguments).then(function(stream){trace('onnavigator.mediaDevices.getDisplayMediaOnSuccess',makeEvent(JSON.stringify(dumpStream(stream))));return stream;},function(err){trace('onnavigator.mediaDevices.getDisplayMediaOnFailure',makeEvent(err.name));return Promise.reject(err);});};navigator.mediaDevices.getDisplayMedia=gdm.bind(navigator.mediaDevices);}var getStatsReport=function getStatsReport(){return __awaiter(void 0,void 0,void 0,function(){return __generator(this,function(_a){return [2/*return*/,pc.getStats(null).then(function(res){// Convert from stats report to js Map in order to have values set in `statsPreProcessor`
|
|
3793
3824
|
var statsMap=new Map();res.forEach(function(stats,key){return statsMap.set(key,stats);});return statsPreProcessor(statsMap).then(function(){var now=map2obj(statsMap);var base=deepCopy$1(now);// our new prev
|
|
3794
3825
|
var compressed=deltaCompression(prev,now);trace('stats-report',formatStatsReport(compressed),compressed.timestamp!==-Infinity?compressed.timestamp:undefined);prev=base;return Promise.resolve();});})];});});};var interval=window.setInterval(function(){if(pc.signalingState==='closed'){window.clearInterval(interval);return;}getStatsReport();},intervalTime);var forceStatsReport=function forceStatsReport(){return __awaiter(void 0,void 0,void 0,function(){return __generator(this,function(_a){return [2/*return*/,getStatsReport()];});});};return {forceStatsReport:forceStatsReport};};rtcStats_1=rtcStats;var NUM$1='\\d+';var SDP_TOKEN$1="[!#$%&'*+\\-.^_`{|}~a-zA-Z0-9]+";var ANY_NON_WS$1='\\S+';var SP$1='\\s';var REST$1='.+';class Line$1{}var _a$5$1;class BandwidthLine$1 extends Line$1{constructor(bandwidthType,bandwidth){super();this.bandwidthType=bandwidthType;this.bandwidth=bandwidth;}static fromSdpLine(line){if(!BandwidthLine$1.regex.test(line)){return undefined;}var tokens=line.match(BandwidthLine$1.regex);var bandwidthType=tokens[1];var bandwidth=parseInt(tokens[2],10);return new BandwidthLine$1(bandwidthType,bandwidth);}toSdpLine(){return "b=".concat(this.bandwidthType,":").concat(this.bandwidth);}}_a$5$1=BandwidthLine$1;BandwidthLine$1.BW_TYPE_REGEX='CT|AS|TIAS';BandwidthLine$1.regex=new RegExp("^(".concat(_a$5$1.BW_TYPE_REGEX,"):(").concat(NUM$1,")"));class BundleGroupLine$1 extends Line$1{constructor(mids){super();this.mids=mids;}static fromSdpLine(line){if(!BundleGroupLine$1.regex.test(line)){return undefined;}var tokens=line.match(BundleGroupLine$1.regex);var mids=tokens[1].split(' ');return new BundleGroupLine$1(mids);}toSdpLine(){return "a=group:BUNDLE ".concat(this.mids.join(' '));}}BundleGroupLine$1.regex=new RegExp("^group:BUNDLE (".concat(REST$1,")"));var _a$4$1;class CandidateLine$1 extends Line$1{constructor(foundation,componentId,transport,priority,connectionAddress,port,candidateType,relAddr,relPort,candidateExtensions){super();this.foundation=foundation;this.componentId=componentId;this.transport=transport;this.priority=priority;this.connectionAddress=connectionAddress;this.port=port;this.candidateType=candidateType;this.relAddr=relAddr;this.relPort=relPort;this.candidateExtensions=candidateExtensions;}static fromSdpLine(line){if(!CandidateLine$1.regex.test(line)){return undefined;}var tokens=line.match(CandidateLine$1.regex);var foundation=tokens[1];var componentId=parseInt(tokens[2],10);var transport=tokens[3];var priority=parseInt(tokens[4],10);var connectionAddress=tokens[5];var port=parseInt(tokens[6],10);var candidateType=tokens[7];var relAddr=tokens[8];var relPort=tokens[9]?parseInt(tokens[9],10):undefined;var candidateExtensions=tokens[10];return new CandidateLine$1(foundation,componentId,transport,priority,connectionAddress,port,candidateType,relAddr,relPort,candidateExtensions);}toSdpLine(){var str='';str+="a=candidate:".concat(this.foundation," ").concat(this.componentId," ").concat(this.transport," ").concat(this.priority," ").concat(this.connectionAddress," ").concat(this.port," typ ").concat(this.candidateType);if(this.relAddr){str+=" raddr ".concat(this.relAddr);}if(this.relPort){str+=" rport ".concat(this.relPort);}if(this.candidateExtensions){str+=" ".concat(this.candidateExtensions);}return str;}}_a$4$1=CandidateLine$1;CandidateLine$1.ICE_CHARS="[a-zA-Z0-9+/]+";CandidateLine$1.regex=new RegExp("^candidate:(".concat(_a$4$1.ICE_CHARS,") (").concat(NUM$1,") (").concat(ANY_NON_WS$1,") (").concat(NUM$1,") (").concat(ANY_NON_WS$1,") (").concat(NUM$1,") typ (").concat(ANY_NON_WS$1,")(?: raddr (").concat(ANY_NON_WS$1,"))?(?: rport (").concat(NUM$1,"))?(?: (").concat(REST$1,"))?"));class ConnectionLine$1 extends Line$1{constructor(netType,addrType,ipAddr){super();this.netType=netType;this.addrType=addrType;this.ipAddr=ipAddr;}static fromSdpLine(line){if(!ConnectionLine$1.regex.test(line)){return undefined;}var tokens=line.match(ConnectionLine$1.regex);var netType=tokens[1];var addrType=tokens[2];var ipAddr=tokens[3];return new ConnectionLine$1(netType,addrType,ipAddr);}toSdpLine(){return "c=".concat(this.netType," ").concat(this.addrType," ").concat(this.ipAddr);}}ConnectionLine$1.regex=new RegExp("^(".concat(ANY_NON_WS$1,") (").concat(ANY_NON_WS$1,") (").concat(ANY_NON_WS$1,")"));class ContentLine$1 extends Line$1{constructor(values){super();this.values=values;}static fromSdpLine(line){if(!ContentLine$1.regex.test(line)){return undefined;}var tokens=line.match(ContentLine$1.regex);var values=tokens[1].split(',');return new ContentLine$1(values);}toSdpLine(){return "a=content:".concat(this.values.join(','));}}ContentLine$1.regex=new RegExp("^content:(".concat(REST$1,")$"));class DirectionLine$1 extends Line$1{constructor(direction){super();this.direction=direction;}static fromSdpLine(line){if(!DirectionLine$1.regex.test(line)){return undefined;}var tokens=line.match(DirectionLine$1.regex);var direction=tokens[1];return new DirectionLine$1(direction);}toSdpLine(){return "a=".concat(this.direction);}}DirectionLine$1.regex=/^(sendrecv|sendonly|recvonly|inactive)$/;var _a$3$1;class ExtMapLine$1 extends Line$1{constructor(id,uri,direction,extensionAttributes){super();this.id=id;this.uri=uri;this.direction=direction;this.extensionAttributes=extensionAttributes;}static fromSdpLine(line){if(!ExtMapLine$1.regex.test(line)){return undefined;}var tokens=line.match(ExtMapLine$1.regex);var id=parseInt(tokens[1],10);var direction=tokens[2];var uri=tokens[3];var extensionAttributes=tokens[4];return new ExtMapLine$1(id,uri,direction,extensionAttributes);}toSdpLine(){var str='';str+="a=extmap:".concat(this.id);if(this.direction){str+="/".concat(this.direction);}str+=" ".concat(this.uri);if(this.extensionAttributes){str+=" ".concat(this.extensionAttributes);}return str;}}_a$3$1=ExtMapLine$1;ExtMapLine$1.EXTMAP_DIRECTION="sendonly|recvonly|sendrecv|inactive";ExtMapLine$1.regex=new RegExp("^extmap:(".concat(NUM$1,")(?:/(").concat(_a$3$1.EXTMAP_DIRECTION,"))? (").concat(ANY_NON_WS$1,")(?: (").concat(REST$1,"))?"));class FingerprintLine$1 extends Line$1{constructor(fingerprint){super();this.fingerprint=fingerprint;}static fromSdpLine(line){if(!FingerprintLine$1.regex.test(line)){return undefined;}var tokens=line.match(FingerprintLine$1.regex);var fingerprint=tokens[1];return new FingerprintLine$1(fingerprint);}toSdpLine(){return "a=fingerprint:".concat(this.fingerprint);}}FingerprintLine$1.regex=new RegExp("^fingerprint:(".concat(REST$1,")"));function parseFmtpParams$1(fmtpParams){fmtpParams=fmtpParams.replace(/^a=fmtp:\d+\x20/,'');var fmtpObj=new Map();if(/^\d+([,/-]\d+)+$/.test(fmtpParams)){fmtpObj.set(fmtpParams,undefined);return fmtpObj;}fmtpParams.split(';').forEach(param=>{var paramArr=param&¶m.split('=');if(paramArr.length!==2||!paramArr[0]||!paramArr[1]){throw new Error("Fmtp params is invalid with ".concat(fmtpParams));}fmtpObj.set(paramArr[0],paramArr[1]);});return fmtpObj;}class FmtpLine$1 extends Line$1{constructor(payloadType,params){super();this.payloadType=payloadType;this.params=params;}static fromSdpLine(line){if(!FmtpLine$1.regex.test(line)){return undefined;}var tokens=line.match(FmtpLine$1.regex);var payloadType=parseInt(tokens[1],10);var params=tokens[2];return new FmtpLine$1(payloadType,parseFmtpParams$1(params));}toSdpLine(){var fmtParams=Array.from(this.params.keys()).map(key=>{if(this.params.get(key)!==undefined){return "".concat(key,"=").concat(this.params.get(key));}return "".concat(key);}).join(';');return "a=fmtp:".concat(this.payloadType," ").concat(fmtParams);}}FmtpLine$1.regex=new RegExp("^fmtp:(".concat(NUM$1,") (").concat(REST$1,")"));class IceOptionsLine$1 extends Line$1{constructor(options){super();this.options=options;}static fromSdpLine(line){if(!IceOptionsLine$1.regex.test(line)){return undefined;}var tokens=line.match(IceOptionsLine$1.regex);var options=tokens[1].split(' ');return new IceOptionsLine$1(options);}toSdpLine(){return "a=ice-options:".concat(this.options.join(' '));}}IceOptionsLine$1.regex=new RegExp("^ice-options:(".concat(REST$1,")$"));class IcePwdLine$1 extends Line$1{constructor(pwd){super();this.pwd=pwd;}static fromSdpLine(line){if(!IcePwdLine$1.regex.test(line)){return undefined;}var tokens=line.match(IcePwdLine$1.regex);var pwd=tokens[1];return new IcePwdLine$1(pwd);}toSdpLine(){return "a=ice-pwd:".concat(this.pwd);}}IcePwdLine$1.regex=new RegExp("^ice-pwd:(".concat(ANY_NON_WS$1,")$"));class IceUfragLine$1 extends Line$1{constructor(ufrag){super();this.ufrag=ufrag;}static fromSdpLine(line){if(!IceUfragLine$1.regex.test(line)){return undefined;}var tokens=line.match(IceUfragLine$1.regex);var ufrag=tokens[1];return new IceUfragLine$1(ufrag);}toSdpLine(){return "a=ice-ufrag:".concat(this.ufrag);}}IceUfragLine$1.regex=new RegExp("^ice-ufrag:(".concat(ANY_NON_WS$1,")$"));class MaxMessageSizeLine$1 extends Line$1{constructor(maxMessageSize){super();this.maxMessageSize=maxMessageSize;}static fromSdpLine(line){if(!MaxMessageSizeLine$1.regex.test(line)){return undefined;}var tokens=line.match(MaxMessageSizeLine$1.regex);var maxMessageSize=parseInt(tokens[1],10);return new MaxMessageSizeLine$1(maxMessageSize);}toSdpLine(){return "a=max-message-size:".concat(this.maxMessageSize);}}MaxMessageSizeLine$1.regex=new RegExp("^max-message-size:(".concat(NUM$1,")"));var _a$2$1;class MediaLine$1 extends Line$1{constructor(type,port,protocol,formats){super();this.type=type;this.port=port;this.protocol=protocol;this.formats=formats;}static fromSdpLine(line){if(!MediaLine$1.regex.test(line)){return undefined;}var tokens=line.match(MediaLine$1.regex);var type=tokens[1];var port=parseInt(tokens[2],10);var protocol=tokens[3];var formats=tokens[4].split(' ');return new MediaLine$1(type,port,protocol,formats);}toSdpLine(){return "m=".concat(this.type," ").concat(this.port," ").concat(this.protocol," ").concat(this.formats.join(' '));}}_a$2$1=MediaLine$1;MediaLine$1.MEDIA_TYPE='audio|video|application';MediaLine$1.regex=new RegExp("^(".concat(_a$2$1.MEDIA_TYPE,") (").concat(NUM$1,") (").concat(ANY_NON_WS$1,") (").concat(REST$1,")"));class MidLine$1 extends Line$1{constructor(mid){super();this.mid=mid;}static fromSdpLine(line){if(!MidLine$1.regex.test(line)){return undefined;}var tokens=line.match(MidLine$1.regex);var mid=tokens[1];return new MidLine$1(mid);}toSdpLine(){return "a=mid:".concat(this.mid);}}MidLine$1.regex=new RegExp("^mid:(".concat(ANY_NON_WS$1,")$"));class OriginLine$1 extends Line$1{constructor(username,sessionId,sessionVersion,netType,addrType,ipAddr){super();this.username=username;this.sessionId=sessionId;this.sessionVersion=sessionVersion;this.netType=netType;this.addrType=addrType;this.ipAddr=ipAddr;}static fromSdpLine(line){if(!OriginLine$1.regex.test(line)){return undefined;}var tokens=line.match(OriginLine$1.regex);var username=tokens[1];var sessionId=tokens[2];var sessionVersion=parseInt(tokens[3],10);var netType=tokens[4];var addrType=tokens[5];var ipAddr=tokens[6];return new OriginLine$1(username,sessionId,sessionVersion,netType,addrType,ipAddr);}toSdpLine(){return "o=".concat(this.username," ").concat(this.sessionId," ").concat(this.sessionVersion," ").concat(this.netType," ").concat(this.addrType," ").concat(this.ipAddr);}}OriginLine$1.regex=new RegExp("^(".concat(ANY_NON_WS$1,") (").concat(ANY_NON_WS$1,") (").concat(NUM$1,") (").concat(ANY_NON_WS$1,") (").concat(ANY_NON_WS$1,") (").concat(ANY_NON_WS$1,")"));var _a$1$2;class RidLine$1 extends Line$1{constructor(id,direction,params){super();this.id=id;this.direction=direction;this.params=params;}static fromSdpLine(line){if(!RidLine$1.regex.test(line)){return undefined;}var tokens=line.match(RidLine$1.regex);var id=tokens[1];var direction=tokens[2];var params=tokens[3];return new RidLine$1(id,direction,params);}toSdpLine(){var str='';str+="a=rid:".concat(this.id," ").concat(this.direction);if(this.params){str+=" ".concat(this.params);}return str;}}_a$1$2=RidLine$1;RidLine$1.RID_ID="[\\w-]+";RidLine$1.RID_DIRECTION="\\bsend\\b|\\brecv\\b";RidLine$1.regex=new RegExp("^rid:(".concat(_a$1$2.RID_ID,") (").concat(_a$1$2.RID_DIRECTION,")(?:").concat(SP$1,"(").concat(REST$1,"))?"));class RtcpMuxLine$1 extends Line$1{static fromSdpLine(line){if(!RtcpMuxLine$1.regex.test(line)){return undefined;}return new RtcpMuxLine$1();}toSdpLine(){return "a=rtcp-mux";}}RtcpMuxLine$1.regex=/^rtcp-mux$/;class RtcpFbLine$1 extends Line$1{constructor(payloadType,feedback){super();this.payloadType=payloadType;this.feedback=feedback;}static fromSdpLine(line){if(!RtcpFbLine$1.regex.test(line)){return undefined;}var tokens=line.match(RtcpFbLine$1.regex);var payloadType=parseInt(tokens[1],10);var feedback=tokens[2];return new RtcpFbLine$1(payloadType,feedback);}toSdpLine(){return "a=rtcp-fb:".concat(this.payloadType," ").concat(this.feedback);}}RtcpFbLine$1.regex=new RegExp("^rtcp-fb:(".concat(NUM$1,") (").concat(REST$1,")"));var _a$7;class RtpMapLine$1 extends Line$1{constructor(payloadType,encodingName,clockRate,encodingParams){super();this.payloadType=payloadType;this.encodingName=encodingName;this.clockRate=clockRate;this.encodingParams=encodingParams;}static fromSdpLine(line){if(!RtpMapLine$1.regex.test(line)){return undefined;}var tokens=line.match(RtpMapLine$1.regex);var payloadType=parseInt(tokens[1],10);var encodingName=tokens[2];var clockRate=parseInt(tokens[3],10);var encodingParams=tokens[4];return new RtpMapLine$1(payloadType,encodingName,clockRate,encodingParams);}toSdpLine(){var str='';str+="a=rtpmap:".concat(this.payloadType," ").concat(this.encodingName,"/").concat(this.clockRate);if(this.encodingParams){str+="/".concat(this.encodingParams);}return str;}}_a$7=RtpMapLine$1;RtpMapLine$1.NON_SLASH_TOKEN='[^\\s/]+';RtpMapLine$1.regex=new RegExp("^rtpmap:(".concat(NUM$1,") (").concat(_a$7.NON_SLASH_TOKEN,")/(").concat(_a$7.NON_SLASH_TOKEN,")(?:/(").concat(_a$7.NON_SLASH_TOKEN,"))?"));class SctpPortLine$1 extends Line$1{constructor(port){super();this.port=port;}static fromSdpLine(line){if(!SctpPortLine$1.regex.test(line)){return undefined;}var tokens=line.match(SctpPortLine$1.regex);var port=parseInt(tokens[1],10);return new SctpPortLine$1(port);}toSdpLine(){return "a=sctp-port:".concat(this.port);}}SctpPortLine$1.regex=new RegExp("^sctp-port:(".concat(NUM$1,")"));class SessionInformationLine$1 extends Line$1{constructor(info){super();this.info=info;}static fromSdpLine(line){if(!SessionInformationLine$1.regex.test(line)){return undefined;}var tokens=line.match(SessionInformationLine$1.regex);var info=tokens[1];return new SessionInformationLine$1(info);}toSdpLine(){return "i=".concat(this.info);}}SessionInformationLine$1.regex=new RegExp("(".concat(REST$1,")"));class SessionNameLine$1 extends Line$1{constructor(name){super();this.name=name;}static fromSdpLine(line){if(!SessionNameLine$1.regex.test(line)){return undefined;}var tokens=line.match(SessionNameLine$1.regex);var name=tokens[1];return new SessionNameLine$1(name);}toSdpLine(){return "s=".concat(this.name);}}SessionNameLine$1.regex=new RegExp("^(".concat(REST$1,")"));class SetupLine$1 extends Line$1{constructor(setup){super();this.setup=setup;}static fromSdpLine(line){if(!SetupLine$1.regex.test(line)){return undefined;}var tokens=line.match(SetupLine$1.regex);var setup=tokens[1];return new SetupLine$1(setup);}toSdpLine(){return "a=setup:".concat(this.setup);}}SetupLine$1.regex=/^setup:(actpass|active|passive)$/;class SimulcastLayer$1{constructor(id,paused){this.id=id;this.paused=paused;}toString(){return this.paused?"~".concat(this.id):this.id;}}class SimulcastLayerList$1{constructor(){this.layers=[];}addLayer(layer){this.layers.push([layer]);}addLayerWithAlternatives(alternatives){this.layers.push(alternatives);}get length(){return this.layers.length;}get(index){return this.layers[index];}static fromString(str){var layerList=new SimulcastLayerList$1();var tokens=str.split(';');if(tokens.length===1&&!tokens[0].trim()){throw new Error('simulcast stream list empty');}tokens.forEach(token=>{if(!token){throw new Error('simulcast layer list empty');}var ridTokens=token.split(',');var layers=[];ridTokens.forEach(ridToken=>{if(!ridToken||ridToken==='~'){throw new Error('rid empty');}var paused=ridToken[0]==='~';var rid=paused?ridToken.substring(1):ridToken;layers.push(new SimulcastLayer$1(rid,paused));});layerList.addLayerWithAlternatives(layers);});return layerList;}toString(){return this.layers.map(altArray=>altArray.map(v=>v.toString()).join(',')).join(';');}}class SimulcastLine$1 extends Line$1{constructor(sendLayers,recvLayers){super();this.sendLayers=sendLayers;this.recvLayers=recvLayers;}static fromSdpLine(line){if(!SimulcastLine$1.regex.test(line)){return undefined;}var tokens=line.match(SimulcastLine$1.regex);var bidirectional=tokens[3]&&tokens[4];var firstDirection=tokens[1];var layerList1=SimulcastLayerList$1.fromString(tokens[2]);var layerList2=new SimulcastLayerList$1();if(bidirectional){var secondDirection=tokens[3];if(firstDirection===secondDirection){return undefined;}layerList2=SimulcastLayerList$1.fromString(tokens[4]);}var sendLayerList;var recvLayerList;if(firstDirection==='send'){sendLayerList=layerList1;recvLayerList=layerList2;}else {sendLayerList=layerList2;recvLayerList=layerList1;}return new SimulcastLine$1(sendLayerList,recvLayerList);}toSdpLine(){var str='a=simulcast:';if(this.sendLayers.length){str+="send ".concat(this.sendLayers.toString());if(this.recvLayers.length){str+=" ";}}if(this.recvLayers.length){str+="recv ".concat(this.recvLayers.toString());}return str;}}SimulcastLine$1.regex=new RegExp("^simulcast:(send|recv) (".concat(ANY_NON_WS$1,")(?: (send|recv) (").concat(ANY_NON_WS$1,"))?"));class SsrcLine$1 extends Line$1{constructor(ssrcId,attribute){var attributeValue=arguments.length>2&&arguments[2]!==undefined?arguments[2]:undefined;var attributeData=arguments.length>3&&arguments[3]!==undefined?arguments[3]:undefined;super();this.ssrcId=ssrcId;this.attribute=attribute;this.attributeValue=attributeValue;this.attributeData=attributeData;}static fromSdpLine(line){if(!SsrcLine$1.regex.test(line)){return undefined;}var tokens=line.match(SsrcLine$1.regex);var ssrcId=parseInt(tokens[1],10);var attribute=tokens[2];var attributeValue=tokens[3];var attributeData=tokens[4];return new SsrcLine$1(ssrcId,attribute,attributeValue,attributeData);}toSdpLine(){var str="a=ssrc:".concat(this.ssrcId," ").concat(this.attribute);if(this.attributeValue){str+=":".concat(this.attributeValue);}if(this.attributeData){str+=" ".concat(this.attributeData);}return str;}}SsrcLine$1.regex=new RegExp("^ssrc:(".concat(NUM$1,") (").concat(SDP_TOKEN$1,")(?::(").concat(SDP_TOKEN$1,")?(?: (").concat(ANY_NON_WS$1,"))?)?$"));class SsrcGroupLine$1 extends Line$1{constructor(semantics,ssrcs){super();this.semantics=semantics;this.ssrcs=ssrcs;}static fromSdpLine(line){if(!SsrcGroupLine$1.regex.test(line)){return undefined;}var tokens=line.match(SsrcGroupLine$1.regex);var semantics=tokens[1];var ssrcs=tokens[2].split(' ').map(ssrcStr=>parseInt(ssrcStr,10));return new SsrcGroupLine$1(semantics,ssrcs);}toSdpLine(){return "a=ssrc-group:".concat(this.semantics," ").concat(this.ssrcs.join(' '));}}SsrcGroupLine$1.regex=new RegExp("^ssrc-group:(SIM|FID|FEC) ((?:".concat(NUM$1).concat(SP$1,"*)+)"));class TimingLine$1 extends Line$1{constructor(startTime,stopTime){super();this.startTime=startTime;this.stopTime=stopTime;}static fromSdpLine(line){if(!TimingLine$1.regex.test(line)){return undefined;}var tokens=line.match(TimingLine$1.regex);var startTime=parseInt(tokens[1],10);var stopTime=parseInt(tokens[2],10);return new TimingLine$1(startTime,stopTime);}toSdpLine(){return "t=".concat(this.startTime," ").concat(this.stopTime);}}TimingLine$1.regex=new RegExp("^(".concat(NUM$1,") (").concat(NUM$1,")"));class VersionLine$1 extends Line$1{constructor(version){super();this.version=version;}static fromSdpLine(line){if(!VersionLine$1.regex.test(line)){return undefined;}var tokens=line.match(VersionLine$1.regex);var version=parseInt(tokens[1],10);return new VersionLine$1(version);}toSdpLine(){return "v=".concat(this.version);}}VersionLine$1.regex=new RegExp("^(".concat(NUM$1,")$"));class UnknownLine$1 extends Line$1{constructor(value){super();this.value=value;}static fromSdpLine(line){var tokens=line.match(UnknownLine$1.regex);var value=tokens[1];return new UnknownLine$1(value);}toSdpLine(){return "".concat(this.value);}}UnknownLine$1.regex=new RegExp("(".concat(REST$1,")"));class IceInfo$1{constructor(){this.candidates=[];}addLine(line){if(line instanceof IceUfragLine$1){this.ufrag=line;return true;}if(line instanceof IcePwdLine$1){this.pwd=line;return true;}if(line instanceof IceOptionsLine$1){this.options=line;return true;}if(line instanceof CandidateLine$1){this.candidates.push(line);return true;}return false;}toLines(){var lines=[];if(this.ufrag){lines.push(this.ufrag);}if(this.pwd){lines.push(this.pwd);}if(this.options){lines.push(this.options);}this.candidates.forEach(candidate=>lines.push(candidate));return lines;}}class MediaDescription$1{constructor(type,port,protocol){this.iceInfo=new IceInfo$1();this.otherLines=[];this.type=type;this.port=port;this.protocol=protocol;}findOtherLine(ty){return this.otherLines.find(line=>line instanceof ty);}addLine(line){if(line instanceof BundleGroupLine$1){throw new Error("Error: bundle group line not allowed in media description");}if(line instanceof BandwidthLine$1){this.bandwidth=line;return true;}if(line instanceof MidLine$1){this.mid=line.mid;return true;}if(line instanceof FingerprintLine$1){this.fingerprint=line.fingerprint;return true;}if(line instanceof SetupLine$1){this.setup=line.setup;return true;}if(line instanceof ConnectionLine$1){this.connection=line;return true;}if(line instanceof ContentLine$1){this.content=line;return true;}return this.iceInfo.addLine(line);}}class ApplicationMediaDescription$1 extends MediaDescription$1{constructor(mediaLine){super(mediaLine.type,mediaLine.port,mediaLine.protocol);this.fmts=[];this.fmts=mediaLine.formats;}toLines(){var lines=[];lines.push(new MediaLine$1(this.type,this.port,this.protocol,this.fmts));if(this.connection){lines.push(this.connection);}if(this.bandwidth){lines.push(this.bandwidth);}lines.push(...this.iceInfo.toLines());if(this.fingerprint){lines.push(new FingerprintLine$1(this.fingerprint));}if(this.setup){lines.push(new SetupLine$1(this.setup));}if(this.mid){lines.push(new MidLine$1(this.mid));}if(this.content){lines.push(this.content);}if(this.sctpPort){lines.push(new SctpPortLine$1(this.sctpPort));}if(this.maxMessageSize){lines.push(new MaxMessageSizeLine$1(this.maxMessageSize));}lines.push(...this.otherLines);return lines;}addLine(line){if(super.addLine(line)){return true;}if(line instanceof MediaLine$1){throw new Error('Error: tried passing a MediaLine to an existing MediaInfo');}if(line instanceof SctpPortLine$1){this.sctpPort=line.port;return true;}if(line instanceof MaxMessageSizeLine$1){this.maxMessageSize=line.maxMessageSize;return true;}this.otherLines.push(line);return true;}}class CodecInfo$2{constructor(pt){this.fmtParams=new Map();this.feedback=[];this.pt=pt;}addLine(line){if(line instanceof RtpMapLine$1){this.name=line.encodingName;this.clockRate=line.clockRate;this.encodingParams=line.encodingParams;return true;}if(line instanceof FmtpLine$1){this.fmtParams=new Map([...Array.from(this.fmtParams.entries()),...Array.from(line.params.entries())]);if(line.params.has('apt')){var apt=line.params.get('apt');this.primaryCodecPt=parseInt(apt,10);}return true;}if(line instanceof RtcpFbLine$1){this.feedback.push(line.feedback);return true;}return false;}toLines(){var lines=[];if(this.name&&this.clockRate){lines.push(new RtpMapLine$1(this.pt,this.name,this.clockRate,this.encodingParams));}this.feedback.forEach(fb=>{lines.push(new RtcpFbLine$1(this.pt,fb));});if(this.fmtParams.size>0){lines.push(new FmtpLine$1(this.pt,this.fmtParams));}return lines;}}class AvMediaDescription$1 extends MediaDescription$1{constructor(mediaLine){super(mediaLine.type,mediaLine.port,mediaLine.protocol);this.pts=[];this.extMaps=new Map();this.rids=[];this.codecs=new Map();this.rtcpMux=false;this.ssrcs=[];this.ssrcGroups=[];this.pts=mediaLine.formats.map(fmt=>{return parseInt(fmt,10);});this.pts.forEach(pt=>this.codecs.set(pt,new CodecInfo$2(pt)));}toLines(){var lines=[];lines.push(new MediaLine$1(this.type,this.port,this.protocol,this.pts.map(pt=>"".concat(pt))));if(this.connection){lines.push(this.connection);}if(this.bandwidth){lines.push(this.bandwidth);}lines.push(...this.iceInfo.toLines());if(this.fingerprint){lines.push(new FingerprintLine$1(this.fingerprint));}if(this.setup){lines.push(new SetupLine$1(this.setup));}if(this.mid){lines.push(new MidLine$1(this.mid));}if(this.rtcpMux){lines.push(new RtcpMuxLine$1());}if(this.content){lines.push(this.content);}this.extMaps.forEach(extMap=>lines.push(extMap));this.rids.forEach(rid=>lines.push(rid));if(this.simulcast){lines.push(this.simulcast);}if(this.direction){lines.push(new DirectionLine$1(this.direction));}this.codecs.forEach(codec=>lines.push(...codec.toLines()));lines.push(...this.ssrcs);lines.push(...this.ssrcGroups);lines.push(...this.otherLines);return lines;}addLine(line){if(super.addLine(line)){return true;}if(line instanceof MediaLine$1){throw new Error('Error: tried passing a MediaLine to an existing MediaInfo');}if(line instanceof DirectionLine$1){this.direction=line.direction;return true;}if(line instanceof ExtMapLine$1){if(this.extMaps.has(line.id)){throw new Error("Tried to extension with duplicate ID: an extension already exists with ID ".concat(line.id));}this.extMaps.set(line.id,line);return true;}if(line instanceof RidLine$1){this.rids.push(line);return true;}if(line instanceof RtcpMuxLine$1){this.rtcpMux=true;return true;}if(line instanceof SimulcastLine$1){this.simulcast=line;return true;}if(line instanceof RtpMapLine$1||line instanceof FmtpLine$1||line instanceof RtcpFbLine$1){var codec=this.codecs.get(line.payloadType);if(!codec){throw new Error("Error: got line for unknown codec: ".concat(line.toSdpLine()));}codec.addLine(line);return true;}if(line instanceof SsrcLine$1){this.ssrcs.push(line);return true;}if(line instanceof SsrcGroupLine$1){this.ssrcGroups.push(line);return true;}this.otherLines.push(line);return true;}getCodecByPt(pt){return this.codecs.get(pt);}removePt(pt){var associatedPts=[...this.codecs.values()].filter(ci=>ci.primaryCodecPt===pt).map(ci=>ci.pt);var allPtsToRemove=[pt,...associatedPts];allPtsToRemove.forEach(ptToRemove=>{this.codecs.delete(ptToRemove);});this.pts=this.pts.filter(existingPt=>allPtsToRemove.indexOf(existingPt)===-1);}addExtension(_ref){var{uri,direction,attributes,id}=_ref;var getFirstFreeId=()=>{var freeId=1;for(;;){if(!this.extMaps.has(freeId)){break;}freeId+=1;}return freeId;};var extId=id||getFirstFreeId();if(this.extMaps.has(extId)){throw new Error("Extension with ID ".concat(id," already exists"));}if(extId===0){throw new Error("Extension ID 0 is reserved");}this.extMaps.set(extId,new ExtMapLine$1(extId,uri,direction,attributes));}}class SessionDescription$1{constructor(){this.groups=[];this.otherLines=[];}addLine(line){if(line instanceof VersionLine$1){this.version=line;return true;}if(line instanceof OriginLine$1){this.origin=line;return true;}if(line instanceof SessionNameLine$1){this.sessionName=line;return true;}if(line instanceof SessionInformationLine$1){this.information=line;return true;}if(line instanceof TimingLine$1){this.timing=line;return true;}if(line instanceof ConnectionLine$1){this.connection=line;return true;}if(line instanceof BandwidthLine$1){this.bandwidth=line;return true;}if(line instanceof BundleGroupLine$1){this.groups.push(line);return true;}this.otherLines.push(line);return true;}toLines(){var lines=[];if(this.version){lines.push(this.version);}if(this.origin){lines.push(this.origin);}if(this.sessionName){lines.push(this.sessionName);}if(this.information){lines.push(this.information);}if(this.connection){lines.push(this.connection);}if(this.bandwidth){lines.push(this.bandwidth);}if(this.timing){lines.push(this.timing);}if(this.groups){lines.push(...this.groups);}lines.push(...this.otherLines);return lines;}}class Sdp$1{constructor(){this.session=new SessionDescription$1();this.media=[];}get avMedia(){return this.media.filter(mi=>mi instanceof AvMediaDescription$1);}toString(){var lines=[];lines.push(...this.session.toLines());this.media.forEach(m=>lines.push(...m.toLines()));return "".concat(lines.map(l=>l.toSdpLine()).join('\r\n'),"\r\n");}}class Grammar$1{constructor(){this.parsers=new Map();}addParser(lineType,parser){var parsers=this.parsers.get(lineType)||[];parsers.push(parser);this.parsers.set(lineType,parsers);}getParsers(lineType){return this.parsers.get(lineType)||[];}}class SdpGrammar$1 extends Grammar$1{constructor(){super();this.addParser('v',VersionLine$1.fromSdpLine);this.addParser('o',OriginLine$1.fromSdpLine);this.addParser('c',ConnectionLine$1.fromSdpLine);this.addParser('i',SessionInformationLine$1.fromSdpLine);this.addParser('m',MediaLine$1.fromSdpLine);this.addParser('s',SessionNameLine$1.fromSdpLine);this.addParser('t',TimingLine$1.fromSdpLine);this.addParser('b',BandwidthLine$1.fromSdpLine);this.addParser('a',RtpMapLine$1.fromSdpLine);this.addParser('a',RtcpFbLine$1.fromSdpLine);this.addParser('a',FmtpLine$1.fromSdpLine);this.addParser('a',DirectionLine$1.fromSdpLine);this.addParser('a',ExtMapLine$1.fromSdpLine);this.addParser('a',MidLine$1.fromSdpLine);this.addParser('a',IceUfragLine$1.fromSdpLine);this.addParser('a',IcePwdLine$1.fromSdpLine);this.addParser('a',IceOptionsLine$1.fromSdpLine);this.addParser('a',FingerprintLine$1.fromSdpLine);this.addParser('a',SetupLine$1.fromSdpLine);this.addParser('a',SctpPortLine$1.fromSdpLine);this.addParser('a',MaxMessageSizeLine$1.fromSdpLine);this.addParser('a',RtcpMuxLine$1.fromSdpLine);this.addParser('a',BundleGroupLine$1.fromSdpLine);this.addParser('a',ContentLine$1.fromSdpLine);this.addParser('a',RidLine$1.fromSdpLine);this.addParser('a',CandidateLine$1.fromSdpLine);this.addParser('a',SimulcastLine$1.fromSdpLine);this.addParser('a',SsrcLine$1.fromSdpLine);this.addParser('a',SsrcGroupLine$1.fromSdpLine);}}var DefaultSdpGrammar$1=new SdpGrammar$1();function isValidLine$1(line){return line.length>2;}function parseToModel$1(lines){var sdp=new Sdp$1();var currBlock=sdp.session;lines.forEach(l=>{if(l instanceof MediaLine$1){var mediaInfo;if(l.type==='audio'||l.type==='video'){mediaInfo=new AvMediaDescription$1(l);}else if(l.type==='application'){mediaInfo=new ApplicationMediaDescription$1(l);}else {throw new Error("Unhandled media type: ".concat(l.type));}sdp.media.push(mediaInfo);currBlock=mediaInfo;}else {currBlock.addLine(l);}});return sdp;}function parseToLines$1(sdp,grammar){var lines=[];sdp.split(/(\r\n|\r|\n)/).filter(isValidLine$1).forEach(l=>{var lineType=l[0];var lineValue=l.slice(2);var parsers=grammar.getParsers(lineType);for(var parser of parsers){var _result=parser(lineValue);if(_result){lines.push(_result);return;}}var result=UnknownLine$1.fromSdpLine(l);lines.push(result);});return lines;}function parse$1(sdp){var grammar=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DefaultSdpGrammar$1;var lines=parseToLines$1(sdp,grammar);var parsed=parseToModel$1(lines);return parsed;}function disableRtcpFbValue(sdpOrAv,rtcpFbValue){var mediaDescriptions=sdpOrAv instanceof Sdp$1?sdpOrAv.avMedia:[sdpOrAv];mediaDescriptions.forEach(media=>{media.codecs.forEach(codec=>{codec.feedback=codec.feedback.filter(fb=>fb!==rtcpFbValue);});});}function disableTwcc(sdpOrAv){disableRtcpFbValue(sdpOrAv,'transport-cc');}function removeCodec(sdpOrAv,codecName){var mediaDescriptions=sdpOrAv instanceof Sdp$1?sdpOrAv.avMedia:[sdpOrAv];mediaDescriptions.forEach(media=>{var codecInfos=[...media.codecs.entries()].filter(_ref2=>{var[,ci]=_ref2;var _a;return ((_a=ci.name)===null||_a===void 0?void 0:_a.toLowerCase())===codecName.toLowerCase();});codecInfos.forEach(_ref3=>{var[pt]=_ref3;return media.removePt(pt);});});}function retainCodecs(sdpOrAv,allowedCodecNames){var avMediaDescriptions=sdpOrAv instanceof Sdp$1?sdpOrAv.avMedia:[sdpOrAv];var allowedLowerCase=allowedCodecNames.map(s=>s.toLowerCase());avMediaDescriptions.map(av=>{return [...av.codecs.values()].map(c=>c.name);}).flat().filter(codecName=>!allowedLowerCase.includes(codecName.toLowerCase())).forEach(unwantedCodec=>removeCodec(sdpOrAv,unwantedCodec));}function retainCandidates(sdpOrMedia,allowedTransportTypes){var mediaDescriptions=sdpOrMedia instanceof Sdp$1?sdpOrMedia.media:[sdpOrMedia];var filtered=false;mediaDescriptions.forEach(media=>{media.iceInfo.candidates=media.iceInfo.candidates.filter(candidate=>{if(allowedTransportTypes.includes(candidate.transport.toLowerCase())){return true;}filtered=true;return false;});});return filtered;}function hasCodec(codecName,mLine){return [...mLine.codecs.values()].some(ci=>{var _a;return ((_a=ci.name)===null||_a===void 0?void 0:_a.toLowerCase())===codecName.toLowerCase();});}var commonjsGlobal=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global$1!=='undefined'?global$1:typeof self!=='undefined'?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default')?x['default']:x;}var es5={exports:{}};(function(module,exports){!function(e,t){module.exports=t();}(commonjsGlobal,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports;}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n});},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e){r.d(n,i,function(t){return e[t];}.bind(null,i));}return n;},r.n=function(e){var t=e&&e.__esModule?function(){return e.default;}:function(){return e;};return r.d(t,"a",t),t;},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t);},r.p="",r(r.s=90);}({17:function _(e,t,r){t.__esModule=!0,t.default=void 0;var n=r(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&r[1]||"";},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||"";},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r;},e.getWindowsVersionName=function(e){switch(e){case"NT":return "NT";case"XP":return "XP";case"NT 5.0":return "2000";case"NT 5.1":return "XP";case"NT 5.2":return "2003";case"NT 6.0":return "Vista";case"NT 6.1":return "7";case"NT 6.2":return "8";case"NT 6.3":return "8.1";case"NT 10.0":return "10";default:return;}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map(function(e){return parseInt(e,10)||0;});if(t.push(0),10===t[0])switch(t[1]){case 5:return "Leopard";case 6:return "Snow Leopard";case 7:return "Lion";case 8:return "Mountain Lion";case 9:return "Mavericks";case 10:return "Yosemite";case 11:return "El Capitan";case 12:return "Sierra";case 13:return "High Sierra";case 14:return "Mojave";case 15:return "Catalina";default:return;}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map(function(e){return parseInt(e,10)||0;});if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0;},e.getVersionPrecision=function(e){return e.split(".").length;},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var i=e.getVersionPrecision(t),s=e.getVersionPrecision(r),a=Math.max(i,s),o=0,u=e.map([t,r],function(t){var r=a-e.getVersionPrecision(t),n=t+new Array(r+1).join(".0");return e.map(n.split("."),function(e){return new Array(20-e.length).join("0")+e;}).reverse();});for(n&&(o=a-Math.min(i,s)),a-=1;a>=o;){if(u[0][a]>u[1][a])return 1;if(u[0][a]===u[1][a]){if(a===o)return 0;a-=1;}else if(u[0][a]<u[1][a])return -1;}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1){n.push(t(e[r]));}return n;},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var i=e[r];if(t(i,r))return i;}},e.assign=function(e){for(var t,r,n=e,i=arguments.length,s=new Array(i>1?i-1:0),a=1;a<i;a++){s[a-1]=arguments[a];}if(Object.assign)return Object.assign.apply(Object,[e].concat(s));var o=function o(){var e=s[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach(function(t){n[t]=e[t];});};for(t=0,r=s.length;t<r;t+=1){o();}return e;},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e];},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||"";},e;}();t.default=i,e.exports=t.default;},18:function _(e,t,r){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0;t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"};t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"};t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"};t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"};t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};},90:function _(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},s=r(18);function a(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n);}}var o=function(){function e(){}var t,r,n;return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t);},e.parse=function(e){return new i.default(e).getResult();},t=e,n=[{key:"BROWSER_MAP",get:function get(){return s.BROWSER_MAP;}},{key:"ENGINE_MAP",get:function get(){return s.ENGINE_MAP;}},{key:"OS_MAP",get:function get(){return s.OS_MAP;}},{key:"PLATFORMS_MAP",get:function get(){return s.PLATFORMS_MAP;}}],(r=null)&&a(t.prototype,r),n&&a(t,n),e;}();t.default=o,e.exports=t.default;},91:function _(e,t,r){t.__esModule=!0,t.default=void 0;var n=u(r(92)),i=u(r(93)),s=u(r(94)),a=u(r(95)),o=u(r(17));function u(e){return e&&e.__esModule?e:{default:e};}var d=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse();}var t=e.prototype;return t.getUA=function(){return this._ua;},t.test=function(e){return e.test(this._ua);},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=o.default.find(n.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t);});throw new Error("Browser's test function is not valid");});return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser;},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser();},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||"";},t.getBrowserVersion=function(){return this.getBrowser().version;},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS();},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=o.default.find(i.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t);});throw new Error("Browser's test function is not valid");});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os;},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||"";},t.getOSVersion=function(){return this.getOS().version;},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform();},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||"";},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=o.default.find(s.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t);});throw new Error("Browser's test function is not valid");});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform;},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine();},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||"";},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=o.default.find(a.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t);});throw new Error("Browser's test function is not valid");});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine;},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this;},t.getResult=function(){return o.default.assign({},this.parsedResult);},t.satisfies=function(e){var t=this,r={},n=0,i={},s=0;if(Object.keys(e).forEach(function(t){var a=e[t];"string"==typeof a?(i[t]=a,s+=1):"object"==typeof a&&(r[t]=a,n+=1);}),n>0){var a=Object.keys(r),u=o.default.find(a,function(e){return t.isOS(e);});if(u){var d=this.satisfies(r[u]);if(void 0!==d)return d;}var c=o.default.find(a,function(e){return t.isPlatform(e);});if(c){var f=this.satisfies(r[c]);if(void 0!==f)return f;}}if(s>0){var l=Object.keys(i),h=o.default.find(l,function(e){return t.isBrowser(e,!0);});if(void 0!==h)return this.compareVersion(i[h]);}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=o.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r;},t.compareVersion=function(e){var t=[0],r=e,n=!1,i=this.getBrowserVersion();if("string"==typeof i)return ">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(o.default.compareVersions(i,r,n))>-1;},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase();},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase();},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase();},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e);},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some(function(e){return t.is(e);});},e;}();t.default=d,e.exports=t.default;},92:function _(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n};var s=/version\/(\d+(\.?_?\d+)+)/i,a=[{test:[/googlebot/i],describe:function describe(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/opera/i],describe:function describe(e){var t={name:"Opera"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/opr\/|opios/i],describe:function describe(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/SamsungBrowser/i],describe:function describe(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/Whale/i],describe:function describe(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/MZBrowser/i],describe:function describe(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/focus/i],describe:function describe(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/swing/i],describe:function describe(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/coast/i],describe:function describe(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function describe(e){var t={name:"Opera Touch"},r=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/yabrowser/i],describe:function describe(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/ucbrowser/i],describe:function describe(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/Maxthon|mxios/i],describe:function describe(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/epiphany/i],describe:function describe(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/puffin/i],describe:function describe(e){var t={name:"Puffin"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/sleipnir/i],describe:function describe(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/k-meleon/i],describe:function describe(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/micromessenger/i],describe:function describe(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/qqbrowser/i],describe:function describe(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/msie|trident/i],describe:function describe(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/\sedg\//i],describe:function describe(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/edg([ea]|ios)/i],describe:function describe(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/vivaldi/i],describe:function describe(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/seamonkey/i],describe:function describe(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/sailfish/i],describe:function describe(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t;}},{test:[/silk/i],describe:function describe(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/phantom/i],describe:function describe(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/slimerjs/i],describe:function describe(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function describe(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/(web|hpw)[o0]s/i],describe:function describe(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/bada/i],describe:function describe(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/tizen/i],describe:function describe(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/qupzilla/i],describe:function describe(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/firefox|iceweasel|fxios/i],describe:function describe(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/electron/i],describe:function describe(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/MiuiBrowser/i],describe:function describe(e){var t={name:"Miui"},r=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/chromium/i],describe:function describe(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/chrome|crios|crmo/i],describe:function describe(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/GSA/i],describe:function describe(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:function test(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r;},describe:function describe(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/playstation 4/i],describe:function describe(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/safari|applewebkit/i],describe:function describe(e){var t={name:"Safari"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t;}},{test:[/.*/i],describe:function describe(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return {name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)};}}];t.default=a,e.exports=t.default;},93:function _(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var a=[{test:[/Roku\/DVP/],describe:function describe(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return {name:s.OS_MAP.Roku,version:t};}},{test:[/windows phone/i],describe:function describe(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return {name:s.OS_MAP.WindowsPhone,version:t};}},{test:[/windows /i],describe:function describe(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return {name:s.OS_MAP.Windows,version:t,versionName:r};}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function describe(e){var t={name:s.OS_MAP.iOS},r=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t;}},{test:[/macintosh/i],describe:function describe(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),n={name:s.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n;}},{test:[/(ipod|iphone|ipad)/i],describe:function describe(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return {name:s.OS_MAP.iOS,version:t};}},{test:function test(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r;},describe:function describe(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),n={name:s.OS_MAP.Android,version:t};return r&&(n.versionName=r),n;}},{test:[/(web|hpw)[o0]s/i],describe:function describe(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:s.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r;}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function describe(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return {name:s.OS_MAP.BlackBerry,version:t};}},{test:[/bada/i],describe:function describe(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return {name:s.OS_MAP.Bada,version:t};}},{test:[/tizen/i],describe:function describe(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return {name:s.OS_MAP.Tizen,version:t};}},{test:[/linux/i],describe:function describe(){return {name:s.OS_MAP.Linux};}},{test:[/CrOS/],describe:function describe(){return {name:s.OS_MAP.ChromeOS};}},{test:[/PlayStation 4/],describe:function describe(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return {name:s.OS_MAP.PlayStation4,version:t};}}];t.default=a,e.exports=t.default;},94:function _(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var a=[{test:[/googlebot/i],describe:function describe(){return {type:"bot",vendor:"Google"};}},{test:[/huawei/i],describe:function describe(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r;}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function describe(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"};}},{test:[/ipad/i],describe:function describe(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"};}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function describe(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"};}},{test:[/kftt build/i],describe:function describe(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"};}},{test:[/silk/i],describe:function describe(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"};}},{test:[/tablet(?! pc)/i],describe:function describe(){return {type:s.PLATFORMS_MAP.tablet};}},{test:function test(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r;},describe:function describe(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return {type:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:t};}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function describe(){return {type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"};}},{test:[/[^-]mobi/i],describe:function describe(){return {type:s.PLATFORMS_MAP.mobile};}},{test:function test(e){return "blackberry"===e.getBrowserName(!0);},describe:function describe(){return {type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"};}},{test:function test(e){return "bada"===e.getBrowserName(!0);},describe:function describe(){return {type:s.PLATFORMS_MAP.mobile};}},{test:function test(e){return "windows phone"===e.getBrowserName();},describe:function describe(){return {type:s.PLATFORMS_MAP.mobile,vendor:"Microsoft"};}},{test:function test(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return "android"===e.getOSName(!0)&&t>=3;},describe:function describe(){return {type:s.PLATFORMS_MAP.tablet};}},{test:function test(e){return "android"===e.getOSName(!0);},describe:function describe(){return {type:s.PLATFORMS_MAP.mobile};}},{test:function test(e){return "macos"===e.getOSName(!0);},describe:function describe(){return {type:s.PLATFORMS_MAP.desktop,vendor:"Apple"};}},{test:function test(e){return "windows"===e.getOSName(!0);},describe:function describe(){return {type:s.PLATFORMS_MAP.desktop};}},{test:function test(e){return "linux"===e.getOSName(!0);},describe:function describe(){return {type:s.PLATFORMS_MAP.desktop};}},{test:function test(e){return "playstation 4"===e.getOSName(!0);},describe:function describe(){return {type:s.PLATFORMS_MAP.tv};}},{test:function test(e){return "roku"===e.getOSName(!0);},describe:function describe(){return {type:s.PLATFORMS_MAP.tv};}}];t.default=a,e.exports=t.default;},95:function _(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var a=[{test:function test(e){return "microsoft edge"===e.getBrowserName(!0);},describe:function describe(e){if(/\sedg\//i.test(e))return {name:s.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return {name:s.ENGINE_MAP.EdgeHTML,version:t};}},{test:[/trident/i],describe:function describe(e){var t={name:s.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:function test(e){return e.test(/presto/i);},describe:function describe(e){var t={name:s.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:function test(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r;},describe:function describe(e){var t={name:s.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}},{test:[/(apple)?webkit\/537\.36/i],describe:function describe(){return {name:s.ENGINE_MAP.Blink};}},{test:[/(apple)?webkit/i],describe:function describe(e){var t={name:s.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t;}}];t.default=a,e.exports=t.default;}});});})(es5);var Bowser=/*@__PURE__*/getDefaultExportFromCjs(es5.exports);var BrowserName;(function(BrowserName){BrowserName["CHROME"]="Chrome";BrowserName["FIREFOX"]="Firefox";BrowserName["EDGE"]="Microsoft Edge";BrowserName["SAFARI"]="Safari";})(BrowserName||(BrowserName={}));class BrowserInfo{static getBrowserDetails(){return this.browser.getBrowser();}static getOSDetails(){return this.browser.getOS();}static getPlatformDetails(){return this.browser.getPlatform();}static getEngineDetails(){return this.browser.getEngine();}static isChrome(){return this.browser.getBrowserName()===BrowserName.CHROME;}static isFirefox(){return this.browser.getBrowserName()===BrowserName.FIREFOX;}static isEdge(){return this.browser.getBrowserName()===BrowserName.EDGE;}static isSafari(){return this.browser.getBrowserName()===BrowserName.SAFARI;}static isVersionGreaterThan(version){var browserName=this.browser.getBrowserName();var checkTree={[browserName]:">".concat(version)};return this.browser.satisfies(checkTree);}static isVersionGreaterThanOrEqualTo(version){var browserName=this.browser.getBrowserName();var checkTree={[browserName]:">=".concat(version)};return this.browser.satisfies(checkTree);}static isVersionLessThan(version){var browserName=this.browser.getBrowserName();var checkTree={[browserName]:"<".concat(version)};return this.browser.satisfies(checkTree);}static isVersionLessThanOrEqualTo(version){var browserName=this.browser.getBrowserName();var checkTree={[browserName]:"<=".concat(version)};return this.browser.satisfies(checkTree);}static isSubVersionOf(version){var browserName=this.browser.getBrowserName();var checkTree={[browserName]:"~".concat(version)};return this.browser.satisfies(checkTree);}}BrowserInfo.browser=Bowser.getParser(window.navigator.userAgent);var CapabilityState;(function(CapabilityState){CapabilityState["NOT_CAPABLE"]="not capable";CapabilityState["CAPABLE"]="capable";CapabilityState["UNKNOWN"]="unknown";})(CapabilityState||(CapabilityState={}));var simulcastMaxFrameSizes={0:'240',1:'2304',2:'8160'};class JmpLine extends Line$1{constructor(versions){super();this.versions=versions;}static fromSdpLine(line){if(!JmpLine.regex.test(line)){return undefined;}var tokens=line.match(JmpLine.regex);var versions=tokens[1].split(',').filter(v=>v.length);return new JmpLine(versions);}toSdpLine(){return "a=jmp:".concat(this.versions.join(','));}}JmpLine.regex=/^jmp:((?:v\d+,?)+)/;class JmpStreamIdModeLine extends Line$1{constructor(streamIdMode){super();this.streamIdMode=streamIdMode;}static fromSdpLine(line){if(!JmpStreamIdModeLine.regex.test(line)){return undefined;}var tokens=line.match(JmpStreamIdModeLine.regex);var mode=tokens[1];return new JmpStreamIdModeLine(mode);}toSdpLine(){return "a=jmp-stream-id-mode:".concat(this.streamIdMode);}}JmpStreamIdModeLine.regex=/^jmp-stream-id-mode:(MID-RID|SSRC)$/;class JmpSourceLine extends Line$1{constructor(source,csi){super();this.source=source;this.csi=csi;}static fromSdpLine(line){if(!JmpSourceLine.regex.test(line)){return undefined;}var tokens=line.match(JmpSourceLine.regex);var source=tokens[1];var csi=tokens[2];return new JmpSourceLine(source,csi);}toSdpLine(){var line="a=jmp-source:".concat(this.source);if(this.csi){line+=" csi=".concat(this.csi);}return line;}}JmpSourceLine.regex=new RegExp("^jmp-source:(".concat(ANY_NON_WS$1,") (?:csi=(").concat(ANY_NON_WS$1,"))"));DefaultSdpGrammar$1.addParser('a',JmpLine.fromSdpLine);DefaultSdpGrammar$1.addParser('a',JmpSourceLine.fromSdpLine);DefaultSdpGrammar$1.addParser('a',JmpStreamIdModeLine.fromSdpLine);function deepCopy(source){return Array.isArray(source)?source.map(item=>deepCopy(item)):source instanceof Map?new Map(source):source instanceof Date?new Date(source.getTime()):source&&typeof source==='object'?Object.getOwnPropertyNames(source).reduce((o,prop)=>{Object.defineProperty(o,prop,Object.getOwnPropertyDescriptor(source,prop));o[prop]=deepCopy(source[prop]);return o;},Object.create(Object.getPrototypeOf(source))):source;}function matchMediaDescriptionsInAnswer(parsedOffer,parsedAnswer){parsedAnswer.session.groups=parsedOffer.session.groups;parsedAnswer.media=parsedOffer.media.map(offerMediaDescription=>{if(!offerMediaDescription.mid){logErrorAndThrow(WcmeErrorType.OFFER_ANSWER_MISMATCH,"Named media groups can only be set for audio.");}var answerMediaDescription=parsedAnswer.media.find(m=>m.mid===offerMediaDescription.mid);if(answerMediaDescription){return answerMediaDescription;}if(!(offerMediaDescription instanceof AvMediaDescription$1)){logErrorAndThrow(WcmeErrorType.OFFER_ANSWER_MISMATCH,"Answer is missing a non-AV media description for MID ".concat(offerMediaDescription.mid,"."));}var startingMediaDescription=parsedAnswer.avMedia.find(m=>m.type===offerMediaDescription.type);if(!startingMediaDescription){logErrorAndThrow(WcmeErrorType.OFFER_ANSWER_MISMATCH,"Answer has no media description of type ".concat(offerMediaDescription.type,", can't generate synthetic answer media description for MID ").concat(offerMediaDescription.mid,"."));}var fakeCorrespondingDescription=deepCopy(startingMediaDescription);fakeCorrespondingDescription.mid=offerMediaDescription.mid;fakeCorrespondingDescription.simulcast=undefined;if(offerMediaDescription.direction==='sendrecv'||offerMediaDescription.direction==='sendonly'){fakeCorrespondingDescription.direction='recvonly';}if(offerMediaDescription.direction==='recvonly'){fakeCorrespondingDescription.direction='sendonly';}return fakeCorrespondingDescription;});}function setupBundle(parsedSdp,bundlePolicy,midMap){if(bundlePolicy==='max-compat'){var audioMainMids=midMap.get(MediaType.AudioMain);var videoMainMids=midMap.get(MediaType.VideoMain);var audioContentMids=midMap.get(MediaType.AudioSlides);var videoContentMids=midMap.get(MediaType.VideoSlides);parsedSdp.session.groups.splice(0,parsedSdp.session.groups.length);if(audioMainMids){parsedSdp.session.groups.push(new BundleGroupLine$1(audioMainMids));}if(videoMainMids){parsedSdp.session.groups.push(new BundleGroupLine$1(videoMainMids));}if(audioContentMids){parsedSdp.session.groups.push(new BundleGroupLine$1(audioContentMids));}if(videoContentMids){parsedSdp.session.groups.push(new BundleGroupLine$1(videoContentMids));}}}function filterRecvOnlyMediaDescriptions(parsedSdp){var filteredMids=[];parsedSdp.media=parsedSdp.media.filter(media=>{if(media instanceof ApplicationMediaDescription$1||media instanceof AvMediaDescription$1&&media.direction!=='recvonly'){filteredMids.push(media.mid);return true;}return false;});parsedSdp.session.groups.forEach(g=>{g.mids=g.mids.filter(m=>filteredMids.includes(m));});}function injectContentType(mediaDescription,mediaContent){if(mediaContent===MediaContent.Slides){mediaDescription.addLine(new ContentLine$1(['slides']));}}function injectJmpAttributes(mediaDescription,csi,streamSignalingMode){if(!mediaDescription.otherLines.find(line=>line instanceof JmpLine)){mediaDescription.addLine(new JmpLine(['v1']));}if(!mediaDescription.otherLines.find(line=>line instanceof JmpSourceLine)){mediaDescription.addLine(new JmpSourceLine(mediaDescription.mid,csi.toString()));}if(!mediaDescription.otherLines.find(line=>line instanceof JmpStreamIdModeLine)){mediaDescription.addLine(new JmpStreamIdModeLine(streamSignalingMode));}}function injectDummyCandidates(mediaDescription){if(mediaDescription.iceInfo.candidates.length===0){mediaDescription.addLine(new CandidateLine$1('dummy1',1,'udp',3,'0.0.0.0',9,'host'));mediaDescription.addLine(new CandidateLine$1('dummy2',1,'tcp',2,'0.0.0.0',9,'host'));mediaDescription.addLine(new CandidateLine$1('dummy3',1,'udp',1,'0.0.0.0',9,'relay'));}}function removeMidRidExtensions(mediaDescription){mediaDescription.extMaps.forEach((extMapLine,extId,extMap)=>{if(/^urn:ietf:params:rtp-hdrext:sdes:(?:mid|rtp-stream-id|repaired-rtp-stream-id)$/.test(extMapLine.uri)){extMap.delete(extId);}});}function addVlaExtension(mediaDescription){var vlaExtensionUri='http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00';if(![...mediaDescription.extMaps.values()].some(extMapLine=>extMapLine.uri===vlaExtensionUri)){mediaDescription.addExtension({uri:vlaExtensionUri});}}function applyFormatParameters(mediaDescription,paramsMap){paramsMap.forEach((value,param)=>{[...mediaDescription.codecs.values()].filter(ci=>ci.name==='H264'||ci.name==='opus').forEach(ci=>{if(value===null){ci.fmtParams.delete(param);}else {ci.fmtParams.set(param,"".concat(value));}});});}function generateSsrc(){return Math.floor(Math.random()*0xffffffff)+1;}class EgressSdpMunger{constructor(){this.streamIds=[];this.customCodecParameters=new Map();}reset(){this.streamIds=[];}mungeLocalDescription(mediaDescription,simulcastEnabled,rtxEnabled,twccDisabled){var _a;retainCodecs(mediaDescription,['h264','opus','rtx']);if(mediaDescription.codecs.size===0){logErrorAndThrow(WcmeErrorType.SDP_MUNGE_MISSING_CODECS,"No codecs present in m-line with MID ".concat(mediaDescription.mid," after filtering."));}mediaDescription.bandwidth=new BandwidthLine$1('TIAS',20000000);mediaDescription.rids=[];mediaDescription.simulcast=undefined;removeMidRidExtensions(mediaDescription);if(simulcastEnabled){addVlaExtension(mediaDescription);}var numStreams=simulcastEnabled?3:1;if(!this.streamIds.length){if(mediaDescription.ssrcs.length){var ssrcs=[...new Set(mediaDescription.ssrcs.map(ssrcLine=>ssrcLine.ssrcId))];mediaDescription.ssrcGroups.forEach(sg=>{if(!sg.ssrcs.every(ssrc=>ssrcs.includes(ssrc))){logErrorAndThrow(WcmeErrorType.SDP_MUNGE_FAILED,'SSRC present in SSRC groups is missing from SSRC lines.');}});var rtxSsrcGroups=mediaDescription.ssrcGroups.filter(sg=>sg.semantics==='FID');if(rtxSsrcGroups.length&&rtxSsrcGroups.length!==numStreams){logErrorAndThrow(WcmeErrorType.SDP_MUNGE_FAILED,"Expected ".concat(numStreams," RTX SSRC groups, got ").concat(rtxSsrcGroups.length,"."));}rtxSsrcGroups.forEach(sg=>{this.streamIds.push({ssrc:sg.ssrcs[0],rtxSsrc:sg.ssrcs[1]});});var simulcastSsrcs=(_a=mediaDescription.ssrcGroups.find(sg=>sg.semantics==='SIM'))===null||_a===void 0?void 0:_a.ssrcs;if(simulcastSsrcs){if(simulcastSsrcs.length!==numStreams||!this.streamIds.every(streamId=>simulcastSsrcs.includes(streamId.ssrc))){logErrorAndThrow(WcmeErrorType.SDP_MUNGE_FAILED,'SSRCs in simulcast SSRC group do not match primary SSRCs in RTX SSRC groups.');}this.streamIds.sort((a,b)=>simulcastSsrcs.indexOf(a.ssrc)-simulcastSsrcs.indexOf(b.ssrc));}else if(rtxSsrcGroups.length>1){logErrorAndThrow(WcmeErrorType.SDP_MUNGE_FAILED,'Multiple RTX SSRC groups but no simulcast SSRC group found.');}if(!this.streamIds.length){this.streamIds.push({ssrc:ssrcs[0]});}}else {[...Array(numStreams).keys()].forEach(()=>{var newStreamId={ssrc:generateSsrc()};if(rtxEnabled){newStreamId.rtxSsrc=generateSsrc();}this.streamIds.push(newStreamId);});}}mediaDescription.ssrcs=[];mediaDescription.ssrcGroups=[];this.streamIds.forEach(streamId=>{var rtpSsrc=streamId.ssrc;mediaDescription.addLine(new SsrcLine$1(rtpSsrc,'cname',"".concat(rtpSsrc,"-cname")));mediaDescription.addLine(new SsrcLine$1(rtpSsrc,'msid','-','1'));if(rtxEnabled){var rtxSsrc=streamId.rtxSsrc;mediaDescription.addLine(new SsrcLine$1(rtxSsrc,'cname',"".concat(rtpSsrc,"-cname")));mediaDescription.addLine(new SsrcLine$1(rtxSsrc,'msid','-','1'));mediaDescription.addLine(new SsrcGroupLine$1('FID',[rtpSsrc,rtxSsrc]));}});if(simulcastEnabled){mediaDescription.addLine(new SsrcGroupLine$1('SIM',this.streamIds.map(streamId=>streamId.ssrc)));}applyFormatParameters(mediaDescription,this.customCodecParameters);if(twccDisabled){disableTwcc(mediaDescription);}}mungeLocalDescriptionForRemoteServer(mediaDescription,mediaContent,csi){injectContentType(mediaDescription,mediaContent);injectJmpAttributes(mediaDescription,csi,'SSRC');injectDummyCandidates(mediaDescription);if(mediaDescription.type==='video'){var ssrcGroup=mediaDescription.ssrcGroups.find(sg=>sg.semantics==='SIM');if(ssrcGroup){ssrcGroup.ssrcs.forEach((ssrc,index)=>{mediaDescription.addLine(new SsrcLine$1(ssrc,'fmtp',"* max-fs=".concat(simulcastMaxFrameSizes[index])));});}}}mungeRemoteDescription(mediaDescription){if(retainCandidates(mediaDescription,['udp','tcp'])){logger.log("Some unsupported remote candidates have been removed from mid ".concat(mediaDescription.mid));}[...mediaDescription.codecs.values()].forEach(ci=>{ci.fmtParams.set('x-google-start-bitrate','60000');});}getSenderIds(){return this.streamIds;}getEncodingIndexForStreamId(streamId){return this.streamIds.findIndex(currStreamId=>compareStreamIds(currStreamId,streamId));}setCodecParameters(parameters){Object.entries(parameters).forEach(_ref4=>{var[param,value]=_ref4;this.customCodecParameters.set(param,value);});}deleteCodecParameters(parameters){parameters.forEach(param=>{this.customCodecParameters.set(param,null);});}}var events$1={exports:{}};var R$1=typeof Reflect==='object'?Reflect:null;var ReflectApply$1=R$1&&typeof R$1.apply==='function'?R$1.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args);};var ReflectOwnKeys$1;if(R$1&&typeof R$1.ownKeys==='function'){ReflectOwnKeys$1=R$1.ownKeys;}else if(Object.getOwnPropertySymbols){ReflectOwnKeys$1=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));};}else {ReflectOwnKeys$1=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target);};}function ProcessEmitWarning$1(warning){if(console&&console.warn)console.warn(warning);}var NumberIsNaN$1=Number.isNaN||function NumberIsNaN(value){return value!==value;};function EventEmitter$3(){EventEmitter$3.init.call(this);}events$1.exports=EventEmitter$3;events$1.exports.once=once$2;// Backwards-compat with node 0.10.x
|
|
3795
3826
|
EventEmitter$3.EventEmitter=EventEmitter$3;EventEmitter$3.prototype._events=undefined;EventEmitter$3.prototype._eventsCount=0;EventEmitter$3.prototype._maxListeners=undefined;// By default EventEmitters will print a warning if more than 10 listeners are
|
|
@@ -5814,7 +5845,7 @@ var{hasOwnProperty}=Object.prototype;for(var i=0;i<mapResults.length;i++){if(map
|
|
|
5814
5845
|
* // arg1 now equals 'three'
|
|
5815
5846
|
* callback(null, 'done');
|
|
5816
5847
|
* }
|
|
5817
|
-
*/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 OfferAnswerType;(function(OfferAnswerType){OfferAnswerType[OfferAnswerType["LocalOnly"]=0]="LocalOnly";OfferAnswerType[OfferAnswerType["Remote"]=1]="Remote";})(OfferAnswerType||(OfferAnswerType={}));class SendOnlyTransceiver extends Transceiver{constructor(rtcRtpTransceiver,mid,csi,munger,mediaType){super(rtcRtpTransceiver,mid);this.rtxEnabled=false;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.csi=csi;this.direction='sendrecv';this.handleTrackChange=this.handleTrackChange.bind(this);this.handleStreamConstraintsChange=this.handleStreamConstraintsChange.bind(this);this.handleStreamMuteStateChange=this.handleStreamMuteStateChange.bind(this);this.munger=munger;this.mediaType=mediaType;}replaceSenderSource(stream){var _a,_b;return __awaiter$1(this,void 0,void 0,function*(){var trackOrNull=(_a=stream===null||stream===void 0?void 0:stream.outputStream.getTracks()[0])!==null&&_a!==void 0?_a:null;if(((_b=this.sender.track)===null||_b===void 0?void 0:_b.id)!==(trackOrNull===null||trackOrNull===void 0?void 0:trackOrNull.id)){yield this.sender.replaceTrack(trackOrNull);if(trackOrNull){logger.log("Sender source for ".concat(this.mediaType," replaced with track ID ").concat(trackOrNull.id));}else {logger.log("Sender source for ".concat(this.mediaType," set to null, sender stopped"));}}});}handleTrackChange(){return __awaiter$1(this,void 0,void 0,function*(){if(this.requested){yield this.replaceSenderSource(this.publishedStream);}});}handleStreamConstraintsChange(){return __awaiter$1(this,void 0,void 0,function*(){yield this.updateSendParameters(this.requestedIdEncodingParamsMap);});}handleStreamMuteStateChange(){this.streamMuteStateChange.emit();}get requested(){return this.requestedIdEncodingParamsMap.size>0;}replaceTransceiver(newRtcRtpTransceiver){var _super=Object.create(null,{replaceTransceiver:{get:()=>super.replaceTransceiver}});return __awaiter$1(this,void 0,void 0,function*(){_super.replaceTransceiver.call(this,newRtcRtpTransceiver);newRtcRtpTransceiver.direction=this.direction;if(this.requested){yield this.replaceSenderSource(this.publishedStream);}});}replacePublishedStream(newStream){return __awaiter$1(this,void 0,void 0,function*(){var oldStream=this.publishedStream;oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(StreamEventNames.MuteStateChange,this.handleStreamMuteStateChange);if(this.requested){yield this.replaceSenderSource(newStream);}this.publishedStream=newStream;newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);newStream===null||newStream===void 0?void 0:newStream.on(StreamEventNames.MuteStateChange,this.handleStreamMuteStateChange);if(!oldStream&&newStream&&!newStream.muted||oldStream&&!newStream&&!oldStream.muted){this.streamPublishStateChange.emit();}else if((oldStream===null||oldStream===void 0?void 0:oldStream.muted)!==(newStream===null||newStream===void 0?void 0:newStream.muted)){this.streamMuteStateChange.emit();}});}setNamedMediaGroups(namedMediaGroups){if(this.mediaType!==MediaType.AudioMain){logErrorAndThrow(WcmeErrorType.SET_NMG_FAILED,"Named media groups can only be set for audio.");}this.namedMediaGroups=namedMediaGroups;this.namedMediaGroupsChange.emit();}publishStream(stream){return this.replacePublishedStream(stream);}unpublishStream(){return this.replacePublishedStream();}get active(){return this._rtcRtpTransceiver.direction==='sendrecv';}set active(enabled){this.direction=enabled?'sendrecv':'inactive';this._rtcRtpTransceiver.direction=this.direction;if(this._rtcRtpTransceiver.direction!==this._rtcRtpTransceiver.currentDirection){this.negotiationNeeded.emit(OfferAnswerType.Remote);}}getStats(){return this.sender.getStats();}updateSendParameters(requestedIdEncodingParamsMap){return __awaiter$1(this,void 0,void 0,function*(){return this.updateSendParametersQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var requested=requestedIdEncodingParamsMap.size>0;if(this.requested!==requested){yield this.replaceSenderSource(requested?this.publishedStream:null);}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);this.requestedIdEncodingParamsMap=requestedIdEncodingParamsMap;}));});}isSimulcastEnabled(){var params=this.sender.getParameters();return params.encodings.length>1;}mungeLocalDescription(mediaDescription){this.munger.mungeLocalDescription(mediaDescription,this.isSimulcastEnabled(),this.rtxEnabled,this.twccDisabled);}mungeLocalDescriptionForRemoteServer(mediaDescription){this.munger.mungeLocalDescriptionForRemoteServer(mediaDescription,getMediaContent(this.mediaType),this.csi);}mungeRemoteDescription(mediaDescription){this.munger.mungeRemoteDescription(mediaDescription);}get senderIds(){return this.munger.getSenderIds();}get numActiveSimulcastLayers(){var _a;if(getMediaFamily(this.mediaType)===MediaFamily.Video){return (_a=this.publishedStream)===null||_a===void 0?void 0:_a.getNumActiveSimulcastLayers();}return this.publishedStream?0:undefined;}getEncodingIndexForStreamId(id){return this.munger.getEncodingIndexForStreamId(id);}resetSdpMunger(){this.munger.reset();}setCodecParameters(parameters){this.munger.setCodecParameters(parameters);this.negotiationNeeded.emit(OfferAnswerType.LocalOnly);}deleteCodecParameters(parameters){this.munger.deleteCodecParameters(parameters);this.negotiationNeeded.emit(OfferAnswerType.LocalOnly);}}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);}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);});}}class StatsManager{constructor(statsGetter){var statsPreprocessor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:()=>__awaiter$1(this,void 0,void 0,function*(){});this.statsGetter=statsGetter;this.statsPreProcessor=statsPreprocessor;}getStats(){return __awaiter$1(this,void 0,void 0,function*(){var statsReport=yield this.statsGetter();var statsMap=new Map();statsReport.forEach((stats,key)=>statsMap.set(key,stats));yield this.statsPreProcessor(statsMap);return statsMap;});}}var organizeTransceiverStats=(sendTransceivers,recvTransceivers)=>__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(_ref6=>{var[mediaType,transceiver]=_ref6;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(mediaType===MediaType.AudioMain){result.audio.senders.push(item);}if(mediaType===MediaType.VideoMain){result.video.senders.push(item);}if(mediaType===MediaType.AudioSlides){result.screenShareAudio.senders.push(item);}if(mediaType===MediaType.VideoSlides){result.screenShareVideo.senders.push(item);}});}));yield Promise.all([...recvTransceivers.entries()].map(_ref7=>{var[mediaType,transceivers]=_ref7;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,_c;var item={report:yield t.getStats(),mid:(_b=t.receiveSlot.id)===null||_b===void 0?void 0:_b.mid,csi:t.receiveSlot.currentRxCsi,currentDirection:'recvonly',localTrackLabel:(_c=t.receiveSlot.stream.getTracks()[0])===null||_c===void 0?void 0:_c.label};if(mediaType===MediaType.AudioMain){result.audio.receivers.push(item);}if(mediaType===MediaType.VideoMain){result.video.receivers.push(item);}if(mediaType===MediaType.AudioSlides){result.screenShareAudio.receivers.push(item);}if(mediaType===MediaType.VideoSlides){result.screenShareVideo.receivers.push(item);}})));});}));return result;});function toMediaStreamTrackKind(mediaType){return [MediaType.VideoMain,MediaType.VideoSlides].includes(mediaType)?MediaStreamTrackKind.Video:MediaStreamTrackKind.Audio;}function webRtcVideoContentHintToJmpVideoContentHint(hint){if(hint==='motion'){return 'motion';}if(hint==='detail'){return 'sharpness';}return undefined;}var MultistreamConnectionEventNames;(function(MultistreamConnectionEventNames){MultistreamConnectionEventNames["VideoSourceCountUpdate"]="video-source-count-update";MultistreamConnectionEventNames["AudioSourceCountUpdate"]="audio-source-count-update";MultistreamConnectionEventNames["ActiveSpeakerNotification"]="active-speaker-notification";MultistreamConnectionEventNames["ConnectionStateUpdate"]="connection-state-update";MultistreamConnectionEventNames["NegotiationNeeded"]="negotiation-needed";})(MultistreamConnectionEventNames||(MultistreamConnectionEventNames={}));var defaultMultistreamConnectionOptions={disableSimulcast:BrowserInfo.isFirefox(),bundlePolicy:'max-compat',iceServers:undefined,disableContentSimulcast:true,disableAudioTwcc:true};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.metricsCallback=()=>{};this.overuseUpdateCallback=()=>{};this.midPredictor=new MidPredictor();this.offerAnswerQueue=new AsyncQueue();this.currentCreateOfferId=0;this.options=Object.assign(Object.assign({},defaultMultistreamConnectionOptions),userOptions);logger.info("Creating multistream connection with options ".concat(JSON.stringify(this.options)));this.initializePeerConnection();this.overuseStateManager=new OveruseStateManager(overuseState=>this.overuseUpdateCallback(overuseState));this.overuseStateManager.start();this.statsManager=new StatsManager(()=>this.pc.getStats(),stats=>this.preProcessStats(stats));var mainSceneId=generateSceneId();var slidesSceneId=generateSceneId();var videoMainEncodingOptions=this.getVideoEncodingOptions(MediaContent.Main);var videoSlidesEncodingOptions=this.getVideoEncodingOptions(MediaContent.Slides);this.createSendTransceiver(MediaType.VideoMain,mainSceneId,videoMainEncodingOptions);this.createSendTransceiver(MediaType.AudioMain,mainSceneId);this.createSendTransceiver(MediaType.VideoSlides,slidesSceneId,videoSlidesEncodingOptions);this.createSendTransceiver(MediaType.AudioSlides,slidesSceneId);}initializePeerConnection(){var _a;(_a=this.pc)===null||_a===void 0?void 0:_a.close();this.pc=new PeerConnection({iceServers:this.options.iceServers,bundlePolicy:this.options.bundlePolicy});this.pc.on(PeerConnection.Events.ConnectionStateChange,state=>this.emit(MultistreamConnectionEventNames.ConnectionStateUpdate,state));this.attachMetricsObserver();this.createDataChannel();}getConnectionState(){return this.pc.getConnectionState();}getVideoEncodingOptions(content){var enabledSimulcast=content===MediaContent.Main?!this.options.disableSimulcast:!this.options.disableContentSimulcast;return enabledSimulcast?[{scaleResolutionDownBy:4,active:false},{scaleResolutionDownBy:2,active:false},{active:false}]:[{active:false}];}createSendTransceiver(mediaType,sceneId,sendEncodingsOptions){var rtcTransceiver;try{rtcTransceiver=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(rtcTransceiver,mid,csi,munger,mediaType);if(getMediaFamily(mediaType)===MediaFamily.Video){transceiver.rtxEnabled=true;transceiver.setCodecParameters({'max-mbps':"".concat(defaultMaxVideoEncodeMbps),'max-fs':"".concat(defaultMaxVideoEncodeFrameSize)});}transceiver.twccDisabled=getMediaFamily(mediaType)===MediaFamily.Audio?this.options.disableAudioTwcc:false;transceiver.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);});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(msg=>{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;}logger.info("Sending JMP message: ".concat(msg));this.dataChannel.send(msg);});var prevNumTotalSources=0;var prevNumLiveSources=0;jmpSession.on(JmpSessionEvents.SourceAdvertisementReceived,data=>{logger.log("SourceAdvertisement received: ".concat(JSON.stringify(data)));if(data.numTotalSources!==prevNumTotalSources||data.numLiveSources!==prevNumLiveSources){prevNumTotalSources=data.numTotalSources;prevNumLiveSources=data.numLiveSources;var eventName=getMediaFamily(mediaType)===MediaFamily.Video?MultistreamConnectionEventNames.VideoSourceCountUpdate:MultistreamConnectionEventNames.AudioSourceCountUpdate;this.emit(eventName,data.numTotalSources,data.numLiveSources,getMediaContent(mediaType));}else {logger.log('Number of sources was unchanged, ignoring message');}});jmpSession.on(JmpSessionEvents.MediaRequestStatusReceived,data=>{logger.log("MediaRequestStatus received: ".concat(JSON.stringify(data)));data.streamStates.forEach(s=>{var receiveSlot=this.getReceiveSlotById(s.id);if(!receiveSlot){logger.warn("Got MediaRequestStatus for unknown receive slot: ".concat(JSON.stringify(s.id)));return;}receiveSlot._updateSource(s.state,s.csi);});});jmpSession.on(JmpSessionEvents.MediaRequestReceived,data=>{logger.log("MediaRequest received: ".concat(JSON.stringify(data)));if(getMediaFamily(mediaType)===MediaFamily.Video){this.sendMediaRequestStatus(mediaType);}this.updateRequestedStreams(mediaType,data.requests);});jmpSession.on(JmpSessionEvents.ActiveSpeaker,data=>{this.emit(MultistreamConnectionEventNames.ActiveSpeakerNotification,data.csis);});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(_ref8=>{var{ids,policySpecificInfo,codecInfos,maxPayloadBitsPerSecond}=_ref8;var _a,_b,_c;if(ids.length>1){logErrorAndThrow(WcmeErrorType.INVALID_STREAM_REQUEST,"Stream request cannot have more than one ID.");}if(ids.length===0){return;}if(sendTransceiver.csi!==policySpecificInfo.csi){logger.warn('csi in the StreamRequest does not match');return;}var id=ids[0];var codecInfo=codecInfos[0];var streamIdsMatched=sendTransceiver.senderIds.some(validId=>compareStreamIds(id,validId));if(streamIdsMatched){var encodingIndex=sendTransceiver.getEncodingIndexForStreamId(id);if(encodingIndex!==-1){var encodingParams={maxPayloadBitsPerSecond};if(mediaFamily===MediaFamily.Video){encodingParams.maxFs=(_a=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_a===void 0?void 0:_a.maxFs;encodingParams.maxWidth=(_b=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_b===void 0?void 0:_b.maxWidth;encodingParams.maxHeight=(_c=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_c===void 0?void 0:_c.maxHeight;}requestedIdEncodingParamsMap.set(encodingIndex,encodingParams);}else {logger.warn("".concat(mediaType,": Unable to get encoding index for stream ID: ").concat(JSON.stringify(id)));}}else {logger.warn("".concat(mediaType,": Unable to find matching stream ID for requested ID: ").concat(JSON.stringify(id)));}});sendTransceiver.updateSendParameters(requestedIdEncodingParamsMap);}createDataChannel(){var dataChannel=this.pc.createDataChannel('datachannel',{ordered:false,maxRetransmits:0});dataChannel.onopen=e=>{logger.info('DataChannel opened: ',e);[...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=e=>{logger.info('DataChannel closed: ',e);};dataChannel.onerror=e=>{logger.info('DataChannel error: ',e);};this.dataChannel=dataChannel;}close(){this.sendTransceivers.forEach(t=>t.close());this.recvTransceivers.forEach(recvTransceivers=>{recvTransceivers.forEach(t=>t.close());});this.pc.close();}sendMediaRequestStatus(mediaType){var _a;if(getMediaFamily(mediaType)!==MediaFamily.Video){return;}var streamStates=this.getVideoStreamStates(mediaType);var task=()=>{var _a;(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendMediaRequestStatus(streamStates);};if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}sendSourceAdvertisement(mediaType){var _a,_b;var transceiver=this.getSendTransceiverOrThrow(mediaType);var numLiveSources=((_a=transceiver.publishedStream)===null||_a===void 0?void 0:_a.muted)===false?1:0;var task;if(getMediaFamily(mediaType)===MediaFamily.Video){var sources=this.getVideoStreamStates(mediaType);if(sources===null){return;}var contentHint;if(transceiver.publishedStream&&mediaType===MediaType.VideoSlides){contentHint=transceiver.publishedStream.contentHint;}task=()=>{var _a;(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendSourceAdvertisement(1,numLiveSources,[],webRtcVideoContentHintToJmpVideoContentHint(contentHint));};}else {task=()=>{var _a;return (_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendSourceAdvertisement(1,numLiveSources,mediaType===MediaType.AudioMain?transceiver.namedMediaGroups:[]);};}if(((_b=this.dataChannel)===null||_b===void 0?void 0:_b.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}getVideoStreamStates(mediaType){var _a;var sendTransceiver=this.getSendTransceiverOrThrow(mediaType);var published=!!sendTransceiver.publishedStream;var muted=(_a=sendTransceiver.publishedStream)===null||_a===void 0?void 0:_a.muted;return sendTransceiver.senderIds.map(id=>{var state;if(!published){state='no source';}else if(muted){state='avatar';}else {state='live';}return {id,state,csi:sendTransceiver.csi};});}createReceiveSlot(mediaType){return __awaiter$1(this,void 0,void 0,function*(){return new Promise(createReceiveSlotResolve=>{this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var rtcRtpTransceiver=this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'recvonly'});var transceiverMid=this.midPredictor.getNextMid(mediaType);var munger=new IngressSdpMunger();var recvOnlyTransceiver=new ReceiveOnlyTransceiver(rtcRtpTransceiver,transceiverMid,munger);recvOnlyTransceiver.twccDisabled=getMediaFamily(mediaType)===MediaFamily.Audio?this.options.disableAudioTwcc:false;this.recvTransceivers.set(mediaType,[...(this.recvTransceivers.get(mediaType)||[]),recvOnlyTransceiver]);if(this.pc.getRemoteDescription()){yield this.doLocalOfferAnswer();}createReceiveSlotResolve(recvOnlyTransceiver.receiveSlot);}));});});}getIngressPayloadType(mediaType,mimeType){var _a,_b,_c;var requestedMediaCodecType=mimeType.split('/')[1];var requestedMid=(_a=this.sendTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.mid;var parsedOffer=parse$1((_b=this.pc.getLocalDescription())===null||_b===void 0?void 0:_b.sdp);var parsedAnswer=parse$1((_c=this.pc.getRemoteDescription())===null||_c===void 0?void 0:_c.sdp);var senderCodecs=parsedAnswer.avMedia.filter(media=>requestedMid===media.mid).map(media=>[...media.codecs.values()]).flat().filter(ci=>ci.name===requestedMediaCodecType);var receiverCodecs=parsedOffer.avMedia.filter(media=>requestedMid===media.mid).map(media=>[...media.codecs.values()]).flat().filter(ci=>ci.name===requestedMediaCodecType);if(!senderCodecs||!receiverCodecs||senderCodecs.length===0||receiverCodecs.length===0){logErrorAndThrow(WcmeErrorType.GET_PAYLOAD_TYPE_FAILED,"Sender codecs or receiver codecs is undefined or empty.");}var senderCodec=senderCodecs[0];var targetCodec=receiverCodecs.find(receiverCodec=>{return areCodecsCompatible(senderCodec,receiverCodec);});if(!targetCodec||!targetCodec.pt){logErrorAndThrow(WcmeErrorType.GET_PAYLOAD_TYPE_FAILED,"Cannot find matching receiver codec for the given mediaType/mimeType.");}return targetCodec.pt;}createOffer(){return __awaiter$1(this,void 0,void 0,function*(){if(!this.pc.getLocalDescription()){this.midPredictor.allocateMidForDatachannel();}if(this.setAnswerResolve){logger.info('Canceling previous offer since setAnswer was never called for it');this.setAnswerResolve();this.setAnswerResolve=undefined;}var createOfferId=++this.currentCreateOfferId;return new Promise((createOfferResolve,createOfferReject)=>{this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var _a;try{var offer=yield this.pc.createOffer();if(!offer.sdp){logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,'SDP not found in offer.');}offer.sdp=this.preProcessLocalOffer(offer.sdp);yield this.pc.setLocalDescription(offer);var sdpToSend=this.prepareLocalOfferForRemoteServer((_a=this.pc.getLocalDescription())===null||_a===void 0?void 0:_a.sdp);createOfferResolve({type:'offer',sdp:sdpToSend});if(this.currentCreateOfferId>createOfferId){logger.log('Canceling previous offer since createOffer was called while it was being created');}else {yield new Promise(setAnswerResolve=>{this.setAnswerResolve=setAnswerResolve;});}}catch(error){createOfferReject(error);}}));});});}setAnswer(answer){return __awaiter$1(this,void 0,void 0,function*(){var sdp=this.preProcessRemoteAnswer(answer);if(!this.setAnswerResolve){logErrorAndThrow(WcmeErrorType.SET_ANSWER_FAILED,"Call to setAnswer without having previously called createOffer.");}logger.info('calling this.pc.setRemoteDescription()');return this.pc.setRemoteDescription({type:'answer',sdp}).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setRemoteDescription() resolved');if(this.setAnswerResolve){this.setAnswerResolve();this.setAnswerResolve=undefined;}else {logger.debug("setAnswerResolve function was cleared between setAnswer and result of setRemoteDescription");}}));});}doLocalOfferAnswer(){var _a;return __awaiter$1(this,void 0,void 0,function*(){var offer=yield this.pc.createOffer();if(!offer.sdp){logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,'SDP not found in offer.');}offer.sdp=this.preProcessLocalOffer(offer.sdp);yield this.pc.setLocalDescription(offer);var answer=this.preProcessRemoteAnswer((_a=this.pc.getRemoteDescription())===null||_a===void 0?void 0:_a.sdp);return this.pc.setRemoteDescription({type:'answer',sdp: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);parsedOffer.avMedia.filter(av=>av.direction==='sendrecv'||av.direction==='inactive').forEach(av=>{var sendTransceiver=this.getSendTransceiverByMidOrThrow(av.mid);sendTransceiver.mungeLocalDescriptionForRemoteServer(av);});parsedOffer.media.filter(media=>media instanceof ApplicationMediaDescription$1).forEach(media=>{injectDummyCandidates(media);});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;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(retainCandidates(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());}return parsedAnswer.toString();}getSendTransceiverOrThrow(mediaType){var sendTransceiver=this.sendTransceivers.get(mediaType);if(!sendTransceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find send transceiver for media type ".concat(mediaType,"."));}return sendTransceiver;}getSendTransceiverByMidOrThrow(mid){var transceiver=[...this.sendTransceivers.values()].find(t=>t.mid===mid);if(!transceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find send transceiver with MID ".concat(mid,"."));}return transceiver;}getRecvTransceiverByMidOrThrow(mid){var transceiver=[...this.recvTransceivers.values()].flat().find(t=>t.mid===mid);if(!transceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find recv transceiver with MID ".concat(mid,"."));}return transceiver;}requestMedia(mediaType,streamRequests){var _a;var task=()=>{var _a;var jmpSession=this.jmpSessions.get(mediaType);if(!jmpSession){logger.error("Unable to find jmp session for ".concat(mediaType));return;}var requestedReceiveSlotIds=[];streamRequests.forEach(sr=>{sr.receiveSlots.forEach(rs=>{if(!rs.id){logger.error("Running stream request task, but ReceiveSlot ID is missing!");return;}requestedReceiveSlotIds.push(rs.id);});});(_a=this.recvTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.forEach(transceiver=>{if(!requestedReceiveSlotIds.some(id=>compareStreamIds(id,transceiver.receiveSlot.id))){transceiver.receiveSlot._updateSource('no source',undefined);}});jmpSession.sendRequests(streamRequests.map(sr=>sr._toJmpStreamRequest()));};if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}renewPeerConnection(userOptions){if(userOptions){this.options=Object.assign(Object.assign({},this.options),userOptions);}logger.info("Renewing multistream connection with options ".concat(JSON.stringify(this.options)));this.midPredictor.reset();this.initializePeerConnection();var mainSceneId=generateSceneId();var slidesSceneId=generateSceneId();this.sendTransceivers.forEach((transceiver,mediaType)=>{var _a;var mediaContent=getMediaContent(mediaType);var sceneId=mediaContent===MediaContent.Main?mainSceneId:slidesSceneId;var mid=this.midPredictor.getNextMid(mediaType);transceiver.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'sendrecv',sendEncodings:getMediaFamily(mediaType)===MediaFamily.Video?this.getVideoEncodingOptions(mediaContent):undefined}));transceiver.mid=mid;transceiver.csi=generateCsi(getMediaFamily(mediaType),sceneId);transceiver.resetSdpMunger();(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.close();this.createJmpSession(mediaType);});this.recvTransceivers.forEach((transceivers,mediaType)=>{transceivers.forEach(t=>{var mid=this.midPredictor.getNextMid(mediaType);t.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'recvonly'}));t.mid=mid;});});}getReceiveSlotById(id){return [...this.recvTransceivers.values()].flat().map(transceiver=>transceiver.receiveSlot).find(receiveSlot=>{var receiveSlotId=receiveSlot.id||{};return Object.keys(receiveSlotId).length===Object.keys(id).length&&Object.keys(receiveSlotId).every(key=>Object.prototype.hasOwnProperty.call(id,key)&&receiveSlotId[key]===id[key]);});}getStats(){return this.statsManager.getStats();}getTransceiverStats(){return __awaiter$1(this,void 0,void 0,function*(){return organizeTransceiverStats(this.sendTransceivers,this.recvTransceivers);});}preProcessStats(stats){return __awaiter$1(this,void 0,void 0,function*(){yield Promise.all([...this.sendTransceivers.entries()].map(_ref9=>{var[mediaType,transceiver]=_ref9;return __awaiter$1(this,void 0,void 0,function*(){(yield transceiver.getStats()).forEach(senderStats=>{var _a;if(senderStats.type==='outbound-rtp'){var statsToModify=stats.get(senderStats.id);statsToModify.mid=transceiver.mid;statsToModify.csi=transceiver.csi;statsToModify.calliopeMediaType=mediaType;var trackSettings=(_a=transceiver.publishedStream)===null||_a===void 0?void 0:_a.getSettings();if(trackSettings===null||trackSettings===void 0?void 0:trackSettings.frameRate){statsToModify.targetFrameRate=trackSettings===null||trackSettings===void 0?void 0:trackSettings.frameRate;}stats.set(senderStats.id,statsToModify);}else if(senderStats.type==='media-source'){var _statsToModify=stats.get(senderStats.id);_statsToModify.calliopeMediaType=mediaType;stats.set(senderStats.id,_statsToModify);}});});}));yield Promise.all([...this.recvTransceivers.entries()].map(_ref10=>{var[mediaType,transceivers]=_ref10;return __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=>{var _a;if(receiverStats.type==='inbound-rtp'){var statsToModify=stats.get(receiverStats.id);statsToModify.mid=(_a=transceiver.receiveSlot.id)===null||_a===void 0?void 0:_a.mid;statsToModify.csi=transceiver.receiveSlot.currentRxCsi;statsToModify.calliopeMediaType=mediaType;Object.assign(statsToModify,transceiver.receiverId);stats.set(receiverStats.id,statsToModify);}});})));});}));});}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);}setMetricsCallback(callback){this.metricsCallback=callback;}setOveruseUpdateCallback(callback){this.overuseUpdateCallback=callback;}getCsiByMediaType(mediaType){var _a;return (_a=this.sendTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.csi;}getAllCsis(){return {audioMain:this.getCsiByMediaType(MediaType.AudioMain),audioSlides:this.getCsiByMediaType(MediaType.AudioSlides),videoMain:this.getCsiByMediaType(MediaType.VideoMain),videoSlides:this.getCsiByMediaType(MediaType.VideoSlides)};}}class StreamRequest{constructor(policy,policySpecificInfo,receiveSlots,maxPayloadBitsPerSecond){var codecInfos=arguments.length>4&&arguments[4]!==undefined?arguments[4]:[];this.policy=policy;this.policySpecificInfo=policySpecificInfo;this.receiveSlots=receiveSlots;this.maxPayloadBitsPerSecond=maxPayloadBitsPerSecond;this.codecInfos=codecInfos;}_toJmpStreamRequest(){return new StreamRequest$1(this.policy,this.policySpecificInfo,this.receiveSlots.map(rs=>rs.id),this.maxPayloadBitsPerSecond,this.codecInfos);}}
|
|
5848
|
+
*/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 OfferAnswerType;(function(OfferAnswerType){OfferAnswerType[OfferAnswerType["LocalOnly"]=0]="LocalOnly";OfferAnswerType[OfferAnswerType["Remote"]=1]="Remote";})(OfferAnswerType||(OfferAnswerType={}));class SendOnlyTransceiver extends Transceiver{constructor(rtcRtpTransceiver,mid,csi,munger,mediaType){super(rtcRtpTransceiver,mid);this.rtxEnabled=false;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.csi=csi;this.direction='sendrecv';this.handleTrackChange=this.handleTrackChange.bind(this);this.handleStreamConstraintsChange=this.handleStreamConstraintsChange.bind(this);this.handleStreamMuteStateChange=this.handleStreamMuteStateChange.bind(this);this.munger=munger;this.mediaType=mediaType;}replaceSenderSource(stream){var _a,_b;return __awaiter$1(this,void 0,void 0,function*(){var trackOrNull=(_a=stream===null||stream===void 0?void 0:stream.outputStream.getTracks()[0])!==null&&_a!==void 0?_a:null;if(((_b=this.sender.track)===null||_b===void 0?void 0:_b.id)!==(trackOrNull===null||trackOrNull===void 0?void 0:trackOrNull.id)){yield this.sender.replaceTrack(trackOrNull);if(trackOrNull){logger.log("Sender source for ".concat(this.mediaType," replaced with track ID ").concat(trackOrNull.id));}else {logger.log("Sender source for ".concat(this.mediaType," set to null, sender stopped"));}}});}handleTrackChange(){return __awaiter$1(this,void 0,void 0,function*(){if(this.requested){yield this.replaceSenderSource(this.publishedStream);}});}handleStreamConstraintsChange(){return __awaiter$1(this,void 0,void 0,function*(){yield this.updateSendParameters(this.requestedIdEncodingParamsMap);});}handleStreamMuteStateChange(){this.streamMuteStateChange.emit();}get requested(){return this.requestedIdEncodingParamsMap.size>0;}replaceTransceiver(newRtcRtpTransceiver){var _super=Object.create(null,{replaceTransceiver:{get:()=>super.replaceTransceiver}});return __awaiter$1(this,void 0,void 0,function*(){_super.replaceTransceiver.call(this,newRtcRtpTransceiver);newRtcRtpTransceiver.direction=this.direction;if(this.requested){yield this.replaceSenderSource(this.publishedStream);}});}replacePublishedStream(newStream){return __awaiter$1(this,void 0,void 0,function*(){var oldStream=this.publishedStream;oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);oldStream===null||oldStream===void 0?void 0:oldStream.off(StreamEventNames.MuteStateChange,this.handleStreamMuteStateChange);if(this.requested){yield this.replaceSenderSource(newStream);}this.publishedStream=newStream;newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.OutputTrackChange,this.handleTrackChange);newStream===null||newStream===void 0?void 0:newStream.on(LocalStreamEventNames.ConstraintsChange,this.handleStreamConstraintsChange);newStream===null||newStream===void 0?void 0:newStream.on(StreamEventNames.MuteStateChange,this.handleStreamMuteStateChange);if(!oldStream&&newStream&&!newStream.muted||oldStream&&!newStream&&!oldStream.muted){this.streamPublishStateChange.emit();}else if((oldStream===null||oldStream===void 0?void 0:oldStream.muted)!==(newStream===null||newStream===void 0?void 0:newStream.muted)){this.streamMuteStateChange.emit();}});}setNamedMediaGroups(namedMediaGroups){if(this.mediaType!==MediaType.AudioMain){logErrorAndThrow(WcmeErrorType.SET_NMG_FAILED,"Named media groups can only be set for audio.");}this.namedMediaGroups=namedMediaGroups;this.namedMediaGroupsChange.emit();}publishStream(stream){return this.replacePublishedStream(stream);}unpublishStream(){return this.replacePublishedStream();}get active(){return this._rtcRtpTransceiver.direction==='sendrecv';}set active(enabled){this.direction=enabled?'sendrecv':'inactive';this._rtcRtpTransceiver.direction=this.direction;if(this._rtcRtpTransceiver.direction!==this._rtcRtpTransceiver.currentDirection){this.negotiationNeeded.emit(OfferAnswerType.Remote);}}getStats(){return this.sender.getStats();}updateSendParameters(requestedIdEncodingParamsMap){return __awaiter$1(this,void 0,void 0,function*(){return this.updateSendParametersQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var requested=requestedIdEncodingParamsMap.size>0;if(this.requested!==requested){yield this.replaceSenderSource(requested?this.publishedStream:null);}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);this.requestedIdEncodingParamsMap=requestedIdEncodingParamsMap;}));});}isSimulcastEnabled(){var params=this.sender.getParameters();return params.encodings.length>1;}mungeLocalDescription(mediaDescription){this.munger.mungeLocalDescription(mediaDescription,this.isSimulcastEnabled(),this.rtxEnabled,this.twccDisabled);}mungeLocalDescriptionForRemoteServer(mediaDescription){this.munger.mungeLocalDescriptionForRemoteServer(mediaDescription,getMediaContent(this.mediaType),this.csi);}mungeRemoteDescription(mediaDescription){this.munger.mungeRemoteDescription(mediaDescription);}get senderIds(){return this.munger.getSenderIds();}get numActiveSimulcastLayers(){var _a;if(getMediaFamily(this.mediaType)===MediaFamily.Video){return (_a=this.publishedStream)===null||_a===void 0?void 0:_a.getNumActiveSimulcastLayers();}return this.publishedStream?0:undefined;}getEncodingIndexForStreamId(id){return this.munger.getEncodingIndexForStreamId(id);}resetSdpMunger(){this.munger.reset();}setCodecParameters(parameters){this.munger.setCodecParameters(parameters);this.negotiationNeeded.emit(OfferAnswerType.LocalOnly);}deleteCodecParameters(parameters){this.munger.deleteCodecParameters(parameters);this.negotiationNeeded.emit(OfferAnswerType.LocalOnly);}}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);}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);});}}class StatsManager{constructor(statsGetter){var statsPreprocessor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:()=>__awaiter$1(this,void 0,void 0,function*(){});this.statsGetter=statsGetter;this.statsPreProcessor=statsPreprocessor;}getStats(){return __awaiter$1(this,void 0,void 0,function*(){var statsReport=yield this.statsGetter();var statsMap=new Map();statsReport.forEach((stats,key)=>statsMap.set(key,stats));yield this.statsPreProcessor(statsMap);return statsMap;});}}var organizeTransceiverStats=(sendTransceivers,recvTransceivers)=>__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(_ref6=>{var[mediaType,transceiver]=_ref6;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(mediaType===MediaType.AudioMain){result.audio.senders.push(item);}if(mediaType===MediaType.VideoMain){result.video.senders.push(item);}if(mediaType===MediaType.AudioSlides){result.screenShareAudio.senders.push(item);}if(mediaType===MediaType.VideoSlides){result.screenShareVideo.senders.push(item);}});}));yield Promise.all([...recvTransceivers.entries()].map(_ref7=>{var[mediaType,transceivers]=_ref7;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,_c;var item={report:yield t.getStats(),mid:(_b=t.receiveSlot.id)===null||_b===void 0?void 0:_b.mid,csi:t.receiveSlot.currentRxCsi,currentDirection:'recvonly',localTrackLabel:(_c=t.receiveSlot.stream.getTracks()[0])===null||_c===void 0?void 0:_c.label};if(mediaType===MediaType.AudioMain){result.audio.receivers.push(item);}if(mediaType===MediaType.VideoMain){result.video.receivers.push(item);}if(mediaType===MediaType.AudioSlides){result.screenShareAudio.receivers.push(item);}if(mediaType===MediaType.VideoSlides){result.screenShareVideo.receivers.push(item);}})));});}));return result;});function toMediaStreamTrackKind(mediaType){return [MediaType.VideoMain,MediaType.VideoSlides].includes(mediaType)?MediaStreamTrackKind.Video:MediaStreamTrackKind.Audio;}function webRtcVideoContentHintToJmpVideoContentHint(hint){if(hint==='motion'){return 'motion';}if(hint==='detail'){return 'sharpness';}return undefined;}var MultistreamConnectionEventNames;(function(MultistreamConnectionEventNames){MultistreamConnectionEventNames["VideoSourceCountUpdate"]="video-source-count-update";MultistreamConnectionEventNames["AudioSourceCountUpdate"]="audio-source-count-update";MultistreamConnectionEventNames["ActiveSpeakerNotification"]="active-speaker-notification";MultistreamConnectionEventNames["ConnectionStateUpdate"]="connection-state-update";MultistreamConnectionEventNames["NegotiationNeeded"]="negotiation-needed";})(MultistreamConnectionEventNames||(MultistreamConnectionEventNames={}));var defaultMultistreamConnectionOptions={disableSimulcast:BrowserInfo.isFirefox(),bundlePolicy:'max-compat',iceServers:undefined,disableContentSimulcast:true,disableAudioTwcc:true};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.metricsCallback=()=>{};this.overuseUpdateCallback=()=>{};this.midPredictor=new MidPredictor();this.offerAnswerQueue=new AsyncQueue();this.currentCreateOfferId=0;this.options=Object.assign(Object.assign({},defaultMultistreamConnectionOptions),userOptions);logger.info("Creating multistream connection with options ".concat(JSON.stringify(this.options)));this.initializePeerConnection();this.overuseStateManager=new OveruseStateManager(overuseState=>this.overuseUpdateCallback(overuseState));this.overuseStateManager.start();this.statsManager=new StatsManager(()=>this.pc.getStats(),stats=>this.preProcessStats(stats));var mainSceneId=generateSceneId();var slidesSceneId=generateSceneId();var videoMainEncodingOptions=this.getVideoEncodingOptions(MediaContent.Main);var videoSlidesEncodingOptions=this.getVideoEncodingOptions(MediaContent.Slides);this.createSendTransceiver(MediaType.VideoMain,mainSceneId,videoMainEncodingOptions);this.createSendTransceiver(MediaType.AudioMain,mainSceneId);this.createSendTransceiver(MediaType.VideoSlides,slidesSceneId,videoSlidesEncodingOptions);this.createSendTransceiver(MediaType.AudioSlides,slidesSceneId);}initializePeerConnection(){var _a;(_a=this.pc)===null||_a===void 0?void 0:_a.close();this.pc=new PeerConnection({iceServers:this.options.iceServers,bundlePolicy:this.options.bundlePolicy});this.pc.on(PeerConnection.Events.ConnectionStateChange,state=>this.emit(MultistreamConnectionEventNames.ConnectionStateUpdate,state));this.attachMetricsObserver();this.createDataChannel();}getConnectionState(){return this.pc.getConnectionState();}getVideoEncodingOptions(content){var enabledSimulcast=content===MediaContent.Main?!this.options.disableSimulcast:!this.options.disableContentSimulcast;return enabledSimulcast?[{scaleResolutionDownBy:4,active:false},{scaleResolutionDownBy:2,active:false},{active:false}]:[{active:false}];}createSendTransceiver(mediaType,sceneId,sendEncodingsOptions){var rtcTransceiver;try{rtcTransceiver=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(rtcTransceiver,mid,csi,munger,mediaType);if(getMediaFamily(mediaType)===MediaFamily.Video){transceiver.rtxEnabled=true;transceiver.setCodecParameters({'max-mbps':"".concat(defaultMaxVideoEncodeMbps),'max-fs':"".concat(defaultMaxVideoEncodeFrameSize)});}transceiver.twccDisabled=getMediaFamily(mediaType)===MediaFamily.Audio?this.options.disableAudioTwcc:false;transceiver.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);});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(msg=>{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;}logger.info("Sending JMP message: ".concat(msg));this.dataChannel.send(msg);});var prevNumTotalSources=0;var prevNumLiveSources=0;jmpSession.on(JmpSessionEvents.SourceAdvertisementReceived,data=>{logger.log("SourceAdvertisement received: ".concat(JSON.stringify(data)));if(data.numTotalSources!==prevNumTotalSources||data.numLiveSources!==prevNumLiveSources){prevNumTotalSources=data.numTotalSources;prevNumLiveSources=data.numLiveSources;var eventName=getMediaFamily(mediaType)===MediaFamily.Video?MultistreamConnectionEventNames.VideoSourceCountUpdate:MultistreamConnectionEventNames.AudioSourceCountUpdate;this.emit(eventName,data.numTotalSources,data.numLiveSources,getMediaContent(mediaType));}else {logger.log('Number of sources was unchanged, ignoring message');}});jmpSession.on(JmpSessionEvents.MediaRequestStatusReceived,data=>{logger.log("MediaRequestStatus received: ".concat(JSON.stringify(data)));data.streamStates.forEach(s=>{var receiveSlot=this.getReceiveSlotById(s.id);if(!receiveSlot){logger.warn("Got MediaRequestStatus for unknown receive slot: ".concat(JSON.stringify(s.id)));return;}receiveSlot._updateSource(s.state,s.csi);});});jmpSession.on(JmpSessionEvents.MediaRequestReceived,data=>{logger.log("MediaRequest received: ".concat(JSON.stringify(data)));if(getMediaFamily(mediaType)===MediaFamily.Video){this.sendMediaRequestStatus(mediaType);}this.updateRequestedStreams(mediaType,data.requests);});jmpSession.on(JmpSessionEvents.ActiveSpeaker,data=>{this.emit(MultistreamConnectionEventNames.ActiveSpeakerNotification,data.csis);});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(_ref8=>{var{ids,policySpecificInfo,codecInfos,maxPayloadBitsPerSecond}=_ref8;var _a,_b,_c;if(ids.length>1){logErrorAndThrow(WcmeErrorType.INVALID_STREAM_REQUEST,"Stream request cannot have more than one ID.");}if(ids.length===0){return;}if(sendTransceiver.csi!==policySpecificInfo.csi){logger.warn('csi in the StreamRequest does not match');return;}var id=ids[0];var codecInfo=codecInfos[0];var streamIdsMatched=sendTransceiver.senderIds.some(validId=>compareStreamIds(id,validId));if(streamIdsMatched){var encodingIndex=sendTransceiver.getEncodingIndexForStreamId(id);if(encodingIndex!==-1){var encodingParams={maxPayloadBitsPerSecond};if(mediaFamily===MediaFamily.Video){encodingParams.maxFs=(_a=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_a===void 0?void 0:_a.maxFs;encodingParams.maxWidth=(_b=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_b===void 0?void 0:_b.maxWidth;encodingParams.maxHeight=(_c=codecInfo===null||codecInfo===void 0?void 0:codecInfo.h264)===null||_c===void 0?void 0:_c.maxHeight;}requestedIdEncodingParamsMap.set(encodingIndex,encodingParams);}else {logger.warn("".concat(mediaType,": Unable to get encoding index for stream ID: ").concat(JSON.stringify(id)));}}else {logger.warn("".concat(mediaType,": Unable to find matching stream ID for requested ID: ").concat(JSON.stringify(id)));}});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.pc.close();}sendMediaRequestStatus(mediaType){var _a;if(getMediaFamily(mediaType)!==MediaFamily.Video){return;}var streamStates=this.getVideoStreamStates(mediaType);var task=()=>{var _a;(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendMediaRequestStatus(streamStates);};if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}sendSourceAdvertisement(mediaType){var _a,_b;var transceiver=this.getSendTransceiverOrThrow(mediaType);var numLiveSources=((_a=transceiver.publishedStream)===null||_a===void 0?void 0:_a.muted)===false?1:0;var task;if(getMediaFamily(mediaType)===MediaFamily.Video){var sources=this.getVideoStreamStates(mediaType);if(sources===null){return;}var contentHint;if(transceiver.publishedStream&&mediaType===MediaType.VideoSlides){contentHint=transceiver.publishedStream.contentHint;}task=()=>{var _a;(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendSourceAdvertisement(1,numLiveSources,[],webRtcVideoContentHintToJmpVideoContentHint(contentHint));};}else {task=()=>{var _a;return (_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.sendSourceAdvertisement(1,numLiveSources,mediaType===MediaType.AudioMain?transceiver.namedMediaGroups:[]);};}if(((_b=this.dataChannel)===null||_b===void 0?void 0:_b.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}getVideoStreamStates(mediaType){var _a;var sendTransceiver=this.getSendTransceiverOrThrow(mediaType);var published=!!sendTransceiver.publishedStream;var muted=(_a=sendTransceiver.publishedStream)===null||_a===void 0?void 0:_a.muted;return sendTransceiver.senderIds.map(id=>{var state;if(!published){state='no source';}else if(muted){state='avatar';}else {state='live';}return {id,state,csi:sendTransceiver.csi};});}createReceiveSlot(mediaType){return __awaiter$1(this,void 0,void 0,function*(){return new Promise(createReceiveSlotResolve=>{this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var rtcRtpTransceiver=this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'recvonly'});var transceiverMid=this.midPredictor.getNextMid(mediaType);var munger=new IngressSdpMunger();var recvOnlyTransceiver=new ReceiveOnlyTransceiver(rtcRtpTransceiver,transceiverMid,munger);recvOnlyTransceiver.twccDisabled=getMediaFamily(mediaType)===MediaFamily.Audio?this.options.disableAudioTwcc:false;this.recvTransceivers.set(mediaType,[...(this.recvTransceivers.get(mediaType)||[]),recvOnlyTransceiver]);if(this.pc.getRemoteDescription()){yield this.doLocalOfferAnswer();}createReceiveSlotResolve(recvOnlyTransceiver.receiveSlot);}));});});}getIngressPayloadType(mediaType,mimeType){var _a,_b,_c;var requestedMediaCodecType=mimeType.split('/')[1];var requestedMid=(_a=this.sendTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.mid;var parsedOffer=parse$1((_b=this.pc.getLocalDescription())===null||_b===void 0?void 0:_b.sdp);var parsedAnswer=parse$1((_c=this.pc.getRemoteDescription())===null||_c===void 0?void 0:_c.sdp);var senderCodecs=parsedAnswer.avMedia.filter(media=>requestedMid===media.mid).map(media=>[...media.codecs.values()]).flat().filter(ci=>ci.name===requestedMediaCodecType);var receiverCodecs=parsedOffer.avMedia.filter(media=>requestedMid===media.mid).map(media=>[...media.codecs.values()]).flat().filter(ci=>ci.name===requestedMediaCodecType);if(!senderCodecs||!receiverCodecs||senderCodecs.length===0||receiverCodecs.length===0){logErrorAndThrow(WcmeErrorType.GET_PAYLOAD_TYPE_FAILED,"Sender codecs or receiver codecs is undefined or empty.");}var senderCodec=senderCodecs[0];var targetCodec=receiverCodecs.find(receiverCodec=>{return areCodecsCompatible(senderCodec,receiverCodec);});if(!targetCodec||!targetCodec.pt){logErrorAndThrow(WcmeErrorType.GET_PAYLOAD_TYPE_FAILED,"Cannot find matching receiver codec for the given mediaType/mimeType.");}return targetCodec.pt;}createOffer(){return __awaiter$1(this,void 0,void 0,function*(){if(!this.pc.getLocalDescription()){this.midPredictor.allocateMidForDatachannel();}if(this.setAnswerResolve){logger.info('Canceling previous offer since setAnswer was never called for it');this.setAnswerResolve();this.setAnswerResolve=undefined;}var createOfferId=++this.currentCreateOfferId;return new Promise((createOfferResolve,createOfferReject)=>{this.offerAnswerQueue.push(()=>__awaiter$1(this,void 0,void 0,function*(){var _a;try{var offer=yield this.pc.createOffer();if(!offer.sdp){logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,'SDP not found in offer.');}offer.sdp=this.preProcessLocalOffer(offer.sdp);yield this.pc.setLocalDescription(offer);var sdpToSend=this.prepareLocalOfferForRemoteServer((_a=this.pc.getLocalDescription())===null||_a===void 0?void 0:_a.sdp);createOfferResolve({type:'offer',sdp:sdpToSend});if(this.currentCreateOfferId>createOfferId){logger.log('Canceling previous offer since createOffer was called while it was being created');}else {yield new Promise(setAnswerResolve=>{this.setAnswerResolve=setAnswerResolve;});}}catch(error){createOfferReject(error);}}));});});}setAnswer(answer){return __awaiter$1(this,void 0,void 0,function*(){var sdp=this.preProcessRemoteAnswer(answer);if(!this.setAnswerResolve){logErrorAndThrow(WcmeErrorType.SET_ANSWER_FAILED,"Call to setAnswer without having previously called createOffer.");}logger.info('calling this.pc.setRemoteDescription()');return this.pc.setRemoteDescription({type:'answer',sdp}).then(()=>__awaiter$1(this,void 0,void 0,function*(){logger.info('this.pc.setRemoteDescription() resolved');if(this.setAnswerResolve){this.setAnswerResolve();this.setAnswerResolve=undefined;}else {logger.debug("setAnswerResolve function was cleared between setAnswer and result of setRemoteDescription");}}));});}doLocalOfferAnswer(){var _a;return __awaiter$1(this,void 0,void 0,function*(){var offer=yield this.pc.createOffer();if(!offer.sdp){logErrorAndThrow(WcmeErrorType.CREATE_OFFER_FAILED,'SDP not found in offer.');}offer.sdp=this.preProcessLocalOffer(offer.sdp);yield this.pc.setLocalDescription(offer);var answer=this.preProcessRemoteAnswer((_a=this.pc.getRemoteDescription())===null||_a===void 0?void 0:_a.sdp);return this.pc.setRemoteDescription({type:'answer',sdp: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);parsedOffer.avMedia.filter(av=>av.direction==='sendrecv'||av.direction==='inactive').forEach(av=>{var sendTransceiver=this.getSendTransceiverByMidOrThrow(av.mid);sendTransceiver.mungeLocalDescriptionForRemoteServer(av);});parsedOffer.media.filter(media=>media instanceof ApplicationMediaDescription$1).forEach(media=>{injectDummyCandidates(media);});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;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(retainCandidates(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());}return parsedAnswer.toString();}getSendTransceiverOrThrow(mediaType){var sendTransceiver=this.sendTransceivers.get(mediaType);if(!sendTransceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find send transceiver for media type ".concat(mediaType,"."));}return sendTransceiver;}getSendTransceiverByMidOrThrow(mid){var transceiver=[...this.sendTransceivers.values()].find(t=>t.mid===mid);if(!transceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find send transceiver with MID ".concat(mid,"."));}return transceiver;}getRecvTransceiverByMidOrThrow(mid){var transceiver=[...this.recvTransceivers.values()].flat().find(t=>t.mid===mid);if(!transceiver){logErrorAndThrow(WcmeErrorType.GET_TRANSCEIVER_FAILED,"Unable to find recv transceiver with MID ".concat(mid,"."));}return transceiver;}requestMedia(mediaType,streamRequests){var _a;var task=()=>{var _a;var jmpSession=this.jmpSessions.get(mediaType);if(!jmpSession){logger.error("Unable to find jmp session for ".concat(mediaType));return;}var requestedReceiveSlotIds=[];streamRequests.forEach(sr=>{sr.receiveSlots.forEach(rs=>{if(!rs.id){logger.error("Running stream request task, but ReceiveSlot ID is missing!");return;}requestedReceiveSlotIds.push(rs.id);});});(_a=this.recvTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.forEach(transceiver=>{if(!requestedReceiveSlotIds.some(id=>compareStreamIds(id,transceiver.receiveSlot.id))){transceiver.receiveSlot._updateSource('no source',undefined);}});jmpSession.sendRequests(streamRequests.map(sr=>sr._toJmpStreamRequest()));};if(((_a=this.dataChannel)===null||_a===void 0?void 0:_a.readyState)==='open'){task();}else {this.pendingJmpTasks.push(task);}}renewPeerConnection(userOptions){if(userOptions){this.options=Object.assign(Object.assign({},this.options),userOptions);}logger.info("Renewing multistream connection with options ".concat(JSON.stringify(this.options)));this.midPredictor.reset();this.initializePeerConnection();var mainSceneId=generateSceneId();var slidesSceneId=generateSceneId();this.sendTransceivers.forEach((transceiver,mediaType)=>{var _a;var mediaContent=getMediaContent(mediaType);var sceneId=mediaContent===MediaContent.Main?mainSceneId:slidesSceneId;var mid=this.midPredictor.getNextMid(mediaType);transceiver.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'sendrecv',sendEncodings:getMediaFamily(mediaType)===MediaFamily.Video?this.getVideoEncodingOptions(mediaContent):undefined}));transceiver.mid=mid;transceiver.csi=generateCsi(getMediaFamily(mediaType),sceneId);transceiver.resetSdpMunger();(_a=this.jmpSessions.get(mediaType))===null||_a===void 0?void 0:_a.close();this.createJmpSession(mediaType);});this.recvTransceivers.forEach((transceivers,mediaType)=>{transceivers.forEach(t=>{var mid=this.midPredictor.getNextMid(mediaType);t.replaceTransceiver(this.pc.addTransceiver(toMediaStreamTrackKind(mediaType),{direction:'recvonly'}));t.mid=mid;});});}getReceiveSlotById(id){return [...this.recvTransceivers.values()].flat().map(transceiver=>transceiver.receiveSlot).find(receiveSlot=>{var receiveSlotId=receiveSlot.id||{};return Object.keys(receiveSlotId).length===Object.keys(id).length&&Object.keys(receiveSlotId).every(key=>Object.prototype.hasOwnProperty.call(id,key)&&receiveSlotId[key]===id[key]);});}getStats(){return this.statsManager.getStats();}getTransceiverStats(){return __awaiter$1(this,void 0,void 0,function*(){return organizeTransceiverStats(this.sendTransceivers,this.recvTransceivers);});}preProcessStats(stats){return __awaiter$1(this,void 0,void 0,function*(){yield Promise.all([...this.sendTransceivers.entries()].map(_ref9=>{var[mediaType,transceiver]=_ref9;return __awaiter$1(this,void 0,void 0,function*(){(yield transceiver.getStats()).forEach(senderStats=>{var _a;if(senderStats.type==='outbound-rtp'){var statsToModify=stats.get(senderStats.id);statsToModify.mid=transceiver.mid;statsToModify.csi=transceiver.csi;statsToModify.calliopeMediaType=mediaType;var trackSettings=(_a=transceiver.publishedStream)===null||_a===void 0?void 0:_a.getSettings();if(trackSettings===null||trackSettings===void 0?void 0:trackSettings.frameRate){statsToModify.targetFrameRate=trackSettings===null||trackSettings===void 0?void 0:trackSettings.frameRate;}stats.set(senderStats.id,statsToModify);}else if(senderStats.type==='media-source'){var _statsToModify=stats.get(senderStats.id);_statsToModify.calliopeMediaType=mediaType;stats.set(senderStats.id,_statsToModify);}});});}));yield Promise.all([...this.recvTransceivers.entries()].map(_ref10=>{var[mediaType,transceivers]=_ref10;return __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=>{var _a;if(receiverStats.type==='inbound-rtp'){var statsToModify=stats.get(receiverStats.id);statsToModify.mid=(_a=transceiver.receiveSlot.id)===null||_a===void 0?void 0:_a.mid;statsToModify.csi=transceiver.receiveSlot.currentRxCsi;statsToModify.calliopeMediaType=mediaType;Object.assign(statsToModify,transceiver.receiverId);stats.set(receiverStats.id,statsToModify);}});})));});}));});}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);}setMetricsCallback(callback){this.metricsCallback=callback;}setOveruseUpdateCallback(callback){this.overuseUpdateCallback=callback;}getCsiByMediaType(mediaType){var _a;return (_a=this.sendTransceivers.get(mediaType))===null||_a===void 0?void 0:_a.csi;}getAllCsis(){return {audioMain:this.getCsiByMediaType(MediaType.AudioMain),audioSlides:this.getCsiByMediaType(MediaType.AudioSlides),videoMain:this.getCsiByMediaType(MediaType.VideoMain),videoSlides:this.getCsiByMediaType(MediaType.VideoSlides)};}}class StreamRequest{constructor(policy,policySpecificInfo,receiveSlots,maxPayloadBitsPerSecond){var codecInfos=arguments.length>4&&arguments[4]!==undefined?arguments[4]:[];this.policy=policy;this.policySpecificInfo=policySpecificInfo;this.receiveSlots=receiveSlots;this.maxPayloadBitsPerSecond=maxPayloadBitsPerSecond;this.codecInfos=codecInfos;}_toJmpStreamRequest(){return new StreamRequest$1(this.policy,this.policySpecificInfo,this.receiveSlots.map(rs=>rs.id),this.maxPayloadBitsPerSecond,this.codecInfos);}}
|
|
5818
5849
|
|
|
5819
5850
|
var defaultLogger = {
|
|
5820
5851
|
info: function info() {
|